context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Reflection;
using System.Threading.Tasks;
using Orleans.CodeGeneration;
using Orleans.Runtime;
namespace Orleans
{
/// <summary>
/// Factory for accessing grains.
/// </summary>
internal class GrainFactory : IInternalGrainFactory, IGrainReferenceConverter
{
/// <summary>
/// The mapping between concrete grain interface types and delegate
/// </summary>
private readonly ConcurrentDictionary<Type, GrainReferenceCaster> casters
= new ConcurrentDictionary<Type, GrainReferenceCaster>();
/// <summary>
/// The collection of <see cref="IGrainMethodInvoker"/>s for their corresponding grain interface type.
/// </summary>
private readonly ConcurrentDictionary<Type, IGrainMethodInvoker> invokers =
new ConcurrentDictionary<Type, IGrainMethodInvoker>();
/// <summary>
/// The cache of typed system target references.
/// </summary>
private readonly Dictionary<Tuple<GrainId, Type>, Dictionary<SiloAddress, ISystemTarget>> typedSystemTargetReferenceCache =
new Dictionary<Tuple<GrainId, Type>, Dictionary<SiloAddress, ISystemTarget>>();
/// <summary>
/// The cache of type metadata.
/// </summary>
private readonly TypeMetadataCache typeCache;
private readonly IRuntimeClient runtimeClient;
private IGrainReferenceRuntime GrainReferenceRuntime => this.runtimeClient.GrainReferenceRuntime;
// Make this internal so that client code is forced to access the IGrainFactory using the
// GrainClient (to make sure they don't forget to initialize the client).
public GrainFactory(IRuntimeClient runtimeClient, TypeMetadataCache typeCache)
{
this.runtimeClient = runtimeClient;
this.typeCache = typeCache;
}
/// <summary>
/// Casts an <see cref="IAddressable"/> to a concrete <see cref="GrainReference"/> implementation.
/// </summary>
/// <param name="existingReference">The existing <see cref="IAddressable"/> reference.</param>
/// <returns>The concrete <see cref="GrainReference"/> implementation.</returns>
internal delegate object GrainReferenceCaster(IAddressable existingReference);
/// <inheritdoc />
public TGrainInterface GetGrain<TGrainInterface>(Guid primaryKey, string grainClassNamePrefix = null) where TGrainInterface : IGrainWithGuidKey
{
Type interfaceType = typeof(TGrainInterface);
var implementation = this.GetGrainClassData(interfaceType, grainClassNamePrefix);
var grainId = GrainId.GetGrainId(implementation.GetTypeCode(interfaceType), primaryKey, null);
return this.Cast<TGrainInterface>(this.MakeGrainReferenceFromType(interfaceType, grainId));
}
/// <inheritdoc />
public TGrainInterface GetGrain<TGrainInterface>(long primaryKey, string grainClassNamePrefix = null) where TGrainInterface : IGrainWithIntegerKey
{
Type interfaceType = typeof(TGrainInterface);
var implementation = this.GetGrainClassData(interfaceType, grainClassNamePrefix);
var grainId = GrainId.GetGrainId(implementation.GetTypeCode(interfaceType), primaryKey, null);
return this.Cast<TGrainInterface>(this.MakeGrainReferenceFromType(interfaceType, grainId));
}
/// <inheritdoc />
public TGrainInterface GetGrain<TGrainInterface>(string primaryKey, string grainClassNamePrefix = null)
where TGrainInterface : IGrainWithStringKey
{
Type interfaceType = typeof(TGrainInterface);
var implementation = this.GetGrainClassData(interfaceType, grainClassNamePrefix);
var grainId = GrainId.GetGrainId(implementation.GetTypeCode(interfaceType), primaryKey);
return this.Cast<TGrainInterface>(this.MakeGrainReferenceFromType(interfaceType, grainId));
}
/// <inheritdoc />
public TGrainInterface GetGrain<TGrainInterface>(Guid primaryKey, string keyExtension, string grainClassNamePrefix = null)
where TGrainInterface : IGrainWithGuidCompoundKey
{
GrainFactoryBase.DisallowNullOrWhiteSpaceKeyExtensions(keyExtension);
Type interfaceType = typeof(TGrainInterface);
var implementation = this.GetGrainClassData(interfaceType, grainClassNamePrefix);
var grainId = GrainId.GetGrainId(implementation.GetTypeCode(interfaceType), primaryKey, keyExtension);
return this.Cast<TGrainInterface>(this.MakeGrainReferenceFromType(interfaceType, grainId));
}
/// <inheritdoc />
public TGrainInterface GetGrain<TGrainInterface>(long primaryKey, string keyExtension, string grainClassNamePrefix = null)
where TGrainInterface : IGrainWithIntegerCompoundKey
{
GrainFactoryBase.DisallowNullOrWhiteSpaceKeyExtensions(keyExtension);
Type interfaceType = typeof(TGrainInterface);
var implementation = this.GetGrainClassData(interfaceType, grainClassNamePrefix);
var grainId = GrainId.GetGrainId(implementation.GetTypeCode(interfaceType), primaryKey, keyExtension);
return this.Cast<TGrainInterface>(this.MakeGrainReferenceFromType(interfaceType, grainId));
}
/// <inheritdoc />
public void BindGrainReference(IAddressable grain)
{
if (grain == null) throw new ArgumentNullException(nameof(grain));
var reference = grain as GrainReference;
if (reference == null) throw new ArgumentException("Provided grain must be a GrainReference.", nameof(grain));
reference.Bind(this.GrainReferenceRuntime);
}
/// <inheritdoc />
public GrainReference GetGrainFromKeyString(string key) => GrainReference.FromKeyString(key, this.GrainReferenceRuntime);
/// <inheritdoc />
public Task<TGrainObserverInterface> CreateObjectReference<TGrainObserverInterface>(IGrainObserver obj)
where TGrainObserverInterface : IGrainObserver
{
return Task.FromResult(this.CreateObjectReferenceImpl<TGrainObserverInterface>(obj));
}
/// <inheritdoc />
public Task DeleteObjectReference<TGrainObserverInterface>(
IGrainObserver obj) where TGrainObserverInterface : IGrainObserver
{
this.runtimeClient.DeleteObjectReference(obj);
return Task.CompletedTask;
}
/// <inheritdoc />
public TGrainObserverInterface CreateObjectReference<TGrainObserverInterface>(IAddressable obj)
where TGrainObserverInterface : IAddressable
{
return this.CreateObjectReferenceImpl<TGrainObserverInterface>(obj);
}
private TGrainObserverInterface CreateObjectReferenceImpl<TGrainObserverInterface>(IAddressable obj) where TGrainObserverInterface : IAddressable
{
var interfaceType = typeof(TGrainObserverInterface);
var interfaceTypeInfo = interfaceType.GetTypeInfo();
if (!interfaceTypeInfo.IsInterface)
{
throw new ArgumentException(
$"The provided type parameter must be an interface. '{interfaceTypeInfo.FullName}' is not an interface.");
}
if (!interfaceTypeInfo.IsInstanceOfType(obj))
{
throw new ArgumentException($"The provided object must implement '{interfaceTypeInfo.FullName}'.", nameof(obj));
}
IGrainMethodInvoker invoker;
if (!this.invokers.TryGetValue(interfaceType, out invoker))
{
invoker = this.MakeInvoker(interfaceType);
this.invokers.TryAdd(interfaceType, invoker);
}
return this.Cast<TGrainObserverInterface>(this.runtimeClient.CreateObjectReference(obj, invoker));
}
private IAddressable MakeGrainReferenceFromType(Type interfaceType, GrainId grainId)
{
var typeInfo = interfaceType.GetTypeInfo();
return GrainReference.FromGrainId(
grainId,
this.GrainReferenceRuntime,
typeInfo.IsGenericType ? TypeUtils.GenericTypeArgsString(typeInfo.UnderlyingSystemType.FullName) : null);
}
private GrainClassData GetGrainClassData(Type interfaceType, string grainClassNamePrefix)
{
if (!GrainInterfaceUtils.IsGrainType(interfaceType))
{
throw new ArgumentException("Cannot fabricate grain-reference for non-grain type: " + interfaceType.FullName);
}
var grainTypeResolver = this.runtimeClient.GrainTypeResolver;
GrainClassData implementation;
if (!grainTypeResolver.TryGetGrainClassData(interfaceType, out implementation, grainClassNamePrefix))
{
var loadedAssemblies = grainTypeResolver.GetLoadedGrainAssemblies();
var assembliesString = string.IsNullOrEmpty(loadedAssemblies)
? string.Empty
: " Loaded grain assemblies: " + loadedAssemblies;
var grainClassPrefixString = string.IsNullOrEmpty(grainClassNamePrefix)
? string.Empty
: ", grainClassNamePrefix: " + grainClassNamePrefix;
throw new ArgumentException(
$"Cannot find an implementation class for grain interface: {interfaceType}{grainClassPrefixString}. " +
"Make sure the grain assembly was correctly deployed and loaded in the silo." + assembliesString);
}
return implementation;
}
private IGrainMethodInvoker MakeInvoker(Type interfaceType)
{
var invokerType = this.typeCache.GetGrainMethodInvokerType(interfaceType);
return (IGrainMethodInvoker)Activator.CreateInstance(invokerType);
}
#region Interface Casting
/// <summary>
/// Casts the provided <paramref name="grain"/> to the specified interface
/// </summary>
/// <typeparam name="TGrainInterface">The target grain interface type.</typeparam>
/// <param name="grain">The grain reference being cast.</param>
/// <returns>
/// A reference to <paramref name="grain"/> which implements <typeparamref name="TGrainInterface"/>.
/// </returns>
public TGrainInterface Cast<TGrainInterface>(IAddressable grain)
{
var interfaceType = typeof(TGrainInterface);
return (TGrainInterface)this.Cast(grain, interfaceType);
}
/// <summary>
/// Casts the provided <paramref name="grain"/> to the provided <paramref name="interfaceType"/>.
/// </summary>
/// <param name="grain">The grain.</param>
/// <param name="interfaceType">The resulting interface type.</param>
/// <returns>A reference to <paramref name="grain"/> which implements <paramref name="interfaceType"/>.</returns>
public object Cast(IAddressable grain, Type interfaceType)
{
GrainReferenceCaster caster;
if (!this.casters.TryGetValue(interfaceType, out caster))
{
// Create and cache a caster for the interface type.
caster = this.casters.GetOrAdd(interfaceType, this.MakeCaster);
}
return caster(grain);
}
/// <summary>
/// Creates and returns a new grain reference caster.
/// </summary>
/// <param name="interfaceType">The interface which the result will cast to.</param>
/// <returns>A new grain reference caster.</returns>
private GrainReferenceCaster MakeCaster(Type interfaceType)
{
var grainReferenceType = this.typeCache.GetGrainReferenceType(interfaceType);
return GrainCasterFactory.CreateGrainReferenceCaster(interfaceType, grainReferenceType);
}
#endregion
#region SystemTargets
/// <summary>
/// Gets a reference to the specified system target.
/// </summary>
/// <typeparam name="TGrainInterface">The system target interface.</typeparam>
/// <param name="grainId">The id of the target.</param>
/// <param name="destination">The destination silo.</param>
/// <returns>A reference to the specified system target.</returns>
public TGrainInterface GetSystemTarget<TGrainInterface>(GrainId grainId, SiloAddress destination)
where TGrainInterface : ISystemTarget
{
Dictionary<SiloAddress, ISystemTarget> cache;
Tuple<GrainId, Type> key = Tuple.Create(grainId, typeof(TGrainInterface));
lock (this.typedSystemTargetReferenceCache)
{
if (this.typedSystemTargetReferenceCache.ContainsKey(key)) cache = this.typedSystemTargetReferenceCache[key];
else
{
cache = new Dictionary<SiloAddress, ISystemTarget>();
this.typedSystemTargetReferenceCache[key] = cache;
}
}
ISystemTarget reference;
lock (cache)
{
if (cache.ContainsKey(destination))
{
reference = cache[destination];
}
else
{
reference = this.Cast<TGrainInterface>(GrainReference.FromGrainId(grainId, this.GrainReferenceRuntime, null, destination));
cache[destination] = reference; // Store for next time
}
}
return (TGrainInterface)reference;
}
/// <inheritdoc />
public TGrainInterface GetGrain<TGrainInterface>(GrainId grainId) where TGrainInterface : IAddressable
{
return this.Cast<TGrainInterface>(GrainReference.FromGrainId(grainId, this.GrainReferenceRuntime));
}
/// <inheritdoc />
public GrainReference GetGrain(GrainId grainId, string genericArguments)
=> GrainReference.FromGrainId(grainId, this.GrainReferenceRuntime, genericArguments);
#endregion
}
}
| |
/*This code is managed under the Apache v2 license.
To see an overview:
http://www.tldrlegal.com/license/apache-license-2.0-(apache-2.0)
Author: Robert Gawdzik
www.github.com/rgawdzik/
THIS CODE HAS NO FORM OF ANY WARRANTY, AND IS CONSIDERED AS-IS.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Paradox.Game.Classes.Engines;
using Paradox.Game.Classes.Cameras;
using Paradox.Game.Classes.Levels;
namespace Paradox.Game.Classes.Ships
{
public class Enemy : Collidable
{
#region Variables and Properties
public Vector3 ShipPosition;
public bool IsFrigate;
public Matrix ShipWorld;
public Quaternion ShipRotation;
public Vector3 ClosestFriendPosition;
public float ClosestDistance;
public int Life;
public float ShipSpeed;
public float MaxShipSpeed;
public float MinShipSpeed;
public float TurningSpeed;
public float DistanceThresholdEnemy;
public float DistanceThresholdFriend;
public bool _shipStopped;
public float _momentum;
protected int _xIndexSpeed;
private Random _randomVar;
private const int _deadLockTime = 30;
protected int _deadLockDelay; //If a deadlock occurs, the alternate direction must be followed for 15 frames.
protected bool _deadLock;
protected Quaternion _alternateRotation;
public event EventHandler DestroyedByPlayer;
#endregion
#region Constructor
public Enemy()
{
_momentum = 0f;
_shipStopped = true;
_randomVar = new Random();
} //This is called by any inherited classes.
public Enemy(CollidableType type, float boundingRadius, Vector3 shipPosition, Quaternion shipRotation, float minShipSpeed, float maxShipSpeed, float turningSpeed, float distanceThresholdEnemy, float distanceThresholdFriend, int life)
{
ShipPosition = shipPosition;
ShipWorld = Matrix.CreateTranslation(shipPosition);
ShipRotation = shipRotation;
ShipSpeed = 1f;
MinShipSpeed = minShipSpeed;
MaxShipSpeed = maxShipSpeed;
TurningSpeed = turningSpeed;
DistanceThresholdEnemy = distanceThresholdEnemy;
DistanceThresholdFriend = distanceThresholdFriend;
this.CollidableType = type;
this.BoundingSphereRadius = boundingRadius;
Life = life;
_momentum = 0f;
_shipStopped = true;
_randomVar = new Random();
}
#endregion
#region Update
public virtual void UpdateEnemy(List<Enemy> enemyList, List<Friend> friendList, List<Objective> objectiveList, Vector3 playerPosition, List<Sound> soundList, List<Explosion> explosionList, GameTime gameTime)
{
//ShipRotation = Quaternion.CreateFromRotationMatrix(RotateToFace(ShipPosition, playerPosition, ShipWorld.Up));
ClosestFriendPosition = ClosestFriend(friendList, objectiveList, playerPosition);
//Makes the ship follow the Closest Friend Position.
//ShipRotation = FollowShip(ClosestFriendPosition, 0.1f);
MoveShip(AIGenerateInputList(enemyList, ClosestFriendPosition, gameTime), gameTime);
this.BoundingSphereCenter = ShipPosition;
}
#endregion
#region HelperMethods
public Vector3 ClosestFriend(List<Friend> friendList, List<Objective> objectiveList, Vector3 playerPosition)
{
Vector3 closestFriend = Vector3.Zero;
float closestDistance = float.MaxValue;
foreach (Friend friend in friendList)
{
float pos = DistanceVector3(ShipPosition, friend.ShipPosition);
if (pos < closestDistance)
{
closestFriend = friend.ShipPosition;
closestDistance = pos;
}
}
foreach (Objective obj in objectiveList)
{
if (obj.IsDrawable && !obj.IsDone)
{
float pos = DistanceVector3(ShipPosition, obj.Position);
if (pos < closestDistance)
{
closestFriend = obj.Position;
closestDistance = pos;
}
}
}
//Checks if the player is closer than any of the friends.
if (DistanceVector3(ShipPosition, playerPosition) < closestDistance)
{
closestFriend = playerPosition;
closestDistance = DistanceVector3(ShipPosition, playerPosition);
}
ClosestDistance = closestDistance;
return closestFriend;
}
public virtual void MoveShip(InputActionEnemy action, GameTime gameTime)
{
float second = (float)gameTime.ElapsedGameTime.TotalSeconds;
float currentTurningSpeed = second * TurningSpeed;
if (_deadLockDelay > 0)
{
ShipRotation = FollowShip(_alternateRotation, 0.025f);
}
else
{
ShipRotation = FollowShip(ClosestFriendPosition, 0.025f);
}
//Increments the Acceleration Variable. Acceleration should occur for 0.5 seconds. This means the ship has only 0.5 seconds to react to another movement.
if (ShipSpeed == MaxShipSpeed)
{
if (_xIndexSpeed < 30)
{
_momentum = CalculateAcceleration(++_xIndexSpeed);
}
}
else if (ShipSpeed == MinShipSpeed)
{
if (_xIndexSpeed > -30)
{
_momentum = CalculateAcceleration(--_xIndexSpeed) * -1;
}
}
else if (_shipStopped)
{
if (_xIndexSpeed < 0)
_momentum = CalculateAcceleration(++_xIndexSpeed);
else if (_xIndexSpeed > 0)
_momentum = CalculateAcceleration(--_xIndexSpeed);
}
switch (action)
{
case InputActionEnemy.Forward:
//The Enemy cannot move until it finalizes it's acceleration.
if (ShipSpeed != MaxShipSpeed)
{
ShipSpeed = MaxShipSpeed;
_shipStopped = false;
}
break;
case InputActionEnemy.Reverse:
if (ShipSpeed != MinShipSpeed)
{
ShipSpeed = MinShipSpeed;
_shipStopped = false;
}
break;
case InputActionEnemy.Stop:
if (!_shipStopped)
{
_shipStopped = true;
}
break;
}
//Updates ShipPosition.
ShipPosition += Vector3.Transform(Vector3.UnitZ, ShipRotation) * (ShipSpeed * _momentum * second);
//Updates ShipWorld.
ShipWorld = Matrix.CreateFromQuaternion(ShipRotation) * Matrix.CreateTranslation(ShipPosition);
}
public InputActionEnemy AIGenerateInputList(List<Enemy> enemyList, Vector3 enemyPosition, GameTime gameTime)
{
_deadLock = false;
//Decrements the deadlockdelay variable (Should last 15 frames)
if (_deadLockDelay > 0)
_deadLockDelay--;
float distanceFriendEnemy = DistanceVector3(ShipPosition, enemyPosition);
//float distanceRotationEnemyPlayer = DistanceZVector3(ShipPosition, playerPosition, distanceEnemyPlayer);
List<float> DistanceBetweenEachShip = new List<float>();
foreach (Enemy enemy in enemyList)
{
//Doesn't matter if this object gets added to the list, since it will be 0, but Object.Equals checking occurs to make sure no error occurs.
DistanceBetweenEachShip.Add(DistanceVector3(enemy.ShipPosition, ShipPosition));
}
bool possibleDeadlock = false;
Vector3 newFriendPositionSim = SimulateShipMovement(InputActionEnemy.Forward, gameTime);
float distanceFriendEnemySim = DistanceVector3(newFriendPositionSim, enemyPosition);
for (int z = 0; z < enemyList.Count; z++)
{
if (!Object.Equals(this, enemyList[z]))
{
float newDistanceBetweenEachShip = DistanceVector3(newFriendPositionSim, enemyList[z].ShipPosition);
if (DistanceThresholdEnemy > newDistanceBetweenEachShip) //The ship is too close to the enemy.
{
possibleDeadlock = true;
if (newDistanceBetweenEachShip < DistanceBetweenEachShip[z])
{
//The ship is getting closer, this action should not be tolerated.
break;
}
}
if (distanceFriendEnemy < distanceFriendEnemySim)
{
if (newDistanceBetweenEachShip > DistanceBetweenEachShip[z])
{
//The ship is getting closer, this action should not be tolerated.
break;
}
}
}
}
//CHECK ON THIS...possibly r
if (DistanceThresholdEnemy > distanceFriendEnemySim) //Distance between enemy and enemy
{
if (distanceFriendEnemy > distanceFriendEnemySim) //This action is making the ships closer.
{
_deadLock = true;
}
}
//Final Checks:
if (possibleDeadlock)
{
Vector3 finalEnemyPositionSim = SimulateShipMovement(InputActionEnemy.Forward, gameTime);
float finalDistanceEnemyPlayerSim = DistanceVector3(finalEnemyPositionSim, enemyPosition);
for (int i = 0; i < enemyList.Count; i++)
{
if (!Object.Equals(this, enemyList[i]))
{
float newDistanceBetweenEachShip = DistanceVector3(finalEnemyPositionSim, enemyList[i].ShipPosition);
if (DistanceThresholdEnemy > newDistanceBetweenEachShip)
{
_deadLock = true;
break;
}
}
}
}
if (_deadLock && _deadLockDelay <= 0)
{
_alternateRotation = FindRandomQuaternion(enemyList, enemyPosition, gameTime);
_deadLockDelay = _deadLockTime;
}
return InputActionEnemy.Forward;
}
public float DistanceVector3(Vector3 v1, Vector3 v2)
{
return (float)Math.Sqrt(Math.Abs(Math.Pow(v1.X - v2.X, 2)) + Math.Abs(Math.Pow(v1.Y - v2.Y, 2)) + Math.Abs(Math.Pow(v1.Z - v2.Z, 2)));
}
public Vector3 SimulateShipMovement(InputActionEnemy action, GameTime gameTime)
{
float second = (float)gameTime.ElapsedGameTime.TotalSeconds;
float currentTurningSpeed = second * TurningSpeed;
float TestShipSpeed = ShipSpeed;
switch (action)
{
case InputActionEnemy.Forward:
TestShipSpeed = MaxShipSpeed;
break;
case InputActionEnemy.Reverse:
TestShipSpeed = MinShipSpeed;
break;
case InputActionEnemy.Stop:
TestShipSpeed = 0;
break;
}
Vector3 ShipPositionSim = ShipPosition;
ShipPositionSim += Vector3.Transform(Vector3.UnitZ, ShipRotation) * (TestShipSpeed * CalculateAcceleration(_xIndexSpeed) * second);
return ShipPositionSim;
}
public override void Collision(CollidableType objectCollidedWithType)
{
switch (objectCollidedWithType)
{
case CollidableType.PlayerBullet:
Life--;
if (Life == 0)
DestroyedPlayerEvent();
break;
case CollidableType.FriendBullet:
Life--;
break;
case CollidableType.FriendlyShip:
Life = 0;
break;
case CollidableType.Station:
Life--;
break;
case CollidableType.FriendBase:
Life = 0;
break;
case CollidableType.FriendMissle:
Life = 0;
if (Life == 0)
DestroyedPlayerEvent();
break;
case CollidableType.Asteroid:
Life = 0;
break;
}
}
public Quaternion FollowShip(Vector3 playerPosition, float lerpValue)
{
Vector3 desiredDirection = Vector3.Normalize(ShipPosition - playerPosition);
Quaternion ShipDirection = Quaternion.CreateFromRotationMatrix(Matrix.CreateWorld(ShipPosition, desiredDirection, ShipWorld.Up));
return Quaternion.Lerp(ShipRotation, ShipDirection, lerpValue);
}
public Quaternion FollowShip(Quaternion alternateRotation, float lerpValue)
{
return Quaternion.Lerp(ShipRotation, alternateRotation, lerpValue);
}
public float CalculateAcceleration(int x)
{
return (float)(1 / 27000f * Math.Pow(x, 3));
}
public Quaternion FindRandomQuaternion(List<Enemy> enemyList, Vector3 FriendPosition, GameTime gameTime)
{
Quaternion possibleRotation = Quaternion.Identity;
for (int i = 0; i < 5; i++) //This method has 5 attempts to find a rotation that does not collide with any of the enemies, and does not get closer to the Friend.
{
bool _working = true;
possibleRotation = GenerateRotation();
Vector3 newThisEnemyPosition = SimulateShipMovement(possibleRotation, gameTime);
float DistanceThisEnemyFriendSim = DistanceVector3(newThisEnemyPosition, FriendPosition);
float DistanceThisEnemyFriend = DistanceVector3(this.ShipPosition, FriendPosition);
if (DistanceThresholdFriend > DistanceThisEnemyFriendSim) //The Enemy is within the threshold.
{
if (DistanceThisEnemyFriend > DistanceThisEnemyFriendSim) //This simulation is making the enemy closer than before.
{
_working = false;
}
}
if (_working)//This means the enemy is getting farther from the friend.
{
foreach (Enemy enemy in enemyList)
{
float DistanceThisEnemyEnemy = DistanceVector3(this.ShipPosition, enemy.ShipPosition);
float DistanceThisEnemyEnemySim = DistanceVector3(newThisEnemyPosition, enemy.ShipPosition);
if (DistanceThresholdEnemy > DistanceThisEnemyEnemySim) //This Enemy is within the Enemy Threshold.
{
if (DistanceThisEnemyEnemy > DistanceThisEnemyEnemySim) //This simulation is making the enemies closer to each other.
{
_working = false;//This rotation does not work.
}
}
}
}
if (_working)
{
return possibleRotation;
}
}
return possibleRotation; //If the code reaches this point, the 5 times given to generate a possible rotation failed.
}
public Quaternion GenerateRotation()
{
return Quaternion.CreateFromYawPitchRoll((float)_randomVar.Next(-10, 10), (float)_randomVar.Next(-10, 10), (float)_randomVar.Next(-10, 10));
}
public Vector3 SimulateShipMovement(Quaternion possibleRotation, GameTime gameTime) //This method only makes the Ship Go Forward.
{
float second = (float)gameTime.ElapsedGameTime.TotalSeconds;
float currentTurningSpeed = second * TurningSpeed;
float TestShipSpeed = MaxShipSpeed;
Vector3 ShipPositionSim = ShipPosition;
ShipPositionSim += Vector3.Transform(Vector3.UnitZ, possibleRotation) * (TestShipSpeed * CalculateAcceleration(_xIndexSpeed) * second);
return ShipPositionSim;
}
public void DestroyedPlayerEvent()
{
if (DestroyedByPlayer != null)
DestroyedByPlayer(this, EventArgs.Empty);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
namespace Microsoft.Tools.ServiceModel.Svcutil
{
/// <summary>
/// This is the options container OM base class and it defines the basic json schema (see options serializer class).
/// Provides base serialization and option handling functionality.
/// </summary>
internal partial class ApplicationOptions : IOptionsSerializationHandler
{
// dictionary of options name/object, kept sorted for serialization purposes and to ease of troubleshooting.
private SortedDictionary<string, OptionBase> PropertyBag { get; set; }
// a list of value-parsing warngins (used mainly for deserialization)
private List<string> _warnings { get; set; } = new List<string>();
public IEnumerable<string> Warnings { get { return this._warnings; } }
// a list of value-parsing errors (used mainly for deserialization)
private List<Exception> _errors { get; set; } = new List<Exception>();
public IEnumerable<Exception> Errors { get { return this._errors; } }
public virtual string Json { get { return Serialize<ApplicationOptions, OptionsSerializer<ApplicationOptions>>(); } }
#region option keys
// basic json schema (see options serializer).
public const string InputsKey = "inputs";
public const string OptionsKey = "options";
public const string ProviderIdKey = "providerId";
public const string VersionKey = "version";
#endregion
#region properties
public ListValue<Uri> Inputs { get { return GetValue<ListValue<Uri>>(InputsKey); } }
private string Options { get { return GetValue<string>(OptionsKey); } set { SetValue(OptionsKey, value); } }
public string ProviderId { get { return GetValue<string>(ProviderIdKey); } set { SetValue(ProviderIdKey, value); } }
public string Version { get { return GetValue<string>(VersionKey); } set { SetValue(VersionKey, value); } }
#endregion
#region construction methods.
public ApplicationOptions()
{
this.PropertyBag = new SortedDictionary<string, OptionBase>();
// base options implementing the JSON schema.
RegisterOptions(
new ListValueOption<Uri>(InputsKey),
new SingleValueOption<string>(OptionsKey) { CanSerialize = false },
new SingleValueOption<string>(ProviderIdKey),
new SingleValueOption<string>(VersionKey));
}
/// <summary>
/// Options registration method.
/// This is the way a derived options class declare what options it cares about.
/// This mechanism works well with the property bag and the serialization and cloning of options so that the container works only with the registered options
/// </summary>
/// <param name="options"></param>
protected void RegisterOptions(params OptionBase[] options)
{
foreach (var option in options)
{
var existingOption = GetOption(option.Name, throwOnMissing: false);
if (existingOption != null)
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Shared.Resources.ErrorOptionAlreadyRegisteredFormat, option.Name));
}
this.PropertyBag[option.Name] = option;
}
}
/// <summary>
/// Copy option values between different options container types.
/// Observe that only the options that have been set in the source container are considered (see GetOptions), and only the registered options in the destination container are copied (see GetOption).
/// </summary>
/// <typeparam name="TOptionsBase"></typeparam>
/// <param name="other"></param>
public void CopyTo<TOptionsBase>(TOptionsBase other) where TOptionsBase : ApplicationOptions
{
foreach (var thisOption in this.GetOptions())
{
var otherOption = other.GetOption(thisOption.Name, throwOnMissing: false);
if (otherOption != null)
{
thisOption.CopyTo(otherOption);
}
}
}
public TOptionsBase CloneAs<TOptionsBase>() where TOptionsBase : ApplicationOptions, new()
{
var options = new TOptionsBase();
this.CopyTo(options);
return options;
}
#endregion
#region serialization methods and events.
protected string Serialize<TOptionsBase, TSerializer>() where TOptionsBase : ApplicationOptions, new()
where TSerializer : OptionsSerializer<TOptionsBase>, new()
{
var serializer = new TSerializer();
string jsonText = JsonConvert.SerializeObject(this, Formatting.Indented, serializer);
return jsonText;
}
protected static TOptionsBase Deserialize<TOptionsBase, TSerializer>(FileInfo fileInfo, bool throwOnError = true)
where TOptionsBase : ApplicationOptions, new()
where TSerializer : OptionsSerializer<TOptionsBase>, new()
{
return Deserialize<TOptionsBase, TSerializer>(null, fileInfo, throwOnError);
}
protected static TOptionsBase Deserialize<TOptionsBase, TSerializer>(string jsonText, bool throwOnError = true)
where TOptionsBase : ApplicationOptions, new()
where TSerializer : OptionsSerializer<TOptionsBase>, new()
{
return Deserialize<TOptionsBase, TSerializer>(jsonText, null, throwOnError);
}
private static TOptionsBase Deserialize<TOptionsBase, TSerializer>(string jsonText, FileInfo fileInfo, bool throwOnError = true)
where TOptionsBase : ApplicationOptions, new()
where TSerializer : OptionsSerializer<TOptionsBase>, new()
{
TOptionsBase options = new TOptionsBase();
try
{
if (string.IsNullOrEmpty(jsonText))
{
jsonText = File.ReadAllText(fileInfo.FullName);
fileInfo = null;
}
var serializer = new TSerializer();
options = JsonConvert.DeserializeObject<TOptionsBase>(jsonText, serializer);
}
catch (Exception ex)
{
if (Utils.IsFatalOrUnexpected(ex)) throw;
options._errors.Add(ex);
}
if (options._errors.Count > 0 && throwOnError)
{
var ex = new AggregateException(options.Errors);
throw ex;
}
return options;
}
protected static TOptionsBase FromFile<TOptionsBase>(string filePath, bool throwOnError = true) where TOptionsBase : ApplicationOptions, new()
{
return Deserialize<TOptionsBase, OptionsSerializer<TOptionsBase>>(null, new FileInfo(filePath), throwOnError);
}
protected static TOptionsBase FromJson<TOptionsBase>(string jsonText, bool throwOnError = true) where TOptionsBase : ApplicationOptions, new()
{
return Deserialize<TOptionsBase, OptionsSerializer<TOptionsBase>>(jsonText, null, throwOnError);
}
public void Save(string filePath)
{
File.WriteAllText(filePath, this.Json);
}
protected virtual void OnBeforeSerialize() { }
protected virtual void OnAfterSerialize() { }
protected virtual void OnBeforeDeserialize() { ResetOptions(); }
protected virtual void OnAfterDeserialize() { }
void IOptionsSerializationHandler.RaiseBeforeSerializeEvent() { OnBeforeSerialize(); }
void IOptionsSerializationHandler.RaiseAfterSerializeEvent() { OnAfterSerialize(); }
void IOptionsSerializationHandler.RaiseBeforeDeserializeEvent() { OnBeforeDeserialize(); }
void IOptionsSerializationHandler.RaiseAfterDeserializeEvent() { OnAfterDeserialize(); }
#endregion
#region options/values get/set
public OptionBase GetOption(string optionId, bool throwOnMissing = true)
{
return GetOption<OptionBase>(optionId, throwOnMissing);
}
/// <summary>
/// Returns the option requested by the option's ID, which can be the option's name or any of the option's aliases.
/// The option type is casted to the specified generic type.
/// </summary>
public TOptionBase GetOption<TOptionBase>(string optionId, bool throwOnMissing = true) where TOptionBase : OptionBase
{
var option = this.PropertyBag.ContainsKey(optionId) ?
this.PropertyBag[optionId] :
this.PropertyBag.Values.FirstOrDefault(v => v.HasSameId(optionId));
if (option == null && throwOnMissing)
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Shared.Resources.WarningUnrecognizedOptionFormat, optionId));
}
return (TOptionBase)option;
}
public bool TryGetOption(string optionId, out OptionBase option)
{
option = GetOption(optionId, throwOnMissing: false);
return option != null;
}
/// <summary>
/// Return the options that have been set.
/// </summary>
/// <returns></returns>
public IEnumerable<OptionBase> GetOptions(bool allOptions = false)
{
var requestedOptions = this.PropertyBag.Where(p =>
{
var option = p.Value;
// exclude the 'options' option and return only the options that have been set.
return option.Name != OptionsKey && (allOptions || option.HasValue);
}).Select(o => o.Value);
return requestedOptions;
}
public IEnumerable<OptionBase> GetAllOptions()
{
return GetOptions(allOptions: true);
}
/// <summary>
/// Get the value of the specified option casted to the specified generic type.
/// </summary>
public TValue GetValue<TValue>(string optionId, bool throwOnMissing = true)
{
var option = GetOption(optionId, throwOnMissing);
if (option != null && option.Value != null)
{
return (TValue)option.Value;
}
return default(TValue);
}
internal void SetValue(string optionId, object value)
{
var option = GetOption(optionId);
if (value != option.Value)
{
option.Value = value;
}
}
/// <summary>
/// This is used when deserializing into an options object.
/// Option values set in the constructor must be reset so they can be initialized from the deserialized object,
/// </summary>
private void ResetOptions()
{
GetOption(OptionsKey).IsInitialized = false;
foreach (var option in GetAllOptions())
{
option.IsInitialized = false;
}
}
#endregion
public void AddWarning(string warning, int idx = -1)
{
if (idx == -1)
{
this._warnings.Add(warning);
}
else
{
this._warnings.Insert(idx, warning);
}
}
public void AddError(string error)
{
var ex = new ArgumentException(error);
AddError(ex);
}
public void AddError(Exception ex)
{
this._errors.Add(ex);
}
public override string ToString()
{
return ToString(false);
}
public string ToString(bool prettyFormat)
{
var value = OptionsSerializer<ApplicationOptions>.SerializeToString(this, prettyFormat);
return value;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using DeOps.Implementation;
using DeOps.Implementation.Dht;
using DeOps.Implementation.Protocol;
using DeOps.Implementation.Protocol.Net;
using DeOps.Services.Assist;
using DeOps.Services.Location;
using DeOps.Services.Transfer;
using DeOps.Services.Trust;
using DeOps.Utility;
namespace DeOps.Services.Storage
{
public delegate void StorageUpdateHandler(OpStorage storage);
public delegate void WorkingUpdateHandler(uint project, string dir, ulong uid, WorkingChange action);
public class StorageService : OpService
{
public string Name { get { return "File System"; } }
public uint ServiceID { get { return (uint)ServiceIDs.Storage; } }
const uint FileTypeCache = 0x01;
const uint FileTypeData = 0x02;
const uint FileTypeWorking = 0x03;
const uint FileTypeResource = 0x04;
public OpCore Core;
public G2Protocol Protocol;
public DhtNetwork Network;
public DhtStore Store;
public TrustService Trust;
bool Loading = true;
List<string> ReferencedPaths = new List<string>();
public string DataPath;
public string WorkingPath;
public string ResourcePath;
public byte[] LocalFileKey;
RijndaelManaged FileCrypt = new RijndaelManaged();
bool SavingLocal;
public StorageUpdateHandler StorageUpdate;
public ThreadedDictionary<ulong, OpStorage> StorageMap = new ThreadedDictionary<ulong, OpStorage>();
public ThreadedDictionary<ulong, OpFile> FileMap = new ThreadedDictionary<ulong, OpFile>();
public ThreadedDictionary<ulong, OpFile> InternalFileMap = new ThreadedDictionary<ulong, OpFile>();// used to bring together files encrypted with different keys
VersionedCache Cache;
// working
public Dictionary<uint, WorkingStorage> Working = new Dictionary<uint, WorkingStorage>();
public WorkingUpdateHandler WorkingFileUpdate;
public WorkingUpdateHandler WorkingFolderUpdate;
public WorkerQueue UnlockFiles = new WorkerQueue("Storage Copy");
public WorkerQueue CopyFiles = new WorkerQueue("Storage Copy");
public WorkerQueue HashFiles = new WorkerQueue("Storage Hash");
public delegate void DisposingHandler();
public DisposingHandler Disposing;
public StorageService(OpCore core)
{
Core = core;
Network = core.Network;
Protocol = Network.Protocol;
Store = Network.Store;
Trust = Core.Trust;
Core.SecondTimerEvent += Core_SecondTimer;
Core.MinuteTimerEvent += Core_MinuteTimer;
Network.CoreStatusChange += new StatusChange(Network_StatusChange);
Core.Transfers.FileSearch[ServiceID, FileTypeData] += new FileSearchHandler(Transfers_DataFileSearch);
Core.Transfers.FileRequest[ServiceID, FileTypeData] += new FileRequestHandler(Transfers_DataFileRequest);
Core.Trust.LinkUpdate += new LinkUpdateHandler(Trust_Update);
LocalFileKey = Core.User.Settings.FileKey;
FileCrypt.Key = LocalFileKey;
FileCrypt.IV = new byte[FileCrypt.IV.Length];
string rootpath = Core.User.RootPath + Path.DirectorySeparatorChar + "Data" + Path.DirectorySeparatorChar + ServiceID.ToString() + Path.DirectorySeparatorChar;
DataPath = rootpath + FileTypeData.ToString();
WorkingPath = rootpath + FileTypeWorking.ToString();
ResourcePath = rootpath + FileTypeResource.ToString();
Directory.CreateDirectory(DataPath);
Directory.CreateDirectory(WorkingPath);
// clear resource files so that updates of these files work
if (Directory.Exists(ResourcePath))
Directory.Delete(ResourcePath, true);
Cache = new VersionedCache(Network, ServiceID, FileTypeCache, false);
Cache.FileAquired += new FileAquiredHandler(Cache_FileAquired);
Cache.FileRemoved += new FileRemovedHandler(Cache_FileRemoved);
Cache.Load();
// load working headers
OpStorage local = GetStorage(Core.UserID);
foreach (uint project in Trust.LocalTrust.Links.Keys)
{
if (local != null)
LoadHeaderFile(GetWorkingPath(project), local, false, true);
Working[project] = new WorkingStorage(this, project);
bool doSave = false;
foreach (ulong higher in Trust.GetAutoInheritIDs(Core.UserID, project))
if (Working[project].RefreshHigherChanges(higher))
doSave = true;
Working[project].AutoIntegrate(doSave);
}
foreach (string testPath in Directory.GetFiles(DataPath))
if (!ReferencedPaths.Contains(testPath))
try { File.Delete(testPath); }
catch { }
ReferencedPaths.Clear();
Loading = false;
}
public void Dispose()
{
if (Disposing != null)
Disposing();
HashFiles.Dispose();
CopyFiles.Dispose();
// lock down working
List<LockError> errors = new List<LockError>();
foreach (WorkingStorage working in Working.Values)
{
working.LockAll(errors);
if(working.Modified)
working.SaveWorking();
}
Working.Clear();
// delete completely folders made for other user's storages
Trust.ProjectRoots.LockReading(delegate()
{
foreach (uint project in Trust.ProjectRoots.Keys)
{
string path = Core.User.RootPath + Path.DirectorySeparatorChar + Trust.GetProjectName(project) + " Storage";
string local = Core.GetName(Core.UserID);
if (Directory.Exists(path))
foreach (string dir in Directory.GetDirectories(path))
if (Path.GetFileName(dir) != local)
{
try
{
Directory.Delete(dir, true);
}
catch
{
errors.Add(new LockError(dir, "", false, LockErrorType.Blocked));
}
}
}
});
// security warning: could not secure these files
if (errors.Count > 0)
{
string message = "Security Warning: Not able to delete these files, please do it manually\n";
foreach (LockError error in errors)
if (error.Type == LockErrorType.Blocked)
message += error.Path;
Core.UserMessage(message);
}
// kill events
Core.SecondTimerEvent -= Core_SecondTimer;
Core.MinuteTimerEvent -= Core_MinuteTimer;
Network.CoreStatusChange -= new StatusChange(Network_StatusChange);
Cache.FileAquired -= new FileAquiredHandler(Cache_FileAquired);
Cache.FileRemoved -= new FileRemovedHandler(Cache_FileRemoved);
Cache.Dispose();
Core.Transfers.FileSearch[ServiceID, FileTypeData] -= new FileSearchHandler(Transfers_DataFileSearch);
Core.Transfers.FileRequest[ServiceID, FileTypeData] -= new FileRequestHandler(Transfers_DataFileRequest);
Core.Trust.LinkUpdate -= new LinkUpdateHandler(Trust_Update);
}
void Core_SecondTimer()
{
// every 10 seconds
if (Core.TimeNow.Second % 9 == 0)
foreach(WorkingStorage working in Working.Values)
if (working.PeriodicSave)
{
working.SaveWorking();
working.PeriodicSave = false;
}
}
void Core_MinuteTimer()
{
// clear de-reffed files
// not working reliable, un-reffed files cleared out when app loads
/*FileMap.LockReading(delegate()
{
foreach (KeyValuePair<ulong, OpFile> pair in FileMap)
if (pair.Value.References == 0)
File.Delete(GetFilePath(pair.Key)); //crit test
});*/
}
public void SimTest()
{
// create file
// add file
// accept file
// integrate file
}
public void SimCleanup()
{
FileMap.SafeClear();
InternalFileMap.SafeClear();
WorkingStorage x = Working[0];
StorageFolder packet = new StorageFolder();
packet.Name = Core.Trust.GetProjectName(0) + " Files";
x.RootFolder = new LocalFolder(null, packet);
SaveLocal(0);
}
void Cache_FileRemoved(OpVersionedFile file)
{
OpStorage storage = GetStorage(file.UserID);
if(storage != null)
UnloadHeaderFile(GetFilePath(storage), storage.File.Header.FileKey);
StorageMap.SafeRemove(file.UserID);
}
public void CallFolderUpdate(uint project, string dir, ulong uid, WorkingChange action)
{
if (WorkingFolderUpdate != null)
Core.RunInGuiThread(WorkingFolderUpdate, project, dir, uid, action);
}
public void CallFileUpdate(uint project, string dir, ulong uid, WorkingChange action)
{
if (WorkingFileUpdate != null)
Core.RunInGuiThread(WorkingFileUpdate, project, dir, uid, action);
}
public void SaveLocal(uint project)
{
try
{
string tempPath = Core.GetTempPath();
byte[] key = Utilities.GenerateKey(Core.StrongRndGen, 256);
using (IVCryptoStream stream = IVCryptoStream.Save(tempPath, key))
{
// write loaded projects
WorkingStorage working = null;
if (Working.ContainsKey(project))
working = Working[project];
if (working != null)
{
Protocol.WriteToFile(new StorageRoot(working.ProjectID), stream);
working.WriteWorkingFile(stream, working.RootFolder, true);
working.Modified = false;
try { File.Delete(GetWorkingPath(project)); }
catch { }
}
// open old file and copy entries, except for working
OpStorage local = GetStorage(Core.UserID);
if (local != null)
{
string oldPath = GetFilePath(local);
if (File.Exists(oldPath))
{
using (TaggedStream file = new TaggedStream(oldPath, Network.Protocol))
using (IVCryptoStream crypto = IVCryptoStream.Load(file, local.File.Header.FileKey))
{
PacketStream oldStream = new PacketStream(crypto, Protocol, FileAccess.Read);
bool write = false;
G2Header g2header = null;
while (oldStream.ReadPacket(ref g2header))
{
if (g2header.Name == StoragePacket.Root)
{
StorageRoot root = StorageRoot.Decode(g2header);
write = (root.ProjectID != project);
}
//copy packet right to new file
if (write) //crit test
stream.Write(g2header.Data, g2header.PacketPos, g2header.PacketSize);
}
}
}
}
stream.WriteByte(0); // signal last packet
stream.FlushFinalBlock();
}
SavingLocal = true; // prevents auto-integrate from re-calling saveLocal
OpVersionedFile vfile = Cache.UpdateLocal(tempPath, key, BitConverter.GetBytes(Core.TimeNow.ToUniversalTime().ToBinary()));
SavingLocal = false;
Store.PublishDirect(Core.Trust.GetLocsAbove(), Core.UserID, ServiceID, FileTypeCache, vfile.SignedHeader);
}
catch (Exception ex)
{
Core.Network.UpdateLog("Storage", "Error updating local " + ex.Message);
}
if (StorageUpdate != null)
Core.RunInGuiThread(StorageUpdate, GetStorage(Core.UserID));
}
void Cache_FileAquired(OpVersionedFile file)
{
// unload old file
OpStorage prevStorage = GetStorage(file.UserID);
if (prevStorage != null)
{
string oldPath = GetFilePath(prevStorage);
UnloadHeaderFile(oldPath, prevStorage.File.Header.FileKey);
}
OpStorage newStorage = new OpStorage(file);
StorageMap.SafeAdd(file.UserID, newStorage);
LoadHeaderFile(GetFilePath(newStorage), newStorage, false, false);
// record changes of higher nodes for auto-integration purposes
Trust.ProjectRoots.LockReading(delegate()
{
foreach (uint project in Trust.ProjectRoots.Keys)
{
List<ulong> inheritIDs = Trust.GetAutoInheritIDs(Core.UserID, project);
if (Core.UserID == newStorage.UserID || inheritIDs.Contains(newStorage.UserID))
// doesnt get called on startup because working not initialized before headers are loaded
if (Working.ContainsKey(project))
{
bool doSave = Working[project].RefreshHigherChanges(newStorage.UserID);
if (!Loading && !SavingLocal)
Working[project].AutoIntegrate(doSave);
}
}
});
// update subs - this ensures file not propagated lower until we have it (prevents flood to original poster)
if (Network.Established)
{
List<LocationData> locations = new List<LocationData>();
Trust.ProjectRoots.LockReading(delegate()
{
foreach (uint project in Trust.ProjectRoots.Keys)
if (newStorage.UserID == Core.UserID || Trust.IsHigher(newStorage.UserID, project))
Trust.GetLocsBelow(Core.UserID, project, locations);
});
Store.PublishDirect(locations, newStorage.UserID, ServiceID, FileTypeCache, file.SignedHeader);
}
if (StorageUpdate != null)
Core.RunInGuiThread(StorageUpdate, newStorage);
if (Core.NewsWorthy(newStorage.UserID, 0, false))
Core.MakeNews(ServiceIDs.Storage, "File System updated by " + Core.GetName(newStorage.UserID), newStorage.UserID, 0, false);
}
void Trust_Update(OpTrust trust)
{
// update working projects (add)
if (trust.UserID == Core.UserID)
{
OpStorage local = GetStorage(Core.UserID);
foreach (uint project in Trust.LocalTrust.Links.Keys)
if (!Working.ContainsKey(project))
{
if(local != null)
LoadHeaderFile(GetWorkingPath(project), local, false, true);
Working[project] = new WorkingStorage(this, project);
}
}
// remove all higher changes, reload with new highers (cause link changed
foreach (WorkingStorage working in Working.Values )
if (Core.UserID == trust.UserID || Trust.IsHigher(trust.UserID, working.ProjectID))
{
working.RemoveAllHigherChanges();
foreach (ulong uplink in Trust.GetAutoInheritIDs(Core.UserID, working.ProjectID))
working.RefreshHigherChanges(uplink);
}
}
bool Transfers_DataFileSearch(ulong key, FileDetails details)
{
ulong hashID = BitConverter.ToUInt64(details.Hash, 0);
OpFile file = null;
if (FileMap.SafeTryGetValue(hashID, out file))
if (details.Size == file.Size && Utilities.MemCompare(details.Hash, file.Hash))
return true;
return false;
}
string Transfers_DataFileRequest(ulong key, FileDetails details)
{
ulong hashID = BitConverter.ToUInt64(details.Hash, 0);
OpFile file = null;
if (FileMap.SafeTryGetValue(hashID, out file))
if (details.Size == file.Size && Utilities.MemCompare(details.Hash, file.Hash))
return GetFilePath(hashID);
return null;
}
void Network_StatusChange()
{
if (!Network.Established)
return;
// trigger download of files now in cache range
StorageMap.LockReading(delegate()
{
foreach (OpStorage storage in StorageMap.Values)
if (Network.Routing.InCacheArea(storage.UserID))
LoadHeaderFile(GetFilePath(storage), storage, true, false);
});
}
public void Research(ulong key)
{
Cache.Research(key);
}
public string GetFilePath(OpStorage storage)
{
return Cache.GetFilePath(storage.File.Header);
}
public string GetFilePath(ulong hashID)
{
ICryptoTransform transform = FileCrypt.CreateEncryptor();
byte[] hash = BitConverter.GetBytes(hashID);
return DataPath + Path.DirectorySeparatorChar + Utilities.ToBase64String(transform.TransformFinalBlock(hash, 0, hash.Length));
}
public string GetWorkingPath(uint project)
{
return WorkingPath + Path.DirectorySeparatorChar + Utilities.CryptFilename(Core, "working:" + project.ToString());
}
public OpStorage GetStorage(ulong key)
{
OpStorage storage = null;
StorageMap.SafeTryGetValue(key, out storage);
return storage;
}
private void LoadHeaderFile(string path, OpStorage storage, bool reload, bool working)
{
try
{
if (!File.Exists(path))
return;
bool cached = Network.Routing.InCacheArea(storage.UserID);
bool local = false;
byte[] key = working ? LocalFileKey : storage.File.Header.FileKey;
using (TaggedStream filex = new TaggedStream(path, Network.Protocol))
using (IVCryptoStream crypto = IVCryptoStream.Load(filex, key))
{
PacketStream stream = new PacketStream(crypto, Protocol, FileAccess.Read);
G2Header header = null;
ulong currentUID = 0;
while (stream.ReadPacket(ref header))
{
if (!working && header.Name == StoragePacket.Root)
{
StorageRoot packet = StorageRoot.Decode(header);
local = Core.UserID == storage.UserID ||
GetHigherRegion(Core.UserID, packet.ProjectID).Contains(storage.UserID) ||
Trust.GetDownlinkIDs(Core.UserID, packet.ProjectID, 1).Contains(storage.UserID);
}
if (header.Name == StoragePacket.File)
{
StorageFile packet = StorageFile.Decode(header);
if (packet == null)
continue;
bool historyFile = true;
if (packet.UID != currentUID)
{
historyFile = false;
currentUID = packet.UID;
}
OpFile file = null;
if (!FileMap.SafeTryGetValue(packet.HashID, out file))
{
file = new OpFile(packet);
FileMap.SafeAdd(packet.HashID, file);
}
InternalFileMap.SafeAdd(packet.InternalHashID, file);
if (!reload)
file.References++;
if (!working) // if one ref is public, then whole file is marked public
file.Working = false;
if (packet.HashID == 0 || packet.InternalHash == null)
{
Debug.Assert(false);
continue;
}
string filepath = GetFilePath(packet.HashID);
file.Downloaded = File.Exists(filepath);
if (Loading && file.Downloaded && !ReferencedPaths.Contains(filepath))
ReferencedPaths.Add(filepath);
if (!file.Downloaded)
{
// if in local range only store latest
if (local && !historyFile)
DownloadFile(storage.UserID, packet);
// if storage is in cache range, download all files
else if (Network.Established && cached)
DownloadFile(storage.UserID, packet);
}
// on link update, if in local range, get latest files
// (handled by location update, when it sees a new version of storage component is available)
}
}
}
}
catch (Exception ex)
{
Core.Network.UpdateLog("Storage", "Error loading files " + ex.Message);
}
}
public void DownloadFile(ulong id, StorageFile file)
{
// called from hash thread
if (Core.InvokeRequired)
{
Core.RunInCoreAsync(delegate() { DownloadFile(id, file); });
return;
}
// if file still processing return
if (file.Hash == null)
return;
FileDetails details = new FileDetails(ServiceID, FileTypeData, file.Hash, file.Size, null);
Core.Transfers.StartDownload(id, details, GetFilePath(file.HashID), new EndDownloadHandler(EndDownloadFile), new object[] { file });
}
private void EndDownloadFile(object[] args)
{
StorageFile file = (StorageFile) args[0];
OpFile commonFile = null;
if (FileMap.SafeTryGetValue(file.HashID, out commonFile))
commonFile.Downloaded = true;
// interface list box would be watching if file is transferring, will catch completed update
}
private void UnloadHeaderFile(string path, byte[] key)
{
try
{
if (!File.Exists(path))
return;
using (TaggedStream filex = new TaggedStream(path, Network.Protocol))
using (IVCryptoStream crypto = IVCryptoStream.Load(filex, key))
{
PacketStream stream = new PacketStream(crypto, Protocol, FileAccess.Read);
G2Header header = null;
while (stream.ReadPacket(ref header))
{
if (header.Name == StoragePacket.File)
{
StorageFile packet = StorageFile.Decode(header);
if (packet == null)
continue;
OpFile commonFile = null;
if (!FileMap.SafeTryGetValue(packet.HashID, out commonFile))
continue;
commonFile.DeRef();
}
}
}
}
catch (Exception ex)
{
Core.Network.UpdateLog("Storage", "Error loading files " + ex.Message);
}
}
public void MarkforHash(LocalFile file, string path, uint project, string dir)
{
HashPack pack = new HashPack(file, path, project, dir);
lock (HashFiles.Pending)
if (HashFiles.Pending.Any(p => ((HashPack)p.Param2).File == file))
return;
file.Info.Size = new FileInfo(path).Length; // set so we can get hash status
HashFiles.Enqueue(() => HashFile(pack), pack);
}
void HashFile(HashPack pack)
{
// three steps, hash file, encrypt file, hash encrypted file
try
{
OpFile file = null;
StorageFile info = pack.File.Info.Clone();
// remove old references from local file
OpFile commonFile = null;
if (FileMap.SafeTryGetValue(pack.File.Info.HashID, out commonFile))
commonFile.DeRef(); //crit test
if (!File.Exists(pack.Path))
return;
// do public hash
Utilities.ShaHashFile(pack.Path, ref info.InternalHash, ref info.InternalSize);
info.InternalHashID = BitConverter.ToUInt64(info.InternalHash, 0);
// if file exists in public map, use key for that file
OpFile internalFile = null;
InternalFileMap.SafeTryGetValue(info.InternalHashID, out internalFile);
if (internalFile != null)
{
file = internalFile;
file.References++;
// if file already encrypted in our system, continue
if (File.Exists(GetFilePath(info.HashID)))
{
info.Size = file.Size;
info.FileKey = file.Key;
info.Hash = file.Hash;
info.HashID = file.HashID;
if (!Utilities.MemCompare(file.Hash, pack.File.Info.Hash))
ReviseFile(pack, info);
return;
}
}
// file key is opID and public hash xor'd so that files won't be duplicated on the network
// apply special compartment key here as well, xor again
RijndaelManaged crypt = Utilities.CommonFileKey(Core.User.Settings.OpKey, info.InternalHash);
info.FileKey = crypt.Key;
// encrypt file to temp dir
string tempPath = Core.GetTempPath();
Utilities.EncryptTagFile(pack.Path, tempPath, crypt, Core.Network.Protocol, ref info.Hash, ref info.Size);
info.HashID = BitConverter.ToUInt64(info.Hash, 0);
// move to official path
string path = GetFilePath(info.HashID);
if (!File.Exists(path))
File.Move(tempPath, path);
// if we dont have record of file make one
if (file == null)
{
file = new OpFile(info);
file.References++;
FileMap.SafeAdd(info.HashID, file);
InternalFileMap.SafeAdd(info.InternalHashID, file);
}
// else, record already made, just needed to put the actual file in the system
else
{
Debug.Assert(info.HashID == file.HashID);
}
// if hash is different than previous mark as modified
if (!Utilities.MemCompare(file.Hash, pack.File.Info.Hash))
ReviseFile(pack, info);
}
catch (Exception ex)
{
/*rotate file to back of queue
lock (HashQueue)
if (HashQueue.Count > 1)
HashQueue.Enqueue(HashQueue.Dequeue());*/
Core.Network.UpdateLog("Storage", "Hash thread: " + ex.Message);
}
}
private void ReviseFile(HashPack pack, StorageFile info)
{
// called from hash thread
if (Core.InvokeRequired)
{
Core.RunInCoreAsync(() => ReviseFile(pack, info));
return;
}
if (Working.ContainsKey(pack.Project))
Working[pack.Project].ReadyChange(pack.File, info);
CallFileUpdate(pack.Project, pack.Dir, info.UID, WorkingChange.Updated);
}
public string GetRootPath(ulong user, uint project)
{
return Core.User.RootPath + Path.DirectorySeparatorChar + Trust.GetProjectName(project) + " Storage" + Path.DirectorySeparatorChar + Core.GetName(user);
}
public WorkingStorage Discard(uint project)
{
if (Core.InvokeRequired)
{
WorkingStorage previous = null;
Core.RunInCoreBlocked(delegate() { previous = Discard(project); });
return previous;
}
if (!Working.ContainsKey(project))
return null;
// LockAll() to prevent unlocked discarded changes from conflicting with previous versions of
// files when they are unlocked again by the user
List<LockError> errors = new List<LockError>();
Working[project].LockAll(errors);
Working.Remove(project);
// call unload on working
string path = GetWorkingPath(project);
UnloadHeaderFile(path, LocalFileKey);
// delete working file
try { File.Delete(path); }
catch { };
//loadworking
Working[project] = new WorkingStorage(this, project);
if (StorageUpdate != null)
Core.RunInGuiThread(StorageUpdate, GetStorage(Core.UserID));
return Working[project];
}
public bool FileExists(StorageFile file)
{
if (FileMap.SafeContainsKey(file.HashID) &&
File.Exists(GetFilePath(file.HashID)))
return true;
return false;
}
public string DownloadStatus(StorageFile file)
{
// returns null if file not being handled by transfer component
if (file.Hash == null) // happens if file is being added to storage
return null;
return Core.Transfers.GetDownloadStatus(ServiceID, file.Hash, file.Size);
}
public bool IsFileUnlocked(ulong dht, uint project, string path, StorageFile file, bool history)
{
string finalpath = GetRootPath(dht, project) + path;
if (history)
finalpath += Path.DirectorySeparatorChar + ".history" + Path.DirectorySeparatorChar + GetHistoryName(file);
else
finalpath += Path.DirectorySeparatorChar + file.Name;
return File.Exists(finalpath);
}
public bool IsHistoryUnlocked(ulong dht, uint project, string path, ThreadedLinkedList<StorageItem> archived)
{
string finalpath = GetRootPath(dht, project) + path + Path.DirectorySeparatorChar + ".history" + Path.DirectorySeparatorChar;
bool result = false;
if (Directory.Exists(finalpath))
archived.LockReading(delegate()
{
foreach (StorageFile file in archived)
if (File.Exists(finalpath + GetHistoryName(file)))
{
result = true;
break;
}
});
return result;
}
private string GetHistoryName(StorageFile file)
{
string name = file.Name;
int pos = name.LastIndexOf('.');
if (pos == -1)
pos = name.Length;
string tag = "unhashed";
if(file.InternalHash != null)
tag = Utilities.BytestoHex(file.InternalHash, 0, 3, false);
name = name.Insert(pos, "-" + tag);
return name;
}
public string UnlockFile(ulong dht, uint project, string path, StorageFile file, bool history, List<LockError> errors)
{
// path needs to include name, because for things like history files name is diff than file.Info
string finalpath = GetRootPath(dht, project) + path;
finalpath += history ? Path.DirectorySeparatorChar + ".history" + Path.DirectorySeparatorChar : Path.DirectorySeparatorChar.ToString();
if (!CreateFolder(finalpath, errors, false))
return null;
finalpath += history ? GetHistoryName(file) : file.Name;
// file not in storage
if(!FileMap.SafeContainsKey(file.HashID) || !File.Exists(GetFilePath(file.HashID)))
{
errors.Add(new LockError(finalpath, "", true, LockErrorType.Missing));
return null;
}
// check if already unlocked
if (File.Exists(finalpath) && file.IsFlagged(StorageFlags.Unlocked))
return finalpath;
// file already exists
if(File.Exists(finalpath))
{
// ask user about local
if (dht == Core.UserID)
{
errors.Add(new LockError(finalpath, "", true, LockErrorType.Existing, file, history));
return null;
}
// overwrite remote
else
{
try
{
File.Delete(finalpath);
}
catch
{
// not an existing error, dont want to give user option to 'use' the old remote file
errors.Add(new LockError(finalpath, "", true, LockErrorType.Unexpected, file, history));
return null;
}
}
}
// extract file
try
{
Utilities.DecryptTagFile(GetFilePath(file.HashID), finalpath, file.FileKey, Core);
}
catch (Exception ex)
{
Core.Network.UpdateLog("Storage", "UnlockFile: " + ex.Message);
errors.Add(new LockError(finalpath, "", true, LockErrorType.Unexpected, file, history));
return null;
}
file.SetFlag(StorageFlags.Unlocked);
if (dht != Core.UserID)
{
//FileInfo info = new FileInfo(finalpath);
//info.IsReadOnly = true;
}
// local
else if (Working.ContainsKey(project) )
{
// let caller trigger event because certain ops unlock multiple files
// set watch on root path
Working[project].StartWatchers();
}
return finalpath;
}
public void LockFileCompletely(ulong dht, uint project, string path, ThreadedLinkedList<StorageItem> archived, List<LockError> errors)
{
if (archived.SafeCount == 0)
return;
StorageFile main = (StorageFile) archived.SafeFirst.Value;
string dirpath = GetRootPath(dht, project) + path;
// delete main file
string finalpath = dirpath + Path.DirectorySeparatorChar + main.Name;
if (File.Exists(finalpath))
if (DeleteFile(finalpath, errors, false))
main.RemoveFlag(StorageFlags.Unlocked);
// delete archived file
finalpath = dirpath + Path.DirectorySeparatorChar + ".history" + Path.DirectorySeparatorChar;
if (Directory.Exists(finalpath))
{
List<string> stillLocked = new List<string>();
archived.LockReading(delegate()
{
foreach (StorageFile file in archived)
{
string historyPath = finalpath + GetHistoryName(file);
if (File.Exists(historyPath))
if (DeleteFile(historyPath, errors, false))
file.RemoveFlag(StorageFlags.Unlocked);
else
stillLocked.Add(historyPath);
}
});
// delete history folder
DeleteFolder(finalpath, errors, stillLocked);
}
}
public bool DeleteFile(string path, List<LockError> errors, bool temp)
{
try
{
File.Delete(path);
}
catch(Exception ex)
{
errors.Add(new LockError(path, ex.Message, true, temp ? LockErrorType.Temp : LockErrorType.Blocked ));
return false;
}
return true;
}
public void DeleteFolder(string path, List<LockError> errors, List<string> stillLocked)
{
try
{
if (Directory.GetDirectories(path).Length > 0 || Directory.GetFiles(path).Length > 0)
{
foreach (string directory in Directory.GetDirectories(path))
if (stillLocked != null && !stillLocked.Contains(directory))
errors.Add(new LockError(directory, "", false, LockErrorType.Temp));
foreach (string file in Directory.GetFiles(path))
if (stillLocked != null && !stillLocked.Contains(file))
errors.Add(new LockError(file, "", true, LockErrorType.Temp));
}
else
{
foreach (WorkingStorage working in Working.Values)
if (path == working.RootPath)
working.StopWatchers();
Directory.Delete(path, true);
}
}
catch (Exception ex)
{
errors.Add(new LockError(path, ex.Message, false, LockErrorType.Blocked));
}
}
public bool CreateFolder(string path, List<LockError> errors, bool subs)
{
try
{
Directory.CreateDirectory(path);
}
catch (Exception ex)
{
LockError error = new LockError(path, ex.Message, true, LockErrorType.Unexpected);
error.Subs = subs;
errors.Add(error);
return false;
}
return true;
}
public void LockFile(ulong dht, uint project, string path, StorageFile file, bool history)
{
string finalpath = GetRootPath(dht, project) + path;
if (history)
finalpath += Path.DirectorySeparatorChar + ".history" + Path.DirectorySeparatorChar + GetHistoryName(file);
else
finalpath += Path.DirectorySeparatorChar + file.Name;
try
{
if (File.Exists(finalpath))
File.Delete(finalpath);
file.RemoveFlag(StorageFlags.Unlocked);
}
catch { }
}
public StorageActions ItemDiff(StorageItem item, StorageItem original)
{
StorageActions actions = StorageActions.None;
if (original == null)
return StorageActions.Created;
if (item.Name != original.Name)
actions = actions | StorageActions.Renamed;
if (ScopeChanged(item.Scope, original.Scope))
actions = actions | StorageActions.Scoped;
if (item.IsFlagged(StorageFlags.Archived) && !original.IsFlagged(StorageFlags.Archived))
actions = actions | StorageActions.Deleted;
if (!item.IsFlagged(StorageFlags.Archived) && original.IsFlagged(StorageFlags.Archived))
actions = actions | StorageActions.Restored;
if (item.GetType() == typeof(StorageFile))
if (!Utilities.MemCompare(((StorageFile)item).InternalHash, ((StorageFile)original).InternalHash))
actions = actions | StorageActions.Modified;
return actions;
}
public bool ScopeChanged(Dictionary<ulong, short> a, Dictionary<ulong, short> b)
{
if (a.Count != b.Count)
return true;
foreach (ulong id in a.Keys)
{
if (!b.ContainsKey(id))
return true;
if (a[id] != b[id])
return true;
}
return false;
}
public List<ulong> GetHigherRegion(ulong id, uint project)
{
// all users form id to the top, and direct subs of superior
List<ulong> highers = Trust.GetUplinkIDs(id, project); // works for loops
highers.AddRange(Trust.GetAdjacentIDs(id, project));
highers.Remove(id); // remove target
return highers;
}
}
public class OpStorage
{
public OpVersionedFile File;
public OpStorage(OpVersionedFile file)
{
File = file;
}
public ulong UserID
{
get
{
return File.UserID;
}
}
public DateTime Date
{
get
{
return DateTime.FromBinary(BitConverter.ToInt64(File.Header.Extra, 0));
}
}
}
public class OpFile
{
public long Size;
public ulong HashID;
public byte[] Key;
public byte[] Hash;
public int References;
public bool Working;
public bool Downloaded;
public OpFile(StorageFile file)
{
HashID = file.HashID;
Hash = file.Hash;
Size = file.Size;
Key = file.FileKey;
Working = true;
}
public void DeRef()
{
if (References > 0)
References--;
}
}
public class HashPack
{
public LocalFile File;
public string Path;
public string Dir;
public uint Project;
public HashPack(LocalFile file, string path, uint project, string dir)
{
File = file;
Path = path;
Project = project;
Dir = dir;
}
public override bool Equals(object obj)
{
HashPack pack = obj as HashPack;
if(obj == null)
return false;
return (string.Compare(Path, pack.Path, true) == 0);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Drawing.Text;
using System.Globalization;
using System.Runtime.InteropServices;
using Gdip = System.Drawing.SafeNativeMethods.Gdip;
namespace System.Drawing
{
/// <summary>
/// Abstracts a group of type faces having a similar basic design but having certain variation in styles.
/// </summary>
public sealed partial class FontFamily : MarshalByRefObject, IDisposable
{
private const int NeutralLanguage = 0;
private IntPtr _nativeFamily;
private readonly bool _createDefaultOnFail;
#if DEBUG
private static readonly object s_lockObj = new object();
private static int s_idCount = 0;
private int _id;
#endif
private void SetNativeFamily(IntPtr family)
{
Debug.Assert(_nativeFamily == IntPtr.Zero, "Setting GDI+ native font family when already initialized.");
_nativeFamily = family;
#if DEBUG
lock (s_lockObj)
{
_id = ++s_idCount;
}
#endif
}
internal FontFamily(IntPtr family) => SetNativeFamily(family);
/// <summary>
/// Initializes a new instance of the <see cref='FontFamily'/> class with the specified name.
///
/// The <paramref name="createDefaultOnFail"/> parameter determines how errors are handled when creating a
/// font based on a font family that does not exist on the end user's system at run time. If this parameter is
/// true, then a fall-back font will always be used instead. If this parameter is false, an exception will be thrown.
/// </summary>
internal FontFamily(string name, bool createDefaultOnFail)
{
_createDefaultOnFail = createDefaultOnFail;
CreateFontFamily(name, null);
}
/// <summary>
/// Initializes a new instance of the <see cref='FontFamily'/> class with the specified name.
/// </summary>
public FontFamily(string name) => CreateFontFamily(name, null);
/// <summary>
/// Initializes a new instance of the <see cref='FontFamily'/> class in the specified
/// <see cref='FontCollection'/> and with the specified name.
/// </summary>
public FontFamily(string name, FontCollection fontCollection) => CreateFontFamily(name, fontCollection);
// Creates the native font family object.
// Note: GDI+ creates singleton font family objects (from the corresponding font file) and reference count them.
private void CreateFontFamily(string name, FontCollection fontCollection)
{
IntPtr fontfamily = IntPtr.Zero;
IntPtr nativeFontCollection = (fontCollection == null) ? IntPtr.Zero : fontCollection._nativeFontCollection;
int status = Gdip.GdipCreateFontFamilyFromName(name, new HandleRef(fontCollection, nativeFontCollection), out fontfamily);
if (status != Gdip.Ok)
{
if (_createDefaultOnFail)
{
fontfamily = GetGdipGenericSansSerif(); // This throws if failed.
}
else
{
// Special case this incredibly common error message to give more information.
if (status == Gdip.FontFamilyNotFound)
{
throw new ArgumentException(SR.Format(SR.GdiplusFontFamilyNotFound, name));
}
else if (status == Gdip.NotTrueTypeFont)
{
throw new ArgumentException(SR.Format(SR.GdiplusNotTrueTypeFont, name));
}
else
{
throw Gdip.StatusException(status);
}
}
}
SetNativeFamily(fontfamily);
}
/// <summary>
/// Initializes a new instance of the <see cref='FontFamily'/> class from the specified generic font family.
/// </summary>
public FontFamily(GenericFontFamilies genericFamily)
{
IntPtr nativeFamily = IntPtr.Zero;
int status;
switch (genericFamily)
{
case GenericFontFamilies.Serif:
status = Gdip.GdipGetGenericFontFamilySerif(out nativeFamily);
break;
case GenericFontFamilies.SansSerif:
status = Gdip.GdipGetGenericFontFamilySansSerif(out nativeFamily);
break;
case GenericFontFamilies.Monospace:
default:
status = Gdip.GdipGetGenericFontFamilyMonospace(out nativeFamily);
break;
}
Gdip.CheckStatus(status);
SetNativeFamily(nativeFamily);
}
~FontFamily() => Dispose(false);
internal IntPtr NativeFamily => _nativeFamily;
/// <summary>
/// Converts this <see cref='FontFamily'/> to a human-readable string.
/// </summary>
public override string ToString() => $"[{GetType().Name}: Name={Name}]";
/// <summary>
/// Gets a hash code for this <see cref='FontFamily'/>.
/// </summary>
public override int GetHashCode() => GetName(NeutralLanguage).GetHashCode();
private static int CurrentLanguage => CultureInfo.CurrentUICulture.LCID;
/// <summary>
/// Disposes of this <see cref='FontFamily'/>.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (_nativeFamily != IntPtr.Zero)
{
try
{
#if DEBUG
int status = !Gdip.Initialized ? Gdip.Ok :
#endif
Gdip.GdipDeleteFontFamily(new HandleRef(this, _nativeFamily));
#if DEBUG
Debug.Assert(status == Gdip.Ok, "GDI+ returned an error status: " + status.ToString(CultureInfo.InvariantCulture));
#endif
}
catch (Exception ex) when (!ClientUtils.IsCriticalException(ex))
{
}
finally
{
_nativeFamily = IntPtr.Zero;
}
}
}
/// <summary>
/// Gets the name of this <see cref='FontFamily'/>.
/// </summary>
public string Name => GetName(CurrentLanguage);
/// <summary>
/// Returns the name of this <see cref='FontFamily'/> in the specified language.
/// </summary>
public unsafe string GetName(int language)
{
char* name = stackalloc char[32]; // LF_FACESIZE is 32
int status = Gdip.GdipGetFamilyName(new HandleRef(this, NativeFamily), name, language);
Gdip.CheckStatus(status);
return Marshal.PtrToStringUni((IntPtr)name);
}
/// <summary>
/// Returns an array that contains all of the <see cref='FontFamily'/> objects associated with the current
/// graphics context.
/// </summary>
public static FontFamily[] Families => new InstalledFontCollection().Families;
/// <summary>
/// Gets a generic SansSerif <see cref='FontFamily'/>.
/// </summary>
public static FontFamily GenericSansSerif => new FontFamily(GetGdipGenericSansSerif());
private static IntPtr GetGdipGenericSansSerif()
{
IntPtr nativeFamily = IntPtr.Zero;
int status = Gdip.GdipGetGenericFontFamilySansSerif(out nativeFamily);
Gdip.CheckStatus(status);
return nativeFamily;
}
/// <summary>
/// Gets a generic Serif <see cref='FontFamily'/>.
/// </summary>
public static FontFamily GenericSerif => new FontFamily(GenericFontFamilies.Serif);
/// <summary>
/// Gets a generic monospace <see cref='FontFamily'/>.
/// </summary>
public static FontFamily GenericMonospace => new FontFamily(GenericFontFamilies.Monospace);
/// <summary>
/// Returns an array that contains all of the <see cref='FontFamily'/> objects associated with the specified
/// graphics context.
/// </summary>
[Obsolete("Do not use method GetFamilies, use property Families instead")]
public static FontFamily[] GetFamilies(Graphics graphics)
{
if (graphics == null)
{
throw new ArgumentNullException(nameof(graphics));
}
return new InstalledFontCollection().Families;
}
/// <summary>
/// Indicates whether the specified <see cref='FontStyle'/> is available.
/// </summary>
public bool IsStyleAvailable(FontStyle style)
{
int bresult;
int status = Gdip.GdipIsStyleAvailable(new HandleRef(this, NativeFamily), style, out bresult);
Gdip.CheckStatus(status);
return bresult != 0;
}
/// <summary>
/// Gets the size of the Em square for the specified style in font design units.
/// </summary>
public int GetEmHeight(FontStyle style)
{
int result = 0;
int status = Gdip.GdipGetEmHeight(new HandleRef(this, NativeFamily), style, out result);
Gdip.CheckStatus(status);
return result;
}
/// <summary>
/// Returns the ascender metric for Windows.
/// </summary>
public int GetCellAscent(FontStyle style)
{
int result = 0;
int status = Gdip.GdipGetCellAscent(new HandleRef(this, NativeFamily), style, out result);
Gdip.CheckStatus(status);
return result;
}
/// <summary>
/// Returns the descender metric for Windows.
/// </summary>
public int GetCellDescent(FontStyle style)
{
int result = 0;
int status = Gdip.GdipGetCellDescent(new HandleRef(this, NativeFamily), style, out result);
Gdip.CheckStatus(status);
return result;
}
/// <summary>
/// Returns the distance between two consecutive lines of text for this <see cref='FontFamily'/> with the
/// specified <see cref='FontStyle'/>.
/// </summary>
public int GetLineSpacing(FontStyle style)
{
int result = 0;
int status = Gdip.GdipGetLineSpacing(new HandleRef(this, NativeFamily), style, out result);
Gdip.CheckStatus(status);
return result;
}
}
}
| |
//C:\Users\t-kevimi\\Documents\\LuaTests\Lua Files for Testing\TableStatements.lua
using LanguageModel.Tests.TestGeneration;
using LanguageService;
using Xunit;
namespace LanguageModel.Tests.GeneratedTestFiles
{
class Generated_30
{
[Fact]
public void Test(Tester t)
{
t.N(SyntaxKind.ChunkNode);
{
t.N(SyntaxKind.BlockNode);
{
t.N(SyntaxKind.AssignmentStatementNode);
{
t.N(SyntaxKind.VarList);
{
t.N(SyntaxKind.NameVar);
{
t.N(SyntaxKind.Identifier);
}
}
t.N(SyntaxKind.AssignmentOperator);
t.N(SyntaxKind.ExpList);
{
t.N(SyntaxKind.TableConstructorExp);
{
t.N(SyntaxKind.OpenCurlyBrace);
t.N(SyntaxKind.FieldList);
t.N(SyntaxKind.CloseCurlyBrace);
}
}
}
t.N(SyntaxKind.AssignmentStatementNode);
{
t.N(SyntaxKind.VarList);
{
t.N(SyntaxKind.NameVar);
{
t.N(SyntaxKind.Identifier);
}
}
t.N(SyntaxKind.AssignmentOperator);
t.N(SyntaxKind.ExpList);
{
t.N(SyntaxKind.SimpleExpression);
{
t.N(SyntaxKind.String);
}
}
}
t.N(SyntaxKind.AssignmentStatementNode);
{
t.N(SyntaxKind.VarList);
{
t.N(SyntaxKind.SquareBracketVar);
{
t.N(SyntaxKind.NameVar);
{
t.N(SyntaxKind.Identifier);
}
t.N(SyntaxKind.OpenBracket);
t.N(SyntaxKind.NameVar);
{
t.N(SyntaxKind.Identifier);
}
t.N(SyntaxKind.CloseBracket);
}
}
t.N(SyntaxKind.AssignmentOperator);
t.N(SyntaxKind.ExpList);
{
t.N(SyntaxKind.SimpleExpression);
{
t.N(SyntaxKind.Number);
}
}
}
t.N(SyntaxKind.AssignmentStatementNode);
{
t.N(SyntaxKind.VarList);
{
t.N(SyntaxKind.SquareBracketVar);
{
t.N(SyntaxKind.NameVar);
{
t.N(SyntaxKind.Identifier);
}
t.N(SyntaxKind.OpenBracket);
t.N(SyntaxKind.SimpleExpression);
{
t.N(SyntaxKind.Number);
}
t.N(SyntaxKind.CloseBracket);
}
}
t.N(SyntaxKind.AssignmentOperator);
t.N(SyntaxKind.ExpList);
{
t.N(SyntaxKind.SimpleExpression);
{
t.N(SyntaxKind.String);
}
}
}
t.N(SyntaxKind.FunctionCallStatementNode);
{
t.N(SyntaxKind.NameVar);
{
t.N(SyntaxKind.Identifier);
}
t.N(SyntaxKind.ParenArg);
{
t.N(SyntaxKind.OpenParen);
t.N(SyntaxKind.ExpList);
{
t.N(SyntaxKind.SquareBracketVar);
{
t.N(SyntaxKind.NameVar);
{
t.N(SyntaxKind.Identifier);
}
t.N(SyntaxKind.OpenBracket);
t.N(SyntaxKind.SimpleExpression);
{
t.N(SyntaxKind.String);
}
t.N(SyntaxKind.CloseBracket);
}
}
t.N(SyntaxKind.CloseParen);
}
}
t.N(SyntaxKind.AssignmentStatementNode);
{
t.N(SyntaxKind.VarList);
{
t.N(SyntaxKind.NameVar);
{
t.N(SyntaxKind.Identifier);
}
}
t.N(SyntaxKind.AssignmentOperator);
t.N(SyntaxKind.ExpList);
{
t.N(SyntaxKind.SimpleExpression);
{
t.N(SyntaxKind.Number);
}
}
}
t.N(SyntaxKind.FunctionCallStatementNode);
{
t.N(SyntaxKind.NameVar);
{
t.N(SyntaxKind.Identifier);
}
t.N(SyntaxKind.ParenArg);
{
t.N(SyntaxKind.OpenParen);
t.N(SyntaxKind.ExpList);
{
t.N(SyntaxKind.SquareBracketVar);
{
t.N(SyntaxKind.NameVar);
{
t.N(SyntaxKind.Identifier);
}
t.N(SyntaxKind.OpenBracket);
t.N(SyntaxKind.NameVar);
{
t.N(SyntaxKind.Identifier);
}
t.N(SyntaxKind.CloseBracket);
}
}
t.N(SyntaxKind.CloseParen);
}
}
t.N(SyntaxKind.AssignmentStatementNode);
{
t.N(SyntaxKind.VarList);
{
t.N(SyntaxKind.SquareBracketVar);
{
t.N(SyntaxKind.NameVar);
{
t.N(SyntaxKind.Identifier);
}
t.N(SyntaxKind.OpenBracket);
t.N(SyntaxKind.SimpleExpression);
{
t.N(SyntaxKind.String);
}
t.N(SyntaxKind.CloseBracket);
}
}
t.N(SyntaxKind.AssignmentOperator);
t.N(SyntaxKind.ExpList);
{
t.N(SyntaxKind.BinaryOperatorExpression);
{
t.N(SyntaxKind.SquareBracketVar);
{
t.N(SyntaxKind.NameVar);
{
t.N(SyntaxKind.Identifier);
}
t.N(SyntaxKind.OpenBracket);
t.N(SyntaxKind.SimpleExpression);
{
t.N(SyntaxKind.String);
}
t.N(SyntaxKind.CloseBracket);
}
t.N(SyntaxKind.PlusOperator);
t.N(SyntaxKind.SimpleExpression);
{
t.N(SyntaxKind.Number);
}
}
}
}
t.N(SyntaxKind.FunctionCallStatementNode);
{
t.N(SyntaxKind.NameVar);
{
t.N(SyntaxKind.Identifier);
}
t.N(SyntaxKind.ParenArg);
{
t.N(SyntaxKind.OpenParen);
t.N(SyntaxKind.ExpList);
{
t.N(SyntaxKind.SquareBracketVar);
{
t.N(SyntaxKind.NameVar);
{
t.N(SyntaxKind.Identifier);
}
t.N(SyntaxKind.OpenBracket);
t.N(SyntaxKind.SimpleExpression);
{
t.N(SyntaxKind.String);
}
t.N(SyntaxKind.CloseBracket);
}
}
t.N(SyntaxKind.CloseParen);
}
}
}
t.N(SyntaxKind.EndOfFile);
}
}
}
}
| |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
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.Web.UI;
using System;
using System.Web;
namespace Contoso.Web.UI.Integrate
{
/// <summary>
/// GoogleAnalyticsTracker
/// </summary>
// http://code.google.com/apis/analytics/docs/gaJS/gaJSApiEcommerce.html
public class GoogleAnalyticsTracker : Control
{
private static readonly string AppSettingID_OperationMode = "GoogleAnalyticsTracker::OperationMode";
private static readonly string AppSettingID_TrackerID = "GoogleAnalyticsTracker::TrackerID";
private static readonly Type _trackerOperationModeType = typeof(TrackerOperationMode);
#region Class Types
public class AnalyticsAttributes
{
public bool? AllowLinker { get; set; }
public string DomainName { get; set; }
public bool? AllowHash { get; set; }
}
/// <summary>
/// TrackerOperationMode
/// </summary>
public enum TrackerOperationMode
{
/// <summary>
/// Production
/// </summary>
Production,
/// <summary>
/// Development
/// </summary>
Development,
/// <summary>
/// Commented
/// </summary>
Commented,
}
/// <summary>
/// AnalyticsCommerceTransaction
/// </summary>
public class AnalyticsCommerceTransaction
{
/// <summary>
/// Initializes a new instance of the <see cref="AnalyticsCommerceTransaction"/> class.
/// </summary>
public AnalyticsCommerceTransaction()
{
Country = "USA";
}
/// <summary>
/// OrderID
/// </summary>
public string OrderID { get; set; }
/// <summary>
/// AffiliationID
/// </summary>
public string AffiliationID { get; set; }
/// <summary>
/// TotalAmount
/// </summary>
public decimal TotalAmount { get; set; }
/// <summary>
/// TaxAmount
/// </summary>
public decimal TaxAmount { get; set; }
/// <summary>
/// ShippingAmount
/// </summary>
public decimal ShippingAmount { get; set; }
/// <summary>
/// City
/// </summary>
public string City { get; set; }
/// <summary>
/// State
/// </summary>
public string State { get; set; }
/// <summary>
/// Country
/// </summary>
public string Country { get; set; }
}
/// <summary>
/// AnalyticsCommerceItem
/// </summary>
public class AnalyticsCommerceItem
{
/// <summary>
/// Initializes a new instance of the <see cref="AnalyticsCommerceItem"/> class.
/// </summary>
public AnalyticsCommerceItem() { }
/// <summary>
/// OrderID
/// </summary>
public string OrderID { get; set; }
/// <summary>
/// SkuID
/// </summary>
public string SkuID { get; set; }
/// <summary>
/// ProductName
/// </summary>
public string ProductName { get; set; }
/// <summary>
/// CategoryName
/// </summary>
public string CategoryName { get; set; }
/// <summary>
/// Price
/// </summary>
public decimal Price { get; set; }
/// <summary>
/// Count
/// </summary>
public int Count { get; set; }
}
#endregion
public GoogleAnalyticsTracker()
: base()
{
DeploymentTarget = DeploymentEnvironment.Production;
Version = 3;
//var hash = Kernel.Instance.Hash;
//// determine operationMode
//object operationMode;
//if (hash.TryGetValue(AppSettingID_OperationMode, out operationMode))
// OperationMode = (TrackerOperationMode)Enum.Parse(s_trackerOperationModeType, (string)operationMode);
//else if (EnvironmentEx.DeploymentEnvironment == DeploymentTarget)
// OperationMode = TrackerOperationMode.Production;
//else
// OperationMode = TrackerOperationMode.Development;
//// determine trackerID
//object trackerID;
//if (hash.TryGetValue(AppSettingID_TrackerID, out trackerID))
// TrackerID = trackerID.Parse<string>();
}
/// <summary>
/// Gets or sets the operation mode.
/// </summary>
/// <value>The operation mode.</value>
public TrackerOperationMode OperationMode { get; set; }
/// <summary>
/// Sends server control content to a provided <see cref="T:System.Web.UI.HtmlTextWriter"/> object, which writes the content to be rendered on the client.
/// </summary>
/// <param name="writer">The <see cref="T:System.Web.UI.HtmlTextWriter"/> object that receives the server control content.</param>
protected override void Render(HtmlTextWriter w)
{
if (string.IsNullOrEmpty(TrackerID))
return;
OnPreEmit();
var operationMode = OperationMode;
switch (operationMode)
{
case TrackerOperationMode.Production:
case TrackerOperationMode.Commented:
var emitCommented = (operationMode == TrackerOperationMode.Commented);
switch (Version)
{
case 3:
EmitVersion3(w, emitCommented);
break;
case 2:
EmitVersion2(w, emitCommented);
break;
case 1:
EmitVersion1(w, emitCommented);
break;
default:
throw new InvalidOperationException();
}
break;
case TrackerOperationMode.Development:
w.WriteLine("<!--GoogleAnalyticsTracker[" + HttpUtility.HtmlEncode(TrackerID) + "]-->");
var commerceTransaction = CommerceTransaction;
if (commerceTransaction != null)
w.WriteLine("<!--GoogleAnalyticsTracker::CommerceTransaction[" + commerceTransaction.OrderID + "]-->");
var commerceItemArray = CommerceItems;
if (commerceItemArray != null)
w.WriteLine("<!--GoogleAnalyticsTracker::CommerceItemArray[" + commerceItemArray.Length.ToString() + "]-->");
break;
default:
throw new InvalidOperationException();
}
}
public DeploymentEnvironment DeploymentTarget { get; set; }
#region Emit
private void EmitCommerceVersion2(HtmlTextWriter w, bool emitCommented)
{
var commerceTransaction = CommerceTransaction;
var commerceItems = CommerceItems;
if ((commerceTransaction != null) || (commerceItems != null))
{
if (commerceTransaction != null)
{
w.Write("pageTracker._addTrans(");
w.Write(ClientScript.EncodeText(commerceTransaction.OrderID ?? string.Empty));
w.Write(","); w.Write(ClientScript.EncodeText(commerceTransaction.AffiliationID ?? string.Empty));
w.Write(","); w.Write(ClientScript.EncodeText(commerceTransaction.TotalAmount.ToString()));
w.Write(","); w.Write(ClientScript.EncodeText(commerceTransaction.TaxAmount.ToString()));
w.Write(","); w.Write(ClientScript.EncodeText(commerceTransaction.ShippingAmount.ToString()));
w.Write(","); w.Write(ClientScript.EncodeText(commerceTransaction.City ?? string.Empty));
w.Write(","); w.Write(ClientScript.EncodeText(commerceTransaction.State ?? string.Empty));
w.Write(","); w.Write(ClientScript.EncodeText(commerceTransaction.Country ?? string.Empty));
w.Write(");\n");
}
if (commerceItems != null)
foreach (var commerceItem in commerceItems)
if (commerceItem != null)
{
w.Write("pageTracker._addItem(");
w.Write(ClientScript.EncodeText(commerceItem.OrderID ?? string.Empty));
w.Write(","); w.Write(ClientScript.EncodeText(commerceItem.SkuID ?? string.Empty));
w.Write(","); w.Write(ClientScript.EncodeText(commerceItem.ProductName ?? string.Empty));
w.Write(","); w.Write(ClientScript.EncodeText(commerceItem.CategoryName ?? string.Empty));
w.Write(","); w.Write(ClientScript.EncodeText(commerceItem.Price.ToString()));
w.Write(","); w.Write(ClientScript.EncodeText(commerceItem.Count.ToString()));
w.Write(");\n");
}
w.Write("pageTracker._trackTrans();\n");
}
}
/// <summary>
/// Emits the version3.
/// </summary>
/// <param name="writer">The writer.</param>
private void EmitVersion3(HtmlTextWriter w, bool emitCommented)
{
w.Write(!emitCommented ? "<script type=\"text/javascript\">\n" : "<!--script type=\"text/javascript\">\n");
w.Write(@"//<![CDATA[
var _gaq = _gaq || [];
_gaq.push(['_setAccount', '"); w.Write(TrackerID); w.WriteLine(@"']);");
if (Attributes != null)
{
if (!string.IsNullOrEmpty(Attributes.DomainName))
{
w.Write(@"_gaq.push(['_setDomainName', "); w.Write(ClientScript.EncodeText(Attributes.DomainName)); w.WriteLine(@"]);");
}
if (Attributes.AllowLinker.HasValue)
{
w.Write(@"_gaq.push(['setAllowLinker', "); w.Write(ClientScript.EncodeBool(Attributes.AllowLinker.Value)); w.WriteLine(@"]);");
}
if (Attributes.AllowHash.HasValue)
{
w.Write(@"_gaq.push(['setAllowHash', "); w.Write(ClientScript.EncodeBool(Attributes.AllowHash.Value)); w.WriteLine(@"]);");
}
}
w.Write(@"_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
//]]>");
w.Write(!emitCommented ? "</script>\n" : "</script-->");
}
/// <summary>
/// Emits the version2.
/// </summary>
/// <param name="writer">The writer.</param>
private void EmitVersion2(HtmlTextWriter w, bool emitCommented)
{
w.Write(!emitCommented ? "<script type=\"text/javascript\">\n" : "<!--script type=\"text/javascript\">\n");
w.Write(@"//<![CDATA[
var gaJsHost = ((""https:"" == document.location.protocol) ? ""https://ssl."" : ""http://www."");
document.write(unescape(""%3Cscript src='"" + gaJsHost + ""google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E""));
//]]>");
w.Write(!emitCommented ? "</script><script type=\"text/javascript\">\n" : "</script--><!--script type=\"text/javascript\">\n");
w.Write(@"//<![CDATA[
try {
var pageTracker = _gat._getTracker("""); w.Write(TrackerID); w.Write("\");\n");
w.Write("pageTracker._trackPageview();\n");
EmitCommerceVersion2(w, emitCommented);
w.Write(@"} catch(err) {}
//]]>");
w.Write(!emitCommented ? "</script>\n" : "</script-->");
}
/// <summary>
/// Emits the version1.
/// </summary>
/// <param name="writer">The writer.</param>
private void EmitVersion1(HtmlTextWriter w, bool emitCommented)
{
w.Write(!emitCommented ? "<script src=\"http://www.google-analytics.com/urchin.js\" type=\"text/javascript\"></script><script type=\"text/javascript\">" : "<!--script src=\"http://www.google-analytics.com/urchin.js\" type=\"text/javascript\"></script--><!--script type=\"text/javascript\">");
w.Write(@"//<![CDATA[
_uacct = """); w.Write(TrackerID); w.Write(@""";
urchinTracker();
//]]>");
w.Write(!emitCommented ? "</script>" : "</script-->");
}
#endregion
public AnalyticsAttributes Attributes { get; set; }
/// <summary>
/// Gets or sets the commerce transaction.
/// </summary>
/// <value>The commerce transaction.</value>
public AnalyticsCommerceTransaction CommerceTransaction { get; set; }
/// <summary>
/// Gets or sets the commerce item array.
/// </summary>
/// <value>The commerce item array.</value>
public AnalyticsCommerceItem[] CommerceItems { get; set; }
/// <summary>
/// Gets or sets the tracker id.
/// </summary>
/// <value>The tracker id.</value>
public string TrackerID { get; set; }
/// <summary>
/// Gets or sets the version.
/// </summary>
/// <value>The version.</value>
//+ should be: VersionID
public int Version { get; set; }
/// <summary>
/// Called when [pre emit].
/// </summary>
protected virtual void OnPreEmit()
{
var preEmit = PreEmit;
if (preEmit != null)
preEmit(this, EventArgs.Empty);
}
/// <summary>
/// Occurs when [pre emit].
/// </summary>
public event EventHandler PreEmit;
}
}
| |
/*
Copyright 2019 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 System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using ArcGIS.Desktop.Editing;
using ArcGIS.Desktop.Mapping;
using ArcGIS.Core.Geometry;
using ArcGIS.Core.Data.UtilityNetwork;
using UtilityNetworkSamples;
using ArcGIS.Desktop.Mapping.Events;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using ArcGIS.Core.Data;
namespace CreateTransformerBank
{
internal class CreateTransformerBankTool : MapTool
{
// Utility Network Constants - Change these to match your data model as needed
const string AssemblyNetworkSourceName = "Electric Assembly";
const string DeviceNetworkSourceName = "Electric Device";
const string TransformerBankAssetGroupName = "Medium Voltage Transformer Bank";
const string TransformerBankAssetTypeName = "Overhead Three Phase";
const string TransformerAssetGroupName = "Medium Voltage Transformer";
const string TransformerAssetTypeName = "Overhead Single Phase";
const string FuseAssetGroupName = "Medium Voltage Fuse";
const string FuseAssetTypeName = "Overhead Cutout Fused Disconnect";
const string ArresterAssetGroupName = "Medium Voltage Arrester";
const string ArresterAssetTypeName = "MV Line Arrester";
const string PhaseFieldName = "phasescurrent";
const int APhase = 4;
const int BPhase = 2;
const int CPhase = 1;
const string DeviceStatusFieldName = "currentdevicestatus";
const int DeviceStatusClosed = 2;
const int DeviceStatusOpen = 1;
// These numbers are used to space out the features created within the bank.
const double XOffset = 1.0;
const double YOffset = 1.0;
public CreateTransformerBankTool()
{
IsSketchTool = true;
UseSnapping = true;
// Select the type of construction tool you wish to implement.
// Make sure that the tool is correctly registered with the correct component category type in the daml
SketchType = SketchGeometryType.Point;
}
/// <summary>
/// Called when the sketch finishes. This is where we will create the sketch operation and then execute it.
/// </summary>
/// <param name="geometry">The geometry created by the sketch.</param>
/// <returns>A Task returning a Boolean indicating if the sketch complete event was successfully handled.</returns>
protected override async Task<bool> OnSketchCompleteAsync(Geometry geometry)
{
if (geometry == null) return false;
// Create an edit operation
var createOperation = new EditOperation()
{
Name = "Create Transformer Bank",
SelectNewFeatures = true
};
bool success = false;
string errorMessage = "";
await QueuedTask.Run(() =>
{
Map map = GetMap();
using (UtilityNetwork utilityNetwork = GetUtilityNetwork())
{
if (utilityNetwork == null)
{
errorMessage = "Please select a layer that participates in a utility network.";
}
else
{
if (!ValidateDataModel(utilityNetwork))
{
errorMessage = "This sample is designed for a different utility network data model";
}
else
{
using (UtilityNetworkDefinition utilityNetworkDefinition = utilityNetwork.GetDefinition())
// Get the NetworkSource, FeatureClass, AssetGroup, and AssetTypes for all of the features we want to create
// The existence of these values has already been confirmed in the ValidateDataModel() routine
// TransformerBank
using (NetworkSource transformerBankNetworkSource = GetNetworkSource(utilityNetworkDefinition, AssemblyNetworkSourceName))
using (FeatureClass transformerBankFeatureClass = utilityNetwork.GetTable(transformerBankNetworkSource) as FeatureClass)
using (AssetGroup transformerBankAssetGroup = transformerBankNetworkSource.GetAssetGroup(TransformerBankAssetGroupName))
using (AssetType transformerBankAssetType = transformerBankAssetGroup.GetAssetType(TransformerBankAssetTypeName))
// Transformer
using (NetworkSource deviceNetworkSource = GetNetworkSource(utilityNetworkDefinition, DeviceNetworkSourceName))
using (FeatureClass deviceFeatureClass = utilityNetwork.GetTable(deviceNetworkSource) as FeatureClass)
using (AssetGroup transformerAssetGroup = deviceNetworkSource.GetAssetGroup(TransformerAssetGroupName))
using (AssetType transformerAssetType = transformerAssetGroup.GetAssetType(TransformerAssetTypeName))
// Arrester
using (AssetGroup arresterAssetGroup = deviceNetworkSource.GetAssetGroup(ArresterAssetGroupName))
using (AssetType arresterAssetType = arresterAssetGroup.GetAssetType(ArresterAssetTypeName))
// Fuse
using (AssetGroup fuseAssetGroup = deviceNetworkSource.GetAssetGroup(FuseAssetGroupName))
using (AssetType fuseAssetType = fuseAssetGroup.GetAssetType(FuseAssetTypeName))
{
MapPoint clickPoint = geometry as MapPoint;
// Create a transformer bank
RowToken token = createOperation.CreateEx(transformerBankFeatureClass, CreateAttributes(transformerBankAssetGroup, transformerBankAssetType, clickPoint));
RowHandle transformerBankHandle = new RowHandle(token);
// Create three transformers, one for each phase
MapPoint transformerPointA = CreateOffsetMapPoint(clickPoint, -1 * XOffset, YOffset);
token = createOperation.CreateEx(deviceFeatureClass, CreateDeviceAttributes(transformerAssetGroup, transformerAssetType, transformerPointA, APhase));
RowHandle transformerHandleA = new RowHandle(token);
MapPoint transformerPointB = CreateOffsetMapPoint(clickPoint, 0, YOffset);
token = createOperation.CreateEx(deviceFeatureClass, CreateDeviceAttributes(transformerAssetGroup, transformerAssetType, transformerPointB, BPhase));
RowHandle transformerHandleB = new RowHandle(token);
MapPoint transformerPointC = CreateOffsetMapPoint(clickPoint, XOffset, YOffset);
token = createOperation.CreateEx(deviceFeatureClass, CreateDeviceAttributes(transformerAssetGroup, transformerAssetType, transformerPointC, CPhase));
RowHandle transformerHandleC = new RowHandle(token);
// Create containment associations between the bank and the transformers
AssociationDescription containmentAssociationDescription = new AssociationDescription(AssociationType.Containment, transformerBankHandle, transformerHandleA, false);
createOperation.Create(containmentAssociationDescription);
containmentAssociationDescription = new AssociationDescription(AssociationType.Containment, transformerBankHandle, transformerHandleB, false);
createOperation.Create(containmentAssociationDescription);
containmentAssociationDescription = new AssociationDescription(AssociationType.Containment, transformerBankHandle, transformerHandleC, false);
createOperation.Create(containmentAssociationDescription);
// Find the high-side terminal for transformers
TerminalConfiguration transformerTerminalConfiguration = transformerAssetType.GetTerminalConfiguration();
IReadOnlyList<Terminal> terminals = transformerTerminalConfiguration.Terminals;
Terminal highSideTerminal = terminals.First(x => x.IsUpstreamTerminal == true);
long highSideTerminalID = highSideTerminal.ID;
// Create three fuses, one for each phase
MapPoint fusePointA = CreateOffsetMapPoint(clickPoint, -1 * XOffset, 2 * YOffset);
token = createOperation.CreateEx(deviceFeatureClass, CreateDeviceAttributes(fuseAssetGroup, fuseAssetType, fusePointA, APhase));
RowHandle fuseHandleA = new RowHandle(token);
MapPoint fusePointB = CreateOffsetMapPoint(clickPoint, 0, 2 * YOffset);
token = createOperation.CreateEx(deviceFeatureClass, CreateDeviceAttributes(fuseAssetGroup, fuseAssetType, fusePointB, BPhase));
RowHandle fuseHandleB = new RowHandle(token);
MapPoint fusePointC = CreateOffsetMapPoint(clickPoint, XOffset, 2 * YOffset);
token = createOperation.CreateEx(deviceFeatureClass, CreateDeviceAttributes(fuseAssetGroup, fuseAssetType, fusePointC, CPhase));
RowHandle fuseHandleC = new RowHandle(token);
// Create containment associations between the bank and the fuses
containmentAssociationDescription = new AssociationDescription(AssociationType.Containment, transformerBankHandle, fuseHandleA, false);
createOperation.Create(containmentAssociationDescription);
containmentAssociationDescription = new AssociationDescription(AssociationType.Containment, transformerBankHandle, fuseHandleB, false);
createOperation.Create(containmentAssociationDescription);
containmentAssociationDescription = new AssociationDescription(AssociationType.Containment, transformerBankHandle, fuseHandleC, false);
createOperation.Create(containmentAssociationDescription);
// Connect the high-side transformer terminals to the fuses (connect the A-phase transformer to the A-phase fuse, and so on)
AssociationDescription connectivityAssociationDescription = new AssociationDescription(AssociationType.JunctionJunctionConnectivity, transformerHandleA, highSideTerminalID, fuseHandleA);
createOperation.Create(connectivityAssociationDescription);
connectivityAssociationDescription = new AssociationDescription(AssociationType.JunctionJunctionConnectivity, transformerHandleB, highSideTerminalID, fuseHandleB);
createOperation.Create(connectivityAssociationDescription);
connectivityAssociationDescription = new AssociationDescription(AssociationType.JunctionJunctionConnectivity, transformerHandleC, highSideTerminalID, fuseHandleC);
createOperation.Create(connectivityAssociationDescription);
// Create three arresters, one for each phase
MapPoint arresterPointA = CreateOffsetMapPoint(clickPoint, -1 * XOffset, 3 * YOffset);
token = createOperation.CreateEx(deviceFeatureClass, CreateDeviceAttributes(arresterAssetGroup, arresterAssetType, arresterPointA, APhase));
RowHandle arresterHandleA = new RowHandle(token);
MapPoint arresterPointB = CreateOffsetMapPoint(clickPoint, 0, 3 * YOffset);
token = createOperation.CreateEx(deviceFeatureClass, CreateDeviceAttributes(arresterAssetGroup, arresterAssetType, arresterPointB, BPhase));
RowHandle arresterHandleB = new RowHandle(token);
MapPoint arresterPointC = CreateOffsetMapPoint(clickPoint, XOffset, 3 * YOffset);
token = createOperation.CreateEx(deviceFeatureClass, CreateDeviceAttributes(arresterAssetGroup, arresterAssetType, arresterPointC, CPhase));
RowHandle arresterHandleC = new RowHandle(token);
// Create containment associations between the bank and the arresters
containmentAssociationDescription = new AssociationDescription(AssociationType.Containment, transformerBankHandle, arresterHandleA, false);
createOperation.Create(containmentAssociationDescription);
containmentAssociationDescription = new AssociationDescription(AssociationType.Containment, transformerBankHandle, arresterHandleB, false);
createOperation.Create(containmentAssociationDescription);
containmentAssociationDescription = new AssociationDescription(AssociationType.Containment, transformerBankHandle, arresterHandleC, false);
createOperation.Create(containmentAssociationDescription);
// Create connectivity associations between the fuses and the arresters (connect the A-phase fuse the A-phase arrester, and so on)
connectivityAssociationDescription = new AssociationDescription(AssociationType.JunctionJunctionConnectivity, fuseHandleA, arresterHandleA);
createOperation.Create(connectivityAssociationDescription);
connectivityAssociationDescription = new AssociationDescription(AssociationType.JunctionJunctionConnectivity, fuseHandleB, arresterHandleB);
createOperation.Create(connectivityAssociationDescription);
connectivityAssociationDescription = new AssociationDescription(AssociationType.JunctionJunctionConnectivity, fuseHandleC, arresterHandleC);
createOperation.Create(connectivityAssociationDescription);
// Execute the edit operation, which creates all of the rows and associations
success = createOperation.Execute();
if (!success)
{
errorMessage = createOperation.ErrorMessage;
}
}
}
}
}
});
if (!success)
{
MessageBox.Show(errorMessage, "Create Transformer Bank Tool");
}
return success;
}
// Get the Utility Network from the currently active layer
private UtilityNetwork GetUtilityNetwork()
{
UtilityNetwork utilityNetwork = null;
if (MapView.Active != null)
{
MapViewEventArgs mapViewEventArgs = new MapViewEventArgs(MapView.Active);
IReadOnlyList<Layer> selectedLayers = mapViewEventArgs.MapView.GetSelectedLayers();
if (selectedLayers.Count > 0)
{
utilityNetwork = UtilityNetworkUtils.GetUtilityNetworkFromLayer(selectedLayers[0]);
}
}
return utilityNetwork;
}
// Get the current map
private Map GetMap()
{
if (MapView.Active == null) return null;
return MapView.Active.Map;
}
// CreateOffsetMapPoint - creates a new MapPoint offset from a given base point.
private MapPoint CreateOffsetMapPoint(MapPoint basePoint, double xOffset, double yOffset)
{
using (MapPointBuilder mapPointBuilder = new MapPointBuilder())
{
mapPointBuilder.X = basePoint.X + xOffset;
mapPointBuilder.Y = basePoint.Y + yOffset;
mapPointBuilder.Z = basePoint.Z;
mapPointBuilder.HasZ = true;
return mapPointBuilder.ToGeometry();
}
}
// CreateAttributes - creates a dictionary of attribute-value pairs
private Dictionary<string, object> CreateAttributes(AssetGroup assetGroup, AssetType assetType, MapPoint mapPoint)
{
var attributes = new Dictionary<string, object>();
attributes.Add("SHAPE", mapPoint);
attributes.Add("ASSETGROUP", assetGroup.Code);
attributes.Add("ASSETTYPE", assetType.Code);
return attributes;
}
private Dictionary<string, object> CreateDeviceAttributes(AssetGroup assetGroup, AssetType assetType, MapPoint mapPoint, int phase)
{
var attributes = CreateAttributes(assetGroup, assetType, mapPoint);
attributes.Add(DeviceStatusFieldName, DeviceStatusClosed);
attributes.Add(PhaseFieldName, phase);
return attributes;
}
// ValidateDataModel - This sample is hard-wired to a particular version of the Naperville data model.
// This routine checks to make sure we are using the correct one
private bool ValidateDataModel(UtilityNetwork utilityNetwork)
{
bool dataModelIsValid = false;
try
{
using (UtilityNetworkDefinition utilityNetworkDefinition = utilityNetwork.GetDefinition())
using (NetworkSource transformerBankNetworkSource = GetNetworkSource(utilityNetworkDefinition, AssemblyNetworkSourceName))
using (AssetGroup transformerBankAssetGroup = transformerBankNetworkSource.GetAssetGroup(TransformerBankAssetGroupName))
using (AssetType transformerBankAssetType = transformerBankAssetGroup.GetAssetType(TransformerBankAssetTypeName))
// Transformer
using (NetworkSource deviceNetworkSource = GetNetworkSource(utilityNetworkDefinition, DeviceNetworkSourceName))
using (AssetGroup transformerAssetGroup = deviceNetworkSource.GetAssetGroup(TransformerAssetGroupName))
using (AssetType transformerAssetType = transformerAssetGroup.GetAssetType(TransformerAssetTypeName))
// Arrester
using (AssetGroup arresterAssetGroup = deviceNetworkSource.GetAssetGroup(ArresterAssetGroupName))
using (AssetType arresterAssetType = arresterAssetGroup.GetAssetType(ArresterAssetTypeName))
// Fuse
using (AssetGroup fuseAssetGroup = deviceNetworkSource.GetAssetGroup(FuseAssetGroupName))
using (AssetType fuseAssetType = fuseAssetGroup.GetAssetType(FuseAssetTypeName))
{
// Find the upstream terminal on the transformer
TerminalConfiguration terminalConfiguration = transformerAssetType.GetTerminalConfiguration();
Terminal upstreamTerminal = null;
foreach(Terminal terminal in terminalConfiguration.Terminals)
{
if (terminal.IsUpstreamTerminal)
{
upstreamTerminal = terminal;
break;
}
}
// Find the terminal on the fuse
Terminal fuseTerminal = fuseAssetType.GetTerminalConfiguration().Terminals[0];
// Find the terminal on the arrester
Terminal arresterTerminal = arresterAssetType.GetTerminalConfiguration().Terminals[0];
// All of our asset groups and asset types exist. Now we have to check for rules.
IReadOnlyList<Rule> rules = utilityNetworkDefinition.GetRules();
if (ContainmentRuleExists(rules, transformerBankAssetType, transformerAssetType) &&
ContainmentRuleExists(rules, transformerBankAssetType, fuseAssetType) &&
ContainmentRuleExists(rules, transformerBankAssetType, arresterAssetType) &&
ConnectivityRuleExists(rules, transformerAssetType, upstreamTerminal, fuseAssetType, fuseTerminal) &&
ConnectivityRuleExists(rules, fuseAssetType, fuseTerminal, arresterAssetType, arresterTerminal))
{
dataModelIsValid = true;
}
}
}
catch { }
return dataModelIsValid;
}
private bool ContainmentRuleExists(IReadOnlyList<Rule> rules, AssetType sourceAssetType, AssetType destinationAssetType)
{
foreach(Rule rule in rules)
{
if (RuleType.Containment == rule.Type)
{
// For containment rules, the first rule element represents the container and the second rule element
// represents the content
// Note that AssetType objects must be compared by using their Handles.
if (rule.RuleElements[0].AssetType.Handle == sourceAssetType.Handle &&
rule.RuleElements[1].AssetType.Handle == destinationAssetType.Handle)
{
return true;
}
}
}
return false;
}
private bool ConnectivityRuleExists(IReadOnlyList<Rule> rules, AssetType sourceAssetType, Terminal sourceTerminal, AssetType destinationAssetType, Terminal destinationTerminal)
{
foreach (Rule rule in rules)
{
if (RuleType.JunctionJunctionConnectivity == rule.Type)
{
// Connectivity rules can exist in either direction, so you have to look for both possibilities
RuleElement ruleElement1 = rule.RuleElements[0];
RuleElement ruleElement2 = rule.RuleElements[1];
// Note that AssetType objects must be compared by using their Handles.
if ((ruleElement1.AssetType.Handle == sourceAssetType.Handle && ruleElement1.Terminal == sourceTerminal && ruleElement2.AssetType.Handle == destinationAssetType.Handle && ruleElement2.Terminal == destinationTerminal)
||
(ruleElement1.AssetType.Handle == destinationAssetType.Handle && ruleElement1.Terminal == destinationTerminal && ruleElement2.AssetType.Handle == sourceAssetType.Handle && ruleElement2.Terminal == sourceTerminal))
{
return true;
}
}
}
return false;
}
private NetworkSource GetNetworkSource(UtilityNetworkDefinition utilityNetworkDefinition, string networkSourceName)
{
string networkSourceNameWithoutSpaces = networkSourceName.Replace(" ", "");
IReadOnlyList<NetworkSource> networkSources = utilityNetworkDefinition.GetNetworkSources();
foreach (NetworkSource networkSource in networkSources)
{
if (networkSource.Name.Replace(" ", "") == networkSourceNameWithoutSpaces) return networkSource;
}
return null; // Not found
}
}
}
| |
// 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 System.Runtime.InteropServices;
using Xunit;
namespace System.Reflection.Tests
{
public class ParameterInfoTests
{
public static IEnumerable<object[]> Parameters_TestData()
{
yield return new object[] { typeof(ParameterInfoMetadata), "Method1", new string[] { "str", "iValue", "lValue" }, new Type[] { typeof(string), typeof(int), typeof(long) } };
yield return new object[] { typeof(ParameterInfoMetadata), "Method2", new string[0], new Type[0] };
yield return new object[] { typeof(ParameterInfoMetadata), "MethodWithArray", new string[] { "strArray" }, new Type[] { typeof(string[]) } };
yield return new object[] { typeof(ParameterInfoMetadata), "VirtualMethod", new string[] { "data" }, new Type[] { typeof(long) } };
yield return new object[] { typeof(ParameterInfoMetadata), "MethodWithRefParameter", new string[] { "str" }, new Type[] { typeof(string).MakeByRefType() } };
yield return new object[] { typeof(ParameterInfoMetadata), "MethodWithOutParameter", new string[] { "i", "str" }, new Type[] { typeof(int), typeof(string).MakeByRefType() } };
yield return new object[] { typeof(GenericClass<string>), "GenericMethod", new string[] { "t" }, new Type[] { typeof(string) } };
}
[Theory]
[MemberData(nameof(Parameters_TestData))]
public void Name(Type type, string methodName, string[] expectedNames, Type[] expectedTypes)
{
MethodInfo methodInfo = GetMethod(type, methodName);
ParameterInfo[] parameters = methodInfo.GetParameters();
Assert.Equal(expectedNames.Length, parameters.Length);
for (int i = 0; i < expectedNames.Length; i++)
{
Assert.Equal(expectedNames[i], parameters[i].Name);
Assert.Equal(expectedTypes[i], parameters[i].ParameterType);
Assert.Equal(i, parameters[i].Position);
Assert.Equal(methodInfo, parameters[i].Member);
}
}
[Theory]
[InlineData(typeof(ParameterInfoMetadata), "Method1", 0)]
[InlineData(typeof(ParameterInfoMetadata), "VirtualMethod", 0)]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithRefParameter", 0)]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithOutParameter", 0)]
[InlineData(typeof(GenericClass<string>), "GenericMethod", 0)]
public void Member(Type type, string name, int index)
{
ParameterInfo parameterInfo = GetParameterInfo(type, name, index);
Assert.NotNull(parameterInfo.Member);
}
[Theory]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithDefault1", 1, true)]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithDefault2", 0, true)]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithDefault3", 0, true)]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithDefault4", 0, true)]
[InlineData(typeof(GenericClass<int>), "GenericMethodWithDefault", 1, true)]
[InlineData(typeof(ParameterInfoMetadata), "Method1", 1, false)]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithRefParameter", 0, false)]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithOutParameter", 1, false)]
[InlineData(typeof(GenericClass<int>), "GenericMethod", 0, false)]
public void HasDefaultValue(Type type, string name, int index, bool expected)
{
ParameterInfo parameterInfo = GetParameterInfo(type, name, index);
Assert.Equal(expected, parameterInfo.HasDefaultValue);
}
[Fact]
public void HasDefaultValue_ReturnParam()
{
ParameterInfo parameterInfo = GetMethod(typeof(ParameterInfoMetadata), "Method1").ReturnParameter;
Assert.True(parameterInfo.HasDefaultValue);
}
[Theory]
[InlineData(typeof(ParameterInfoMetadata), "Method1", 0)]
[InlineData(typeof(ParameterInfoMetadata), "VirtualMethod", 0)]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithRefParameter", 0)]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithOutParameter", 0)]
[InlineData(typeof(GenericClass<string>), "GenericMethod", 0)]
public void RawDefaultValue(Type type, string name, int index)
{
ParameterInfo parameterInfo = GetParameterInfo(type, name, index);
Assert.NotNull(parameterInfo.RawDefaultValue);
}
[Theory]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithRefParameter", 0, false)]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithOutParameter", 1, true)]
[InlineData(typeof(ParameterInfoMetadata), "Method1", 1, false)]
public void IsOut(Type type, string name, int index, bool expected)
{
ParameterInfo parameterInfo = GetParameterInfo(type, name, index);
Assert.Equal(expected, parameterInfo.IsOut);
}
[Theory]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithOutParameter", 1, false)]
public void IsIn(Type type, string name, int index, bool expected)
{
ParameterInfo parameterInfo = GetParameterInfo(type, name, index);
Assert.Equal(expected, parameterInfo.IsIn);
}
[Theory]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithDefault1", 1, 0)]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithDefault2", 0, "abc")]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithDefault3", 0, false)]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithDefault4", 0, '\0')]
public void DefaultValue(Type type, string name, int index, object expected)
{
ParameterInfo parameterInfo = GetParameterInfo(type, name, index);
Assert.Equal(expected, parameterInfo.DefaultValue);
}
[Fact]
public void DefaultValue_NoDefaultValue()
{
ParameterInfo parameterInfo = GetParameterInfo(typeof(ParameterInfoMetadata), "MethodWithOptionalAndNoDefault", 0);
Assert.Equal(Missing.Value, parameterInfo.DefaultValue);
}
[Theory]
[InlineData(typeof(ParameterInfoMetadata), "Method1", 1, false)]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithOutParameter", 1, false)]
public void IsOptional(Type type, string name, int index, bool expected)
{
ParameterInfo parameterInfo = GetParameterInfo(type, name, index);
Assert.Equal(expected, parameterInfo.IsOptional);
}
[Theory]
[InlineData(typeof(ParameterInfoMetadata), "Method1", 1, false)]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithDefault2", 0, false)]
public void IsRetval(Type type, string name, int index, bool expected)
{
ParameterInfo parameterInfo = GetParameterInfo(type, name, index);
Assert.Equal(expected, parameterInfo.IsRetval);
}
[Theory]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithOptionalDefaultOutInMarshalParam", 0,
ParameterAttributes.Optional | ParameterAttributes.HasDefault | ParameterAttributes.HasFieldMarshal | ParameterAttributes.Out | ParameterAttributes.In)]
public void Attributes(Type type, string name, int index, ParameterAttributes expected)
{
ParameterInfo parameterInfo = GetParameterInfo(type, name, index);
Assert.Equal(expected, parameterInfo.Attributes);
}
[Theory]
[InlineData(typeof(OptionalAttribute))]
[InlineData(typeof(MarshalAsAttribute))]
[InlineData(typeof(OutAttribute))]
[InlineData(typeof(InAttribute))]
public void CustomAttributesTest(Type attrType)
{
ParameterInfo parameterInfo = GetParameterInfo(typeof(ParameterInfoMetadata), "MethodWithOptionalDefaultOutInMarshalParam", 0);
CustomAttributeData attribute = parameterInfo.CustomAttributes.SingleOrDefault(a => a.AttributeType.Equals(attrType));
Assert.NotNull(attribute);
Assert.NotNull(attribute);
ICustomAttributeProvider prov = parameterInfo as ICustomAttributeProvider;
Assert.NotNull(prov.GetCustomAttributes(attrType, false).SingleOrDefault());
Assert.NotNull(prov.GetCustomAttributes(attrType, true).SingleOrDefault());
Assert.NotNull(prov.GetCustomAttributes(false).SingleOrDefault(a => a.GetType().Equals(attrType)));
Assert.NotNull(prov.GetCustomAttributes(true).SingleOrDefault(a => a.GetType().Equals(attrType)));
Assert.True(prov.IsDefined(attrType, false));
Assert.True(prov.IsDefined(attrType, true));
}
[Theory]
[InlineData(typeof(ParameterInfoMetadata), "Method1", 0, new Type[0])]
[InlineData(typeof(ParameterInfoMetadata), "VirtualMethod", 0, new Type[0])]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithRefParameter", 0, new Type[0])]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithOutParameter", 0, new Type[0])]
[InlineData(typeof(GenericClass<string>), "GenericMethod", 0, new Type[0])]
public void GetOptionalCustomModifiers(Type type, string name, int index, Type[] expected)
{
ParameterInfo parameterInfo = GetParameterInfo(type, name, index);
Assert.Equal(expected, parameterInfo.GetOptionalCustomModifiers());
}
[Theory]
[InlineData(typeof(ParameterInfoMetadata), "Method1", 0, new Type[0])]
[InlineData(typeof(ParameterInfoMetadata), "VirtualMethod", 0, new Type[0])]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithRefParameter", 0, new Type[0])]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithOutParameter", 0, new Type[0])]
[InlineData(typeof(GenericClass<string>), "GenericMethod", 0, new Type[0])]
public void GetRequiredCustomModifiers(Type type, string name, int index, Type[] expected)
{
ParameterInfo parameterInfo = GetParameterInfo(type, name, index);
Assert.Equal(expected, parameterInfo.GetRequiredCustomModifiers());
}
private static ParameterInfo GetParameterInfo(Type type, string name, int index)
{
ParameterInfo[] parameters = GetMethod(type, name).GetParameters();
return parameters[index];
}
private static MethodInfo GetMethod(Type type, string name)
{
return type.GetTypeInfo().DeclaredMethods.FirstOrDefault(methodInfo => methodInfo.Name.Equals(name));
}
// Metadata for reflection
public class ParameterInfoMetadata
{
public void Method1(string str, int iValue, long lValue) { }
public void Method2() { }
public void MethodWithArray(string[] strArray) { }
public virtual void VirtualMethod(long data) { }
public void MethodWithRefParameter(ref string str) { str = "newstring"; }
public void MethodWithOutParameter(int i, out string str) { str = "newstring"; }
public int MethodWithDefault1(long lValue, int iValue = 0) { return 1; }
public int MethodWithDefault2(string str = "abc") { return 1; }
public int MethodWithDefault3(bool result = false) { return 1; }
public int MethodWithDefault4(char c = '\0') { return 1; }
public int MethodWithOptionalAndNoDefault([Optional] object o) { return 1; }
public int MethodWithOptionalDefaultOutInMarshalParam([MarshalAs(UnmanagedType.LPWStr)][Out][In] string str = "") { return 1; }
}
public class GenericClass<T>
{
public void GenericMethod(T t) { }
public string GenericMethodWithDefault(int i, T t = default(T)) { return "somestring"; }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using Task = System.Threading.Tasks.Task;
namespace Microsoft.DotNet.Build.CloudTestTasks
{
public class UploadClient
{
private TaskLoggingHelper log;
public UploadClient(TaskLoggingHelper loggingHelper)
{
log = loggingHelper;
}
public string EncodeBlockIds(int numberOfBlocks, int lengthOfId)
{
string numberOfBlocksString = numberOfBlocks.ToString("D" + lengthOfId);
if (Encoding.UTF8.GetByteCount(numberOfBlocksString) <= 64)
{
byte[] bytes = Encoding.UTF8.GetBytes(numberOfBlocksString);
return Convert.ToBase64String(bytes);
}
else
{
throw new Exception("Task failed - Could not encode block id.");
}
}
public async Task UploadBlockBlobAsync(
CancellationToken ct,
string AccountName,
string AccountKey,
string ContainerName,
string filePath,
string destinationBlob)
{
string resourceUrl = AzureHelper.GetContainerRestUrl(AccountName, ContainerName);
string fileName = destinationBlob;
fileName = fileName.Replace("\\", "/");
string blobUploadUrl = resourceUrl + "/" + fileName;
int size = (int)new FileInfo(filePath).Length;
int blockSize = 4 * 1024 * 1024; //4MB max size of a block blob
int bytesLeft = size;
List<string> blockIds = new List<string>();
int numberOfBlocks = (size / blockSize) + 1;
int countForId = 0;
using (FileStream fileStreamTofilePath = new FileStream(filePath, FileMode.Open))
{
int offset = 0;
while (bytesLeft > 0)
{
int nextBytesToRead = (bytesLeft < blockSize) ? bytesLeft : blockSize;
byte[] fileBytes = new byte[blockSize];
int read = fileStreamTofilePath.Read(fileBytes, 0, nextBytesToRead);
if (nextBytesToRead != read)
{
throw new Exception(string.Format(
"Number of bytes read ({0}) from file {1} isn't equal to the number of bytes expected ({2}) .",
read, fileName, nextBytesToRead));
}
string blockId = EncodeBlockIds(countForId, numberOfBlocks.ToString().Length);
blockIds.Add(blockId);
string blockUploadUrl = blobUploadUrl + "?comp=block&blockid=" + WebUtility.UrlEncode(blockId);
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Clear();
Func<HttpRequestMessage> createRequest = () =>
{
DateTime dt = DateTime.UtcNow;
var req = new HttpRequestMessage(HttpMethod.Put, blockUploadUrl);
req.Headers.Add(
AzureHelper.DateHeaderString,
dt.ToString("R", CultureInfo.InvariantCulture));
req.Headers.Add(AzureHelper.VersionHeaderString, AzureHelper.StorageApiVersion);
req.Headers.Add(
AzureHelper.AuthorizationHeaderString,
AzureHelper.AuthorizationHeader(
AccountName,
AccountKey,
"PUT",
dt,
req,
string.Empty,
string.Empty,
nextBytesToRead.ToString(),
string.Empty));
Stream postStream = new MemoryStream();
postStream.Write(fileBytes, 0, nextBytesToRead);
postStream.Seek(0, SeekOrigin.Begin);
req.Content = new StreamContent(postStream);
return req;
};
log.LogMessage(MessageImportance.Low, "Sending request to upload part {0} of file {1}", countForId, fileName);
using (HttpResponseMessage response = await AzureHelper.RequestWithRetry(log, client, createRequest))
{
log.LogMessage(
MessageImportance.Low,
"Received response to upload part {0} of file {1}: Status Code:{2} Status Desc: {3}",
countForId,
fileName,
response.StatusCode,
await response.Content.ReadAsStringAsync());
}
}
offset += read;
bytesLeft -= nextBytesToRead;
countForId += 1;
}
}
string blockListUploadUrl = blobUploadUrl + "?comp=blocklist";
using (HttpClient client = new HttpClient())
{
Func<HttpRequestMessage> createRequest = () =>
{
DateTime dt1 = DateTime.UtcNow;
var req = new HttpRequestMessage(HttpMethod.Put, blockListUploadUrl);
req.Headers.Add(AzureHelper.DateHeaderString, dt1.ToString("R", CultureInfo.InvariantCulture));
req.Headers.Add(AzureHelper.VersionHeaderString, AzureHelper.StorageApiVersion);
string contentType = DetermineContentTypeBasedOnFileExtension(filePath);
if (!string.IsNullOrEmpty(contentType))
{
req.Headers.Add(AzureHelper.ContentTypeString, contentType);
}
string cacheControl = DetermineCacheControlBasedOnFileExtension(filePath);
if (!string.IsNullOrEmpty(cacheControl))
{
req.Headers.Add(AzureHelper.CacheControlString, cacheControl);
}
var body = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?><BlockList>");
foreach (object item in blockIds)
body.AppendFormat("<Latest>{0}</Latest>", item);
body.Append("</BlockList>");
byte[] bodyData = Encoding.UTF8.GetBytes(body.ToString());
req.Headers.Add(
AzureHelper.AuthorizationHeaderString,
AzureHelper.AuthorizationHeader(
AccountName,
AccountKey,
"PUT",
dt1,
req,
string.Empty,
string.Empty,
bodyData.Length.ToString(),
string.Empty));
Stream postStream = new MemoryStream();
postStream.Write(bodyData, 0, bodyData.Length);
postStream.Seek(0, SeekOrigin.Begin);
req.Content = new StreamContent(postStream);
return req;
};
using (HttpResponseMessage response = await AzureHelper.RequestWithRetry(log, client, createRequest))
{
log.LogMessage(
MessageImportance.Low,
"Received response to combine block list for file {0}: Status Code:{1} Status Desc: {2}",
fileName,
response.StatusCode,
await response.Content.ReadAsStringAsync());
}
}
}
private string DetermineContentTypeBasedOnFileExtension(string filename)
{
if(Path.GetExtension(filename) == ".svg")
{
return "image/svg+xml";
}
else if(Path.GetExtension(filename) == ".version")
{
return "text/plain";
}
return string.Empty;
}
private string DetermineCacheControlBasedOnFileExtension(string filename)
{
if(Path.GetExtension(filename) == ".svg")
{
return "No-Cache";
}
return string.Empty;
}
}
}
| |
/**
* LookupService.cs
*
* Copyright (C) 2008 MaxMind Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
using System;
using System.IO;
using System.Net;
using System.Reflection;
using System.Runtime.CompilerServices;
public class LookupService{
private Stream file = null;
private DatabaseInfo databaseInfo = null;
byte databaseType = Convert.ToByte(DatabaseInfo.COUNTRY_EDITION);
int[] databaseSegments;
int recordLength;
int dboptions;
byte[] dbbuffer;
String licenseKey;
int dnsService = 0;
private static Country UNKNOWN_COUNTRY = new Country("--", "N/A");
private static int COUNTRY_BEGIN = 16776960;
private static int STATE_BEGIN = 16700000;
private static int STRUCTURE_INFO_MAX_SIZE = 20;
private static int DATABASE_INFO_MAX_SIZE = 100;
private static int FULL_RECORD_LENGTH = 100;//???
private static int SEGMENT_RECORD_LENGTH = 3;
private static int STANDARD_RECORD_LENGTH = 3;
private static int ORG_RECORD_LENGTH = 4;
private static int MAX_RECORD_LENGTH = 4;
private static int MAX_ORG_RECORD_LENGTH = 1000;//???
private static int FIPS_RANGE = 360;
private static int STATE_BEGIN_REV0 = 16700000;
private static int STATE_BEGIN_REV1 = 16000000;
private static int US_OFFSET = 1;
private static int CANADA_OFFSET = 677;
private static int WORLD_OFFSET = 1353;
public static int GEOIP_STANDARD = 0;
public static int GEOIP_MEMORY_CACHE = 1;
public static int GEOIP_UNKNOWN_SPEED = 0;
public static int GEOIP_DIALUP_SPEED = 1;
public static int GEOIP_CABLEDSL_SPEED = 2;
public static int GEOIP_CORPORATE_SPEED = 3;
private static String[] countryCode = {
"--","AP","EU","AD","AE","AF","AG","AI","AL","AM","AN","AO","AQ","AR",
"AS","AT","AU","AW","AZ","BA","BB","BD","BE","BF","BG","BH","BI","BJ",
"BM","BN","BO","BR","BS","BT","BV","BW","BY","BZ","CA","CC","CD","CF",
"CG","CH","CI","CK","CL","CM","CN","CO","CR","CU","CV","CX","CY","CZ",
"DE","DJ","DK","DM","DO","DZ","EC","EE","EG","EH","ER","ES","ET","FI",
"FJ","FK","FM","FO","FR","FX","GA","GB","GD","GE","GF","GH","GI","GL",
"GM","GN","GP","GQ","GR","GS","GT","GU","GW","GY","HK","HM","HN","HR",
"HT","HU","ID","IE","IL","IN","IO","IQ","IR","IS","IT","JM","JO","JP",
"KE","KG","KH","KI","KM","KN","KP","KR","KW","KY","KZ","LA","LB","LC",
"LI","LK","LR","LS","LT","LU","LV","LY","MA","MC","MD","MG","MH","MK",
"ML","MM","MN","MO","MP","MQ","MR","MS","MT","MU","MV","MW","MX","MY",
"MZ","NA","NC","NE","NF","NG","NI","NL","NO","NP","NR","NU","NZ","OM",
"PA","PE","PF","PG","PH","PK","PL","PM","PN","PR","PS","PT","PW","PY",
"QA","RE","RO","RU","RW","SA","SB","SC","SD","SE","SG","SH","SI","SJ",
"SK","SL","SM","SN","SO","SR","ST","SV","SY","SZ","TC","TD","TF","TG",
"TH","TJ","TK","TM","TN","TO","TL","TR","TT","TV","TW","TZ","UA","UG",
"UM","US","UY","UZ","VA","VC","VE","VG","VI","VN","VU","WF","WS","YE",
"YT","RS","ZA","ZM","ME","ZW","A1","A2","O1","AX","GG","IM","JE","BL",
"MF"};
private static String[] countryName = {
"N/A","Asia/Pacific Region","Europe","Andorra","United Arab Emirates",
"Afghanistan","Antigua and Barbuda","Anguilla","Albania","Armenia",
"Netherlands Antilles","Angola","Antarctica","Argentina","American Samoa",
"Austria","Australia","Aruba","Azerbaijan","Bosnia and Herzegovina",
"Barbados","Bangladesh","Belgium","Burkina Faso","Bulgaria","Bahrain",
"Burundi","Benin","Bermuda","Brunei Darussalam","Bolivia","Brazil","Bahamas",
"Bhutan","Bouvet Island","Botswana","Belarus","Belize","Canada",
"Cocos (Keeling) Islands","Congo, The Democratic Republic of the",
"Central African Republic","Congo","Switzerland","Cote D'Ivoire",
"Cook Islands","Chile","Cameroon","China","Colombia","Costa Rica","Cuba",
"Cape Verde","Christmas Island","Cyprus","Czech Republic","Germany",
"Djibouti","Denmark","Dominica","Dominican Republic","Algeria","Ecuador",
"Estonia","Egypt","Western Sahara","Eritrea","Spain","Ethiopia","Finland",
"Fiji","Falkland Islands (Malvinas)","Micronesia, Federated States of",
"Faroe Islands","France","France, Metropolitan","Gabon","United Kingdom",
"Grenada","Georgia","French Guiana","Ghana","Gibraltar","Greenland","Gambia",
"Guinea","Guadeloupe","Equatorial Guinea","Greece",
"South Georgia and the South Sandwich Islands","Guatemala","Guam",
"Guinea-Bissau","Guyana","Hong Kong","Heard Island and McDonald Islands",
"Honduras","Croatia","Haiti","Hungary","Indonesia","Ireland","Israel","India",
"British Indian Ocean Territory","Iraq","Iran, Islamic Republic of",
"Iceland","Italy","Jamaica","Jordan","Japan","Kenya","Kyrgyzstan","Cambodia",
"Kiribati","Comoros","Saint Kitts and Nevis",
"Korea, Democratic People's Republic of","Korea, Republic of","Kuwait",
"Cayman Islands","Kazakhstan","Lao People's Democratic Republic","Lebanon",
"Saint Lucia","Liechtenstein","Sri Lanka","Liberia","Lesotho","Lithuania",
"Luxembourg","Latvia","Libyan Arab Jamahiriya","Morocco","Monaco",
"Moldova, Republic of","Madagascar","Marshall Islands",
"Macedonia, the Former Yugoslav Republic of","Mali","Myanmar","Mongolia",
"Macau","Northern Mariana Islands","Martinique","Mauritania","Montserrat",
"Malta","Mauritius","Maldives","Malawi","Mexico","Malaysia","Mozambique",
"Namibia","New Caledonia","Niger","Norfolk Island","Nigeria","Nicaragua",
"Netherlands","Norway","Nepal","Nauru","Niue","New Zealand","Oman","Panama",
"Peru","French Polynesia","Papua New Guinea","Philippines","Pakistan",
"Poland","Saint Pierre and Miquelon","Pitcairn","Puerto Rico","" +
"Palestinian Territory, Occupied","Portugal","Palau","Paraguay","Qatar",
"Reunion","Romania","Russian Federation","Rwanda","Saudi Arabia",
"Solomon Islands","Seychelles","Sudan","Sweden","Singapore","Saint Helena",
"Slovenia","Svalbard and Jan Mayen","Slovakia","Sierra Leone","San Marino",
"Senegal","Somalia","Suriname","Sao Tome and Principe","El Salvador",
"Syrian Arab Republic","Swaziland","Turks and Caicos Islands","Chad",
"French Southern Territories","Togo","Thailand","Tajikistan","Tokelau",
"Turkmenistan","Tunisia","Tonga","Timor-Leste","Turkey","Trinidad and Tobago",
"Tuvalu","Taiwan","Tanzania, United Republic of","Ukraine","Uganda",
"United States Minor Outlying Islands","United States","Uruguay","Uzbekistan",
"Holy See (Vatican City State)","Saint Vincent and the Grenadines",
"Venezuela","Virgin Islands, British","Virgin Islands, U.S.","Vietnam",
"Vanuatu","Wallis and Futuna","Samoa","Yemen","Mayotte","Serbia",
"South Africa","Zambia","Montenegro","Zimbabwe","Anonymous Proxy",
"Satellite Provider","Other",
"Aland Islands","Guernsey","Isle of Man","Jersey","Saint Barthelemy",
"Saint Martin"};
public LookupService(int options)
{
var assembly = Assembly.GetExecutingAssembly();
this.file = assembly.GetManifestResourceStream("ApiGeoIP.GeoLiteCity.dat");
dboptions = options;
init();
}
public LookupService(String databaseFile, int options){
try {
this.file = new FileStream(databaseFile, FileMode.Open, FileAccess.Read);
dboptions = options;
init();
} catch(System.SystemException) {
Console.Write("cannot open file " + databaseFile + "\n");
}
}
public LookupService(String databaseFile):this(databaseFile, GEOIP_STANDARD){
}
private void init(){
int i, j;
byte [] delim = new byte[3];
byte [] buf = new byte[SEGMENT_RECORD_LENGTH];
databaseType = (byte)DatabaseInfo.COUNTRY_EDITION;
recordLength = STANDARD_RECORD_LENGTH;
//file.Seek(file.Length() - 3,SeekOrigin.Begin);
file.Seek(-3,SeekOrigin.End);
for (i = 0; i < STRUCTURE_INFO_MAX_SIZE; i++) {
file.Read(delim,0,3);
if (delim[0] == 255 && delim[1] == 255 && delim[2] == 255){
databaseType = Convert.ToByte(file.ReadByte());
if (databaseType >= 106) {
// Backward compatibility with databases from April 2003 and earlier
databaseType -= 105;
}
// Determine the database type.
if (databaseType == DatabaseInfo.REGION_EDITION_REV0) {
databaseSegments = new int[1];
databaseSegments[0] = STATE_BEGIN_REV0;
recordLength = STANDARD_RECORD_LENGTH;
} else if (databaseType == DatabaseInfo.REGION_EDITION_REV1) {
databaseSegments = new int[1];
databaseSegments[0] = STATE_BEGIN_REV1;
recordLength = STANDARD_RECORD_LENGTH;
} else if (databaseType == DatabaseInfo.CITY_EDITION_REV0 ||
databaseType == DatabaseInfo.CITY_EDITION_REV1 ||
databaseType == DatabaseInfo.ORG_EDITION ||
databaseType == DatabaseInfo.ISP_EDITION ||
databaseType == DatabaseInfo.ASNUM_EDITION)
{
databaseSegments = new int[1];
databaseSegments[0] = 0;
if (databaseType == DatabaseInfo.CITY_EDITION_REV0 ||
databaseType == DatabaseInfo.CITY_EDITION_REV1) {
recordLength = STANDARD_RECORD_LENGTH;
}
else {
recordLength = ORG_RECORD_LENGTH;
}
file.Read(buf,0,SEGMENT_RECORD_LENGTH);
for (j = 0; j < SEGMENT_RECORD_LENGTH; j++) {
databaseSegments[0] += (unsignedByteToInt(buf[j]) << (j * 8));
}
}
break;
}
else {
//file.Seek(file.getFilePointer() - 4);
file.Seek(-4,SeekOrigin.Current);
//file.Seek(file.position-4,SeekOrigin.Begin);
}
}
if ((databaseType == DatabaseInfo.COUNTRY_EDITION) |
(databaseType == DatabaseInfo.PROXY_EDITION) |
(databaseType == DatabaseInfo.NETSPEED_EDITION)) {
databaseSegments = new int[1];
databaseSegments[0] = COUNTRY_BEGIN;
recordLength = STANDARD_RECORD_LENGTH;
}
if ((dboptions & GEOIP_MEMORY_CACHE) == 1) {
int l = (int) file.Length;
dbbuffer = new byte[l];
file.Seek(0,SeekOrigin.Begin);
file.Read(dbbuffer,0,l);
}
}
public void close(){
try {
file.Close();
file = null;
}
catch (Exception) { }
}
public Country getCountry(IPAddress ipAddress) {
return getCountry(bytestoLong(ipAddress.GetAddressBytes()));
}
public Country getCountry(String ipAddress){
IPAddress addr;
try {
addr = IPAddress.Parse(ipAddress);
}
//catch (UnknownHostException e) {
catch (Exception e) {
Console.Write(e.Message);
return UNKNOWN_COUNTRY;
}
// return getCountry(bytestoLong(addr.GetAddressBytes()));
return getCountry(bytestoLong(addr.GetAddressBytes()));
}
public Country getCountry(long ipAddress){
if (file == null) {
//throw new IllegalStateException("Database has been closed.");
throw new Exception("Database has been closed.");
}
if ((databaseType == DatabaseInfo.CITY_EDITION_REV1) |
(databaseType == DatabaseInfo.CITY_EDITION_REV0)) {
Location l = getLocation(ipAddress);
if (l == null) {
return UNKNOWN_COUNTRY;
}
else {
return new Country(l.countryCode, l.countryName);
}
}
else {
int ret = SeekCountry(ipAddress) - COUNTRY_BEGIN;
if (ret == 0) {
return UNKNOWN_COUNTRY;
}
else {
return new Country(countryCode[ret], countryName[ret]);
}
}
}
public int getID(String ipAddress){
IPAddress addr;
try {
addr = IPAddress.Parse(ipAddress);
}
catch (Exception e) {
Console.Write(e.Message);
return 0;
}
return getID(bytestoLong(addr.GetAddressBytes()));
}
public int getID(IPAddress ipAddress) {
return getID(bytestoLong(ipAddress.GetAddressBytes()));
}
public int getID(long ipAddress){
if (file == null) {
throw new Exception("Database has been closed.");
}
int ret = SeekCountry(ipAddress) - databaseSegments[0];
return ret;
}
public DatabaseInfo getDatabaseInfo(){
if (databaseInfo != null) {
return databaseInfo;
}
try {
// Synchronize since we're accessing the database file.
lock (this) {
bool hasStructureInfo = false;
byte [] delim = new byte[3];
// Advance to part of file where database info is stored.
file.Seek(-3,SeekOrigin.End);
for (int i=0; i<STRUCTURE_INFO_MAX_SIZE; i++) {
file.Read(delim,0,3);
if (delim[0] == 255 && delim[1] == 255 && delim[2] == 255) {
hasStructureInfo = true;
break;
}
}
if (hasStructureInfo) {
file.Seek(-3,SeekOrigin.Current);
}
else {
// No structure info, must be pre Sep 2002 database, go back to end.
file.Seek(-3,SeekOrigin.End);
}
// Find the database info string.
for (int i=0; i<DATABASE_INFO_MAX_SIZE; i++) {
file.Read(delim,0,3);
if (delim[0]==0 && delim[1]==0 && delim[2]==0) {
byte[] dbInfo = new byte[i];
char[] dbInfo2 = new char[i];
file.Read(dbInfo,0,i);
for (int a0 = 0;a0 < i;a0++){
dbInfo2[a0] = Convert.ToChar(dbInfo[a0]);
}
// Create the database info object using the string.
this.databaseInfo = new DatabaseInfo(new String(dbInfo2));
return databaseInfo;
}
file.Seek(-4,SeekOrigin.Current);
}
}
}
catch (Exception e) {
Console.Write(e.Message);
//e.printStackTrace();
}
return new DatabaseInfo("");
}
public Region getRegion(IPAddress ipAddress) {
return getRegion(bytestoLong(ipAddress.GetAddressBytes()));
}
public Region getRegion(String str){
IPAddress addr;
try {
addr = IPAddress.Parse(str);
}
catch (Exception e) {
Console.Write(e.Message);
return null;
}
return getRegion(bytestoLong(addr.GetAddressBytes()));
}
[MethodImpl(MethodImplOptions.Synchronized)]
public Region getRegion(long ipnum){
Region record = new Region();
int seek_region = 0;
if (databaseType == DatabaseInfo.REGION_EDITION_REV0) {
seek_region = SeekCountry(ipnum) - STATE_BEGIN_REV0;
char [] ch = new char[2];
if (seek_region >= 1000){
record.countryCode = "US";
record.countryName = "United States";
ch[0] = (char)(((seek_region - 1000)/26) + 65);
ch[1] = (char)(((seek_region - 1000)%26) + 65);
record.region = new String(ch);
} else {
record.countryCode = countryCode[seek_region];
record.countryName = countryName[seek_region];
record.region = "";
}
} else if (databaseType == DatabaseInfo.REGION_EDITION_REV1) {
seek_region = SeekCountry(ipnum) - STATE_BEGIN_REV1;
char [] ch = new char[2];
if (seek_region < US_OFFSET) {
record.countryCode = "";
record.countryName = "";
record.region = "";
} else if (seek_region < CANADA_OFFSET) {
record.countryCode = "US";
record.countryName = "United States";
ch[0] = (char)(((seek_region - US_OFFSET)/26) + 65);
ch[1] = (char)(((seek_region - US_OFFSET)%26) + 65);
record.region = new String(ch);
} else if (seek_region < WORLD_OFFSET) {
record.countryCode = "CA";
record.countryName = "Canada";
ch[0] = (char)(((seek_region - CANADA_OFFSET)/26) + 65);
ch[1] = (char)(((seek_region - CANADA_OFFSET)%26) + 65);
record.region = new String(ch);
} else {
record.countryCode = countryCode[(seek_region - WORLD_OFFSET) / FIPS_RANGE];
record.countryName = countryName[(seek_region - WORLD_OFFSET) / FIPS_RANGE];
record.region = "";
}
}
return record;
}
public Location getLocation(IPAddress addr){
return getLocation(bytestoLong(addr.GetAddressBytes()));
}
public Location getLocation(String str){
IPAddress addr;
try {
addr = IPAddress.Parse(str);
}
catch (Exception e) {
Console.Write(e.Message);
return null;
}
return getLocation(bytestoLong(addr.GetAddressBytes()));
}
[MethodImpl(MethodImplOptions.Synchronized)]
public Location getLocation(long ipnum){
int record_pointer;
byte[] record_buf = new byte[FULL_RECORD_LENGTH];
char[] record_buf2 = new char[FULL_RECORD_LENGTH];
int record_buf_offset = 0;
Location record = new Location();
int str_length = 0;
int j, Seek_country;
double latitude = 0, longitude = 0;
try {
Seek_country = SeekCountry(ipnum);
if (Seek_country == databaseSegments[0]) {
return null;
}
record_pointer = Seek_country + ((2 * recordLength - 1) * databaseSegments[0]);
if ((dboptions & GEOIP_MEMORY_CACHE) == 1){
Array.Copy(dbbuffer, record_pointer, record_buf, 0, Math.Min(dbbuffer.Length - record_pointer, FULL_RECORD_LENGTH));
} else {
file.Seek(record_pointer,SeekOrigin.Begin);
file.Read(record_buf,0,FULL_RECORD_LENGTH);
}
for (int a0 = 0;a0 < FULL_RECORD_LENGTH;a0++){
record_buf2[a0] = Convert.ToChar(record_buf[a0]);
}
// get country
record.countryCode = countryCode[unsignedByteToInt(record_buf[0])];
record.countryName = countryName[unsignedByteToInt(record_buf[0])];
record_buf_offset++;
// get region
while (record_buf[record_buf_offset + str_length] != '\0')
str_length++;
if (str_length > 0) {
record.region = new String(record_buf2, record_buf_offset, str_length);
}
record_buf_offset += str_length + 1;
str_length = 0;
// get region_name
record.regionName = RegionName.getRegionName( record.countryCode, record.region );
// get city
while (record_buf[record_buf_offset + str_length] != '\0')
str_length++;
if (str_length > 0) {
record.city = new String(record_buf2, record_buf_offset, str_length);
}
record_buf_offset += (str_length + 1);
str_length = 0;
// get postal code
while (record_buf[record_buf_offset + str_length] != '\0')
str_length++;
if (str_length > 0) {
record.postalCode = new String(record_buf2, record_buf_offset, str_length);
}
record_buf_offset += (str_length + 1);
// get latitude
for (j = 0; j < 3; j++)
latitude += (unsignedByteToInt(record_buf[record_buf_offset + j]) << (j * 8));
record.latitude = (float) latitude/10000 - 180;
record_buf_offset += 3;
// get longitude
for (j = 0; j < 3; j++)
longitude += (unsignedByteToInt(record_buf[record_buf_offset + j]) << (j * 8));
record.longitude = (float) longitude/10000 - 180;
record.metro_code = record.dma_code = 0;
record.area_code = 0;
if (databaseType == DatabaseInfo.CITY_EDITION_REV1) {
// get metro_code
int metroarea_combo = 0;
if (record.countryCode == "US"){
record_buf_offset += 3;
for (j = 0; j < 3; j++)
metroarea_combo += (unsignedByteToInt(record_buf[record_buf_offset + j]) << (j * 8));
record.metro_code = record.dma_code = metroarea_combo/1000;
record.area_code = metroarea_combo % 1000;
}
}
}
catch (IOException) {
Console.Write("IO Exception while seting up segments");
}
return record;
}
public String getOrg(IPAddress addr) {
return getOrg(bytestoLong(addr.GetAddressBytes()));
}
public String getOrg(String str){
IPAddress addr;
try {
addr = IPAddress.Parse(str);
}
//catch (UnknownHostException e) {
catch (Exception e){
Console.Write(e.Message);
return null;
}
return getOrg(bytestoLong(addr.GetAddressBytes()));
}
[MethodImpl(MethodImplOptions.Synchronized)]
public String getOrg(long ipnum){
int Seek_org;
int record_pointer;
int str_length = 0;
byte [] buf = new byte[MAX_ORG_RECORD_LENGTH];
char [] buf2 = new char[MAX_ORG_RECORD_LENGTH];
String org_buf;
try {
Seek_org = SeekCountry(ipnum);
if (Seek_org == databaseSegments[0]) {
return null;
}
record_pointer = Seek_org + (2 * recordLength - 1) * databaseSegments[0];
if ((dboptions & GEOIP_MEMORY_CACHE) == 1) {
Array.Copy(dbbuffer, record_pointer, buf, 0, Math.Min(dbbuffer.Length - record_pointer, MAX_ORG_RECORD_LENGTH));
} else {
file.Seek(record_pointer,SeekOrigin.Begin);
file.Read(buf,0,MAX_ORG_RECORD_LENGTH);
}
while (buf[str_length] != 0) {
buf2[str_length] = Convert.ToChar(buf[str_length]);
str_length++;
}
buf2[str_length] = '\0';
org_buf = new String(buf2,0,str_length);
return org_buf;
}
catch (IOException) {
Console.Write("IO Exception");
return null;
}
}
[MethodImpl(MethodImplOptions.Synchronized)]
private int SeekCountry(long ipAddress){
byte [] buf = new byte[2 * MAX_RECORD_LENGTH];
int [] x = new int[2];
int offset = 0;
for (int depth = 31; depth >= 0; depth--) {
try {
if ((dboptions & GEOIP_MEMORY_CACHE) == 1) {
for (int i = 0;i < (2 * MAX_RECORD_LENGTH);i++) {
buf[i] = dbbuffer[i+(2 * recordLength * offset)];
}
} else {
file.Seek(2 * recordLength * offset,SeekOrigin.Begin);
file.Read(buf,0,2 * MAX_RECORD_LENGTH);
}
}
catch (IOException) {
Console.Write("IO Exception");
}
for (int i = 0; i<2; i++) {
x[i] = 0;
for (int j = 0; j<recordLength; j++) {
int y = buf[(i*recordLength)+j];
if (y < 0) {
y+= 256;
}
x[i] += (y << (j * 8));
}
}
if ((ipAddress & (1 << depth)) > 0) {
if (x[1] >= databaseSegments[0]) {
return x[1];
}
offset = x[1];
}
else {
if (x[0] >= databaseSegments[0]) {
return x[0];
}
offset = x[0];
}
}
// shouldn't reach here
Console.Write("Error Seeking country while Seeking " + ipAddress);
return 0;
}
private static long swapbytes(long ipAddress){
return (((ipAddress>>0) & 255) << 24) | (((ipAddress>>8) & 255) << 16)
| (((ipAddress>>16) & 255) << 8) | (((ipAddress>>24) & 255) << 0);
}
private static long bytestoLong(byte [] address){
long ipnum = 0;
for (int i = 0; i < 4; ++i) {
long y = address[i];
if (y < 0) {
y+= 256;
}
ipnum += y << ((3-i)*8);
}
return ipnum;
}
private static int unsignedByteToInt(byte b) {
return (int) b & 0xFF;
}
}
| |
// dnlib: See LICENSE.txt for more info
using System;
using System.Collections.Generic;
using dnlib.Utils;
using dnlib.IO;
using dnlib.PE;
namespace dnlib.W32Resources {
/// <summary>
/// A Win32 resource directory (see IMAGE_RESOURCE_DIRECTORY in the Windows SDK)
/// </summary>
public abstract class ResourceDirectory : ResourceDirectoryEntry {
/// <summary>See <see cref="Characteristics"/></summary>
protected uint characteristics;
/// <summary>See <see cref="TimeDateStamp"/></summary>
protected uint timeDateStamp;
/// <summary>See <see cref="MajorVersion"/></summary>
protected ushort majorVersion;
/// <summary>See <see cref="MinorVersion"/></summary>
protected ushort minorVersion;
/// <summary>See <see cref="Directories"/></summary>
private protected LazyList<ResourceDirectory> directories;
/// <summary>See <see cref="Data"/></summary>
private protected LazyList<ResourceData> data;
/// <summary>
/// Gets/sets the characteristics
/// </summary>
public uint Characteristics {
get => characteristics;
set => characteristics = value;
}
/// <summary>
/// Gets/sets the time date stamp
/// </summary>
public uint TimeDateStamp {
get => timeDateStamp;
set => timeDateStamp = value;
}
/// <summary>
/// Gets/sets the major version number
/// </summary>
public ushort MajorVersion {
get => majorVersion;
set => majorVersion = value;
}
/// <summary>
/// Gets/sets the minor version number
/// </summary>
public ushort MinorVersion {
get => minorVersion;
set => minorVersion = value;
}
/// <summary>
/// Gets all directory entries
/// </summary>
public IList<ResourceDirectory> Directories => directories;
/// <summary>
/// Gets all resource data
/// </summary>
public IList<ResourceData> Data => data;
/// <summary>
/// Constructor
/// </summary>
/// <param name="name">Name</param>
protected ResourceDirectory(ResourceName name)
: base(name) {
}
/// <summary>
/// Finds a <see cref="ResourceDirectory"/> by name
/// </summary>
/// <param name="name">Name</param>
/// <returns>A <see cref="ResourceDirectory"/> or <c>null</c> if it wasn't found</returns>
public ResourceDirectory FindDirectory(ResourceName name) {
foreach (var dir in directories) {
if (dir.Name == name)
return dir;
}
return null;
}
/// <summary>
/// Finds a <see cref="ResourceData"/> by name
/// </summary>
/// <param name="name">Name</param>
/// <returns>A <see cref="ResourceData"/> or <c>null</c> if it wasn't found</returns>
public ResourceData FindData(ResourceName name) {
foreach (var d in data) {
if (d.Name == name)
return d;
}
return null;
}
}
/// <summary>
/// A Win32 resource directory created by the user
/// </summary>
public class ResourceDirectoryUser : ResourceDirectory {
/// <summary>
/// Constructor
/// </summary>
/// <param name="name">Name</param>
public ResourceDirectoryUser(ResourceName name)
: base(name) {
directories = new LazyList<ResourceDirectory>();
data = new LazyList<ResourceData>();
}
}
/// <summary>
/// A Win32 resource directory created from a PE file
/// </summary>
public sealed class ResourceDirectoryPE : ResourceDirectory {
/// <summary>
/// To make sure we don't get stuck in an infinite loop, don't allow more than this
/// many sub directories.
/// </summary>
const uint MAX_DIR_DEPTH = 10;
/// <summary>Owner</summary>
readonly Win32ResourcesPE resources;
/// <summary>Directory depth. When creating more <see cref="ResourceDirectoryPE"/>'s,
/// the instances get this value + 1</summary>
uint depth;
/// <summary>
/// Info about all <see cref="ResourceData"/>'s we haven't created yet
/// </summary>
List<EntryInfo> dataInfos;
/// <summary>
/// Info about all <see cref="ResourceDirectory"/>'s we haven't created yet
/// </summary>
List<EntryInfo> dirInfos;
readonly struct EntryInfo {
public readonly ResourceName name;
/// <summary>Offset of resource directory / data</summary>
public readonly uint offset;
public EntryInfo(ResourceName name, uint offset) {
this.name = name;
this.offset = offset;
}
public override string ToString() => $"{offset:X8} {name}";
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="depth">Starts from 0. If it's big enough, we'll stop reading more data.</param>
/// <param name="name">Name</param>
/// <param name="resources">Resources</param>
/// <param name="reader">Reader positioned at the start of this resource directory</param>
public ResourceDirectoryPE(uint depth, ResourceName name, Win32ResourcesPE resources, ref DataReader reader)
: base(name) {
this.resources = resources;
this.depth = depth;
Initialize(ref reader);
}
/// <summary>
/// Reads the directory header and initializes <see cref="ResourceDirectory.directories"/> and
/// <see cref="ResourceDirectory.data"/>.
/// </summary>
/// <param name="reader"></param>
void Initialize(ref DataReader reader) {
if (depth > MAX_DIR_DEPTH || !reader.CanRead(16U)) {
InitializeDefault();
return;
}
characteristics = reader.ReadUInt32();
timeDateStamp = reader.ReadUInt32();
majorVersion = reader.ReadUInt16();
minorVersion = reader.ReadUInt16();
ushort numNamed = reader.ReadUInt16();
ushort numIds = reader.ReadUInt16();
int total = numNamed + numIds;
if (!reader.CanRead((uint)total * 8)) {
InitializeDefault();
return;
}
dataInfos = new List<EntryInfo>();
dirInfos = new List<EntryInfo>();
uint offset = reader.Position;
for (int i = 0; i < total; i++, offset += 8) {
reader.Position = offset;
uint nameOrId = reader.ReadUInt32();
uint dataOrDirectory = reader.ReadUInt32();
ResourceName name;
if ((nameOrId & 0x80000000) != 0)
name = new ResourceName(ReadString(ref reader, nameOrId & 0x7FFFFFFF) ?? string.Empty);
else
name = new ResourceName((int)nameOrId);
if ((dataOrDirectory & 0x80000000) == 0)
dataInfos.Add(new EntryInfo(name, dataOrDirectory));
else
dirInfos.Add(new EntryInfo(name, dataOrDirectory & 0x7FFFFFFF));
}
directories = new LazyList<ResourceDirectory, object>(dirInfos.Count, null, (ctx, i) => ReadResourceDirectory(i));
data = new LazyList<ResourceData, object>(dataInfos.Count, null, (ctx, i) => ReadResourceData(i));
}
/// <summary>
/// Reads a string
/// </summary>
/// <param name="reader">Reader</param>
/// <param name="offset">Offset of string</param>
/// <returns>The string or <c>null</c> if we could not read it</returns>
static string ReadString(ref DataReader reader, uint offset) {
reader.Position = offset;
if (!reader.CanRead(2U))
return null;
int size = reader.ReadUInt16();
int sizeInBytes = size * 2;
if (!reader.CanRead((uint)sizeInBytes))
return null;
try {
return reader.ReadUtf16String(sizeInBytes / 2);
}
catch {
return null;
}
}
ResourceDirectory ReadResourceDirectory(int i) {
var info = dirInfos[i];
var reader = resources.GetResourceReader();
reader.Position = Math.Min(reader.Length, info.offset);
return new ResourceDirectoryPE(depth + 1, info.name, resources, ref reader);
}
ResourceData ReadResourceData(int i) {
var info = dataInfos[i];
var reader = resources.GetResourceReader();
reader.Position = Math.Min(reader.Length, info.offset);
ResourceData data;
if (reader.CanRead(16U)) {
var rva = (RVA)reader.ReadUInt32();
uint size = reader.ReadUInt32();
uint codePage = reader.ReadUInt32();
uint reserved = reader.ReadUInt32();
resources.GetDataReaderInfo(rva, size, out var dataReaderFactory, out uint dataOffset, out uint dataLength);
data = new ResourceData(info.name, dataReaderFactory, dataOffset, dataLength, codePage, reserved);
}
else
data = new ResourceData(info.name);
return data;
}
void InitializeDefault() {
directories = new LazyList<ResourceDirectory>();
data = new LazyList<ResourceData>();
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Test.Utilities;
using Xunit;
namespace Microsoft.NetFramework.Analyzers.UnitTests
{
public partial class DoNotUseInsecureDtdProcessingAnalyzerTests : DiagnosticAnalyzerTestBase
{
private DiagnosticResult GetCA3075LoadCSharpResultAt(int line, int column)
{
return GetCSharpResultAt(line, column, CA3075RuleId, string.Format(_CA3075LoadXmlMessage, "Load"));
}
private DiagnosticResult GetCA3075LoadBasicResultAt(int line, int column)
{
return GetBasicResultAt(line, column, CA3075RuleId, string.Format(_CA3075LoadXmlMessage, "Load"));
}
[Fact]
public void UseXmlDocumentLoadShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
public class TestClass
{
public void TestMethod(string path)
{
var doc = new XmlDocument();
doc.XmlResolver = null;
doc.Load(path);
}
}
}
",
GetCA3075LoadCSharpResultAt(12, 13)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Public Class TestClass
Public Sub TestMethod(path As String)
Dim doc = New XmlDocument()
doc.XmlResolver = Nothing
doc.Load(path)
End Sub
End Class
End Namespace",
GetCA3075LoadBasicResultAt(9, 13)
);
}
[Fact]
public void UseXmlDocumentLoadInGetShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
class TestClass
{
public XmlDocument Test
{
get {
var xml = """";
var doc = new XmlDocument();
doc.XmlResolver = null;
doc.Load(xml);
return doc;
}
}
}",
GetCA3075LoadCSharpResultAt(12, 13)
);
VerifyBasic(@"
Imports System.Xml
Class TestClass
Public ReadOnly Property Test() As XmlDocument
Get
Dim xml = """"
Dim doc = New XmlDocument()
doc.XmlResolver = Nothing
doc.Load(xml)
Return doc
End Get
End Property
End Class",
GetCA3075LoadBasicResultAt(10, 13)
);
}
[Fact]
public void UseXmlDocumentLoadInSetShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
class TestClass
{
XmlDocument privateDoc;
public XmlDocument GetDoc
{
set
{
if (value == null)
{
var xml = """";
var doc = new XmlDocument();
doc.XmlResolver = null;
doc.Load(xml);
privateDoc = doc;
}
else
privateDoc = value;
}
}
}",
GetCA3075LoadCSharpResultAt(16, 17)
);
VerifyBasic(@"
Imports System.Xml
Class TestClass
Private privateDoc As XmlDocument
Public WriteOnly Property GetDoc() As XmlDocument
Set
If value Is Nothing Then
Dim xml = """"
Dim doc = New XmlDocument()
doc.XmlResolver = Nothing
doc.Load(xml)
privateDoc = doc
Else
privateDoc = value
End If
End Set
End Property
End Class",
GetCA3075LoadBasicResultAt(12, 17)
);
}
[Fact]
public void UseXmlDocumentLoadInTryBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System;
using System.Xml;
class TestClass
{
private void TestMethod()
{
try
{
var xml = """";
var doc = new XmlDocument();
doc.XmlResolver = null;
doc.Load(xml);
}
catch (Exception) { throw; }
finally { }
}
}",
GetCA3075LoadCSharpResultAt(14, 17)
);
VerifyBasic(@"
Imports System
Imports System.Xml
Class TestClass
Private Sub TestMethod()
Try
Dim xml = """"
Dim doc = New XmlDocument()
doc.XmlResolver = Nothing
doc.Load(xml)
Catch generatedExceptionName As Exception
Throw
Finally
End Try
End Sub
End Class",
GetCA3075LoadBasicResultAt(11, 13)
);
}
[Fact]
public void UseXmlDocumentLoadInCatchBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System;
using System.Xml;
class TestClass
{
private void TestMethod()
{
try { }
catch (Exception)
{
var xml = """";
var doc = new XmlDocument();
doc.XmlResolver = null;
doc.Load(xml);
}
finally { }
}
}",
GetCA3075LoadCSharpResultAt(15, 17)
);
VerifyBasic(@"
Imports System
Imports System.Xml
Class TestClass
Private Sub TestMethod()
Try
Catch generatedExceptionName As Exception
Dim xml = """"
Dim doc = New XmlDocument()
doc.XmlResolver = Nothing
doc.Load(xml)
Finally
End Try
End Sub
End Class",
GetCA3075LoadBasicResultAt(12, 13)
);
}
[Fact]
public void UseXmlDocumentLoadInFinallyBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System;
using System.Xml;
class TestClass
{
private void TestMethod()
{
try { }
catch (Exception) { throw; }
finally
{
var xml = """";
var doc = new XmlDocument();
doc.XmlResolver = null;
doc.Load(xml);
}
}
}",
GetCA3075LoadCSharpResultAt(16, 13)
);
VerifyBasic(@"
Imports System
Imports System.Xml
Class TestClass
Private Sub TestMethod()
Try
Catch generatedExceptionName As Exception
Throw
Finally
Dim xml = """"
Dim doc = New XmlDocument()
doc.XmlResolver = Nothing
doc.Load(xml)
End Try
End Sub
End Class",
GetCA3075LoadBasicResultAt(14, 13)
);
}
[Fact]
public void UseXmlDocumentLoadInAsyncAwaitShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Threading.Tasks;
using System.Xml;
class TestClass
{
private async Task TestMethod()
{
await Task.Run(() => {
var xml = """";
var doc = new XmlDocument();
doc.XmlResolver = null;
doc.Load(xml);
});
}
private async void TestMethod2()
{
await TestMethod();
}
}",
GetCA3075LoadCSharpResultAt(13, 13)
);
VerifyBasic(@"
Imports System.Threading.Tasks
Imports System.Xml
Class TestClass
Private Async Function TestMethod() As Task
Await Task.Run(Function()
Dim xml = """"
Dim doc = New XmlDocument()
doc.XmlResolver = Nothing
doc.Load(xml)
End Function)
End Function
Private Async Sub TestMethod2()
Await TestMethod()
End Sub
End Class",
GetCA3075LoadBasicResultAt(11, 17)
);
}
[Fact]
public void UseXmlDocumentLoadInDelegateShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
class TestClass
{
delegate void Del();
Del d = delegate () {
var xml = """";
var doc = new XmlDocument();
doc.XmlResolver = null;
doc.Load(xml);
};
}",
GetCA3075LoadCSharpResultAt(12, 9)
);
VerifyBasic(@"
Imports System.Xml
Class TestClass
Private Delegate Sub Del()
Private d As Del = Sub()
Dim xml = """"
Dim doc = New XmlDocument()
doc.XmlResolver = Nothing
doc.Load(xml)
End Sub
End Class",
GetCA3075LoadBasicResultAt(11, 5)
);
}
[Fact]
public void UseXmlDataDocumentLoadShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
public class TestClass
{
public void TestMethod(string path)
{
new XmlDataDocument().Load(path);
}
}
}
",
GetCA3075LoadCSharpResultAt(10, 13)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Public Class TestClass
Public Sub TestMethod(path As String)
Call New XmlDataDocument().Load(path)
End Sub
End Class
End Namespace",
GetCA3075LoadBasicResultAt(7, 18)
);
}
[Fact]
public void UseXmlDataDocumentLoadInGetShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
class TestClass
{
public XmlDataDocument Test
{
get
{
var xml = """";
XmlDataDocument doc = new XmlDataDocument() { XmlResolver = null };
doc.Load(xml);
return doc;
}
}
}",
GetCA3075LoadCSharpResultAt(12, 13)
);
VerifyBasic(@"
Imports System.Xml
Class TestClass
Public ReadOnly Property Test() As XmlDataDocument
Get
Dim xml = """"
Dim doc As New XmlDataDocument() With { _
.XmlResolver = Nothing _
}
doc.Load(xml)
Return doc
End Get
End Property
End Class",
GetCA3075LoadBasicResultAt(11, 13)
);
}
[Fact]
public void UseXmlDataDocumentLoadInTryBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System;
using System.Xml;
class TestClass
{
private void TestMethod()
{
try
{
var xml = """";
XmlDataDocument doc = new XmlDataDocument() { XmlResolver = null };
doc.Load(xml);
}
catch (Exception) { throw; }
finally { }
}
}",
GetCA3075LoadCSharpResultAt(13, 17)
);
VerifyBasic(@"
Imports System
Imports System.Xml
Class TestClass
Private Sub TestMethod()
Try
Dim xml = """"
Dim doc As New XmlDataDocument() With { _
.XmlResolver = Nothing _
}
doc.Load(xml)
Catch generatedExceptionName As Exception
Throw
Finally
End Try
End Sub
End Class",
GetCA3075LoadBasicResultAt(12, 13)
);
}
[Fact]
public void UseXmlDataDocumentLoadInCatchBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System;
using System.Xml;
class TestClass
{
private void TestMethod()
{
try { }
catch (Exception)
{
var xml = """";
XmlDataDocument doc = new XmlDataDocument() { XmlResolver = null };
doc.Load(xml);
}
finally { }
}
}",
GetCA3075LoadCSharpResultAt(14, 17)
);
VerifyBasic(@"
Imports System
Imports System.Xml
Class TestClass
Private Sub TestMethod()
Try
Catch generatedExceptionName As Exception
Dim xml = """"
Dim doc As New XmlDataDocument() With { _
.XmlResolver = Nothing _
}
doc.Load(xml)
Finally
End Try
End Sub
End Class",
GetCA3075LoadBasicResultAt(13, 13)
);
}
[Fact]
public void UseXmlDataDocumentLoadInFinallyBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System;
using System.Xml;
class TestClass
{
private void TestMethod()
{
try { }
catch (Exception) { throw; }
finally
{
var xml = """";
XmlDataDocument doc = new XmlDataDocument() { XmlResolver = null };
doc.Load(xml);
}
}
}",
GetCA3075LoadCSharpResultAt(15, 17)
);
VerifyBasic(@"
Imports System
Imports System.Xml
Class TestClass
Private Sub TestMethod()
Try
Catch generatedExceptionName As Exception
Throw
Finally
Dim xml = """"
Dim doc As New XmlDataDocument() With { _
.XmlResolver = Nothing _
}
doc.Load(xml)
End Try
End Sub
End Class",
GetCA3075LoadBasicResultAt(15, 13)
);
}
[Fact]
public void UseXmlDataDocumentLoadInAsyncAwaitShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Threading.Tasks;
using System.Xml;
class TestClass
{
private async Task TestMethod()
{
await Task.Run(() => {
var xml = """";
XmlDataDocument doc = new XmlDataDocument() { XmlResolver = null };
doc.Load(xml);
});
}
private async void TestMethod2()
{
await TestMethod();
}
}",
GetCA3075LoadCSharpResultAt(12, 17)
);
VerifyBasic(@"
Imports System.Threading.Tasks
Imports System.Xml
Class TestClass
Private Async Function TestMethod() As Task
Await Task.Run(Function()
Dim xml = """"
Dim doc As New XmlDataDocument() With { _
.XmlResolver = Nothing _
}
doc.Load(xml)
End Function)
End Function
Private Async Sub TestMethod2()
Await TestMethod()
End Sub
End Class",
GetCA3075LoadBasicResultAt(12, 9)
);
}
[Fact]
public void UseXmlDataDocumentLoadInDelegateShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
class TestClass
{
delegate void Del();
Del d = delegate () {
var xml = """";
XmlDataDocument doc = new XmlDataDocument() { XmlResolver = null };
doc.Load(xml);
};
}",
GetCA3075LoadCSharpResultAt(11, 9)
);
VerifyBasic(@"
Imports System.Xml
Class TestClass
Private Delegate Sub Del()
Private d As Del = Sub()
Dim xml = """"
Dim doc As New XmlDataDocument() With { _
.XmlResolver = Nothing _
}
doc.Load(xml)
End Sub
End Class",
GetCA3075LoadBasicResultAt(12, 5)
);
}
[Fact]
public void UseXmlDocumentLoadWithXmlReaderParameterShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XmlTextReader reader)
{
new XmlDocument(){ XmlResolver = null }.Load(reader);
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(reader As XmlTextReader)
Call New XmlDocument() With { _
.XmlResolver = Nothing _
}.Load(reader)
End Sub
End Class
End Namespace");
}
[Fact]
public void UseXmlDataDocumentLoadWithXmlReaderParameterShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XmlTextReader reader)
{
var doc = new XmlDataDocument(){XmlResolver = null};
doc.Load(reader);
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(reader As XmlTextReader)
Dim doc = New XmlDataDocument() With { _
.XmlResolver = Nothing _
}
doc.Load(reader)
End Sub
End Class
End Namespace");
}
}
}
| |
// Copyright (c) 2015 Alachisoft
//
// 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;
using System.IO;
using System.Web;
using Alachisoft.NCache.Common;
using Alachisoft.NCache.Config.Dom;
using Alachisoft.NCache.Management;
using Alachisoft.NCache.Runtime.Exceptions;
namespace Alachisoft.NCache.Web
{
internal class DirectoryUtil
{
/// <summary>
/// search for the specified file in the executing assembly's working folder
/// if the file is found, then a path string is returned back. otherwise it returns null.
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public static string GetFileLocalPath(string fileName)
{
string path = Environment.CurrentDirectory + fileName;
if (File.Exists(path))
return path;
return null;
}
/// <summary>
/// search for the specified file in NCache install directory. if the file is found
/// then returns the path string from where the file can be loaded. otherwise it returns
/// null.
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public static string GetFileGlobalPath(string fileName, string directoryName)
{
string directoryPath = string.Empty;
string filePath = string.Empty;
if (!SearchGlobalDirectory(directoryName, false, out directoryPath)) return null;
filePath = Path.Combine(directoryPath, fileName);
if (!File.Exists(filePath))
return null;
return filePath;
}
public static ArrayList GetCacheConfig(string cacheId, bool inproc)
{
string filePath = GetBaseFilePath("config.ncconf");
ArrayList configurationList = null;
if (filePath != null)
{
try
{
configurationList = ThinClientConfigManager.GetCacheConfig(cacheId, filePath, inproc);
}
catch (ManagementException exception)
{
}
}
return configurationList;
}
public static CacheServerConfig GetCacheDom(string cacheId, bool inproc)
{
string filePath = GetBaseFilePath("config.ncconf");
CacheServerConfig dom = null;
if (filePath != null)
{
try
{
dom = ThinClientConfigManager.GetConfigDom(cacheId, filePath, inproc);
}
catch (ManagementException exception)
{
}
}
return dom;
}
public static bool SearchLocalDirectory(string directoryName, bool createNew, out string path)
{
path = new FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).DirectoryName;
if (!Directory.Exists(path))
{
if (createNew)
{
try
{
Directory.CreateDirectory(path);
return true;
}
catch (Exception)
{
throw;
}
}
return false;
}
return true;
}
public static bool SearchGlobalDirectory(string directoryName, bool createNew, out string path)
{
string ncacheInstallDirectory = AppUtil.InstallDir;
path = string.Empty;
if (ncacheInstallDirectory == null)
return false;
path = Path.Combine(ncacheInstallDirectory, directoryName);
if (!Directory.Exists(path))
{
if (createNew)
{
try
{
Directory.CreateDirectory(path);
return true;
}
catch (Exception)
{
throw;
}
}
return false;
}
return true;
}
public static string GetBaseFilePath(string fileName)
{
Search result;
return SearchLocal(fileName,out result);
}
public static string GetBaseFilePath(string fileName, Search search, out Search result)
{
if (search == Search.LocalSearch)
{
return SearchLocal(fileName, out result);
}
else
if (search == Search.LocalConfigSearch)
{
return SearchLocalConfig(fileName, out result);
}
else
{
return SearchGlobal(fileName, out result);
}
}
private static string SearchLocal(string fileName, out Search result)
{
result = Search.LocalSearch;
String path = null;
path = Environment.CurrentDirectory + "\\" + fileName;
if (File.Exists(path))
return path;
return SearchLocalConfig(fileName,out result);
}
private static string SearchLocalConfig(string fileName, out Search result)
{
result = Search.LocalConfigSearch;
String path = null;
bool found = false;
if (HttpContext.Current != null)
{
string approot = HttpContext.Current.Server.MapPath(@"~\");
if (approot != null)
{
path = approot + fileName;
if (!File.Exists(path))
{
path = Path.Combine(approot + @"\", @"bin\config\" + fileName);
if (!File.Exists(path))
{
string configDir = System.Configuration.ConfigurationSettings.AppSettings.Get("NCache.ConfigDir");
if (configDir != null)
{
path = Path.Combine(configDir + @"/", fileName);
path = HttpContext.Current.Server.MapPath(@path);
if (File.Exists(path))
{
found = true;
}
}
}
else
found = true;
}
}
}
if (!found)
{
string roleRootDir = Environment.GetEnvironmentVariable("RoleRoot");
if (roleRootDir != null)
{
path = roleRootDir + "\\approot\\" + fileName;
if (!File.Exists(path))
{
path = roleRootDir + "\\approot\\bin\\config\\" + fileName;
if (File.Exists(path))
{
return path;
}
}
else
return path;
}
}
else
return path;
return SearchGlobal(fileName,out result);
}
private static string SearchGlobal(string fileName, out Search result)
{
result = Search.GlobalSearch;
string directoryPath = string.Empty;
string filePath = string.Empty;
if (SearchGlobalDirectory("config", false, out directoryPath))
{
filePath = Path.Combine(directoryPath, fileName);
if (File.Exists(filePath))
return filePath;
}
return null;
}
}
}
| |
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace UnityEngine.Advertisements.XCodeEditor
{
public class PBXParser
{
public const string PBX_HEADER_TOKEN = "// !$*UTF8*$!\n";
public const char WHITESPACE_SPACE = ' ';
public const char WHITESPACE_TAB = '\t';
public const char WHITESPACE_NEWLINE = '\n';
public const char WHITESPACE_CARRIAGE_RETURN = '\r';
public const char ARRAY_BEGIN_TOKEN = '(';
public const char ARRAY_END_TOKEN = ')';
public const char ARRAY_ITEM_DELIMITER_TOKEN = ',';
public const char DICTIONARY_BEGIN_TOKEN = '{';
public const char DICTIONARY_END_TOKEN = '}';
public const char DICTIONARY_ASSIGN_TOKEN = '=';
public const char DICTIONARY_ITEM_DELIMITER_TOKEN = ';';
public const char QUOTEDSTRING_BEGIN_TOKEN = '"';
public const char QUOTEDSTRING_END_TOKEN = '"';
public const char QUOTEDSTRING_ESCAPE_TOKEN = '\\';
public const char END_OF_FILE = (char)0x1A;
public const string COMMENT_BEGIN_TOKEN = "/*";
public const string COMMENT_END_TOKEN = "*/";
public const string COMMENT_LINE_TOKEN = "//";
private const int BUILDER_CAPACITY = 20000;
private char[] data;
private int index;
private int indent;
public PBXDictionary Decode(string data)
{
if(!data.StartsWith(PBX_HEADER_TOKEN.TrimEnd('\r', '\n'))) {
Debug.Log("Wrong file format.");
return null;
}
data = data.Substring(13);
this.data = data.ToCharArray();
index = 0;
return (PBXDictionary)ParseValue();
}
public string Encode(PBXDictionary pbxData)
{
indent = 0;
StringBuilder builder = new StringBuilder(PBX_HEADER_TOKEN, BUILDER_CAPACITY);
bool success = SerializeValue(pbxData, builder);
return (success ? builder.ToString() : null);
}
#region Move
private char NextToken()
{
SkipWhitespaces();
return StepForeward();
}
private string Peek(int step = 1)
{
string sneak = string.Empty;
for(int i = 1; i <= step; i++) {
if(data.Length - 1 < index + i) {
break;
}
sneak += data[index + i];
}
return sneak;
}
private bool SkipWhitespaces()
{
bool whitespace = false;
while(Regex.IsMatch( StepForeward().ToString(), @"\s" ))
whitespace = true;
StepBackward();
if(SkipComments()) {
whitespace = true;
SkipWhitespaces();
}
return whitespace;
}
private bool SkipComments()
{
string s = string.Empty;
string tag = Peek(2);
switch(tag) {
case COMMENT_BEGIN_TOKEN:
{
while(Peek( 2 ).CompareTo( COMMENT_END_TOKEN ) != 0) {
s += StepForeward();
}
s += StepForeward(2);
break;
}
case COMMENT_LINE_TOKEN:
{
while(!Regex.IsMatch( StepForeward().ToString(), @"\n" ))
continue;
break;
}
default:
return false;
}
return true;
}
private char StepForeward(int step = 1)
{
index = Math.Min(data.Length, index + step);
return data[index];
}
private char StepBackward(int step = 1)
{
index = Math.Max(0, index - step);
return data[index];
}
#endregion
#region Parse
private object ParseValue()
{
switch(NextToken()) {
case END_OF_FILE:
Debug.Log("End of file");
return null;
case DICTIONARY_BEGIN_TOKEN:
return ParseDictionary();
case ARRAY_BEGIN_TOKEN:
return ParseArray();
case QUOTEDSTRING_BEGIN_TOKEN:
return ParseString();
default:
StepBackward();
return ParseEntity();
}
}
private PBXDictionary ParseDictionary()
{
SkipWhitespaces();
PBXDictionary dictionary = new PBXDictionary();
string keyString = string.Empty;
object valueObject = null;
bool complete = false;
while(!complete) {
switch(NextToken()) {
case END_OF_FILE:
Debug.Log("Error: reached end of file inside a dictionary: " + index);
complete = true;
break;
case DICTIONARY_ITEM_DELIMITER_TOKEN:
keyString = string.Empty;
valueObject = null;
break;
case DICTIONARY_END_TOKEN:
keyString = string.Empty;
valueObject = null;
complete = true;
break;
case DICTIONARY_ASSIGN_TOKEN:
valueObject = ParseValue();
dictionary.Add(keyString, valueObject);
break;
default:
StepBackward();
keyString = ParseValue() as string;
break;
}
}
return dictionary;
}
private PBXList ParseArray()
{
PBXList list = new PBXList();
bool complete = false;
while(!complete) {
switch(NextToken()) {
case END_OF_FILE:
Debug.Log("Error: Reached end of file inside a list: " + list);
complete = true;
break;
case ARRAY_END_TOKEN:
complete = true;
break;
case ARRAY_ITEM_DELIMITER_TOKEN:
break;
default:
StepBackward();
list.Add(ParseValue());
break;
}
}
return list;
}
private object ParseString()
{
string s = string.Empty;
s += "\"";
char c = StepForeward();
while(c != QUOTEDSTRING_END_TOKEN) {
s += c;
if(c == QUOTEDSTRING_ESCAPE_TOKEN)
s += StepForeward();
c = StepForeward();
}
s += "\"";
return s;
}
//there has got to be a better way to do this
private string GetDataSubstring(int begin, int length)
{
string res = string.Empty;
for(int i=begin; i<begin+length && i<data.Length; i++) {
res += data[i];
}
return res;
}
private int CountWhitespace(int pos)
{
int i = 0;
for(int currPos=pos; currPos<data.Length && Regex.IsMatch( GetDataSubstring(currPos, 1), @"[;,\s=]" ); i++, currPos++) {
}
return i;
}
private string ParseCommentFollowingWhitespace()
{
int currIdx = index + 1;
int whitespaceLength = CountWhitespace(currIdx);
currIdx += whitespaceLength;
if(currIdx + 1 >= data.Length)
return "";
if(data[currIdx] == '/' && data[currIdx + 1] == '*') {
while(!GetDataSubstring(currIdx, 2).Equals(COMMENT_END_TOKEN)) {
if(currIdx >= data.Length) {
Debug.LogError("Unterminated comment found in .pbxproj file. Bad things are probably going to start happening");
return "";
}
currIdx++;
}
return GetDataSubstring(index + 1, (currIdx - index + 1));
} else {
return "";
}
}
private object ParseEntity()
{
string word = string.Empty;
while(!Regex.IsMatch( Peek(), @"[;,\s=]" )) {
word += StepForeward();
}
string comment = ParseCommentFollowingWhitespace();
if(comment.Length > 0) {
word += comment;
index += comment.Length;
}
if(word.Length != 24 && Regex.IsMatch(word, @"^\d+$")) {
return Int32.Parse(word);
}
return word;
}
#endregion
#region Serialize
private void AppendNewline(StringBuilder builder)
{
builder.Append(WHITESPACE_NEWLINE);
for(int i=0; i<indent; i++) {
builder.Append(WHITESPACE_TAB);
}
}
private void AppendLineDelim(StringBuilder builder, bool newline)
{
if(newline) {
AppendNewline(builder);
} else {
builder.Append(WHITESPACE_SPACE);
}
}
private bool SerializeValue(object value, StringBuilder builder)
{
bool internalNewlines = false;
if(value is PBXObject) {
internalNewlines = ((PBXObject)value).internalNewlines;
} else if(value is PBXDictionary) {
internalNewlines = ((PBXDictionary)value).internalNewlines;
} else if(value is PBXList) {
internalNewlines = ((PBXList)value).internalNewlines;
}
if(value == null) {
builder.Append("null");
} else if(value is PBXObject) {
SerializeDictionary(((PBXObject)value).data, builder, internalNewlines);
} else if(value is PBXDictionary) {
SerializeDictionary((Dictionary<string, object>)value, builder, internalNewlines);
} else if(value is Dictionary<string, object>) {
SerializeDictionary((Dictionary<string, object>)value, builder, internalNewlines);
} else if(value.GetType().IsArray) {
SerializeArray(new ArrayList((ICollection)value), builder, internalNewlines);
} else if(value is ArrayList) {
SerializeArray((ArrayList)value, builder, internalNewlines);
} else if(value is string) {
SerializeString((string)value, builder);
} else if(value is Char) {
SerializeString(Convert.ToString((char)value), builder);
} else if(value is bool) {
builder.Append(Convert.ToInt32(value).ToString());
} else if(value.GetType().IsPrimitive) {
builder.Append(Convert.ToString(value));
} else {
Debug.LogWarning("Error: unknown object of type " + value.GetType().Name);
return false;
}
return true;
}
private bool SerializeDictionary(Dictionary<string, object> dictionary, StringBuilder builder, bool internalNewlines)
{
builder.Append(DICTIONARY_BEGIN_TOKEN);
if(dictionary.Count > 0)
indent++;
if(internalNewlines)
AppendNewline(builder);
int i = 0;
foreach(KeyValuePair<string, object> pair in dictionary) {
SerializeString(pair.Key, builder);
builder.Append(WHITESPACE_SPACE);
builder.Append(DICTIONARY_ASSIGN_TOKEN);
builder.Append(WHITESPACE_SPACE);
SerializeValue(pair.Value, builder);
builder.Append(DICTIONARY_ITEM_DELIMITER_TOKEN);
if(i == dictionary.Count - 1)
indent--;
AppendLineDelim(builder, internalNewlines);
i++;
}
builder.Append(DICTIONARY_END_TOKEN);
return true;
}
private bool SerializeArray(ArrayList anArray, StringBuilder builder, bool internalNewlines)
{
builder.Append(ARRAY_BEGIN_TOKEN);
if(anArray.Count > 0)
indent++;
if(internalNewlines)
AppendNewline(builder);
for(int i = 0; i < anArray.Count; i++) {
object value = anArray[i];
if(!SerializeValue(value, builder)) {
return false;
}
builder.Append(ARRAY_ITEM_DELIMITER_TOKEN);
if(i == anArray.Count - 1)
indent--;
AppendLineDelim(builder, internalNewlines);
}
builder.Append(ARRAY_END_TOKEN);
return true;
}
private bool SerializeString(string aString, StringBuilder builder)
{
// Is a GUID?
if(PBXObject.IsGuid(aString)) {
builder.Append(aString);
return true;
}
// Is an empty string?
if(string.IsNullOrEmpty(aString)) {
builder.Append(QUOTEDSTRING_BEGIN_TOKEN);
builder.Append(QUOTEDSTRING_END_TOKEN);
return true;
}
builder.Append(aString);
return true;
}
#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 CoroutinesLib.Shared.Enums;
using System;
using System.Collections;
using System.Collections.Generic;
using CoroutinesLib.Shared.Exceptions;
using CoroutinesLib.Shared.Logging;
namespace CoroutinesLib.Shared.Enumerators
{
public interface ICoroutineResultEnumerator : ICoroutineResult, ILoggable
{
void Dispose();
bool MoveNext();
void Reset();
ICoroutineResult Current { get; }
}
public class CoroutineResultEnumerator : IEnumerator<ICoroutineResult>, ICoroutineResultEnumerator, INamedItem
{
private bool _started = false;
private IEnumerator<ICoroutineResult> _base;
private readonly TimeSpan _expireIn;
private CoroutineResultEnumerator _child;
public CoroutineResultEnumerator(string instanceName, IEnumerator<ICoroutineResult> baseEnumerator, TimeSpan? expireIn = null)
{
Log = NullLogger.Create();
_base = baseEnumerator;
_instanceName = instanceName;
if (expireIn == null || _expireIn.TotalMilliseconds < 0.01)
{
_expireIn = TimeSpan.FromDays(4096);
}
_expiration = DateTime.UtcNow + _expireIn;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// NOTE: Leave out the finalizer altogether if this class doesn't
// own unmanaged resources itself, but leave the other methods
// exactly as they are.
~CoroutineResultEnumerator()
{
// Finalizer calls Dispose(false)
Dispose(false);
}
public string InstanceName
{
get
{
return _instanceName;
}
set
{
_instanceName = value;
}
}
// The bulk of the clean-up code is implemented in Dispose(bool)
protected virtual void Dispose(bool disposing)
{
if (!_started)
{
Log.Warning("Not started {0}", InstanceName);
}
if (disposing)
{
// free managed resources
if (_base != null)
{
_base.Dispose();
_base = null;
if (_child != null)
{
_child.Dispose();
_child = null;
}
}
}
}
private readonly DateTime? _expiration;
private string _instanceName;
public bool MoveNext()
{
_started = true;
var now = DateTime.UtcNow;
if (now > _expiration)
{
throw new CoroutineTimeoutException(
string.Format("Timeout exception on '{0}', '{1}'.", InstanceName, now - _expiration.Value));
}
Current = CoroutineResult.Wait;
if (MoveNextForChild())
{
return true;
}
return MoveNextForCurrent();
}
private bool MoveNextForChild()
{
if (_child == null) return false;
if (_child.MoveNext())
{
var frb = _child.Current as FluentResultBuilder;
if (frb != null && !frb.Type.HasFlag(FluentResultType.Waiting))
{
//Bubble up the fluent
Current = _child.Current;
}
return true;
}
_child.MoveNext();
_child.Dispose();
_child = null;
return false;
}
private bool MoveNextForCurrent()
{
//Completed with the default yield break
if (!_base.MoveNext())
{
_base.MoveNext();
return false;
}
//It is the current underlying enumerator result
var current = _base.Current;
VerifyChildStatus(current);
var result = false;
switch (current.ResultType)
{
case (ResultType.Wait):
result = true;
break;
case (ResultType.Return):
break;
case (ResultType.YieldReturn):
result = true;
break;
case (ResultType.YieldBreak):
_base.MoveNext();
break;
case (ResultType.Enumerator):
_child = (CoroutineResultEnumerator)current.Result;
result = true;
break;
case (ResultType.FluentBuilder):
SetupFluentResultEnumerator(current);
result = true;
break;
}
return result;
}
private void VerifyChildStatus(ICoroutineResult current)
{
if (_child != null)
{
if (current.ResultType == ResultType.FluentBuilder || current.ResultType == ResultType.Enumerator)
{
throw new CoroutinesLibException("Duplicate child enumerator instance.");
}
}
}
private void SetupFluentResultEnumerator(ICoroutineResult current)
{
var builder = (FluentResultBuilder)current;
builder.Log = Log;
if (builder.Type.HasFlag(FluentResultType.CoroutineFunction) && !builder.Type.HasFlag(FluentResultType.Waiting))
{
_child = new CoroutineResultEnumerator(builder.InstanceName, builder.Coroutine.Execute().GetEnumerator())
{
Log = Log
};
}
else if (builder.Type.HasFlag(FluentResultType.Waiting))
{
_child = new CoroutineResultEnumerator(builder.InstanceName, builder.RunEnumerator().GetEnumerator())
{
Log = Log
};
}
else
{
Current = builder;
}
}
public void Reset()
{
_base.Reset();
}
public ICoroutineResult Current { get; private set; }
object IEnumerator.Current
{
get { return Current; }
}
public ResultType ResultType
{
get { return ResultType.Enumerator; }
}
public object Result
{
get { return Current; }
}
public ILogger Log { get; set; }
public string BuildRunningStatus()
{
var result = _instanceName;
if (_child != null)
{
result += "->" + _child.BuildRunningStatus();
}
return result;
}
}
}
| |
/*
* 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.Globalization;
using Newtonsoft.Json;
using QuantConnect.Data;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression test to demonstrate importing and trading on custom data.
/// </summary>
/// <meta name="tag" content="using data" />
/// <meta name="tag" content="custom data" />
/// <meta name="tag" content="crypto" />
/// <meta name="tag" content="regression test" />
public class CustomDataRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
/// <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(2011, 9, 13);
SetEndDate(2015, 12, 01);
//Set the cash for the strategy:
SetCash(100000);
//Define the symbol and "type" of our generic data:
var resolution = LiveMode ? Resolution.Second : Resolution.Daily;
AddData<Bitcoin>("BTC", resolution);
}
/// <summary>
/// Event Handler for Bitcoin Data Events: These Bitcoin objects are created from our
/// "Bitcoin" type below and fired into this event handler.
/// </summary>
/// <param name="data">One(1) Bitcoin Object, streamed into our algorithm synchronised in time with our other data streams</param>
public void OnData(Bitcoin data)
{
//If we don't have any bitcoin "SHARES" -- invest"
if (!Portfolio.Invested)
{
//Bitcoin used as a tradable asset, like stocks, futures etc.
if (data.Close != 0)
{
//Access custom data symbols using <ticker>.<custom-type>
Order("BTC.Bitcoin", Portfolio.MarginRemaining / Math.Abs(data.Close + 1));
}
}
}
/// <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, Language.Python };
/// <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", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "157.497%"},
{"Drawdown", "84.800%"},
{"Expectancy", "0"},
{"Net Profit", "5319.007%"},
{"Sharpe Ratio", "2.086"},
{"Probabilistic Sharpe Ratio", "69.456%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "1.736"},
{"Beta", "0.142"},
{"Annual Standard Deviation", "0.84"},
{"Annual Variance", "0.706"},
{"Information Ratio", "1.925"},
{"Tracking Error", "0.846"},
{"Treynor Ratio", "12.333"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "BTC.Bitcoin 2S"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "2.269"},
{"Return Over Maximum Drawdown", "1.858"},
{"Portfolio Turnover", "0"},
{"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", "50faa37f15732bf5c24ad1eeaa335bc7"}
};
/// <summary>
/// Custom Data Type: Bitcoin data from Quandl - http://www.quandl.com/help/api-for-bitcoin-data
/// </summary>
public class Bitcoin : BaseData
{
[JsonProperty("timestamp")]
public int Timestamp = 0;
[JsonProperty("open")]
public decimal Open = 0;
[JsonProperty("high")]
public decimal High = 0;
[JsonProperty("low")]
public decimal Low = 0;
[JsonProperty("last")]
public decimal Close = 0;
[JsonProperty("bid")]
public decimal Bid = 0;
[JsonProperty("ask")]
public decimal Ask = 0;
[JsonProperty("vwap")]
public decimal WeightedPrice = 0;
[JsonProperty("volume")]
public decimal VolumeBTC = 0;
public decimal VolumeUSD = 0;
/// <summary>
/// 1. DEFAULT CONSTRUCTOR: Custom data types need a default constructor.
/// We search for a default constructor so please provide one here. It won't be used for data, just to generate the "Factory".
/// </summary>
public Bitcoin()
{
Symbol = "BTC";
}
/// <summary>
/// 2. RETURN THE STRING URL SOURCE LOCATION FOR YOUR DATA:
/// This is a powerful and dynamic select source file method. If you have a large dataset, 10+mb we recommend you break it into smaller files. E.g. One zip per year.
/// We can accept raw text or ZIP files. We read the file extension to determine if it is a zip file.
/// </summary>
/// <param name="config">Configuration object</param>
/// <param name="date">Date of this source file</param>
/// <param name="isLiveMode">true if we're in live mode, false for backtesting mode</param>
/// <returns>String URL of source file.</returns>
public override SubscriptionDataSource GetSource(SubscriptionDataConfig config, DateTime date, bool isLiveMode)
{
if (isLiveMode)
{
return new SubscriptionDataSource("https://www.bitstamp.net/api/ticker/", SubscriptionTransportMedium.Rest);
}
//return "http://my-ftp-server.com/futures-data-" + date.ToString("Ymd") + ".zip";
// OR simply return a fixed small data file. Large files will slow down your backtest
return new SubscriptionDataSource("https://www.quantconnect.com/api/v2/proxy/quandl/api/v3/datasets/BCHARTS/BITSTAMPUSD.csv?order=asc&api_key=WyAazVXnq7ATy_fefTqm", SubscriptionTransportMedium.RemoteFile);
}
/// <summary>
/// 3. READER METHOD: Read 1 line from data source and convert it into Object.
/// Each line of the CSV File is presented in here. The backend downloads your file, loads it into memory and then line by line
/// feeds it into your algorithm
/// </summary>
/// <param name="line">string line from the data source file submitted above</param>
/// <param name="config">Subscription data, symbol name, data type</param>
/// <param name="date">Current date we're requesting. This allows you to break up the data source into daily files.</param>
/// <param name="isLiveMode">true if we're in live mode, false for backtesting mode</param>
/// <returns>New Bitcoin Object which extends BaseData.</returns>
public override BaseData Reader(SubscriptionDataConfig config, string line, DateTime date, bool isLiveMode)
{
var coin = new Bitcoin();
if (isLiveMode)
{
//Example Line Format:
//{"high": "441.00", "last": "421.86", "timestamp": "1411606877", "bid": "421.96", "vwap": "428.58", "volume": "14120.40683975", "low": "418.83", "ask": "421.99"}
try
{
coin = JsonConvert.DeserializeObject<Bitcoin>(line);
coin.EndTime = DateTime.UtcNow.ConvertFromUtc(config.ExchangeTimeZone);
coin.Value = coin.Close;
}
catch { /* Do nothing, possible error in json decoding */ }
return coin;
}
//Example Line Format:
//Date Open High Low Close Volume (BTC) Volume (Currency) Weighted Price
//2011-09-13 5.8 6.0 5.65 5.97 58.37138238, 346.0973893944 5.929230648356
try
{
string[] data = line.Split(',');
coin.Time = DateTime.Parse(data[0], CultureInfo.InvariantCulture);
coin.EndTime = coin.Time.AddDays(1);
coin.Open = Convert.ToDecimal(data[1], CultureInfo.InvariantCulture);
coin.High = Convert.ToDecimal(data[2], CultureInfo.InvariantCulture);
coin.Low = Convert.ToDecimal(data[3], CultureInfo.InvariantCulture);
coin.Close = Convert.ToDecimal(data[4], CultureInfo.InvariantCulture);
coin.VolumeBTC = Convert.ToDecimal(data[5], CultureInfo.InvariantCulture);
coin.VolumeUSD = Convert.ToDecimal(data[6], CultureInfo.InvariantCulture);
coin.WeightedPrice = Convert.ToDecimal(data[7], CultureInfo.InvariantCulture);
coin.Value = coin.Close;
}
catch { /* Do nothing, skip first title row */ }
return coin;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Text;
using System.Threading;
using System.Runtime.InteropServices.ComTypes;
using Internal.Runtime.CompilerHelpers;
namespace System.Runtime.InteropServices
{
public static partial class Marshal
{
#if PLATFORM_WINDOWS
private const long HIWORDMASK = unchecked((long)0xffffffffffff0000L);
// Win32 has the concept of Atoms, where a pointer can either be a pointer
// or an int. If it's less than 64K, this is guaranteed to NOT be a
// pointer since the bottom 64K bytes are reserved in a process' page table.
// We should be careful about deallocating this stuff. Extracted to
// a function to avoid C# problems with lack of support for IntPtr.
// We have 2 of these methods for slightly different semantics for NULL.
private static bool IsWin32Atom(IntPtr ptr)
{
long lPtr = (long)ptr;
return 0 == (lPtr & HIWORDMASK);
}
private static bool IsNotWin32Atom(IntPtr ptr)
{
long lPtr = (long)ptr;
return 0 != (lPtr & HIWORDMASK);
}
#else // PLATFORM_WINDOWS
private static bool IsWin32Atom(IntPtr ptr) => false;
private static bool IsNotWin32Atom(IntPtr ptr) => true;
#endif // PLATFORM_WINDOWS
//====================================================================
// The default character size for the system. This is always 2 because
// the framework only runs on UTF-16 systems.
//====================================================================
public static readonly int SystemDefaultCharSize = 2;
//====================================================================
// The max DBCS character size for the system.
//====================================================================
public static readonly int SystemMaxDBCSCharSize = PInvokeMarshal.GetSystemMaxDBCSCharSize();
public static unsafe String PtrToStringAnsi(IntPtr ptr)
{
if (IntPtr.Zero == ptr)
{
return null;
}
else if (IsWin32Atom(ptr))
{
return null;
}
else
{
int nb = lstrlenA(ptr);
if (nb == 0)
{
return string.Empty;
}
else
{
return new string((sbyte*)ptr);
}
}
}
public static unsafe String PtrToStringAnsi(IntPtr ptr, int len)
{
if (ptr == IntPtr.Zero)
throw new ArgumentNullException(nameof(ptr));
if (len < 0)
throw new ArgumentException(nameof(len));
return ConvertToUnicode(ptr, len);
}
public static unsafe String PtrToStringUni(IntPtr ptr, int len)
{
return PInvokeMarshal.PtrToStringUni(ptr, len);
}
public static unsafe String PtrToStringUni(IntPtr ptr)
{
return PInvokeMarshal.PtrToStringUni(ptr);
}
public static String PtrToStringAuto(IntPtr ptr, int len)
{
// Ansi platforms are no longer supported
return PtrToStringUni(ptr, len);
}
public static String PtrToStringAuto(IntPtr ptr)
{
// Ansi platforms are no longer supported
return PtrToStringUni(ptr);
}
//====================================================================
// SizeOf()
//====================================================================
/// <summary>
/// Returns the size of an instance of a value type.
/// </summary>
public static int SizeOf<T>()
{
return SizeOf(typeof(T));
}
public static int SizeOf<T>(T structure)
{
return SizeOf<T>();
}
public static int SizeOf(Object structure)
{
if (structure == null)
throw new ArgumentNullException(nameof(structure));
// we never had a check for generics here
return SizeOfHelper(structure.GetType(), true);
}
public static int SizeOf(Type t)
{
if (t == null)
throw new ArgumentNullException(nameof(t));
if (t.TypeHandle.IsGenericType() || t.TypeHandle.IsGenericTypeDefinition())
throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(t));
return SizeOfHelper(t, true);
}
private static int SizeOfHelper(Type t, bool throwIfNotMarshalable)
{
RuntimeTypeHandle typeHandle = t.TypeHandle;
int size;
if (RuntimeInteropData.Instance.TryGetStructUnsafeStructSize(typeHandle, out size))
{
return size;
}
if (!typeHandle.IsBlittable() && !typeHandle.IsValueType())
{
throw new MissingInteropDataException(SR.StructMarshalling_MissingInteropData, t);
}
else
{
return typeHandle.GetValueTypeSize();
}
}
//====================================================================
// OffsetOf()
//====================================================================
public static IntPtr OffsetOf(Type t, String fieldName)
{
if (t == null)
throw new ArgumentNullException(nameof(t));
if (String.IsNullOrEmpty(fieldName))
throw new ArgumentNullException(nameof(fieldName));
if (t.TypeHandle.IsGenericType() || t.TypeHandle.IsGenericTypeDefinition())
throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(t));
return OffsetOfHelper(t, fieldName);
}
private static IntPtr OffsetOfHelper(Type t, String fieldName)
{
bool structExists;
uint offset;
if (RuntimeInteropData.Instance.TryGetStructFieldOffset(t.TypeHandle, fieldName, out structExists, out offset))
{
return new IntPtr(offset);
}
// if we can find the struct but couldn't find its field, throw Argument Exception
if (structExists)
{
throw new ArgumentException(SR.Format(SR.Argument_OffsetOfFieldNotFound, t.TypeHandle.GetDisplayName()), nameof(fieldName));
}
else
{
throw new MissingInteropDataException(SR.StructMarshalling_MissingInteropData, t);
}
}
public static IntPtr OffsetOf<T>(String fieldName)
{
return OffsetOf(typeof(T), fieldName);
}
//====================================================================
// Copy blocks from CLR arrays to native memory.
//====================================================================
public static void Copy(int[] source, int startIndex, IntPtr destination, int length)
{
PInvokeMarshal.CopyToNative(source, startIndex, destination, length);
}
public static void Copy(char[] source, int startIndex, IntPtr destination, int length)
{
PInvokeMarshal.CopyToNative(source, startIndex, destination, length);
}
public static void Copy(short[] source, int startIndex, IntPtr destination, int length)
{
PInvokeMarshal.CopyToNative(source, startIndex, destination, length);
}
public static void Copy(long[] source, int startIndex, IntPtr destination, int length)
{
PInvokeMarshal.CopyToNative(source, startIndex, destination, length);
}
public static void Copy(float[] source, int startIndex, IntPtr destination, int length)
{
PInvokeMarshal.CopyToNative(source, startIndex, destination, length);
}
public static void Copy(double[] source, int startIndex, IntPtr destination, int length)
{
PInvokeMarshal.CopyToNative(source, startIndex, destination, length);
}
public static void Copy(byte[] source, int startIndex, IntPtr destination, int length)
{
PInvokeMarshal.CopyToNative(source, startIndex, destination, length);
}
public static void Copy(IntPtr[] source, int startIndex, IntPtr destination, int length)
{
PInvokeMarshal.CopyToNative(source, startIndex, destination, length);
}
//====================================================================
// Copy blocks from native memory to CLR arrays
//====================================================================
public static void Copy(IntPtr source, int[] destination, int startIndex, int length)
{
PInvokeMarshal.CopyToManaged(source, destination, startIndex, length);
}
public static void Copy(IntPtr source, char[] destination, int startIndex, int length)
{
PInvokeMarshal.CopyToManaged(source, destination, startIndex, length);
}
public static void Copy(IntPtr source, short[] destination, int startIndex, int length)
{
PInvokeMarshal.CopyToManaged(source, destination, startIndex, length);
}
public static void Copy(IntPtr source, long[] destination, int startIndex, int length)
{
PInvokeMarshal.CopyToManaged(source, destination, startIndex, length);
}
public static void Copy(IntPtr source, float[] destination, int startIndex, int length)
{
PInvokeMarshal.CopyToManaged(source, destination, startIndex, length);
}
public static void Copy(IntPtr source, double[] destination, int startIndex, int length)
{
PInvokeMarshal.CopyToManaged(source, destination, startIndex, length);
}
public static void Copy(IntPtr source, byte[] destination, int startIndex, int length)
{
PInvokeMarshal.CopyToManaged(source, destination, startIndex, length);
}
public static void Copy(IntPtr source, IntPtr[] destination, int startIndex, int length)
{
PInvokeMarshal.CopyToManaged(source, destination, startIndex, length);
}
//====================================================================
// Read from memory
//====================================================================
public static unsafe byte ReadByte(IntPtr ptr, int ofs)
{
byte* addr = (byte*)ptr + ofs;
return *addr;
}
public static byte ReadByte(IntPtr ptr)
{
return ReadByte(ptr, 0);
}
public static unsafe short ReadInt16(IntPtr ptr, int ofs)
{
byte* addr = (byte*)ptr + ofs;
if ((unchecked((int)addr) & 0x1) == 0)
{
// aligned read
return *((short*)addr);
}
else
{
// unaligned read
short val;
byte* valPtr = (byte*)&val;
valPtr[0] = addr[0];
valPtr[1] = addr[1];
return val;
}
}
public static short ReadInt16(IntPtr ptr)
{
return ReadInt16(ptr, 0);
}
public static unsafe int ReadInt32(IntPtr ptr, int ofs)
{
byte* addr = (byte*)ptr + ofs;
if ((unchecked((int)addr) & 0x3) == 0)
{
// aligned read
return *((int*)addr);
}
else
{
// unaligned read
int val;
byte* valPtr = (byte*)&val;
valPtr[0] = addr[0];
valPtr[1] = addr[1];
valPtr[2] = addr[2];
valPtr[3] = addr[3];
return val;
}
}
public static int ReadInt32(IntPtr ptr)
{
return ReadInt32(ptr, 0);
}
public static IntPtr ReadIntPtr([MarshalAs(UnmanagedType.AsAny), In] Object ptr, int ofs)
{
if (IntPtr.Size == 4)
return (IntPtr)ReadInt32(ptr, ofs);
else
return (IntPtr)ReadInt64(ptr, ofs);
}
public static IntPtr ReadIntPtr(IntPtr ptr, int ofs)
{
if (IntPtr.Size == 4)
return (IntPtr)ReadInt32(ptr, ofs);
else
return (IntPtr)ReadInt64(ptr, ofs);
}
public static IntPtr ReadIntPtr(IntPtr ptr)
{
return ReadIntPtr(ptr, 0);
}
public static unsafe long ReadInt64(IntPtr ptr, int ofs)
{
byte* addr = (byte*)ptr + ofs;
if ((unchecked((int)addr) & 0x7) == 0)
{
// aligned read
return *((long*)addr);
}
else
{
// unaligned read
long val;
byte* valPtr = (byte*)&val;
valPtr[0] = addr[0];
valPtr[1] = addr[1];
valPtr[2] = addr[2];
valPtr[3] = addr[3];
valPtr[4] = addr[4];
valPtr[5] = addr[5];
valPtr[6] = addr[6];
valPtr[7] = addr[7];
return val;
}
}
public static long ReadInt64(IntPtr ptr)
{
return ReadInt64(ptr, 0);
}
//====================================================================
// Write to memory
//====================================================================
public static unsafe void WriteByte(IntPtr ptr, int ofs, byte val)
{
byte* addr = (byte*)ptr + ofs;
*addr = val;
}
public static void WriteByte(IntPtr ptr, byte val)
{
WriteByte(ptr, 0, val);
}
public static unsafe void WriteInt16(IntPtr ptr, int ofs, short val)
{
byte* addr = (byte*)ptr + ofs;
if ((unchecked((int)addr) & 0x1) == 0)
{
// aligned write
*((short*)addr) = val;
}
else
{
// unaligned write
byte* valPtr = (byte*)&val;
addr[0] = valPtr[0];
addr[1] = valPtr[1];
}
}
public static void WriteInt16(IntPtr ptr, short val)
{
WriteInt16(ptr, 0, val);
}
public static void WriteInt16(IntPtr ptr, int ofs, char val)
{
WriteInt16(ptr, ofs, (short)val);
}
public static void WriteInt16([In, Out]Object ptr, int ofs, char val)
{
WriteInt16(ptr, ofs, (short)val);
}
public static void WriteInt16(IntPtr ptr, char val)
{
WriteInt16(ptr, 0, (short)val);
}
public static unsafe void WriteInt32(IntPtr ptr, int ofs, int val)
{
byte* addr = (byte*)ptr + ofs;
if ((unchecked((int)addr) & 0x3) == 0)
{
// aligned write
*((int*)addr) = val;
}
else
{
// unaligned write
byte* valPtr = (byte*)&val;
addr[0] = valPtr[0];
addr[1] = valPtr[1];
addr[2] = valPtr[2];
addr[3] = valPtr[3];
}
}
public static void WriteInt32(IntPtr ptr, int val)
{
WriteInt32(ptr, 0, val);
}
public static void WriteIntPtr(IntPtr ptr, int ofs, IntPtr val)
{
if (IntPtr.Size == 4)
WriteInt32(ptr, ofs, (int)val);
else
WriteInt64(ptr, ofs, (long)val);
}
public static void WriteIntPtr([MarshalAs(UnmanagedType.AsAny), In, Out] Object ptr, int ofs, IntPtr val)
{
if (IntPtr.Size == 4)
WriteInt32(ptr, ofs, (int)val);
else
WriteInt64(ptr, ofs, (long)val);
}
public static void WriteIntPtr(IntPtr ptr, IntPtr val)
{
WriteIntPtr(ptr, 0, val);
}
public static unsafe void WriteInt64(IntPtr ptr, int ofs, long val)
{
byte* addr = (byte*)ptr + ofs;
if ((unchecked((int)addr) & 0x7) == 0)
{
// aligned write
*((long*)addr) = val;
}
else
{
// unaligned write
byte* valPtr = (byte*)&val;
addr[0] = valPtr[0];
addr[1] = valPtr[1];
addr[2] = valPtr[2];
addr[3] = valPtr[3];
addr[4] = valPtr[4];
addr[5] = valPtr[5];
addr[6] = valPtr[6];
addr[7] = valPtr[7];
}
}
public static void WriteInt64(IntPtr ptr, long val)
{
WriteInt64(ptr, 0, val);
}
//====================================================================
// GetHRForLastWin32Error
//====================================================================
public static int GetHRForLastWin32Error()
{
int dwLastError = GetLastWin32Error();
if ((dwLastError & 0x80000000) == 0x80000000)
{
return dwLastError;
}
else
{
return (dwLastError & 0x0000FFFF) | unchecked((int)0x80070000);
}
}
public static Exception GetExceptionForHR(int errorCode, IntPtr errorInfo)
{
#if ENABLE_WINRT
if (errorInfo != new IntPtr(-1))
{
throw new PlatformNotSupportedException();
}
return ExceptionHelpers.GetMappingExceptionForHR(
errorCode,
message: null,
createCOMException: false,
hasErrorInfo: false);
#else
return new COMException(errorCode);
#endif // ENABLE_WINRT
}
//====================================================================
// Throws a CLR exception based on the HRESULT.
//====================================================================
public static void ThrowExceptionForHR(int errorCode)
{
ThrowExceptionForHRInternal(errorCode, new IntPtr(-1));
}
public static void ThrowExceptionForHR(int errorCode, IntPtr errorInfo)
{
ThrowExceptionForHRInternal(errorCode, errorInfo);
}
private static void ThrowExceptionForHRInternal(int errorCode, IntPtr errorInfo)
{
if (errorCode < 0)
{
throw GetExceptionForHR(errorCode, errorInfo);
}
}
//====================================================================
// Memory allocation and deallocation.
//====================================================================
public static unsafe IntPtr ReAllocHGlobal(IntPtr pv, IntPtr cb)
{
return PInvokeMarshal.MemReAlloc(pv, cb);
}
private static unsafe void ConvertToAnsi(string source, IntPtr pbNativeBuffer, int cbNativeBuffer)
{
Debug.Assert(source != null);
Debug.Assert(pbNativeBuffer != IntPtr.Zero);
Debug.Assert(cbNativeBuffer >= (source.Length + 1) * SystemMaxDBCSCharSize, "Insufficient buffer length passed to ConvertToAnsi");
fixed (char* pch = source)
{
int convertedBytes =
PInvokeMarshal.ConvertWideCharToMultiByte(pch, source.Length, (byte*)pbNativeBuffer, cbNativeBuffer, false, false);
((byte*)pbNativeBuffer)[convertedBytes] = 0;
}
}
private static unsafe string ConvertToUnicode(IntPtr sourceBuffer, int cbSourceBuffer)
{
if (IsWin32Atom(sourceBuffer))
{
throw new ArgumentException(SR.Arg_MustBeStringPtrNotAtom);
}
if (sourceBuffer == IntPtr.Zero || cbSourceBuffer == 0)
{
return String.Empty;
}
// MB_PRECOMPOSED is the default.
int charsRequired = PInvokeMarshal.GetCharCount((byte*)sourceBuffer, cbSourceBuffer);
if (charsRequired == 0)
{
throw new ArgumentException(SR.Arg_InvalidANSIString);
}
char[] wideChars = new char[charsRequired + 1];
fixed (char* pWideChars = &wideChars[0])
{
int converted = PInvokeMarshal.ConvertMultiByteToWideChar((byte*)sourceBuffer,
cbSourceBuffer,
pWideChars,
wideChars.Length);
if (converted == 0)
{
throw new ArgumentException(SR.Arg_InvalidANSIString);
}
wideChars[converted] = '\0';
return new String(pWideChars);
}
}
private static unsafe int lstrlenA(IntPtr sz)
{
Debug.Assert(sz != IntPtr.Zero);
byte* pb = (byte*)sz;
byte* start = pb;
while (*pb != 0)
{
++pb;
}
return (int)(pb - start);
}
private static unsafe int lstrlenW(IntPtr wsz)
{
Debug.Assert(wsz != IntPtr.Zero);
char* pc = (char*)wsz;
char* start = pc;
while (*pc != 0)
{
++pc;
}
return (int)(pc - start);
}
// Zero out the buffer pointed to by ptr, making sure that the compiler cannot
// replace the zeroing with a nop
private static unsafe void SecureZeroMemory(IntPtr ptr, int bytes)
{
Debug.Assert(ptr != IntPtr.Zero);
Debug.Assert(bytes >= 0);
byte* pBuffer = (byte*)ptr;
for (int i = 0; i < bytes; ++i)
{
Volatile.Write(ref pBuffer[i], 0);
}
}
//====================================================================
// String convertions.
//====================================================================
public static unsafe IntPtr StringToHGlobalAnsi(String s)
{
if (s == null)
{
return IntPtr.Zero;
}
else
{
int nb = (s.Length + 1) * SystemMaxDBCSCharSize;
// Overflow checking
if (nb < s.Length)
throw new ArgumentOutOfRangeException(nameof(s));
IntPtr hglobal = PInvokeMarshal.MemAlloc(new IntPtr(nb));
ConvertToAnsi(s, hglobal, nb);
return hglobal;
}
}
public static unsafe IntPtr StringToHGlobalUni(String s)
{
if (s == null)
{
return IntPtr.Zero;
}
else
{
int nb = (s.Length + 1) * 2;
// Overflow checking
if (nb < s.Length)
throw new ArgumentOutOfRangeException(nameof(s));
IntPtr hglobal = PInvokeMarshal.MemAlloc(new IntPtr(nb));
fixed (char* firstChar = s)
{
InteropExtensions.Memcpy(hglobal, new IntPtr(firstChar), nb);
}
return hglobal;
}
}
public static IntPtr StringToHGlobalAuto(String s)
{
// Ansi platforms are no longer supported
return StringToHGlobalUni(s);
}
//====================================================================
// return the IUnknown* for an Object if the current context
// is the one where the RCW was first seen. Will return null
// otherwise.
//====================================================================
public static IntPtr /* IUnknown* */ GetIUnknownForObject(Object o)
{
if (o == null)
{
throw new ArgumentNullException(nameof(o));
}
return McgMarshal.ObjectToComInterface(o, InternalTypes.IUnknown);
}
//====================================================================
// return an Object for IUnknown
//====================================================================
public static Object GetObjectForIUnknown(IntPtr /* IUnknown* */ pUnk)
{
if (pUnk == default(IntPtr))
{
throw new ArgumentNullException(nameof(pUnk));
}
return McgMarshal.ComInterfaceToObject(pUnk, InternalTypes.IUnknown);
}
//====================================================================
// check if the object is classic COM component
//====================================================================
public static bool IsComObject(Object o)
{
if (o == null)
throw new ArgumentNullException(nameof(o), SR.Arg_InvalidHandle);
return McgMarshal.IsComObject(o);
}
public static unsafe IntPtr StringToCoTaskMemUni(String s)
{
if (s == null)
{
return IntPtr.Zero;
}
else
{
int nb = (s.Length + 1) * 2;
// Overflow checking
if (nb < s.Length)
throw new ArgumentOutOfRangeException(nameof(s));
IntPtr hglobal = PInvokeMarshal.CoTaskMemAlloc(new UIntPtr((uint)nb));
if (hglobal == IntPtr.Zero)
{
throw new OutOfMemoryException();
}
else
{
fixed (char* firstChar = s)
{
InteropExtensions.Memcpy(hglobal, new IntPtr(firstChar), nb);
}
return hglobal;
}
}
}
public static unsafe IntPtr StringToCoTaskMemAnsi(String s)
{
if (s == null)
{
return IntPtr.Zero;
}
else
{
int nb = (s.Length + 1) * SystemMaxDBCSCharSize;
// Overflow checking
if (nb < s.Length)
throw new ArgumentOutOfRangeException(nameof(s));
IntPtr hglobal = PInvokeMarshal.CoTaskMemAlloc(new UIntPtr((uint)nb));
if (hglobal == IntPtr.Zero)
{
throw new OutOfMemoryException();
}
else
{
ConvertToAnsi(s, hglobal, nb);
return hglobal;
}
}
}
public static IntPtr StringToCoTaskMemAuto(String s)
{
// Ansi platforms are no longer supported
return StringToCoTaskMemUni(s);
}
//====================================================================
// release the COM component and if the reference hits 0 zombie this object
// further usage of this Object might throw an exception
//====================================================================
public static int ReleaseComObject(Object o)
{
if (o == null)
throw new ArgumentNullException(nameof(o));
__ComObject co = null;
// Make sure the obj is an __ComObject.
try
{
co = (__ComObject)o;
}
catch (InvalidCastException)
{
throw new ArgumentException(SR.Argument_ObjNotComObject, nameof(o));
}
return McgMarshal.Release(co);
}
//====================================================================
// release the COM component and zombie this object
// further usage of this Object might throw an exception
//====================================================================
public static Int32 FinalReleaseComObject(Object o)
{
if (o == null)
throw new ArgumentNullException(nameof(o));
__ComObject co = null;
// Make sure the obj is an __ComObject.
try
{
co = (__ComObject)o;
}
catch (InvalidCastException)
{
throw new ArgumentException(SR.Argument_ObjNotComObject, nameof(o));
}
co.FinalReleaseSelf();
return 0;
}
//====================================================================
// IUnknown Helpers
//====================================================================
public static int /* HRESULT */ QueryInterface(IntPtr /* IUnknown */ pUnk, ref Guid iid, out IntPtr ppv)
{
if (pUnk == IntPtr.Zero)
throw new ArgumentNullException(nameof(pUnk));
return McgMarshal.ComQueryInterfaceWithHR(pUnk, ref iid, out ppv);
}
public static int /* ULONG */ AddRef(IntPtr /* IUnknown */ pUnk)
{
if (pUnk == IntPtr.Zero)
throw new ArgumentNullException(nameof(pUnk));
return McgMarshal.ComAddRef(pUnk);
}
public static int /* ULONG */ Release(IntPtr /* IUnknown */ pUnk)
{
if (pUnk == IntPtr.Zero)
throw new ArgumentNullException(nameof(pUnk));
// This is documented to have "undefined behavior" when the ref count is already zero, so
// let's not AV if we can help it
return McgMarshal.ComSafeRelease(pUnk);
}
public static IntPtr ReAllocCoTaskMem(IntPtr pv, int cb)
{
IntPtr pNewMem = PInvokeMarshal.CoTaskMemReAlloc(pv, new IntPtr(cb));
if (pNewMem == IntPtr.Zero && cb != 0)
{
throw new OutOfMemoryException();
}
return pNewMem;
}
//====================================================================
// BSTR allocation and dealocation.
//====================================================================
public static void FreeBSTR(IntPtr ptr)
{
if (IsNotWin32Atom(ptr))
{
ExternalInterop.SysFreeString(ptr);
}
}
public static unsafe IntPtr StringToBSTR(String s)
{
if (s == null)
return IntPtr.Zero;
// Overflow checking
if (s.Length + 1 < s.Length)
throw new ArgumentOutOfRangeException(nameof(s));
fixed (char* pch = s)
{
IntPtr bstr = new IntPtr(ExternalInterop.SysAllocStringLen(pch, (uint)s.Length));
if (bstr == IntPtr.Zero)
throw new OutOfMemoryException();
return bstr;
}
}
public static String PtrToStringBSTR(IntPtr ptr)
{
return PtrToStringUni(ptr, (int)ExternalInterop.SysStringLen(ptr));
}
public static void ZeroFreeBSTR(IntPtr s)
{
SecureZeroMemory(s, (int)ExternalInterop.SysStringLen(s) * 2);
FreeBSTR(s);
}
public static void ZeroFreeCoTaskMemAnsi(IntPtr s)
{
SecureZeroMemory(s, lstrlenA(s));
FreeCoTaskMem(s);
}
public static void ZeroFreeCoTaskMemUnicode(IntPtr s)
{
SecureZeroMemory(s, lstrlenW(s));
FreeCoTaskMem(s);
}
public static void ZeroFreeGlobalAllocAnsi(IntPtr s)
{
SecureZeroMemory(s, lstrlenA(s));
FreeHGlobal(s);
}
public static void ZeroFreeGlobalAllocUnicode(IntPtr s)
{
SecureZeroMemory(s, lstrlenW(s));
FreeHGlobal(s);
}
/// <summary>
/// Returns the unmanaged function pointer for this delegate
/// </summary>
public static IntPtr GetFunctionPointerForDelegate(Delegate d)
{
if (d == null)
throw new ArgumentNullException(nameof(d));
return PInvokeMarshal.GetFunctionPointerForDelegate(d);
}
public static IntPtr GetFunctionPointerForDelegate<TDelegate>(TDelegate d)
{
return GetFunctionPointerForDelegate((Delegate)(object)d);
}
//====================================================================
// Marshals data from a native memory block to a preallocated structure class.
//====================================================================
private static unsafe void PtrToStructureHelper(IntPtr ptr, Object structure)
{
RuntimeTypeHandle structureTypeHandle = structure.GetType().TypeHandle;
// Boxed struct start at offset 1 (EEType* at offset 0) while class start at offset 0
int offset = structureTypeHandle.IsValueType() ? 1 : 0;
if (structureTypeHandle.IsBlittable() && structureTypeHandle.IsValueType())
{
int structSize = Marshal.SizeOf(structure);
InteropExtensions.PinObjectAndCall(structure,
unboxedStructPtr =>
{
InteropExtensions.Memcpy(
(IntPtr)((IntPtr*)unboxedStructPtr + offset), // safe (need to adjust offset as it could be class)
ptr, // unsafe (no need to adjust as it is always struct)
structSize
);
});
return;
}
IntPtr unmarshalStub;
if (RuntimeInteropData.Instance.TryGetStructUnmarshalStub(structureTypeHandle, out unmarshalStub))
{
InteropExtensions.PinObjectAndCall(structure,
unboxedStructPtr =>
{
CalliIntrinsics.Call<int>(
unmarshalStub,
(void*)ptr, // unsafe (no need to adjust as it is always struct)
((void*)((IntPtr*)unboxedStructPtr + offset)) // safe (need to adjust offset as it could be class)
);
});
return;
}
throw new MissingInteropDataException(SR.StructMarshalling_MissingInteropData, structure.GetType());
}
//====================================================================
// Creates a new instance of "structuretype" and marshals data from a
// native memory block to it.
//====================================================================
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static Object PtrToStructure(IntPtr ptr, Type structureType)
{
// Boxing the struct here is important to ensure that the original copy is written to,
// not the autoboxed copy
if (ptr == IntPtr.Zero)
throw new ArgumentNullException(nameof(ptr));
if (structureType == null)
throw new ArgumentNullException(nameof(structureType));
Object boxedStruct = InteropExtensions.RuntimeNewObject(structureType.TypeHandle);
PtrToStructureHelper(ptr, boxedStruct);
return boxedStruct;
}
public static T PtrToStructure<T>(IntPtr ptr)
{
return (T)PtrToStructure(ptr, typeof(T));
}
public static void PtrToStructure(IntPtr ptr, Object structure)
{
if (ptr == IntPtr.Zero)
throw new ArgumentNullException(nameof(ptr));
if (structure == null)
throw new ArgumentNullException(nameof(structure));
RuntimeTypeHandle structureTypeHandle = structure.GetType().TypeHandle;
if (structureTypeHandle.IsValueType())
{
throw new ArgumentException(nameof(structure), SR.Argument_StructMustNotBeValueClass);
}
PtrToStructureHelper(ptr, structure);
}
public static void PtrToStructure<T>(IntPtr ptr, T structure)
{
PtrToStructure(ptr, (object)structure);
}
//====================================================================
// Marshals data from a structure class to a native memory block.
// If the structure contains pointers to allocated blocks and
// "fDeleteOld" is true, this routine will call DestroyStructure() first.
//====================================================================
public static unsafe void StructureToPtr(Object structure, IntPtr ptr, bool fDeleteOld)
{
if (structure == null)
throw new ArgumentNullException(nameof(structure));
if (ptr == IntPtr.Zero)
throw new ArgumentNullException(nameof(ptr));
if (fDeleteOld)
{
DestroyStructure(ptr, structure.GetType());
}
RuntimeTypeHandle structureTypeHandle = structure.GetType().TypeHandle;
if (structureTypeHandle.IsGenericType() || structureTypeHandle.IsGenericTypeDefinition())
{
throw new ArgumentException(nameof(structure), SR.Argument_NeedNonGenericObject);
}
// Boxed struct start at offset 1 (EEType* at offset 0) while class start at offset 0
int offset = structureTypeHandle.IsValueType() ? 1 : 0;
bool isBlittable = false; // whether Mcg treat this struct as blittable struct
IntPtr marshalStub;
if (RuntimeInteropData.Instance.TryGetStructMarshalStub(structureTypeHandle, out marshalStub))
{
if (marshalStub != IntPtr.Zero)
{
InteropExtensions.PinObjectAndCall(structure,
unboxedStructPtr =>
{
CalliIntrinsics.Call<int>(
marshalStub,
((void*)((IntPtr*)unboxedStructPtr + offset)), // safe (need to adjust offset as it could be class)
(void*)ptr // unsafe (no need to adjust as it is always struct)
);
});
return;
}
else
{
isBlittable = true;
}
}
if (isBlittable || structureTypeHandle.IsBlittable()) // blittable
{
int structSize = Marshal.SizeOf(structure);
InteropExtensions.PinObjectAndCall(structure,
unboxedStructPtr =>
{
InteropExtensions.Memcpy(
ptr, // unsafe (no need to adjust as it is always struct)
(IntPtr)((IntPtr*)unboxedStructPtr + offset), // safe (need to adjust offset as it could be class)
structSize
);
});
return;
}
throw new MissingInteropDataException(SR.StructMarshalling_MissingInteropData, structure.GetType());
}
public static void StructureToPtr<T>(T structure, IntPtr ptr, bool fDeleteOld)
{
StructureToPtr((object)structure, ptr, fDeleteOld);
}
//====================================================================
// DestroyStructure()
//
//====================================================================
public static void DestroyStructure(IntPtr ptr, Type structuretype)
{
if (ptr == IntPtr.Zero)
throw new ArgumentNullException(nameof(ptr));
if (structuretype == null)
throw new ArgumentNullException(nameof(structuretype));
RuntimeTypeHandle structureTypeHandle = structuretype.TypeHandle;
if (structureTypeHandle.IsGenericType() || structureTypeHandle.IsGenericTypeDefinition())
throw new ArgumentException(SR.Argument_NeedNonGenericType, "t");
if (structureTypeHandle.IsEnum() ||
structureTypeHandle.IsInterface() ||
InteropExtensions.AreTypesAssignable(typeof(Delegate).TypeHandle, structureTypeHandle))
{
throw new ArgumentException(SR.Argument_MustHaveLayoutOrBeBlittable, structureTypeHandle.GetDisplayName());
}
DestroyStructureHelper(ptr, structuretype);
}
private static unsafe void DestroyStructureHelper(IntPtr ptr, Type structuretype)
{
RuntimeTypeHandle structureTypeHandle = structuretype.TypeHandle;
// Boxed struct start at offset 1 (EEType* at offset 0) while class start at offset 0
int offset = structureTypeHandle.IsValueType() ? 1 : 0;
if (structureTypeHandle.IsBlittable())
{
// ok to call with blittable structure, but no work to do in this case.
return;
}
IntPtr destroyStructureStub;
bool hasInvalidLayout;
if (RuntimeInteropData.Instance.TryGetDestroyStructureStub(structureTypeHandle, out destroyStructureStub, out hasInvalidLayout))
{
if (hasInvalidLayout)
throw new ArgumentException(SR.Argument_MustHaveLayoutOrBeBlittable, structureTypeHandle.GetDisplayName());
// DestroyStructureStub == IntPtr.Zero means its fields don't need to be destroied
if (destroyStructureStub != IntPtr.Zero)
{
CalliIntrinsics.Call<int>(
destroyStructureStub,
(void*)ptr // unsafe (no need to adjust as it is always struct)
);
}
return;
}
// Didn't find struct marshal data
throw new MissingInteropDataException(SR.StructMarshalling_MissingInteropData, structuretype);
}
public static void DestroyStructure<T>(IntPtr ptr)
{
DestroyStructure(ptr, typeof(T));
}
public static IntPtr GetComInterfaceForObject<T, TInterface>(T o)
{
return GetComInterfaceForObject(o, typeof(TInterface));
}
public static IntPtr /* IUnknown* */ GetComInterfaceForObject(Object o, Type T)
{
if (o == null)
throw new ArgumentNullException(nameof(o));
if (T == null)
throw new ArgumentNullException(nameof(T));
return McgMarshal.ObjectToComInterface(o, T.TypeHandle);
}
public static TDelegate GetDelegateForFunctionPointer<TDelegate>(IntPtr ptr)
{
return (TDelegate)(object)GetDelegateForFunctionPointer(ptr, typeof(TDelegate));
}
public static Delegate GetDelegateForFunctionPointer(IntPtr ptr, Type t)
{
// Validate the parameters
if (ptr == IntPtr.Zero)
throw new ArgumentNullException(nameof(ptr));
if (t == null)
throw new ArgumentNullException(nameof(t));
if (t.TypeHandle.IsGenericType() || t.TypeHandle.IsGenericTypeDefinition())
throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(t));
bool isDelegateType = InteropExtensions.AreTypesAssignable(t.TypeHandle, typeof(Delegate).TypeHandle);
if (!isDelegateType)
throw new ArgumentException(SR.Arg_MustBeDelegateType, nameof(t));
return McgMarshal.GetPInvokeDelegateForStub(ptr, t.TypeHandle);
}
//====================================================================
// GetNativeVariantForObject()
//
//====================================================================
public static void GetNativeVariantForObject<T>(T obj, IntPtr pDstNativeVariant)
{
GetNativeVariantForObject((object)obj, pDstNativeVariant);
}
public static unsafe void GetNativeVariantForObject(Object obj, /* VARIANT * */ IntPtr pDstNativeVariant)
{
// Obsolete
if (pDstNativeVariant == IntPtr.Zero)
throw new ArgumentNullException(nameof(pDstNativeVariant));
if (obj != null && (obj.GetType().TypeHandle.IsGenericType() || obj.GetType().TypeHandle.IsGenericTypeDefinition()))
throw new ArgumentException(SR.Argument_NeedNonGenericObject, nameof(obj));
Variant* pVariant = (Variant*)pDstNativeVariant;
*pVariant = new Variant(obj);
}
//====================================================================
// GetObjectForNativeVariant()
//
//====================================================================
public static unsafe T GetObjectForNativeVariant<T>(IntPtr pSrcNativeVariant)
{
return (T)GetObjectForNativeVariant(pSrcNativeVariant);
}
public static unsafe Object GetObjectForNativeVariant(/* VARIANT * */ IntPtr pSrcNativeVariant)
{
// Obsolete
if (pSrcNativeVariant == IntPtr.Zero)
throw new ArgumentNullException(nameof(pSrcNativeVariant));
Variant* pNativeVar = (Variant*)pSrcNativeVariant;
return pNativeVar->ToObject();
}
//====================================================================
// GetObjectsForNativeVariants()
//
//====================================================================
public static unsafe Object[] GetObjectsForNativeVariants(IntPtr aSrcNativeVariant, int cVars)
{
// Obsolete
if (aSrcNativeVariant == IntPtr.Zero)
throw new ArgumentNullException(nameof(aSrcNativeVariant));
if (cVars < 0)
throw new ArgumentOutOfRangeException(nameof(cVars), SR.ArgumentOutOfRange_NeedNonNegNum);
Object[] obj = new Object[cVars];
IntPtr aNativeVar = aSrcNativeVariant;
for (int i = 0; i < cVars; i++)
{
obj[i] = GetObjectForNativeVariant(aNativeVar);
aNativeVar = aNativeVar + sizeof(Variant);
}
return obj;
}
public static T[] GetObjectsForNativeVariants<T>(IntPtr aSrcNativeVariant, int cVars)
{
object[] objects = GetObjectsForNativeVariants(aSrcNativeVariant, cVars);
T[] result = null;
if (objects != null)
{
result = new T[objects.Length];
Array.Copy(objects, result, objects.Length);
}
return result;
}
//====================================================================
// UnsafeAddrOfPinnedArrayElement()
//
// IMPORTANT NOTICE: This method does not do any verification on the
// array. It must be used with EXTREME CAUTION since passing in
// an array that is not pinned or in the fixed heap can cause
// unexpected results !
//====================================================================
public static IntPtr UnsafeAddrOfPinnedArrayElement(Array arr, int index)
{
return PInvokeMarshal.UnsafeAddrOfPinnedArrayElement(arr, index);
}
public static IntPtr UnsafeAddrOfPinnedArrayElement<T>(T[] arr, int index)
{
return PInvokeMarshal.UnsafeAddrOfPinnedArrayElement(arr, index);
}
//====================================================================
// This method binds to the specified moniker.
//====================================================================
public static Object BindToMoniker(String monikerName)
{
#if TARGET_CORE_API_SET // BindMoniker not available in core API set
throw new PlatformNotSupportedException();
#else
Object obj = null;
IBindCtx bindctx = null;
ExternalInterop.CreateBindCtx(0, out bindctx);
UInt32 cbEaten;
IMoniker pmoniker = null;
ExternalInterop.MkParseDisplayName(bindctx, monikerName, out cbEaten, out pmoniker);
ExternalInterop.BindMoniker(pmoniker, 0, ref Interop.COM.IID_IUnknown, out obj);
return obj;
#endif
}
#if ENABLE_WINRT
public static Type GetTypeFromCLSID(Guid clsid)
{
return Type.GetTypeFromCLSID(clsid);
}
//====================================================================
// Return a unique Object given an IUnknown. This ensures that you
// receive a fresh object (we will not look in the cache to match up this
// IUnknown to an already existing object). This is useful in cases
// where you want to be able to call ReleaseComObject on a RCW
// and not worry about other active uses of said RCW.
//====================================================================
public static Object GetUniqueObjectForIUnknown(IntPtr unknown)
{
throw new PlatformNotSupportedException();
}
public static bool AreComObjectsAvailableForCleanup()
{
throw new PlatformNotSupportedException();
}
public static IntPtr CreateAggregatedObject(IntPtr pOuter, Object o)
{
throw new PlatformNotSupportedException();
}
public static IntPtr CreateAggregatedObject<T>(IntPtr pOuter, T o)
{
return CreateAggregatedObject(pOuter, (object)o);
}
public static Object CreateWrapperOfType(Object o, Type t)
{
throw new PlatformNotSupportedException();
}
public static TWrapper CreateWrapperOfType<T, TWrapper>(T o)
{
return (TWrapper)CreateWrapperOfType(o, typeof(TWrapper));
}
public static IntPtr /* IUnknown* */ GetComInterfaceForObject(Object o, Type T, CustomQueryInterfaceMode mode)
{
// Obsolete
throw new PlatformNotSupportedException();
}
public static int GetExceptionCode()
{
// Obsolete
throw new PlatformNotSupportedException();
}
/// <summary>
/// <para>Returns the first valid COM slot that GetMethodInfoForSlot will work on
/// This will be 3 for IUnknown based interfaces and 7 for IDispatch based interfaces. </para>
/// </summary>
public static int GetStartComSlot(Type t)
{
throw new PlatformNotSupportedException();
}
//====================================================================
// Given a managed object that wraps an ITypeInfo, return its name
//====================================================================
public static String GetTypeInfoName(ITypeInfo typeInfo)
{
throw new PlatformNotSupportedException();
}
#endif //ENABLE_WINRT
public static byte ReadByte(Object ptr, int ofs)
{
// Obsolete
throw new PlatformNotSupportedException("ReadByte");
}
public static short ReadInt16(Object ptr, int ofs)
{
// Obsolete
throw new PlatformNotSupportedException("ReadInt16");
}
public static int ReadInt32(Object ptr, int ofs)
{
// Obsolete
throw new PlatformNotSupportedException("ReadInt32");
}
public static long ReadInt64(Object ptr, int ofs)
{
// Obsolete
throw new PlatformNotSupportedException("ReadInt64");
}
public static void WriteByte(Object ptr, int ofs, byte val)
{
// Obsolete
throw new PlatformNotSupportedException("WriteByte");
}
public static void WriteInt16(Object ptr, int ofs, short val)
{
// Obsolete
throw new PlatformNotSupportedException("WriteInt16");
}
public static void WriteInt32(Object ptr, int ofs, int val)
{
// Obsolete
throw new PlatformNotSupportedException("WriteInt32");
}
public static void WriteInt64(Object ptr, int ofs, long val)
{
// Obsolete
throw new PlatformNotSupportedException("WriteInt64");
}
public static void ChangeWrapperHandleStrength(Object otp, bool fIsWeak)
{
throw new PlatformNotSupportedException("ChangeWrapperHandleStrength");
}
public static void CleanupUnusedObjectsInCurrentContext()
{
// RCW cleanup implemented in native code in CoreCLR, and uses a global list to indicate which objects need to be collected. In
// CoreRT, RCWs are implemented in managed code and their cleanup is normally accomplished using finalizers. Implementing
// this method in a more complicated way (without calling WaitForPendingFinalizers) is non-trivial because it possible for timing
// problems to occur when competing with finalizers.
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
}
public static void Prelink(MethodInfo m)
{
if (m == null)
throw new ArgumentNullException(nameof(m));
// Note: This method is effectively a no-op in ahead-of-time compilation scenarios. In CoreCLR and Desktop, this will pre-generate
// the P/Invoke, but everything is pre-generated in CoreRT.
}
public static void PrelinkAll(Type c)
{
if (c == null)
throw new ArgumentNullException(nameof(c));
MethodInfo[] mi = c.GetMethods();
if (mi != null)
{
for (int i = 0; i < mi.Length; i++)
{
Prelink(mi[i]);
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Xml;
using AlteryxRecordInfoNet;
using OmniBus.Framework.Factories;
using OmniBus.Framework.Interfaces;
using OmniBus.Framework.Serialisation;
namespace OmniBus.Framework
{
/// <summary>
/// Base Implementation of an <see cref="AlteryxRecordInfoNet.INetPlugin" />
/// </summary>
/// <typeparam name="TConfig">Configuration object for reading XML into.</typeparam>
public abstract class BaseEngine<TConfig> : INetPlugin, IBaseEngine
where TConfig : new()
{
private readonly IOutputHelperFactory _outputHelperFactory;
private readonly Dictionary<string, PropertyInfo> _inputs;
private readonly Dictionary<string, PropertyInfo> _outputs;
private Lazy<TConfig> _configObject;
private XmlElement _xmlConfig;
/// <summary>
/// Initializes a new instance of the <see cref="BaseEngine{T}" /> class.
/// </summary>
protected BaseEngine()
: this(new RecordCopierFactory(), new OutputHelperFactory())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BaseEngine{T}" /> class.
/// </summary>
/// <param name="recordCopierFactory">Factory to create copiers</param>
/// <param name="outputHelperFactory">Factory to create output helpers</param>
protected BaseEngine(IRecordCopierFactory recordCopierFactory, IOutputHelperFactory outputHelperFactory)
{
this.RecordCopierFactory = recordCopierFactory;
this._outputHelperFactory = outputHelperFactory;
var type = this.GetType();
this._inputs = type.GetProperties<IIncomingConnectionInterface>();
this._outputs = type.GetProperties<IOutputHelper>();
if (this._outputHelperFactory == null && this._outputs.Count > 0)
{
throw new ArgumentNullException(
nameof(outputHelperFactory),
"Tool has an output but no factory has been provided.");
}
}
/// <summary>
/// Gets the Alteryx engine.
/// </summary>
public EngineInterface Engine { get; private set; }
/// <summary>
/// Gets the tool identifier. Set at PI_Init, unset at PI_Close.
/// </summary>
public int NToolId { get; private set; }
/// <summary>
/// Gets the XML configuration from the work flow.
/// </summary>
public XmlElement XmlConfig
{
get => this._xmlConfig;
private set
{
this._xmlConfig = value;
this._configObject = new Lazy<TConfig>(this.CreateConfigObject);
}
}
/// <summary>
/// Gets the factory to create RecordCopiers
/// </summary>
protected IRecordCopierFactory RecordCopierFactory { get; }
/// <summary>
/// Gets the configuration object read from the XML node.
/// </summary>
/// <returns>Configuration Object</returns>
protected TConfig ConfigObject => this._configObject.Value;
/// <summary>
/// Called by Alteryx to initialize the plug in with configuration info.
/// </summary>
/// <param name="nToolId">Tool ID</param>
/// <param name="engineInterface">Connection to Alteryx Engine (for logging and so on).</param>
/// <param name="pXmlProperties">Configuration details</param>
public void PI_Init(int nToolId, EngineInterface engineInterface, XmlElement pXmlProperties)
{
this.NToolId = nToolId;
this.Engine = engineInterface;
this.XmlConfig = pXmlProperties;
foreach (var kvp in this._outputs)
{
kvp.Value.SetValue(this, this._outputHelperFactory.CreateOutputHelper(this, kvp.Key), null);
}
this.OnInitCalled();
this.DebugMessage("PI_Init Called");
}
/// <summary>
/// The PI_AddIncomingConnection function pointed to by this property will be called by the Alteryx Engine when an
/// incoming data connection is being made.
/// </summary>
/// <param name="pIncomingConnectionType">The name of connection given in GetInputConnections.</param>
/// <param name="pIncomingConnectionName">The name the user gave the connection.</param>
/// <returns>An <see cref="AlteryxRecordInfoNet.IIncomingConnectionInterface" /> set up to handle the connection.</returns>
public virtual IIncomingConnectionInterface PI_AddIncomingConnection(
string pIncomingConnectionType,
string pIncomingConnectionName)
{
if (!this._inputs.TryGetValue(pIncomingConnectionType, out PropertyInfo prop))
{
throw new KeyNotFoundException($"Unable to find input {pIncomingConnectionType}");
}
var input = prop.GetValue(this, null) as IIncomingConnectionInterface;
if (input == null)
{
throw new NullReferenceException($"{prop.Name} is null.");
}
return input;
}
/// <summary>
/// The PI_AddOutgoingConnection function pointed to by this property will be called by the Alteryx Engine when an
/// outgoing data connection is being made.
/// </summary>
/// <param name="pOutgoingConnectionName">
/// The name will be the name that you gave the connection in the
/// IPlugin.GetOutputConnections() method.
/// </param>
/// <param name="outgoingConnection">You will need to use the OutgoingConnection object to send your data downstream.</param>
/// <returns>True if the connection was handled successfully, false otherwise.</returns>
public virtual bool PI_AddOutgoingConnection(
string pOutgoingConnectionName,
OutgoingConnection outgoingConnection)
{
if (this._outputs.TryGetValue(pOutgoingConnectionName, out PropertyInfo prop)
&& prop.GetValue(this, null) is OutputHelper helper)
{
helper.AddConnection(outgoingConnection);
this.DebugMessage($"Added Outgoing Connection {pOutgoingConnectionName}");
return true;
}
return false;
}
/// <summary>
/// The PI_PushAllRecords function pointed to by this property will be called by the Alteryx Engine when the plugin
/// should provide all of it's data to the downstream tools.
/// This is only pertinent to tools which have no upstream (input) connections (such as the Input tool).
/// </summary>
/// <param name="nRecordLimit">
/// The nRecordLimit parameter will be < 0 to indicate that there is no limit, 0 to indicate
/// that the tool is being configured and no records should be sent, or > 0 to indicate that only the requested
/// number of records should be sent.
/// </param>
/// <returns>Return true to indicate you successfully handled the request.</returns>
public virtual bool PI_PushAllRecords(long nRecordLimit)
{
return true;
}
/// <summary>
/// The PI_Close function pointed to by this property will be called by the Alteryx Engine just prior to the
/// destruction of the tool object.
/// This is guaranteed to happen after all data has finished flowing through all the fields.
/// </summary>
/// <param name="bHasErrors">If the bHasErrors parameter is set to true, you would typically not do the final processing.</param>
public void PI_Close(bool bHasErrors)
{
this.DebugMessage("PI_Close Called.");
foreach (var kvp in this._outputs)
{
kvp.Value.SetValue(this, null, null);
}
this.XmlConfig = null;
this.Engine = null;
this.NToolId = 0;
}
/// <summary>
/// Tells Alteryx whether to show debug error messages or not.
/// </summary>
/// <returns>A value indicating whether to show debug error messages or not.</returns>
public virtual bool ShowDebugMessages() => false;
/// <summary>
/// Tell Alteryx execution is complete.
/// </summary>
public void ExecutionComplete()
{
this.DebugMessage("Output Complete.");
this.Message(string.Empty, MessageStatus.STATUS_Complete);
}
/// <summary>
/// Sends a Debug message to the Alteryx log window.
/// </summary>
/// <param name="message">Message text.</param>
public void DebugMessage(string message)
{
if (this.ShowDebugMessages())
{
this.Message(message);
}
}
/// <summary>
/// Sends a message to the Alteryx log window.
/// </summary>
/// <param name="message">Message text.</param>
/// <param name="messageStatus">Type of Message (defaults to Info)</param>
public void Message(string message, MessageStatus messageStatus = MessageStatus.STATUS_Info)
{
this.Engine?.OutputMessage(this.NToolId, messageStatus, message);
}
/// <summary>
/// Called after <see cref="PI_Init" /> is done.
/// </summary>
protected virtual void OnInitCalled()
{
}
/// <summary>
/// Create a Serialiser
/// </summary>
/// <returns><see cref="ISerialiser{TConfig}"/> to de-serialise object</returns>
protected virtual ISerialiser<TConfig> Serialiser()
=> new XmlSerialiser<TConfig>();
private TConfig CreateConfigObject()
{
var config = this.XmlConfig.SelectSingleNode("Configuration");
return this.Serialiser().Deserialise(config);
}
}
}
| |
// 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.
// TypeDelegator
//
// This class wraps a Type object and delegates all methods to that Type.
namespace System.Reflection {
using System;
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;
using CultureInfo = System.Globalization.CultureInfo;
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class TypeDelegator : TypeInfo
{
public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo){
if(typeInfo==null) return false;
return IsAssignableFrom(typeInfo.AsType());
}
protected Type typeImpl;
#if FEATURE_CORECLR
[System.Security.SecuritySafeCritical] // auto-generated
#endif
protected TypeDelegator() {}
public TypeDelegator(Type delegatingType) {
if (delegatingType == null)
throw new ArgumentNullException(nameof(delegatingType));
Contract.EndContractBlock();
typeImpl = delegatingType;
}
public override Guid GUID {
get {return typeImpl.GUID;}
}
public override int MetadataToken { get { return typeImpl.MetadataToken; } }
public override Object InvokeMember(String name,BindingFlags invokeAttr,Binder binder,Object target,
Object[] args,ParameterModifier[] modifiers,CultureInfo culture,String[] namedParameters)
{
return typeImpl.InvokeMember(name,invokeAttr,binder,target,args,modifiers,culture,namedParameters);
}
public override Module Module {
get {return typeImpl.Module;}
}
public override Assembly Assembly {
get {return typeImpl.Assembly;}
}
public override RuntimeTypeHandle TypeHandle {
get{return typeImpl.TypeHandle;}
}
public override String Name {
get{return typeImpl.Name;}
}
public override String FullName {
get{return typeImpl.FullName;}
}
public override String Namespace {
get{return typeImpl.Namespace;}
}
public override String AssemblyQualifiedName {
get {
return typeImpl.AssemblyQualifiedName;
}
}
public override Type BaseType {
get{return typeImpl.BaseType;}
}
protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr,Binder binder,
CallingConventions callConvention, Type[] types,ParameterModifier[] modifiers)
{
return typeImpl.GetConstructor(bindingAttr,binder,callConvention,types,modifiers);
}
[System.Runtime.InteropServices.ComVisible(true)]
public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr)
{
return typeImpl.GetConstructors(bindingAttr);
}
protected override MethodInfo GetMethodImpl(String name,BindingFlags bindingAttr,Binder binder,
CallingConventions callConvention, Type[] types,ParameterModifier[] modifiers)
{
// This is interesting there are two paths into the impl. One that validates
// type as non-null and one where type may be null.
if (types == null)
return typeImpl.GetMethod(name,bindingAttr);
else
return typeImpl.GetMethod(name,bindingAttr,binder,callConvention,types,modifiers);
}
public override MethodInfo[] GetMethods(BindingFlags bindingAttr)
{
return typeImpl.GetMethods(bindingAttr);
}
public override FieldInfo GetField(String name, BindingFlags bindingAttr)
{
return typeImpl.GetField(name,bindingAttr);
}
public override FieldInfo[] GetFields(BindingFlags bindingAttr)
{
return typeImpl.GetFields(bindingAttr);
}
public override Type GetInterface(String name, bool ignoreCase)
{
return typeImpl.GetInterface(name,ignoreCase);
}
public override Type[] GetInterfaces()
{
return typeImpl.GetInterfaces();
}
public override EventInfo GetEvent(String name,BindingFlags bindingAttr)
{
return typeImpl.GetEvent(name,bindingAttr);
}
public override EventInfo[] GetEvents()
{
return typeImpl.GetEvents();
}
protected override PropertyInfo GetPropertyImpl(String name,BindingFlags bindingAttr,Binder binder,
Type returnType, Type[] types, ParameterModifier[] modifiers)
{
if (returnType == null && types == null)
return typeImpl.GetProperty(name,bindingAttr);
else
return typeImpl.GetProperty(name,bindingAttr,binder,returnType,types,modifiers);
}
public override PropertyInfo[] GetProperties(BindingFlags bindingAttr)
{
return typeImpl.GetProperties(bindingAttr);
}
public override EventInfo[] GetEvents(BindingFlags bindingAttr)
{
return typeImpl.GetEvents(bindingAttr);
}
public override Type[] GetNestedTypes(BindingFlags bindingAttr)
{
return typeImpl.GetNestedTypes(bindingAttr);
}
public override Type GetNestedType(String name, BindingFlags bindingAttr)
{
return typeImpl.GetNestedType(name,bindingAttr);
}
public override MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr)
{
return typeImpl.GetMember(name,type,bindingAttr);
}
public override MemberInfo[] GetMembers(BindingFlags bindingAttr)
{
return typeImpl.GetMembers(bindingAttr);
}
protected override TypeAttributes GetAttributeFlagsImpl()
{
return typeImpl.Attributes;
}
protected override bool IsArrayImpl()
{
return typeImpl.IsArray;
}
protected override bool IsPrimitiveImpl()
{
return typeImpl.IsPrimitive;
}
protected override bool IsByRefImpl()
{
return typeImpl.IsByRef;
}
protected override bool IsPointerImpl()
{
return typeImpl.IsPointer;
}
protected override bool IsValueTypeImpl()
{
return typeImpl.IsValueType;
}
protected override bool IsCOMObjectImpl()
{
return typeImpl.IsCOMObject;
}
public override bool IsConstructedGenericType
{
get
{
return typeImpl.IsConstructedGenericType;
}
}
public override Type GetElementType()
{
return typeImpl.GetElementType();
}
protected override bool HasElementTypeImpl()
{
return typeImpl.HasElementType;
}
public override Type UnderlyingSystemType
{
get {return typeImpl.UnderlyingSystemType;}
}
// ICustomAttributeProvider
public override Object[] GetCustomAttributes(bool inherit)
{
return typeImpl.GetCustomAttributes(inherit);
}
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
return typeImpl.GetCustomAttributes(attributeType, inherit);
}
public override bool IsDefined(Type attributeType, bool inherit)
{
return typeImpl.IsDefined(attributeType, inherit);
}
[System.Runtime.InteropServices.ComVisible(true)]
public override InterfaceMapping GetInterfaceMap(Type interfaceType)
{
return typeImpl.GetInterfaceMap(interfaceType);
}
}
}
| |
using UnityEngine;
using System;
namespace Cinemachine
{
/// <summary>
/// A Cinemachine Virtual Camera Body component that constrains camera motion
/// to a CinemachinePath. The camera can move along the path.
///
/// This behaviour can operate in two modes: manual positioning, and Auto-Dolly positioning.
/// In Manual mode, the camera's position is specified by animating the Path Position field.
/// In Auto-Dolly mode, the Path Position field is animated automatically every frame by finding
/// the position on the path that's closest to the virtual camera's Follow target.
/// </summary>
[DocumentationSorting(7, DocumentationSortingAttribute.Level.UserRef)]
[AddComponentMenu("")] // Don't display in add component menu
[RequireComponent(typeof(CinemachinePipeline))]
[SaveDuringPlay]
public class CinemachineTrackedDolly : MonoBehaviour, ICinemachineComponent
{
/// <summary>The path to which the camera will be constrained. This must be non-null.</summary>
[Tooltip("The path to which the camera will be constrained. This must be non-null.")]
public CinemachinePathBase m_Path;
/// <summary>The position along the path at which the camera will be placed.
/// This can be animated directly, or set automatically by the Auto-Dolly feature
/// to get as close as possible to the Follow target.</summary>
[Tooltip("The position along the path at which the camera will be placed. This can be animated directly, or set automatically by the Auto-Dolly feature to get as close as possible to the Follow target. Values are as follows: 0 represents the first waypoint on the path, 1 is the second, and so on. Values in-between are points on the path in between the waypoints.")]
public float m_PathPosition;
/// <summary>Where to put the camera realtive to the path postion. X is perpendicular to the path, Y is up, and Z is parallel to the path.</summary>
[Tooltip("Where to put the camera relative to the path position. X is perpendicular to the path, Y is up, and Z is parallel to the path. This allows the camera to be offset from the path itself (as if on a tripod, for example).")]
public Vector3 m_PathOffset = Vector3.zero;
/// <summary>How aggressively the camera tries to maintain the offset perpendicular to the path.
/// Small numbers are more responsive, rapidly translating the camera to keep the target's
/// x-axis offset. Larger numbers give a more heavy slowly responding camera.
/// Using different settings per axis can yield a wide range of camera behaviors</summary>
[Range(0f, 20f)]
[Tooltip("How aggressively the camera tries to maintain its position in a direction perpendicular to the path. Small numbers are more responsive, rapidly translating the camera to keep the target's x-axis offset. Larger numbers give a more heavy slowly responding camera. Using different settings per axis can yield a wide range of camera behaviors.")]
public float m_XDamping = 0f;
/// <summary>How aggressively the camera tries to maintain the offset in the path-local up direction.
/// Small numbers are more responsive, rapidly translating the camera to keep the target's
/// y-axis offset. Larger numbers give a more heavy slowly responding camera.
/// Using different settings per axis can yield a wide range of camera behaviors</summary>
[Range(0f, 20f)]
[Tooltip("How aggressively the camera tries to maintain its position in the path-local up direction. Small numbers are more responsive, rapidly translating the camera to keep the target's y-axis offset. Larger numbers give a more heavy slowly responding camera. Using different settings per axis can yield a wide range of camera behaviors.")]
public float m_YDamping = 0f;
/// <summary>How aggressively the camera tries to maintain the offset parallel to the path.
/// Small numbers are more responsive, rapidly translating the camera to keep the
/// target's z-axis offset. Larger numbers give a more heavy slowly responding camera.
/// Using different settings per axis can yield a wide range of camera behaviors</summary>
[Range(0f, 20f)]
[Tooltip("How aggressively the camera tries to maintain its position in a direction parallel to the path. Small numbers are more responsive, rapidly translating the camera to keep the target's z-axis offset. Larger numbers give a more heavy slowly responding camera. Using different settings per axis can yield a wide range of camera behaviors.")]
public float m_ZDamping = 1f;
/// <summary>Different ways to set the camera's up vector</summary>
[DocumentationSorting(7.1f, DocumentationSortingAttribute.Level.UserRef)]
public enum CameraUpMode
{
/// <summary>Leave the camera's up vector alone</summary>
Default,
/// <summary>Take the up vector from the path's up vector at the current point</summary>
Path,
/// <summary>Take the up vector from the path's up vector at the current point, but with the roll zeroed out</summary>
PathNoRoll,
/// <summary>Take the up vector from the Follow target's up vector</summary>
FollowTarget,
/// <summary>Take the up vector from the Follow target's up vector, but with the roll zeroed out</summary>
FollowTargetNoRoll,
};
/// <summary>How to set the virtual camera's Up vector. This will affect the screen composition.</summary>
[Tooltip("How to set the virtual camera's Up vector. This will affect the screen composition, because the camera Aim behaviours will always try to respect the Up direction.")]
public CameraUpMode m_CameraUp = CameraUpMode.Default;
/// <summary>Controls how automatic dollying occurs</summary>
[DocumentationSorting(7.2f, DocumentationSortingAttribute.Level.UserRef)]
[Serializable]
public struct AutoDolly
{
/// <summary>If checked, will enable automatic dolly, which chooses a path position
/// that is as close as possible to the Follow target.</summary>
[Tooltip("If checked, will enable automatic dolly, which chooses a path position that is as close as possible to the Follow target. Note: this can have significant performance impact")]
public bool m_Enabled;
/// <summary>How many segments on either side of the current segment. Use 0 for Entire path</summary>
[Tooltip("How many segments on either side of the current segment. Use 0 for Entire path.")]
public int m_SearchRadius;
/// <summary>We search a segment by dividing it into this many straight pieces.
/// The higher the number, the more accurate the result, but performance is
/// proportionally slower for higher numbers</summary>
[Tooltip("We search a segment by dividing it into this many straight pieces. The higher the number, the more accurate the result, but performance is proportionally slower for higher numbers")]
public int m_StepsPerSegment;
/// <summary>Constructor with specific field values</summary>
public AutoDolly(
bool enabled, int searchRadius, int stepsPerSegment,
float waitTime, float maxSpeed,
float accelTime, float decelTime)
{
m_Enabled = enabled;
m_SearchRadius = searchRadius;
m_StepsPerSegment = stepsPerSegment;
}
};
/// <summary>Controls how automatic dollying occurs</summary>
[Tooltip("Controls how automatic dollying occurs. A Follow target is necessary to use this feature.")]
public AutoDolly m_AutoDolly = new AutoDolly(false, 2, 5, 0, 2f, 1, 1);
/// <summary>True if component is enabled and has a path</summary>
public bool IsValid { get { return enabled && m_Path != null; } }
/// <summary>Get the Cinemachine Virtual Camera affected by this component</summary>
public ICinemachineCamera VirtualCamera
{ get { return gameObject.transform.parent.gameObject.GetComponent<ICinemachineCamera>(); } }
/// <summary>Get the Cinemachine Pipeline stage that this component implements.
/// Always returns the Body stage</summary>
public CinemachineCore.Stage Stage { get { return CinemachineCore.Stage.Body; } }
/// <summary>Positions the virtual camera according to the transposer rules.</summary>
/// <param name="curState">The current camera state</param>
/// <param name="statePrevFrame">The camera state on the previous frame (unused)</param>
/// <param name="deltaTime">Used for damping. If 0 or less, no damping is done.</param>
/// <returns>curState with new RawPosition</returns>
public CameraState MutateCameraState(
CameraState curState, CameraState statePrevFrame, float deltaTime)
{
if (!IsValid)
return curState;
if (deltaTime <= 0)
m_PreviousPathPosition = m_PathPosition;
CameraState newState = curState;
// Get the new ideal path base position
if (m_AutoDolly.m_Enabled)
m_PathPosition = PerformAutoDolly(m_PreviousPathPosition, deltaTime);
float newPathPosition = m_PathPosition;
if (deltaTime > 0)
{
// Normalize previous position to find the shortest path
if (m_Path.MaxPos > 0)
{
float prev = m_Path.NormalizePos(m_PreviousPathPosition);
float next = m_Path.NormalizePos(newPathPosition);
if (m_Path.Looped && Mathf.Abs(next - prev) > m_Path.MaxPos / 2)
{
if (next > prev)
prev += m_Path.MaxPos;
else
prev -= m_Path.MaxPos;
}
m_PreviousPathPosition = prev;
newPathPosition = next;
}
// Apply damping along the path direction
float offset = m_PreviousPathPosition - newPathPosition;
offset *= deltaTime / Mathf.Max(m_ZDamping * kDampingScale, deltaTime);
newPathPosition = m_PreviousPathPosition - offset;
}
m_PreviousPathPosition = newPathPosition;
Quaternion newPathOrientation = m_Path.EvaluateOrientation(newPathPosition);
// Apply the offset to get the new camera position
Vector3 newCameraPos = m_Path.EvaluatePosition(newPathPosition);
Vector3[] offsetDir = new Vector3[3];
offsetDir[2] = newPathOrientation * Vector3.forward;
offsetDir[1] = newPathOrientation * Vector3.up;
offsetDir[0] = Vector3.Cross(offsetDir[1], offsetDir[2]);
for (int i = 0; i < 3; ++i)
newCameraPos += m_PathOffset[i] * offsetDir[i];
// Apply damping to the remaining directions
if (deltaTime > 0)
{
Vector3 currentCameraPos = statePrevFrame.RawPosition;
Vector3 delta = (currentCameraPos - newCameraPos);
Vector3 delta1 = Vector3.Dot(delta, offsetDir[1]) * offsetDir[1];
Vector3 delta0 = delta - delta1;
delta = delta0 * deltaTime / Mathf.Max(m_XDamping * kDampingScale, deltaTime)
+ delta1 * deltaTime / Mathf.Max(m_YDamping * kDampingScale, deltaTime);
newCameraPos = currentCameraPos - delta;
}
newState.RawPosition = newCameraPos;
// Set the up
switch (m_CameraUp)
{
default:
case CameraUpMode.Default:
break;
case CameraUpMode.Path:
newState.ReferenceUp = newPathOrientation * Vector3.up;
newState.RawOrientation = newPathOrientation;
break;
case CameraUpMode.PathNoRoll:
newState.RawOrientation = Quaternion.LookRotation(
newPathOrientation * Vector3.forward, Vector3.up);
newState.ReferenceUp = newState.RawOrientation * Vector3.up;
break;
case CameraUpMode.FollowTarget:
if (VirtualCamera.Follow != null)
{
newState.RawOrientation = VirtualCamera.Follow.rotation;
newState.ReferenceUp = newState.RawOrientation * Vector3.up;
}
break;
case CameraUpMode.FollowTargetNoRoll:
if (VirtualCamera.Follow != null)
{
newState.RawOrientation = Quaternion.LookRotation(
VirtualCamera.Follow.rotation * Vector3.forward, Vector3.up);
newState.ReferenceUp = newState.RawOrientation * Vector3.up;
}
break;
}
return newState;
}
private const float kDampingScale = 0.1f;
private float m_PreviousPathPosition = 0;
float PerformAutoDolly(float currentPos, float deltaTime)
{
if (m_AutoDolly.m_Enabled && VirtualCamera.Follow != null)
{
float pos = m_Path.FindClosestPoint(
VirtualCamera.Follow.transform.position,
Mathf.FloorToInt(currentPos),
(deltaTime <= 0 || m_AutoDolly.m_SearchRadius <= 0) ? -1 : m_AutoDolly.m_SearchRadius,
m_AutoDolly.m_StepsPerSegment);
return pos;
}
return m_PathPosition;
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using OpenMetaverse;
using OpenSim.Framework;
namespace OpenSim.Region.ClientStack.LindenUDP
{
/// <summary>
/// A work in progress, to contain the SL specific file transfer code that is currently in various region modules
/// This file currently contains multiple classes that need to be split out into their own files.
/// </summary>
public class LLFileTransfer : IClientFileTransfer
{
protected IClientAPI m_clientAPI;
/// Dictionary of handlers for uploading files from client
/// TODO: Need to add cleanup code to remove handlers that have completed their upload
protected Dictionary<ulong, XferUploadHandler> m_uploadHandlers;
protected object m_uploadHandlersLock = new object();
/// <summary>
/// Dictionary of files ready to be sent to clients
/// </summary>
protected static Dictionary<string, byte[]> m_files;
/// <summary>
/// Dictionary of Download Transfers in progess
/// </summary>
protected Dictionary<ulong, XferDownloadHandler> m_downloadHandlers = new Dictionary<ulong, XferDownloadHandler>();
public LLFileTransfer(IClientAPI clientAPI)
{
m_uploadHandlers = new Dictionary<ulong, XferUploadHandler>();
m_clientAPI = clientAPI;
m_clientAPI.OnXferReceive += XferReceive;
m_clientAPI.OnAbortXfer += AbortXferUploadHandler;
}
public void Close()
{
if (m_clientAPI != null)
{
m_clientAPI.OnXferReceive -= XferReceive;
m_clientAPI.OnAbortXfer -= AbortXferUploadHandler;
m_clientAPI = null;
}
}
#region Upload Handling
public bool RequestUpload(string clientFileName, UploadComplete uploadCompleteCallback, UploadAborted abortCallback)
{
if ((String.IsNullOrEmpty(clientFileName)) || (uploadCompleteCallback == null))
{
return false;
}
XferUploadHandler uploader = new XferUploadHandler(m_clientAPI, clientFileName);
return StartUpload(uploader, uploadCompleteCallback, abortCallback);
}
public bool RequestUpload(UUID fileID, UploadComplete uploadCompleteCallback, UploadAborted abortCallback)
{
if ((fileID == UUID.Zero) || (uploadCompleteCallback == null))
{
return false;
}
XferUploadHandler uploader = new XferUploadHandler(m_clientAPI, fileID);
return StartUpload(uploader, uploadCompleteCallback, abortCallback);
}
private bool StartUpload(XferUploadHandler uploader, UploadComplete uploadCompleteCallback, UploadAborted abortCallback)
{
uploader.UploadDone += uploadCompleteCallback;
uploader.UploadDone += RemoveXferUploadHandler;
if (abortCallback != null)
{
uploader.UploadAborted += abortCallback;
}
lock (m_uploadHandlersLock)
{
if (!m_uploadHandlers.ContainsKey(uploader.XferID))
{
m_uploadHandlers.Add(uploader.XferID, uploader);
uploader.RequestStartXfer(m_clientAPI);
return true;
}
else
{
// something went wrong with the xferID allocation
uploader.UploadDone -= uploadCompleteCallback;
uploader.UploadDone -= RemoveXferUploadHandler;
if (abortCallback != null)
{
uploader.UploadAborted -= abortCallback;
}
return false;
}
}
}
protected void AbortXferUploadHandler(IClientAPI remoteClient, ulong xferID)
{
lock (m_uploadHandlersLock)
{
if (m_uploadHandlers.ContainsKey(xferID))
{
m_uploadHandlers[xferID].AbortUpload(remoteClient);
m_uploadHandlers.Remove(xferID);
}
}
}
protected void XferReceive(IClientAPI remoteClient, ulong xferID, uint packetID, byte[] data)
{
lock (m_uploadHandlersLock)
{
if (m_uploadHandlers.ContainsKey(xferID))
{
m_uploadHandlers[xferID].XferReceive(remoteClient, xferID, packetID, data);
}
}
}
protected void RemoveXferUploadHandler(string filename, UUID fileID, ulong transferID, byte[] fileData, IClientAPI remoteClient)
{
}
#endregion
}
public class XferUploadHandler
{
private AssetBase m_asset;
public event UploadComplete UploadDone;
public event UploadAborted UploadAborted;
private sbyte type = 0;
public ulong mXferID;
private UploadComplete handlerUploadDone;
private UploadAborted handlerAbort;
private bool m_complete = false;
public bool UploadComplete
{
get { return m_complete; }
}
public XferUploadHandler(IClientAPI pRemoteClient, string pClientFilename)
{
Initialize(UUID.Zero, pClientFilename);
}
public XferUploadHandler(IClientAPI pRemoteClient, UUID fileID)
{
Initialize(fileID, String.Empty);
}
private void Initialize(UUID fileID, string fileName)
{
m_asset = new AssetBase(fileID, fileName, type, UUID.Zero.ToString());
m_asset.Data = new byte[0];
m_asset.Description = "empty";
m_asset.Local = true;
m_asset.Temporary = true;
mXferID = Util.GetNextXferID();
}
public ulong XferID
{
get { return mXferID; }
}
public void RequestStartXfer(IClientAPI pRemoteClient)
{
//m_asset.Metadata.CreatorID = pRemoteClient.AgentId.ToString();
if (!String.IsNullOrEmpty(m_asset.Name))
{
pRemoteClient.SendXferRequest(mXferID, m_asset.Type, m_asset.FullID, 0, Utils.StringToBytes(m_asset.Name));
}
else
{
pRemoteClient.SendXferRequest(mXferID, m_asset.Type, m_asset.FullID, 0, new byte[0]);
}
}
/// <summary>
/// Process transfer data received from the client.
/// </summary>
/// <param name="xferID"></param>
/// <param name="packetID"></param>
/// <param name="data"></param>
public void XferReceive(IClientAPI remoteClient, ulong xferID, uint packetID, byte[] data)
{
if (mXferID == xferID)
{
if (m_asset.Data.Length > 1)
{
byte[] destinationArray = new byte[m_asset.Data.Length + data.Length];
Array.Copy(m_asset.Data, 0, destinationArray, 0, m_asset.Data.Length);
Array.Copy(data, 0, destinationArray, m_asset.Data.Length, data.Length);
m_asset.Data = destinationArray;
}
else
{
byte[] buffer2 = new byte[data.Length - 4];
Array.Copy(data, 4, buffer2, 0, data.Length - 4);
m_asset.Data = buffer2;
}
remoteClient.SendConfirmXfer(xferID, packetID);
if ((packetID & 0x80000000) != 0)
{
SendCompleteMessage(remoteClient);
}
}
}
protected void SendCompleteMessage(IClientAPI remoteClient)
{
m_complete = true;
handlerUploadDone = UploadDone;
if (handlerUploadDone != null)
{
handlerUploadDone(m_asset.Name, m_asset.FullID, mXferID, m_asset.Data, remoteClient);
}
}
public void AbortUpload(IClientAPI remoteClient)
{
handlerAbort = UploadAborted;
if (handlerAbort != null)
{
handlerAbort(m_asset.Name, m_asset.FullID, mXferID, remoteClient);
}
}
}
public class XferDownloadHandler
{
public IClientAPI Client;
private bool complete;
public byte[] Data = new byte[0];
public int DataPointer = 0;
public string FileName = String.Empty;
public uint Packet = 0;
public uint Serial = 1;
public ulong XferID = 0;
public XferDownloadHandler(string fileName, byte[] data, ulong xferID, IClientAPI client)
{
FileName = fileName;
Data = data;
XferID = xferID;
Client = client;
}
public XferDownloadHandler()
{
}
/// <summary>
/// Start a transfer
/// </summary>
/// <returns>True if the transfer is complete, false if not</returns>
public bool StartSend()
{
if (Data.Length < 1000)
{
// for now (testing) we only support files under 1000 bytes
byte[] transferData = new byte[Data.Length + 4];
Array.Copy(Utils.IntToBytes(Data.Length), 0, transferData, 0, 4);
Array.Copy(Data, 0, transferData, 4, Data.Length);
Client.SendXferPacket(XferID, 0 + 0x80000000, transferData);
complete = true;
}
else
{
byte[] transferData = new byte[1000 + 4];
Array.Copy(Utils.IntToBytes(Data.Length), 0, transferData, 0, 4);
Array.Copy(Data, 0, transferData, 4, 1000);
Client.SendXferPacket(XferID, 0, transferData);
Packet++;
DataPointer = 1000;
}
return complete;
}
/// <summary>
/// Respond to an ack packet from the client
/// </summary>
/// <param name="packet"></param>
/// <returns>True if the transfer is complete, false otherwise</returns>
public bool AckPacket(uint packet)
{
if (!complete)
{
if ((Data.Length - DataPointer) > 1000)
{
byte[] transferData = new byte[1000];
Array.Copy(Data, DataPointer, transferData, 0, 1000);
Client.SendXferPacket(XferID, Packet, transferData);
Packet++;
DataPointer += 1000;
}
else
{
byte[] transferData = new byte[Data.Length - DataPointer];
Array.Copy(Data, DataPointer, transferData, 0, Data.Length - DataPointer);
uint endPacket = Packet |= (uint)0x80000000;
Client.SendXferPacket(XferID, endPacket, transferData);
Packet++;
DataPointer += (Data.Length - DataPointer);
complete = true;
}
}
return complete;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Cryptography.Apple;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Win32.SafeHandles;
internal static partial class Interop
{
internal static partial class AppleCrypto
{
[DllImport(Libraries.AppleCryptoNative)]
private static extern int AppleCryptoNative_X509ImportCertificate(
byte[] pbKeyBlob,
int cbKeyBlob,
X509ContentType contentType,
SafeCreateHandle cfPfxPassphrase,
SafeKeychainHandle tmpKeychain,
int exportable,
out SafeSecCertificateHandle pCertOut,
out SafeSecIdentityHandle pPrivateKeyOut,
out int pOSStatus);
[DllImport(Libraries.AppleCryptoNative)]
private static extern int AppleCryptoNative_X509ImportCollection(
byte[] pbKeyBlob,
int cbKeyBlob,
X509ContentType contentType,
SafeCreateHandle cfPfxPassphrase,
SafeKeychainHandle tmpKeychain,
int exportable,
out SafeCFArrayHandle pCollectionOut,
out int pOSStatus);
[DllImport(Libraries.AppleCryptoNative)]
private static extern int AppleCryptoNative_X509GetRawData(
SafeSecCertificateHandle cert,
out SafeCFDataHandle cfDataOut,
out int pOSStatus);
[DllImport(Libraries.AppleCryptoNative)]
private static extern int AppleCryptoNative_X509GetPublicKey(SafeSecCertificateHandle cert, out SafeSecKeyRefHandle publicKey, out int pOSStatus);
[DllImport(Libraries.AppleCryptoNative, EntryPoint = "AppleCryptoNative_X509GetContentType")]
internal static extern X509ContentType X509GetContentType(byte[] pbData, int cbData);
[DllImport(Libraries.AppleCryptoNative)]
private static extern int AppleCryptoNative_X509CopyCertFromIdentity(
SafeSecIdentityHandle identity,
out SafeSecCertificateHandle cert);
[DllImport(Libraries.AppleCryptoNative)]
private static extern int AppleCryptoNative_X509CopyPrivateKeyFromIdentity(
SafeSecIdentityHandle identity,
out SafeSecKeyRefHandle key);
[DllImport(Libraries.AppleCryptoNative)]
private static extern int AppleCryptoNative_X509DemuxAndRetainHandle(
IntPtr handle,
out SafeSecCertificateHandle certHandle,
out SafeSecIdentityHandle identityHandle);
[DllImport(Libraries.AppleCryptoNative)]
private static extern int AppleCryptoNative_X509ExportData(
SafeCreateHandle data,
X509ContentType type,
SafeCreateHandle cfExportPassphrase,
out SafeCFDataHandle pExportOut,
out int pOSStatus);
[DllImport(Libraries.AppleCryptoNative)]
private static extern int AppleCryptoNative_X509CopyWithPrivateKey(
SafeSecCertificateHandle certHandle,
SafeSecKeyRefHandle privateKeyHandle,
SafeKeychainHandle targetKeychain,
out SafeSecIdentityHandle pIdentityHandleOut,
out int pOSStatus);
internal static byte[] X509GetRawData(SafeSecCertificateHandle cert)
{
int osStatus;
SafeCFDataHandle data;
int ret = AppleCryptoNative_X509GetRawData(
cert,
out data,
out osStatus);
if (ret == 1)
{
return CoreFoundation.CFGetData(data);
}
if (ret == 0)
{
throw CreateExceptionForOSStatus(osStatus);
}
Debug.Fail($"Unexpected return value {ret}");
throw new CryptographicException();
}
internal static SafeSecCertificateHandle X509ImportCertificate(
byte[] bytes,
X509ContentType contentType,
SafePasswordHandle importPassword,
SafeKeychainHandle keychain,
bool exportable,
out SafeSecIdentityHandle identityHandle)
{
SafeSecCertificateHandle certHandle;
int osStatus;
int ret;
SafeCreateHandle cfPassphrase = s_nullExportString;
bool releasePassword = false;
try
{
if (!importPassword.IsInvalid)
{
importPassword.DangerousAddRef(ref releasePassword);
IntPtr passwordHandle = importPassword.DangerousGetHandle();
if (passwordHandle != IntPtr.Zero)
{
cfPassphrase = CoreFoundation.CFStringCreateWithCString(passwordHandle);
}
}
ret = AppleCryptoNative_X509ImportCertificate(
bytes,
bytes.Length,
contentType,
cfPassphrase,
keychain,
exportable ? 1 : 0,
out certHandle,
out identityHandle,
out osStatus);
SafeTemporaryKeychainHandle.TrackItem(certHandle);
SafeTemporaryKeychainHandle.TrackItem(identityHandle);
}
finally
{
if (releasePassword)
{
importPassword.DangerousRelease();
}
if (cfPassphrase != s_nullExportString)
{
cfPassphrase.Dispose();
}
}
if (ret == 1)
{
return certHandle;
}
certHandle.Dispose();
identityHandle.Dispose();
const int SeeOSStatus = 0;
const int ImportReturnedEmpty = -2;
const int ImportReturnedNull = -3;
switch (ret)
{
case SeeOSStatus:
throw CreateExceptionForOSStatus(osStatus);
case ImportReturnedNull:
case ImportReturnedEmpty:
throw new CryptographicException();
default:
Debug.Fail($"Unexpected return value {ret}");
throw new CryptographicException();
}
}
internal static SafeCFArrayHandle X509ImportCollection(
byte[] bytes,
X509ContentType contentType,
SafePasswordHandle importPassword,
SafeKeychainHandle keychain,
bool exportable)
{
SafeCreateHandle cfPassphrase = s_nullExportString;
bool releasePassword = false;
int ret;
SafeCFArrayHandle collectionHandle;
int osStatus;
try
{
if (!importPassword.IsInvalid)
{
importPassword.DangerousAddRef(ref releasePassword);
IntPtr passwordHandle = importPassword.DangerousGetHandle();
if (passwordHandle != IntPtr.Zero)
{
cfPassphrase = CoreFoundation.CFStringCreateWithCString(passwordHandle);
}
}
ret = AppleCryptoNative_X509ImportCollection(
bytes,
bytes.Length,
contentType,
cfPassphrase,
keychain,
exportable ? 1 : 0,
out collectionHandle,
out osStatus);
if (ret == 1)
{
return collectionHandle;
}
}
finally
{
if (releasePassword)
{
importPassword.DangerousRelease();
}
if (cfPassphrase != s_nullExportString)
{
cfPassphrase.Dispose();
}
}
collectionHandle.Dispose();
const int SeeOSStatus = 0;
const int ImportReturnedEmpty = -2;
const int ImportReturnedNull = -3;
switch (ret)
{
case SeeOSStatus:
throw CreateExceptionForOSStatus(osStatus);
case ImportReturnedNull:
case ImportReturnedEmpty:
throw new CryptographicException();
default:
Debug.Fail($"Unexpected return value {ret}");
throw new CryptographicException();
}
}
internal static SafeSecCertificateHandle X509GetCertFromIdentity(SafeSecIdentityHandle identity)
{
SafeSecCertificateHandle cert;
int osStatus = AppleCryptoNative_X509CopyCertFromIdentity(identity, out cert);
SafeTemporaryKeychainHandle.TrackItem(cert);
if (osStatus != 0)
{
cert.Dispose();
throw CreateExceptionForOSStatus(osStatus);
}
if (cert.IsInvalid)
{
cert.Dispose();
throw new CryptographicException(SR.Cryptography_OpenInvalidHandle);
}
return cert;
}
internal static SafeSecKeyRefHandle X509GetPrivateKeyFromIdentity(SafeSecIdentityHandle identity)
{
SafeSecKeyRefHandle key;
int osStatus = AppleCryptoNative_X509CopyPrivateKeyFromIdentity(identity, out key);
SafeTemporaryKeychainHandle.TrackItem(key);
if (osStatus != 0)
{
key.Dispose();
throw CreateExceptionForOSStatus(osStatus);
}
if (key.IsInvalid)
{
key.Dispose();
throw new CryptographicException(SR.Cryptography_OpenInvalidHandle);
}
return key;
}
internal static SafeSecKeyRefHandle X509GetPublicKey(SafeSecCertificateHandle cert)
{
SafeSecKeyRefHandle publicKey;
int osStatus;
int ret = AppleCryptoNative_X509GetPublicKey(cert, out publicKey, out osStatus);
SafeTemporaryKeychainHandle.TrackItem(publicKey);
if (ret == 1)
{
return publicKey;
}
publicKey.Dispose();
if (ret == 0)
{
throw CreateExceptionForOSStatus(osStatus);
}
Debug.Fail($"Unexpected return value {ret}");
throw new CryptographicException();
}
internal static bool X509DemuxAndRetainHandle(
IntPtr handle,
out SafeSecCertificateHandle certHandle,
out SafeSecIdentityHandle identityHandle)
{
int result = AppleCryptoNative_X509DemuxAndRetainHandle(handle, out certHandle, out identityHandle);
SafeTemporaryKeychainHandle.TrackItem(certHandle);
SafeTemporaryKeychainHandle.TrackItem(identityHandle);
switch (result)
{
case 1:
return true;
case 0:
return false;
default:
Debug.Fail($"AppleCryptoNative_X509DemuxAndRetainHandle returned {result}");
throw new CryptographicException();
}
}
internal static SafeSecIdentityHandle X509CopyWithPrivateKey(
SafeSecCertificateHandle certHandle,
SafeSecKeyRefHandle privateKeyHandle,
SafeKeychainHandle targetKeychain)
{
SafeSecIdentityHandle identityHandle;
int osStatus;
int result = AppleCryptoNative_X509CopyWithPrivateKey(
certHandle,
privateKeyHandle,
targetKeychain,
out identityHandle,
out osStatus);
if (result == 1)
{
Debug.Assert(!identityHandle.IsInvalid);
return identityHandle;
}
identityHandle.Dispose();
if (result == 0)
{
throw CreateExceptionForOSStatus(osStatus);
}
Debug.Fail($"AppleCryptoNative_X509CopyWithPrivateKey returned {result}");
throw new CryptographicException();
}
private static byte[] X509Export(X509ContentType contentType, SafeCreateHandle cfPassphrase, IntPtr[] certHandles)
{
Debug.Assert(contentType == X509ContentType.Pkcs7 || contentType == X509ContentType.Pkcs12);
using (SafeCreateHandle handlesArray = CoreFoundation.CFArrayCreate(certHandles, (UIntPtr)certHandles.Length))
{
SafeCFDataHandle exportData;
int osStatus;
int result = AppleCryptoNative_X509ExportData(
handlesArray,
contentType,
cfPassphrase,
out exportData,
out osStatus);
using (exportData)
{
if (result != 1)
{
if (result == 0)
{
throw CreateExceptionForOSStatus(osStatus);
}
Debug.Fail($"Unexpected result from AppleCryptoNative_X509ExportData: {result}");
throw new CryptographicException();
}
Debug.Assert(!exportData.IsInvalid, "Successful export yielded no data");
return CoreFoundation.CFGetData(exportData);
}
}
}
internal static byte[] X509ExportPkcs7(IntPtr[] certHandles)
{
return X509Export(X509ContentType.Pkcs7, s_nullExportString, certHandles);
}
internal static byte[] X509ExportPfx(IntPtr[] certHandles, SafePasswordHandle exportPassword)
{
SafeCreateHandle cfPassphrase = s_emptyExportString;
bool releasePassword = false;
try
{
if (!exportPassword.IsInvalid)
{
exportPassword.DangerousAddRef(ref releasePassword);
IntPtr passwordHandle = exportPassword.DangerousGetHandle();
if (passwordHandle != IntPtr.Zero)
{
cfPassphrase = CoreFoundation.CFStringCreateWithCString(passwordHandle);
}
}
return X509Export(X509ContentType.Pkcs12, cfPassphrase, certHandles);
}
finally
{
if (releasePassword)
{
exportPassword.DangerousRelease();
}
if (cfPassphrase != s_emptyExportString)
{
cfPassphrase.Dispose();
}
}
}
}
}
namespace System.Security.Cryptography.X509Certificates
{
internal sealed class SafeSecIdentityHandle : SafeKeychainItemHandle
{
public SafeSecIdentityHandle()
{
}
}
internal sealed class SafeSecCertificateHandle : SafeKeychainItemHandle
{
public SafeSecCertificateHandle()
{
}
}
}
| |
// 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
//
//
// Compiler-targeted types that build tasks for use as the return types of asynchronous methods.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Diagnostics;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using Internal.Runtime.Augments;
using AsyncStatus = Internal.Runtime.Augments.AsyncStatus;
using CausalityRelation = Internal.Runtime.Augments.CausalityRelation;
using CausalitySource = Internal.Runtime.Augments.CausalitySource;
using CausalityTraceLevel = Internal.Runtime.Augments.CausalityTraceLevel;
using CausalitySynchronousWork = Internal.Runtime.Augments.CausalitySynchronousWork;
using Thread = Internal.Runtime.Augments.RuntimeThread;
namespace System.Runtime.CompilerServices
{
/// <summary>
/// Provides a builder for asynchronous methods that return void.
/// This type is intended for compiler use only.
/// </summary>
public struct AsyncVoidMethodBuilder
{
/// <summary>Action to invoke the state machine's MoveNext.</summary>
private Action m_moveNextAction;
/// <summary>The synchronization context associated with this operation.</summary>
private SynchronizationContext m_synchronizationContext;
//WARNING: We allow diagnostic tools to directly inspect this member (m_task).
//See https://github.com/dotnet/corert/blob/master/Documentation/design-docs/diagnostics/diagnostics-tools-contract.md for more details.
//Please do not change the type, the name, or the semantic usage of this member without understanding the implication for tools.
//Get in touch with the diagnostics team if you have questions.
/// <summary>Task used for debugging and logging purposes only. Lazily initialized.</summary>
private Task m_task;
/// <summary>Initializes a new <see cref="AsyncVoidMethodBuilder"/>.</summary>
/// <returns>The initialized <see cref="AsyncVoidMethodBuilder"/>.</returns>
[MethodImpl(MethodImplOptions.NoInlining)]
public static AsyncVoidMethodBuilder Create()
{
SynchronizationContext sc = SynchronizationContext.Current;
if (sc != null)
sc.OperationStarted();
// On ProjectN we will eagerly initalize the task and it's Id if the debugger is attached
AsyncVoidMethodBuilder avmb = new AsyncVoidMethodBuilder() { m_synchronizationContext = sc };
avmb.m_task = avmb.GetTaskIfDebuggingEnabled();
if (avmb.m_task != null)
{
int i = avmb.m_task.Id;
}
return avmb;
}
/// <summary>Initiates the builder's execution with the associated state machine.</summary>
/// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam>
/// <param name="stateMachine">The state machine instance, passed by reference.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="stateMachine"/> argument was null (Nothing in Visual Basic).</exception>
[DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
{
AsyncMethodBuilderCore.Start(ref stateMachine);
}
/// <summary>Associates the builder with the state machine it represents.</summary>
/// <param name="stateMachine">The heap-allocated state machine object.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="stateMachine"/> argument was null (Nothing in Visual Basic).</exception>
/// <exception cref="System.InvalidOperationException">The builder is incorrectly initialized.</exception>
public void SetStateMachine(IAsyncStateMachine stateMachine)
{
AsyncMethodBuilderCore.SetStateMachine(stateMachine, m_moveNextAction); // argument validation handled by AsyncMethodBuilderCore
}
/// <summary>
/// Schedules the specified state machine to be pushed forward when the specified awaiter completes.
/// </summary>
/// <typeparam name="TAwaiter">Specifies the type of the awaiter.</typeparam>
/// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam>
/// <param name="awaiter">The awaiter.</param>
/// <param name="stateMachine">The state machine.</param>
public void AwaitOnCompleted<TAwaiter, TStateMachine>(
ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : INotifyCompletion
where TStateMachine : IAsyncStateMachine
{
AsyncMethodBuilderCore.CallOnCompleted(
AsyncMethodBuilderCore.GetCompletionAction(ref m_moveNextAction, ref stateMachine, this.GetTaskIfDebuggingEnabled()),
ref awaiter);
}
/// <summary>
/// Schedules the specified state machine to be pushed forward when the specified awaiter completes.
/// </summary>
/// <typeparam name="TAwaiter">Specifies the type of the awaiter.</typeparam>
/// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam>
/// <param name="awaiter">The awaiter.</param>
/// <param name="stateMachine">The state machine.</param>
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(
ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : ICriticalNotifyCompletion
where TStateMachine : IAsyncStateMachine
{
AsyncMethodBuilderCore.CallUnsafeOnCompleted(
AsyncMethodBuilderCore.GetCompletionAction(ref m_moveNextAction, ref stateMachine, this.GetTaskIfDebuggingEnabled()),
ref awaiter);
}
/// <summary>Completes the method builder successfully.</summary>
public void SetResult()
{
Task taskIfDebuggingEnabled = this.GetTaskIfDebuggingEnabled();
if (taskIfDebuggingEnabled != null)
{
if (DebuggerSupport.LoggingOn)
DebuggerSupport.TraceOperationCompletion(CausalityTraceLevel.Required, taskIfDebuggingEnabled, AsyncStatus.Completed);
DebuggerSupport.RemoveFromActiveTasks(taskIfDebuggingEnabled);
}
NotifySynchronizationContextOfCompletion();
}
/// <summary>Faults the method builder with an exception.</summary>
/// <param name="exception">The exception that is the cause of this fault.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="exception"/> argument is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.InvalidOperationException">The builder is not initialized.</exception>
[MethodImpl(MethodImplOptions.NoInlining)]
public void SetException(Exception exception)
{
Task taskIfDebuggingEnabled = this.GetTaskIfDebuggingEnabled();
if (taskIfDebuggingEnabled != null)
{
if (DebuggerSupport.LoggingOn)
DebuggerSupport.TraceOperationCompletion(CausalityTraceLevel.Required, taskIfDebuggingEnabled, AsyncStatus.Error);
}
AsyncMethodBuilderCore.ThrowAsync(exception, m_synchronizationContext);
NotifySynchronizationContextOfCompletion();
}
/// <summary>Notifies the current synchronization context that the operation completed.</summary>
[MethodImpl(MethodImplOptions.NoInlining)]
private void NotifySynchronizationContextOfCompletion()
{
if (m_synchronizationContext != null)
{
try
{
m_synchronizationContext.OperationCompleted();
}
catch (Exception exc)
{
// If the interaction with the SynchronizationContext goes awry,
// fall back to propagating on the ThreadPool.
AsyncMethodBuilderCore.ThrowAsync(exc, targetContext: null);
}
}
}
// This property lazily instantiates the Task in a non-thread-safe manner.
internal Task Task
{
get
{
if (m_task == null) m_task = new Task();
return m_task;
}
}
/// <summary>
/// Gets an object that may be used to uniquely identify this builder to the debugger.
/// </summary>
/// <remarks>
/// This property lazily instantiates the ID in a non-thread-safe manner.
/// It must only be used by the debugger and only in a single-threaded manner.
/// </remarks>
private object ObjectIdForDebugger
{
get
{
return this.Task;
}
}
}
/// <summary>
/// Provides a builder for asynchronous methods that return <see cref="System.Threading.Tasks.Task"/>.
/// This type is intended for compiler use only.
/// </summary>
/// <remarks>
/// AsyncTaskMethodBuilder is a value type, and thus it is copied by value.
/// Prior to being copied, one of its Task, SetResult, or SetException members must be accessed,
/// or else the copies may end up building distinct Task instances.
/// </remarks>
public struct AsyncTaskMethodBuilder
{
/// <summary>A cached VoidTaskResult task used for builders that complete synchronously.</summary>
private static readonly Task<VoidTaskResult> s_cachedCompleted = AsyncTaskCache.CreateCacheableTask<VoidTaskResult>(default(VoidTaskResult));
private Action m_moveNextAction;
// WARNING: We allow diagnostic tools to directly inspect this member (m_task).
// See https://github.com/dotnet/corert/blob/master/Documentation/design-docs/diagnostics/diagnostics-tools-contract.md for more details.
// Please do not change the type, the name, or the semantic usage of this member without understanding the implication for tools.
// Get in touch with the diagnostics team if you have questions.
private Task<VoidTaskResult> m_task;
/// <summary>Initializes a new <see cref="AsyncTaskMethodBuilder"/>.</summary>
/// <returns>The initialized <see cref="AsyncTaskMethodBuilder"/>.</returns>
public static AsyncTaskMethodBuilder Create()
{
AsyncTaskMethodBuilder atmb = default(AsyncTaskMethodBuilder);
// On ProjectN we will eagerly initalize the task and it's Id if the debugger is attached
atmb.m_task = (Task<VoidTaskResult>)atmb.GetTaskIfDebuggingEnabled();
if (atmb.m_task != null)
{
int i = atmb.m_task.Id;
}
return atmb;
}
/// <summary>Initiates the builder's execution with the associated state machine.</summary>
/// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam>
/// <param name="stateMachine">The state machine instance, passed by reference.</param>
[DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
{
AsyncMethodBuilderCore.Start(ref stateMachine);
}
/// <summary>Associates the builder with the state machine it represents.</summary>
/// <param name="stateMachine">The heap-allocated state machine object.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="stateMachine"/> argument was null (Nothing in Visual Basic).</exception>
/// <exception cref="System.InvalidOperationException">The builder is incorrectly initialized.</exception>
public void SetStateMachine(IAsyncStateMachine stateMachine)
{
AsyncMethodBuilderCore.SetStateMachine(stateMachine, m_moveNextAction); // argument validation handled by AsyncMethodBuilderCore
}
/// <summary>
/// Schedules the specified state machine to be pushed forward when the specified awaiter completes.
/// </summary>
/// <typeparam name="TAwaiter">Specifies the type of the awaiter.</typeparam>
/// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam>
/// <param name="awaiter">The awaiter.</param>
/// <param name="stateMachine">The state machine.</param>
public void AwaitOnCompleted<TAwaiter, TStateMachine>(
ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : INotifyCompletion
where TStateMachine : IAsyncStateMachine
{
EnsureTaskCreated();
AsyncMethodBuilderCore.CallOnCompleted(
AsyncMethodBuilderCore.GetCompletionAction(ref m_moveNextAction, ref stateMachine, this.GetTaskIfDebuggingEnabled()),
ref awaiter);
}
/// <summary>
/// Schedules the specified state machine to be pushed forward when the specified awaiter completes.
/// </summary>
/// <typeparam name="TAwaiter">Specifies the type of the awaiter.</typeparam>
/// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam>
/// <param name="awaiter">The awaiter.</param>
/// <param name="stateMachine">The state machine.</param>
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(
ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : ICriticalNotifyCompletion
where TStateMachine : IAsyncStateMachine
{
EnsureTaskCreated();
AsyncMethodBuilderCore.CallUnsafeOnCompleted(
AsyncMethodBuilderCore.GetCompletionAction(ref m_moveNextAction, ref stateMachine, this.GetTaskIfDebuggingEnabled()),
ref awaiter);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void EnsureTaskCreated()
{
if (m_task == null)
m_task = new Task<VoidTaskResult>();
}
/// <summary>Gets the <see cref="System.Threading.Tasks.Task"/> for this builder.</summary>
/// <returns>The <see cref="System.Threading.Tasks.Task"/> representing the builder's asynchronous operation.</returns>
/// <exception cref="System.InvalidOperationException">The builder is not initialized.</exception>
public Task Task
{
get
{
return m_task ?? (m_task = new Task<VoidTaskResult>());
}
}
/// <summary>
/// Completes the <see cref="System.Threading.Tasks.Task"/> in the
/// <see cref="System.Threading.Tasks.TaskStatus">RanToCompletion</see> state.
/// </summary>
/// <exception cref="System.InvalidOperationException">The builder is not initialized.</exception>
/// <exception cref="System.InvalidOperationException">The task has already completed.</exception>
[MethodImpl(MethodImplOptions.NoInlining)]
public void SetResult()
{
var task = m_task;
if (task == null)
m_task = s_cachedCompleted;
else
{
if (DebuggerSupport.LoggingOn)
DebuggerSupport.TraceOperationCompletion(CausalityTraceLevel.Required, task, AsyncStatus.Completed);
DebuggerSupport.RemoveFromActiveTasks(task);
if (!task.TrySetResult(default(VoidTaskResult)))
throw new InvalidOperationException(SR.TaskT_TransitionToFinal_AlreadyCompleted);
}
}
/// <summary>
/// Completes the <see cref="System.Threading.Tasks.Task"/> in the
/// <see cref="System.Threading.Tasks.TaskStatus">Faulted</see> state with the specified exception.
/// </summary>
/// <param name="exception">The <see cref="System.Exception"/> to use to fault the task.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="exception"/> argument is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.InvalidOperationException">The builder is not initialized.</exception>
/// <exception cref="System.InvalidOperationException">The task has already completed.</exception>
[MethodImpl(MethodImplOptions.NoInlining)]
public void SetException(Exception exception) { SetException(this.Task, exception); }
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void SetException(Task task, Exception exception)
{
if (exception == null) throw new ArgumentNullException(nameof(exception));
// If the exception represents cancellation, cancel the task. Otherwise, fault the task.
var oce = exception as OperationCanceledException;
bool successfullySet = oce != null ?
task.TrySetCanceled(oce.CancellationToken, oce) :
task.TrySetException(exception);
// Unlike with TaskCompletionSource, we do not need to spin here until m_task is completed,
// since AsyncTaskMethodBuilder.SetException should not be immediately followed by any code
// that depends on the task having completely completed. Moreover, with correct usage,
// SetResult or SetException should only be called once, so the Try* methods should always
// return true, so no spinning would be necessary anyway (the spinning in TCS is only relevant
// if another thread won the race to complete the task).
if (!successfullySet)
{
throw new InvalidOperationException(SR.TaskT_TransitionToFinal_AlreadyCompleted);
}
}
/// <summary>
/// Called by the debugger to request notification when the first wait operation
/// (await, Wait, Result, etc.) on this builder's task completes.
/// </summary>
/// <param name="enabled">
/// true to enable notification; false to disable a previously set notification.
/// </param>
internal void SetNotificationForWaitCompletion(bool enabled)
{
// Get the task (forcing initialization if not already initialized), and set debug notification
Task.SetNotificationForWaitCompletion(enabled);
}
/// <summary>
/// Gets an object that may be used to uniquely identify this builder to the debugger.
/// </summary>
/// <remarks>
/// This property lazily instantiates the ID in a non-thread-safe manner.
/// It must only be used by the debugger, and only in a single-threaded manner
/// when no other threads are in the middle of accessing this property or this.Task.
/// </remarks>
private object ObjectIdForDebugger { get { return this.Task; } }
}
/// <summary>
/// Provides a builder for asynchronous methods that return <see cref="System.Threading.Tasks.Task{TResult}"/>.
/// This type is intended for compiler use only.
/// </summary>
/// <remarks>
/// AsyncTaskMethodBuilder{TResult} is a value type, and thus it is copied by value.
/// Prior to being copied, one of its Task, SetResult, or SetException members must be accessed,
/// or else the copies may end up building distinct Task instances.
/// </remarks>
public struct AsyncTaskMethodBuilder<TResult>
{
#if false
/// <summary>A cached task for default(TResult).</summary>
internal static readonly Task<TResult> s_defaultResultTask = AsyncTaskCache.CreateCacheableTask(default(TResult));
#endif
private Action m_moveNextAction;
// WARNING: We allow diagnostic tools to directly inspect this member (m_task).
// See https://github.com/dotnet/corert/blob/master/Documentation/design-docs/diagnostics/diagnostics-tools-contract.md for more details.
// Please do not change the type, the name, or the semantic usage of this member without understanding the implication for tools.
// Get in touch with the diagnostics team if you have questions.
// WARNING: For performance reasons, the m_task field is lazily initialized.
// For correct results, the struct AsyncTaskMethodBuilder<TResult> must
// always be used from the same location/copy, at least until m_task is
// initialized. If that guarantee is broken, the field could end up being
// initialized on the wrong copy.
/// <summary>The lazily-initialized built task.</summary>
private Task<TResult> m_task; // lazily-initialized: must not be readonly
/// <summary>Initializes a new <see cref="AsyncTaskMethodBuilder"/>.</summary>
/// <returns>The initialized <see cref="AsyncTaskMethodBuilder"/>.</returns>
public static AsyncTaskMethodBuilder<TResult> Create()
{
AsyncTaskMethodBuilder<TResult> atmb = new AsyncTaskMethodBuilder<TResult>();
// On ProjectN we will eagerly initalize the task and it's Id if the debugger is attached
atmb.m_task = (Task<TResult>)atmb.GetTaskIfDebuggingEnabled();
if (atmb.m_task != null)
{
int i = atmb.m_task.Id;
}
return atmb;
}
/// <summary>Initiates the builder's execution with the associated state machine.</summary>
/// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam>
/// <param name="stateMachine">The state machine instance, passed by reference.</param>
[DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
{
AsyncMethodBuilderCore.Start(ref stateMachine); // argument validation handled by AsyncMethodBuilderCore
}
/// <summary>Associates the builder with the state machine it represents.</summary>
/// <param name="stateMachine">The heap-allocated state machine object.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="stateMachine"/> argument was null (Nothing in Visual Basic).</exception>
/// <exception cref="System.InvalidOperationException">The builder is incorrectly initialized.</exception>
public void SetStateMachine(IAsyncStateMachine stateMachine)
{
AsyncMethodBuilderCore.SetStateMachine(stateMachine, m_moveNextAction); // argument validation handled by AsyncMethodBuilderCore
}
/// <summary>
/// Schedules the specified state machine to be pushed forward when the specified awaiter completes.
/// </summary>
/// <typeparam name="TAwaiter">Specifies the type of the awaiter.</typeparam>
/// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam>
/// <param name="awaiter">The awaiter.</param>
/// <param name="stateMachine">The state machine.</param>
public void AwaitOnCompleted<TAwaiter, TStateMachine>(
ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : INotifyCompletion
where TStateMachine : IAsyncStateMachine
{
// If this is our first await, we're not boxed yet. Set up our Task now, so it will be
// visible to both the non-boxed and boxed builders.
EnsureTaskCreated();
AsyncMethodBuilderCore.CallOnCompleted(
AsyncMethodBuilderCore.GetCompletionAction(ref m_moveNextAction, ref stateMachine, this.GetTaskIfDebuggingEnabled()),
ref awaiter);
}
/// <summary>
/// Schedules the specified state machine to be pushed forward when the specified awaiter completes.
/// </summary>
/// <typeparam name="TAwaiter">Specifies the type of the awaiter.</typeparam>
/// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam>
/// <param name="awaiter">The awaiter.</param>
/// <param name="stateMachine">The state machine.</param>
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(
ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : ICriticalNotifyCompletion
where TStateMachine : IAsyncStateMachine
{
// If this is our first await, we're not boxed yet. Set up our Task now, so it will be
// visible to both the non-boxed and boxed builders.
EnsureTaskCreated();
AsyncMethodBuilderCore.CallUnsafeOnCompleted(
AsyncMethodBuilderCore.GetCompletionAction(ref m_moveNextAction, ref stateMachine, this.GetTaskIfDebuggingEnabled()),
ref awaiter);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void EnsureTaskCreated()
{
if (m_task == null)
m_task = new Task<TResult>();
}
/// <summary>Gets the <see cref="System.Threading.Tasks.Task{TResult}"/> for this builder.</summary>
/// <returns>The <see cref="System.Threading.Tasks.Task{TResult}"/> representing the builder's asynchronous operation.</returns>
public Task<TResult> Task
{
get
{
// Get and return the task. If there isn't one, first create one and store it.
var task = m_task;
if (task == null) { m_task = task = new Task<TResult>(); }
return task;
}
}
/// <summary>
/// Completes the <see cref="System.Threading.Tasks.Task{TResult}"/> in the
/// <see cref="System.Threading.Tasks.TaskStatus">RanToCompletion</see> state with the specified result.
/// </summary>
/// <param name="result">The result to use to complete the task.</param>
/// <exception cref="System.InvalidOperationException">The task has already completed.</exception>
[MethodImpl(MethodImplOptions.NoInlining)]
public void SetResult(TResult result)
{
// Get the currently stored task, which will be non-null if get_Task has already been accessed.
// If there isn't one, get a task and store it.
var task = m_task;
if (task == null)
{
m_task = GetTaskForResult(result);
Debug.Assert(m_task != null, "GetTaskForResult should never return null");
}
// Slow path: complete the existing task.
else
{
if (DebuggerSupport.LoggingOn)
DebuggerSupport.TraceOperationCompletion(CausalityTraceLevel.Required, task, AsyncStatus.Completed);
DebuggerSupport.RemoveFromActiveTasks(task);
if (!task.TrySetResult(result))
{
throw new InvalidOperationException(SR.TaskT_TransitionToFinal_AlreadyCompleted);
}
}
}
/// <summary>
/// Completes the <see cref="System.Threading.Tasks.Task{TResult}"/> in the
/// <see cref="System.Threading.Tasks.TaskStatus">Faulted</see> state with the specified exception.
/// </summary>
/// <param name="exception">The <see cref="System.Exception"/> to use to fault the task.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="exception"/> argument is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.InvalidOperationException">The task has already completed.</exception>
[MethodImpl(MethodImplOptions.NoInlining)]
public void SetException(Exception exception)
{
AsyncTaskMethodBuilder.SetException(this.Task, exception);
}
/// <summary>
/// Called by the debugger to request notification when the first wait operation
/// (await, Wait, Result, etc.) on this builder's task completes.
/// </summary>
/// <param name="enabled">
/// true to enable notification; false to disable a previously set notification.
/// </param>
/// <remarks>
/// This should only be invoked from within an asynchronous method,
/// and only by the debugger.
/// </remarks>
internal void SetNotificationForWaitCompletion(bool enabled)
{
// Get the task (forcing initialization if not already initialized), and set debug notification
this.Task.SetNotificationForWaitCompletion(enabled);
}
/// <summary>
/// Gets an object that may be used to uniquely identify this builder to the debugger.
/// </summary>
/// <remarks>
/// This property lazily instantiates the ID in a non-thread-safe manner.
/// It must only be used by the debugger, and only in a single-threaded manner
/// when no other threads are in the middle of accessing this property or this.Task.
/// </remarks>
private object ObjectIdForDebugger { get { return this.Task; } }
/// <summary>
/// Gets a task for the specified result. This will either
/// be a cached or new task, never null.
/// </summary>
/// <param name="result">The result for which we need a task.</param>
/// <returns>The completed task containing the result.</returns>
internal static Task<TResult> GetTaskForResult(TResult result)
{
// Currently NUTC does not perform the optimization needed by this method. The result is that
// every call to this method results in quite a lot of work, including many allocations, which
// is the opposite of the intent. For now, let's just return a new Task each time.
// Bug 719350 tracks re-optimizing this in ProjectN.
#if false
// The goal of this function is to be give back a cached task if possible,
// or to otherwise give back a new task. To give back a cached task,
// we need to be able to evaluate the incoming result value, and we need
// to avoid as much overhead as possible when doing so, as this function
// is invoked as part of the return path from every async method.
// Most tasks won't be cached, and thus we need the checks for those that are
// to be as close to free as possible. This requires some trickiness given the
// lack of generic specialization in .NET.
//
// Be very careful when modifying this code. It has been tuned
// to comply with patterns recognized by both 32-bit and 64-bit JITs.
// If changes are made here, be sure to look at the generated assembly, as
// small tweaks can have big consequences for what does and doesn't get optimized away.
//
// Note that this code only ever accesses a static field when it knows it'll
// find a cached value, since static fields (even if readonly and integral types)
// require special access helpers in this NGEN'd and domain-neutral.
if (null != (object)default(TResult)) // help the JIT avoid the value type branches for ref types
{
// Special case simple value types:
// - Boolean
// - Byte, SByte
// - Char
// - Decimal
// - Int32, UInt32
// - Int64, UInt64
// - Int16, UInt16
// - IntPtr, UIntPtr
// As of .NET 4.5, the (Type)(object)result pattern used below
// is recognized and optimized by both 32-bit and 64-bit JITs.
// For Boolean, we cache all possible values.
if (typeof(TResult) == typeof(Boolean)) // only the relevant branches are kept for each value-type generic instantiation
{
Boolean value = (Boolean)(object)result;
Task<Boolean> task = value ? AsyncTaskCache.TrueTask : AsyncTaskCache.FalseTask;
return (Task<TResult>)(Task)(task);// JitHelpers.UnsafeCast<Task<TResult>>(task); // UnsafeCast avoids type check we know will succeed
}
// For Int32, we cache a range of common values, e.g. [-1,4).
else if (typeof(TResult) == typeof(Int32))
{
// Compare to constants to avoid static field access if outside of cached range.
// We compare to the upper bound first, as we're more likely to cache miss on the upper side than on the
// lower side, due to positive values being more common than negative as return values.
Int32 value = (Int32)(object)result;
if (value < AsyncTaskCache.EXCLUSIVE_INT32_MAX &&
value >= AsyncTaskCache.INCLUSIVE_INT32_MIN)
{
Task<Int32> task = AsyncTaskCache.Int32Tasks[value - AsyncTaskCache.INCLUSIVE_INT32_MIN];
return (Task<TResult>)(Task)(task);// JitHelpers.UnsafeCast<Task<TResult>>(task); // UnsafeCast avoids a type check we know will succeed
}
}
// For other known value types, we only special-case 0 / default(TResult).
else if (
(typeof(TResult) == typeof(UInt32) && default(UInt32) == (UInt32)(object)result) ||
(typeof(TResult) == typeof(Byte) && default(Byte) == (Byte)(object)result) ||
(typeof(TResult) == typeof(SByte) && default(SByte) == (SByte)(object)result) ||
(typeof(TResult) == typeof(Char) && default(Char) == (Char)(object)result) ||
(typeof(TResult) == typeof(Decimal) && default(Decimal) == (Decimal)(object)result) ||
(typeof(TResult) == typeof(Int64) && default(Int64) == (Int64)(object)result) ||
(typeof(TResult) == typeof(UInt64) && default(UInt64) == (UInt64)(object)result) ||
(typeof(TResult) == typeof(Int16) && default(Int16) == (Int16)(object)result) ||
(typeof(TResult) == typeof(UInt16) && default(UInt16) == (UInt16)(object)result) ||
(typeof(TResult) == typeof(IntPtr) && default(IntPtr) == (IntPtr)(object)result) ||
(typeof(TResult) == typeof(UIntPtr) && default(UIntPtr) == (UIntPtr)(object)result))
{
return s_defaultResultTask;
}
}
else if (result == null) // optimized away for value types
{
return s_defaultResultTask;
}
#endif
// No cached task is available. Manufacture a new one for this result.
return new Task<TResult>(result);
}
}
/// <summary>Provides a cache of closed generic tasks for async methods.</summary>
internal static class AsyncTaskCache
{
// All static members are initialized inline to ensure type is beforefieldinit
#if false
/// <summary>A cached Task{Boolean}.Result == true.</summary>
internal static readonly Task<Boolean> TrueTask = CreateCacheableTask(true);
/// <summary>A cached Task{Boolean}.Result == false.</summary>
internal static readonly Task<Boolean> FalseTask = CreateCacheableTask(false);
/// <summary>The cache of Task{Int32}.</summary>
internal static readonly Task<Int32>[] Int32Tasks = CreateInt32Tasks();
/// <summary>The minimum value, inclusive, for which we want a cached task.</summary>
internal const Int32 INCLUSIVE_INT32_MIN = -1;
/// <summary>The maximum value, exclusive, for which we want a cached task.</summary>
internal const Int32 EXCLUSIVE_INT32_MAX = 9;
/// <summary>Creates an array of cached tasks for the values in the range [INCLUSIVE_MIN,EXCLUSIVE_MAX).</summary>
private static Task<Int32>[] CreateInt32Tasks()
{
Debug.Assert(EXCLUSIVE_INT32_MAX >= INCLUSIVE_INT32_MIN, "Expected max to be at least min");
var tasks = new Task<Int32>[EXCLUSIVE_INT32_MAX - INCLUSIVE_INT32_MIN];
for (int i = 0; i < tasks.Length; i++)
{
tasks[i] = CreateCacheableTask(i + INCLUSIVE_INT32_MIN);
}
return tasks;
}
#endif
/// <summary>Creates a non-disposable task.</summary>
/// <typeparam name="TResult">Specifies the result type.</typeparam>
/// <param name="result">The result for the task.</param>
/// <returns>The cacheable task.</returns>
internal static Task<TResult> CreateCacheableTask<TResult>(TResult result)
{
return new Task<TResult>(false, result, (TaskCreationOptions)InternalTaskOptions.DoNotDispose, default(CancellationToken));
}
}
internal static class AsyncMethodBuilderCore
{
/// <summary>Initiates the builder's execution with the associated state machine.</summary>
/// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam>
/// <param name="stateMachine">The state machine instance, passed by reference.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="stateMachine"/> argument is null (Nothing in Visual Basic).</exception>
[DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void Start<TStateMachine>(ref TStateMachine stateMachine)
where TStateMachine : IAsyncStateMachine
{
// Async state machines are required not to throw, so no need for try/finally here.
Thread currentThread = Thread.CurrentThread;
ExecutionContextSwitcher ecs = default(ExecutionContextSwitcher);
ExecutionContext.EstablishCopyOnWriteScope(currentThread, ref ecs);
stateMachine.MoveNext();
ecs.Undo(currentThread);
}
//
// We are going to do something odd here, which may require some explaining. GetCompletionAction does quite a bit
// of work, and is generic, parameterized over the type of the state machine. Since every async method has its own
// state machine type, and they are basically all value types, we end up generating separate copies of this method
// for every state machine. This adds up to a *lot* of code for an app that has many async methods.
//
// So, to save code size, we delegate all of the work to a non-generic helper. In the non-generic method, we have
// to coerce our "ref TStateMachine" arg into both a "ref byte" and a "ref IAsyncResult."
//
// Note that this is only safe because:
//
// a) We are coercing byrefs only. These are just interior pointers; the runtime doesn't care *what* they point to.
// b) We only read from one of those pointers after we're sure it's of the right type. This prevents us from,
// say, ending up with a "heap reference" that's really a pointer to the stack.
//
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static Action GetCompletionAction<TStateMachine>(ref Action cachedMoveNextAction, ref TStateMachine stateMachine, Task taskIfDebuggingEnabled)
where TStateMachine : IAsyncStateMachine
{
return GetCompletionActionHelper(
ref cachedMoveNextAction,
ref Unsafe.As<TStateMachine, byte>(ref stateMachine),
EETypePtr.EETypePtrOf<TStateMachine>(),
taskIfDebuggingEnabled);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static unsafe Action GetCompletionActionHelper(
ref Action cachedMoveNextAction,
ref byte stateMachineAddress,
EETypePtr stateMachineType,
Task taskIfDebuggingEnabled)
{
// Alert a listening debugger that we can't make forward progress unless it slips threads.
// If we don't do this, and a method that uses "await foo;" is invoked through funceval,
// we could end up hooking up a callback to push forward the async method's state machine,
// the debugger would then abort the funceval after it takes too long, and then continuing
// execution could result in another callback being hooked up. At that point we have
// multiple callbacks registered to push the state machine, which could result in bad behavior.
//Debugger.NotifyOfCrossThreadDependency();
MoveNextRunner runner;
if (cachedMoveNextAction != null)
{
Debug.Assert(cachedMoveNextAction.Target is MoveNextRunner);
runner = (MoveNextRunner)cachedMoveNextAction.Target;
runner.m_executionContext = ExecutionContext.Capture();
return cachedMoveNextAction;
}
runner = new MoveNextRunner();
runner.m_executionContext = ExecutionContext.Capture();
cachedMoveNextAction = runner.CallMoveNext;
if (taskIfDebuggingEnabled != null)
{
runner.m_task = taskIfDebuggingEnabled;
if (DebuggerSupport.LoggingOn)
{
IntPtr eeType = stateMachineType.RawValue;
DebuggerSupport.TraceOperationCreation(CausalityTraceLevel.Required, taskIfDebuggingEnabled, "Async: " + eeType.ToString("x"), 0);
}
DebuggerSupport.AddToActiveTasks(taskIfDebuggingEnabled);
}
//
// If the state machine is a value type, we need to box it now.
//
IAsyncStateMachine boxedStateMachine;
if (stateMachineType.IsValueType)
{
object boxed = RuntimeImports.RhBox(stateMachineType, ref stateMachineAddress);
Debug.Assert(boxed is IAsyncStateMachine);
boxedStateMachine = Unsafe.As<IAsyncStateMachine>(boxed);
}
else
{
boxedStateMachine = Unsafe.As<byte, IAsyncStateMachine>(ref stateMachineAddress);
}
runner.m_stateMachine = boxedStateMachine;
#if DEBUG
//
// In debug builds, we'll go ahead and call SetStateMachine, even though all of our initialization is done.
// This way we'll keep forcing state machine implementations to keep the behavior needed by the CLR.
//
boxedStateMachine.SetStateMachine(boxedStateMachine);
#endif
// All done!
return cachedMoveNextAction;
}
private class MoveNextRunner
{
internal IAsyncStateMachine m_stateMachine;
internal ExecutionContext m_executionContext;
internal Task m_task;
internal void CallMoveNext()
{
Task task = m_task;
if (task != null)
DebuggerSupport.TraceSynchronousWorkStart(CausalityTraceLevel.Required, task, CausalitySynchronousWork.Execution);
ExecutionContext.Run(
m_executionContext,
state => Unsafe.As<IAsyncStateMachine>(state).MoveNext(),
m_stateMachine);
if (task != null)
DebuggerSupport.TraceSynchronousWorkCompletion(CausalityTraceLevel.Required, CausalitySynchronousWork.Execution);
}
}
/// <summary>Associates the builder with the state machine it represents.</summary>
/// <param name="stateMachine">The heap-allocated state machine object.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="stateMachine"/> argument was null (Nothing in Visual Basic).</exception>
/// <exception cref="System.InvalidOperationException">The builder is incorrectly initialized.</exception>
internal static void SetStateMachine(IAsyncStateMachine stateMachine, Action cachedMoveNextAction)
{
//
// Unlike the CLR, we do all of our initialization of the boxed state machine in GetCompletionAction. All we
// need to do here is validate that everything's been set up correctly. Note that we don't call
// IAsyncStateMachine.SetStateMachine in retail builds of the Framework, so we don't really expect a lot of calls
// to this method.
//
if (stateMachine == null)
throw new ArgumentNullException(nameof(stateMachine));
if (cachedMoveNextAction == null)
throw new InvalidOperationException(SR.AsyncMethodBuilder_InstanceNotInitialized);
Action unwrappedMoveNextAction = TryGetStateMachineForDebugger(cachedMoveNextAction);
if (unwrappedMoveNextAction.Target != stateMachine)
throw new InvalidOperationException(SR.AsyncMethodBuilder_InstanceNotInitialized);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void CallOnCompleted<TAwaiter>(Action continuation, ref TAwaiter awaiter)
where TAwaiter : INotifyCompletion
{
try
{
awaiter.OnCompleted(continuation);
}
catch (Exception e)
{
RuntimeAugments.ReportUnhandledException(e);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void CallUnsafeOnCompleted<TAwaiter>(Action continuation, ref TAwaiter awaiter)
where TAwaiter : ICriticalNotifyCompletion
{
try
{
awaiter.UnsafeOnCompleted(continuation);
}
catch (Exception e)
{
RuntimeAugments.ReportUnhandledException(e);
}
}
/// <summary>Throws the exception on the ThreadPool.</summary>
/// <param name="exception">The exception to propagate.</param>
/// <param name="targetContext">The target context on which to propagate the exception. Null to use the ThreadPool.</param>
internal static void ThrowAsync(Exception exception, SynchronizationContext targetContext)
{
if (exception == null) throw new ArgumentNullException(nameof(exception));
// If the user supplied a SynchronizationContext...
if (targetContext != null)
{
try
{
// Capture the exception into an ExceptionDispatchInfo so that its
// stack trace and Watson bucket info will be preserved
var edi = ExceptionDispatchInfo.Capture(exception);
// Post the throwing of the exception to that context, and return.
targetContext.Post(state => ((ExceptionDispatchInfo)state).Throw(), edi);
return;
}
catch (Exception postException)
{
// If something goes horribly wrong in the Post, we'll treat this a *both* exceptions
// going unhandled.
RuntimeAugments.ReportUnhandledException(new AggregateException(exception, postException));
}
}
RuntimeAugments.ReportUnhandledException(exception);
}
//
// This helper routine is targeted by the debugger. Its purpose is to remove any delegate wrappers introduced by the framework
// that the debugger doesn't want to see.
//
[DependencyReductionRoot]
internal static Action TryGetStateMachineForDebugger(Action action)
{
Object target = action.Target;
MoveNextRunner runner = target as MoveNextRunner;
if (runner != null)
return runner.m_stateMachine.MoveNext;
return action;
}
}
}
| |
// Copyright ?2004, 2015, Oracle and/or its affiliates. All rights reserved.
//
// MySQL Connector/NET is licensed under the terms of the GPLv2
// <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most
// MySQL Connectors. There are special exceptions to the terms and
// conditions of the GPLv2 as it is applied to this software, see the
// FLOSS License Exception
// <http://www.mysql.com/about/legal/licensing/foss-exception.html>.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published
// by the Free Software Foundation; version 2 of the License.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
using System;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
using MySql.Data.Common;
using MySql.Data.Types;
using System.Collections.Specialized;
using System.Collections;
using System.Text.RegularExpressions;
using MySql.Data.MySqlClient.Properties;
using System.Collections.Generic;
#if !RT
using System.Data;
using System.Data.Common;
#endif
namespace MySql.Data.MySqlClient
{
internal class SchemaProvider
{
protected MySqlConnection connection;
public static string MetaCollection = "MetaDataCollections";
public SchemaProvider(MySqlConnection connectionToUse)
{
connection = connectionToUse;
}
public virtual MySqlSchemaCollection GetSchema(string collection, String[] restrictions)
{
if (connection.State != ConnectionState.Open)
throw new MySqlException("GetSchema can only be called on an open connection.");
collection = StringUtility.ToUpperInvariant(collection);
MySqlSchemaCollection c = GetSchemaInternal(collection, restrictions);
if (c == null)
throw new ArgumentException("Invalid collection name");
return c;
}
public virtual MySqlSchemaCollection GetDatabases(string[] restrictions)
{
Regex regex = null;
int caseSetting = Int32.Parse(connection.driver.Property("lower_case_table_names"));
string sql = "SHOW DATABASES";
// if lower_case_table_names is zero, then case lookup should be sensitive
// so we can use LIKE to do the matching.
if (caseSetting == 0)
{
if (restrictions != null && restrictions.Length >= 1)
sql = sql + " LIKE '" + restrictions[0] + "'";
}
MySqlSchemaCollection c = QueryCollection("Databases", sql);
if (caseSetting != 0 && restrictions != null && restrictions.Length >= 1 && restrictions[0] != null)
regex = new Regex(restrictions[0], RegexOptions.IgnoreCase);
MySqlSchemaCollection c2 = new MySqlSchemaCollection("Databases");
c2.AddColumn("CATALOG_NAME", typeof(string));
c2.AddColumn("SCHEMA_NAME", typeof(string));
foreach (MySqlSchemaRow row in c.Rows)
{
if (regex != null && !regex.Match(row[0].ToString()).Success) continue;
MySqlSchemaRow newRow = c2.AddRow();
newRow[1] = row[0];
}
return c2;
}
public virtual MySqlSchemaCollection GetTables(string[] restrictions)
{
MySqlSchemaCollection c = new MySqlSchemaCollection("Tables");
c.AddColumn("TABLE_CATALOG", typeof(string));
c.AddColumn("TABLE_SCHEMA", typeof(string));
c.AddColumn("TABLE_NAME", typeof(string));
c.AddColumn("TABLE_TYPE", typeof(string));
c.AddColumn("ENGINE", typeof(string));
c.AddColumn("VERSION", typeof(ulong));
c.AddColumn("ROW_FORMAT", typeof(string));
c.AddColumn("TABLE_ROWS", typeof(ulong));
c.AddColumn("AVG_ROW_LENGTH", typeof(ulong));
c.AddColumn("DATA_LENGTH", typeof(ulong));
c.AddColumn("MAX_DATA_LENGTH", typeof(ulong));
c.AddColumn("INDEX_LENGTH", typeof(ulong));
c.AddColumn("DATA_FREE", typeof(ulong));
c.AddColumn("AUTO_INCREMENT", typeof(ulong));
c.AddColumn("CREATE_TIME", typeof(DateTime));
c.AddColumn("UPDATE_TIME", typeof(DateTime));
c.AddColumn("CHECK_TIME", typeof(DateTime));
c.AddColumn("TABLE_COLLATION", typeof(string));
c.AddColumn("CHECKSUM", typeof(ulong));
c.AddColumn("CREATE_OPTIONS", typeof(string));
c.AddColumn("TABLE_COMMENT", typeof(string));
// we have to new up a new restriction array here since
// GetDatabases takes the database in the first slot
string[] dbRestriction = new string[4];
if (restrictions != null && restrictions.Length >= 2)
dbRestriction[0] = restrictions[1];
MySqlSchemaCollection databases = GetDatabases(dbRestriction);
if (restrictions != null)
Array.Copy(restrictions, dbRestriction,
Math.Min(dbRestriction.Length, restrictions.Length));
foreach (MySqlSchemaRow row in databases.Rows)
{
dbRestriction[1] = row["SCHEMA_NAME"].ToString();
FindTables(c, dbRestriction);
}
return c;
}
protected void QuoteDefaultValues(MySqlSchemaCollection schemaCollection)
{
if (schemaCollection == null) return;
if (!schemaCollection.ContainsColumn("COLUMN_DEFAULT")) return;
foreach (MySqlSchemaRow row in schemaCollection.Rows)
{
object defaultValue = row["COLUMN_DEFAULT"];
if (MetaData.IsTextType(row["DATA_TYPE"].ToString()))
row["COLUMN_DEFAULT"] = String.Format("{0}", defaultValue);
}
}
public virtual MySqlSchemaCollection GetColumns(string[] restrictions)
{
MySqlSchemaCollection c = new MySqlSchemaCollection("Columns");
c.AddColumn("TABLE_CATALOG", typeof(string));
c.AddColumn("TABLE_SCHEMA", typeof(string));
c.AddColumn("TABLE_NAME", typeof(string));
c.AddColumn("COLUMN_NAME", typeof(string));
c.AddColumn("ORDINAL_POSITION", typeof(ulong));
c.AddColumn("COLUMN_DEFAULT", typeof(string));
c.AddColumn("IS_NULLABLE", typeof(string));
c.AddColumn("DATA_TYPE", typeof(string));
c.AddColumn("CHARACTER_MAXIMUM_LENGTH", typeof(ulong));
c.AddColumn("CHARACTER_OCTET_LENGTH", typeof(ulong));
c.AddColumn("NUMERIC_PRECISION", typeof(ulong));
c.AddColumn("NUMERIC_SCALE", typeof(ulong));
c.AddColumn("CHARACTER_SET_NAME", typeof(string));
c.AddColumn("COLLATION_NAME", typeof(string));
c.AddColumn("COLUMN_TYPE", typeof(string));
c.AddColumn("COLUMN_KEY", typeof(string));
c.AddColumn("EXTRA", typeof(string));
c.AddColumn("PRIVILEGES", typeof(string));
c.AddColumn("COLUMN_COMMENT", typeof(string));
c.AddColumn("GENERATION_EXPRESSION", typeof(string));
// we don't allow restricting on table type here
string columnName = null;
if (restrictions != null && restrictions.Length == 4)
{
columnName = restrictions[3];
restrictions[3] = null;
}
MySqlSchemaCollection tables = GetTables(restrictions);
foreach (MySqlSchemaRow row in tables.Rows)
LoadTableColumns(c, row["TABLE_SCHEMA"].ToString(),
row["TABLE_NAME"].ToString(), columnName);
QuoteDefaultValues(c);
return c;
}
private void LoadTableColumns(MySqlSchemaCollection schemaCollection, string schema,
string tableName, string columnRestriction)
{
string sql = String.Format("SHOW FULL COLUMNS FROM `{0}`.`{1}`",
schema, tableName);
MySqlCommand cmd = new MySqlCommand(sql, connection);
int pos = 1;
using (MySqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
string colName = reader.GetString(0);
if (columnRestriction != null && colName != columnRestriction)
continue;
MySqlSchemaRow row = schemaCollection.AddRow();
row["TABLE_CATALOG"] = DBNull.Value;
row["TABLE_SCHEMA"] = schema;
row["TABLE_NAME"] = tableName;
row["COLUMN_NAME"] = colName;
row["ORDINAL_POSITION"] = pos++;
row["COLUMN_DEFAULT"] = reader.GetValue(5);
row["IS_NULLABLE"] = reader.GetString(3);
row["DATA_TYPE"] = reader.GetString(1);
row["CHARACTER_MAXIMUM_LENGTH"] = DBNull.Value;
row["CHARACTER_OCTET_LENGTH"] = DBNull.Value;
row["NUMERIC_PRECISION"] = DBNull.Value;
row["NUMERIC_SCALE"] = DBNull.Value;
row["CHARACTER_SET_NAME"] = reader.GetValue(2);
row["COLLATION_NAME"] = row["CHARACTER_SET_NAME"];
row["COLUMN_TYPE"] = reader.GetString(1);
row["COLUMN_KEY"] = reader.GetString(4);
row["EXTRA"] = reader.GetString(6);
row["PRIVILEGES"] = reader.GetString(7);
row["COLUMN_COMMENT"] = reader.GetString(8);
#if !RT
row["GENERATION_EXPRESION"] = reader.GetString(6).Contains("VIRTUAL") ? reader.GetString(9) : string.Empty;
#endif
ParseColumnRow(row);
}
}
}
private static void ParseColumnRow(MySqlSchemaRow row)
{
// first parse the character set name
string charset = row["CHARACTER_SET_NAME"].ToString();
int index = charset.IndexOf('_');
if (index != -1)
row["CHARACTER_SET_NAME"] = charset.Substring(0, index);
// now parse the data type
string dataType = row["DATA_TYPE"].ToString();
index = dataType.IndexOf('(');
if (index == -1)
return;
row["DATA_TYPE"] = dataType.Substring(0, index);
int stop = dataType.IndexOf(')', index);
string dataLen = dataType.Substring(index + 1, stop - (index + 1));
string lowerType = row["DATA_TYPE"].ToString().ToLower();
if (lowerType == "char" || lowerType == "varchar")
row["CHARACTER_MAXIMUM_LENGTH"] = dataLen;
else if (lowerType == "real" || lowerType == "decimal")
{
string[] lenparts = dataLen.Split(new char[] { ',' });
row["NUMERIC_PRECISION"] = lenparts[0];
if (lenparts.Length == 2)
row["NUMERIC_SCALE"] = lenparts[1];
}
}
public virtual MySqlSchemaCollection GetIndexes(string[] restrictions)
{
MySqlSchemaCollection dt = new MySqlSchemaCollection("Indexes");
dt.AddColumn("INDEX_CATALOG", typeof(string));
dt.AddColumn("INDEX_SCHEMA", typeof(string));
dt.AddColumn("INDEX_NAME", typeof(string));
dt.AddColumn("TABLE_NAME", typeof(string));
dt.AddColumn("UNIQUE", typeof(bool));
dt.AddColumn("PRIMARY", typeof(bool));
dt.AddColumn("TYPE", typeof(string));
dt.AddColumn("COMMENT", typeof(string));
// Get the list of tables first
int max = restrictions == null ? 4 : restrictions.Length;
string[] tableRestrictions = new string[Math.Max(max, 4)];
if (restrictions != null)
restrictions.CopyTo(tableRestrictions, 0);
tableRestrictions[3] = "BASE TABLE";
MySqlSchemaCollection tables = GetTables(tableRestrictions);
foreach (MySqlSchemaRow table in tables.Rows)
{
string sql = String.Format("SHOW INDEX FROM `{0}`.`{1}`",
MySqlHelper.DoubleQuoteString((string)table["TABLE_SCHEMA"]),
MySqlHelper.DoubleQuoteString((string)table["TABLE_NAME"]));
MySqlSchemaCollection indexes = QueryCollection("indexes", sql);
foreach (MySqlSchemaRow index in indexes.Rows)
{
long seq_index = (long)index["SEQ_IN_INDEX"];
if (seq_index != 1) continue;
if (restrictions != null && restrictions.Length == 4 &&
restrictions[3] != null &&
!index["KEY_NAME"].Equals(restrictions[3])) continue;
MySqlSchemaRow row = dt.AddRow();
row["INDEX_CATALOG"] = null;
row["INDEX_SCHEMA"] = table["TABLE_SCHEMA"];
row["INDEX_NAME"] = index["KEY_NAME"];
row["TABLE_NAME"] = index["TABLE"];
row["UNIQUE"] = (long)index["NON_UNIQUE"] == 0;
row["PRIMARY"] = index["KEY_NAME"].Equals("PRIMARY");
row["TYPE"] = index["INDEX_TYPE"];
row["COMMENT"] = index["COMMENT"];
}
}
return dt;
}
public virtual MySqlSchemaCollection GetIndexColumns(string[] restrictions)
{
MySqlSchemaCollection dt = new MySqlSchemaCollection("IndexColumns");
dt.AddColumn("INDEX_CATALOG", typeof(string));
dt.AddColumn("INDEX_SCHEMA", typeof(string));
dt.AddColumn("INDEX_NAME", typeof(string));
dt.AddColumn("TABLE_NAME", typeof(string));
dt.AddColumn("COLUMN_NAME", typeof(string));
dt.AddColumn("ORDINAL_POSITION", typeof(int));
dt.AddColumn("SORT_ORDER", typeof(string));
int max = restrictions == null ? 4 : restrictions.Length;
string[] tableRestrictions = new string[Math.Max(max, 4)];
if (restrictions != null)
restrictions.CopyTo(tableRestrictions, 0);
tableRestrictions[3] = "BASE TABLE";
MySqlSchemaCollection tables = GetTables(tableRestrictions);
foreach (MySqlSchemaRow table in tables.Rows)
{
string sql = String.Format("SHOW INDEX FROM `{0}`.`{1}`",
table["TABLE_SCHEMA"], table["TABLE_NAME"]);
MySqlCommand cmd = new MySqlCommand(sql, connection);
using (MySqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
string key_name = GetString(reader, reader.GetOrdinal("KEY_NAME"));
string col_name = GetString(reader, reader.GetOrdinal("COLUMN_NAME"));
if (restrictions != null)
{
if (restrictions.Length >= 4 && restrictions[3] != null &&
key_name != restrictions[3]) continue;
if (restrictions.Length >= 5 && restrictions[4] != null &&
col_name != restrictions[4]) continue;
}
MySqlSchemaRow row = dt.AddRow();
row["INDEX_CATALOG"] = null;
row["INDEX_SCHEMA"] = table["TABLE_SCHEMA"];
row["INDEX_NAME"] = key_name;
row["TABLE_NAME"] = GetString(reader, reader.GetOrdinal("TABLE"));
row["COLUMN_NAME"] = col_name;
row["ORDINAL_POSITION"] = reader.GetValue(reader.GetOrdinal("SEQ_IN_INDEX"));
row["SORT_ORDER"] = reader.GetString("COLLATION");
}
}
}
return dt;
}
public virtual MySqlSchemaCollection GetForeignKeys(string[] restrictions)
{
MySqlSchemaCollection dt = new MySqlSchemaCollection("Foreign Keys");
dt.AddColumn("CONSTRAINT_CATALOG", typeof(string));
dt.AddColumn("CONSTRAINT_SCHEMA", typeof(string));
dt.AddColumn("CONSTRAINT_NAME", typeof(string));
dt.AddColumn("TABLE_CATALOG", typeof(string));
dt.AddColumn("TABLE_SCHEMA", typeof(string));
dt.AddColumn("TABLE_NAME", typeof(string));
dt.AddColumn("MATCH_OPTION", typeof(string));
dt.AddColumn("UPDATE_RULE", typeof(string));
dt.AddColumn("DELETE_RULE", typeof(string));
dt.AddColumn("REFERENCED_TABLE_CATALOG", typeof(string));
dt.AddColumn("REFERENCED_TABLE_SCHEMA", typeof(string));
dt.AddColumn("REFERENCED_TABLE_NAME", typeof(string));
// first we use our restrictions to get a list of tables that should be
// consulted. We save the keyname restriction since GetTables doesn't
// understand that.
string keyName = null;
if (restrictions != null && restrictions.Length >= 4)
{
keyName = restrictions[3];
restrictions[3] = null;
}
MySqlSchemaCollection tables = GetTables(restrictions);
// now for each table retrieved, we call our helper function to
// parse it's foreign keys
foreach (MySqlSchemaRow table in tables.Rows)
GetForeignKeysOnTable(dt, table, keyName, false);
return dt;
}
public virtual MySqlSchemaCollection GetForeignKeyColumns(string[] restrictions)
{
MySqlSchemaCollection dt = new MySqlSchemaCollection("Foreign Keys");
dt.AddColumn("CONSTRAINT_CATALOG", typeof(string));
dt.AddColumn("CONSTRAINT_SCHEMA", typeof(string));
dt.AddColumn("CONSTRAINT_NAME", typeof(string));
dt.AddColumn("TABLE_CATALOG", typeof(string));
dt.AddColumn("TABLE_SCHEMA", typeof(string));
dt.AddColumn("TABLE_NAME", typeof(string));
dt.AddColumn("COLUMN_NAME", typeof(string));
dt.AddColumn("ORDINAL_POSITION", typeof(int));
dt.AddColumn("REFERENCED_TABLE_CATALOG", typeof(string));
dt.AddColumn("REFERENCED_TABLE_SCHEMA", typeof(string));
dt.AddColumn("REFERENCED_TABLE_NAME", typeof(string));
dt.AddColumn("REFERENCED_COLUMN_NAME", typeof(string));
// first we use our restrictions to get a list of tables that should be
// consulted. We save the keyname restriction since GetTables doesn't
// understand that.
string keyName = null;
if (restrictions != null && restrictions.Length >= 4)
{
keyName = restrictions[3];
restrictions[3] = null;
}
MySqlSchemaCollection tables = GetTables(restrictions);
// now for each table retrieved, we call our helper function to
// parse it's foreign keys
foreach (MySqlSchemaRow table in tables.Rows)
GetForeignKeysOnTable(dt, table, keyName, true);
return dt;
}
private string GetSqlMode()
{
MySqlCommand cmd = new MySqlCommand("SELECT @@SQL_MODE", connection);
return cmd.ExecuteScalar().ToString();
}
#region Foreign Key routines
/// <summary>
/// GetForeignKeysOnTable retrieves the foreign keys on the given table.
/// Since MySQL supports foreign keys on versions prior to 5.0, we can't use
/// information schema. MySQL also does not include any type of SHOW command
/// for foreign keys so we have to resort to use SHOW CREATE TABLE and parsing
/// the output.
/// </summary>
/// <param name="fkTable">The table to store the key info in.</param>
/// <param name="tableToParse">The table to get the foeign key info for.</param>
/// <param name="filterName">Only get foreign keys that match this name.</param>
/// <param name="includeColumns">Should column information be included in the table.</param>
private void GetForeignKeysOnTable(MySqlSchemaCollection fkTable, MySqlSchemaRow tableToParse,
string filterName, bool includeColumns)
{
string sqlMode = GetSqlMode();
if (filterName != null)
filterName = StringUtility.ToLowerInvariant(filterName);
string sql = string.Format("SHOW CREATE TABLE `{0}`.`{1}`",
tableToParse["TABLE_SCHEMA"], tableToParse["TABLE_NAME"]);
string lowerBody = null, body = null;
MySqlCommand cmd = new MySqlCommand(sql, connection);
using (MySqlDataReader reader = cmd.ExecuteReader())
{
reader.Read();
body = reader.GetString(1);
lowerBody = StringUtility.ToLowerInvariant(body);
}
MySqlTokenizer tokenizer = new MySqlTokenizer(lowerBody);
tokenizer.AnsiQuotes = sqlMode.IndexOf("ANSI_QUOTES") != -1;
tokenizer.BackslashEscapes = sqlMode.IndexOf("NO_BACKSLASH_ESCAPES") != -1;
while (true)
{
string token = tokenizer.NextToken();
// look for a starting contraint
while (token != null && (token != "constraint" || tokenizer.Quoted))
token = tokenizer.NextToken();
if (token == null) break;
ParseConstraint(fkTable, tableToParse, tokenizer, includeColumns);
}
}
private static void ParseConstraint(MySqlSchemaCollection fkTable, MySqlSchemaRow table,
MySqlTokenizer tokenizer, bool includeColumns)
{
string name = tokenizer.NextToken();
MySqlSchemaRow row = fkTable.AddRow();
// make sure this constraint is a FK
string token = tokenizer.NextToken();
if (token != "foreign" || tokenizer.Quoted)
return;
tokenizer.NextToken(); // read off the 'KEY' symbol
tokenizer.NextToken(); // read off the '(' symbol
row["CONSTRAINT_CATALOG"] = table["TABLE_CATALOG"];
row["CONSTRAINT_SCHEMA"] = table["TABLE_SCHEMA"];
row["TABLE_CATALOG"] = table["TABLE_CATALOG"];
row["TABLE_SCHEMA"] = table["TABLE_SCHEMA"];
row["TABLE_NAME"] = table["TABLE_NAME"];
row["REFERENCED_TABLE_CATALOG"] = null;
row["CONSTRAINT_NAME"] = name.Trim(new char[] { '\'', '`' });
List<string> srcColumns = includeColumns ? ParseColumns(tokenizer) : null;
// now look for the references section
while (token != "references" || tokenizer.Quoted)
token = tokenizer.NextToken();
string target1 = tokenizer.NextToken();
string target2 = tokenizer.NextToken();
if (target2.StartsWith(".", StringComparison.Ordinal))
{
row["REFERENCED_TABLE_SCHEMA"] = target1;
row["REFERENCED_TABLE_NAME"] = target2.Substring(1).Trim(new char[] { '\'', '`' });
tokenizer.NextToken(); // read off the '('
}
else
{
row["REFERENCED_TABLE_SCHEMA"] = table["TABLE_SCHEMA"];
row["REFERENCED_TABLE_NAME"] = target1.Substring(1).Trim(new char[] { '\'', '`' }); ;
}
// if we are supposed to include columns, read the target columns
List<string> targetColumns = includeColumns ? ParseColumns(tokenizer) : null;
if (includeColumns)
ProcessColumns(fkTable, row, srcColumns, targetColumns);
else
fkTable.Rows.Add(row);
}
private static List<string> ParseColumns(MySqlTokenizer tokenizer)
{
List<string> sc = new List<string>();
string token = tokenizer.NextToken();
while (token != ")")
{
if (token != ",")
sc.Add(token);
token = tokenizer.NextToken();
}
return sc;
}
private static void ProcessColumns(MySqlSchemaCollection fkTable, MySqlSchemaRow row, List<string> srcColumns, List<string> targetColumns)
{
for (int i = 0; i < srcColumns.Count; i++)
{
MySqlSchemaRow newRow = fkTable.AddRow();
row.CopyRow(newRow);
newRow["COLUMN_NAME"] = srcColumns[i];
newRow["ORDINAL_POSITION"] = i;
newRow["REFERENCED_COLUMN_NAME"] = targetColumns[i];
fkTable.Rows.Add(newRow);
}
}
#endregion
public virtual MySqlSchemaCollection GetUsers(string[] restrictions)
{
StringBuilder sb = new StringBuilder("SELECT Host, User FROM mysql.user");
if (restrictions != null && restrictions.Length > 0)
sb.AppendFormat(CultureInfo.InvariantCulture, " WHERE User LIKE '{0}'", restrictions[0]);
MySqlSchemaCollection c = QueryCollection("Users", sb.ToString());
c.Columns[0].Name = "HOST";
c.Columns[1].Name = "USERNAME";
return c;
}
public virtual MySqlSchemaCollection GetProcedures(string[] restrictions)
{
MySqlSchemaCollection dt = new MySqlSchemaCollection("Procedures");
dt.AddColumn("SPECIFIC_NAME", typeof(string));
dt.AddColumn("ROUTINE_CATALOG", typeof(string));
dt.AddColumn("ROUTINE_SCHEMA", typeof(string));
dt.AddColumn("ROUTINE_NAME", typeof(string));
dt.AddColumn("ROUTINE_TYPE", typeof(string));
dt.AddColumn("DTD_IDENTIFIER", typeof(string));
dt.AddColumn("ROUTINE_BODY", typeof(string));
dt.AddColumn("ROUTINE_DEFINITION", typeof(string));
dt.AddColumn("EXTERNAL_NAME", typeof(string));
dt.AddColumn("EXTERNAL_LANGUAGE", typeof(string));
dt.AddColumn("PARAMETER_STYLE", typeof(string));
dt.AddColumn("IS_DETERMINISTIC", typeof(string));
dt.AddColumn("SQL_DATA_ACCESS", typeof(string));
dt.AddColumn("SQL_PATH", typeof(string));
dt.AddColumn("SECURITY_TYPE", typeof(string));
dt.AddColumn("CREATED", typeof(DateTime));
dt.AddColumn("LAST_ALTERED", typeof(DateTime));
dt.AddColumn("SQL_MODE", typeof(string));
dt.AddColumn("ROUTINE_COMMENT", typeof(string));
dt.AddColumn("DEFINER", typeof(string));
StringBuilder sql = new StringBuilder("SELECT * FROM mysql.proc WHERE 1=1");
if (restrictions != null)
{
if (restrictions.Length >= 2 && restrictions[1] != null)
sql.AppendFormat(CultureInfo.InvariantCulture,
" AND db LIKE '{0}'", restrictions[1]);
if (restrictions.Length >= 3 && restrictions[2] != null)
sql.AppendFormat(CultureInfo.InvariantCulture,
" AND name LIKE '{0}'", restrictions[2]);
if (restrictions.Length >= 4 && restrictions[3] != null)
sql.AppendFormat(CultureInfo.InvariantCulture,
" AND type LIKE '{0}'", restrictions[3]);
}
MySqlCommand cmd = new MySqlCommand(sql.ToString(), connection);
using (MySqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
MySqlSchemaRow row = dt.AddRow();
row["SPECIFIC_NAME"] = reader.GetString("specific_name");
row["ROUTINE_CATALOG"] = DBNull.Value;
row["ROUTINE_SCHEMA"] = reader.GetString("db");
row["ROUTINE_NAME"] = reader.GetString("name");
string routineType = reader.GetString("type");
row["ROUTINE_TYPE"] = routineType;
row["DTD_IDENTIFIER"] = StringUtility.ToLowerInvariant(routineType) == "function" ?
(object)reader.GetString("returns") : DBNull.Value;
row["ROUTINE_BODY"] = "SQL";
row["ROUTINE_DEFINITION"] = reader.GetString("body");
row["EXTERNAL_NAME"] = DBNull.Value;
row["EXTERNAL_LANGUAGE"] = DBNull.Value;
row["PARAMETER_STYLE"] = "SQL";
row["IS_DETERMINISTIC"] = reader.GetString("is_deterministic");
row["SQL_DATA_ACCESS"] = reader.GetString("sql_data_access");
row["SQL_PATH"] = DBNull.Value;
row["SECURITY_TYPE"] = reader.GetString("security_type");
row["CREATED"] = reader.GetDateTime("created");
row["LAST_ALTERED"] = reader.GetDateTime("modified");
row["SQL_MODE"] = reader.GetString("sql_mode");
row["ROUTINE_COMMENT"] = reader.GetString("comment");
row["DEFINER"] = reader.GetString("definer");
}
}
return dt;
}
protected virtual MySqlSchemaCollection GetCollections()
{
object[][] collections = new object[][]
{
new object[] {"MetaDataCollections", 0, 0},
new object[] {"DataSourceInformation", 0, 0},
new object[] {"DataTypes", 0, 0},
new object[] {"Restrictions", 0, 0},
new object[] {"ReservedWords", 0, 0},
new object[] {"Databases", 1, 1},
new object[] {"Tables", 4, 2},
new object[] {"Columns", 4, 4},
new object[] {"Users", 1, 1},
new object[] {"Foreign Keys", 4, 3},
new object[] {"IndexColumns", 5, 4},
new object[] {"Indexes", 4, 3},
new object[] {"Foreign Key Columns", 4, 3},
new object[] {"UDF", 1, 1}
};
MySqlSchemaCollection dt = new MySqlSchemaCollection("MetaDataCollections");
dt.AddColumn("CollectionName", typeof(string));
dt.AddColumn("NumberOfRestrictions", typeof(int));
dt.AddColumn("NumberOfIdentifierParts", typeof(int));
FillTable(dt, collections);
return dt;
}
private MySqlSchemaCollection GetDataSourceInformation()
{
#if RT
throw new NotSupportedException();
#else
MySqlSchemaCollection dt = new MySqlSchemaCollection("DataSourceInformation");
dt.AddColumn("CompositeIdentifierSeparatorPattern", typeof(string));
dt.AddColumn("DataSourceProductName", typeof(string));
dt.AddColumn("DataSourceProductVersion", typeof(string));
dt.AddColumn("DataSourceProductVersionNormalized", typeof(string));
dt.AddColumn("GroupByBehavior", typeof(GroupByBehavior));
dt.AddColumn("IdentifierPattern", typeof(string));
dt.AddColumn("IdentifierCase", typeof(IdentifierCase));
dt.AddColumn("OrderByColumnsInSelect", typeof(bool));
dt.AddColumn("ParameterMarkerFormat", typeof(string));
dt.AddColumn("ParameterMarkerPattern", typeof(string));
dt.AddColumn("ParameterNameMaxLength", typeof(int));
dt.AddColumn("ParameterNamePattern", typeof(string));
dt.AddColumn("QuotedIdentifierPattern", typeof(string));
dt.AddColumn("QuotedIdentifierCase", typeof(IdentifierCase));
dt.AddColumn("StatementSeparatorPattern", typeof(string));
dt.AddColumn("StringLiteralPattern", typeof(string));
dt.AddColumn("SupportedJoinOperators", typeof(SupportedJoinOperators));
DBVersion v = connection.driver.Version;
string ver = String.Format("{0:0}.{1:0}.{2:0}",
v.Major, v.Minor, v.Build);
MySqlSchemaRow row = dt.AddRow();
row["CompositeIdentifierSeparatorPattern"] = "\\.";
row["DataSourceProductName"] = "MySQL";
row["DataSourceProductVersion"] = connection.ServerVersion;
row["DataSourceProductVersionNormalized"] = ver;
row["GroupByBehavior"] = GroupByBehavior.Unrelated;
row["IdentifierPattern"] =
@"(^\`\p{Lo}\p{Lu}\p{Ll}_@#][\p{Lo}\p{Lu}\p{Ll}\p{Nd}@$#_]*$)|(^\`[^\`\0]|\`\`+\`$)|(^\"" + [^\""\0]|\""\""+\""$)";
row["IdentifierCase"] = IdentifierCase.Insensitive;
row["OrderByColumnsInSelect"] = false;
row["ParameterMarkerFormat"] = "{0}";
row["ParameterMarkerPattern"] = "(@[A-Za-z0-9_$#]*)";
row["ParameterNameMaxLength"] = 128;
row["ParameterNamePattern"] =
@"^[\p{Lo}\p{Lu}\p{Ll}\p{Lm}_@#][\p{Lo}\p{Lu}\p{Ll}\p{Lm}\p{Nd}\uff3f_@#\$]*(?=\s+|$)";
row["QuotedIdentifierPattern"] = @"(([^\`]|\`\`)*)";
row["QuotedIdentifierCase"] = IdentifierCase.Sensitive;
row["StatementSeparatorPattern"] = ";";
row["StringLiteralPattern"] = "'(([^']|'')*)'";
row["SupportedJoinOperators"] = 15;
dt.Rows.Add(row);
return dt;
#endif
}
private static MySqlSchemaCollection GetDataTypes()
{
MySqlSchemaCollection dt = new MySqlSchemaCollection("DataTypes");
dt.AddColumn("TypeName", typeof(string));
dt.AddColumn("ProviderDbType", typeof(int));
dt.AddColumn("ColumnSize", typeof(long));
dt.AddColumn("CreateFormat", typeof(string));
dt.AddColumn("CreateParameters", typeof(string));
dt.AddColumn("DataType", typeof(string));
dt.AddColumn("IsAutoincrementable", typeof(bool));
dt.AddColumn("IsBestMatch", typeof(bool));
dt.AddColumn("IsCaseSensitive", typeof(bool));
dt.AddColumn("IsFixedLength", typeof(bool));
dt.AddColumn("IsFixedPrecisionScale", typeof(bool));
dt.AddColumn("IsLong", typeof(bool));
dt.AddColumn("IsNullable", typeof(bool));
dt.AddColumn("IsSearchable", typeof(bool));
dt.AddColumn("IsSearchableWithLike", typeof(bool));
dt.AddColumn("IsUnsigned", typeof(bool));
dt.AddColumn("MaximumScale", typeof(short));
dt.AddColumn("MinimumScale", typeof(short));
dt.AddColumn("IsConcurrencyType", typeof(bool));
dt.AddColumn("IsLiteralSupported", typeof(bool));
dt.AddColumn("LiteralPrefix", typeof(string));
dt.AddColumn("LiteralSuffix", typeof(string));
dt.AddColumn("NativeDataType", typeof(string));
// have each one of the types contribute to the datatypes collection
MySqlBit.SetDSInfo(dt);
MySqlBinary.SetDSInfo(dt);
MySqlDateTime.SetDSInfo(dt);
MySqlTimeSpan.SetDSInfo(dt);
MySqlString.SetDSInfo(dt);
MySqlDouble.SetDSInfo(dt);
MySqlSingle.SetDSInfo(dt);
MySqlByte.SetDSInfo(dt);
MySqlInt16.SetDSInfo(dt);
MySqlInt32.SetDSInfo(dt);
MySqlInt64.SetDSInfo(dt);
MySqlDecimal.SetDSInfo(dt);
MySqlUByte.SetDSInfo(dt);
MySqlUInt16.SetDSInfo(dt);
MySqlUInt32.SetDSInfo(dt);
MySqlUInt64.SetDSInfo(dt);
return dt;
}
protected virtual MySqlSchemaCollection GetRestrictions()
{
object[][] restrictions = new object[][]
{
new object[] {"Users", "Name", "", 0},
new object[] {"Databases", "Name", "", 0},
new object[] {"Tables", "Database", "", 0},
new object[] {"Tables", "Schema", "", 1},
new object[] {"Tables", "Table", "", 2},
new object[] {"Tables", "TableType", "", 3},
new object[] {"Columns", "Database", "", 0},
new object[] {"Columns", "Schema", "", 1},
new object[] {"Columns", "Table", "", 2},
new object[] {"Columns", "Column", "", 3},
new object[] {"Indexes", "Database", "", 0},
new object[] {"Indexes", "Schema", "", 1},
new object[] {"Indexes", "Table", "", 2},
new object[] {"Indexes", "Name", "", 3},
new object[] {"IndexColumns", "Database", "", 0},
new object[] {"IndexColumns", "Schema", "", 1},
new object[] {"IndexColumns", "Table", "", 2},
new object[] {"IndexColumns", "ConstraintName", "", 3},
new object[] {"IndexColumns", "Column", "", 4},
new object[] {"Foreign Keys", "Database", "", 0},
new object[] {"Foreign Keys", "Schema", "", 1},
new object[] {"Foreign Keys", "Table", "", 2},
new object[] {"Foreign Keys", "Constraint Name", "", 3},
new object[] {"Foreign Key Columns", "Catalog", "", 0},
new object[] {"Foreign Key Columns", "Schema", "", 1},
new object[] {"Foreign Key Columns", "Table", "", 2},
new object[] {"Foreign Key Columns", "Constraint Name", "", 3},
new object[] {"UDF", "Name", "", 0}
};
MySqlSchemaCollection dt = new MySqlSchemaCollection("Restrictions");
dt.AddColumn("CollectionName", typeof(string));
dt.AddColumn("RestrictionName", typeof(string));
dt.AddColumn("RestrictionDefault", typeof(string));
dt.AddColumn("RestrictionNumber", typeof(int));
FillTable(dt, restrictions);
return dt;
}
private static MySqlSchemaCollection GetReservedWords()
{
MySqlSchemaCollection dt = new MySqlSchemaCollection("ReservedWords");
#if !RT
dt.AddColumn(DbMetaDataColumnNames.ReservedWord, typeof(string));
Stream str = Assembly.GetExecutingAssembly().GetManifestResourceStream(
"MySql.Data.MySqlClient.Properties.ReservedWords.txt");
#else
dt.AddColumn("ReservedWord", typeof(string));
Stream str = typeof(SchemaProvider).GetTypeInfo().Assembly.GetManifestResourceStream("MySql.Data.MySqlClient.Properties.ReservedWords.txt");
#endif
StreamReader sr = new StreamReader(str);
string line = sr.ReadLine();
while (line != null)
{
string[] keywords = line.Split(new char[] { ' ' });
foreach (string s in keywords)
{
if (String.IsNullOrEmpty(s)) continue;
MySqlSchemaRow row = dt.AddRow();
row[0] = s;
}
line = sr.ReadLine();
}
sr.Dispose();
str.Close();
return dt;
}
protected static void FillTable(MySqlSchemaCollection dt, object[][] data)
{
foreach (object[] dataItem in data)
{
MySqlSchemaRow row = dt.AddRow();
for (int i = 0; i < dataItem.Length; i++)
row[i] = dataItem[i];
}
}
private void FindTables(MySqlSchemaCollection schema, string[] restrictions)
{
StringBuilder sql = new StringBuilder();
StringBuilder where = new StringBuilder();
sql.AppendFormat(CultureInfo.InvariantCulture,
"SHOW TABLE STATUS FROM `{0}`", restrictions[1]);
if (restrictions != null && restrictions.Length >= 3 &&
restrictions[2] != null)
where.AppendFormat(CultureInfo.InvariantCulture,
" LIKE '{0}'", restrictions[2]);
sql.Append(where.ToString());
string table_type = restrictions[1].ToLower() == "information_schema"
?
"SYSTEM VIEW"
: "BASE TABLE";
MySqlCommand cmd = new MySqlCommand(sql.ToString(), connection);
using (MySqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
MySqlSchemaRow row = schema.AddRow();
row["TABLE_CATALOG"] = null;
row["TABLE_SCHEMA"] = restrictions[1];
row["TABLE_NAME"] = reader.GetString(0);
row["TABLE_TYPE"] = table_type;
row["ENGINE"] = GetString(reader, 1);
row["VERSION"] = reader.GetValue(2);
row["ROW_FORMAT"] = GetString(reader, 3);
row["TABLE_ROWS"] = reader.GetValue(4);
row["AVG_ROW_LENGTH"] = reader.GetValue(5);
row["DATA_LENGTH"] = reader.GetValue(6);
row["MAX_DATA_LENGTH"] = reader.GetValue(7);
row["INDEX_LENGTH"] = reader.GetValue(8);
row["DATA_FREE"] = reader.GetValue(9);
row["AUTO_INCREMENT"] = reader.GetValue(10);
row["CREATE_TIME"] = reader.GetValue(11);
row["UPDATE_TIME"] = reader.GetValue(12);
row["CHECK_TIME"] = reader.GetValue(13);
row["TABLE_COLLATION"] = GetString(reader, 14);
row["CHECKSUM"] = reader.GetValue(15);
row["CREATE_OPTIONS"] = GetString(reader, 16);
row["TABLE_COMMENT"] = GetString(reader, 17);
}
}
}
private static string GetString(MySqlDataReader reader, int index)
{
if (reader.IsDBNull(index))
return null;
return reader.GetString(index);
}
public virtual MySqlSchemaCollection GetUDF(string[] restrictions)
{
string sql = "SELECT name,ret,dl FROM mysql.func";
if (restrictions != null)
{
if (restrictions.Length >= 1 && !String.IsNullOrEmpty(restrictions[0]))
sql += String.Format(" WHERE name LIKE '{0}'", restrictions[0]);
}
MySqlSchemaCollection dt = new MySqlSchemaCollection("User-defined Functions");
dt.AddColumn("NAME", typeof(string));
dt.AddColumn("RETURN_TYPE", typeof(int));
dt.AddColumn("LIBRARY_NAME", typeof(string));
MySqlCommand cmd = new MySqlCommand(sql, connection);
try
{
using (MySqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
MySqlSchemaRow row = dt.AddRow();
row[0] = reader.GetString(0);
row[1] = reader.GetInt32(1);
row[2] = reader.GetString(2);
}
}
}
catch (MySqlException ex)
{
if (ex.Number != (int)MySqlErrorCode.TableAccessDenied)
throw;
throw new MySqlException(Resources.UnableToEnumerateUDF, ex);
}
return dt;
}
protected virtual MySqlSchemaCollection GetSchemaInternal(string collection, string[] restrictions)
{
switch (collection)
{
// common collections
case "METADATACOLLECTIONS":
return GetCollections();
case "DATASOURCEINFORMATION":
return GetDataSourceInformation();
case "DATATYPES":
return GetDataTypes();
case "RESTRICTIONS":
return GetRestrictions();
case "RESERVEDWORDS":
return GetReservedWords();
// collections specific to our provider
case "USERS":
return GetUsers(restrictions);
case "DATABASES":
return GetDatabases(restrictions);
case "UDF":
return GetUDF(restrictions);
}
// if we have a current database and our users have
// not specified a database, then default to the currently
// selected one.
if (restrictions == null)
restrictions = new string[2];
if (connection != null &&
connection.Database != null &&
connection.Database.Length > 0 &&
restrictions.Length > 1 &&
restrictions[1] == null)
restrictions[1] = connection.Database;
switch (collection)
{
case "TABLES":
return GetTables(restrictions);
case "COLUMNS":
return GetColumns(restrictions);
case "INDEXES":
return GetIndexes(restrictions);
case "INDEXCOLUMNS":
return GetIndexColumns(restrictions);
case "FOREIGN KEYS":
return GetForeignKeys(restrictions);
case "FOREIGN KEY COLUMNS":
return GetForeignKeyColumns(restrictions);
}
return null;
}
internal string[] CleanRestrictions(string[] restrictionValues)
{
string[] restrictions = null;
if (restrictionValues != null)
{
restrictions = (string[])restrictionValues.Clone();
for (int x = 0; x < restrictions.Length; x++)
{
string s = restrictions[x];
if (s == null) continue;
restrictions[x] = s.Trim('`');
}
}
return restrictions;
}
protected MySqlSchemaCollection QueryCollection(string name, string sql)
{
MySqlSchemaCollection c = new MySqlSchemaCollection(name);
MySqlCommand cmd = new MySqlCommand(sql, connection);
MySqlDataReader reader = cmd.ExecuteReader();
for (int i = 0; i < reader.FieldCount; i++)
c.AddColumn(reader.GetName(i), reader.GetFieldType(i));
using (reader)
{
while (reader.Read())
{
MySqlSchemaRow row = c.AddRow();
for (int i = 0; i < reader.FieldCount; i++)
row[i] = reader.GetValue(i);
}
}
return c;
}
}
}
| |
/*
* UTF7Encoding.cs - Implementation of the
* "System.Text.UTF7Encoding" class.
*
* Copyright (C) 2001 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Text
{
using System;
[Serializable]
#if ECMA_COMPAT
internal
#else
public
#endif
class UTF7Encoding : Encoding
{
// Magic number used by Windows for UTF-7.
internal const int UTF7_CODE_PAGE = 65000;
// Internal state.
private bool allowOptionals;
// Encoding rule table for 0x00-0x7F.
// 0 - full encode, 1 - direct, 2 - optional, 3 - encode plus.
private static readonly byte[] encodingRules = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, // 00
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 10
1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 2, 3, 1, 1, 1, 1, // 20
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 1, // 30
2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 40
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 0, 2, 2, 2, // 50
2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 60
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 0, 0, // 70
};
// Characters to use to encode 6-bit values in base64.
private const String base64Chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
// Map bytes in base64 to 6-bit values.
private static readonly sbyte[] base64Values = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 00
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 10
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, 63, // 20
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, // 30
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, // 40
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, // 50
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, // 60
42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, -1, // 70
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 80
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 90
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // A0
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // B0
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // C0
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // D0
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // E0
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // F0
};
// Constructors.
public UTF7Encoding()
: base(UTF7_CODE_PAGE)
{
allowOptionals = false;
}
public UTF7Encoding(bool allowOptionals)
: base(UTF7_CODE_PAGE)
{
this.allowOptionals = allowOptionals;
}
// Internal version of "GetByteCount" that can handle
// a rolling state between calls.
private static int InternalGetByteCount
(char[] chars, int index, int count, bool flush,
int leftOver, bool allowOptionals)
{
// Validate the parameters.
if(chars == null)
{
throw new ArgumentNullException("chars");
}
if(index < 0 || index > chars.Length)
{
throw new ArgumentOutOfRangeException
("index", _("ArgRange_Array"));
}
if(count < 0 || count > (chars.Length - index))
{
throw new ArgumentOutOfRangeException
("count", _("ArgRange_Array"));
}
// Determine the length of the output.
int length = 0;
int leftOverSize = (leftOver >> 8);
byte[] rules = encodingRules;
int ch, rule;
while(count > 0)
{
ch = (int)(chars[index++]);
--count;
if(ch < 0x0080)
{
rule = rules[ch];
}
else
{
rule = 0;
}
switch(rule)
{
case 0:
{
// Handle characters that must be fully encoded.
if(leftOverSize == 0)
{
++length;
}
leftOverSize += 16;
while(leftOverSize >= 6)
{
++length;
leftOverSize -= 6;
}
}
break;
case 1:
{
// The character is encoded as itself.
if(leftOverSize != 0)
{
// Flush the previous encoded sequence.
length += 2;
leftOverSize = 0;
}
++length;
}
break;
case 2:
{
// The character may need to be encoded.
if(allowOptionals)
{
goto case 1;
}
else
{
goto case 0;
}
}
// Not reached.
case 3:
{
// Encode the plus sign as "+-".
if(leftOverSize != 0)
{
// Flush the previous encoded sequence.
length += 2;
leftOverSize = 0;
}
length += 2;
}
break;
}
}
if(leftOverSize != 0 && flush)
{
length += 2;
}
// Return the length to the caller.
return length;
}
// Get the number of bytes needed to encode a character buffer.
public override int GetByteCount(char[] chars, int index, int count)
{
return InternalGetByteCount(chars, index, count,
true, 0, allowOptionals);
}
// Internal version of "GetBytes" that can handle a
// rolling state between calls.
private static int InternalGetBytes
(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex, bool flush,
ref int leftOver, bool allowOptionals)
{
// Validate the parameters.
if(chars == null)
{
throw new ArgumentNullException("chars");
}
if(bytes == null)
{
throw new ArgumentNullException("bytes");
}
if(charIndex < 0 || charIndex > chars.Length)
{
throw new ArgumentOutOfRangeException
("charIndex", _("ArgRange_Array"));
}
if(charCount < 0 || charCount > (chars.Length - charIndex))
{
throw new ArgumentOutOfRangeException
("charCount", _("ArgRange_Array"));
}
if(byteIndex < 0 || byteIndex > bytes.Length)
{
throw new ArgumentOutOfRangeException
("byteIndex", _("ArgRange_Array"));
}
// Convert the characters.
int posn = byteIndex;
int byteLength = bytes.Length;
int leftOverSize = (leftOver >> 8);
int leftOverBits = (leftOver & 0xFF);
byte[] rules = encodingRules;
String base64 = base64Chars;
int ch, rule;
while(charCount > 0)
{
ch = (int)(chars[charIndex++]);
--charCount;
if(ch < 0x0080)
{
rule = rules[ch];
}
else
{
rule = 0;
}
switch(rule)
{
case 0:
{
// Handle characters that must be fully encoded.
if(leftOverSize == 0)
{
if(posn >= byteLength)
{
throw new ArgumentException
(_("Arg_InsufficientSpace"), "bytes");
}
bytes[posn++] = (byte)'+';
}
leftOverBits = ((leftOverBits << 16) | ch);
leftOverSize += 16;
while(leftOverSize >= 6)
{
if(posn >= byteLength)
{
throw new ArgumentException
(_("Arg_InsufficientSpace"), "bytes");
}
leftOverSize -= 6;
bytes[posn++] = (byte)(base64
[leftOverBits >> leftOverSize]);
leftOverBits &= ((1 << leftOverSize) - 1);
}
}
break;
case 1:
{
// The character is encoded as itself.
if(leftOverSize != 0)
{
// Flush the previous encoded sequence.
if((posn + 2) > byteLength)
{
throw new ArgumentException
(_("Arg_InsufficientSpace"), "bytes");
}
bytes[posn++] = (byte)(base64
[leftOverBits << (6 - leftOverSize)]);
bytes[posn++] = (byte)'-';
leftOverSize = 0;
leftOverBits = 0;
}
if(posn >= byteLength)
{
throw new ArgumentException
(_("Arg_InsufficientSpace"), "bytes");
}
bytes[posn++] = (byte)ch;
}
break;
case 2:
{
// The character may need to be encoded.
if(allowOptionals)
{
goto case 1;
}
else
{
goto case 0;
}
}
// Not reached.
case 3:
{
// Encode the plus sign as "+-".
if(leftOverSize != 0)
{
// Flush the previous encoded sequence.
if((posn + 2) > byteLength)
{
throw new ArgumentException
(_("Arg_InsufficientSpace"), "bytes");
}
bytes[posn++] = (byte)(base64
[leftOverBits << (6 - leftOverSize)]);
bytes[posn++] = (byte)'-';
leftOverSize = 0;
leftOverBits = 0;
}
if((posn + 2) > byteLength)
{
throw new ArgumentException
(_("Arg_InsufficientSpace"), "bytes");
}
bytes[posn++] = (byte)'+';
bytes[posn++] = (byte)'-';
}
break;
}
}
if(leftOverSize != 0 && flush)
{
if((posn + 2) > byteLength)
{
throw new ArgumentException
(_("Arg_InsufficientSpace"), "bytes");
}
bytes[posn++] = (byte)(base64
[leftOverBits << (6 - leftOverSize)]);
bytes[posn++] = (byte)'-';
leftOverSize = 0;
leftOverBits = 0;
}
leftOver = ((leftOverSize << 8) | leftOverBits);
// Return the length to the caller.
return posn - byteIndex;
}
// Get the bytes that result from encoding a character buffer.
public override int GetBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
int leftOver = 0;
return InternalGetBytes(chars, charIndex, charCount,
bytes, byteIndex, true,
ref leftOver, allowOptionals);
}
// Internal version of "GetCharCount" that can handle
// a rolling state between call.s
private static int InternalGetCharCount
(byte[] bytes, int index, int count, int leftOver)
{
// Validate the parameters.
if(bytes == null)
{
throw new ArgumentNullException("bytes");
}
if(index < 0 || index > bytes.Length)
{
throw new ArgumentOutOfRangeException
("index", _("ArgRange_Array"));
}
if(count < 0 || count > (bytes.Length - index))
{
throw new ArgumentOutOfRangeException
("count", _("ArgRange_Array"));
}
// Determine the length of the result.
int length = 0;
int byteval, b64value;
bool normal = ((leftOver & 0x01000000) == 0);
bool prevIsPlus = ((leftOver & 0x02000000) != 0);
int leftOverSize = ((leftOver >> 16) & 0xFF);
sbyte[] base64 = base64Values;
while(count > 0)
{
byteval = (int)(bytes[index++]);
--count;
if(normal)
{
if(byteval != '+')
{
// Directly-encoded character.
++length;
}
else
{
// Start of a base64-encoded character.
normal = false;
prevIsPlus = true;
}
}
else
{
// Process the next byte in a base64 sequence.
if(byteval == (int)'-')
{
// End of a base64 sequence.
if(prevIsPlus || leftOverSize > 0)
{
++length;
leftOverSize = 0;
}
normal = true;
}
else if((b64value = base64[byteval]) != -1)
{
// Extra character in a base64 sequence.
leftOverSize += 6;
if(leftOverSize >= 16)
{
++length;
leftOverSize -= 16;
}
}
else
{
// Normal character terminating a base64 sequence.
if(leftOverSize > 0)
{
++length;
leftOverSize = 0;
}
++length;
normal = true;
}
prevIsPlus = false;
}
}
// Return the final length to the caller.
return length;
}
// Get the number of characters needed to decode a byte buffer.
public override int GetCharCount(byte[] bytes, int index, int count)
{
return InternalGetCharCount(bytes, index, count, 0);
}
// Internal version of "GetChars" that can handle a
// rolling state between calls.
private static int InternalGetChars
(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex, ref int leftOver)
{
// Validate the parameters.
if(bytes == null)
{
throw new ArgumentNullException("bytes");
}
if(chars == null)
{
throw new ArgumentNullException("chars");
}
if(byteIndex < 0 || byteIndex > bytes.Length)
{
throw new ArgumentOutOfRangeException
("byteIndex", _("ArgRange_Array"));
}
if(byteCount < 0 || byteCount > (bytes.Length - byteIndex))
{
throw new ArgumentOutOfRangeException
("byteCount", _("ArgRange_Array"));
}
if(charIndex < 0 || charIndex > chars.Length)
{
throw new ArgumentOutOfRangeException
("charIndex", _("ArgRange_Array"));
}
// Convert the bytes into characters.
int posn = charIndex;
int charLength = chars.Length;
int byteval, b64value;
bool normal = ((leftOver & 0x01000000) == 0);
bool prevIsPlus = ((leftOver & 0x02000000) != 0);
int leftOverSize = ((leftOver >> 16) & 0xFF);
int leftOverBits = (leftOver & 0xFFFF);
sbyte[] base64 = base64Values;
while(byteCount > 0)
{
byteval = (int)(bytes[byteIndex++]);
--byteCount;
if(normal)
{
if(byteval != '+')
{
// Directly-encoded character.
if(posn >= charLength)
{
throw new ArgumentException
(_("Arg_InsufficientSpace"), "chars");
}
chars[posn++] = (char)byteval;
}
else
{
// Start of a base64-encoded character.
normal = false;
prevIsPlus = true;
}
}
else
{
// Process the next byte in a base64 sequence.
if(byteval == (int)'-')
{
// End of a base64 sequence.
if(prevIsPlus)
{
if(posn >= charLength)
{
throw new ArgumentException
(_("Arg_InsufficientSpace"), "chars");
}
chars[posn++] = '+';
}
else if(leftOverSize > 0)
{
if(posn >= charLength)
{
throw new ArgumentException
(_("Arg_InsufficientSpace"), "chars");
}
chars[posn++] =
(char)(leftOverBits << (16 - leftOverSize));
leftOverSize = 0;
leftOverBits = 0;
}
normal = true;
}
else if((b64value = base64[byteval]) != -1)
{
// Extra character in a base64 sequence.
leftOverBits = (leftOverBits << 6) | b64value;
leftOverSize += 6;
if(leftOverSize >= 16)
{
if(posn >= charLength)
{
throw new ArgumentException
(_("Arg_InsufficientSpace"), "chars");
}
leftOverSize -= 16;
chars[posn++] =
(char)(leftOverBits >> leftOverSize);
leftOverBits &= ((1 << leftOverSize) - 1);
}
}
else
{
// Normal character terminating a base64 sequence.
if(leftOverSize > 0)
{
if(posn >= charLength)
{
throw new ArgumentException
(_("Arg_InsufficientSpace"), "chars");
}
chars[posn++] =
(char)(leftOverBits << (16 - leftOverSize));
leftOverSize = 0;
leftOverBits = 0;
}
if(posn >= charLength)
{
throw new ArgumentException
(_("Arg_InsufficientSpace"), "chars");
}
chars[posn++] = (char)byteval;
normal = true;
}
prevIsPlus = false;
}
}
leftOver = (leftOverBits | (leftOverSize << 16) |
(normal ? 0 : 0x01000000) |
(prevIsPlus ? 0x02000000 : 0));
// Return the final length to the caller.
return posn - charIndex;
}
// Get the characters that result from decoding a byte buffer.
public override int GetChars(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex)
{
int leftOver = 0;
return InternalGetChars(bytes, byteIndex, byteCount,
chars, charIndex, ref leftOver);
}
// Get the maximum number of bytes needed to encode a
// specified number of characters.
public override int GetMaxByteCount(int charCount)
{
if(charCount < 0)
{
throw new ArgumentOutOfRangeException
("charCount", _("ArgRange_NonNegative"));
}
return charCount * 5;
}
// Get the maximum number of characters needed to decode a
// specified number of bytes.
public override int GetMaxCharCount(int byteCount)
{
if(byteCount < 0)
{
throw new ArgumentOutOfRangeException
("byteCount", _("ArgRange_NonNegative"));
}
return byteCount;
}
// Get a UTF7-specific decoder that is attached to this instance.
public override Decoder GetDecoder()
{
return new UTF7Decoder();
}
// Get a UTF7-specific encoder that is attached to this instance.
public override Encoder GetEncoder()
{
return new UTF7Encoder(allowOptionals);
}
#if !ECMA_COMPAT
// Get the mail body name for this encoding.
internal override String InternalBodyName
{
get
{
return "utf-7";
}
}
// Get the human-readable name for this encoding.
internal override String InternalEncodingName
{
get
{
return "Unicode (UTF-7)";
}
}
// Get the mail agent header name for this encoding.
internal override String InternalHeaderName
{
get
{
return "utf-7";
}
}
// Determine if this encoding can be displayed in a mail/news agent.
internal override bool InternalIsMailNewsDisplay
{
get
{
return true;
}
}
// Determine if this encoding can be saved from a mail/news agent.
internal override bool InternalIsMailNewsSave
{
get
{
return true;
}
}
// Get the IANA-preferred Web name for this encoding.
internal override String InternalWebName
{
get
{
return "utf-7";
}
}
// Get the Windows code page represented by this object.
internal override int InternalWindowsCodePage
{
get
{
return UnicodeEncoding.UNICODE_CODE_PAGE;
}
}
#endif // !ECMA_COMPAT
// UTF-7 decoder implementation.
private sealed class UTF7Decoder : Decoder
{
// Internal state.
private int leftOver;
// Constructor.
public UTF7Decoder()
{
leftOver = 0;
}
// Override inherited methods.
public override int GetCharCount(byte[] bytes, int index, int count)
{
return InternalGetCharCount(bytes, index, count, leftOver);
}
public override int GetChars(byte[] bytes, int byteIndex,
int byteCount, char[] chars,
int charIndex)
{
return InternalGetChars(bytes, byteIndex, byteCount,
chars, charIndex, ref leftOver);
}
} // class UTF7Decoder
// UTF-7 encoder implementation.
private sealed class UTF7Encoder : Encoder
{
private bool allowOptionals;
private int leftOver;
// Constructor.
public UTF7Encoder(bool allowOptionals)
{
this.allowOptionals = allowOptionals;
this.leftOver = 0;
}
// Override inherited methods.
public override int GetByteCount(char[] chars, int index,
int count, bool flush)
{
return InternalGetByteCount
(chars, index, count, flush, leftOver, allowOptionals);
}
public override int GetBytes(char[] chars, int charIndex,
int charCount, byte[] bytes,
int byteIndex, bool flush)
{
return InternalGetBytes(chars, charIndex, charCount,
bytes, byteIndex, flush,
ref leftOver, allowOptionals);
}
} // class UTF7Encoder
}; // class UTF7Encoding
}; // namespace System.Text
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Immutable;
using System.Diagnostics.SymbolStore;
using System.Runtime.InteropServices.ComTypes;
using Microsoft.VisualStudio.SymReaderInterop;
using Xunit;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal sealed class MockSymUnmanagedReader : ISymUnmanagedReader
{
private readonly ImmutableDictionary<int, MethodDebugInfoBytes> _methodDebugInfoMap;
public MockSymUnmanagedReader(ImmutableDictionary<int, MethodDebugInfoBytes> methodDebugInfoMap)
{
_methodDebugInfoMap = methodDebugInfoMap;
}
int ISymUnmanagedReader.GetSymAttribute(SymbolToken token, string name, int bytesDesired, out int bytesRead, byte[] buffer)
{
Assert.Equal("MD2", name);
MethodDebugInfoBytes info;
if (!_methodDebugInfoMap.TryGetValue(token.GetToken(), out info))
{
bytesRead = 0;
return SymUnmanagedReaderExtensions.S_FALSE; // This is a guess. We're not consuming it, so it doesn't really matter.
}
Assert.NotNull(info);
info.Bytes.TwoPhaseCopy(bytesDesired, out bytesRead, buffer);
return SymUnmanagedReaderExtensions.S_OK;
}
int ISymUnmanagedReader.GetMethodByVersion(SymbolToken methodToken, int version, out ISymUnmanagedMethod retVal)
{
Assert.Equal(1, version);
MethodDebugInfoBytes info;
if (!_methodDebugInfoMap.TryGetValue(methodToken.GetToken(), out info))
{
retVal = null;
return SymUnmanagedReaderExtensions.E_FAIL;
}
Assert.NotNull(info);
retVal = info.Method;
return SymUnmanagedReaderExtensions.S_OK;
}
int ISymUnmanagedReader.GetDocument(string url, Guid language, Guid languageVendor, Guid documentType, out ISymUnmanagedDocument retVal)
{
throw new NotImplementedException();
}
int ISymUnmanagedReader.GetDocuments(int cDocs, out int pcDocs, ISymUnmanagedDocument[] pDocs)
{
throw new NotImplementedException();
}
int ISymUnmanagedReader.GetUserEntryPoint(out SymbolToken EntryPoint)
{
throw new NotImplementedException();
}
int ISymUnmanagedReader.GetMethod(SymbolToken methodToken, out ISymUnmanagedMethod retVal)
{
throw new NotImplementedException();
}
int ISymUnmanagedReader.GetVariables(SymbolToken parent, int cVars, out int pcVars, ISymUnmanagedVariable[] vars)
{
throw new NotImplementedException();
}
int ISymUnmanagedReader.GetGlobalVariables(int cVars, out int pcVars, ISymUnmanagedVariable[] vars)
{
throw new NotImplementedException();
}
int ISymUnmanagedReader.GetMethodFromDocumentPosition(ISymUnmanagedDocument document, int line, int column, out ISymUnmanagedMethod retVal)
{
throw new NotImplementedException();
}
int ISymUnmanagedReader.GetNamespaces(int cNameSpaces, out int pcNameSpaces, ISymUnmanagedNamespace[] namespaces)
{
throw new NotImplementedException();
}
int ISymUnmanagedReader.Initialize(object importer, string filename, string searchPath, IStream stream)
{
throw new NotImplementedException();
}
int ISymUnmanagedReader.UpdateSymbolStore(string filename, IStream stream)
{
throw new NotImplementedException();
}
int ISymUnmanagedReader.ReplaceSymbolStore(string filename, IStream stream)
{
throw new NotImplementedException();
}
int ISymUnmanagedReader.GetSymbolStoreFileName(int cchName, out int pcchName, char[] szName)
{
throw new NotImplementedException();
}
int ISymUnmanagedReader.GetMethodsFromDocumentPosition(ISymUnmanagedDocument document, int line, int column, int cMethod, out int pcMethod, ISymUnmanagedMethod[] pRetVal)
{
throw new NotImplementedException();
}
int ISymUnmanagedReader.GetDocumentVersion(ISymUnmanagedDocument pDoc, out int version, out bool pbCurrent)
{
throw new NotImplementedException();
}
int ISymUnmanagedReader.GetMethodVersion(ISymUnmanagedMethod pMethod, out int version)
{
throw new NotImplementedException();
}
}
internal sealed class MockSymUnmanagedMethod : ISymUnmanagedMethod
{
private readonly ISymUnmanagedScope _rootScope;
public MockSymUnmanagedMethod(ISymUnmanagedScope rootScope)
{
_rootScope = rootScope;
}
int ISymUnmanagedMethod.GetRootScope(out ISymUnmanagedScope retVal)
{
retVal = _rootScope;
return SymUnmanagedReaderExtensions.S_OK;
}
int ISymUnmanagedMethod.GetSequencePointCount(out int retVal)
{
retVal = 1;
return SymUnmanagedReaderExtensions.S_OK;
}
int ISymUnmanagedMethod.GetSequencePoints(int cPoints, out int pcPoints, int[] offsets, ISymUnmanagedDocument[] documents, int[] lines, int[] columns, int[] endLines, int[] endColumns)
{
pcPoints = 1;
offsets[0] = 0;
documents[0] = null;
lines[0] = 0;
columns[0] = 0;
endLines[0] = 0;
endColumns[0] = 0;
return SymUnmanagedReaderExtensions.S_OK;
}
int ISymUnmanagedMethod.GetNamespace(out ISymUnmanagedNamespace retVal)
{
throw new NotImplementedException();
}
int ISymUnmanagedMethod.GetOffset(ISymUnmanagedDocument document, int line, int column, out int retVal)
{
throw new NotImplementedException();
}
int ISymUnmanagedMethod.GetParameters(int cParams, out int pcParams, ISymUnmanagedVariable[] parms)
{
throw new NotImplementedException();
}
int ISymUnmanagedMethod.GetRanges(ISymUnmanagedDocument document, int line, int column, int cRanges, out int pcRanges, int[] ranges)
{
throw new NotImplementedException();
}
int ISymUnmanagedMethod.GetScopeFromOffset(int offset, out ISymUnmanagedScope retVal)
{
throw new NotImplementedException();
}
int ISymUnmanagedMethod.GetSourceStartEnd(ISymUnmanagedDocument[] docs, int[] lines, int[] columns, out bool retVal)
{
throw new NotImplementedException();
}
int ISymUnmanagedMethod.GetToken(out SymbolToken pToken)
{
throw new NotImplementedException();
}
}
internal sealed class MockSymUnmanagedScope : ISymUnmanagedScope, ISymUnmanagedScope2
{
private readonly ImmutableArray<ISymUnmanagedScope> _children;
private readonly ImmutableArray<ISymUnmanagedNamespace> _namespaces;
private readonly int _startOffset;
private readonly int _endOffset;
public MockSymUnmanagedScope(ImmutableArray<ISymUnmanagedScope> children, ImmutableArray<ISymUnmanagedNamespace> namespaces, int startOffset = 0, int endOffset = 1)
{
_children = children;
_namespaces = namespaces;
_startOffset = startOffset;
_endOffset = endOffset;
}
public int GetChildren(int numDesired, out int numRead, ISymUnmanagedScope[] buffer)
{
_children.TwoPhaseCopy(numDesired, out numRead, buffer);
return SymUnmanagedReaderExtensions.S_OK;
}
public int GetNamespaces(int numDesired, out int numRead, ISymUnmanagedNamespace[] buffer)
{
_namespaces.TwoPhaseCopy(numDesired, out numRead, buffer);
return SymUnmanagedReaderExtensions.S_OK;
}
public int GetStartOffset(out int pRetVal)
{
pRetVal = _startOffset;
return SymUnmanagedReaderExtensions.S_OK;
}
public int GetEndOffset(out int pRetVal)
{
pRetVal = _endOffset;
return SymUnmanagedReaderExtensions.S_OK;
}
public int GetLocalCount(out int pRetVal)
{
pRetVal = 0;
return SymUnmanagedReaderExtensions.S_OK;
}
public int GetLocals(int cLocals, out int pcLocals, ISymUnmanagedVariable[] locals)
{
pcLocals = 0;
return SymUnmanagedReaderExtensions.S_OK;
}
public int GetMethod(out ISymUnmanagedMethod pRetVal)
{
throw new NotImplementedException();
}
public int GetParent(out ISymUnmanagedScope pRetVal)
{
throw new NotImplementedException();
}
public int GetConstantCount(out int pRetVal)
{
pRetVal = 0;
return SymUnmanagedReaderExtensions.S_OK;
}
public int GetConstants(int cConstants, out int pcConstants, ISymUnmanagedConstant[] constants)
{
pcConstants = 0;
return SymUnmanagedReaderExtensions.S_OK;
}
}
internal sealed class MockSymUnmanagedNamespace : ISymUnmanagedNamespace
{
private readonly ImmutableArray<char> _nameChars;
public MockSymUnmanagedNamespace(string name)
{
if (name != null)
{
var builder = ArrayBuilder<char>.GetInstance();
builder.AddRange(name);
builder.AddRange('\0');
_nameChars = builder.ToImmutableAndFree();
}
}
int ISymUnmanagedNamespace.GetName(int numDesired, out int numRead, char[] buffer)
{
_nameChars.TwoPhaseCopy(numDesired, out numRead, buffer);
return 0;
}
int ISymUnmanagedNamespace.GetNamespaces(int cNameSpaces, out int pcNameSpaces, ISymUnmanagedNamespace[] namespaces)
{
throw new NotImplementedException();
}
int ISymUnmanagedNamespace.GetVariables(int cVars, out int pcVars, ISymUnmanagedVariable[] pVars)
{
throw new NotImplementedException();
}
}
internal static class MockSymUnmanagedHelpers
{
public static void TwoPhaseCopy<T>(this ImmutableArray<T> source, int numDesired, out int numRead, T[] destination)
{
if (destination == null)
{
Assert.Equal(0, numDesired);
numRead = source.IsDefault ? 0 : source.Length;
}
else
{
Assert.False(source.IsDefault);
Assert.Equal(source.Length, numDesired);
source.CopyTo(0, destination, 0, numDesired);
numRead = numDesired;
}
}
public static void Add2(this ArrayBuilder<byte> bytes, short s)
{
var shortBytes = BitConverter.GetBytes(s);
Assert.Equal(2, shortBytes.Length);
bytes.AddRange(shortBytes);
}
public static void Add4(this ArrayBuilder<byte> bytes, int i)
{
var intBytes = BitConverter.GetBytes(i);
Assert.Equal(4, intBytes.Length);
bytes.AddRange(intBytes);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace oct01securitybasic.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames.
// If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames
// If still not found, try get the sample provided for a specific type and mediaType
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// Try create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
sampleObject = objectGenerator.GenerateObject(type);
}
return sampleObject;
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ActionDescriptor.ReturnType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
e.Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
/*
* UltraCart Rest API V2
*
* UltraCart REST API Version 2
*
* OpenAPI spec version: 2.0.0
* Contact: [email protected]
* Generated by: https://github.com/swagger-api/swagger-codegen.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 SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter;
namespace com.ultracart.admin.v2.Model
{
/// <summary>
/// IntegrationLogQueryFilterValues
/// </summary>
[DataContract]
public partial class IntegrationLogQueryFilterValues : IEquatable<IntegrationLogQueryFilterValues>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="IntegrationLogQueryFilterValues" /> class.
/// </summary>
/// <param name="actions">actions.</param>
/// <param name="directions">directions.</param>
/// <param name="emails">emails.</param>
/// <param name="fileNames">fileNames.</param>
/// <param name="itemIds">itemIds.</param>
/// <param name="itemIpnOids">itemIpnOids.</param>
/// <param name="logDtsMax">Maximum date/time log date/time.</param>
/// <param name="logDtsMin">Minimum date/time log date/time.</param>
/// <param name="logTypes">logTypes.</param>
/// <param name="loggerNames">loggerNames.</param>
/// <param name="orderIds">orderIds.</param>
/// <param name="statuses">statuses.</param>
public IntegrationLogQueryFilterValues(List<string> actions = default(List<string>), List<string> directions = default(List<string>), List<string> emails = default(List<string>), List<string> fileNames = default(List<string>), List<string> itemIds = default(List<string>), List<int?> itemIpnOids = default(List<int?>), string logDtsMax = default(string), string logDtsMin = default(string), List<string> logTypes = default(List<string>), List<string> loggerNames = default(List<string>), List<string> orderIds = default(List<string>), List<string> statuses = default(List<string>))
{
this.Actions = actions;
this.Directions = directions;
this.Emails = emails;
this.FileNames = fileNames;
this.ItemIds = itemIds;
this.ItemIpnOids = itemIpnOids;
this.LogDtsMax = logDtsMax;
this.LogDtsMin = logDtsMin;
this.LogTypes = logTypes;
this.LoggerNames = loggerNames;
this.OrderIds = orderIds;
this.Statuses = statuses;
}
/// <summary>
/// Gets or Sets Actions
/// </summary>
[DataMember(Name="actions", EmitDefaultValue=false)]
public List<string> Actions { get; set; }
/// <summary>
/// Gets or Sets Directions
/// </summary>
[DataMember(Name="directions", EmitDefaultValue=false)]
public List<string> Directions { get; set; }
/// <summary>
/// Gets or Sets Emails
/// </summary>
[DataMember(Name="emails", EmitDefaultValue=false)]
public List<string> Emails { get; set; }
/// <summary>
/// Gets or Sets FileNames
/// </summary>
[DataMember(Name="file_names", EmitDefaultValue=false)]
public List<string> FileNames { get; set; }
/// <summary>
/// Gets or Sets ItemIds
/// </summary>
[DataMember(Name="item_ids", EmitDefaultValue=false)]
public List<string> ItemIds { get; set; }
/// <summary>
/// Gets or Sets ItemIpnOids
/// </summary>
[DataMember(Name="item_ipn_oids", EmitDefaultValue=false)]
public List<int?> ItemIpnOids { get; set; }
/// <summary>
/// Maximum date/time log date/time
/// </summary>
/// <value>Maximum date/time log date/time</value>
[DataMember(Name="log_dts_max", EmitDefaultValue=false)]
public string LogDtsMax { get; set; }
/// <summary>
/// Minimum date/time log date/time
/// </summary>
/// <value>Minimum date/time log date/time</value>
[DataMember(Name="log_dts_min", EmitDefaultValue=false)]
public string LogDtsMin { get; set; }
/// <summary>
/// Gets or Sets LogTypes
/// </summary>
[DataMember(Name="log_types", EmitDefaultValue=false)]
public List<string> LogTypes { get; set; }
/// <summary>
/// Gets or Sets LoggerNames
/// </summary>
[DataMember(Name="logger_names", EmitDefaultValue=false)]
public List<string> LoggerNames { get; set; }
/// <summary>
/// Gets or Sets OrderIds
/// </summary>
[DataMember(Name="order_ids", EmitDefaultValue=false)]
public List<string> OrderIds { get; set; }
/// <summary>
/// Gets or Sets Statuses
/// </summary>
[DataMember(Name="statuses", EmitDefaultValue=false)]
public List<string> Statuses { 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 IntegrationLogQueryFilterValues {\n");
sb.Append(" Actions: ").Append(Actions).Append("\n");
sb.Append(" Directions: ").Append(Directions).Append("\n");
sb.Append(" Emails: ").Append(Emails).Append("\n");
sb.Append(" FileNames: ").Append(FileNames).Append("\n");
sb.Append(" ItemIds: ").Append(ItemIds).Append("\n");
sb.Append(" ItemIpnOids: ").Append(ItemIpnOids).Append("\n");
sb.Append(" LogDtsMax: ").Append(LogDtsMax).Append("\n");
sb.Append(" LogDtsMin: ").Append(LogDtsMin).Append("\n");
sb.Append(" LogTypes: ").Append(LogTypes).Append("\n");
sb.Append(" LoggerNames: ").Append(LoggerNames).Append("\n");
sb.Append(" OrderIds: ").Append(OrderIds).Append("\n");
sb.Append(" Statuses: ").Append(Statuses).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 JsonConvert.SerializeObject(this, 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 IntegrationLogQueryFilterValues);
}
/// <summary>
/// Returns true if IntegrationLogQueryFilterValues instances are equal
/// </summary>
/// <param name="input">Instance of IntegrationLogQueryFilterValues to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(IntegrationLogQueryFilterValues input)
{
if (input == null)
return false;
return
(
this.Actions == input.Actions ||
this.Actions != null &&
this.Actions.SequenceEqual(input.Actions)
) &&
(
this.Directions == input.Directions ||
this.Directions != null &&
this.Directions.SequenceEqual(input.Directions)
) &&
(
this.Emails == input.Emails ||
this.Emails != null &&
this.Emails.SequenceEqual(input.Emails)
) &&
(
this.FileNames == input.FileNames ||
this.FileNames != null &&
this.FileNames.SequenceEqual(input.FileNames)
) &&
(
this.ItemIds == input.ItemIds ||
this.ItemIds != null &&
this.ItemIds.SequenceEqual(input.ItemIds)
) &&
(
this.ItemIpnOids == input.ItemIpnOids ||
this.ItemIpnOids != null &&
this.ItemIpnOids.SequenceEqual(input.ItemIpnOids)
) &&
(
this.LogDtsMax == input.LogDtsMax ||
(this.LogDtsMax != null &&
this.LogDtsMax.Equals(input.LogDtsMax))
) &&
(
this.LogDtsMin == input.LogDtsMin ||
(this.LogDtsMin != null &&
this.LogDtsMin.Equals(input.LogDtsMin))
) &&
(
this.LogTypes == input.LogTypes ||
this.LogTypes != null &&
this.LogTypes.SequenceEqual(input.LogTypes)
) &&
(
this.LoggerNames == input.LoggerNames ||
this.LoggerNames != null &&
this.LoggerNames.SequenceEqual(input.LoggerNames)
) &&
(
this.OrderIds == input.OrderIds ||
this.OrderIds != null &&
this.OrderIds.SequenceEqual(input.OrderIds)
) &&
(
this.Statuses == input.Statuses ||
this.Statuses != null &&
this.Statuses.SequenceEqual(input.Statuses)
);
}
/// <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.Actions != null)
hashCode = hashCode * 59 + this.Actions.GetHashCode();
if (this.Directions != null)
hashCode = hashCode * 59 + this.Directions.GetHashCode();
if (this.Emails != null)
hashCode = hashCode * 59 + this.Emails.GetHashCode();
if (this.FileNames != null)
hashCode = hashCode * 59 + this.FileNames.GetHashCode();
if (this.ItemIds != null)
hashCode = hashCode * 59 + this.ItemIds.GetHashCode();
if (this.ItemIpnOids != null)
hashCode = hashCode * 59 + this.ItemIpnOids.GetHashCode();
if (this.LogDtsMax != null)
hashCode = hashCode * 59 + this.LogDtsMax.GetHashCode();
if (this.LogDtsMin != null)
hashCode = hashCode * 59 + this.LogDtsMin.GetHashCode();
if (this.LogTypes != null)
hashCode = hashCode * 59 + this.LogTypes.GetHashCode();
if (this.LoggerNames != null)
hashCode = hashCode * 59 + this.LoggerNames.GetHashCode();
if (this.OrderIds != null)
hashCode = hashCode * 59 + this.OrderIds.GetHashCode();
if (this.Statuses != null)
hashCode = hashCode * 59 + this.Statuses.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;
}
}
}
| |
using System;
using System.IO;
using System.Linq;
using GitVersion.Common;
using GitVersion.Extensions;
using GitVersion.Logging;
using GitVersion.Model.Configuration;
using Microsoft.Extensions.Options;
namespace GitVersion
{
public class GitPreparer : IGitPreparer
{
private readonly ILog log;
private readonly IEnvironment environment;
private readonly IMutatingGitRepository repository;
private readonly IOptions<GitVersionOptions> options;
private readonly IGitRepositoryInfo repositoryInfo;
private readonly IRepositoryStore repositoryStore;
private readonly ICurrentBuildAgent buildAgent;
private const string DefaultRemoteName = "origin";
public GitPreparer(ILog log, IEnvironment environment, ICurrentBuildAgent buildAgent, IOptions<GitVersionOptions> options,
IMutatingGitRepository repository, IGitRepositoryInfo repositoryInfo, IRepositoryStore repositoryStore)
{
this.log = log ?? throw new ArgumentNullException(nameof(log));
this.environment = environment ?? throw new ArgumentNullException(nameof(environment));
this.repository = repository ?? throw new ArgumentNullException(nameof(repository));
this.options = options ?? throw new ArgumentNullException(nameof(options));
this.repositoryInfo = repositoryInfo ?? throw new ArgumentNullException(nameof(repositoryInfo));
this.repositoryStore = repositoryStore ?? throw new ArgumentNullException(nameof(repositoryStore));
this.buildAgent = buildAgent;
}
public void Prepare()
{
var gitVersionOptions = options.Value;
// Normalize if we are running on build server
var normalizeGitDirectory = !gitVersionOptions.Settings.NoNormalize && buildAgent != null;
var shouldCleanUpRemotes = buildAgent != null && buildAgent.ShouldCleanUpRemotes();
var currentBranch = ResolveCurrentBranch();
var dotGitDirectory = repositoryInfo.DotGitDirectory;
var projectRoot = repositoryInfo.ProjectRootDirectory;
log.Info($"Project root is: {projectRoot}");
log.Info($"DotGit directory is: {dotGitDirectory}");
if (string.IsNullOrEmpty(dotGitDirectory) || string.IsNullOrEmpty(projectRoot))
{
throw new Exception($"Failed to prepare or find the .git directory in path '{gitVersionOptions.WorkingDirectory}'.");
}
PrepareInternal(normalizeGitDirectory, currentBranch, shouldCleanUpRemotes);
}
private void PrepareInternal(bool normalizeGitDirectory, string currentBranch, bool shouldCleanUpRemotes = false)
{
var gitVersionOptions = options.Value;
if (!string.IsNullOrWhiteSpace(gitVersionOptions.RepositoryInfo.TargetUrl))
{
CreateDynamicRepository(currentBranch);
}
else
{
if (!normalizeGitDirectory) return;
if (shouldCleanUpRemotes)
{
CleanupDuplicateOrigin();
}
NormalizeGitDirectory(currentBranch, false);
}
}
private string ResolveCurrentBranch()
{
var gitVersionOptions = options.Value;
var targetBranch = gitVersionOptions.RepositoryInfo.TargetBranch;
if (buildAgent == null)
{
return targetBranch;
}
var isDynamicRepository = !string.IsNullOrWhiteSpace(gitVersionOptions.RepositoryInfo.DynamicRepositoryClonePath);
var currentBranch = buildAgent.GetCurrentBranch(isDynamicRepository) ?? targetBranch;
log.Info("Branch from build environment: " + currentBranch);
return currentBranch;
}
private void CleanupDuplicateOrigin()
{
var remoteToKeep = DefaultRemoteName;
// check that we have a remote that matches defaultRemoteName if not take the first remote
if (!repository.Remotes.Any(remote => remote.Name.Equals(DefaultRemoteName, StringComparison.InvariantCultureIgnoreCase)))
{
remoteToKeep = repository.Remotes.First().Name;
}
var duplicateRemotes = repository.Remotes
.Where(remote => !remote.Name.Equals(remoteToKeep, StringComparison.InvariantCultureIgnoreCase))
.Select(remote => remote.Name);
// remove all remotes that are considered duplicates
foreach (var remoteName in duplicateRemotes)
{
repository.Remotes.Remove(remoteName);
}
}
private void CreateDynamicRepository(string targetBranch)
{
var gitVersionOptions = options.Value;
if (string.IsNullOrWhiteSpace(targetBranch))
{
throw new Exception("Dynamic Git repositories must have a target branch (/b)");
}
var gitDirectory = repositoryInfo.DynamicGitRepositoryPath;
using (log.IndentLog($"Creating dynamic repository at '{gitDirectory}'"))
{
var authentication = gitVersionOptions.Authentication;
if (!Directory.Exists(gitDirectory))
{
CloneRepository(gitVersionOptions.RepositoryInfo.TargetUrl, gitDirectory, authentication);
}
else
{
log.Info("Git repository already exists");
}
NormalizeGitDirectory(targetBranch, true);
}
}
private void NormalizeGitDirectory(string targetBranch, bool isDynamicRepository)
{
using (log.IndentLog($"Normalizing git directory for branch '{targetBranch}'"))
{
// Normalize (download branches) before using the branch
NormalizeGitDirectory(options.Value.Settings.NoFetch, targetBranch, isDynamicRepository);
}
}
private void CloneRepository(string repositoryUrl, string gitDirectory, AuthenticationInfo auth)
{
using (log.IndentLog($"Cloning repository from url '{repositoryUrl}'"))
{
repository.Clone(repositoryUrl, gitDirectory, auth);
}
}
/// <summary>
/// Normalization of a git directory turns all remote branches into local branches,
/// turns pull request refs into a real branch and a few other things.
/// This is designed to be run *only on the build server* which checks out repositories in different ways.
/// It is not recommended to run normalization against a local repository
/// </summary>
private void NormalizeGitDirectory(bool noFetch, string currentBranchName, bool isDynamicRepository)
{
var authentication = options.Value.Authentication;
// Need to ensure the HEAD does not move, this is essentially a BugCheck
var expectedSha = repository.Head.Tip.Sha;
var expectedBranchName = repository.Head.Name.Canonical;
try
{
var remote = EnsureOnlyOneRemoteIsDefined();
//If noFetch is enabled, then GitVersion will assume that the git repository is normalized before execution, so that fetching from remotes is not required.
if (noFetch)
{
log.Info("Skipping fetching, if GitVersion does not calculate your version as expected you might need to allow fetching or use dynamic repositories");
}
else
{
var refSpecs = string.Join(", ", remote.FetchRefSpecs.Select(r => r.Specification));
log.Info($"Fetching from remote '{remote.Name}' using the following refspecs: {refSpecs}.");
repository.Fetch(remote.Name, Enumerable.Empty<string>(), authentication, null);
}
EnsureLocalBranchExistsForCurrentBranch(remote, currentBranchName);
CreateOrUpdateLocalBranchesFromRemoteTrackingOnes(remote.Name);
var currentBranch = repositoryStore.FindBranch(currentBranchName);
// Bug fix for https://github.com/GitTools/GitVersion/issues/1754, head maybe have been changed
// if this is a dynamic repository. But only allow this in case the branches are different (branch switch)
if (expectedSha != repository.Head.Tip.Sha &&
(isDynamicRepository || currentBranch is null || !repository.Head.Equals(currentBranch)))
{
var newExpectedSha = repository.Head.Tip.Sha;
var newExpectedBranchName = repository.Head.Name.Canonical;
log.Info($"Head has moved from '{expectedBranchName} | {expectedSha}' => '{newExpectedBranchName} | {newExpectedSha}', allowed since this is a dynamic repository");
expectedSha = newExpectedSha;
}
var headSha = repository.Refs.Head.TargetIdentifier;
if (!repository.IsHeadDetached)
{
log.Info($"HEAD points at branch '{headSha}'.");
return;
}
log.Info($"HEAD is detached and points at commit '{headSha}'.");
log.Info($"Local Refs:{System.Environment.NewLine}" + string.Join(System.Environment.NewLine, repository.Refs.FromGlob("*").Select(r => $"{r.Name.Canonical} ({r.TargetIdentifier})")));
// In order to decide whether a fake branch is required or not, first check to see if any local branches have the same commit SHA of the head SHA.
// If they do, go ahead and checkout that branch
// If no, go ahead and check out a new branch, using the known commit SHA as the pointer
var localBranchesWhereCommitShaIsHead = repository.Branches.Where(b => !b.IsRemote && b.Tip.Sha == headSha).ToList();
var matchingCurrentBranch = !string.IsNullOrEmpty(currentBranchName)
? localBranchesWhereCommitShaIsHead.SingleOrDefault(b => b.Name.Canonical.Replace("/heads/", "/") == currentBranchName.Replace("/heads/", "/"))
: null;
if (matchingCurrentBranch != null)
{
log.Info($"Checking out local branch '{currentBranchName}'.");
repository.Checkout(matchingCurrentBranch.Name.Canonical);
}
else if (localBranchesWhereCommitShaIsHead.Count > 1)
{
var branchNames = localBranchesWhereCommitShaIsHead.Select(r => r.Name.Canonical);
var csvNames = string.Join(", ", branchNames);
const string moveBranchMsg = "Move one of the branches along a commit to remove warning";
log.Warning($"Found more than one local branch pointing at the commit '{headSha}' ({csvNames}).");
var master = localBranchesWhereCommitShaIsHead.SingleOrDefault(n => n.Name.EquivalentTo(Config.MasterBranchKey));
if (master != null)
{
log.Warning("Because one of the branches is 'master', will build master." + moveBranchMsg);
repository.Checkout(Config.MasterBranchKey);
}
else
{
var branchesWithoutSeparators = localBranchesWhereCommitShaIsHead.Where(b => !b.Name.Friendly.Contains('/') && !b.Name.Friendly.Contains('-')).ToList();
if (branchesWithoutSeparators.Count == 1)
{
var branchWithoutSeparator = branchesWithoutSeparators[0];
log.Warning($"Choosing {branchWithoutSeparator.Name.Canonical} as it is the only branch without / or - in it. " + moveBranchMsg);
repository.Checkout(branchWithoutSeparator.Name.Canonical);
}
else
{
throw new WarningException("Failed to try and guess branch to use. " + moveBranchMsg);
}
}
}
else if (localBranchesWhereCommitShaIsHead.Count == 0)
{
log.Info($"No local branch pointing at the commit '{headSha}'. Fake branch needs to be created.");
repository.CreateBranchForPullRequestBranch(authentication);
}
else
{
log.Info($"Checking out local branch 'refs/heads/{localBranchesWhereCommitShaIsHead[0]}'.");
repository.Checkout(localBranchesWhereCommitShaIsHead[0].Name.Friendly);
}
}
finally
{
if (repository.Head.Tip.Sha != expectedSha)
{
if (environment.GetEnvironmentVariable("IGNORE_NORMALISATION_GIT_HEAD_MOVE") != "1")
{
// Whoa, HEAD has moved, it shouldn't have. We need to blow up because there is a bug in normalisation
throw new BugException($@"GitVersion has a bug, your HEAD has moved after repo normalisation.
To disable this error set an environmental variable called IGNORE_NORMALISATION_GIT_HEAD_MOVE to 1
Please run `git {GitExtensions.CreateGitLogArgs(100)}` and submit it along with your build log (with personal info removed) in a new issue at https://github.com/GitTools/GitVersion");
}
}
}
}
private IRemote EnsureOnlyOneRemoteIsDefined()
{
var remotes = repository.Remotes;
var howMany = remotes.Count();
if (howMany == 1)
{
var remote = remotes.Single();
log.Info($"One remote found ({remote.Name} -> '{remote.Url}').");
if (remote.FetchRefSpecs.Any(r => r.Source == "refs/heads/*"))
return remote;
var allBranchesFetchRefSpec = $"+refs/heads/*:refs/remotes/{remote.Name}/*";
log.Info($"Adding refspec: {allBranchesFetchRefSpec}");
remotes.Update(remote.Name, allBranchesFetchRefSpec);
return remote;
}
var message = $"{howMany} remote(s) have been detected. When being run on a build server, the Git repository is expected to bear one (and no more than one) remote.";
throw new WarningException(message);
}
private void CreateOrUpdateLocalBranchesFromRemoteTrackingOnes(string remoteName)
{
var prefix = $"refs/remotes/{remoteName}/";
var remoteHeadCanonicalName = $"{prefix}HEAD";
var headReferenceName = ReferenceName.Parse(remoteHeadCanonicalName);
var remoteTrackingReferences = repository.Refs
.FromGlob(prefix + "*")
.Where(r => !r.Name.Equals(headReferenceName));
foreach (var remoteTrackingReference in remoteTrackingReferences)
{
var remoteTrackingReferenceName = remoteTrackingReference.Name.Canonical;
var branchName = remoteTrackingReferenceName.Substring(prefix.Length);
var localCanonicalName = "refs/heads/" + branchName;
var referenceName = ReferenceName.Parse(localCanonicalName);
// We do not want to touch our current branch
if (repository.Head.Name.EquivalentTo(branchName)) continue;
if (repository.Refs.Any(x => x.Name.Equals(referenceName)))
{
var localRef = repository.Refs[localCanonicalName];
if (localRef.TargetIdentifier == remoteTrackingReference.TargetIdentifier)
{
log.Info($"Skipping update of '{remoteTrackingReference.Name.Canonical}' as it already matches the remote ref.");
continue;
}
var remoteRefTipId = remoteTrackingReference.ReferenceTargetId;
log.Info($"Updating local ref '{localRef.Name.Canonical}' to point at {remoteRefTipId}.");
repository.Refs.UpdateTarget(localRef, remoteRefTipId);
continue;
}
log.Info($"Creating local branch from remote tracking '{remoteTrackingReference.Name.Canonical}'.");
repository.Refs.Add(localCanonicalName, remoteTrackingReference.TargetIdentifier, true);
var branch = repository.Branches[branchName];
repository.Branches.UpdateTrackedBranch(branch, remoteTrackingReferenceName);
}
}
public void EnsureLocalBranchExistsForCurrentBranch(IRemote remote, string currentBranch)
{
if (remote is null)
{
throw new ArgumentNullException(nameof(remote));
}
if (string.IsNullOrEmpty(currentBranch)) return;
var isRef = currentBranch.Contains("refs");
var isBranch = currentBranch.Contains("refs/heads");
var localCanonicalName = !isRef
? "refs/heads/" + currentBranch
: isBranch
? currentBranch
: currentBranch.Replace("refs/", "refs/heads/");
var repoTip = repository.Head.Tip;
// We currently have the rep.Head of the *default* branch, now we need to look up the right one
var originCanonicalName = $"{remote.Name}/{currentBranch}";
var originBranch = repository.Branches[originCanonicalName];
if (originBranch != null)
{
repoTip = originBranch.Tip;
}
var repoTipId = repoTip.Id;
var referenceName = ReferenceName.Parse(localCanonicalName);
if (repository.Branches.All(b => !b.Name.Equals(referenceName)))
{
log.Info(isBranch ? $"Creating local branch {referenceName}"
: $"Creating local branch {referenceName} pointing at {repoTipId}");
repository.Refs.Add(localCanonicalName, repoTipId.Sha);
}
else
{
log.Info(isBranch ? $"Updating local branch {referenceName} to point at {repoTip}"
: $"Updating local branch {referenceName} to match ref {currentBranch}");
var localRef = repository.Refs[localCanonicalName];
repository.Refs.UpdateTarget(localRef, repoTipId);
}
repository.Checkout(localCanonicalName);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace FrontEndRole.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
using System;
namespace GrpcPool
{
/// <summary>
/// Preconditions for checking method arguments, state etc.
/// </summary>
public static class GaxPreconditions
{
// Possible future directions:
// - Debug-only preconditions, as used extensively in Noda Time (for checking and self-documenting internal
// assumptions)
// - Methods that return null or "something that will throw an exception" to be chained with string interpolation
// - Methods accepting a string format and one or two arguments (to avoid any arrays being created at
// execution time, but still allow for string formatting)
// - Conditional public/internal access, so that we can create a Google.Common assembly exposing all of this
// publicly, without duplication.
/// <summary>
/// Checks that the given argument (to the calling method) is non-null.
/// </summary>
/// <typeparam name="T">The type of the parameter.</typeparam>
/// <param name="argument">The argument provided for the parameter.</param>
/// <param name="paramName">The name of the parameter in the calling method.</param>
/// <exception cref="ArgumentNullException"><paramref name="argument"/> is null</exception>
/// <returns><paramref name="argument"/> if it is not null</returns>
public static T CheckNotNull<T>(T argument, string paramName) where T : class
{
if (argument == null)
{
throw new ArgumentNullException(paramName);
}
return argument;
}
/// <summary>
/// Checks that a string argument is neither null, nor an empty string.
/// </summary>
/// <param name="argument">The argument provided for the parameter.</param>
/// <param name="paramName">The name of the parameter in the calling method.</param>
/// <exception cref="ArgumentNullException"><paramref name="argument"/> is null</exception>
/// <exception cref="ArgumentException"><paramref name="argument"/> is empty</exception>
/// <returns><paramref name="argument"/> if it is not null or empty</returns>
public static string CheckNotNullOrEmpty(string argument, string paramName)
{
if (argument == null)
{
throw new ArgumentNullException(paramName);
}
if (argument == "")
{
throw new ArgumentException("An empty string was provided, but is not valid", paramName);
}
return argument;
}
/// <summary>
/// Checks that the given argument value is valid.
/// </summary>
/// <remarks>
/// Note that the upper bound (<paramref name="maxInclusive"/>) is inclusive,
/// not exclusive. This is deliberate, to allow the specification of ranges which include
/// <see cref="Int32.MaxValue"/>.
/// </remarks>
/// <param name="argument">The value of the argument passed to the calling method.</param>
/// <param name="paramName">The name of the parameter in the calling method.</param>
/// <param name="minInclusive">The smallest valid value.</param>
/// <param name="maxInclusive">The largest valid value.</param>
/// <returns><paramref name="argument"/> if it was in range</returns>
/// <exception cref="ArgumentOutOfRangeException">The argument was outside the specified range.</exception>
public static int CheckArgumentRange(int argument, string paramName, int minInclusive, int maxInclusive)
{
if (argument < minInclusive || argument > maxInclusive)
{
throw new ArgumentOutOfRangeException(
paramName,
$"Value {argument} should be in range [{minInclusive}, {maxInclusive}]");
}
return argument;
}
/// <summary>
/// Checks that given condition is met, throwing an <see cref="InvalidOperationException"/> otherwise.
/// </summary>
/// <param name="condition">The (already evaluated) condition to check.</param>
/// <param name="message">The message to include in the exception, if generated. This should not
/// use interpolation, as the interpolation would be performed regardless of whether or
/// not an exception is thrown.</param>
public static void CheckState(bool condition, string message)
{
if (!condition)
{
throw new InvalidOperationException(message);
}
}
/// <summary>
/// Checks that given condition is met, throwing an <see cref="InvalidOperationException"/> otherwise.
/// </summary>
/// <param name="condition">The (already evaluated) condition to check.</param>
/// <param name="format">The format string to use to create the exception message if the
/// condition is not met.</param>
/// <param name="arg0">The argument to the format string.</param>
public static void CheckState<T>(bool condition, string format, T arg0)
{
if (!condition)
{
throw new InvalidOperationException(string.Format(format, arg0));
}
}
/// <summary>
/// Checks that given condition is met, throwing an <see cref="InvalidOperationException"/> otherwise.
/// </summary>
/// <param name="condition">The (already evaluated) condition to check.</param>
/// <param name="format">The format string to use to create the exception message if the
/// condition is not met.</param>
/// <param name="arg0">The first argument to the format string.</param>
/// <param name="arg1">The second argument to the format string.</param>
public static void CheckState<T1, T2>(bool condition, string format, T1 arg0, T2 arg1)
{
if (!condition)
{
throw new InvalidOperationException(string.Format(format, arg0, arg1));
}
}
/// <summary>
/// Checks that given argument-based condition is met, throwing an <see cref="ArgumentException"/> otherwise.
/// </summary>
/// <param name="condition">The (already evaluated) condition to check.</param>
/// <param name="paramName">The name of the parameter whose value is being tested.</param>
/// <param name="message">The message to include in the exception, if generated. This should not
/// use interpolation, as the interpolation would be performed regardless of whether or not an exception
/// is thrown.</param>
public static void CheckArgument(bool condition, string paramName, string message)
{
if (!condition)
{
throw new ArgumentException(message, paramName);
}
}
/// <summary>
/// Checks that given argument-based condition is met, throwing an <see cref="ArgumentException"/> otherwise.
/// </summary>
/// <param name="condition">The (already evaluated) condition to check.</param>
/// <param name="paramName">The name of the parameter whose value is being tested.</param>
/// <param name="format">The format string to use to create the exception message if the
/// condition is not met.</param>
/// <param name="arg0">The argument to the format string.</param>
public static void CheckArgument<T>(bool condition, string paramName, string format, T arg0)
{
if (!condition)
{
throw new ArgumentException(string.Format(format, arg0), paramName);
}
}
/// <summary>
/// Checks that given argument-based condition is met, throwing an <see cref="ArgumentException"/> otherwise.
/// </summary>
/// <param name="condition">The (already evaluated) condition to check.</param>
/// <param name="paramName">The name of the parameter whose value is being tested.</param>
/// <param name="format">The format string to use to create the exception message if the
/// condition is not met.</param>
/// <param name="arg0">The first argument to the format string.</param>
/// <param name="arg1">The second argument to the format string.</param>
public static void CheckArgument<T1, T2>(bool condition, string paramName, string format, T1 arg0, T2 arg1)
{
if (!condition)
{
throw new ArgumentException(string.Format(format, arg0, arg1), paramName);
}
}
/// <summary>
/// Checks that the given value is in fact defined in the enum used as the type argument of the method.
/// </summary>
/// <typeparam name="T">The enum type to check the value within.</typeparam>
/// <param name="value">The value to check.</param>
/// <param name="paramName">The name of the parameter whose value is being tested.</param>
/// <returns><paramref name="value"/> if it was a defined value</returns>
public static T CheckEnumValue<T>(T value, string paramName) where T : struct
{
CheckArgument(
Enum.IsDefined(typeof(T), value),
paramName,
"Value {0} not defined in enum {1}", value, typeof(T).Name);
return value;
}
/// <summary>
/// Checks that the given <see cref="TimeSpan"/> used as a delay is non-negative. This is internal
/// as it's very specialized.
/// </summary>
/// <param name="value">The value to check.</param>
/// <param name="paramName">The name of the parameter whose value is being tested.</param>
internal static TimeSpan CheckNonNegativeDelay(TimeSpan value, string paramName)
{
if (value < TimeSpan.Zero)
{
throw new ArgumentOutOfRangeException(nameof(value), value, "Delay must not be negative");
}
return value;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Avalonia.Controls;
using Avalonia.Markup.Xaml.XamlIl.CompilerExtensions.AstNodes;
using Avalonia.Markup.Xaml.XamlIl.CompilerExtensions.Transformers;
using Avalonia.Media;
using XamlX.Ast;
using XamlX.Transform;
using XamlX.TypeSystem;
namespace Avalonia.Markup.Xaml.XamlIl.CompilerExtensions
{
class AvaloniaXamlIlLanguageParseIntrinsics
{
public static bool TryConvert(AstTransformationContext context, IXamlAstValueNode node, string text, IXamlType type, AvaloniaXamlIlWellKnownTypes types, out IXamlAstValueNode result)
{
if (type.FullName == "System.TimeSpan")
{
var tsText = text.Trim();
if (!TimeSpan.TryParse(tsText, CultureInfo.InvariantCulture, out var timeSpan))
{
// // shorthand seconds format (ie. "0.25")
if (!tsText.Contains(":") && double.TryParse(tsText,
NumberStyles.Float | NumberStyles.AllowThousands,
CultureInfo.InvariantCulture, out var seconds))
timeSpan = TimeSpan.FromSeconds(seconds);
else
throw new XamlX.XamlLoadException($"Unable to parse {text} as a time span", node);
}
result = new XamlStaticOrTargetedReturnMethodCallNode(node,
type.FindMethod("FromTicks", type, false, types.Long),
new[] { new XamlConstantNode(node, types.Long, timeSpan.Ticks) });
return true;
}
if (type.Equals(types.FontFamily))
{
result = new AvaloniaXamlIlFontFamilyAstNode(types, text, node);
return true;
}
if (type.Equals(types.Thickness))
{
try
{
var thickness = Thickness.Parse(text);
result = new AvaloniaXamlIlVectorLikeConstantAstNode(node, types, types.Thickness, types.ThicknessFullConstructor,
new[] { thickness.Left, thickness.Top, thickness.Right, thickness.Bottom });
return true;
}
catch
{
throw new XamlX.XamlLoadException($"Unable to parse \"{text}\" as a thickness", node);
}
}
if (type.Equals(types.Point))
{
try
{
var point = Point.Parse(text);
result = new AvaloniaXamlIlVectorLikeConstantAstNode(node, types, types.Point, types.PointFullConstructor,
new[] { point.X, point.Y });
return true;
}
catch
{
throw new XamlX.XamlLoadException($"Unable to parse \"{text}\" as a point", node);
}
}
if (type.Equals(types.Vector))
{
try
{
var vector = Vector.Parse(text);
result = new AvaloniaXamlIlVectorLikeConstantAstNode(node, types, types.Vector, types.VectorFullConstructor,
new[] { vector.X, vector.Y });
return true;
}
catch
{
throw new XamlX.XamlLoadException($"Unable to parse \"{text}\" as a vector", node);
}
}
if (type.Equals(types.Size))
{
try
{
var size = Size.Parse(text);
result = new AvaloniaXamlIlVectorLikeConstantAstNode(node, types, types.Size, types.SizeFullConstructor,
new[] { size.Width, size.Height });
return true;
}
catch
{
throw new XamlX.XamlLoadException($"Unable to parse \"{text}\" as a size", node);
}
}
if (type.Equals(types.Matrix))
{
try
{
var matrix = Matrix.Parse(text);
result = new AvaloniaXamlIlVectorLikeConstantAstNode(node, types, types.Matrix, types.MatrixFullConstructor,
new[] { matrix.M11, matrix.M12, matrix.M21, matrix.M22, matrix.M31, matrix.M32 });
return true;
}
catch
{
throw new XamlX.XamlLoadException($"Unable to parse \"{text}\" as a matrix", node);
}
}
if (type.Equals(types.CornerRadius))
{
try
{
var cornerRadius = CornerRadius.Parse(text);
result = new AvaloniaXamlIlVectorLikeConstantAstNode(node, types, types.CornerRadius, types.CornerRadiusFullConstructor,
new[] { cornerRadius.TopLeft, cornerRadius.TopRight, cornerRadius.BottomRight, cornerRadius.BottomLeft });
return true;
}
catch
{
throw new XamlX.XamlLoadException($"Unable to parse \"{text}\" as a corner radius", node);
}
}
if (type.Equals(types.Color))
{
if (!Color.TryParse(text, out Color color))
{
throw new XamlX.XamlLoadException($"Unable to parse \"{text}\" as a color", node);
}
result = new XamlStaticOrTargetedReturnMethodCallNode(node,
type.GetMethod(
new FindMethodMethodSignature("FromUInt32", type, types.UInt) { IsStatic = true }),
new[] { new XamlConstantNode(node, types.UInt, color.ToUint32()) });
return true;
}
if (type.Equals(types.GridLength))
{
try
{
var gridLength = GridLength.Parse(text);
result = new AvaloniaXamlIlGridLengthAstNode(node, types, gridLength);
return true;
}
catch
{
throw new XamlX.XamlLoadException($"Unable to parse \"{text}\" as a grid length", node);
}
}
if (type.Equals(types.Cursor))
{
if (TypeSystemHelpers.TryGetEnumValueNode(types.StandardCursorType, text, node, out var enumConstantNode))
{
var cursorTypeRef = new XamlAstClrTypeReference(node, types.Cursor, false);
result = new XamlAstNewClrObjectNode(node, cursorTypeRef, types.CursorTypeConstructor, new List<IXamlAstValueNode> { enumConstantNode });
return true;
}
}
if (type.Equals(types.ColumnDefinitions))
{
return ConvertDefinitionList(node, text, types, types.ColumnDefinitions, types.ColumnDefinition, "column definitions", out result);
}
if (type.Equals(types.RowDefinitions))
{
return ConvertDefinitionList(node, text, types, types.RowDefinitions, types.RowDefinition, "row definitions", out result);
}
if (type.Equals(types.Classes))
{
var classes = text.Split(' ');
var classNodes = classes.Select(c => new XamlAstTextNode(node, c, types.XamlIlTypes.String)).ToArray();
result = new AvaloniaXamlIlAvaloniaListConstantAstNode(node, types, types.Classes, types.XamlIlTypes.String, classNodes);
return true;
}
if (types.IBrush.IsAssignableFrom(type))
{
if (Color.TryParse(text, out Color color))
{
var brushTypeRef = new XamlAstClrTypeReference(node, types.ImmutableSolidColorBrush, false);
result = new XamlAstNewClrObjectNode(node, brushTypeRef,
types.ImmutableSolidColorBrushConstructorColor,
new List<IXamlAstValueNode> { new XamlConstantNode(node, types.UInt, color.ToUint32()) });
return true;
}
}
result = null;
return false;
}
private static bool ConvertDefinitionList(
IXamlAstValueNode node,
string text,
AvaloniaXamlIlWellKnownTypes types,
IXamlType listType,
IXamlType elementType,
string errorDisplayName,
out IXamlAstValueNode result)
{
try
{
var lengths = GridLength.ParseLengths(text);
var definitionTypeRef = new XamlAstClrTypeReference(node, elementType, false);
var definitionConstructorGridLength = elementType.GetConstructor(new List<IXamlType> {types.GridLength});
IXamlAstValueNode CreateDefinitionNode(GridLength length)
{
var lengthNode = new AvaloniaXamlIlGridLengthAstNode(node, types, length);
return new XamlAstNewClrObjectNode(node, definitionTypeRef,
definitionConstructorGridLength, new List<IXamlAstValueNode> {lengthNode});
}
var definitionNodes =
new List<IXamlAstValueNode>(lengths.Select(CreateDefinitionNode));
result = new AvaloniaXamlIlAvaloniaListConstantAstNode(node, types, listType, elementType, definitionNodes);
return true;
}
catch
{
throw new XamlX.XamlLoadException($"Unable to parse \"{text}\" as a {errorDisplayName}", node);
}
}
}
}
| |
#region License
// Copyright (c) K2 Workflow (SourceCode Technology Holdings Inc.). All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using SourceCode.Clay.Buffers;
using Xunit;
namespace SourceCode.Chasm.Tests
{
public static class Sha1Tests
{
#region Constants
private const string _surrogatePair = "\uD869\uDE01";
#endregion
#region Methods
[Trait("Type", "Unit")]
[Fact(DisplayName = nameof(When_create_null_sha1))]
public static void When_create_null_sha1()
{
var expected = Sha1.Empty;
Assert.Throws<ArgumentNullException>(() => new Sha1((byte[])null, 0));
Assert.True(default == expected);
Assert.False(default != expected);
Assert.True(expected.Equals((object)expected));
Assert.Equal(new KeyValuePair<string, string>("", "0000000000000000000000000000000000000000"), expected.Split(0));
Assert.Equal(new KeyValuePair<string, string>("00", "00000000000000000000000000000000000000"), expected.Split(2));
Assert.Equal(new KeyValuePair<string, string>("0000000000000000000000000000000000000000", ""), expected.Split(Sha1.CharLen));
// Null string
var actual = Sha1.Hash((string)null);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
Assert.Equal(expected.Memory, actual.Memory, BufferComparer.Memory);
// Null bytes
actual = Sha1.Hash((byte[])null);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
Assert.Equal(expected.Memory, actual.Memory, BufferComparer.Memory);
actual = Sha1.Hash(null, 0, 0);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
Assert.Equal(expected.Memory, actual.Memory, BufferComparer.Memory);
// Stream
actual = Sha1.Hash((Stream)null);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
Assert.Equal(expected.Memory, actual.Memory, BufferComparer.Memory);
// Null segment
actual = Sha1.Hash(default(ArraySegment<byte>));
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
Assert.Equal(expected.Memory, actual.Memory, BufferComparer.Memory);
// Roundtrip string
actual = Sha1.Parse(expected.ToString());
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
Assert.Equal(expected.Memory, actual.Memory, BufferComparer.Memory);
// Roundtrip formatted
actual = Sha1.Parse(expected.ToString("D"));
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
Assert.Equal(expected.Memory, actual.Memory, BufferComparer.Memory);
actual = Sha1.Parse(expected.ToString("S"));
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
Assert.Equal(expected.Memory, actual.Memory, BufferComparer.Memory);
// With hex specifier
actual = Sha1.Parse("0x" + expected.ToString("D"));
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
Assert.Equal(expected.Memory, actual.Memory, BufferComparer.Memory);
actual = Sha1.Parse("0x" + expected.ToString("S"));
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
Assert.Equal(expected.Memory, actual.Memory, BufferComparer.Memory);
}
[Trait("Type", "Unit")]
[Fact(DisplayName = nameof(When_construct_sha1_from_Bytes))]
public static void When_construct_sha1_from_Bytes()
{
var expected = Sha1.Hash("abc");
var buffer = new byte[Sha1.ByteLen + 10];
Assert.Throws<ArgumentOutOfRangeException>(() => new Sha1(new byte[Sha1.ByteLen - 1], 0)); // Too short
Assert.Throws<ArgumentOutOfRangeException>(() => new Sha1(new byte[Sha1.ByteLen], 1)); // Bad offset
Assert.Throws<ArgumentOutOfRangeException>(() => Sha1.Hash(new byte[Sha1.ByteLen], 0, -1)); // Bad count
Assert.Throws<ArgumentOutOfRangeException>(() => Sha1.Hash(new byte[Sha1.ByteLen], 1, Sha1.ByteLen)); // Bad offset
// Construct Byte[]
expected.CopyTo(buffer, 0);
var actual = new Sha1(buffer);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
Assert.Equal(expected.Memory, actual.Memory, BufferComparer.Memory);
// Construct Byte[] with offset 0
expected.CopyTo(buffer, 0);
actual = new Sha1(buffer, 0);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
Assert.Equal(expected.Memory, actual.Memory, BufferComparer.Memory);
// Construct Byte[] with offset N
expected.CopyTo(buffer, 5);
actual = new Sha1(buffer, 5);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
Assert.Equal(expected.Memory, actual.Memory, BufferComparer.Memory);
}
[Trait("Type", "Unit")]
[Fact(DisplayName = nameof(When_construct_sha1_from_ArraySegment))]
public static void When_construct_sha1_from_ArraySegment()
{
var expected = Sha1.Hash("abc");
var buffer = new byte[Sha1.ByteLen + 10];
// Construct Byte[] with offset N
expected.CopyTo(buffer, 5);
var actual = new Sha1(buffer, 5);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
Assert.Equal(expected.Memory, actual.Memory, BufferComparer.Memory);
// Construct Segment
expected.CopyTo(buffer, 0);
var seg = new ArraySegment<byte>(buffer);
actual = new Sha1(seg);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
Assert.Equal(expected.Memory, actual.Memory, BufferComparer.Memory);
// Construct Segment with offset 0
expected.CopyTo(buffer, 0);
seg = new ArraySegment<byte>(buffer, 0, Sha1.ByteLen);
actual = new Sha1(seg);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
Assert.Equal(expected.Memory, actual.Memory, BufferComparer.Memory);
// Construct Segment with offset N
expected.CopyTo(buffer, 5);
seg = new ArraySegment<byte>(buffer, 5, Sha1.ByteLen);
actual = new Sha1(seg);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
Assert.Equal(expected.Memory, actual.Memory, BufferComparer.Memory);
}
[Trait("Type", "Unit")]
[Fact(DisplayName = nameof(When_construct_sha1_from_Memory))]
public static void When_construct_sha1_from_Memory()
{
var expected = Sha1.Hash("abc");
var buffer = new byte[Sha1.ByteLen + 10];
Assert.Throws<ArgumentOutOfRangeException>(() => new Sha1(Memory<byte>.Empty.Span)); // Empty
Assert.Throws<ArgumentOutOfRangeException>(() => new Sha1(new Memory<byte>(new byte[Sha1.ByteLen - 1]).Span)); // Too short
// Construct Memory
expected.CopyTo(buffer, 0);
var mem = new Memory<byte>(buffer);
var actual = new Sha1(mem.Span);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
Assert.Equal(expected.Memory, actual.Memory, BufferComparer.Memory);
// Construct Memory with offset 0
expected.CopyTo(buffer, 0);
mem = new Memory<byte>(buffer, 0, Sha1.ByteLen);
actual = new Sha1(mem.Span);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
Assert.Equal(expected.Memory, actual.Memory, BufferComparer.Memory);
// Construct Memory with offset N
expected.CopyTo(buffer, 5);
mem = new Memory<byte>(buffer, 5, Sha1.ByteLen);
actual = new Sha1(mem.Span);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
Assert.Equal(expected.Memory, actual.Memory, BufferComparer.Memory);
}
[Trait("Type", "Unit")]
[Fact(DisplayName = nameof(When_construct_sha1_from_ReadOnlyMemory))]
public static void When_construct_sha1_from_ReadOnlyMemory()
{
var expected = Sha1.Hash("abc");
var buffer = new byte[Sha1.ByteLen + 10];
// Construct ReadOnlyMemory
expected.CopyTo(buffer, 0);
var mem = new ReadOnlyMemory<byte>(buffer);
var actual = new Sha1(mem.Span);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
Assert.Equal(expected.Memory, actual.Memory, BufferComparer.Memory);
// Construct ReadOnlyMemory with offset 0
expected.CopyTo(buffer, 0);
mem = new ReadOnlyMemory<byte>(buffer, 0, Sha1.ByteLen);
actual = new Sha1(mem.Span);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
Assert.Equal(expected.Memory, actual.Memory, BufferComparer.Memory);
// Construct ReadOnlyMemory with offset N
expected.CopyTo(buffer, 5);
mem = new ReadOnlyMemory<byte>(buffer, 5, Sha1.ByteLen);
actual = new Sha1(mem.Span);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
Assert.Equal(expected.Memory, actual.Memory, BufferComparer.Memory);
}
[Trait("Type", "Unit")]
[Fact(DisplayName = nameof(When_construct_sha1_from_Stream))]
public static void When_construct_sha1_from_Stream()
{
var buffer = Encoding.UTF8.GetBytes(Guid.NewGuid().ToString());
// Construct MemoryStream
var mem = new MemoryStream(buffer);
var expected = Sha1.Hash(buffer);
var actual = Sha1.Hash(mem);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
Assert.Equal(expected.Memory, actual.Memory, BufferComparer.Memory);
// Construct MemoryStream with offset 0
mem = new MemoryStream(buffer, 0, buffer.Length);
expected = Sha1.Hash(buffer, 0, buffer.Length);
actual = Sha1.Hash(mem);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
Assert.Equal(expected.Memory, actual.Memory, BufferComparer.Memory);
// Construct MemoryStream with offset N
mem = new MemoryStream(buffer, 5, buffer.Length - 5);
expected = Sha1.Hash(buffer, 5, buffer.Length - 5);
actual = Sha1.Hash(mem);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
Assert.Equal(expected.Memory, actual.Memory, BufferComparer.Memory);
}
[Trait("Type", "Unit")]
[Fact(DisplayName = nameof(When_construct_sha1_from_Span))]
public static void When_construct_sha1_from_Span()
{
var expected = Sha1.Hash("abc");
var buffer = new byte[Sha1.ByteLen + 10];
// Construct Span
expected.CopyTo(buffer, 0);
var span = new Span<byte>(buffer);
var actual = new Sha1(span);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
Assert.Equal(expected.Memory, actual.Memory, BufferComparer.Memory);
// Construct Span with offset 0
expected.CopyTo(buffer, 0);
span = new Span<byte>(buffer, 0, Sha1.ByteLen);
actual = new Sha1(span);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
Assert.Equal(expected.Memory, actual.Memory, BufferComparer.Memory);
// Construct Span with offset N
expected.CopyTo(buffer, 5);
span = new Span<byte>(buffer, 5, Sha1.ByteLen);
actual = new Sha1(span);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
Assert.Equal(expected.Memory, actual.Memory, BufferComparer.Memory);
}
[Trait("Type", "Unit")]
[Fact(DisplayName = nameof(When_copyto_with_null_buffer))]
public static void When_copyto_with_null_buffer()
{
// Arrange
var buffer = (byte[])null;
var sha1 = new Sha1();
// Action
var actual = Assert.Throws<ArgumentNullException>(() => sha1.CopyTo(buffer, 0));
// Assert
Assert.Contains(nameof(buffer), actual.Message);
}
[Trait("Type", "Unit")]
[Fact(DisplayName = nameof(When_copyto_with_null_buffer))]
public static void When_copyto_with_negative_offset()
{
// Arrange
var buffer = new byte[0];
var offset = int.MinValue;
var sha1 = new Sha1();
// Action
var actual = Assert.Throws<ArgumentOutOfRangeException>(() => sha1.CopyTo(buffer, offset));
// Assert
Assert.Contains(nameof(offset), actual.Message);
}
[Trait("Type", "Unit")]
[Fact(DisplayName = nameof(When_copyto_with_overflow_offset))]
public static void When_copyto_with_overflow_offset()
{
// Arrange
var buffer = new byte[0];
var offset = int.MaxValue;
var sha1 = new Sha1();
// Action & Assert
Assert.Throws<OverflowException>(() => sha1.CopyTo(buffer, offset));
}
[Trait("Type", "Unit")]
[Fact(DisplayName = nameof(When_copyto_with_outofrange_offset))]
public static void When_copyto_with_outofrange_offset()
{
// Arrange
var buffer = new byte[0];
var offset = Sha1.ByteLen;
var sha1 = new Sha1();
// Action
var actual = Assert.Throws<ArgumentOutOfRangeException>(() => sha1.CopyTo(buffer, offset));
// Assert
Assert.Contains(nameof(offset), actual.Message);
}
[Trait("Type", "Unit")]
[Fact(DisplayName = nameof(When_construct_sha1_from_ReadOnlySpan))]
public static void When_construct_sha1_from_ReadOnlySpan()
{
var expected = Sha1.Hash("abc");
var buffer = new byte[Sha1.ByteLen + 10];
// Construct ReadOnlySpan
expected.CopyTo(buffer, 0);
var span = new ReadOnlySpan<byte>(buffer);
var actual = new Sha1(span);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
Assert.Equal(expected.Memory, actual.Memory, BufferComparer.Memory);
// Construct ReadOnlySpan with offset 0
expected.CopyTo(buffer, 0);
span = new ReadOnlySpan<byte>(buffer, 0, Sha1.ByteLen);
actual = new Sha1(span);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
Assert.Equal(expected.Memory, actual.Memory, BufferComparer.Memory);
// Construct ReadOnlySpan with offset N
expected.CopyTo(buffer, 5);
span = new ReadOnlySpan<byte>(buffer, 5, Sha1.ByteLen);
actual = new Sha1(span);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
Assert.Equal(expected.Memory, actual.Memory, BufferComparer.Memory);
}
[Trait("Type", "Unit")]
[Theory(DisplayName = nameof(When_create_test_vectors))]
[ClassData(typeof(TestVectors))]
public static void When_create_test_vectors(string input, string expected)
{
// http://www.di-mgt.com.au/sha_testvectors.html
var sha1 = Sha1.Parse(expected);
{
// String
var actual = Sha1.Hash(input).ToString();
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
Assert.Equal(Sha1.CharLen, Encoding.UTF8.GetByteCount(actual));
// Bytes
var bytes = Encoding.UTF8.GetBytes(input);
actual = Sha1.Hash(bytes).ToString();
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
actual = Sha1.Hash(bytes, 0, bytes.Length).ToString();
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Object
Assert.True(expected.Equals((object)actual));
// Roundtrip string
actual = sha1.ToString();
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Roundtrip formatted
actual = Sha1.Parse(sha1.ToString("D")).ToString();
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
actual = Sha1.Parse(sha1.ToString("S")).ToString();
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// With hex specifier
actual = Sha1.Parse("0x" + sha1.ToString("D")).ToString();
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
actual = Sha1.Parse("0x" + sha1.ToString("S")).ToString();
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Get Byte[]
var buffer = new byte[Sha1.ByteLen];
sha1.CopyTo(buffer, 0);
// Roundtrip Byte[]
actual = new Sha1(buffer).ToString();
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Roundtrip Segment
actual = new Sha1(new ArraySegment<byte>(buffer)).ToString();
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
}
}
[Trait("Type", "Unit")]
[Fact(DisplayName = nameof(When_create_sha_from_empty_string))]
public static void When_create_sha_from_empty_string()
{
// http://www.di-mgt.com.au/sha_testvectors.html
const string expected = "da39a3ee5e6b4b0d3255bfef95601890afd80709";
var sha1 = Sha1.Parse(expected);
{
const string input = "";
// String
var actual = Sha1.Hash(input).ToString();
Assert.Equal(expected, actual);
Assert.Equal(Sha1.CharLen, Encoding.UTF8.GetByteCount(actual));
// Empty array
actual = Sha1.Hash(Array.Empty<byte>()).ToString();
Assert.Equal(expected, actual);
actual = Sha1.Hash(Array.Empty<byte>(), 0, 0).ToString();
Assert.Equal(expected, actual);
// Empty segment
actual = Sha1.Hash(new ArraySegment<byte>(Array.Empty<byte>())).ToString();
Assert.Equal(expected, actual);
// Bytes
var bytes = Encoding.UTF8.GetBytes(input);
actual = Sha1.Hash(bytes).ToString();
Assert.Equal(expected, actual);
// Object
Assert.True(expected.Equals((object)actual));
// Roundtrip string
actual = sha1.ToString();
Assert.Equal(expected, actual);
// Roundtrip formatted
actual = Sha1.Parse(sha1.ToString("D")).ToString();
Assert.Equal(expected, actual);
actual = Sha1.Parse(sha1.ToString("S")).ToString();
Assert.Equal(expected, actual);
// With hex specifier
actual = Sha1.Parse("0x" + sha1.ToString("D")).ToString();
Assert.Equal(expected, actual);
actual = Sha1.Parse("0x" + sha1.ToString("S")).ToString();
Assert.Equal(expected, actual);
// Get Byte[]
var buffer = new byte[Sha1.ByteLen];
sha1.CopyTo(buffer, 0);
// Roundtrip Byte[]
actual = new Sha1(buffer).ToString();
Assert.Equal(expected, actual);
// Roundtrip Segment
actual = new Sha1(new ArraySegment<byte>(buffer)).ToString();
Assert.Equal(expected, actual);
}
}
[Trait("Type", "Unit")]
[Fact(DisplayName = nameof(When_create_sha_from_narrow_string))]
public static void When_create_sha_from_narrow_string()
{
for (var i = 1; i < 200; i++)
{
var str = new string(Char.MinValue, i);
var sha1 = Sha1.Hash(str);
Assert.NotEqual(Sha1.Empty, sha1);
Assert.Equal(Sha1.CharLen, Encoding.UTF8.GetByteCount(sha1.ToString()));
}
}
[Trait("Type", "Unit")]
[Fact(DisplayName = nameof(When_create_sha_from_wide_string_1))]
public static void When_create_sha_from_wide_string_1()
{
for (var i = 1; i < 200; i++)
{
var str = new string(Char.MaxValue, i);
var sha1 = Sha1.Hash(str);
Assert.NotEqual(Sha1.Empty, sha1);
Assert.Equal(Sha1.CharLen, Encoding.UTF8.GetByteCount(sha1.ToString()));
}
}
[Trait("Type", "Unit")]
[Fact(DisplayName = nameof(When_create_sha_from_wide_string_2))]
public static void When_create_sha_from_wide_string_2()
{
var str = string.Empty;
for (var i = 1; i < 200; i++)
{
str += _surrogatePair;
var sha1 = Sha1.Hash(str);
Assert.NotEqual(Sha1.Empty, sha1);
Assert.Equal(Sha1.CharLen, Encoding.UTF8.GetByteCount(sha1.ToString()));
}
}
[Trait("Type", "Unit")]
[Fact(DisplayName = nameof(When_format_sha1))]
public static void When_format_sha1()
{
const string expected_N = "a9993e364706816aba3e25717850c26c9cd0d89d";
var sha1 = Sha1.Parse(expected_N);
// ("N")
{
var actual = sha1.ToString(); // Default format
Assert.Equal(expected_N, actual);
actual = sha1.ToString("N");
Assert.Equal(expected_N, actual);
actual = sha1.ToString("n");
Assert.Equal(expected_N, actual);
}
// ("D")
{
const string expected_D = "a9993e36-4706816a-ba3e2571-7850c26c-9cd0d89d";
var actual = sha1.ToString("D");
Assert.Equal(expected_D, actual);
actual = sha1.ToString("d");
Assert.Equal(expected_D, actual);
}
// ("S")
{
const string expected_S = "a9993e36 4706816a ba3e2571 7850c26c 9cd0d89d";
var actual = sha1.ToString("S");
Assert.Equal(expected_S, actual);
actual = sha1.ToString("s");
Assert.Equal(expected_S, actual);
}
// (null)
{
Assert.Throws<FormatException>(() => sha1.ToString(null));
}
// ("")
{
Assert.Throws<FormatException>(() => sha1.ToString(""));
}
// (" ")
{
Assert.Throws<FormatException>(() => sha1.ToString(" "));
}
// ("x")
{
Assert.Throws<FormatException>(() => sha1.ToString("x"));
}
// ("ss")
{
Assert.Throws<FormatException>(() => sha1.ToString("nn"));
}
}
[Trait("Type", "Unit")]
[Fact(DisplayName = nameof(When_parse_sha1))]
public static void When_parse_sha1()
{
const string expected_N = "a9993e364706816aba3e25717850c26c9cd0d89d";
var sha1 = Sha1.Parse(expected_N);
Assert.True(Sha1.TryParse(expected_N, out _));
Assert.True(Sha1.TryParse("0x" + expected_N, out _));
Assert.True(Sha1.TryParse("0X" + expected_N, out _));
Assert.False(Sha1.TryParse(expected_N.Substring(10), out _));
Assert.False(Sha1.TryParse("0x" + expected_N.Substring(10), out _));
Assert.False(Sha1.TryParse("0X" + expected_N.Substring(10), out _));
Assert.False(Sha1.TryParse("0x" + expected_N.Substring(Sha1.CharLen - 2), out _));
Assert.False(Sha1.TryParse("0X" + expected_N.Substring(Sha1.CharLen - 2), out _));
Assert.False(Sha1.TryParse(expected_N.Replace('8', 'G'), out _));
Assert.False(Sha1.TryParse($"0x{new string('1', 38)}", out _));
Assert.False(Sha1.TryParse($"0x{new string('1', 39)}", out _));
Assert.True(Sha1.TryParse($"0x{new string('1', 40)}", out _));
// "N"
{
var actual = Sha1.Parse(sha1.ToString()); // Default format
Assert.Equal(sha1, actual);
actual = Sha1.Parse(sha1.ToString("N"));
Assert.Equal(sha1, actual);
actual = Sha1.Parse("0x" + sha1.ToString("N"));
Assert.Equal(sha1, actual);
Assert.Throws<FormatException>(() => Sha1.Parse(sha1.ToString("N") + "a"));
}
// "D"
{
var actual = Sha1.Parse(sha1.ToString("D"));
Assert.Equal(sha1, actual);
actual = Sha1.Parse("0x" + sha1.ToString("D"));
Assert.Equal(sha1, actual);
Assert.Throws<FormatException>(() => Sha1.Parse(sha1.ToString("D") + "a"));
}
// "S"
{
var actual = Sha1.Parse(sha1.ToString("S"));
Assert.Equal(sha1, actual);
actual = Sha1.Parse("0x" + sha1.ToString("S"));
Assert.Equal(sha1, actual);
Assert.Throws<FormatException>(() => Sha1.Parse(sha1.ToString("S") + "a"));
}
// null
{
Assert.Throws<FormatException>(() => Sha1.Parse(null));
}
// Empty
{
Assert.Throws<FormatException>(() => Sha1.Parse(""));
}
// Whitespace
{
Assert.Throws<FormatException>(() => Sha1.Parse(" "));
Assert.Throws<FormatException>(() => Sha1.Parse("\t"));
Assert.Throws<FormatException>(() => Sha1.Parse(" " + expected_N));
Assert.Throws<FormatException>(() => Sha1.Parse(expected_N + " "));
}
// "0x"
{
Assert.Throws<FormatException>(() => Sha1.Parse("0x"));
}
}
[Trait("Type", "Unit")]
[Fact(DisplayName = nameof(When_lexographic_compare_sha1))]
public static void When_lexographic_compare_sha1()
{
var byt1 = new byte[20] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 };
var sha1 = new Sha1(byt1);
var str1 = sha1.ToString();
Assert.Equal(@"000102030405060708090a0b0c0d0e0f10111213", str1);
// Bump blit0
var sha2 = new Sha1(sha1.Blit0 + 1, sha1.Blit1, sha1.Blit2);
var str2 = sha2.ToString();
Assert.Equal(@"_01_0102030405060708090a0b0c0d0e0f10111213".Replace("_", ""), str2);
for (ushort i = 1; i < ushort.MaxValue; i++)
{
sha2 = new Sha1(sha1.Blit0 + i, sha1.Blit1, sha1.Blit2);
Assert.True(sha2 > sha1);
}
// Bump blit1
sha2 = new Sha1(sha1.Blit0, sha1.Blit1 + 1, sha1.Blit2);
str2 = sha2.ToString();
Assert.Equal(@"0001020304050607_09_090a0b0c0d0e0f10111213".Replace("_", ""), str2);
for (ushort i = 1; i < ushort.MaxValue; i++)
{
sha2 = new Sha1(sha1.Blit0, sha1.Blit1 + i, sha1.Blit2);
Assert.True(sha2 > sha1);
}
// Bump blit2
sha2 = new Sha1(sha1.Blit0, sha1.Blit1, sha1.Blit2 + 1);
str2 = sha2.ToString();
Assert.Equal(@"000102030405060708090a0b0c0d0e0f_11_111213".Replace("_", ""), str2);
for (ushort i = 1; i < ushort.MaxValue; i++)
{
sha2 = new Sha1(sha1.Blit0, sha1.Blit1, sha1.Blit2 + i);
Assert.True(sha2 > sha1);
}
}
[Trait("Type", "Unit")]
[Fact(DisplayName = nameof(Sha1_Deconstruct))]
public static void Sha1_Deconstruct()
{
var expected = Sha1.Hash("abc");
var (blit0, blit1, blit2) = expected;
var actual = new Sha1(blit0, blit1, blit2);
Assert.Equal(expected, actual);
}
[Trait("Type", "Unit")]
[Fact(DisplayName = nameof(Sha1_Compare))]
public static void Sha1_Compare()
{
var comparer = Sha1Comparer.Default;
var sha1 = Sha1.Hash("abc");
var sha2 = Sha1.Hash("abc");
var sha3 = Sha1.Hash("def");
Assert.True(Sha1.Empty < sha1);
Assert.True(sha1 > Sha1.Empty);
var list = new[] { sha1, sha2, sha3 };
Assert.True(sha1.CompareTo(sha2) == 0);
Assert.True(sha1.CompareTo(sha3) != 0);
Array.Sort(list, comparer.Compare);
Assert.True(list[0] <= list[1]);
Assert.True(list[2] >= list[1]);
}
#endregion
}
}
| |
using System;
using System.Buffers;
using System.Diagnostics;
using System.IO.Pipelines;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
namespace Orleans.Networking.Shared
{
internal sealed class SocketConnection : TransportConnection
{
private static readonly int MinAllocBufferSize = SlabMemoryPool.BlockSize / 2;
private static readonly bool IsWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
private static readonly bool IsMacOS = RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
private readonly Socket _socket;
private readonly ISocketsTrace _trace;
private readonly SocketReceiver _receiver;
private readonly SocketSender _sender;
private readonly CancellationTokenSource _connectionClosedTokenSource = new CancellationTokenSource();
private readonly object _shutdownLock = new object();
private volatile bool _socketDisposed;
private volatile Exception _shutdownReason;
private Task _processingTask;
private readonly TaskCompletionSource<object> _waitForConnectionClosedTcs = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);
private bool _connectionClosed;
internal SocketConnection(Socket socket,
MemoryPool<byte> memoryPool,
PipeScheduler scheduler,
ISocketsTrace trace,
long? maxReadBufferSize = null,
long? maxWriteBufferSize = null)
{
Debug.Assert(socket != null);
Debug.Assert(memoryPool != null);
Debug.Assert(trace != null);
_socket = socket;
MemoryPool = memoryPool;
_trace = trace;
LocalEndPoint = _socket.LocalEndPoint;
RemoteEndPoint = _socket.RemoteEndPoint;
ConnectionClosed = _connectionClosedTokenSource.Token;
// On *nix platforms, Sockets already dispatches to the ThreadPool.
// Yes, the IOQueues are still used for the PipeSchedulers. This is intentional.
// https://github.com/aspnet/KestrelHttpServer/issues/2573
var awaiterScheduler = IsWindows ? scheduler : PipeScheduler.Inline;
_receiver = new SocketReceiver(_socket, awaiterScheduler);
_sender = new SocketSender(_socket, awaiterScheduler);
maxReadBufferSize = maxReadBufferSize ?? 0;
maxWriteBufferSize = maxWriteBufferSize ?? 0;
var inputOptions = new PipeOptions(MemoryPool, PipeScheduler.ThreadPool, scheduler, maxReadBufferSize.Value, maxReadBufferSize.Value / 2, useSynchronizationContext: false);
var outputOptions = new PipeOptions(MemoryPool, scheduler, PipeScheduler.ThreadPool, maxWriteBufferSize.Value, maxWriteBufferSize.Value / 2, useSynchronizationContext: false);
var pair = DuplexPipe.CreateConnectionPair(inputOptions, outputOptions);
// Set the transport and connection id
Transport = pair.Transport;
Application = pair.Application;
}
public PipeWriter Input => Application.Output;
public PipeReader Output => Application.Input;
public override MemoryPool<byte> MemoryPool { get; }
public void Start()
{
_processingTask = StartAsync();
}
private async Task StartAsync()
{
try
{
// Spawn send and receive logic
var receiveTask = DoReceive();
var sendTask = DoSend();
// Now wait for both to complete
await receiveTask;
await sendTask;
_receiver.Dispose();
_sender.Dispose();
}
catch (Exception ex)
{
_trace.LogError(0, ex, $"Unexpected exception in {nameof(SocketConnection)}.{nameof(StartAsync)}.");
}
}
public override void Abort(ConnectionAbortedException abortReason)
{
// Try to gracefully close the socket to match libuv behavior.
Shutdown(abortReason);
// Cancel ProcessSends loop after calling shutdown to ensure the correct _shutdownReason gets set.
Output.CancelPendingRead();
}
// Only called after connection middleware is complete which means the ConnectionClosed token has fired.
public override async ValueTask DisposeAsync()
{
Transport.Input.Complete();
Transport.Output.Complete();
if (_processingTask != null)
{
await _processingTask;
}
_connectionClosedTokenSource.Dispose();
}
private async Task DoReceive()
{
Exception error = null;
try
{
await ProcessReceives();
}
catch (SocketException ex) when (IsConnectionResetError(ex.SocketErrorCode))
{
// This could be ignored if _shutdownReason is already set.
error = new ConnectionResetException(ex.Message, ex);
// There's still a small chance that both DoReceive() and DoSend() can log the same connection reset.
// Both logs will have the same ConnectionId. I don't think it's worthwhile to lock just to avoid this.
if (!_socketDisposed)
{
_trace.ConnectionReset(ConnectionId);
}
}
catch (Exception ex)
when ((ex is SocketException socketEx && IsConnectionAbortError(socketEx.SocketErrorCode)) ||
ex is ObjectDisposedException)
{
// This exception should always be ignored because _shutdownReason should be set.
error = ex;
if (!_socketDisposed)
{
// This is unexpected if the socket hasn't been disposed yet.
_trace.ConnectionError(ConnectionId, error);
}
}
catch (Exception ex)
{
// This is unexpected.
error = ex;
_trace.ConnectionError(ConnectionId, error);
}
finally
{
// If Shutdown() has already bee called, assume that was the reason ProcessReceives() exited.
Input.Complete(_shutdownReason ?? error);
FireConnectionClosed();
await _waitForConnectionClosedTcs.Task;
}
}
private async Task ProcessReceives()
{
// Resolve `input` PipeWriter via the IDuplexPipe interface prior to loop start for performance.
var input = Input;
while (true)
{
// Wait for data before allocating a buffer.
await _receiver.WaitForDataAsync();
// Ensure we have some reasonable amount of buffer space
var buffer = input.GetMemory(MinAllocBufferSize);
var bytesReceived = await _receiver.ReceiveAsync(buffer);
if (bytesReceived == 0)
{
// FIN
_trace.ConnectionReadFin(ConnectionId);
break;
}
input.Advance(bytesReceived);
var flushTask = input.FlushAsync();
var paused = !flushTask.IsCompleted;
if (paused)
{
_trace.ConnectionPause(ConnectionId);
}
var result = await flushTask;
if (paused)
{
_trace.ConnectionResume(ConnectionId);
}
if (result.IsCompleted || result.IsCanceled)
{
// Pipe consumer is shut down, do we stop writing
break;
}
}
}
private async Task DoSend()
{
Exception shutdownReason = null;
Exception unexpectedError = null;
try
{
await ProcessSends();
}
catch (SocketException ex) when (IsConnectionResetError(ex.SocketErrorCode))
{
shutdownReason = new ConnectionResetException(ex.Message, ex);
_trace.ConnectionReset(ConnectionId);
}
catch (Exception ex)
when ((ex is SocketException socketEx && IsConnectionAbortError(socketEx.SocketErrorCode)) ||
ex is ObjectDisposedException)
{
// This should always be ignored since Shutdown() must have already been called by Abort().
shutdownReason = ex;
}
catch (Exception ex)
{
shutdownReason = ex;
unexpectedError = ex;
_trace.ConnectionError(ConnectionId, unexpectedError);
}
finally
{
Shutdown(shutdownReason);
// Complete the output after disposing the socket
Output.Complete(unexpectedError);
// Cancel any pending flushes so that the input loop is un-paused
Input.CancelPendingFlush();
}
}
private async Task ProcessSends()
{
// Resolve `output` PipeReader via the IDuplexPipe interface prior to loop start for performance.
var output = Output;
while (true)
{
var result = await output.ReadAsync();
if (result.IsCanceled)
{
break;
}
var buffer = result.Buffer;
var end = buffer.End;
var isCompleted = result.IsCompleted;
if (!buffer.IsEmpty)
{
await _sender.SendAsync(buffer);
}
output.AdvanceTo(end);
if (isCompleted)
{
break;
}
}
}
private void FireConnectionClosed()
{
// Guard against scheduling this multiple times
if (_connectionClosed)
{
return;
}
_connectionClosed = true;
ThreadPool.UnsafeQueueUserWorkItem(state =>
{
((SocketConnection)state).CancelConnectionClosedToken();
((SocketConnection)state)._waitForConnectionClosedTcs.TrySetResult(null);
},
this);
}
private void Shutdown(Exception shutdownReason)
{
lock (_shutdownLock)
{
if (_socketDisposed)
{
return;
}
// Make sure to close the connection only after the _aborted flag is set.
// Without this, the RequestsCanBeAbortedMidRead test will sometimes fail when
// a BadHttpRequestException is thrown instead of a TaskCanceledException.
_socketDisposed = true;
// shutdownReason should only be null if the output was completed gracefully, so no one should ever
// ever observe the nondescript ConnectionAbortedException except for connection middleware attempting
// to half close the connection which is currently unsupported.
_shutdownReason = shutdownReason ?? new ConnectionAbortedException("The Socket transport's send loop completed gracefully.");
_trace.ConnectionWriteFin(ConnectionId, _shutdownReason.Message);
try
{
// Try to gracefully close the socket even for aborts to match libuv behavior.
_socket.Shutdown(SocketShutdown.Both);
}
catch
{
// Ignore any errors from Socket.Shutdown() since we're tearing down the connection anyway.
}
_socket.Dispose();
}
}
private void CancelConnectionClosedToken()
{
try
{
_connectionClosedTokenSource.Cancel();
}
catch (Exception ex)
{
_trace.LogError(0, ex, $"Unexpected exception in {nameof(SocketConnection)}.{nameof(CancelConnectionClosedToken)}.");
}
}
private static bool IsConnectionResetError(SocketError errorCode)
{
// A connection reset can be reported as SocketError.ConnectionAborted on Windows.
// ProtocolType can be removed once https://github.com/dotnet/corefx/issues/31927 is fixed.
return errorCode == SocketError.ConnectionReset ||
errorCode == SocketError.Shutdown ||
(errorCode == SocketError.ConnectionAborted && IsWindows) ||
(errorCode == SocketError.ProtocolType && IsMacOS);
}
private static bool IsConnectionAbortError(SocketError errorCode)
{
// Calling Dispose after ReceiveAsync can cause an "InvalidArgument" error on *nix.
return errorCode == SocketError.OperationAborted ||
errorCode == SocketError.Interrupted ||
(errorCode == SocketError.InvalidArgument && !IsWindows);
}
}
}
| |
/*
* Farseer Physics Engine:
* Copyright (c) 2012 Ian Qvist
*
* Original source Box2D:
* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#pragma warning disable 0162
using System.Diagnostics;
namespace TrueSync.Physics2D
{
/// <summary>
/// A motor joint is used to control the relative motion
/// between two bodies. A typical usage is to control the movement
/// of a dynamic body with respect to the ground.
/// </summary>
public class MotorJoint : Joint2D
{
// Solver shared
private TSVector2 _linearOffset;
private FP _angularOffset;
private TSVector2 _linearImpulse;
private FP _angularImpulse;
private FP _maxForce;
private FP _maxTorque;
// Solver temp
private int _indexA;
private int _indexB;
private TSVector2 _rA;
private TSVector2 _rB;
private TSVector2 _localCenterA;
private TSVector2 _localCenterB;
private TSVector2 _linearError;
private FP _angularError;
private FP _invMassA;
private FP _invMassB;
private FP _invIA;
private FP _invIB;
private Mat22 _linearMass;
private FP _angularMass;
internal MotorJoint()
{
JointType = JointType.Motor;
}
/// <summary>
/// Constructor for MotorJoint.
/// </summary>
/// <param name="bodyA">The first body</param>
/// <param name="bodyB">The second body</param>
/// <param name="useWorldCoordinates">Set to true if you are using world coordinates as anchors.</param>
public MotorJoint(Body bodyA, Body bodyB, bool useWorldCoordinates = false)
: base(bodyA, bodyB)
{
JointType = JointType.Motor;
TSVector2 xB = BodyB.Position;
if (useWorldCoordinates)
_linearOffset = BodyA.GetLocalPoint(xB);
else
_linearOffset = xB;
//Defaults
_angularOffset = 0.0f;
_maxForce = 1.0f;
_maxTorque = 1.0f;
CorrectionFactor = 0.3f;
_angularOffset = BodyB.Rotation - BodyA.Rotation;
}
public override TSVector2 WorldAnchorA
{
get { return BodyA.Position; }
set { Debug.Assert(false, "You can't set the world anchor on this joint type."); }
}
public override TSVector2 WorldAnchorB
{
get { return BodyB.Position; }
set { Debug.Assert(false, "You can't set the world anchor on this joint type."); }
}
/// <summary>
/// The maximum amount of force that can be applied to BodyA
/// </summary>
public FP MaxForce
{
set
{
Debug.Assert(MathUtils.IsValid(value) && value >= 0.0f);
_maxForce = value;
}
get { return _maxForce; }
}
/// <summary>
/// The maximum amount of torque that can be applied to BodyA
/// </summary>
public FP MaxTorque
{
set
{
Debug.Assert(MathUtils.IsValid(value) && value >= 0.0f);
_maxTorque = value;
}
get { return _maxTorque; }
}
/// <summary>
/// The linear (translation) offset.
/// </summary>
public TSVector2 LinearOffset
{
set
{
if (_linearOffset.x != value.x || _linearOffset.y != value.y)
{
WakeBodies();
_linearOffset = value;
}
}
get { return _linearOffset; }
}
/// <summary>
/// Get or set the angular offset.
/// </summary>
public FP AngularOffset
{
set
{
if (_angularOffset != value)
{
WakeBodies();
_angularOffset = value;
}
}
get { return _angularOffset; }
}
//FPE note: Used for serialization.
internal FP CorrectionFactor { get; set; }
public override TSVector2 GetReactionForce(FP invDt)
{
return invDt * _linearImpulse;
}
public override FP GetReactionTorque(FP invDt)
{
return invDt * _angularImpulse;
}
internal override void InitVelocityConstraints(ref SolverData data)
{
_indexA = BodyA.IslandIndex;
_indexB = BodyB.IslandIndex;
_localCenterA = BodyA._sweep.LocalCenter;
_localCenterB = BodyB._sweep.LocalCenter;
_invMassA = BodyA._invMass;
_invMassB = BodyB._invMass;
_invIA = BodyA._invI;
_invIB = BodyB._invI;
TSVector2 cA = data.positions[_indexA].c;
FP aA = data.positions[_indexA].a;
TSVector2 vA = data.velocities[_indexA].v;
FP wA = data.velocities[_indexA].w;
TSVector2 cB = data.positions[_indexB].c;
FP aB = data.positions[_indexB].a;
TSVector2 vB = data.velocities[_indexB].v;
FP wB = data.velocities[_indexB].w;
Rot qA = new Rot(aA);
Rot qB = new Rot(aB);
// Compute the effective mass matrix.
_rA = MathUtils.Mul(qA, -_localCenterA);
_rB = MathUtils.Mul(qB, -_localCenterB);
// J = [-I -r1_skew I r2_skew]
// [ 0 -1 0 1]
// r_skew = [-ry; rx]
// Matlab
// K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB]
// [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB]
// [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB]
FP mA = _invMassA, mB = _invMassB;
FP iA = _invIA, iB = _invIB;
Mat22 K = new Mat22();
K.ex.x = mA + mB + iA * _rA.y * _rA.y + iB * _rB.y * _rB.y;
K.ex.y = -iA * _rA.x * _rA.y - iB * _rB.x * _rB.y;
K.ey.x = K.ex.y;
K.ey.y = mA + mB + iA * _rA.x * _rA.x + iB * _rB.x * _rB.x;
_linearMass = K.Inverse;
_angularMass = iA + iB;
if (_angularMass > 0.0f)
{
_angularMass = 1.0f / _angularMass;
}
_linearError = cB + _rB - cA - _rA - MathUtils.Mul(qA, _linearOffset);
_angularError = aB - aA - _angularOffset;
if (Settings.EnableWarmstarting)
{
// Scale impulses to support a variable time step.
_linearImpulse *= data.step.dtRatio;
_angularImpulse *= data.step.dtRatio;
TSVector2 P = new TSVector2(_linearImpulse.x, _linearImpulse.y);
vA -= mA * P;
wA -= iA * (MathUtils.Cross(_rA, P) + _angularImpulse);
vB += mB * P;
wB += iB * (MathUtils.Cross(_rB, P) + _angularImpulse);
}
else
{
_linearImpulse = TSVector2.zero;
_angularImpulse = 0.0f;
}
data.velocities[_indexA].v = vA;
data.velocities[_indexA].w = wA;
data.velocities[_indexB].v = vB;
data.velocities[_indexB].w = wB;
}
internal override void SolveVelocityConstraints(ref SolverData data)
{
TSVector2 vA = data.velocities[_indexA].v;
FP wA = data.velocities[_indexA].w;
TSVector2 vB = data.velocities[_indexB].v;
FP wB = data.velocities[_indexB].w;
FP mA = _invMassA, mB = _invMassB;
FP iA = _invIA, iB = _invIB;
FP h = data.step.dt;
FP inv_h = data.step.inv_dt;
// Solve angular friction
{
FP Cdot = wB - wA + inv_h * CorrectionFactor * _angularError;
FP impulse = -_angularMass * Cdot;
FP oldImpulse = _angularImpulse;
FP maxImpulse = h * _maxTorque;
_angularImpulse = MathUtils.Clamp(_angularImpulse + impulse, -maxImpulse, maxImpulse);
impulse = _angularImpulse - oldImpulse;
wA -= iA * impulse;
wB += iB * impulse;
}
// Solve linear friction
{
TSVector2 Cdot = vB + MathUtils.Cross(wB, _rB) - vA - MathUtils.Cross(wA, _rA) + inv_h * CorrectionFactor * _linearError;
TSVector2 impulse = -MathUtils.Mul(ref _linearMass, ref Cdot);
TSVector2 oldImpulse = _linearImpulse;
_linearImpulse += impulse;
FP maxImpulse = h * _maxForce;
if (_linearImpulse.LengthSquared() > maxImpulse * maxImpulse)
{
_linearImpulse.Normalize();
_linearImpulse *= maxImpulse;
}
impulse = _linearImpulse - oldImpulse;
vA -= mA * impulse;
wA -= iA * MathUtils.Cross(_rA, impulse);
vB += mB * impulse;
wB += iB * MathUtils.Cross(_rB, impulse);
}
data.velocities[_indexA].v = vA;
data.velocities[_indexA].w = wA;
data.velocities[_indexB].v = vB;
data.velocities[_indexB].w = wB;
}
internal override bool SolvePositionConstraints(ref SolverData data)
{
return true;
}
}
}
| |
// SF API version v50.0
// Custom fields included: False
// Relationship objects included: True
using System;
using NetCoreForce.Client.Models;
using NetCoreForce.Client.Attributes;
using Newtonsoft.Json;
namespace NetCoreForce.Models
{
///<summary>
/// Embedded Service
///<para>SObject Name: EmbeddedServiceDetail</para>
///<para>Custom Object: False</para>
///</summary>
public class SfEmbeddedServiceDetail : SObject
{
[JsonIgnore]
public static string SObjectTypeName
{
get { return "EmbeddedServiceDetail"; }
}
///<summary>
/// Embedded Service ID
/// <para>Name: Id</para>
/// <para>SF Type: id</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "id")]
[Updateable(false), Createable(false)]
public string Id { get; set; }
///<summary>
/// Embedded Service Durable ID
/// <para>Name: DurableId</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "durableId")]
[Updateable(false), Createable(false)]
public string DurableId { get; set; }
///<summary>
/// Site
/// <para>Name: Site</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "site")]
[Updateable(false), Createable(false)]
public string Site { get; set; }
///<summary>
/// Primary Color
/// <para>Name: PrimaryColor</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "primaryColor")]
[Updateable(false), Createable(false)]
public string PrimaryColor { get; set; }
///<summary>
/// Secondary Color
/// <para>Name: SecondaryColor</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "secondaryColor")]
[Updateable(false), Createable(false)]
public string SecondaryColor { get; set; }
///<summary>
/// Contrast Primary Color
/// <para>Name: ContrastPrimaryColor</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "contrastPrimaryColor")]
[Updateable(false), Createable(false)]
public string ContrastPrimaryColor { get; set; }
///<summary>
/// Contrast Inverted Color
/// <para>Name: ContrastInvertedColor</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "contrastInvertedColor")]
[Updateable(false), Createable(false)]
public string ContrastInvertedColor { get; set; }
///<summary>
/// NavBar Color
/// <para>Name: NavBarColor</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "navBarColor")]
[Updateable(false), Createable(false)]
public string NavBarColor { get; set; }
///<summary>
/// NavBar Text Color
/// <para>Name: NavBarTextColor</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "navBarTextColor")]
[Updateable(false), Createable(false)]
public string NavBarTextColor { get; set; }
///<summary>
/// Secondary NavBar Color
/// <para>Name: SecondaryNavBarColor</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "secondaryNavBarColor")]
[Updateable(false), Createable(false)]
public string SecondaryNavBarColor { get; set; }
///<summary>
/// Font
/// <para>Name: Font</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "font")]
[Updateable(false), Createable(false)]
public string Font { get; set; }
///<summary>
/// Enabled
/// <para>Name: IsLiveAgentEnabled</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isLiveAgentEnabled")]
[Updateable(false), Createable(false)]
public bool? IsLiveAgentEnabled { get; set; }
///<summary>
/// Enabled
/// <para>Name: IsFieldServiceEnabled</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isFieldServiceEnabled")]
[Updateable(false), Createable(false)]
public bool? IsFieldServiceEnabled { get; set; }
///<summary>
/// Width
/// <para>Name: Width</para>
/// <para>SF Type: int</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "width")]
[Updateable(false), Createable(false)]
public int? Width { get; set; }
///<summary>
/// Height
/// <para>Name: Height</para>
/// <para>SF Type: int</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "height")]
[Updateable(false), Createable(false)]
public int? Height { get; set; }
///<summary>
/// Pre-Chat Enabled
/// <para>Name: IsPrechatEnabled</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isPrechatEnabled")]
[Updateable(false), Createable(false)]
public bool? IsPrechatEnabled { get; set; }
///<summary>
/// Custom Prechat Component Developer Name
/// <para>Name: CustomPrechatComponent</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "customPrechatComponent")]
[Updateable(false), Createable(false)]
public string CustomPrechatComponent { get; set; }
///<summary>
/// Avatar Image URL
/// <para>Name: AvatarImg</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "avatarImg")]
[Updateable(false), Createable(false)]
public string AvatarImg { get; set; }
///<summary>
/// Small Company Logo Image URL
/// <para>Name: SmallCompanyLogoImg</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "smallCompanyLogoImg")]
[Updateable(false), Createable(false)]
public string SmallCompanyLogoImg { get; set; }
///<summary>
/// Pre-Chat Background Image URL
/// <para>Name: PrechatBackgroundImg</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "prechatBackgroundImg")]
[Updateable(false), Createable(false)]
public string PrechatBackgroundImg { get; set; }
///<summary>
/// Waiting State Background Image URL
/// <para>Name: WaitingStateBackgroundImg</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "waitingStateBackgroundImg")]
[Updateable(false), Createable(false)]
public string WaitingStateBackgroundImg { get; set; }
///<summary>
/// Font Size
/// <para>Name: FontSize</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "fontSize")]
[Updateable(false), Createable(false)]
public string FontSize { get; set; }
///<summary>
/// Offline Case Background Image URL
/// <para>Name: OfflineCaseBackgroundImg</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "offlineCaseBackgroundImg")]
[Updateable(false), Createable(false)]
public string OfflineCaseBackgroundImg { get; set; }
///<summary>
/// Offline Case Enabled
/// <para>Name: IsOfflineCaseEnabled</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isOfflineCaseEnabled")]
[Updateable(false), Createable(false)]
public bool? IsOfflineCaseEnabled { get; set; }
///<summary>
/// Queue Position Enabled
/// <para>Name: IsQueuePositionEnabled</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isQueuePositionEnabled")]
[Updateable(false), Createable(false)]
public bool? IsQueuePositionEnabled { get; set; }
///<summary>
/// Show New Appointment
/// <para>Name: ShouldShowNewAppointment</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "shouldShowNewAppointment")]
[Updateable(false), Createable(false)]
public bool? ShouldShowNewAppointment { get; set; }
///<summary>
/// Show Existing Appointment
/// <para>Name: ShouldShowExistingAppointment</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "shouldShowExistingAppointment")]
[Updateable(false), Createable(false)]
public bool? ShouldShowExistingAppointment { get; set; }
///<summary>
/// Field Service Home Image URL
/// <para>Name: FieldServiceHomeImg</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "fieldServiceHomeImg")]
[Updateable(false), Createable(false)]
public string FieldServiceHomeImg { get; set; }
///<summary>
/// Field Service Logo Image URL
/// <para>Name: FieldServiceLogoImg</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "fieldServiceLogoImg")]
[Updateable(false), Createable(false)]
public string FieldServiceLogoImg { get; set; }
///<summary>
/// Field Service Confirmation Card Image URL
/// <para>Name: FieldServiceConfirmCardImg</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "fieldServiceConfirmCardImg")]
[Updateable(false), Createable(false)]
public string FieldServiceConfirmCardImg { get; set; }
///<summary>
/// Hide Authentication Dialog
/// <para>Name: ShouldHideAuthDialog</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "shouldHideAuthDialog")]
[Updateable(false), Createable(false)]
public bool? ShouldHideAuthDialog { get; set; }
///<summary>
/// Custom Minimized Component Developer Name
/// <para>Name: CustomMinimizedComponent</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "customMinimizedComponent")]
[Updateable(false), Createable(false)]
public string CustomMinimizedComponent { get; set; }
}
}
| |
#region COPYRIGHT (c) 2007 by Matthias Fischer
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
// PURPOSE.
//
// This material may not be duplicated in whole or in part, except for
// personal use, without the express written consent of the author.
//
// Autor: Matthais Fischer
// Email: [email protected]
//
// Copyright (C) 2007 Matthias Fischer. All Rights Reserved.
#endregion
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace stRevizor.TFTP
{
/// <summary>
/// Implementation of Basic TFTP Client Functions
/// </summary>
public class TFTPClient {
#region -=[ Declarations ]=-
/// <summary>
/// TFTP opcodes
/// </summary>
public enum Opcodes {
Unknown = 0,
Read = 1,
Write = 2,
Data = 3,
Ack = 4,
Error = 5
}
/// <summary>
/// TFTP modes
/// </summary>
public enum Modes {
Unknown = 0,
NetAscii = 1,
Octet = 2,
Mail = 3
}
private int tftpPort ;
private string tftpServer = "";
#endregion
#region -=[ Ctor ]=-
/// <summary>
/// Initializes a new instance of the <see cref="TFTPClient"/> class.
/// </summary>
/// <param name="server">The server.</param>
public TFTPClient(string server)
: this(server, 69) {
}
/// <summary>
/// Initializes a new instance of the <see cref="TFTPClient"/> class.
/// </summary>
/// <param name="server">The server.</param>
/// <param name="port">The port.</param>
public TFTPClient(string server, int port) {
Server = server;
Port = port;
}
#endregion
#region -=[ Public Properties ]=-
/// <summary>
/// Gets the port.
/// </summary>
/// <value>The port.</value>
public int Port {
get { return tftpPort; }
private set { tftpPort = value; }
}
/// <summary>
/// Gets the server.
/// </summary>
/// <value>The server.</value>
public string Server {
get { return tftpServer; }
private set { tftpServer = value; }
}
#endregion
#region -=[ Public Member ]=-
/// <summary>
/// Gets the specified remote file.
/// </summary>
/// <param name="remoteFile">The remote file.</param>
/// <param name="localFile">The local file.</param>
public void Get(string remoteFile, string localFile) {
Get(remoteFile, localFile, Modes.Octet);
}
/// <summary>
/// Gets the specified remote file.
/// </summary>
/// <param name="remoteFile">The remote file.</param>
/// <param name="localFile">The local file.</param>
/// <param name="tftpMode">The TFTP mode.</param>
public void Get(string remoteFile, string localFile, Modes tftpMode) {
int len = 0;
int packetNr = 1;
byte[] sndBuffer = CreateRequestPacket(Opcodes.Read, remoteFile, tftpMode);
byte[] rcvBuffer = new byte[516];
IPAddress ipa;
if ((ipa = stXFTPUtil.GetIPAddress(tftpServer)) == null)
{
throw new XFTPException(502, Properties.Resources.txtXFTPBadIpAddress);
}
BinaryWriter fileStream = new BinaryWriter(new FileStream(localFile, FileMode.Create, FileAccess.Write, FileShare.Read));
IPEndPoint serverEP = new IPEndPoint(ipa, tftpPort);
EndPoint dataEP = (EndPoint)serverEP;
Socket tftpSocket = new Socket(serverEP.Address.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
// Request and Receive first Data Packet From TFTP Server
tftpSocket.SendTo(sndBuffer, sndBuffer.Length, SocketFlags.None, serverEP);
tftpSocket.ReceiveTimeout = 1000 ;
len = tftpSocket.ReceiveFrom(rcvBuffer, ref dataEP);
// keep track of the TID
serverEP.Port = ((IPEndPoint)dataEP).Port;
while (true) {
// handle any kind of error
if (((Opcodes)rcvBuffer[1]) == Opcodes.Error) {
fileStream.Close();
tftpSocket.Close();
throw new XFTPException(((rcvBuffer[2] << 8) & 0xff00) | rcvBuffer[3], Encoding.ASCII.GetString(rcvBuffer, 4, rcvBuffer.Length - 5).Trim('\0'));
}
// expect the next packet
if ((((rcvBuffer[2] << 8) & 0xff00) | rcvBuffer[3]) == packetNr) {
// Store to local file
fileStream.Write(rcvBuffer, 4, len - 4);
// Send Ack Packet to TFTP Server
sndBuffer = CreateAckPacket(packetNr++);
tftpSocket.SendTo(sndBuffer, sndBuffer.Length, SocketFlags.None, serverEP);
}
// Was ist the last packet ?
if (len < 516) {
break;
} else {
// Receive Next Data Packet From TFTP Server
len = tftpSocket.ReceiveFrom(rcvBuffer, ref dataEP);
}
}
// Close Socket and release resources
tftpSocket.Close();
fileStream.Close();
}
/// <summary>
/// Puts the specified remote file.
/// </summary>
/// <param name="remoteFile">The remote file.</param>
/// <param name="localFile">The local file.</param>
public void Put(string remoteFile, string localFile) {
Put(remoteFile, localFile, Modes.Octet);
}
/// <summary>
/// Puts the specified remote file.
/// </summary>
/// <param name="remoteFile">The remote file.</param>
/// <param name="localFile">The local file.</param>
/// <param name="tftpMode">The TFTP mode.</param>
/// <remarks>What if the ack does not come !</remarks>
public void Put(string remoteFile, string localFile, Modes tftpMode) {
int len = 0;
int packetNr = 0;
byte[] sndBuffer = CreateRequestPacket(Opcodes.Write, remoteFile, tftpMode);
byte[] rcvBuffer = new byte[516];
IPAddress ipa;
if ((ipa = stXFTPUtil.GetIPAddress(tftpServer)) == null)
{
throw new XFTPException(502, Properties.Resources.txtXFTPBadIpAddress);
}
BinaryReader fileStream = new BinaryReader(new FileStream(localFile,FileMode.Open,FileAccess.Read,FileShare.ReadWrite));
IPEndPoint serverEP = new IPEndPoint(ipa, tftpPort);
EndPoint dataEP = (EndPoint)serverEP;
Socket tftpSocket = new Socket(serverEP.Address.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
// Request Writing to TFTP Server
tftpSocket.SendTo(sndBuffer, sndBuffer.Length, SocketFlags.None, serverEP);
tftpSocket.ReceiveTimeout = 1000 ;
len = tftpSocket.ReceiveFrom(rcvBuffer, ref dataEP);
// keep track of the TID
serverEP.Port = ((IPEndPoint)dataEP).Port;
while (true) {
// handle any kind of error
if (((Opcodes)rcvBuffer[1]) == Opcodes.Error) {
fileStream.Close();
tftpSocket.Close();
throw new XFTPException(((rcvBuffer[2] << 8) & 0xff00) | rcvBuffer[3], Encoding.ASCII.GetString(rcvBuffer, 4, rcvBuffer.Length - 5).Trim('\0'));
}
// expect the next packet ack
if ((((Opcodes)rcvBuffer[1]) == Opcodes.Ack) && (((rcvBuffer[2] << 8) & 0xff00) | rcvBuffer[3]) == packetNr) {
sndBuffer = CreateDataPacket(++packetNr,fileStream.ReadBytes(512));
tftpSocket.SendTo(sndBuffer, sndBuffer.Length, SocketFlags.None, serverEP);
}
// we are done
if (sndBuffer.Length < 516) {
break;
} else {
len = tftpSocket.ReceiveFrom(rcvBuffer, ref dataEP);
}
}
// Close Socket and release resources
tftpSocket.Close();
fileStream.Close();
}
#endregion
#region -=[ Private Member ]=-
/// <summary>
/// Creates the request packet.
/// </summary>
/// <param name="opCode">The op code.</param>
/// <param name="remoteFile">The remote file.</param>
/// <param name="tftpMode">The TFTP mode.</param>
/// <returns>the ack packet</returns>
private byte[] CreateRequestPacket(Opcodes opCode, string remoteFile, Modes tftpMode) {
// Create new Byte array to hold Initial
// Read Request Packet
int pos = 0;
string modeAscii = tftpMode.ToString().ToLowerInvariant();
byte[] ret = new byte[modeAscii.Length + remoteFile.Length + 4];
// Set first Opcode of packet to indicate
// if this is a read request or write request
ret[pos++] = 0;
ret[pos++] = (byte)opCode;
// Convert Filename to a char array
pos += Encoding.ASCII.GetBytes(remoteFile, 0, remoteFile.Length, ret, pos);
ret[pos++] = 0;
pos += Encoding.ASCII.GetBytes(modeAscii, 0, modeAscii.Length, ret, pos);
ret[pos] = 0;
return ret;
}
/// <summary>
/// Creates the data packet.
/// </summary>
/// <param name="packetNr">The packet nr.</param>
/// <param name="data">The data.</param>
/// <returns>the data packet</returns>
private byte[] CreateDataPacket(int blockNr, byte[] data) {
// Create Byte array to hold ack packet
byte[] ret = new byte[4 + data.Length];
// Set first Opcode of packet to TFTP_ACK
ret[0] = 0;
ret[1] = (byte)Opcodes.Data;
ret[2] = (byte)((blockNr >> 8) & 0xff);
ret[3] = (byte)(blockNr & 0xff);
Array.Copy(data, 0, ret, 4, data.Length);
return ret;
}
/// <summary>
/// Creates the ack packet.
/// </summary>
/// <param name="blockNr">The block nr.</param>
/// <returns>the ack packet</returns>
private byte[] CreateAckPacket(int blockNr) {
// Create Byte array to hold ack packet
byte[] ret = new byte[4];
// Set first Opcode of packet to TFTP_ACK
ret[0] = 0;
ret[1] = (byte)Opcodes.Ack;
// Insert block number into packet array
ret[2] = (byte)((blockNr >> 8) & 0xff);
ret[3] = (byte)(blockNr & 0xff);
return ret;
}
#endregion
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace LowoUN.Module.Sound
{
public class Module_Sound : MonoBehaviour
{
private static Module_Sound _instance;
public static Module_Sound instance {
get {
if (_instance == null)
Debug.LogError ("====== LowoUN / Module / Sound ===> no sound module found!");
return _instance;
}
}
[SerializeField] private float _mainSfxVolume = 1.0f;
[SerializeField] private float _mainBgmVolume = 1.0f;
[SerializeField] private SoundSet setter_UI;
[SerializeField] private SoundSet setter_Evt;
[SerializeField] private SoundSetCollector setters_Act_Collector;
[SerializeField] private bool isBgmEnable = true;
[SerializeField] private bool isSfxEnable = true;
public float mainBgmVolume{get{return _mainBgmVolume;} private set{_mainBgmVolume = value;}}
//inclule evt and ui type
public float mainSfxVolume{get{return _mainSfxVolume;} private set{_mainSfxVolume = value;}}
private AudioSource bgmSource;
//private bool readyToPlayBgm = false;
//private bool readyToPlayAmb = false;
private bool isStopOrPlayCurBgm = false;
private float fadeVolume = 0.0f;
private float fadeInTime = 1.0f;
private float fadeOutTime = 1.0f;
private Transform listener;
private Transform followThing = null;
private string curBgmName = "";
private bool hasInit = false;
void Awake() {
_instance = this;
}
void Start () {
Init ();
}
void OnApplicationQuit () {
DestroyImmediate(listener.gameObject);
}
void OnDestroy() {
_instance = null;
hasInit = false;
evts.Clear();
}
private void Init () {
if(!hasInit) {
hasInit = true;
listener = new GameObject("Listener").transform;
listener.parent = transform;
listener.gameObject.AddComponent<AudioListener>();
bgmSource = listener.gameObject.AddComponent<AudioSource>();
bgmSource.spatialBlend = 0.0f;
bgmSource.volume = fadeVolume * mainBgmVolume;
}
}
public void Reset() {
evts.Clear();
}
//0, public settings --------------------------------------------------
public void SetBgmVolume(float volume) {
mainBgmVolume = volume;
}
public void SetSfxVolume(float volume) {
mainSfxVolume = volume;
}
private void ToggleBgm() {
isBgmEnable = !isBgmEnable;
if(!isBgmEnable)
StopBgm();
}
public void ToggleSfx () {
isSfxEnable = !isSfxEnable;
if(!isSfxEnable) {
StopEvts();
}
}
//1, bgm ----------------------------------------------------------------
public void PlayBgm(string bgmBundleName,bool loop = true, float fadeInTime = 1f) {
if(!isBgmEnable) return;
if (curBgmName == bgmBundleName) return;
curBgmName = bgmBundleName;
float fIn = 1.0f / fadeInTime;
isStopOrPlayCurBgm = false;//bgmSource.isPlaying;
StartCoroutine(LoadAndPlayBgm(curBgmName, loop, fIn));
}
public void StopBgm() {
curBgmName = "";
if (bgmSource.isPlaying)
isStopOrPlayCurBgm = true;
}
private IEnumerator LoadAndPlayBgm(string bundleName, bool loop, float fadeInTime) {
yield return null;
Debug.Log("====== LowoUN / Module / Sound ===> play " + bundleName);
if (bgmSource.clip != null) {
Resources.UnloadAsset(bgmSource.clip);
bgmSource.clip = null;
}
bgmSource.clip = Resources.Load(bundleName) as AudioClip;
this.fadeInTime = fadeInTime;
bgmSource.loop = loop;
bgmSource.Play();
}
//2, sfx ------------------------------------------------------------------
private List<AudioSource> evts = new List<AudioSource>();
public void PlayEvt(string groupName, bool loop = false, float fadeTime = 0.5f, GameObject go = null) {
if(!isSfxEnable) return;
if (setter_Evt != null) {
AudioSource s = setter_Evt.Play(groupName, go??gameObject);
s.spatialBlend = 0.0f;
setter_Evt.PlayOneShot (s, mainSfxVolume);
evts.Add(s);
}
}
public void PlayAct(string soundID, string evtName, GameObject go, bool loop = false, float fadeTime = 0.5f) {
if(!isSfxEnable) return;
SoundSet setter_act = SoundSetCollector.instance.GetSoundSet ("sfx_" + soundID);
if(setter_act != null){
AudioSource s = setter_act.Play(evtName, gameObject);
s.spatialBlend = 0.0f;
s.volume = mainSfxVolume;
}
}
public void StopEvts() {
if(evts.Count > 0) {
foreach (var item in evts) {
StopEvt(item);
}
}
evts.Clear();
}
public void StopEvt(AudioSource s, float fadeOutTime = 0.5f) {
if (setter_Evt != null)
setter_Evt.Stop(s, fadeOutTime);
}
//3, ui ----------------------------------------------------------------
public void PlayUI(string groupName, bool isLoop = false) {
if(!isSfxEnable) return;
if (setter_UI != null) {
if(isLoop) {
setter_UI.PlayLoop (groupName, gameObject);
}
else {
AudioSource a = setter_UI.Play(groupName, gameObject);
setter_UI.PlayOneShot (a, 1f);
}
}
}
private void CheckListenerToFollowSth () {
if (followThing) {
listener.position = followThing.position;
listener.rotation = followThing.rotation;
}
else {
//need set one camera with the tag "MainCamera"
if (Camera.main != null){
followThing = Camera.main.transform;
}
else {
#if UNITY_EDITOR
Debug.LogWarning ("=== LowoUN / Module / Sound => No main camera found!");
#endif
}
}
}
private void Fade4Bgm () {
if (bgmSource.isPlaying) {
if (isStopOrPlayCurBgm) {
if (fadeVolume > 0f) {
fadeVolume -= Time.deltaTime * fadeOutTime;
if (fadeVolume < 0f) {
fadeVolume = 0f;
bgmSource.Stop ();
isStopOrPlayCurBgm = false;
}
}
}
else {
if (fadeVolume < 1f) {
fadeVolume += Time.deltaTime * fadeInTime;
if (fadeVolume > 1f)
fadeVolume = 1f;
}
}
bgmSource.volume = fadeVolume * mainBgmVolume;
}
}
// Update is called once per frame
void Update () {
CheckListenerToFollowSth ();
Fade4Bgm ();
}
//TEMP audio fade out
public void PlayFadeAudio(AudioSource source, bool In, float time) {
StartCoroutine(FadeAudioSource(source, In, time));
}
IEnumerator FadeAudioSource(AudioSource source, bool In, float time) {
float origVolume = source.volume;
float precent = 0.0f;
if (In) source.volume = 0.0f;
while (precent < 1.0f) {
precent += Time.deltaTime * (1.0f / time);
if (source == null) yield break;
source.volume = origVolume * (In ? precent : (1.0f - precent));
yield return null;
}
}
}
}
| |
/* $Id$
*
* Project: Swicli.Library - Two Way Interface for .NET and MONO to SWI-Prolog
* Author: Douglas R. Miles
* E-mail: [email protected]
* WWW: http://www.logicmoo.com
* Copyright (C): 2010-2012 LogicMOO Developement
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*********************************************************/
#if USE_IKVM
using IKVM.Internal;
using ikvm.runtime;
using java.net;
//using jpl;
using Hashtable = java.util.Hashtable;
using ClassLoader = java.lang.ClassLoader;
using Class = java.lang.Class;
using sun.reflect.misc;
#endif
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using SbsSW.SwiPlCs;
using SbsSW.SwiPlCs.Callback;
using SbsSW.SwiPlCs.Exceptions;
using PlTerm = SbsSW.SwiPlCs.PlTerm;
namespace Swicli.Library
{
public partial class PrologCLR
{
static public bool ClientReady = false;
static private object _threadRegLock = new object();
static public object ThreadRegLock
{
get
{
return LockInfo.Watch(_threadRegLock);
}
}
public static bool SaneThreadWorld = true;
public static Dictionary<Thread, int> ThreadRegisterations = new Dictionary<Thread, int>();
public static Dictionary<Thread, int> ForiegnFrameCounts = new Dictionary<Thread, int>();
internal static int IncrementUseCount(Thread thread)
{
return IncrementUseCount(thread, ThreadRegisterations);
}
internal static int DecrementUseCount(Thread thread)
{
return DecrementUseCount(thread, ThreadRegisterations);
}
internal static int IncrementUseCount(Thread thread, Dictionary<Thread, int> registration)
{
lock (ThreadRegLock)
{
int regs = 0;
if (!registration.TryGetValue(thread, out regs))
{
registration[thread] = 1;
}
else
{
registration[thread] = regs + 1;
}
return regs + 1;
}
}
internal static int DecrementUseCount(Thread thread, Dictionary<Thread, int> registration)
{
lock (ThreadRegLock)
{
int regs = 0;
if (!registration.TryGetValue(thread, out regs))
{
registration[thread] = 0;
}
else
{
registration[thread] = regs - 1;
}
return regs - 1;
}
}
public static Dictionary<int, IntPtr> SafeThreads = new Dictionary<int, IntPtr>();
public static Dictionary<int, Thread> engineToThread = new Dictionary<int, Thread>();
public static Dictionary<int, int> threadToEngine = new Dictionary<int, int>();
public static Dictionary<int, PlMtEngine> ThreadEngines = new Dictionary<int, PlMtEngine>();
public static List<IntPtr> FreeEngines = new List<IntPtr>();
public static bool UseEnginePool = true;
public static void RegisterMainThread()
{
PingThreadFactories();
lock (ThreadRegLock)
{
var fa = Type.GetType("System.Windows.Forms.Application");
if (fa != null)
{
var evinfo = fa.GetEvent("ThreadExit");
if (evinfo != null)
{
evinfo.AddEventHandler(null, new EventHandler(OnThreadExit));
}
} else
{
Embedded.Debug("Not installing ThreadExit hook to System.Windows.Forms.Application");
}
var t = Thread.CurrentThread.ManagedThreadId;
//libpl.PL_thread_at_exit((DelegateParameter0)PrologThreadAtExitGlobal, IntPtr.Zero, 1);
// SafeThreads.Add(t, new IntPtr(libpl.PL_ENGINE_MAIN));
// int self = libpl.PL_thread_self();
// engineToThread.Add(self, t);
}
}
public static bool NoTestThreadFActory = true;
public static void PingThreadFactories()
{
try
{
if (NoTestThreadFActory) return;
Assembly assem = AssemblyLoad("MushDLR223");
if (assem != null)
{
Type type = assem.GetType("MushDLR223.Utilities.SafeThread");
if (type != null)
{
NoTestThreadFActory = true;
type.GetEvent("ThreadAdded").GetAddMethod().Invoke(null,
new[] { new Action<Thread>(RegisterThread) });
type.GetEvent("ThreadRemoved").GetAddMethod().Invoke(null,
new[] { new Action<Thread>(DeregisterThread) });
}
}
}
catch (Exception)
{
}
}
private static void OnThreadExit(object sender, EventArgs e)
{
}
public static void RegisterCurrentThread()
{
RegisterThread(Thread.CurrentThread);
}
public static bool OneToOneEnginesPeThread = true;
public static void RegisterThread(Thread thread)
{
//if (thread == CreatorThread) return;
if (OneToOneEnginesPeThread)
{
// leaks!
RegisterThread121(thread);
}
else
{
RegisterThread12Many(thread);
}
}
static readonly IntPtr PL_ENGINE_CURRENT_PTR = new IntPtr(libpl.PL_ENGINE_CURRENT); // ((PL_engine_t)0x2)
public static void RegisterThread121(Thread thread)
{
try
{
IntPtr ce = GetCurrentEngine();
if (ce == IntPtr.Zero)
{
RegisterThread121A(thread);
//ce = GetCurrentEngine();
} else
{
}
TestEngineViable(ce);
} catch(Exception e)
{
RegisterThread121A(thread);
}
}
private static void TestEngineViable(IntPtr ce)
{
//PlQuery.PlCall(
}
public static void RegisterThread121A(Thread thread)
{
if (thread == CreatorThread)
{
return;
}
lock (ThreadRegLock)
{
IncrementUseCount(thread);
int count;
if (ForiegnFrameCounts.TryGetValue(thread, out count))
{
// if (count > 1) return;
}
lock (ThreadRegLock) unregisteredThreads.Remove(thread);
IntPtr _iEngineNumber;
IntPtr _iEngineNumberReally = IntPtr.Zero;
lock (SafeThreads) if (SafeThreads.TryGetValue(thread.ManagedThreadId, out _iEngineNumber)) return;
if (0 != libpl.PL_is_initialised(IntPtr.Zero, IntPtr.Zero))
{
try
{
//_iEngineNumber = libpl.PL_create_engine(IntPtr.Zero);
var self = libpl.PL_thread_attach_engine(_iEngineNumber);
var ce = GetCurrentEngine();
lock (SafeThreads) SafeThreads.Add(thread.ManagedThreadId, ce);
threadToEngine.Add(thread.ManagedThreadId, self);
libpl.PL_thread_at_exit((DelegateParameter0)PrologThreadAtExit, IntPtr.Zero, 0);
return;
int iRet = libpl.PL_set_engine(_iEngineNumber, ref _iEngineNumberReally);
EnsureEngine(_iEngineNumber);
}
catch (Exception ex)
{
throw (new PlException("PL_create_engine : " + ex.Message));
}
} else
{
string[] local_argv = new string[] { "-q" };
if (0 == libpl.PL_initialise(local_argv.Length, local_argv))
throw new PlLibException("failed to initialize");
RegisterThread121A(thread);
}
}
}
private static bool PrologThreadAtExit()
{
//throw new NotImplementedException();
return true;
}
private static bool PrologThreadAtExitGlobal()
{
//throw new NotImplementedException();
return true;
}
static IntPtr GetCurrentEngine()
{
IntPtr _iEngineNumberReallyCurrent = IntPtr.Zero;
int iRet2 = libpl.PL_set_engine(PL_ENGINE_CURRENT_PTR, ref _iEngineNumberReallyCurrent);
if (iRet2 == libpl.PL_ENGINE_INVAL)
{
return IntPtr.Zero;
}
CheckIRet(iRet2);
return _iEngineNumberReallyCurrent;
}
private static void EnsureEngine(IntPtr _iEngineNumber)
{
IntPtr _iEngineNumberReallyCurrent = IntPtr.Zero;
int iRet2 = libpl.PL_set_engine(PL_ENGINE_CURRENT_PTR, ref _iEngineNumberReallyCurrent);
CheckIRet(iRet2);
if (_iEngineNumber == _iEngineNumberReallyCurrent)
{
return;
}
int iRet = libpl.PL_set_engine(_iEngineNumber, ref _iEngineNumberReallyCurrent);
if (libpl.PL_ENGINE_SET == iRet)
{
EnsureEngine(_iEngineNumber);
return;
}
CheckIRet(iRet);
}
private static void CheckIRet(int iRet)
{
switch (iRet)
{
case libpl.PL_ENGINE_SET:
{
break; // all is fine!
}
case libpl.PL_ENGINE_INVAL:
throw (new PlLibException("PlSetEngine returns Invalid")); //break;
case libpl.PL_ENGINE_INUSE:
throw (new PlLibException("PlSetEngine returns it is used by an other thread")); //break;
default:
throw (new PlLibException("Unknown return from PlSetEngine = " + iRet));
}
}
public static void RegisterThread121T(Thread thread)
{
if (thread == CreatorThread) return;
lock (ThreadRegLock)
{
lock (ThreadRegLock) unregisteredThreads.Remove(thread);
int oldSelf;
bool threadHasSelf = threadToEngine.TryGetValue(thread.ManagedThreadId, out oldSelf);
if (!threadHasSelf)
{
//if (thread == CreatorThread) return;
IncrementUseCount(thread);
threadToEngine[thread.ManagedThreadId] = libpl.PL_thread_attach_engine(IntPtr.Zero);
}
IntPtr _iEngineNumber = IntPtr.Zero;
int iRet = libpl.PL_set_engine(PL_ENGINE_CURRENT_PTR, ref _iEngineNumber);
if (libpl.PL_ENGINE_SET == iRet) return;
CheckIRet(iRet);
}
}
public static void RegisterThread121Leak(Thread thread)
{
lock (ThreadRegLock)
{
IncrementUseCount(thread);
lock (ThreadRegLock) unregisteredThreads.Remove(thread);
int self = libpl.PL_thread_self();
int oldSelf;
Thread otherThread;
bool plthreadHasThread = engineToThread.TryGetValue(self, out otherThread);
bool threadHasSelf = threadToEngine.TryGetValue(thread.ManagedThreadId, out oldSelf);
bool plThreadHasDifferntThread = false;
GCHandle.Alloc(thread, GCHandleType.Normal);
if (plthreadHasThread)
{
plThreadHasDifferntThread = otherThread != thread;
}
if (threadHasSelf)
{
if (self < 1)
{
Embedded.Debug("self < 1: {0}", thread);
return; //maybe mnot fine
}
if (plThreadHasDifferntThread)
{
Embedded.Debug("plThreadHasDifferntThread {0}", thread);
return; //maybe mnot fine
}
if (thread == CreatorThread) return;
int ret0 = libpl.PL_thread_attach_engine(IntPtr.Zero);
//int iRet = CheckEngine();
return; // all was fine;
}
// thread never had engine
int ret = libpl.PL_thread_attach_engine(IntPtr.Zero);
int self0 = libpl.PL_thread_self();
engineToThread[self0] = thread;
threadToEngine[thread.ManagedThreadId] = self0;
RegisterThread121Leak(thread);
return;
}
}
/// <summary>
/// FIX ME!!
/// </summary>
/// <param name="thread"></param>
public static void RegisterThread12Many(Thread thread)
{
lock (ThreadRegLock)
{
IncrementUseCount(thread);
lock (ThreadRegLock) unregisteredThreads.Remove(thread);
PlMtEngine oldSelf;
if (ThreadEngines.TryGetValue(thread.ManagedThreadId, out oldSelf))
{
oldSelf.PlSetEngine();
return;
}
try
{
//var _iEngineNumber = libpl.PL_create_engine(IntPtr.Zero);
oldSelf = new PlMtEngine();
oldSelf.PlSetEngine();
ThreadEngines.Add(thread.ManagedThreadId, oldSelf);
}
catch (Exception)
{
throw;
}
}
}
public static void RegisterThreadOrig(Thread thread)
{
lock (ThreadRegLock)
{
int regs;
if (!ThreadRegisterations.TryGetValue(thread, out regs))
{
ThreadRegisterations[thread] = 1;
}
else
{
ThreadRegisterations[thread] = regs + 1;
}
lock (unregisteredThreads) unregisteredThreads.Remove(thread);
int self = libpl.PL_thread_self();
IntPtr _iEngineNumber;
IntPtr _oiEngineNumber;
Thread otherThread;
bool threadOnceHadEngine = SafeThreads.TryGetValue(thread.ManagedThreadId, out _iEngineNumber);
bool plthreadHasThread = engineToThread.TryGetValue(self, out otherThread);
bool plThreadHasDifferntThread = false;
GCHandle.Alloc(thread, GCHandleType.Normal);
if (plthreadHasThread)
{
plThreadHasDifferntThread = otherThread != thread;
}
if (self < 0 || threadOnceHadEngine)
{
if (self < 1)
{
Embedded.Debug("self < 1: {0}", thread);
return; //maybe mnot fine
}
if (plThreadHasDifferntThread)
{
Embedded.Debug("plThreadHasDifferntThread {0}", thread);
return; //maybe mnot fine
}
//return; // all was fine;
// if (thread == CreatorThread || true) return;
int iRet = CheckEngine();
return; // all was fine;
}
else
{
// thread never had engine
int ret = libpl.PL_thread_attach_engine(IntPtr.Zero);
int self0 = libpl.PL_thread_self();
if (ret == self0)
{
lock (SafeThreads) SafeThreads.Add(thread.ManagedThreadId, IntPtr.Zero);
engineToThread[self0] = thread;
//RegisterThread(thread);
return;
}
_iEngineNumber = GetFreeEngine();
lock (SafeThreads) SafeThreads.Add(thread.ManagedThreadId, _iEngineNumber);
int self2 = libpl.PL_thread_self();
if (self2 == -1)
{
if (libpl.PL_is_initialised(IntPtr.Zero, IntPtr.Zero) != 0)
{
try
{
ret = libpl.PL_thread_attach_engine(_iEngineNumber);
int self3 = libpl.PL_thread_self();
engineToThread.Add(self3, thread);
return;
}
catch (Exception ex)
{
throw (new PlException("PL_create_engine : " + ex.Message));
}
}
else
{
//int ret = libpl.PL_thread_attach_engine(_iEngineNumber);
IntPtr pNullPointer = IntPtr.Zero;
int iRet = libpl.PL_set_engine(_iEngineNumber, ref pNullPointer);
switch (iRet)
{
case libpl.PL_ENGINE_SET:
{
int self4 = libpl.PL_thread_self();
engineToThread.Add(self4, thread);
return; // all is fine!
}
case libpl.PL_ENGINE_INVAL: throw (new PlLibException("PlSetEngine returns Invalid")); //break;
case libpl.PL_ENGINE_INUSE: throw (new PlLibException("PlSetEngine returns it is used by an other thread")); //break;
default: throw (new PlLibException("Unknown return from PlSetEngine"));
}
int self3 = libpl.PL_thread_self();
engineToThread.Add(self3, thread);
}
return;
}
engineToThread.Add(self2, thread);
}
/*
//
if (self != ret)
{
engineToThread[ret] = thread;
}
if (engineToThread.TryGetValue(self, out otherThread))
{
// All good!
if (otherThread == thread)
return;
bool othreadOnceHadEngine = SafeThreads.TryGetValue(otherThread, out _oiEngineNumber);
int ret = libpl.PL_thread_attach_engine(_iEngineNumber);
if (self != ret)
{
engineToThread[ret] = thread;
//what does this mean?
SafeThreads.TryGetValue(thread, out _iEngineNumber);
}
}
libpl.PL_set_engine(libpl.PL_ENGINE_CURRENT, ref oldEngine);
if (!OneToOneEnginesPeThread)
{
}
SafeThreads.Add(thread, _iEngineNumber);
*/
}
}
private static IntPtr GetFreeEngine()
{
lock (FreeEngines)
{
if (FreeEngines.Count > 0)
{
var fe = FreeEngines[0];
FreeEngines.RemoveAt(0);
return fe;
}
}
return libpl.PL_create_engine(IntPtr.Zero);
}
public static int CheckEngine()
{
IntPtr _iEngineNumber;
IntPtr pNullPointer = IntPtr.Zero;
int iRet = libpl.PL_set_engine(PL_ENGINE_CURRENT_PTR, ref pNullPointer);
if (libpl.PL_ENGINE_SET == iRet) return iRet;
switch (iRet)
{
case libpl.PL_ENGINE_SET:
{
break; // all is fine!
}
case libpl.PL_ENGINE_INVAL:
throw (new PlLibException("PlSetEngine returns Invalid")); //break;
case libpl.PL_ENGINE_INUSE:
throw (new PlLibException("PlSetEngine returns it is used by an other thread")); //break;
default:
throw (new PlLibException("Unknown return from PlSetEngine"));
}
return iRet;
}
static readonly List<Thread> unregisteredThreads = new List<Thread>();
public static void DeregisterThread(Thread thread)
{
lock (ThreadRegLock)
{
int regs = DecrementUseCount(thread);
if (regs == 0)
{
if (OneToOneEnginesPeThread)
{
// libpl.PL_thread_destroy_engine();
}
else
{
}
//ExitThread(thread);
}
}
}
public static void ExitThread(Thread thread)
{
lock (ThreadRegLock)
{
int self = libpl.PL_thread_self();
IntPtr _iEngineNumber;
lock (SafeThreads) if (!SafeThreads.TryGetValue(thread.ManagedThreadId, out _iEngineNumber))
{
return;
}
// if (_iEngineNumber == IntPtr.Zero) return;
lock (SafeThreads) SafeThreads.Remove(thread.ManagedThreadId);
var rnull = IntPtr.Zero;
if (libpl.PL_set_engine(IntPtr.Zero, ref rnull) != 0)
{
lock (FreeEngines)
{
if (_iEngineNumber != IntPtr.Zero) FreeEngines.Add(_iEngineNumber);
}
return;
}
if (libpl.PL_destroy_engine(_iEngineNumber) != 0)
{
try
{
_iEngineNumber = libpl.PL_create_engine(IntPtr.Zero);
lock (FreeEngines)
{
FreeEngines.Add(_iEngineNumber);
}
}
catch (Exception ex)
{
throw (new PlException("PL_create_engine : " + ex.Message));
}
}
}
}
public static void KillPrologThreads()
{
lock (ThreadRegLock)
{
lock (SafeThreads) foreach (KeyValuePair<int, IntPtr> engine in SafeThreads)
{
IntPtr ptr = engine.Value;
if (ptr.ToInt64() > PL_ENGINE_CURRENT_PTR.ToInt64())
{
libpl.PL_destroy_engine(ptr);
}
}
}
throw new NotImplementedException("KillPrologThreads");
}
}
}
| |
/*
* Simulator.cs
* RVO2 Library C#
*
* Copyright 2008 University of North Carolina at Chapel Hill
*
* 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.
*
* Please send all bug reports to <[email protected]>.
*
* The authors may be contacted via:
*
* Jur van den Berg, Stephen J. Guy, Jamie Snape, Ming C. Lin, Dinesh Manocha
* Dept. of Computer Science
* 201 S. Columbia St.
* Frederick P. Brooks, Jr. Computer Science Bldg.
* Chapel Hill, N.C. 27599-3175
* United States of America
*
* <http://gamma.cs.unc.edu/RVO2/>
*/
using System;
using System.Collections.Generic;
using System.Threading;
namespace RVO
{
/**
* <summary>Defines the simulation.</summary>
*/
public class Simulator
{
/**
* <summary>Defines a worker.</summary>
*/
private class Worker
{
private ManualResetEvent doneEvent_;
private int end_;
private int start_;
/**
* <summary>Constructs and initializes a worker.</summary>
*
* <param name="start">Start.</param>
* <param name="end">End.</param>
* <param name="doneEvent">Done event.</param>
*/
internal Worker(int start, int end, ManualResetEvent doneEvent)
{
start_ = start;
end_ = end;
doneEvent_ = doneEvent;
}
/**
* <summary>Performs a simulation step.</summary>
*
* <param name="obj">Unused.</param>
*/
internal void step(object obj)
{
for (int agentNo = start_; agentNo < end_; ++agentNo)
{
Simulator.Instance.agents_[agentNo].computeNeighbors();
Simulator.Instance.agents_[agentNo].computeNewVelocity();
}
doneEvent_.Set();
}
/**
* <summary>updates the two-dimensional position and
* two-dimensional velocity of each agent.</summary>
*
* <param name="obj">Unused.</param>
*/
internal void update(object obj)
{
for (int agentNo = start_; agentNo < end_; ++agentNo)
{
Simulator.Instance.agents_[agentNo].update();
}
doneEvent_.Set();
}
}
internal IList<Agent> agents_;
internal IList<Obstacle> obstacles_;
internal KdTree kdTree_;
internal float timeStep_;
private static Simulator instance_ = new Simulator();
private Agent defaultAgent_;
private ManualResetEvent[] doneEvents_;
private Worker[] workers_;
private int numWorkers_;
private float globalTime_;
public static Simulator Instance
{
get
{
return instance_;
}
}
/**
* <summary>Adds a new agent with default properties to the simulation.
* </summary>
*
* <returns>The number of the agent, or -1 when the agent defaults have
* not been set.</returns>
*
* <param name="position">The two-dimensional starting position of this
* agent.</param>
*/
public int addAgent(Vector2 position)
{
if (defaultAgent_ == null)
{
return -1;
}
Agent agent = new Agent();
agent.sim_ = this;
agent.id_ = agents_.Count;
agent.maxNeighbors_ = defaultAgent_.maxNeighbors_;
agent.maxSpeed_ = defaultAgent_.maxSpeed_;
agent.neighborDist_ = defaultAgent_.neighborDist_;
agent.position_ = position;
agent.radius_ = defaultAgent_.radius_;
agent.timeHorizon_ = defaultAgent_.timeHorizon_;
agent.timeHorizonObst_ = defaultAgent_.timeHorizonObst_;
agent.velocity_ = defaultAgent_.velocity_;
agents_.Add(agent);
return agent.id_;
}
/**
* <summary>Adds a new agent to the simulation.</summary>
*
* <returns>The number of the agent.</returns>
*
* <param name="position">The two-dimensional starting position of this
* agent.</param>
* <param name="neighborDist">The maximum distance (center point to
* center point) to other agents this agent takes into account in the
* navigation. The larger this number, the longer the running time of
* the simulation. If the number is too low, the simulation will not be
* safe. Must be non-negative.</param>
* <param name="maxNeighbors">The maximum number of other agents this
* agent takes into account in the navigation. The larger this number,
* the longer the running time of the simulation. If the number is too
* low, the simulation will not be safe.</param>
* <param name="timeHorizon">The minimal amount of time for which this
* agent's velocities that are computed by the simulation are safe with
* respect to other agents. The larger this number, the sooner this
* agent will respond to the presence of other agents, but the less
* freedom this agent has in choosing its velocities. Must be positive.
* </param>
* <param name="timeHorizonObst">The minimal amount of time for which
* this agent's velocities that are computed by the simulation are safe
* with respect to obstacles. The larger this number, the sooner this
* agent will respond to the presence of obstacles, but the less freedom
* this agent has in choosing its velocities. Must be positive.</param>
* <param name="radius">The radius of this agent. Must be non-negative.
* </param>
* <param name="maxSpeed">The maximum speed of this agent. Must be
* non-negative.</param>
* <param name="velocity">The initial two-dimensional linear velocity of
* this agent.</param>
*/
public int addAgent(Vector2 position, float neighborDist, int maxNeighbors, float timeHorizon, float timeHorizonObst, float radius, float maxSpeed, Vector2 velocity)
{
Agent agent = new Agent();
agent.id_ = agents_.Count;
agent.maxNeighbors_ = maxNeighbors;
agent.maxSpeed_ = maxSpeed;
agent.neighborDist_ = neighborDist;
agent.position_ = position;
agent.radius_ = radius;
agent.timeHorizon_ = timeHorizon;
agent.timeHorizonObst_ = timeHorizonObst;
agent.velocity_ = velocity;
agents_.Add(agent);
return agent.id_;
}
/**
* <summary>Adds a new obstacle to the simulation.</summary>
*
* <returns>The number of the first vertex of the obstacle, or -1 when
* the number of vertices is less than two.</returns>
*
* <param name="vertices">List of the vertices of the polygonal obstacle
* in counterclockwise order.</param>
*
* <remarks>To add a "negative" obstacle, e.g. a bounding polygon around
* the environment, the vertices should be listed in clockwise order.
* </remarks>
*/
public int addObstacle(IList<Vector2> vertices)
{
if (vertices.Count < 2)
{
return -1;
}
int obstacleNo = obstacles_.Count;
for (int i = 0; i < vertices.Count; ++i)
{
Obstacle obstacle = new Obstacle();
obstacle.point_ = vertices[i];
if (i != 0)
{
obstacle.previous_ = obstacles_[obstacles_.Count - 1];
obstacle.previous_.next_ = obstacle;
}
if (i == vertices.Count - 1)
{
obstacle.next_ = obstacles_[obstacleNo];
obstacle.next_.previous_ = obstacle;
}
obstacle.direction_ = RVOMath.normalize(vertices[(i == vertices.Count - 1 ? 0 : i + 1)] - vertices[i]);
if (vertices.Count == 2)
{
obstacle.convex_ = true;
}
else
{
obstacle.convex_ = (RVOMath.leftOf(vertices[(i == 0 ? vertices.Count - 1 : i - 1)], vertices[i], vertices[(i == vertices.Count - 1 ? 0 : i + 1)]) >= 0.0f);
}
obstacle.id_ = obstacles_.Count;
obstacles_.Add(obstacle);
}
return obstacleNo;
}
/**
* <summary>Clears the simulation.</summary>
*/
public void Clear()
{
agents_ = new List<Agent>();
defaultAgent_ = null;
kdTree_ = new KdTree();
obstacles_ = new List<Obstacle>();
globalTime_ = 0.0f;
timeStep_ = 0.1f;
SetNumWorkers(0);
}
/**
* <summary>Performs a simulation step and updates the two-dimensional
* position and two-dimensional velocity of each agent.</summary>
*
* <returns>The global time after the simulation step.</returns>
*/
public float doStepST() {
kdTree_.buildAgentTree(this);
int numAgents = getNumAgents();
for (int i = 0; i < numAgents; ++i) {
agents_[i].computeNeighbors();
agents_[i].computeNewVelocity();
}
for (int i = 0; i < numAgents; ++i) {
agents_[i].update();
}
globalTime_ += timeStep_;
return globalTime_;
}
public float doStep()
{
if (workers_ == null)
{
workers_ = new Worker[numWorkers_];
doneEvents_ = new ManualResetEvent[workers_.Length];
for (int block = 0; block < workers_.Length; ++block)
{
doneEvents_[block] = new ManualResetEvent(false);
workers_[block] = new Worker(block * getNumAgents() / workers_.Length, (block + 1) * getNumAgents() / workers_.Length, doneEvents_[block]);
}
}
kdTree_.buildAgentTree(this);
for (int block = 0; block < workers_.Length; ++block)
{
doneEvents_[block].Reset();
ThreadPool.QueueUserWorkItem(workers_[block].step);
}
WaitHandle.WaitAll(doneEvents_);
for (int block = 0; block < workers_.Length; ++block)
{
doneEvents_[block].Reset();
ThreadPool.QueueUserWorkItem(workers_[block].update);
}
WaitHandle.WaitAll(doneEvents_);
globalTime_ += timeStep_;
return globalTime_;
}
/**
* <summary>Returns the specified agent neighbor of the specified agent.
* </summary>
*
* <returns>The number of the neighboring agent.</returns>
*
* <param name="agentNo">The number of the agent whose agent neighbor is
* to be retrieved.</param>
* <param name="neighborNo">The number of the agent neighbor to be
* retrieved.</param>
*/
public int getAgentAgentNeighbor(int agentNo, int neighborNo)
{
return agents_[agentNo].agentNeighbors_[neighborNo].Value.id_;
}
/**
* <summary>Returns the maximum neighbor count of a specified agent.
* </summary>
*
* <returns>The present maximum neighbor count of the agent.</returns>
*
* <param name="agentNo">The number of the agent whose maximum neighbor
* count is to be retrieved.</param>
*/
public int getAgentMaxNeighbors(int agentNo)
{
return agents_[agentNo].maxNeighbors_;
}
/**
* <summary>Returns the maximum speed of a specified agent.</summary>
*
* <returns>The present maximum speed of the agent.</returns>
*
* <param name="agentNo">The number of the agent whose maximum speed is
* to be retrieved.</param>
*/
public float getAgentMaxSpeed(int agentNo)
{
return agents_[agentNo].maxSpeed_;
}
/**
* <summary>Returns the maximum neighbor distance of a specified agent.
* </summary>
*
* <returns>The present maximum neighbor distance of the agent.
* </returns>
*
* <param name="agentNo">The number of the agent whose maximum neighbor
* distance is to be retrieved.</param>
*/
public float getAgentNeighborDist(int agentNo)
{
return agents_[agentNo].neighborDist_;
}
/**
* <summary>Returns the count of agent neighbors taken into account to
* compute the current velocity for the specified agent.</summary>
*
* <returns>The count of agent neighbors taken into account to compute
* the current velocity for the specified agent.</returns>
*
* <param name="agentNo">The number of the agent whose count of agent
* neighbors is to be retrieved.</param>
*/
public int getAgentNumAgentNeighbors(int agentNo)
{
return agents_[agentNo].agentNeighbors_.Count;
}
/**
* <summary>Returns the count of obstacle neighbors taken into account
* to compute the current velocity for the specified agent.</summary>
*
* <returns>The count of obstacle neighbors taken into account to
* compute the current velocity for the specified agent.</returns>
*
* <param name="agentNo">The number of the agent whose count of obstacle
* neighbors is to be retrieved.</param>
*/
public int getAgentNumObstacleNeighbors(int agentNo)
{
return agents_[agentNo].obstacleNeighbors_.Count;
}
/**
* <summary>Returns the specified obstacle neighbor of the specified
* agent.</summary>
*
* <returns>The number of the first vertex of the neighboring obstacle
* edge.</returns>
*
* <param name="agentNo">The number of the agent whose obstacle neighbor
* is to be retrieved.</param>
* <param name="neighborNo">The number of the obstacle neighbor to be
* retrieved.</param>
*/
public int getAgentObstacleNeighbor(int agentNo, int neighborNo)
{
return agents_[agentNo].obstacleNeighbors_[neighborNo].Value.id_;
}
/**
* <summary>Returns the ORCA constraints of the specified agent.
* </summary>
*
* <returns>A list of lines representing the ORCA constraints.</returns>
*
* <param name="agentNo">The number of the agent whose ORCA constraints
* are to be retrieved.</param>
*
* <remarks>The halfplane to the left of each line is the region of
* permissible velocities with respect to that ORCA constraint.
* </remarks>
*/
public IList<Line> getAgentOrcaLines(int agentNo)
{
return agents_[agentNo].orcaLines_;
}
/**
* <summary>Returns the two-dimensional position of a specified agent.
* </summary>
*
* <returns>The present two-dimensional position of the (center of the)
* agent.</returns>
*
* <param name="agentNo">The number of the agent whose two-dimensional
* position is to be retrieved.</param>
*/
public Vector2 getAgentPosition(int agentNo)
{
return agents_[agentNo].position_;
}
/**
* <summary>Returns the two-dimensional preferred velocity of a
* specified agent.</summary>
*
* <returns>The present two-dimensional preferred velocity of the agent.
* </returns>
*
* <param name="agentNo">The number of the agent whose two-dimensional
* preferred velocity is to be retrieved.</param>
*/
public Vector2 getAgentPrefVelocity(int agentNo)
{
return agents_[agentNo].prefVelocity_;
}
/**
* <summary>Returns the radius of a specified agent.</summary>
*
* <returns>The present radius of the agent.</returns>
*
* <param name="agentNo">The number of the agent whose radius is to be
* retrieved.</param>
*/
public float getAgentRadius(int agentNo)
{
return agents_[agentNo].radius_;
}
/**
* <summary>Returns the time horizon of a specified agent.</summary>
*
* <returns>The present time horizon of the agent.</returns>
*
* <param name="agentNo">The number of the agent whose time horizon is
* to be retrieved.</param>
*/
public float getAgentTimeHorizon(int agentNo)
{
return agents_[agentNo].timeHorizon_;
}
/**
* <summary>Returns the time horizon with respect to obstacles of a
* specified agent.</summary>
*
* <returns>The present time horizon with respect to obstacles of the
* agent.</returns>
*
* <param name="agentNo">The number of the agent whose time horizon with
* respect to obstacles is to be retrieved.</param>
*/
public float getAgentTimeHorizonObst(int agentNo)
{
return agents_[agentNo].timeHorizonObst_;
}
/**
* <summary>Returns the two-dimensional linear velocity of a specified
* agent.</summary>
*
* <returns>The present two-dimensional linear velocity of the agent.
* </returns>
*
* <param name="agentNo">The number of the agent whose two-dimensional
* linear velocity is to be retrieved.</param>
*/
public Vector2 getAgentVelocity(int agentNo)
{
return agents_[agentNo].velocity_;
}
/**
* <summary>Returns the global time of the simulation.</summary>
*
* <returns>The present global time of the simulation (zero initially).
* </returns>
*/
public float getGlobalTime()
{
return globalTime_;
}
/**
* <summary>Returns the count of agents in the simulation.</summary>
*
* <returns>The count of agents in the simulation.</returns>
*/
public int getNumAgents()
{
return agents_.Count;
}
/**
* <summary>Returns the count of obstacle vertices in the simulation.
* </summary>
*
* <returns>The count of obstacle vertices in the simulation.</returns>
*/
public int getNumObstacleVertices()
{
return obstacles_.Count;
}
/**
* <summary>Returns the count of workers.</summary>
*
* <returns>The count of workers.</returns>
*/
public int GetNumWorkers()
{
return numWorkers_;
}
/**
* <summary>Returns the two-dimensional position of a specified obstacle
* vertex.</summary>
*
* <returns>The two-dimensional position of the specified obstacle
* vertex.</returns>
*
* <param name="vertexNo">The number of the obstacle vertex to be
* retrieved.</param>
*/
public Vector2 getObstacleVertex(int vertexNo)
{
return obstacles_[vertexNo].point_;
}
/**
* <summary>Returns the number of the obstacle vertex succeeding the
* specified obstacle vertex in its polygon.</summary>
*
* <returns>The number of the obstacle vertex succeeding the specified
* obstacle vertex in its polygon.</returns>
*
* <param name="vertexNo">The number of the obstacle vertex whose
* successor is to be retrieved.</param>
*/
public int getNextObstacleVertexNo(int vertexNo)
{
return obstacles_[vertexNo].next_.id_;
}
/**
* <summary>Returns the number of the obstacle vertex preceding the
* specified obstacle vertex in its polygon.</summary>
*
* <returns>The number of the obstacle vertex preceding the specified
* obstacle vertex in its polygon.</returns>
*
* <param name="vertexNo">The number of the obstacle vertex whose
* predecessor is to be retrieved.</param>
*/
public int getPrevObstacleVertexNo(int vertexNo)
{
return obstacles_[vertexNo].previous_.id_;
}
/**
* <summary>Returns the time step of the simulation.</summary>
*
* <returns>The present time step of the simulation.</returns>
*/
public float getTimeStep()
{
return timeStep_;
}
/**
* <summary>Processes the obstacles that have been added so that they
* are accounted for in the simulation.</summary>
*
* <remarks>Obstacles added to the simulation after this function has
* been called are not accounted for in the simulation.</remarks>
*/
public void processObstacles()
{
kdTree_.buildObstacleTree(this);
}
/**
* <summary>Performs a visibility query between the two specified points
* with respect to the obstacles.</summary>
*
* <returns>A boolean specifying whether the two points are mutually
* visible. Returns true when the obstacles have not been processed.
* </returns>
*
* <param name="point1">The first point of the query.</param>
* <param name="point2">The second point of the query.</param>
* <param name="radius">The minimal distance between the line connecting
* the two points and the obstacles in order for the points to be
* mutually visible (optional). Must be non-negative.</param>
*/
public bool queryVisibility(Vector2 point1, Vector2 point2, float radius)
{
return kdTree_.queryVisibility(point1, point2, radius);
}
/**
* <summary>Sets the default properties for any new agent that is added.
* </summary>
*
* <param name="neighborDist">The default maximum distance (center point
* to center point) to other agents a new agent takes into account in
* the navigation. The larger this number, the longer he running time of
* the simulation. If the number is too low, the simulation will not be
* safe. Must be non-negative.</param>
* <param name="maxNeighbors">The default maximum number of other agents
* a new agent takes into account in the navigation. The larger this
* number, the longer the running time of the simulation. If the number
* is too low, the simulation will not be safe.</param>
* <param name="timeHorizon">The default minimal amount of time for
* which a new agent's velocities that are computed by the simulation
* are safe with respect to other agents. The larger this number, the
* sooner an agent will respond to the presence of other agents, but the
* less freedom the agent has in choosing its velocities. Must be
* positive.</param>
* <param name="timeHorizonObst">The default minimal amount of time for
* which a new agent's velocities that are computed by the simulation
* are safe with respect to obstacles. The larger this number, the
* sooner an agent will respond to the presence of obstacles, but the
* less freedom the agent has in choosing its velocities. Must be
* positive.</param>
* <param name="radius">The default radius of a new agent. Must be
* non-negative.</param>
* <param name="maxSpeed">The default maximum speed of a new agent. Must
* be non-negative.</param>
* <param name="velocity">The default initial two-dimensional linear
* velocity of a new agent.</param>
*/
public void setAgentDefaults(float neighborDist, int maxNeighbors, float timeHorizon, float timeHorizonObst, float radius, float maxSpeed, Vector2 velocity)
{
if (defaultAgent_ == null)
{
defaultAgent_ = new Agent();
}
defaultAgent_.maxNeighbors_ = maxNeighbors;
defaultAgent_.maxSpeed_ = maxSpeed;
defaultAgent_.neighborDist_ = neighborDist;
defaultAgent_.radius_ = radius;
defaultAgent_.timeHorizon_ = timeHorizon;
defaultAgent_.timeHorizonObst_ = timeHorizonObst;
defaultAgent_.velocity_ = velocity;
}
/**
* <summary>Sets the maximum neighbor count of a specified agent.
* </summary>
*
* <param name="agentNo">The number of the agent whose maximum neighbor
* count is to be modified.</param>
* <param name="maxNeighbors">The replacement maximum neighbor count.
* </param>
*/
public void setAgentMaxNeighbors(int agentNo, int maxNeighbors)
{
agents_[agentNo].maxNeighbors_ = maxNeighbors;
}
/**
* <summary>Sets the maximum speed of a specified agent.</summary>
*
* <param name="agentNo">The number of the agent whose maximum speed is
* to be modified.</param>
* <param name="maxSpeed">The replacement maximum speed. Must be
* non-negative.</param>
*/
public void setAgentMaxSpeed(int agentNo, float maxSpeed)
{
agents_[agentNo].maxSpeed_ = maxSpeed;
}
/**
* <summary>Sets the maximum neighbor distance of a specified agent.
* </summary>
*
* <param name="agentNo">The number of the agent whose maximum neighbor
* distance is to be modified.</param>
* <param name="neighborDist">The replacement maximum neighbor distance.
* Must be non-negative.</param>
*/
public void setAgentNeighborDist(int agentNo, float neighborDist)
{
agents_[agentNo].neighborDist_ = neighborDist;
}
/**
* <summary>Sets the two-dimensional position of a specified agent.
* </summary>
*
* <param name="agentNo">The number of the agent whose two-dimensional
* position is to be modified.</param>
* <param name="position">The replacement of the two-dimensional
* position.</param>
*/
public void setAgentPosition(int agentNo, Vector2 position)
{
agents_[agentNo].position_ = position;
}
/**
* <summary>Sets the two-dimensional preferred velocity of a specified
* agent.</summary>
*
* <param name="agentNo">The number of the agent whose two-dimensional
* preferred velocity is to be modified.</param>
* <param name="prefVelocity">The replacement of the two-dimensional
* preferred velocity.</param>
*/
public void setAgentPrefVelocity(int agentNo, Vector2 prefVelocity)
{
agents_[agentNo].prefVelocity_ = prefVelocity;
}
/**
* <summary>Sets the radius of a specified agent.</summary>
*
* <param name="agentNo">The number of the agent whose radius is to be
* modified.</param>
* <param name="radius">The replacement radius. Must be non-negative.
* </param>
*/
public void setAgentRadius(int agentNo, float radius)
{
agents_[agentNo].radius_ = radius;
}
/**
* <summary>Sets the time horizon of a specified agent with respect to
* other agents.</summary>
*
* <param name="agentNo">The number of the agent whose time horizon is
* to be modified.</param>
* <param name="timeHorizon">The replacement time horizon with respect
* to other agents. Must be positive.</param>
*/
public void setAgentTimeHorizon(int agentNo, float timeHorizon)
{
agents_[agentNo].timeHorizon_ = timeHorizon;
}
/**
* <summary>Sets the time horizon of a specified agent with respect to
* obstacles.</summary>
*
* <param name="agentNo">The number of the agent whose time horizon with
* respect to obstacles is to be modified.</param>
* <param name="timeHorizonObst">The replacement time horizon with
* respect to obstacles. Must be positive.</param>
*/
public void setAgentTimeHorizonObst(int agentNo, float timeHorizonObst)
{
agents_[agentNo].timeHorizonObst_ = timeHorizonObst;
}
/**
* <summary>Sets the two-dimensional linear velocity of a specified
* agent.</summary>
*
* <param name="agentNo">The number of the agent whose two-dimensional
* linear velocity is to be modified.</param>
* <param name="velocity">The replacement two-dimensional linear
* velocity.</param>
*/
public void setAgentVelocity(int agentNo, Vector2 velocity)
{
agents_[agentNo].velocity_ = velocity;
}
/**
* <summary>Sets the global time of the simulation.</summary>
*
* <param name="globalTime">The global time of the simulation.</param>
*/
public void setGlobalTime(float globalTime)
{
globalTime_ = globalTime;
}
/**
* <summary>Sets the number of workers.</summary>
*
* <param name="numWorkers">The number of workers.</param>
*/
public void SetNumWorkers(int numWorkers)
{
numWorkers_ = numWorkers;
if (numWorkers_ <= 0)
{
int completionPorts;
ThreadPool.GetMinThreads(out numWorkers_, out completionPorts);
}
workers_ = null;
}
/**
* <summary>Sets the time step of the simulation.</summary>
*
* <param name="timeStep">The time step of the simulation. Must be
* positive.</param>
*/
public void setTimeStep(float timeStep)
{
timeStep_ = timeStep;
}
/**
* <summary>Constructs and initializes a simulation.</summary>
*/
public Simulator()
{
Clear();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Text
{
public sealed class DecoderReplacementFallback : DecoderFallback
{
// Our variables
private String strDefault;
// Construction. Default replacement fallback uses no best fit and ? replacement string
public DecoderReplacementFallback() : this("?")
{
}
public DecoderReplacementFallback(String replacement)
{
if (replacement == null)
throw new ArgumentNullException(nameof(replacement));
Contract.EndContractBlock();
// Make sure it doesn't have bad surrogate pairs
bool bFoundHigh = false;
for (int i = 0; i < replacement.Length; i++)
{
// Found a surrogate?
if (Char.IsSurrogate(replacement, i))
{
// High or Low?
if (Char.IsHighSurrogate(replacement, i))
{
// if already had a high one, stop
if (bFoundHigh)
break; // break & throw at the bFoundHIgh below
bFoundHigh = true;
}
else
{
// Low, did we have a high?
if (!bFoundHigh)
{
// Didn't have one, make if fail when we stop
bFoundHigh = true;
break;
}
// Clear flag
bFoundHigh = false;
}
}
// If last was high we're in trouble (not surrogate so not low surrogate, so break)
else if (bFoundHigh)
break;
}
if (bFoundHigh)
throw new ArgumentException(SR.Format(SR.Argument_InvalidCharSequenceNoIndex, nameof(replacement)));
strDefault = replacement;
}
public String DefaultString
{
get
{
return strDefault;
}
}
public override DecoderFallbackBuffer CreateFallbackBuffer()
{
return new DecoderReplacementFallbackBuffer(this);
}
// Maximum number of characters that this instance of this fallback could return
public override int MaxCharCount
{
get
{
return strDefault.Length;
}
}
public override bool Equals(Object value)
{
DecoderReplacementFallback that = value as DecoderReplacementFallback;
if (that != null)
{
return (strDefault == that.strDefault);
}
return (false);
}
public override int GetHashCode()
{
return strDefault.GetHashCode();
}
}
public sealed class DecoderReplacementFallbackBuffer : DecoderFallbackBuffer
{
// Store our default string
private String strDefault;
private int fallbackCount = -1;
private int fallbackIndex = -1;
// Construction
public DecoderReplacementFallbackBuffer(DecoderReplacementFallback fallback)
{
strDefault = fallback.DefaultString;
}
// Fallback Methods
public override bool Fallback(byte[] bytesUnknown, int index)
{
// We expect no previous fallback in our buffer
// We can't call recursively but others might (note, we don't test on last char!!!)
if (fallbackCount >= 1)
{
ThrowLastBytesRecursive(bytesUnknown);
}
// Go ahead and get our fallback
if (strDefault.Length == 0)
return false;
fallbackCount = strDefault.Length;
fallbackIndex = -1;
return true;
}
public override char GetNextChar()
{
// We want it to get < 0 because == 0 means that the current/last character is a fallback
// and we need to detect recursion. We could have a flag but we already have this counter.
fallbackCount--;
fallbackIndex++;
// Do we have anything left? 0 is now last fallback char, negative is nothing left
if (fallbackCount < 0)
return '\0';
// Need to get it out of the buffer.
// Make sure it didn't wrap from the fast count-- path
if (fallbackCount == int.MaxValue)
{
fallbackCount = -1;
return '\0';
}
// Now make sure its in the expected range
Debug.Assert(fallbackIndex < strDefault.Length && fallbackIndex >= 0,
"Index exceeds buffer range");
return strDefault[fallbackIndex];
}
public override bool MovePrevious()
{
// Back up one, only if we just processed the last character (or earlier)
if (fallbackCount >= -1 && fallbackIndex >= 0)
{
fallbackIndex--;
fallbackCount++;
return true;
}
// Return false 'cause we couldn't do it.
return false;
}
// How many characters left to output?
public override int Remaining
{
get
{
// Our count is 0 for 1 character left.
return (fallbackCount < 0) ? 0 : fallbackCount;
}
}
// Clear the buffer
public override unsafe void Reset()
{
fallbackCount = -1;
fallbackIndex = -1;
byteStart = null;
}
// This version just counts the fallback and doesn't actually copy anything.
internal unsafe override int InternalFallback(byte[] bytes, byte* pBytes)
// Right now this has both bytes and bytes[], since we might have extra bytes, hence the
// array, and we might need the index, hence the byte*
{
// return our replacement string Length
return strDefault.Length;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using Validation;
namespace System.Collections.Immutable
{
public partial struct ImmutableArray<T>
{
/// <summary>
/// A writable array accessor that can be converted into an <see cref="ImmutableArray{T}"/>
/// instance without allocating memory.
/// </summary>
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(ImmutableArrayBuilderDebuggerProxy<>))]
public sealed class Builder : IList<T>, IReadOnlyList<T>
{
/// <summary>
/// The backing array for the builder.
/// </summary>
private RefAsValueType<T>[] elements;
/// <summary>
/// The number of initialized elements in the array.
/// </summary>
private int count;
/// <summary>
/// Initializes a new instance of the <see cref="Builder"/> class.
/// </summary>
/// <param name="capacity">The initial capacity of the internal array.</param>
internal Builder(int capacity)
{
Requires.Range(capacity >= 0, "capacity");
this.elements = new RefAsValueType<T>[capacity];
this.Count = 0;
}
/// <summary>
/// Initializes a new instance of the <see cref="Builder"/> class.
/// </summary>
internal Builder()
: this(8)
{
}
/// <summary>
/// Gets or sets the length of the array.
/// </summary>
/// <remarks>
/// If the value is decreased, the array contents are truncated.
/// If the value is increased, the added elements are initialized to <c>default(T)</c>.
/// </remarks>
public int Count
{
get
{
return this.count;
}
set
{
Requires.Range(value >= 0, "value");
if (value < this.count)
{
// truncation mode
// Clear the elements of the elements that are effectively removed.
var e = this.elements;
// PERF: Array.Clear works well for big arrays,
// but may have too much overhead with small ones (which is the common case here)
if (this.count - value > 64)
{
Array.Clear(this.elements, value, this.count - value);
}
else
{
for (int i = value; i < this.Count; i++)
{
this.elements[i].Value = default(T);
}
}
}
else if (value > this.count)
{
// expansion
this.EnsureCapacity(value);
}
this.count = value;
}
}
/// <summary>
/// Gets or sets the element at the specified index.
/// </summary>
/// <param name="index">The index.</param>
/// <returns></returns>
/// <exception cref="System.IndexOutOfRangeException">
/// </exception>
public T this[int index]
{
get
{
if (index >= this.Count)
{
throw new IndexOutOfRangeException();
}
return this.elements[index].Value;
}
set
{
if (index >= this.Count)
{
throw new IndexOutOfRangeException();
}
this.elements[index].Value = value;
}
}
/// <summary>
/// Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1" /> is read-only.
/// </summary>
/// <returns>true if the <see cref="T:System.Collections.Generic.ICollection`1" /> is read-only; otherwise, false.
/// </returns>
bool ICollection<T>.IsReadOnly
{
get { return false; }
}
/// <summary>
/// Returns an immutable copy of the current contents of this collection.
/// </summary>
/// <returns>An immutable array.</returns>
public ImmutableArray<T> ToImmutable()
{
if (this.Count == 0)
{
return Empty;
}
return new ImmutableArray<T>(this.ToArray());
}
/// <summary>
/// Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1" />.
/// </summary>
public void Clear()
{
this.Count = 0;
}
/// <summary>
/// Inserts an item to the <see cref="T:System.Collections.Generic.IList`1" /> at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which <paramref name="item" /> should be inserted.</param>
/// <param name="item">The object to insert into the <see cref="T:System.Collections.Generic.IList`1" />.</param>
public void Insert(int index, T item)
{
Requires.Range(index >= 0 && index <= this.Count, "index");
this.EnsureCapacity(this.Count + 1);
if (index < this.Count)
{
Array.Copy(this.elements, index, this.elements, index + 1, this.Count - index);
}
this.count++;
this.elements[index].Value = item;
}
/// <summary>
/// Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1" />.
/// </summary>
/// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1" />.</param>
public void Add(T item)
{
this.EnsureCapacity(this.Count + 1);
this.elements[this.count++].Value = item;
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
public void AddRange(IEnumerable<T> items)
{
Requires.NotNull(items, "items");
int count;
if (items.TryGetCount(out count))
{
this.EnsureCapacity(this.Count + count);
}
foreach (var item in items)
{
this.Add(item);
}
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
public void AddRange(params T[] items)
{
Requires.NotNull(items, "items");
var offset = this.Count;
this.Count += items.Length;
var nodes = this.elements;
for (int i = 0; i < items.Length; i++)
{
nodes[offset + i].Value = items[i];
}
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
public void AddRange<TDerived>(TDerived[] items) where TDerived : T
{
Requires.NotNull(items, "items");
var offset = this.Count;
this.Count += items.Length;
var nodes = this.elements;
for (int i = 0; i < items.Length; i++)
{
nodes[offset + i].Value = items[i];
}
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
/// <param name="length">The number of elements from the source array to add.</param>
public void AddRange(T[] items, int length)
{
Requires.NotNull(items, "items");
Requires.Range(length >= 0, "length");
var offset = this.Count;
this.Count += length;
var nodes = this.elements;
for (int i = 0; i < length; i++)
{
nodes[offset + i].Value = items[i];
}
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
public void AddRange(ImmutableArray<T> items)
{
this.AddRange(items, items.Length);
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
/// <param name="length">The number of elements from the source array to add.</param>
public void AddRange(ImmutableArray<T> items, int length)
{
Requires.Range(length >= 0, "length");
if (items.array != null)
{
this.AddRange(items.array, length);
}
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
public void AddRange<TDerived>(ImmutableArray<TDerived> items) where TDerived : T
{
if (items.array != null)
{
this.AddRange(items.array);
}
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
public void AddRange(Builder items)
{
Requires.NotNull(items, "items");
this.AddRange(items.elements, items.Count);
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
public void AddRange<TDerived>(ImmutableArray<TDerived>.Builder items) where TDerived : T
{
Requires.NotNull(items, "items");
this.AddRange(items.elements, items.Count);
}
/// <summary>
/// Removes the specified element.
/// </summary>
/// <param name="element">The element.</param>
/// <returns>A value indicating whether the specified element was found and removed from the collection.</returns>
public bool Remove(T element)
{
int index = this.IndexOf(element);
if (index >= 0)
{
this.RemoveAt(index);
return true;
}
return false;
}
/// <summary>
/// Removes the <see cref="T:System.Collections.Generic.IList`1" /> item at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the item to remove.</param>
public void RemoveAt(int index)
{
Requires.Range(index >= 0 && index < this.Count, "index");
if (index < this.Count - 1)
{
Array.Copy(this.elements, index + 1, this.elements, index, this.Count - index - 1);
}
this.Count--;
}
/// <summary>
/// Determines whether the <see cref="T:System.Collections.Generic.ICollection`1" /> contains a specific value.
/// </summary>
/// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1" />.</param>
/// <returns>
/// true if <paramref name="item" /> is found in the <see cref="T:System.Collections.Generic.ICollection`1" />; otherwise, false.
/// </returns>
public bool Contains(T item)
{
return this.IndexOf(item) >= 0;
}
/// <summary>
/// Creates a new array with the current contents of this Builder.
/// </summary>
public T[] ToArray()
{
var tmp = new T[this.Count];
var elements = this.elements;
for (int i = 0; i < tmp.Length; i++)
{
tmp[i] = elements[i].Value;
}
return tmp;
}
/// <summary>
/// Copies the current contents to the specified array.
/// </summary>
/// <param name="array">The array to copy to.</param>
/// <param name="index">The starting index of the target array.</param>
public void CopyTo(T[] array, int index)
{
Requires.NotNull(array, "array");
Requires.Range(index >= 0 && index + this.Count <= array.Length, "start");
foreach (var item in this)
{
array[index++] = item;
}
}
/// <summary>
/// Resizes the array to accommodate the specified capacity requirement.
/// </summary>
/// <param name="capacity">The required capacity.</param>
public void EnsureCapacity(int capacity)
{
if (this.elements.Length < capacity)
{
int newCapacity = Math.Max(this.elements.Length * 2, capacity);
Array.Resize(ref this.elements, newCapacity);
}
}
/// <summary>
/// Determines the index of a specific item in the <see cref="T:System.Collections.Generic.IList`1" />.
/// </summary>
/// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.IList`1" />.</param>
/// <returns>
/// The index of <paramref name="item" /> if found in the list; otherwise, -1.
/// </returns>
[Pure]
public int IndexOf(T item)
{
return this.IndexOf(item, 0, this.count, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches the array for the specified item.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <param name="startIndex">The index at which to begin the search.</param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int IndexOf(T item, int startIndex)
{
return this.IndexOf(item, startIndex, this.Count - startIndex, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches the array for the specified item.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <param name="startIndex">The index at which to begin the search.</param>
/// <param name="count">The number of elements to search.</param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int IndexOf(T item, int startIndex, int count)
{
return this.IndexOf(item, startIndex, count, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches the array for the specified item.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <param name="startIndex">The index at which to begin the search.</param>
/// <param name="count">The number of elements to search.</param>
/// <param name="equalityComparer">The equality comparer to use in the search.</param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int IndexOf(T item, int startIndex, int count, IEqualityComparer<T> equalityComparer)
{
Requires.NotNull(equalityComparer, "equalityComparer");
if (count == 0 && startIndex == 0)
{
return -1;
}
Requires.Range(startIndex >= 0 && startIndex < this.Count, "startIndex");
Requires.Range(count >= 0 && startIndex + count <= this.Count, "count");
if (equalityComparer == EqualityComparer<T>.Default)
{
return Array.IndexOf(this.elements, new RefAsValueType<T>(item), startIndex, count);
}
else
{
for (int i = startIndex; i < startIndex + count; i++)
{
if (equalityComparer.Equals(this.elements[i].Value, item))
{
return i;
}
}
return -1;
}
}
/// <summary>
/// Searches the array for the specified item in reverse.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int LastIndexOf(T item)
{
if (this.Count == 0)
{
return -1;
}
return this.LastIndexOf(item, this.Count - 1, this.Count, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches the array for the specified item in reverse.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <param name="startIndex">The index at which to begin the search.</param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int LastIndexOf(T item, int startIndex)
{
if (this.Count == 0 && startIndex == 0)
{
return -1;
}
Requires.Range(startIndex >= 0 && startIndex < this.Count, "startIndex");
return this.LastIndexOf(item, startIndex, startIndex + 1, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches the array for the specified item in reverse.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <param name="startIndex">The index at which to begin the search.</param>
/// <param name="count">The number of elements to search.</param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int LastIndexOf(T item, int startIndex, int count)
{
return this.LastIndexOf(item, startIndex, count, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches the array for the specified item in reverse.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <param name="startIndex">The index at which to begin the search.</param>
/// <param name="count">The number of elements to search.</param>
/// <param name="equalityComparer">The equality comparer to use in the search.</param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int LastIndexOf(T item, int startIndex, int count, IEqualityComparer<T> equalityComparer)
{
Requires.NotNull(equalityComparer, "equalityComparer");
if (count == 0 && startIndex == 0)
{
return -1;
}
Requires.Range(startIndex >= 0 && startIndex < this.Count, "startIndex");
Requires.Range(count >= 0 && startIndex - count + 1 >= 0, "count");
if (equalityComparer == EqualityComparer<T>.Default)
{
return Array.LastIndexOf(this.elements, new RefAsValueType<T>(item), startIndex, count);
}
else
{
for (int i = startIndex; i >= startIndex - count + 1; i--)
{
if (equalityComparer.Equals(item, this.elements[i].Value))
{
return i;
}
}
return -1;
}
}
/// <summary>
/// Reverses the order of elements in the collection.
/// </summary>
public void ReverseContents()
{
int end = this.Count - 1;
for (int i = 0, j = end; i < j; i++, j--)
{
var tmp = this.elements[i].Value;
this.elements[i] = this.elements[j];
this.elements[j].Value = tmp;
}
}
/// <summary>
/// Sorts the array.
/// </summary>
public void Sort()
{
Array.Sort(this.elements, 0, this.Count, Comparer.Default);
}
/// <summary>
/// Sorts the array.
/// </summary>
/// <param name="comparer">The comparer to use in sorting. If <c>null</c>, the default comparer is used.</param>
public void Sort(IComparer<T> comparer)
{
Array.Sort(this.elements, 0, this.Count, new Comparer(comparer));
}
/// <summary>
/// Sorts the array.
/// </summary>
/// <param name="index">The index of the first element to consider in the sort.</param>
/// <param name="count">The number of elements to include in the sort.</param>
/// <param name="comparer">The comparer to use in sorting. If <c>null</c>, the default comparer is used.</param>
public void Sort(int index, int count, IComparer<T> comparer)
{
// Don't rely on Array.Sort's argument validation since our internal array may exceed
// the bounds of the publically addressible region.
Requires.Range(index >= 0, "index");
Requires.Range(count >= 0 && index + count <= this.Count, "count");
Array.Sort(this.elements, index, count, new Comparer(comparer));
}
/// <summary>
/// Returns an enumerator for the contents of the array.
/// </summary>
/// <returns>An enumerator.</returns>
public IEnumerator<T> GetEnumerator()
{
for (int i = 0; i < this.Count; i++)
{
yield return this[i];
}
}
/// <summary>
/// Returns an enumerator for the contents of the array.
/// </summary>
/// <returns>An enumerator.</returns>
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return this.GetEnumerator();
}
/// <summary>
/// Returns an enumerator for the contents of the array.
/// </summary>
/// <returns>An enumerator.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
/// <summary>
/// Adds items to this collection.
/// </summary>
/// <typeparam name="TDerived">The type of source elements.</typeparam>
/// <param name="items">The source array.</param>
/// <param name="length">The number of elements to add to this array.</param>
private void AddRange<TDerived>(RefAsValueType<TDerived>[] items, int length) where TDerived : T
{
this.EnsureCapacity(this.Count + length);
var offset = this.Count;
this.Count += length;
var nodes = this.elements;
for (int i = 0; i < length; i++)
{
nodes[offset + i].Value = items[i].Value;
}
}
private sealed class Comparer : IComparer<RefAsValueType<T>>
{
private readonly IComparer<T> comparer;
public static readonly Comparer Default = new Comparer(Comparer<T>.Default);
internal Comparer(IComparer<T> comparer = null)
{
Requires.NotNull(comparer, "comparer");
this.comparer = comparer;
}
public int Compare(RefAsValueType<T> x, RefAsValueType<T> y)
{
return this.comparer.Compare(x.Value, y.Value);
}
}
}
}
/// <summary>
/// A simple view of the immutable collection that the debugger can show to the developer.
/// </summary>
[ExcludeFromCodeCoverage]
internal sealed class ImmutableArrayBuilderDebuggerProxy<T>
{
/// <summary>
/// The collection to be enumerated.
/// </summary>
private readonly ImmutableArray<T>.Builder builder;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableArrayBuilderDebuggerProxy<T>"/> class.
/// </summary>
/// <param name="builder">The collection to display in the debugger</param>
public ImmutableArrayBuilderDebuggerProxy(ImmutableArray<T>.Builder builder)
{
this.builder = builder;
}
/// <summary>
/// Gets a simple debugger-viewable collection.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public T[] A
{
get
{
return this.builder.ToArray();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Reflection;
using System.Runtime;
using System.Threading;
using Internal.Metadata.NativeFormat;
using Internal.Runtime.CompilerServices;
using Internal.TypeSystem;
namespace Internal.TypeSystem.NativeFormat
{
public sealed class NativeFormatMethod : MethodDesc, NativeFormatMetadataUnit.IHandleObject
{
private static class MethodFlags
{
public const int BasicMetadataCache = 0x0001;
public const int Virtual = 0x0002;
public const int NewSlot = 0x0004;
public const int Abstract = 0x0008;
public const int Final = 0x0010;
public const int NoInlining = 0x0020;
public const int AggressiveInlining = 0x0040;
public const int RuntimeImplemented = 0x0080;
public const int InternalCall = 0x0100;
public const int Synchronized = 0x0200;
public const int AttributeMetadataCache = 0x1000;
public const int Intrinsic = 0x2000;
public const int NativeCallable = 0x4000;
public const int RuntimeExport = 0x8000;
};
private NativeFormatType _type;
private MethodHandle _handle;
// Cached values
private ThreadSafeFlags _methodFlags;
private MethodSignature _signature;
private string _name;
private TypeDesc[] _genericParameters; // TODO: Optional field?
internal NativeFormatMethod(NativeFormatType type, MethodHandle handle)
{
_type = type;
_handle = handle;
#if DEBUG
// Initialize name eagerly in debug builds for convenience
this.ToString();
#endif
}
Handle NativeFormatMetadataUnit.IHandleObject.Handle
{
get
{
return _handle;
}
}
NativeFormatType NativeFormatMetadataUnit.IHandleObject.Container
{
get
{
return _type;
}
}
public override TypeSystemContext Context
{
get
{
return _type.Module.Context;
}
}
public override TypeDesc OwningType
{
get
{
return _type;
}
}
private MethodSignature InitializeSignature()
{
var metadataReader = MetadataReader;
NativeFormatSignatureParser parser = new NativeFormatSignatureParser(MetadataUnit, MetadataReader.GetMethod(_handle).Signature, metadataReader);
var signature = parser.ParseMethodSignature();
return (_signature = signature);
}
public override MethodSignature Signature
{
get
{
if (_signature == null)
return InitializeSignature();
return _signature;
}
}
public NativeFormatModule NativeFormatModule
{
get
{
return _type.NativeFormatModule;
}
}
public MetadataReader MetadataReader
{
get
{
return _type.MetadataReader;
}
}
public NativeFormatMetadataUnit MetadataUnit
{
get
{
return _type.MetadataUnit;
}
}
public MethodHandle Handle
{
get
{
return _handle;
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private int InitializeMethodFlags(int mask)
{
int flags = 0;
if ((mask & MethodFlags.BasicMetadataCache) != 0)
{
var methodAttributes = Attributes;
var methodImplAttributes = ImplAttributes;
if ((methodAttributes & MethodAttributes.Virtual) != 0)
flags |= MethodFlags.Virtual;
if ((methodAttributes & MethodAttributes.NewSlot) != 0)
flags |= MethodFlags.NewSlot;
if ((methodAttributes & MethodAttributes.Abstract) != 0)
flags |= MethodFlags.Abstract;
if ((methodAttributes & MethodAttributes.Final) != 0)
flags |= MethodFlags.Final;
if ((methodImplAttributes & MethodImplAttributes.NoInlining) != 0)
flags |= MethodFlags.NoInlining;
if ((methodImplAttributes & MethodImplAttributes.AggressiveInlining) != 0)
flags |= MethodFlags.AggressiveInlining;
if ((methodImplAttributes & MethodImplAttributes.Runtime) != 0)
flags |= MethodFlags.RuntimeImplemented;
if ((methodImplAttributes & MethodImplAttributes.InternalCall) != 0)
flags |= MethodFlags.InternalCall;
if ((methodImplAttributes & MethodImplAttributes.Synchronized) != 0)
flags |= MethodFlags.Synchronized;
flags |= MethodFlags.BasicMetadataCache;
}
// Fetching custom attribute based properties is more expensive, so keep that under
// a separate cache that might not be accessed very frequently.
if ((mask & MethodFlags.AttributeMetadataCache) != 0)
{
var metadataReader = this.MetadataReader;
var methodDefinition = MetadataReader.GetMethod(_handle);
foreach (var attributeHandle in methodDefinition.CustomAttributes)
{
ConstantStringValueHandle nameHandle;
string namespaceName;
if (!metadataReader.GetAttributeNamespaceAndName(attributeHandle, out namespaceName, out nameHandle))
continue;
if (namespaceName.Equals("System.Runtime.CompilerServices"))
{
if (nameHandle.StringEquals("IntrinsicAttribute", metadataReader))
{
flags |= MethodFlags.Intrinsic;
}
}
else
if (namespaceName.Equals("System.Runtime.InteropServices"))
{
if (nameHandle.StringEquals("NativeCallableAttribute", metadataReader))
{
flags |= MethodFlags.NativeCallable;
}
}
else
if (namespaceName.Equals("System.Runtime"))
{
if (nameHandle.StringEquals("RuntimeExportAttribute", metadataReader))
{
flags |= MethodFlags.RuntimeExport;
}
}
}
flags |= MethodFlags.AttributeMetadataCache;
}
Debug.Assert((flags & mask) != 0);
_methodFlags.AddFlags(flags);
return flags & mask;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private int GetMethodFlags(int mask)
{
int flags = _methodFlags.Value & mask;
if (flags != 0)
return flags;
return InitializeMethodFlags(mask);
}
public override bool IsVirtual
{
get
{
return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.Virtual) & MethodFlags.Virtual) != 0;
}
}
public override bool IsNewSlot
{
get
{
return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.NewSlot) & MethodFlags.NewSlot) != 0;
}
}
public override bool IsAbstract
{
get
{
return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.Abstract) & MethodFlags.Abstract) != 0;
}
}
public override bool IsFinal
{
get
{
return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.Final) & MethodFlags.Final) != 0;
}
}
public override bool IsNoInlining
{
get
{
return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.NoInlining) & MethodFlags.NoInlining) != 0;
}
}
public override bool IsAggressiveInlining
{
get
{
return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.AggressiveInlining) & MethodFlags.AggressiveInlining) != 0;
}
}
public override bool IsRuntimeImplemented
{
get
{
return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.RuntimeImplemented) & MethodFlags.RuntimeImplemented) != 0;
}
}
public override bool IsIntrinsic
{
get
{
return (GetMethodFlags(MethodFlags.AttributeMetadataCache | MethodFlags.Intrinsic) & MethodFlags.Intrinsic) != 0;
}
}
public override bool IsInternalCall
{
get
{
return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.InternalCall) & MethodFlags.InternalCall) != 0;
}
}
public override bool IsSynchronized
{
get
{
return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.Synchronized) & MethodFlags.Synchronized) != 0;
}
}
public override bool IsNativeCallable
{
get
{
return (GetMethodFlags(MethodFlags.AttributeMetadataCache | MethodFlags.NativeCallable) & MethodFlags.NativeCallable) != 0;
}
}
public override bool IsRuntimeExport
{
get
{
return (GetMethodFlags(MethodFlags.AttributeMetadataCache | MethodFlags.RuntimeExport) & MethodFlags.RuntimeExport) != 0;
}
}
public override bool IsDefaultConstructor
{
get
{
MethodAttributes attributes = Attributes;
return attributes.IsRuntimeSpecialName()
&& attributes.IsPublic()
&& Signature.Length == 0
&& Name == ".ctor"
&& !_type.IsAbstract;
}
}
public MethodAttributes Attributes
{
get
{
return MetadataReader.GetMethod(_handle).Flags;
}
}
public MethodImplAttributes ImplAttributes
{
get
{
return MetadataReader.GetMethod(_handle).ImplFlags;
}
}
private string InitializeName()
{
var metadataReader = MetadataReader;
var name = metadataReader.GetString(MetadataReader.GetMethod(_handle).Name);
return (_name = name);
}
public override string Name
{
get
{
if (_name == null)
return InitializeName();
return _name;
}
}
private void ComputeGenericParameters()
{
var genericParameterHandles = MetadataReader.GetMethod(_handle).GenericParameters;
int count = genericParameterHandles.Count;
if (count > 0)
{
TypeDesc[] genericParameters = new TypeDesc[count];
int i = 0;
foreach (var genericParameterHandle in genericParameterHandles)
{
genericParameters[i++] = new NativeFormatGenericParameter(MetadataUnit, genericParameterHandle);
}
Interlocked.CompareExchange(ref _genericParameters, genericParameters, null);
}
else
{
_genericParameters = TypeDesc.EmptyTypes;
}
}
public override Instantiation Instantiation
{
get
{
if (_genericParameters == null)
ComputeGenericParameters();
return new Instantiation(_genericParameters);
}
}
public override bool HasCustomAttribute(string attributeNamespace, string attributeName)
{
return MetadataReader.HasCustomAttribute(MetadataReader.GetMethod(_handle).CustomAttributes,
attributeNamespace, attributeName);
}
public override string ToString()
{
return _type.ToString() + "." + Name;
}
public override MethodNameAndSignature NameAndSignature
{
get
{
int handleAsToken = _handle.ToInt();
TypeManagerHandle moduleHandle = Internal.Runtime.TypeLoader.ModuleList.Instance.GetModuleForMetadataReader(MetadataReader);
return new MethodNameAndSignature(Name, RuntimeSignature.CreateFromMethodHandle(moduleHandle, handleAsToken));
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace Asn1 {
public class AsnOID {
static Dictionary<string, string> OIDToName =
new Dictionary<string, string>();
static Dictionary<string, string> NameToOID =
new Dictionary<string, string>();
static AsnOID()
{
/*
* From RFC 5280, PKIX1Explicit88 module.
*/
Reg("1.3.6.1.5.5.7", "id-pkix");
Reg("1.3.6.1.5.5.7.1", "id-pe");
Reg("1.3.6.1.5.5.7.2", "id-qt");
Reg("1.3.6.1.5.5.7.3", "id-kp");
Reg("1.3.6.1.5.5.7.48", "id-ad");
Reg("1.3.6.1.5.5.7.2.1", "id-qt-cps");
Reg("1.3.6.1.5.5.7.2.2", "id-qt-unotice");
Reg("1.3.6.1.5.5.7.48.1", "id-ad-ocsp");
Reg("1.3.6.1.5.5.7.48.2", "id-ad-caIssuers");
Reg("1.3.6.1.5.5.7.48.3", "id-ad-timeStamping");
Reg("1.3.6.1.5.5.7.48.5", "id-ad-caRepository");
Reg("2.5.4", "id-at");
Reg("2.5.4.41", "id-at-name");
Reg("2.5.4.4", "id-at-surname");
Reg("2.5.4.42", "id-at-givenName");
Reg("2.5.4.43", "id-at-initials");
Reg("2.5.4.44", "id-at-generationQualifier");
Reg("2.5.4.3", "id-at-commonName");
Reg("2.5.4.7", "id-at-localityName");
Reg("2.5.4.8", "id-at-stateOrProvinceName");
Reg("2.5.4.10", "id-at-organizationName");
Reg("2.5.4.11", "id-at-organizationalUnitName");
Reg("2.5.4.12", "id-at-title");
Reg("2.5.4.46", "id-at-dnQualifier");
Reg("2.5.4.6", "id-at-countryName");
Reg("2.5.4.5", "id-at-serialNumber");
Reg("2.5.4.65", "id-at-pseudonym");
Reg("0.9.2342.19200300.100.1.25", "id-domainComponent");
Reg("1.2.840.113549.1.9", "pkcs-9");
Reg("1.2.840.113549.1.9.1", "id-emailAddress");
/*
* From RFC 5280, PKIX1Implicit88 module.
*/
Reg("2.5.29", "id-ce");
Reg("2.5.29.35", "id-ce-authorityKeyIdentifier");
Reg("2.5.29.14", "id-ce-subjectKeyIdentifier");
Reg("2.5.29.15", "id-ce-keyUsage");
Reg("2.5.29.16", "id-ce-privateKeyUsagePeriod");
Reg("2.5.29.32", "id-ce-certificatePolicies");
Reg("2.5.29.33", "id-ce-policyMappings");
Reg("2.5.29.17", "id-ce-subjectAltName");
Reg("2.5.29.18", "id-ce-issuerAltName");
Reg("2.5.29.9", "id-ce-subjectDirectoryAttributes");
Reg("2.5.29.19", "id-ce-basicConstraints");
Reg("2.5.29.30", "id-ce-nameConstraints");
Reg("2.5.29.36", "id-ce-policyConstraints");
Reg("2.5.29.31", "id-ce-cRLDistributionPoints");
Reg("2.5.29.37", "id-ce-extKeyUsage");
Reg("2.5.29.37.0", "anyExtendedKeyUsage");
Reg("1.3.6.1.5.5.7.3.1", "id-kp-serverAuth");
Reg("1.3.6.1.5.5.7.3.2", "id-kp-clientAuth");
Reg("1.3.6.1.5.5.7.3.3", "id-kp-codeSigning");
Reg("1.3.6.1.5.5.7.3.4", "id-kp-emailProtection");
Reg("1.3.6.1.5.5.7.3.8", "id-kp-timeStamping");
Reg("1.3.6.1.5.5.7.3.9", "id-kp-OCSPSigning");
Reg("2.5.29.54", "id-ce-inhibitAnyPolicy");
Reg("2.5.29.46", "id-ce-freshestCRL");
Reg("1.3.6.1.5.5.7.1.1", "id-pe-authorityInfoAccess");
Reg("1.3.6.1.5.5.7.1.11", "id-pe-subjectInfoAccess");
Reg("2.5.29.20", "id-ce-cRLNumber");
Reg("2.5.29.28", "id-ce-issuingDistributionPoint");
Reg("2.5.29.27", "id-ce-deltaCRLIndicator");
Reg("2.5.29.21", "id-ce-cRLReasons");
Reg("2.5.29.29", "id-ce-certificateIssuer");
Reg("2.5.29.23", "id-ce-holdInstructionCode");
Reg("2.2.840.10040.2", "WRONG-holdInstruction");
Reg("2.2.840.10040.2.1", "WRONG-id-holdinstruction-none");
Reg("2.2.840.10040.2.2", "WRONG-id-holdinstruction-callissuer");
Reg("2.2.840.10040.2.3", "WRONG-id-holdinstruction-reject");
Reg("2.5.29.24", "id-ce-invalidityDate");
/*
* These are the "right" OID. RFC 5280 mistakenly defines
* the first OID element as "2".
*/
Reg("1.2.840.10040.2", "holdInstruction");
Reg("1.2.840.10040.2.1", "id-holdinstruction-none");
Reg("1.2.840.10040.2.2", "id-holdinstruction-callissuer");
Reg("1.2.840.10040.2.3", "id-holdinstruction-reject");
/*
* From PKCS#1.
*/
Reg("1.2.840.113549.1.1", "pkcs-1");
Reg("1.2.840.113549.1.1.1", "rsaEncryption");
Reg("1.2.840.113549.1.1.7", "id-RSAES-OAEP");
Reg("1.2.840.113549.1.1.9", "id-pSpecified");
Reg("1.2.840.113549.1.1.10", "id-RSASSA-PSS");
Reg("1.2.840.113549.1.1.2", "md2WithRSAEncryption");
Reg("1.2.840.113549.1.1.4", "md5WithRSAEncryption");
Reg("1.2.840.113549.1.1.5", "sha1WithRSAEncryption");
Reg("1.2.840.113549.1.1.11", "sha256WithRSAEncryption");
Reg("1.2.840.113549.1.1.12", "sha384WithRSAEncryption");
Reg("1.2.840.113549.1.1.13", "sha512WithRSAEncryption");
Reg("1.3.14.3.2.26", "id-sha1");
Reg("1.2.840.113549.2.2", "id-md2");
Reg("1.2.840.113549.2.5", "id-md5");
Reg("1.2.840.113549.1.1.8", "id-mgf1");
/*
* From NIST: http://csrc.nist.gov/groups/ST/crypto_apps_infra/csor/algorithms.html
*/
Reg("2.16.840.1.101.3", "csor");
Reg("2.16.840.1.101.3.4", "nistAlgorithms");
Reg("2.16.840.1.101.3.4.0", "csorModules");
Reg("2.16.840.1.101.3.4.0.1", "aesModule1");
Reg("2.16.840.1.101.3.4.1", "aes");
Reg("2.16.840.1.101.3.4.1.1", "id-aes128-ECB");
Reg("2.16.840.1.101.3.4.1.2", "id-aes128-CBC");
Reg("2.16.840.1.101.3.4.1.3", "id-aes128-OFB");
Reg("2.16.840.1.101.3.4.1.4", "id-aes128-CFB");
Reg("2.16.840.1.101.3.4.1.5", "id-aes128-wrap");
Reg("2.16.840.1.101.3.4.1.6", "id-aes128-GCM");
Reg("2.16.840.1.101.3.4.1.7", "id-aes128-CCM");
Reg("2.16.840.1.101.3.4.1.8", "id-aes128-wrap-pad");
Reg("2.16.840.1.101.3.4.1.21", "id-aes192-ECB");
Reg("2.16.840.1.101.3.4.1.22", "id-aes192-CBC");
Reg("2.16.840.1.101.3.4.1.23", "id-aes192-OFB");
Reg("2.16.840.1.101.3.4.1.24", "id-aes192-CFB");
Reg("2.16.840.1.101.3.4.1.25", "id-aes192-wrap");
Reg("2.16.840.1.101.3.4.1.26", "id-aes192-GCM");
Reg("2.16.840.1.101.3.4.1.27", "id-aes192-CCM");
Reg("2.16.840.1.101.3.4.1.28", "id-aes192-wrap-pad");
Reg("2.16.840.1.101.3.4.1.41", "id-aes256-ECB");
Reg("2.16.840.1.101.3.4.1.42", "id-aes256-CBC");
Reg("2.16.840.1.101.3.4.1.43", "id-aes256-OFB");
Reg("2.16.840.1.101.3.4.1.44", "id-aes256-CFB");
Reg("2.16.840.1.101.3.4.1.45", "id-aes256-wrap");
Reg("2.16.840.1.101.3.4.1.46", "id-aes256-GCM");
Reg("2.16.840.1.101.3.4.1.47", "id-aes256-CCM");
Reg("2.16.840.1.101.3.4.1.48", "id-aes256-wrap-pad");
Reg("2.16.840.1.101.3.4.2", "hashAlgs");
Reg("2.16.840.1.101.3.4.2.1", "id-sha256");
Reg("2.16.840.1.101.3.4.2.2", "id-sha384");
Reg("2.16.840.1.101.3.4.2.3", "id-sha512");
Reg("2.16.840.1.101.3.4.2.4", "id-sha224");
Reg("2.16.840.1.101.3.4.2.5", "id-sha512-224");
Reg("2.16.840.1.101.3.4.2.6", "id-sha512-256");
Reg("2.16.840.1.101.3.4.3", "sigAlgs");
Reg("2.16.840.1.101.3.4.3.1", "id-dsa-with-sha224");
Reg("2.16.840.1.101.3.4.3.2", "id-dsa-with-sha256");
Reg("1.2.840.113549", "rsadsi");
Reg("1.2.840.113549.2", "digestAlgorithm");
Reg("1.2.840.113549.2.7", "id-hmacWithSHA1");
Reg("1.2.840.113549.2.8", "id-hmacWithSHA224");
Reg("1.2.840.113549.2.9", "id-hmacWithSHA256");
Reg("1.2.840.113549.2.10", "id-hmacWithSHA384");
Reg("1.2.840.113549.2.11", "id-hmacWithSHA512");
/*
* From X9.57: http://oid-info.com/get/1.2.840.10040.4
*/
Reg("1.2.840.10040.4", "x9algorithm");
Reg("1.2.840.10040.4", "x9cm");
Reg("1.2.840.10040.4.1", "dsa");
Reg("1.2.840.10040.4.3", "dsa-with-sha1");
/*
* From SEC: http://oid-info.com/get/1.3.14.3.2
*/
Reg("1.3.14.3.2.2", "md4WithRSA");
Reg("1.3.14.3.2.3", "md5WithRSA");
Reg("1.3.14.3.2.4", "md4WithRSAEncryption");
Reg("1.3.14.3.2.12", "dsaSEC");
Reg("1.3.14.3.2.13", "dsaWithSHASEC");
Reg("1.3.14.3.2.27", "dsaWithSHA1SEC");
/*
* From Microsoft: http://oid-info.com/get/1.3.6.1.4.1.311.20.2
*/
Reg("1.3.6.1.4.1.311.20.2", "ms-certType");
Reg("1.3.6.1.4.1.311.20.2.2", "ms-smartcardLogon");
Reg("1.3.6.1.4.1.311.20.2.3", "ms-UserPrincipalName");
Reg("1.3.6.1.4.1.311.20.2.3", "ms-UPN");
}
static void Reg(string oid, string name)
{
if (!OIDToName.ContainsKey(oid)) {
OIDToName.Add(oid, name);
}
string nn = Normalize(name);
if (NameToOID.ContainsKey(nn)) {
throw new Exception("OID name collision: " + nn);
}
NameToOID.Add(nn, oid);
/*
* Many names start with 'id-??-' and we want to support
* the short names (without that prefix) as aliases. But
* we must take care of some collisions on short names.
*/
if (name.StartsWith("id-")
&& name.Length >= 7 && name[5] == '-')
{
if (name.StartsWith("id-ad-")) {
Reg(oid, name.Substring(6) + "-IA");
} else if (name.StartsWith("id-kp-")) {
Reg(oid, name.Substring(6) + "-EKU");
} else {
Reg(oid, name.Substring(6));
}
}
}
static string Normalize(string name)
{
StringBuilder sb = new StringBuilder();
foreach (char c in name) {
int d = (int)c;
if (d <= 32 || d == '-') {
continue;
}
if (d >= 'A' && d <= 'Z') {
d += 'a' - 'A';
}
sb.Append((char)c);
}
return sb.ToString();
}
public static string ToName(string oid)
{
return OIDToName.ContainsKey(oid) ? OIDToName[oid] : oid;
}
public static string ToOID(string name)
{
if (IsNumericOID(name)) {
return name;
}
string nn = Normalize(name);
if (!NameToOID.ContainsKey(nn)) {
throw new AsnException(
"unrecognized OID name: " + name);
}
return NameToOID[nn];
}
public static bool IsNumericOID(string oid)
{
/*
* An OID is in numeric format if:
* -- it contains only digits and dots
* -- it does not start or end with a dot
* -- it does not contain two consecutive dots
* -- it contains at least one dot
*/
foreach (char c in oid) {
if (!(c >= '0' && c <= '9') && c != '.') {
return false;
}
}
if (oid.StartsWith(".") || oid.EndsWith(".")) {
return false;
}
if (oid.IndexOf("..") >= 0) {
return false;
}
if (oid.IndexOf('.') < 0) {
return false;
}
return true;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.ServiceModel.Channels;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Dispatcher;
using System.Threading;
using System.Threading.Tasks;
namespace System.ServiceModel
{
public sealed class InstanceContext : CommunicationObject, IExtensibleObject<InstanceContext>
{
private InstanceBehavior _behavior;
private ConcurrencyInstanceContextFacet _concurrency;
private ServiceChannelManager _channels;
private ExtensionCollection<InstanceContext> _extensions;
private object _serviceInstanceLock = new object();
private SynchronizationContext _synchronizationContext;
private object _userObject;
private bool _wellKnown;
private SynchronizedCollection<IChannel> _wmiChannels;
private bool _isUserCreated;
public InstanceContext(object implementation)
: this(implementation, true)
{
}
internal InstanceContext(object implementation, bool isUserCreated)
: this(implementation, true, isUserCreated)
{
}
internal InstanceContext(object implementation, bool wellKnown, bool isUserCreated)
{
if (implementation != null)
{
_userObject = implementation;
_wellKnown = wellKnown;
}
_channels = new ServiceChannelManager(this);
_isUserCreated = isUserCreated;
}
internal InstanceBehavior Behavior
{
get { return _behavior; }
set
{
if (_behavior == null)
{
_behavior = value;
}
}
}
internal ConcurrencyInstanceContextFacet Concurrency
{
get
{
if (_concurrency == null)
{
lock (this.ThisLock)
{
if (_concurrency == null)
_concurrency = new ConcurrencyInstanceContextFacet();
}
}
return _concurrency;
}
}
protected override TimeSpan DefaultCloseTimeout
{
get
{
return ServiceDefaults.CloseTimeout;
}
}
protected override TimeSpan DefaultOpenTimeout
{
get
{
return ServiceDefaults.OpenTimeout;
}
}
public IExtensionCollection<InstanceContext> Extensions
{
get
{
this.ThrowIfClosed();
lock (this.ThisLock)
{
if (_extensions == null)
_extensions = new ExtensionCollection<InstanceContext>(this, this.ThisLock);
return _extensions;
}
}
}
public ICollection<IChannel> IncomingChannels
{
get
{
this.ThrowIfClosed();
return _channels.IncomingChannels;
}
}
public ICollection<IChannel> OutgoingChannels
{
get
{
this.ThrowIfClosed();
return _channels.OutgoingChannels;
}
}
public SynchronizationContext SynchronizationContext
{
get { return _synchronizationContext; }
set
{
this.ThrowIfClosedOrOpened();
_synchronizationContext = value;
}
}
new internal object ThisLock
{
get { return base.ThisLock; }
}
internal object UserObject
{
get { return _userObject; }
}
internal ICollection<IChannel> WmiChannels
{
get
{
if (_wmiChannels == null)
{
lock (this.ThisLock)
{
if (_wmiChannels == null)
{
_wmiChannels = new SynchronizedCollection<IChannel>();
}
}
}
return _wmiChannels;
}
}
protected override void OnAbort()
{
_channels.Abort();
}
internal void BindRpc(ref MessageRpc rpc)
{
this.ThrowIfClosed();
_channels.IncrementActivityCount();
rpc.SuccessfullyBoundInstance = true;
}
internal void FaultInternal()
{
this.Fault();
}
public object GetServiceInstance(Message message)
{
lock (_serviceInstanceLock)
{
this.ThrowIfClosedOrNotOpen();
object current = _userObject;
if (current != null)
{
return current;
}
if (_behavior == null)
{
Exception error = new InvalidOperationException(SR.SFxInstanceNotInitialized);
if (message != null)
{
throw TraceUtility.ThrowHelperError(error, message);
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(error);
}
}
object newUserObject;
if (message != null)
{
newUserObject = _behavior.GetInstance(this, message);
}
else
{
newUserObject = _behavior.GetInstance(this);
}
if (newUserObject != null)
{
SetUserObject(newUserObject);
}
return newUserObject;
}
}
protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
return new CloseAsyncResult(timeout, callback, state, this);
}
protected override void OnEndClose(IAsyncResult result)
{
CloseAsyncResult.End(result);
}
protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return new CompletedAsyncResult(callback, state);
}
protected override void OnEndOpen(IAsyncResult result)
{
CompletedAsyncResult.End(result);
}
protected override void OnClose(TimeSpan timeout)
{
_channels.Close(timeout);
}
protected override void OnOpen(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
}
protected override void OnOpened()
{
base.OnOpened();
}
protected override void OnOpening()
{
base.OnOpening();
}
protected internal override Task OnCloseAsync(TimeSpan timeout)
{
this.OnClose(timeout);
return TaskHelpers.CompletedTask();
}
protected internal override Task OnOpenAsync(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
return TaskHelpers.CompletedTask();
}
void SetUserObject(object newUserObject)
{
if (_behavior != null && !_wellKnown)
{
object oldUserObject = Interlocked.Exchange(ref _userObject, newUserObject);
}
}
internal void UnbindRpc(ref MessageRpc rpc)
{
if (rpc.InstanceContext == this && rpc.SuccessfullyBoundInstance)
{
_channels.DecrementActivityCount();
}
}
internal class CloseAsyncResult : AsyncResult
{
private InstanceContext _instanceContext;
private TimeoutHelper _timeoutHelper;
public CloseAsyncResult(TimeSpan timeout, AsyncCallback callback, object state, InstanceContext instanceContext)
: base(callback, state)
{
_timeoutHelper = new TimeoutHelper(timeout);
_instanceContext = instanceContext;
IAsyncResult result = _instanceContext._channels.BeginClose(_timeoutHelper.RemainingTime(), PrepareAsyncCompletion(new AsyncCompletion(CloseChannelsCallback)), this);
if (result.CompletedSynchronously && CloseChannelsCallback(result))
{
base.Complete(true);
}
}
public static void End(IAsyncResult result)
{
AsyncResult.End<CloseAsyncResult>(result);
}
private bool CloseChannelsCallback(IAsyncResult result)
{
Fx.Assert(object.ReferenceEquals(this, result.AsyncState), "AsyncState should be this");
_instanceContext._channels.EndClose(result);
return true;
}
}
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Reactive;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using Microsoft.Reactive.Testing;
using Avalonia.Data;
using Avalonia.Markup.Data;
using Avalonia.UnitTests;
using Xunit;
using System.Threading.Tasks;
namespace Avalonia.Markup.UnitTests.Data
{
public class ExpressionObserverTests_Property
{
[Fact]
public async Task Should_Get_Simple_Property_Value()
{
var data = new { Foo = "foo" };
var target = new ExpressionObserver(data, "Foo");
var result = await target.Take(1);
Assert.Equal("foo", result);
GC.KeepAlive(data);
}
[Fact]
public void Should_Get_Simple_Property_Value_Type()
{
var data = new { Foo = "foo" };
var target = new ExpressionObserver(data, "Foo");
target.Subscribe(_ => { });
Assert.Equal(typeof(string), target.ResultType);
GC.KeepAlive(data);
}
[Fact]
public async Task Should_Get_Simple_Property_Value_Null()
{
var data = new { Foo = (string)null };
var target = new ExpressionObserver(data, "Foo");
var result = await target.Take(1);
Assert.Null(result);
GC.KeepAlive(data);
}
[Fact]
public async Task Should_Get_Simple_Property_From_Base_Class()
{
var data = new Class3 { Foo = "foo" };
var target = new ExpressionObserver(data, "Foo");
var result = await target.Take(1);
Assert.Equal("foo", result);
GC.KeepAlive(data);
}
[Fact]
public async Task Should_Return_BindingNotification_Error_For_Root_Null()
{
var data = new Class3 { Foo = "foo" };
var target = new ExpressionObserver(default(object), "Foo");
var result = await target.Take(1);
Assert.Equal(
new BindingNotification(
new MarkupBindingChainException("Null value", "Foo", string.Empty),
BindingErrorType.Error,
AvaloniaProperty.UnsetValue),
result);
GC.KeepAlive(data);
}
[Fact]
public async Task Should_Return_BindingNotification_Error_For_Root_UnsetValue()
{
var data = new Class3 { Foo = "foo" };
var target = new ExpressionObserver(AvaloniaProperty.UnsetValue, "Foo");
var result = await target.Take(1);
Assert.Equal(
new BindingNotification(
new MarkupBindingChainException("Null value", "Foo", string.Empty),
BindingErrorType.Error,
AvaloniaProperty.UnsetValue),
result);
GC.KeepAlive(data);
}
[Fact]
public async Task Should_Return_BindingNotification_Error_For_Observable_Root_Null()
{
var data = new Class3 { Foo = "foo" };
var target = new ExpressionObserver(Observable.Return(default(object)), "Foo");
var result = await target.Take(1);
Assert.Equal(
new BindingNotification(
new MarkupBindingChainException("Null value", "Foo", string.Empty),
BindingErrorType.Error,
AvaloniaProperty.UnsetValue),
result);
GC.KeepAlive(data);
}
[Fact]
public async void Should_Return_BindingNotification_Error_For_Observable_Root_UnsetValue()
{
var data = new Class3 { Foo = "foo" };
var target = new ExpressionObserver(Observable.Return(AvaloniaProperty.UnsetValue), "Foo");
var result = await target.Take(1);
Assert.Equal(
new BindingNotification(
new MarkupBindingChainException("Null value", "Foo", string.Empty),
BindingErrorType.Error,
AvaloniaProperty.UnsetValue),
result);
GC.KeepAlive(data);
}
[Fact]
public async Task Should_Get_Simple_Property_Chain()
{
var data = new { Foo = new { Bar = new { Baz = "baz" } } };
var target = new ExpressionObserver(data, "Foo.Bar.Baz");
var result = await target.Take(1);
Assert.Equal("baz", result);
GC.KeepAlive(data);
}
[Fact]
public void Should_Get_Simple_Property_Chain_Type()
{
var data = new { Foo = new { Bar = new { Baz = "baz" } } };
var target = new ExpressionObserver(data, "Foo.Bar.Baz");
target.Subscribe(_ => { });
Assert.Equal(typeof(string), target.ResultType);
GC.KeepAlive(data);
}
[Fact]
public async Task Should_Return_BindingNotification_Error_For_Broken_Chain()
{
var data = new { Foo = new { Bar = 1 } };
var target = new ExpressionObserver(data, "Foo.Bar.Baz");
var result = await target.Take(1);
Assert.IsType<BindingNotification>(result);
Assert.Equal(
new BindingNotification(
new MissingMemberException("Could not find CLR property 'Baz' on '1'"), BindingErrorType.Error),
result);
GC.KeepAlive(data);
}
[Fact]
public void Should_Return_BindingNotification_Error_For_Chain_With_Null_Value()
{
var data = new { Foo = default(object) };
var target = new ExpressionObserver(data, "Foo.Bar.Baz");
var result = new List<object>();
target.Subscribe(x => result.Add(x));
Assert.Equal(
new[]
{
new BindingNotification(
new MarkupBindingChainException("Null value", "Foo.Bar.Baz", "Foo"),
BindingErrorType.Error,
AvaloniaProperty.UnsetValue),
},
result);
GC.KeepAlive(data);
}
[Fact]
public void Should_Have_Null_ResultType_For_Broken_Chain()
{
var data = new { Foo = new { Bar = 1 } };
var target = new ExpressionObserver(data, "Foo.Bar.Baz");
Assert.Null(target.ResultType);
GC.KeepAlive(data);
}
[Fact]
public void Should_Track_Simple_Property_Value()
{
var data = new Class1 { Foo = "foo" };
var target = new ExpressionObserver(data, "Foo");
var result = new List<object>();
var sub = target.Subscribe(x => result.Add(x));
data.Foo = "bar";
Assert.Equal(new[] { "foo", "bar" }, result);
sub.Dispose();
Assert.Equal(0, data.PropertyChangedSubscriptionCount);
GC.KeepAlive(data);
}
[Fact]
public void Should_Trigger_PropertyChanged_On_Null_Or_Empty_String()
{
var data = new Class1 { Bar = "foo" };
var target = new ExpressionObserver(data, "Bar");
var result = new List<object>();
var sub = target.Subscribe(x => result.Add(x));
Assert.Equal(new[] { "foo" }, result);
data.Bar = "bar";
Assert.Equal(new[] { "foo" }, result);
data.RaisePropertyChanged(string.Empty);
Assert.Equal(new[] { "foo", "bar" }, result);
data.RaisePropertyChanged(null);
Assert.Equal(new[] { "foo", "bar", "bar" }, result);
sub.Dispose();
Assert.Equal(0, data.PropertyChangedSubscriptionCount);
GC.KeepAlive(data);
}
[Fact]
public void Should_Track_End_Of_Property_Chain_Changing()
{
var data = new Class1 { Next = new Class2 { Bar = "bar" } };
var target = new ExpressionObserver(data, "Next.Bar");
var result = new List<object>();
var sub = target.Subscribe(x => result.Add(x));
((Class2)data.Next).Bar = "baz";
((Class2)data.Next).Bar = null;
Assert.Equal(new[] { "bar", "baz", null }, result);
sub.Dispose();
Assert.Equal(0, data.PropertyChangedSubscriptionCount);
Assert.Equal(0, data.Next.PropertyChangedSubscriptionCount);
GC.KeepAlive(data);
}
[Fact]
public void Should_Track_Property_Chain_Changing()
{
var data = new Class1 { Next = new Class2 { Bar = "bar" } };
var target = new ExpressionObserver(data, "Next.Bar");
var result = new List<object>();
var sub = target.Subscribe(x => result.Add(x));
var old = data.Next;
data.Next = new Class2 { Bar = "baz" };
data.Next = new Class2 { Bar = null };
Assert.Equal(new[] { "bar", "baz", null }, result);
sub.Dispose();
Assert.Equal(0, data.PropertyChangedSubscriptionCount);
Assert.Equal(0, data.Next.PropertyChangedSubscriptionCount);
Assert.Equal(0, old.PropertyChangedSubscriptionCount);
GC.KeepAlive(data);
}
[Fact]
public void Should_Track_Property_Chain_Breaking_With_Null_Then_Mending()
{
var data = new Class1
{
Next = new Class2
{
Next = new Class2
{
Bar = "bar"
}
}
};
var target = new ExpressionObserver(data, "Next.Next.Bar");
var result = new List<object>();
var sub = target.Subscribe(x => result.Add(x));
var old = data.Next;
data.Next = new Class2 { Bar = "baz" };
data.Next = old;
Assert.Equal(
new object[]
{
"bar",
new BindingNotification(
new MarkupBindingChainException("Null value", "Next.Next.Bar", "Next.Next"),
BindingErrorType.Error,
AvaloniaProperty.UnsetValue),
"bar"
},
result);
sub.Dispose();
Assert.Equal(0, data.PropertyChangedSubscriptionCount);
Assert.Equal(0, data.Next.PropertyChangedSubscriptionCount);
Assert.Equal(0, old.PropertyChangedSubscriptionCount);
GC.KeepAlive(data);
}
[Fact]
public void Should_Track_Property_Chain_Breaking_With_Missing_Member_Then_Mending()
{
var data = new Class1 { Next = new Class2 { Bar = "bar" } };
var target = new ExpressionObserver(data, "Next.Bar");
var result = new List<object>();
var sub = target.Subscribe(x => result.Add(x));
var old = data.Next;
var breaking = new WithoutBar();
data.Next = breaking;
data.Next = new Class2 { Bar = "baz" };
Assert.Equal(
new object[]
{
"bar",
new BindingNotification(
new MissingMemberException("Could not find CLR property 'Bar' on 'Avalonia.Markup.UnitTests.Data.ExpressionObserverTests_Property+WithoutBar'"),
BindingErrorType.Error),
"baz",
},
result);
sub.Dispose();
Assert.Equal(0, data.PropertyChangedSubscriptionCount);
Assert.Equal(0, data.Next.PropertyChangedSubscriptionCount);
Assert.Equal(0, breaking.PropertyChangedSubscriptionCount);
Assert.Equal(0, old.PropertyChangedSubscriptionCount);
GC.KeepAlive(data);
}
[Fact]
public void Empty_Expression_Should_Track_Root()
{
var data = new Class1 { Foo = "foo" };
var update = new Subject<Unit>();
var target = new ExpressionObserver(() => data.Foo, "", update);
var result = new List<object>();
target.Subscribe(x => result.Add(x));
data.Foo = "bar";
update.OnNext(Unit.Default);
Assert.Equal(new[] { "foo", "bar" }, result);
GC.KeepAlive(data);
}
[Fact]
public void Should_Track_Property_Value_From_Observable_Root()
{
var scheduler = new TestScheduler();
var source = scheduler.CreateColdObservable(
OnNext(1, new Class1 { Foo = "foo" }),
OnNext(2, new Class1 { Foo = "bar" }));
var target = new ExpressionObserver(source, "Foo");
var result = new List<object>();
using (target.Subscribe(x => result.Add(x)))
{
scheduler.Start();
}
Assert.Equal(new[] { "foo", "bar" }, result);
Assert.All(source.Subscriptions, x => Assert.NotEqual(Subscription.Infinite, x.Unsubscribe));
}
[Fact]
public void Subscribing_Multiple_Times_Should_Return_Values_To_All()
{
var data = new Class1 { Foo = "foo" };
var target = new ExpressionObserver(data, "Foo");
var result1 = new List<object>();
var result2 = new List<object>();
var result3 = new List<object>();
target.Subscribe(x => result1.Add(x));
target.Subscribe(x => result2.Add(x));
data.Foo = "bar";
target.Subscribe(x => result3.Add(x));
Assert.Equal(new[] { "foo", "bar" }, result1);
Assert.Equal(new[] { "foo", "bar" }, result2);
Assert.Equal(new[] { "bar" }, result3);
GC.KeepAlive(data);
}
[Fact]
public void Subscribing_Multiple_Times_Should_Only_Add_PropertyChanged_Handlers_Once()
{
var data = new Class1 { Foo = "foo" };
var target = new ExpressionObserver(data, "Foo");
var sub1 = target.Subscribe(x => { });
var sub2 = target.Subscribe(x => { });
Assert.Equal(1, data.PropertyChangedSubscriptionCount);
sub1.Dispose();
sub2.Dispose();
Assert.Equal(0, data.PropertyChangedSubscriptionCount);
GC.KeepAlive(data);
}
[Fact]
public void SetValue_Should_Set_Simple_Property_Value()
{
var data = new Class1 { Foo = "foo" };
var target = new ExpressionObserver(data, "Foo");
using (target.Subscribe(_ => { }))
{
Assert.True(target.SetValue("bar"));
}
Assert.Equal("bar", data.Foo);
GC.KeepAlive(data);
}
[Fact]
public void SetValue_Should_Set_Property_At_The_End_Of_Chain()
{
var data = new Class1 { Next = new Class2 { Bar = "bar" } };
var target = new ExpressionObserver(data, "Next.Bar");
using (target.Subscribe(_ => { }))
{
Assert.True(target.SetValue("baz"));
}
Assert.Equal("baz", ((Class2)data.Next).Bar);
GC.KeepAlive(data);
}
[Fact]
public void SetValue_Should_Return_False_For_Missing_Property()
{
var data = new Class1 { Next = new WithoutBar() };
var target = new ExpressionObserver(data, "Next.Bar");
using (target.Subscribe(_ => { }))
{
Assert.False(target.SetValue("baz"));
}
GC.KeepAlive(data);
}
[Fact]
public void SetValue_Should_Notify_New_Value_With_Inpc()
{
var data = new Class1();
var target = new ExpressionObserver(data, "Foo");
var result = new List<object>();
target.Subscribe(x => result.Add(x));
target.SetValue("bar");
Assert.Equal(new[] { null, "bar" }, result);
GC.KeepAlive(data);
}
[Fact]
public void SetValue_Should_Notify_New_Value_Without_Inpc()
{
var data = new Class1();
var target = new ExpressionObserver(data, "Bar");
var result = new List<object>();
target.Subscribe(x => result.Add(x));
target.SetValue("bar");
Assert.Equal(new[] { null, "bar" }, result);
GC.KeepAlive(data);
}
[Fact]
public void SetValue_Should_Return_False_For_Missing_Object()
{
var data = new Class1();
var target = new ExpressionObserver(data, "Next.Bar");
using (target.Subscribe(_ => { }))
{
Assert.False(target.SetValue("baz"));
}
GC.KeepAlive(data);
}
[Fact]
public void Can_Replace_Root()
{
var first = new Class1 { Foo = "foo" };
var second = new Class1 { Foo = "bar" };
var root = first;
var update = new Subject<Unit>();
var target = new ExpressionObserver(() => root, "Foo", update);
var result = new List<object>();
var sub = target.Subscribe(x => result.Add(x));
root = second;
update.OnNext(Unit.Default);
root = null;
update.OnNext(Unit.Default);
Assert.Equal(
new object[]
{
"foo",
"bar",
new BindingNotification(
new MarkupBindingChainException("Null value", "Foo", string.Empty),
BindingErrorType.Error,
AvaloniaProperty.UnsetValue)
},
result);
Assert.Equal(0, first.PropertyChangedSubscriptionCount);
Assert.Equal(0, second.PropertyChangedSubscriptionCount);
GC.KeepAlive(first);
GC.KeepAlive(second);
}
[Fact]
public void Should_Not_Keep_Source_Alive()
{
Func<Tuple<ExpressionObserver, WeakReference>> run = () =>
{
var source = new Class1 { Foo = "foo" };
var target = new ExpressionObserver(source, "Foo");
return Tuple.Create(target, new WeakReference(source));
};
var result = run();
result.Item1.Subscribe(x => { });
GC.Collect();
Assert.Null(result.Item2.Target);
}
private interface INext
{
int PropertyChangedSubscriptionCount { get; }
}
private class Class1 : NotifyingBase
{
private string _foo;
private INext _next;
public string Foo
{
get { return _foo; }
set
{
_foo = value;
RaisePropertyChanged(nameof(Foo));
}
}
private string _bar;
public string Bar
{
get { return _bar; }
set { _bar = value; }
}
public INext Next
{
get { return _next; }
set
{
_next = value;
RaisePropertyChanged(nameof(Next));
}
}
}
private class Class2 : NotifyingBase, INext
{
private string _bar;
private INext _next;
public string Bar
{
get { return _bar; }
set
{
_bar = value;
RaisePropertyChanged(nameof(Bar));
}
}
public INext Next
{
get { return _next; }
set
{
_next = value;
RaisePropertyChanged(nameof(Next));
}
}
}
private class Class3 : Class1
{
}
private class WithoutBar : NotifyingBase, INext
{
}
private Recorded<Notification<object>> OnNext(long time, object value)
{
return new Recorded<Notification<object>>(time, Notification.CreateOnNext<object>(value));
}
}
}
| |
using System;
using Autofac.Builder;
using Autofac.Core.Lifetime;
using NUnit.Framework;
using Autofac.Core;
using System.Collections.Generic;
namespace Autofac.Tests
{
[TestFixture]
public class TagsFixture
{
public class HomeController
{
public HomeController()
{
}
}
public enum Tag { None, Outer, Middle, Inner }
[Test]
public void OuterSatisfiesInnerResolutions()
{
var builder = new ContainerBuilder();
var instantiations = 0;
builder.Register(c => { instantiations++; return ""; }).InstancePerMatchingLifetimeScope(LifetimeScope.RootTag);
var root = builder.Build();
var middle = root.BeginLifetimeScope(Tag.Middle);
var inner = middle.BeginLifetimeScope(Tag.Inner);
middle.Resolve<string>();
root.Resolve<string>();
inner.Resolve<string>();
Assert.AreEqual(1, instantiations);
}
[Test]
public void AnonymousInnerContainer()
{
var builder = new ContainerBuilder();
var instantiations = 0;
builder.Register(c => { instantiations++; return ""; })
.InstancePerMatchingLifetimeScope(LifetimeScope.RootTag);
var root = builder.Build();
var anon = root.BeginLifetimeScope();
anon.Resolve<string>();
root.Resolve<string>();
Assert.AreEqual(1, instantiations);
}
[Test]
[ExpectedException(typeof(DependencyResolutionException))]
public void InnerRegistrationNotAccessibleToOuter()
{
var builder = new ContainerBuilder();
builder.Register(c => "")
.InstancePerMatchingLifetimeScope(Tag.Middle);
var outer = builder.Build();
Assert.IsTrue(outer.IsRegistered<string>());
outer.Resolve<string>();
}
[Test]
public void TaggedRegistrationsAccessibleThroughNames()
{
var name = "Name";
var builder = new ContainerBuilder();
builder.Register(c => "")
.InstancePerMatchingLifetimeScope(LifetimeScope.RootTag)
.Named<string>(name);
var outer = builder.Build();
var s = outer.ResolveNamed<string>(name);
Assert.IsNotNull(s);
}
[Test]
public void CorrectScopeMaintainsOwnership()
{
var builder = new ContainerBuilder();
builder.Register(c => new DisposeTracker())
.InstancePerMatchingLifetimeScope(LifetimeScope.RootTag);
var container = builder.Build();
var inner = container.BeginLifetimeScope();
var dt = inner.Resolve<DisposeTracker>();
Assert.IsFalse(dt.IsDisposed);
inner.Dispose();
Assert.IsFalse(dt.IsDisposed);
container.Dispose();
Assert.IsTrue(dt.IsDisposed);
}
[Test]
public void DefaultSingletonSemanticsCorrect()
{
var builder = new ContainerBuilder();
builder.Register(c => new object()).InstancePerMatchingLifetimeScope(LifetimeScope.RootTag);
var container = builder.Build();
var inner = container.BeginLifetimeScope();
Assert.AreSame(container.Resolve<object>(), inner.Resolve<object>());
}
[Test]
public void ReflectiveRegistration()
{
var builder = new ContainerBuilder();
builder.RegisterType(typeof(object)).InstancePerMatchingLifetimeScope(LifetimeScope.RootTag);
var container = builder.Build();
Assert.IsNotNull(container.Resolve<object>());
}
[Test]
public void CollectionsAreTaggable()
{
var builder = new ContainerBuilder();
builder.RegisterCollection<object>("o")
.InstancePerMatchingLifetimeScope("tag")
.As(typeof(IList<object>));
var outer = builder.Build();
var inner = outer.BeginLifetimeScope("tag");
var coll = inner.Resolve<IList<object>>();
Assert.IsNotNull(coll);
var threw = false;
try
{
outer.Resolve<IList<object>>();
}
catch (Exception)
{
threw = true;
}
Assert.IsTrue(threw);
}
[Test]
public void GenericsAreTaggable()
{
var builder = new ContainerBuilder();
builder.RegisterGeneric(typeof(List<>))
.InstancePerMatchingLifetimeScope("tag")
.As(typeof(IList<>));
var outer = builder.Build();
var inner = outer.BeginLifetimeScope("tag");
var coll = inner.Resolve<IList<object>>();
Assert.IsNotNull(coll);
var threw = false;
try
{
outer.Resolve<IList<object>>();
}
catch (Exception)
{
threw = true;
}
Assert.IsTrue(threw);
}
[Test]
public void MatchesAgainstMultipleScopes()
{
const string tag1 = "Tag1";
const string tag2 = "Tag2";
var builder = new ContainerBuilder();
builder.Register(c => new object()).InstancePerMatchingLifetimeScope(tag1, tag2);
var container = builder.Build();
var lifetimeScope = container.BeginLifetimeScope(tag1);
Assert.That(lifetimeScope.Resolve<object>(), Is.Not.Null);
lifetimeScope = container.BeginLifetimeScope(tag2);
Assert.That(lifetimeScope.Resolve<object>(), Is.Not.Null);
}
}
}
| |
// -----------------------------------------------------------------------
// <copyright file="ActorContext.cs" company="Asynkron HB">
// Copyright (C) 2015-2018 Asynkron HB All rights reserved
// </copyright>
// -----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Proto.Mailbox;
using static Proto.Actor;
namespace Proto
{
internal enum ContextState : byte
{
Alive,
Restarting,
Stopping,
Stopped,
}
//Angels cry over this code, but it serves a purpose, lazily init of less frequently used features
public class ActorContextExtras
{
public ImmutableHashSet<PID> Children { get; private set; } = ImmutableHashSet<PID>.Empty;
public Timer ReceiveTimeoutTimer { get; private set; }
public RestartStatistics RestartStatistics { get; } = new RestartStatistics(0, null);
public Stack<object> Stash { get; } = new Stack<object>();
public ImmutableHashSet<PID> Watchers { get; private set; } = ImmutableHashSet<PID>.Empty;
public IContext Context { get; }
public ActorContextExtras(IContext context)
{
Context = context;
}
public void InitReceiveTimeoutTimer(Timer timer) => ReceiveTimeoutTimer = timer;
public void ResetReceiveTimeoutTimer(TimeSpan timeout) => ReceiveTimeoutTimer?.Change(timeout, timeout);
public void StopReceiveTimeoutTimer() => ReceiveTimeoutTimer?.Change(-1, -1);
public void KillreceiveTimeoutTimer()
{
ReceiveTimeoutTimer.Dispose();
ReceiveTimeoutTimer = null;
}
public void AddChild(PID pid) => Children = Children.Add(pid);
public void RemoveChild(PID msgWho) => Children = Children.Remove(msgWho);
public void Watch(PID watcher)
{
Watchers = Watchers.Add(watcher);
}
public void Unwatch(PID watcher)
{
Watchers = Watchers.Remove(watcher);
}
}
public class ActorContext : IMessageInvoker, IContext, ISupervisor
{
public static readonly ImmutableHashSet<PID> EmptyChildren = ImmutableHashSet<PID>.Empty;
private readonly Props _props;
private ActorContextExtras _extras;
private object _messageOrEnvelope;
private ContextState _state;
private ActorContextExtras EnsureExtras()
{
if (_extras == null)
{
var context = _props?.ContextDecoratorChain(this) ?? this;
_extras = new ActorContextExtras(context);
}
return _extras ;
}
public ActorContext(Props props, PID parent)
{
_props = props;
//Parents are implicitly watching the child
//The parent is not part of the Watchers set
Parent = parent;
IncarnateActor();
}
private static ILogger Logger { get; } = Log.CreateLogger<ActorContext>();
public IImmutableSet<PID> Children => _extras?.Children ?? EmptyChildren;
IReadOnlyCollection<PID> IContext.Children => Children;
public IActor Actor { get; private set; }
public PID Parent { get; }
public PID Self { get; set; }
public object Message => MessageEnvelope.UnwrapMessage(_messageOrEnvelope);
public PID Sender => MessageEnvelope.UnwrapSender(_messageOrEnvelope);
public MessageHeader Headers => MessageEnvelope.UnwrapHeader(_messageOrEnvelope);
public TimeSpan ReceiveTimeout { get; private set; }
public void Stash() => EnsureExtras().Stash.Push(Message);
public void Respond(object message) => Send(Sender, message);
public PID Spawn(Props props)
{
var id = ProcessRegistry.Instance.NextId();
return SpawnNamed(props, id);
}
public PID SpawnPrefix(Props props, string prefix)
{
var name = prefix + ProcessRegistry.Instance.NextId();
return SpawnNamed(props, name);
}
public PID SpawnNamed(Props props, string name)
{
if (props.GuardianStrategy != null)
{
throw new ArgumentException("Props used to spawn child cannot have GuardianStrategy.");
}
var pid = props.Spawn($"{Self.Id}/{name}", Self);
EnsureExtras().AddChild(pid);
return pid;
}
public void Watch(PID pid) => pid.SendSystemMessage(new Watch(Self));
public void Unwatch(PID pid) => pid.SendSystemMessage(new Unwatch(Self));
public void SetReceiveTimeout(TimeSpan duration)
{
if (duration <= TimeSpan.Zero)
{
throw new ArgumentOutOfRangeException(nameof(duration), duration, "Duration must be greater than zero");
}
if (duration == ReceiveTimeout)
{
return;
}
ReceiveTimeout = duration;
EnsureExtras();
_extras.StopReceiveTimeoutTimer();
if (_extras.ReceiveTimeoutTimer == null)
{
_extras.InitReceiveTimeoutTimer(new Timer(ReceiveTimeoutCallback, null, ReceiveTimeout,
ReceiveTimeout));
}
else
{
_extras.ResetReceiveTimeoutTimer(ReceiveTimeout);
}
}
public void CancelReceiveTimeout()
{
if (_extras?.ReceiveTimeoutTimer == null)
{
return;
}
_extras.StopReceiveTimeoutTimer();
_extras.KillreceiveTimeoutTimer();
ReceiveTimeout = TimeSpan.Zero;
}
public void Send(PID target, object message) => SendUserMessage(target, message);
public void Forward(PID target)
{
if (_messageOrEnvelope is SystemMessage)
{
//SystemMessage cannot be forwarded
Logger.LogWarning("SystemMessage cannot be forwarded. {0}", _messageOrEnvelope);
return;
}
SendUserMessage(target, _messageOrEnvelope);
}
public void Request(PID target, object message)
{
var messageEnvelope = new MessageEnvelope(message, Self, null);
SendUserMessage(target, messageEnvelope);
}
public Task<T> RequestAsync<T>(PID target, object message, TimeSpan timeout)
=> RequestAsync(target, message, new FutureProcess<T>(timeout));
public Task<T> RequestAsync<T>(PID target, object message, CancellationToken cancellationToken)
=> RequestAsync(target, message, new FutureProcess<T>(cancellationToken));
public Task<T> RequestAsync<T>(PID target, object message)
=> RequestAsync(target, message, new FutureProcess<T>());
public void ReenterAfter<T>(Task<T> target, Func<Task<T>, Task> action)
{
var msg = _messageOrEnvelope;
var cont = new Continuation(() => action(target), msg);
target.ContinueWith(t => { Self.SendSystemMessage(cont); });
}
public void ReenterAfter(Task target, Action action)
{
var msg = _messageOrEnvelope;
var cont = new Continuation(() =>
{
action();
return Done;
}, msg);
target.ContinueWith(t => { Self.SendSystemMessage(cont); });
}
public void EscalateFailure(Exception reason, object message)
{
var failure = new Failure(Self, reason, EnsureExtras().RestartStatistics, message);
Self.SendSystemMessage(SuspendMailbox.Instance);
if (Parent == null)
{
HandleRootFailure(failure);
}
else
{
Parent.SendSystemMessage(failure);
}
}
public void RestartChildren(Exception reason, params PID[] pids) => pids.SendSystemNessage(new Restart(reason));
public void StopChildren(params PID[] pids) => pids.SendSystemNessage(Stop.Instance);
public void ResumeChildren(params PID[] pids) => pids.SendSystemNessage(ResumeMailbox.Instance);
public Task InvokeSystemMessageAsync(object msg)
{
try
{
switch (msg)
{
case Started s:
return InvokeUserMessageAsync(s);
case Stop _:
return InitiateStopAsync();
case Terminated t:
return HandleTerminatedAsync(t);
case Watch w:
HandleWatch(w);
return Done;
case Unwatch uw:
HandleUnwatch(uw);
return Done;
case Failure f:
HandleFailure(f);
return Done;
case Restart _:
return HandleRestartAsync();
case SuspendMailbox _:
return Done;
case ResumeMailbox _:
return Done;
case Continuation cont:
_messageOrEnvelope = cont.Message;
return cont.Action();
default:
Logger.LogWarning("Unknown system message {0}", msg);
return Done;
}
}
catch (Exception x)
{
Logger.LogError("Error handling SystemMessage {0}", x);
throw;
}
}
public Task InvokeUserMessageAsync(object msg)
{
if (_state == ContextState.Stopped)
{
//already stopped
Logger.LogError("Actor already stopped, ignore user message {0}", msg);
return Done;
}
var influenceTimeout = true;
if (ReceiveTimeout > TimeSpan.Zero)
{
var notInfluenceTimeout = msg is INotInfluenceReceiveTimeout;
influenceTimeout = !notInfluenceTimeout;
if (influenceTimeout)
{
_extras.StopReceiveTimeoutTimer();
}
}
var res = ProcessMessageAsync(msg);
if (ReceiveTimeout != TimeSpan.Zero && influenceTimeout)
{
//special handle non completed tasks that need to reset ReceiveTimout
if (!res.IsCompleted)
{
return res.ContinueWith(_ => _extras.ResetReceiveTimeoutTimer(ReceiveTimeout));
}
_extras.ResetReceiveTimeoutTimer(ReceiveTimeout);
}
return res;
}
public Task Receive(MessageEnvelope envelope)
{
_messageOrEnvelope = envelope;
return DefaultReceive();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private Task DefaultReceive()
{
if (Message is PoisonPill)
{
Self.Stop();
return Done;
}
//are we using decorators, if so, ensure it has been created
if (_props.ContextDecoratorChain != null)
{
return Actor.ReceiveAsync(EnsureExtras().Context);
}
return Actor.ReceiveAsync(this);
}
private Task ProcessMessageAsync(object msg)
{
//slow path, there is middleware, message must be wrapped in an envelop
if (_props.ReceiverMiddlewareChain != null)
{
return _props.ReceiverMiddlewareChain(EnsureExtras().Context, MessageEnvelope.Wrap(msg));
}
if (_props.ContextDecoratorChain != null)
{
return EnsureExtras().Context.Receive(MessageEnvelope.Wrap(msg));
}
//fast path, 0 alloc invocation of actor receive
_messageOrEnvelope = msg;
return DefaultReceive();
}
private Task<T> RequestAsync<T>(PID target, object message, FutureProcess<T> future)
{
var messageEnvelope = new MessageEnvelope(message, future.Pid, null);
SendUserMessage(target, messageEnvelope);
return future.Task;
}
private void SendUserMessage(PID target, object message)
{
if (_props.SenderMiddlewareChain != null)
{
//slow path
_props.SenderMiddlewareChain(EnsureExtras().Context, target, MessageEnvelope.Wrap(message));
}
else
{
//fast path, 0 alloc
target.SendUserMessage(message);
}
}
private void IncarnateActor()
{
_state = ContextState.Alive;
Actor = _props.Producer();
}
private async Task HandleRestartAsync()
{
_state = ContextState.Restarting;
CancelReceiveTimeout();
await InvokeUserMessageAsync(Restarting.Instance);
await StopAllChildren();
}
private void HandleUnwatch(Unwatch uw) => _extras?.Unwatch(uw.Watcher);
private void HandleWatch(Watch w)
{
if (_state >= ContextState.Stopping)
{
w.Watcher.SendSystemMessage(Terminated.From(Self));
}
else
{
EnsureExtras().Watch(w.Watcher);
}
}
private void HandleFailure(Failure msg)
{
switch (Actor)
{
case ISupervisorStrategy supervisor:
supervisor.HandleFailure(this, msg.Who, msg.RestartStatistics, msg.Reason, msg.Message);
break;
default:
_props.SupervisorStrategy.HandleFailure(this, msg.Who, msg.RestartStatistics, msg.Reason, msg.Message);
break;
}
}
private async Task HandleTerminatedAsync(Terminated msg)
{
_extras?.RemoveChild(msg.Who);
await InvokeUserMessageAsync(msg);
if (_state == ContextState.Stopping || _state == ContextState.Restarting)
{
await TryRestartOrStopAsync();
}
}
private void HandleRootFailure(Failure failure)
{
Supervision.DefaultStrategy.HandleFailure(this, failure.Who, failure.RestartStatistics, failure.Reason, failure.Message);
}
//Initiate stopping, not final
private async Task InitiateStopAsync()
{
if (_state >= ContextState.Stopping)
{
//already stopping or stopped
return;
}
_state = ContextState.Stopping;
CancelReceiveTimeout();
//this is intentional
await InvokeUserMessageAsync(Stopping.Instance);
await StopAllChildren();
}
private async Task StopAllChildren()
{
_extras?.Children?.Stop();
await TryRestartOrStopAsync();
}
//intermediate stopping stage, waiting for children to stop
private Task TryRestartOrStopAsync()
{
if (_extras?.Children?.Count > 0)
{
return Done;
}
CancelReceiveTimeout();
switch (_state)
{
case ContextState.Restarting:
return RestartAsync();
case ContextState.Stopping:
return FinalizeStopAsync();
default: return Done;
}
}
//Last and final termination step
private async Task FinalizeStopAsync()
{
ProcessRegistry.Instance.Remove(Self);
//This is intentional
await InvokeUserMessageAsync(Stopped.Instance);
DisposeActorIfDisposable();
//Notify watchers
_extras?.Watchers.SendSystemNessage(Terminated.From(Self));
//Notify parent
Parent?.SendSystemMessage(Terminated.From(Self));
_state = ContextState.Stopped;
}
private async Task RestartAsync()
{
DisposeActorIfDisposable();
IncarnateActor();
Self.SendSystemMessage(ResumeMailbox.Instance);
await InvokeUserMessageAsync(Started.Instance);
if (_extras?.Stash != null)
{
while (_extras.Stash.Any())
{
var msg = _extras.Stash.Pop();
await InvokeUserMessageAsync(msg);
}
}
}
private void DisposeActorIfDisposable()
{
if (Actor is IDisposable disposableActor)
{
disposableActor.Dispose();
}
}
private void ReceiveTimeoutCallback(object state)
{
if (_extras?.ReceiveTimeoutTimer == null)
{
return;
}
CancelReceiveTimeout();
Send(Self, Proto.ReceiveTimeout.Instance);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Orchard.ContentManagement;
using Orchard.ContentManagement.MetaData;
using Orchard.ContentManagement.MetaData.Models;
using Orchard.Core.Common.Models;
using Orchard.Core.Containers.Models;
using Orchard.Core.Containers.Services;
using Orchard.Core.Containers.ViewModels;
using Orchard.Core.Contents;
using Orchard.Core.Contents.ViewModels;
using Orchard.Core.Title.Models;
using Orchard.Data;
using Orchard.DisplayManagement;
using Orchard.Lists.Helpers;
using Orchard.Lists.ViewModels;
using Orchard.Localization;
using Orchard.Logging;
using Orchard.Mvc;
using Orchard.Mvc.Extensions;
using Orchard.UI.Navigation;
using Orchard.UI.Notify;
using ContentOptions = Orchard.Lists.ViewModels.ContentOptions;
using ContentsBulkAction = Orchard.Lists.ViewModels.ContentsBulkAction;
using ListContentsViewModel = Orchard.Lists.ViewModels.ListContentsViewModel;
namespace Orchard.Lists.Controllers {
public class AdminController : Controller {
private readonly IContentManager _contentManager;
private readonly IContentDefinitionManager _contentDefinitionManager;
private readonly IOrchardServices _services;
private readonly IContainerService _containerService;
private readonly IListViewService _listViewService;
private readonly ITransactionManager _transactionManager;
public AdminController(
IOrchardServices services,
IContentDefinitionManager contentDefinitionManager,
IShapeFactory shapeFactory,
IContainerService containerService,
IListViewService listViewService,
ITransactionManager transactionManager) {
_services = services;
_contentManager = services.ContentManager;
_contentDefinitionManager = contentDefinitionManager;
T = NullLocalizer.Instance;
Logger = NullLogger.Instance;
Shape = shapeFactory;
_containerService = containerService;
_listViewService = listViewService;
_transactionManager = transactionManager;
}
public Localizer T { get; set; }
public ILogger Logger { get; set; }
dynamic Shape { get; set; }
public ActionResult Index(Core.Contents.ViewModels.ListContentsViewModel model, PagerParameters pagerParameters) {
var query = _containerService.GetContainersQuery(VersionOptions.Latest);
if (!String.IsNullOrEmpty(model.TypeName)) {
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(model.TypeName);
if (contentTypeDefinition == null)
return HttpNotFound();
model.TypeDisplayName = !String.IsNullOrWhiteSpace(contentTypeDefinition.DisplayName)
? contentTypeDefinition.DisplayName
: contentTypeDefinition.Name;
query = query.ForType(model.TypeName);
}
switch (model.Options.OrderBy) {
case ContentsOrder.Modified:
query = query.OrderByDescending<CommonPartRecord>(cr => cr.ModifiedUtc);
break;
case ContentsOrder.Published:
query = query.OrderByDescending<CommonPartRecord>(cr => cr.PublishedUtc);
break;
case ContentsOrder.Created:
query = query.OrderByDescending<CommonPartRecord>(cr => cr.CreatedUtc);
break;
}
model.Options.SelectedFilter = model.TypeName;
model.Options.FilterOptions = _containerService.GetContainerTypes()
.Select(ctd => new KeyValuePair<string, string>(ctd.Name, ctd.DisplayName))
.ToList().OrderBy(kvp => kvp.Value);
var pager = new Pager(_services.WorkContext.CurrentSite, pagerParameters);
var pagerShape = Shape.Pager(pager).TotalItemCount(query.Count());
var pageOfLists = query.Slice(pager.GetStartIndex(), pager.PageSize);
var listsShape = Shape.List();
listsShape.AddRange(pageOfLists.Select(x => _contentManager.BuildDisplay(x, "SummaryAdmin")).ToList());
var viewModel = Shape.ViewModel()
.Lists(listsShape)
.Pager(pagerShape)
.Options(model.Options);
return View(viewModel);
}
[HttpPost, ActionName("Index")]
[FormValueRequired("submit.Filter")]
public ActionResult ListFilterPOST(ContentOptions options) {
var routeValues = ControllerContext.RouteData.Values;
if (options != null) {
routeValues["Options.OrderBy"] = options.OrderBy;
if (_containerService.GetContainerTypes().Any(ctd => string.Equals(ctd.Name, options.SelectedFilter, StringComparison.OrdinalIgnoreCase))) {
routeValues["id"] = options.SelectedFilter;
}
else {
routeValues.Remove("id");
}
}
return RedirectToAction("Index", routeValues);
}
[HttpPost, ActionName("Index")]
[FormValueRequired("submit.BulkEdit")]
public ActionResult ListPOST(ContentOptions options, IEnumerable<int> itemIds, PagerParameters pagerParameters) {
if (itemIds != null) {
var checkedContentItems = _contentManager.GetMany<ContentItem>(itemIds, VersionOptions.Latest, QueryHints.Empty);
switch (options.BulkAction) {
case ContentsBulkAction.None:
break;
case ContentsBulkAction.PublishNow:
foreach (var item in checkedContentItems) {
if (!_services.Authorizer.Authorize(Orchard.Core.Contents.Permissions.PublishContent, item, T("Couldn't publish selected lists."))) {
_transactionManager.Cancel();
return new HttpUnauthorizedResult();
}
_contentManager.Publish(item);
}
_services.Notifier.Information(T("Lists successfully published."));
break;
case ContentsBulkAction.Unpublish:
foreach (var item in checkedContentItems) {
if (!_services.Authorizer.Authorize(Orchard.Core.Contents.Permissions.PublishContent, item, T("Couldn't unpublish selected lists."))) {
_transactionManager.Cancel();
return new HttpUnauthorizedResult();
}
_contentManager.Unpublish(item);
}
_services.Notifier.Information(T("Lists successfully unpublished."));
break;
case ContentsBulkAction.Remove:
foreach (var item in checkedContentItems) {
if (!_services.Authorizer.Authorize(Orchard.Core.Contents.Permissions.DeleteContent, item, T("Couldn't remove selected lists."))) {
_transactionManager.Cancel();
return new HttpUnauthorizedResult();
}
_contentManager.Remove(item);
}
_services.Notifier.Information(T("Lists successfully removed."));
break;
default:
throw new ArgumentOutOfRangeException();
}
}
return RedirectToAction("Index", new { page = pagerParameters.Page, pageSize = pagerParameters.PageSize });
}
public ActionResult Create(string id) {
if (String.IsNullOrWhiteSpace(id)) {
var containerTypes = _containerService.GetContainerTypes().ToList();
if (containerTypes.Count > 1) {
return RedirectToAction("SelectType");
}
return RedirectToAction("Create", new {id = containerTypes.First().Name});
}
return RedirectToAction("Create", "Admin", new {area = "Contents", id, returnUrl = Url.Action("Index", "Admin", new { area = "Orchard.Lists" })});
}
public ActionResult SelectType() {
var viewModel = Shape.ViewModel().ContainerTypes(_containerService.GetContainerTypes().ToList());
return View(viewModel);
}
public ActionResult List(ListContentsViewModel model, PagerParameters pagerParameters) {
var pager = new Pager(_services.WorkContext.CurrentSite, pagerParameters);
var container = _contentManager.GetLatest(model.ContainerId);
if (container == null || !container.Has<ContainerPart>()) {
return HttpNotFound();
}
model.ContainerDisplayName = container.ContentManager.GetItemMetadata(container).DisplayText;
if (string.IsNullOrEmpty(model.ContainerDisplayName)) {
model.ContainerDisplayName = container.ContentType;
}
var query = GetListContentItemQuery(model.ContainerId);
if (query == null) {
return HttpNotFound();
}
var containerPart = container.As<ContainerPart>();
if (containerPart.EnablePositioning) {
query = OrderByPosition(query);
}
else {
switch (model.Options.OrderBy) {
case SortBy.Modified:
query = query.OrderByDescending<CommonPartRecord>(cr => cr.ModifiedUtc);
break;
case SortBy.Published:
query = query.OrderByDescending<CommonPartRecord>(cr => cr.PublishedUtc);
break;
case SortBy.Created:
query = query.OrderByDescending<CommonPartRecord>(cr => cr.CreatedUtc);
break;
case SortBy.DisplayText:
// Note: This will obviously not work for items without a TitlePart, but we're OK with that.
query = query.OrderBy<TitlePartRecord>(cr => cr.Title);
break;
}
}
var listView = containerPart.AdminListView.BuildDisplay(new BuildListViewDisplayContext {
New = _services.New,
Container = containerPart,
ContentQuery = query,
Pager = pager,
ContainerDisplayName = model.ContainerDisplayName
});
var viewModel = Shape.ViewModel()
.Pager(pager)
.ListView(listView)
.ListViewProvider(containerPart.AdminListView)
.ListViewProviders(_listViewService.Providers.ToList())
.Options(model.Options)
.Container(container)
.ContainerId(model.ContainerId)
.ContainerDisplayName(model.ContainerDisplayName)
.ContainerContentType(container.ContentType)
.ItemContentTypes(container.As<ContainerPart>().ItemContentTypes.ToList())
;
if (containerPart.Is<ContainablePart>()) {
viewModel.ListNavigation(_services.New.ListNavigation(ContainablePart: containerPart.As<ContainablePart>()));
}
return View(viewModel);
}
[HttpPost, ActionName("List")]
[FormValueRequired("submit.Order")]
public ActionResult ListOrderPOST(ContentOptions options) {
var routeValues = ControllerContext.RouteData.Values;
if (options != null) {
routeValues["Options.OrderBy"] = options.OrderBy;
}
return RedirectToAction("List", routeValues);
}
[HttpPost, ActionName("List")]
[FormValueRequired("submit.BulkEdit")]
public ActionResult ListPOST(ContentOptions options, IEnumerable<int> itemIds, int? targetContainerId, PagerParameters pagerParameters, string returnUrl) {
if (itemIds != null) {
switch (options.BulkAction) {
case ContentsBulkAction.None:
break;
case ContentsBulkAction.PublishNow:
if (!BulkPublishNow(itemIds)) {
return new HttpUnauthorizedResult();
}
break;
case ContentsBulkAction.Unpublish:
if (!BulkUnpublish(itemIds)) {
return new HttpUnauthorizedResult();
}
break;
case ContentsBulkAction.Remove:
if (!BulkRemove(itemIds)) {
return new HttpUnauthorizedResult();
}
break;
case ContentsBulkAction.RemoveFromList:
if (!BulkRemoveFromList(itemIds)) {
return new HttpUnauthorizedResult();
}
break;
case ContentsBulkAction.MoveToList:
if (!BulkMoveToList(itemIds, targetContainerId)) {
return new HttpUnauthorizedResult();
}
break;
default:
throw new ArgumentOutOfRangeException();
}
}
return this.RedirectLocal(returnUrl, () => RedirectToAction("List", new { page = pagerParameters.Page, pageSize = pagerParameters.PageSize }));
}
[HttpPost]
public ActionResult Insert(int containerId, int itemId, PagerParameters pagerParameters) {
var container = _containerService.Get(containerId, VersionOptions.Latest);
var item = _contentManager.Get(itemId, VersionOptions.Latest, QueryHints.Empty.ExpandParts<CommonPart, ContainablePart>());
var commonPart = item.As<CommonPart>();
var previousItemContainer = commonPart.Container;
var itemMetadata = _contentManager.GetItemMetadata(item);
var containerMetadata = _contentManager.GetItemMetadata(container);
var position = _containerService.GetFirstPosition(containerId) + 1;
LocalizedString message;
if (previousItemContainer == null) {
message = T("{0} was moved to <a href=\"{1}\">{2}</a>", itemMetadata.DisplayText, Url.RouteUrl(containerMetadata.AdminRouteValues), containerMetadata.DisplayText);
}
else if (previousItemContainer.Id != containerId) {
var previousItemContainerMetadata = _contentManager.GetItemMetadata(commonPart.Container);
message = T("{0} was moved from <a href=\"{3}\">{4}</a> to <a href=\"{1}\">{2}</a>",
itemMetadata.DisplayText,
Url.RouteUrl(containerMetadata.AdminRouteValues),
containerMetadata.DisplayText,
Url.RouteUrl(previousItemContainerMetadata.AdminRouteValues),
previousItemContainerMetadata.DisplayText);
}
else {
message = T("{0} is already part of this list and was moved to the top.", itemMetadata.DisplayText);
}
_containerService.MoveItem(item.As<ContainablePart>(), container, position);
_services.Notifier.Information(message);
return RedirectToAction("List", new { containerId, page = pagerParameters.Page, pageSize = pagerParameters.PageSize });
}
[HttpPost]
public ActionResult UpdatePositions(int containerId, int oldIndex, int newIndex, PagerParameters pagerParameters) {
var pager = new Pager(_services.WorkContext.CurrentSite, pagerParameters);
var query = OrderByPosition(GetListContentItemQuery(containerId));
if (query == null) {
return HttpNotFound();
}
var pageOfContentItems = query.Slice(pager.GetStartIndex(), pager.PageSize).ToList();
var contentItem = pageOfContentItems[oldIndex];
pageOfContentItems.Remove(contentItem);
pageOfContentItems.Insert(newIndex, contentItem);
var index = pager.GetStartIndex() + pageOfContentItems.Count;
foreach (var item in pageOfContentItems.Select(x => x.As<ContainablePart>())) {
item.Position = --index;
RePublish(item);
}
return new EmptyResult();
}
[ActionName("List")]
[HttpPost, FormValueRequired("submit.ListOp")]
public ActionResult ListOperation(int containerId, ListOperation operation, SortBy? sortBy, SortDirection? sortByDirection, PagerParameters pagerParameters) {
var items = _containerService.GetContentItems(containerId, VersionOptions.Latest).Select(x => x.As<ContainablePart>());
switch (operation) {
case ViewModels.ListOperation.Reverse:
_containerService.Reverse(items);
_services.Notifier.Information(T("The list has been reversed."));
break;
case ViewModels.ListOperation.Shuffle:
_containerService.Shuffle(items);
_services.Notifier.Information(T("The list has been shuffled."));
break;
case ViewModels.ListOperation.Sort:
_containerService.Sort(items, sortBy.GetValueOrDefault(), sortByDirection.GetValueOrDefault());
_services.Notifier.Information(T("The list has been sorted."));
break;
default:
_services.Notifier.Error(T("Please select an operation to perform on the list."));
break;
}
return RedirectToAction("List", new {containerId, page = pagerParameters.Page, pageSize = pagerParameters.PageSize});
}
[HttpPost, ActionName("List")]
[FormValueRequired("listViewName")]
public ActionResult ChangeListView(int containerId, string listViewName, PagerParameters pagerParameters) {
var container = _containerService.Get(containerId);
container.Record.AdminListViewName = listViewName;
return RedirectToAction("List", new { containerId, page = pagerParameters.Page, pageSize = pagerParameters.PageSize });
}
/// <summary>
/// Only publishes the content if it is already published.
/// </summary>
private void RePublish(IContent content) {
if(content.ContentItem.VersionRecord.Published)
_contentManager.Publish(content.ContentItem);
}
private IContentQuery<ContentItem> GetListContentItemQuery(int containerId) {
var containableTypes = GetContainableTypes().Select(ctd => ctd.Name).ToList();
if (containableTypes.Count == 0) {
// Force the name to be matched against empty and return no items in the query
containableTypes.Add(string.Empty);
}
var query = _contentManager
.Query(VersionOptions.Latest, containableTypes.ToArray())
.Join<CommonPartRecord>().Where(cr => cr.Container.Id == containerId);
return query;
}
private IContentQuery<ContentItem> OrderByPosition(IContentQuery<ContentItem> query) {
return query.Join<ContainablePartRecord>().OrderByDescending(x => x.Position);
}
private IEnumerable<ContentTypeDefinition> GetContainableTypes() {
return _contentDefinitionManager.ListTypeDefinitions().Where(ctd => ctd.Parts.Any(c => c.PartDefinition.Name == "ContainablePart"));
}
private bool BulkMoveToList(IEnumerable<int> selectedIds, int? targetContainerId) {
if (!targetContainerId.HasValue) {
_services.Notifier.Information(T("Please select the list to move the items to."));
return true;
}
var id = targetContainerId.Value;
var targetContainer = _contentManager.Get<ContainerPart>(id);
if (targetContainer == null) {
_services.Notifier.Information(T("Please select the list to move the items to."));
return true;
}
var itemContentTypes = targetContainer.ItemContentTypes.ToList();
var containerDisplayText = _contentManager.GetItemMetadata(targetContainer).DisplayText ?? targetContainer.ContentItem.ContentType;
var selectedItems = _contentManager.GetMany<ContainablePart>(selectedIds, VersionOptions.Latest, QueryHints.Empty);
foreach (var item in selectedItems) {
if (!_services.Authorizer.Authorize(Orchard.Core.Contents.Permissions.EditContent, item, T("Couldn't move selected content."))) {
return false;
}
// Ensure the item can be in that container.
if (itemContentTypes.Any() && itemContentTypes.All(x => x.Name != item.ContentItem.ContentType)) {
_services.TransactionManager.Cancel();
_services.Notifier.Warning(T("One or more items could not be moved to '{0}' because it is restricted to containing items of type '{1}'.", containerDisplayText, itemContentTypes.Select(x => x.DisplayName).ToOrString(T)));
return true; // todo: transactions
}
_containerService.MoveItem(item, targetContainer);
}
_services.Notifier.Information(T("Content successfully moved to <a href=\"{0}\">{1}</a>.", Url.Action("List", new { containerId = targetContainerId }), containerDisplayText));
return true;
}
private bool BulkRemoveFromList(IEnumerable<int> itemIds) {
var selectedItems = _contentManager.GetMany<ContainablePart>(itemIds, VersionOptions.Latest, QueryHints.Empty);
foreach (var item in selectedItems) {
if (!_services.Authorizer.Authorize(Orchard.Core.Contents.Permissions.EditContent, item, T("Couldn't remove selected content from the list."))) {
_services.TransactionManager.Cancel();
return false;
}
item.As<CommonPart>().Record.Container = null;
_containerService.UpdateItemPath(item.ContentItem);
}
_services.Notifier.Information(T("Content successfully removed from the list."));
return true;
}
private bool BulkRemove(IEnumerable<int> itemIds) {
foreach (var item in itemIds.Select(itemId => _contentManager.GetLatest(itemId))) {
if (!_services.Authorizer.Authorize(Orchard.Core.Contents.Permissions.DeleteContent, item, T("Couldn't remove selected content."))) {
_services.TransactionManager.Cancel();
return false;
}
_contentManager.Remove(item);
}
_services.Notifier.Information(T("Content successfully removed."));
return true;
}
private bool BulkUnpublish(IEnumerable<int> itemIds) {
foreach (var item in itemIds.Select(itemId => _contentManager.GetLatest(itemId))) {
if (!_services.Authorizer.Authorize(Orchard.Core.Contents.Permissions.PublishContent, item, T("Couldn't unpublish selected content."))) {
_services.TransactionManager.Cancel();
return false;
}
_contentManager.Unpublish(item);
}
_services.Notifier.Information(T("Content successfully unpublished."));
return true;
}
private bool BulkPublishNow(IEnumerable<int> itemIds) {
foreach (var item in itemIds.Select(itemId => _contentManager.GetLatest(itemId))) {
if (!_services.Authorizer.Authorize(Orchard.Core.Contents.Permissions.PublishContent, item, T("Couldn't publish selected content."))) {
_services.TransactionManager.Cancel();
return false;
}
_contentManager.Publish(item);
}
_services.Notifier.Information(T("Content successfully published."));
return true;
}
}
}
| |
// 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.Collections.DictionaryBase.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.Collections
{
abstract public partial class DictionaryBase : IDictionary, ICollection, IEnumerable
{
#region Methods and constructors
public void Clear()
{
}
public void CopyTo(Array array, int index)
{
}
protected DictionaryBase()
{
}
public IDictionaryEnumerator GetEnumerator()
{
return default(IDictionaryEnumerator);
}
protected virtual new void OnClear()
{
}
protected virtual new void OnClearComplete()
{
}
protected virtual new Object OnGet(Object key, Object currentValue)
{
return default(Object);
}
protected virtual new void OnInsert(Object key, Object value)
{
}
protected virtual new void OnInsertComplete(Object key, Object value)
{
}
protected virtual new void OnRemove(Object key, Object value)
{
}
protected virtual new void OnRemoveComplete(Object key, Object value)
{
}
protected virtual new void OnSet(Object key, Object oldValue, Object newValue)
{
}
protected virtual new void OnSetComplete(Object key, Object oldValue, Object newValue)
{
}
protected virtual new void OnValidate(Object key, Object value)
{
}
void System.Collections.IDictionary.Add(Object key, Object value)
{
}
bool System.Collections.IDictionary.Contains(Object key)
{
return default(bool);
}
void System.Collections.IDictionary.Remove(Object key)
{
}
IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return default(IEnumerator);
}
#endregion
#region Properties and indexers
public int Count
{
get
{
return default(int);
}
}
protected IDictionary Dictionary
{
get
{
Contract.Ensures(Contract.Result<System.Collections.IDictionary>() != null);
Contract.Ensures(Contract.Result<System.Collections.IDictionary>() == this);
return default(IDictionary);
}
}
protected Hashtable InnerHashtable
{
get
{
Contract.Ensures(Contract.Result<System.Collections.Hashtable>() != null);
return default(Hashtable);
}
}
bool System.Collections.ICollection.IsSynchronized
{
get
{
return default(bool);
}
}
Object System.Collections.ICollection.SyncRoot
{
get
{
return default(Object);
}
}
bool System.Collections.IDictionary.IsFixedSize
{
get
{
return default(bool);
}
}
bool System.Collections.IDictionary.IsReadOnly
{
get
{
return default(bool);
}
}
Object System.Collections.IDictionary.this [Object key]
{
get
{
return default(Object);
}
set
{
}
}
ICollection System.Collections.IDictionary.Keys
{
get
{
return default(ICollection);
}
}
ICollection System.Collections.IDictionary.Values
{
get
{
return default(ICollection);
}
}
#endregion
}
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// A movie rental store.
/// </summary>
public class MovieRentalStore_Core : TypeCore, IStore
{
public MovieRentalStore_Core()
{
this._TypeId = 170;
this._Id = "MovieRentalStore";
this._Schema_Org_Url = "http://schema.org/MovieRentalStore";
string label = "";
GetLabel(out label, "MovieRentalStore", typeof(MovieRentalStore_Core));
this._Label = label;
this._Ancestors = new int[]{266,193,155,252};
this._SubTypes = new int[0];
this._SuperTypes = new int[]{252};
this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,47,75,77,94,95,130,137,36,60,152,156,167};
}
/// <summary>
/// Physical address of the item.
/// </summary>
private Address_Core address;
public Address_Core Address
{
get
{
return address;
}
set
{
address = value;
SetPropertyInstance(address);
}
}
/// <summary>
/// The overall rating, based on a collection of reviews or ratings, of the item.
/// </summary>
private Properties.AggregateRating_Core aggregateRating;
public Properties.AggregateRating_Core AggregateRating
{
get
{
return aggregateRating;
}
set
{
aggregateRating = value;
SetPropertyInstance(aggregateRating);
}
}
/// <summary>
/// The larger organization that this local business is a branch of, if any.
/// </summary>
private BranchOf_Core branchOf;
public BranchOf_Core BranchOf
{
get
{
return branchOf;
}
set
{
branchOf = value;
SetPropertyInstance(branchOf);
}
}
/// <summary>
/// A contact point for a person or organization.
/// </summary>
private ContactPoints_Core contactPoints;
public ContactPoints_Core ContactPoints
{
get
{
return contactPoints;
}
set
{
contactPoints = value;
SetPropertyInstance(contactPoints);
}
}
/// <summary>
/// The basic containment relation between places.
/// </summary>
private ContainedIn_Core containedIn;
public ContainedIn_Core ContainedIn
{
get
{
return containedIn;
}
set
{
containedIn = value;
SetPropertyInstance(containedIn);
}
}
/// <summary>
/// The currency accepted (in <a href=\http://en.wikipedia.org/wiki/ISO_4217\ target=\new\>ISO 4217 currency format</a>).
/// </summary>
private CurrenciesAccepted_Core currenciesAccepted;
public CurrenciesAccepted_Core CurrenciesAccepted
{
get
{
return currenciesAccepted;
}
set
{
currenciesAccepted = value;
SetPropertyInstance(currenciesAccepted);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// Email address.
/// </summary>
private Email_Core email;
public Email_Core Email
{
get
{
return email;
}
set
{
email = value;
SetPropertyInstance(email);
}
}
/// <summary>
/// People working for this organization.
/// </summary>
private Employees_Core employees;
public Employees_Core Employees
{
get
{
return employees;
}
set
{
employees = value;
SetPropertyInstance(employees);
}
}
/// <summary>
/// Upcoming or past events associated with this place or organization.
/// </summary>
private Events_Core events;
public Events_Core Events
{
get
{
return events;
}
set
{
events = value;
SetPropertyInstance(events);
}
}
/// <summary>
/// The fax number.
/// </summary>
private FaxNumber_Core faxNumber;
public FaxNumber_Core FaxNumber
{
get
{
return faxNumber;
}
set
{
faxNumber = value;
SetPropertyInstance(faxNumber);
}
}
/// <summary>
/// A person who founded this organization.
/// </summary>
private Founders_Core founders;
public Founders_Core Founders
{
get
{
return founders;
}
set
{
founders = value;
SetPropertyInstance(founders);
}
}
/// <summary>
/// The date that this organization was founded.
/// </summary>
private FoundingDate_Core foundingDate;
public FoundingDate_Core FoundingDate
{
get
{
return foundingDate;
}
set
{
foundingDate = value;
SetPropertyInstance(foundingDate);
}
}
/// <summary>
/// The geo coordinates of the place.
/// </summary>
private Geo_Core geo;
public Geo_Core Geo
{
get
{
return geo;
}
set
{
geo = value;
SetPropertyInstance(geo);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>.
/// </summary>
private InteractionCount_Core interactionCount;
public InteractionCount_Core InteractionCount
{
get
{
return interactionCount;
}
set
{
interactionCount = value;
SetPropertyInstance(interactionCount);
}
}
/// <summary>
/// The location of the event or organization.
/// </summary>
private Location_Core location;
public Location_Core Location
{
get
{
return location;
}
set
{
location = value;
SetPropertyInstance(location);
}
}
/// <summary>
/// A URL to a map of the place.
/// </summary>
private Maps_Core maps;
public Maps_Core Maps
{
get
{
return maps;
}
set
{
maps = value;
SetPropertyInstance(maps);
}
}
/// <summary>
/// A member of this organization.
/// </summary>
private Members_Core members;
public Members_Core Members
{
get
{
return members;
}
set
{
members = value;
SetPropertyInstance(members);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code><time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\>Tuesdays and Thursdays 4-8pm</time></code>. <br/>- If a business is open 7 days a week, then it can be specified as <code><time itemprop=\openingHours\ datetime=\Mo-Su\>Monday through Sunday, all day</time></code>.
/// </summary>
private OpeningHours_Core openingHours;
public OpeningHours_Core OpeningHours
{
get
{
return openingHours;
}
set
{
openingHours = value;
SetPropertyInstance(openingHours);
}
}
/// <summary>
/// Cash, credit card, etc.
/// </summary>
private PaymentAccepted_Core paymentAccepted;
public PaymentAccepted_Core PaymentAccepted
{
get
{
return paymentAccepted;
}
set
{
paymentAccepted = value;
SetPropertyInstance(paymentAccepted);
}
}
/// <summary>
/// Photographs of this place.
/// </summary>
private Photos_Core photos;
public Photos_Core Photos
{
get
{
return photos;
}
set
{
photos = value;
SetPropertyInstance(photos);
}
}
/// <summary>
/// The price range of the business, for example <code>$$$</code>.
/// </summary>
private PriceRange_Core priceRange;
public PriceRange_Core PriceRange
{
get
{
return priceRange;
}
set
{
priceRange = value;
SetPropertyInstance(priceRange);
}
}
/// <summary>
/// Review of the item.
/// </summary>
private Reviews_Core reviews;
public Reviews_Core Reviews
{
get
{
return reviews;
}
set
{
reviews = value;
SetPropertyInstance(reviews);
}
}
/// <summary>
/// The telephone number.
/// </summary>
private Telephone_Core telephone;
public Telephone_Core Telephone
{
get
{
return telephone;
}
set
{
telephone = value;
SetPropertyInstance(telephone);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
}
}
| |
/*
* Copyright (c) 2006, Jonas Beckeman
* 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 Jonas Beckeman 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 JONAS BECKEMAN 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 JONAS BECKEMAN AND 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.
*
* HEADER_END*/
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Xml.Serialization;
using System.Drawing;
namespace PhotoshopFile.Text
{
[Description("lrFX")]
public class Effects : PhotoshopFile.Layer.AdjustmentLayerInfo
{
public Dictionary<string, PhotoshopFile.Layer.AdjustmentLayerInfo> _resources = new Dictionary<string, PhotoshopFile.Layer.AdjustmentLayerInfo>();
public Effects()
{
}
public Effects(PhotoshopFile.Layer.AdjustmentLayerInfo info)
{
this.m_data = info.Data;
this.m_key = info.Key;
this.m_layer = info.Layer;
BinaryReverseReader r = this.DataReader;
r.BaseStream.Position += 2; //unused
ushort nNumEffects = r.ReadUInt16();
this._resources = new Dictionary<string, PhotoshopFile.Layer.AdjustmentLayerInfo>();
for (int nEffectNum = 0; nEffectNum < nNumEffects; nEffectNum++)
{
PhotoshopFile.Layer.AdjustmentLayerInfo res = new PhotoshopFile.Layer.AdjustmentLayerInfo(r, info.Layer);
//if (res.Tag != "cmnS")
// continue;
this._resources.Add(res.Key, res);
// case "sofi": //unknown
}
this.Data = null;
}
}
[Description("oglw,iglw")]
public class Glow : EffectBase
{
[XmlAttributeAttribute()]
public uint Intensity;
[XmlAttributeAttribute()]
public bool UseGlobalAngle;
[XmlAttributeAttribute()]
public bool Inner { get { return m_key.StartsWith("i"); } }
public byte Unknown;
public Color UnknownColor;
public Glow()
{ }
public Glow(PhotoshopFile.Layer.AdjustmentLayerInfo info)
{
this.m_data = info.Data;
this.m_key = info.Key;
this.m_layer = info.Layer;
BinaryReverseReader r = this.DataReader;
//string blendModeSignature = null;
uint version = r.ReadUInt32(); //two version specifications?!?
switch (version)
{
case 0:
this.Blur = r.ReadUInt32();
this.Data = null;
break;
case 2:
this.Blur = (uint)r.ReadUInt16();
this.Intensity = r.ReadUInt32();
ushort something = r.ReadUInt16();
this.Color = r.ReadPSDColor(16, false); //Inner color (no alpha)
this.BlendModeKey = this.ReadBlendKey(r);
this.Enabled = r.ReadBoolean();
this.Opacity = r.ReadByte();
//TODO!
if (this.Inner)
this.Unknown = r.ReadByte();
this.UnknownColor = r.ReadPSDColor(16, false); //unknown color(no alpha)
this.Data = r.ReadBytes((int)r.BytesToEnd);
break;
}
}
}
[Description("bevl"), Category("Effect")]
public class Bevel : EffectBase
{
[XmlAttributeAttribute()]
public uint Angle;
[XmlAttributeAttribute()]
public uint Strength;
[XmlAttributeAttribute()]
public string ShadowBlendModeKey;
public Color ShadowColor;
[XmlAttributeAttribute()]
public byte BevelStyle;
[XmlAttributeAttribute()]
public byte ShadowOpacity;
[XmlAttributeAttribute()]
public bool UseGlobalAngle;
[XmlAttributeAttribute()]
public bool Inverted;
public byte Unknown1;
public byte Unknown2;
public ushort Unknown3;
public ushort Unknown4;
public Bevel()
{
}
public Bevel(PhotoshopFile.Layer.AdjustmentLayerInfo info)
{
this.m_data = info.Data;
this.m_key = info.Key;
this.m_layer = info.Layer;
BinaryReverseReader r = this.DataReader;
//string blendModeSignature = null;
uint version = r.ReadUInt32();
switch (version)
{
case 0:
this.Blur = r.ReadUInt32();
this.Data = null;
break;
case 2:
this.Angle = (uint)r.ReadUInt16();
this.Strength = (uint)r.ReadUInt16();
this.Blur = (uint)r.ReadUInt16();
this.Unknown1 = r.ReadByte();
this.Unknown2 = r.ReadByte();
this.Unknown3 = r.ReadUInt16();
this.Unknown4 = r.ReadUInt16();
this.BlendModeKey = this.ReadBlendKey(r);
this.ShadowBlendModeKey = this.ReadBlendKey(r);
this.Color = r.ReadPSDColor(16, true);
this.ShadowColor = r.ReadPSDColor(16, true);
this.BevelStyle = r.ReadByte();
this.Opacity = r.ReadByte();
this.ShadowOpacity = r.ReadByte();
this.Enabled = r.ReadBoolean();
this.UseGlobalAngle = r.ReadBoolean();
this.Inverted = r.ReadBoolean();
System.Drawing.Color someColor = r.ReadPSDColor(16, true);
System.Drawing.Color someColor2 = r.ReadPSDColor(16, true);
break;
}
this.Data = null;
}
}
[Description("dsdw,isdw")]
public class Shadow : EffectBase
{
[XmlAttributeAttribute()]
public uint Intensity;
[XmlAttributeAttribute()]
public uint Angle;
[XmlAttributeAttribute()]
public uint Distance;
[XmlAttributeAttribute()]
public bool UseGlobalAngle;
[XmlAttributeAttribute()]
public bool Inner { get { return m_key.StartsWith("i"); } }
public Shadow()
{ }
public Shadow(PhotoshopFile.Layer.AdjustmentLayerInfo info)
{
this.m_data = info.Data;
this.m_key = info.Key;
this.m_layer = info.Layer;
BinaryReverseReader r = this.DataReader;
//string blendModeSignature = null;
int version = r.ReadInt32();
switch (version)
{
case 0:
this.Blur = r.ReadUInt32();
this.Intensity = r.ReadUInt32();
this.Angle = r.ReadUInt32();
this.Distance = r.ReadUInt32();
this.Color = r.ReadPSDColor(16, true);
this.BlendModeKey = this.ReadBlendKey(r);
//this.BlendModeSignature = r.ReadUInt32();
//this.BlendModeKey = r.ReadUInt32();
this.Enabled = r.ReadBoolean();
this.UseGlobalAngle = r.ReadBoolean();
this.Opacity = r.ReadByte();
break;
case 2:
this.Blur = (uint)r.ReadUInt16();
this.Intensity = r.ReadUInt32();
this.Angle = r.ReadUInt32();
this.Distance = r.ReadUInt32();
ushort something = r.ReadUInt16();//TODO:?
this.Color = r.ReadPSDColor(16, true);
this.BlendModeKey = this.ReadBlendKey(r);
this.Enabled = r.ReadBoolean();
this.UseGlobalAngle = r.ReadBoolean();
this.Opacity = r.ReadByte();
//TODO: 10 unknown bytes!
break;
}
this.Data = null;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.MachineLearning.WebServices
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// WebServicesOperations operations.
/// </summary>
internal partial class WebServicesOperations : Microsoft.Rest.IServiceOperations<AzureMLWebServicesManagementClient>, IWebServicesOperations
{
/// <summary>
/// Initializes a new instance of the WebServicesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal WebServicesOperations(AzureMLWebServicesManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AzureMLWebServicesManagementClient
/// </summary>
public AzureMLWebServicesManagementClient Client { get; private set; }
/// <summary>
/// Creates or updates a new Azure ML web service or update an existing one.
/// </summary>
/// <param name='createOrUpdatePayload'>
/// The payload to create or update the Azure ML web service.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group.
/// </param>
/// <param name='webServiceName'>
/// The Azure ML web service name which you want to reach.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<WebService>> CreateOrUpdateWithHttpMessagesAsync(WebService createOrUpdatePayload, string resourceGroupName, string webServiceName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Send Request
Microsoft.Rest.Azure.AzureOperationResponse<WebService> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(
createOrUpdatePayload, resourceGroupName, webServiceName, customHeaders, cancellationToken);
return await this.Client.GetPutOrPatchOperationResultAsync(_response,
customHeaders,
cancellationToken);
}
/// <summary>
/// Creates or updates a new Azure ML web service or update an existing one.
/// </summary>
/// <param name='createOrUpdatePayload'>
/// The payload to create or update the Azure ML web service.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group.
/// </param>
/// <param name='webServiceName'>
/// The Azure ML web service name which you want to reach.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<WebService>> BeginCreateOrUpdateWithHttpMessagesAsync(WebService createOrUpdatePayload, string resourceGroupName, string webServiceName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (createOrUpdatePayload == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "createOrUpdatePayload");
}
if (createOrUpdatePayload != null)
{
createOrUpdatePayload.Validate();
}
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName");
}
if (webServiceName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "webServiceName");
}
if (this.Client.ApiVersion == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("createOrUpdatePayload", createOrUpdatePayload);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("webServiceName", webServiceName);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearning/webServices/{webServiceName}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{webServiceName}", System.Uri.EscapeDataString(webServiceName));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(createOrUpdatePayload != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(createOrUpdatePayload, this.Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<WebService>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<WebService>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<WebService>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Retrieve an Azure ML web service definition by its subscription, resource
/// group and name.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the resource group.
/// </param>
/// <param name='webServiceName'>
/// The Azure ML web service name which you want to reach.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<WebService>> GetWithHttpMessagesAsync(string resourceGroupName, string webServiceName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName");
}
if (webServiceName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "webServiceName");
}
if (this.Client.ApiVersion == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("webServiceName", webServiceName);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearning/webServices/{webServiceName}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{webServiceName}", System.Uri.EscapeDataString(webServiceName));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<WebService>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<WebService>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Patch an existing Azure ML web service resource.
/// </summary>
/// <param name='patchPayload'>
/// The payload to patch the Azure ML web service with.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group.
/// </param>
/// <param name='webServiceName'>
/// The Azure ML web service name which you want to reach.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<WebService>> PatchWithHttpMessagesAsync(WebService patchPayload, string resourceGroupName, string webServiceName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Send Request
Microsoft.Rest.Azure.AzureOperationResponse<WebService> _response = await BeginPatchWithHttpMessagesAsync(
patchPayload, resourceGroupName, webServiceName, customHeaders, cancellationToken);
return await this.Client.GetPutOrPatchOperationResultAsync(_response,
customHeaders,
cancellationToken);
}
/// <summary>
/// Patch an existing Azure ML web service resource.
/// </summary>
/// <param name='patchPayload'>
/// The payload to patch the Azure ML web service with.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group.
/// </param>
/// <param name='webServiceName'>
/// The Azure ML web service name which you want to reach.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<WebService>> BeginPatchWithHttpMessagesAsync(WebService patchPayload, string resourceGroupName, string webServiceName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (patchPayload == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "patchPayload");
}
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName");
}
if (webServiceName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "webServiceName");
}
if (this.Client.ApiVersion == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("patchPayload", patchPayload);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("webServiceName", webServiceName);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "BeginPatch", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearning/webServices/{webServiceName}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{webServiceName}", System.Uri.EscapeDataString(webServiceName));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PATCH");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(patchPayload != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(patchPayload, this.Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<WebService>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<WebService>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Remove an existing Azure ML web service.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the resource group.
/// </param>
/// <param name='webServiceName'>
/// The Azure ML web service name which you want to reach.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> RemoveWithHttpMessagesAsync(string resourceGroupName, string webServiceName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Send request
Microsoft.Rest.Azure.AzureOperationResponse _response = await BeginRemoveWithHttpMessagesAsync(
resourceGroupName, webServiceName, customHeaders, cancellationToken);
return await this.Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken);
}
/// <summary>
/// Remove an existing Azure ML web service.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the resource group.
/// </param>
/// <param name='webServiceName'>
/// The Azure ML web service name which you want to reach.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> BeginRemoveWithHttpMessagesAsync(string resourceGroupName, string webServiceName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName");
}
if (webServiceName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "webServiceName");
}
if (this.Client.ApiVersion == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("webServiceName", webServiceName);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "BeginRemove", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearning/webServices/{webServiceName}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{webServiceName}", System.Uri.EscapeDataString(webServiceName));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 202 && (int)_statusCode != 204)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get the access keys of a particular Azure ML web service
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the resource group.
/// </param>
/// <param name='webServiceName'>
/// The Azure ML web service name which you want to reach.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<WebServiceKeys>> ListKeysWithHttpMessagesAsync(string resourceGroupName, string webServiceName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName");
}
if (webServiceName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "webServiceName");
}
if (this.Client.ApiVersion == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("webServiceName", webServiceName);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ListKeys", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearning/webServices/{webServiceName}/listKeys").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{webServiceName}", System.Uri.EscapeDataString(webServiceName));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<WebServiceKeys>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<WebServiceKeys>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Retrieve all Azure ML web services in a given resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the resource group.
/// </param>
/// <param name='skiptoken'>
/// Continuation token for pagination.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<PaginatedWebServicesList>> ListInResourceGroupWithHttpMessagesAsync(string resourceGroupName, string skiptoken = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName");
}
if (this.Client.ApiVersion == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("skiptoken", skiptoken);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ListInResourceGroup", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearning/webServices").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (skiptoken != null)
{
_queryParameters.Add(string.Format("$skiptoken={0}", System.Uri.EscapeDataString(skiptoken)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<PaginatedWebServicesList>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<PaginatedWebServicesList>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Retrieve all Azure ML web services in the current Azure subscription.
/// </summary>
/// <param name='skiptoken'>
/// Continuation token for pagination.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<PaginatedWebServicesList>> ListWithHttpMessagesAsync(string skiptoken = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (this.Client.ApiVersion == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("skiptoken", skiptoken);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.MachineLearning/webServices").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (skiptoken != null)
{
_queryParameters.Add(string.Format("$skiptoken={0}", System.Uri.EscapeDataString(skiptoken)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<PaginatedWebServicesList>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<PaginatedWebServicesList>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
#region License
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
#region Imports
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using Spring.Collections;
using Spring.Util;
#endregion
namespace Spring.Objects.Factory.Config
{
/// <summary>
/// Visitor class for traversing <see cref="IObjectDefinition"/> objects, in particular
/// the property values and constructor arguments contained in them resolving
/// object metadata values.
/// </summary>
/// <remarks>
/// Used by <see cref="PropertyPlaceholderConfigurer"/> and <see cref="VariablePlaceholderConfigurer"/>
/// to parse all string values contained in a ObjectDefinition, resolving any placeholders found.
/// </remarks>
/// <author>Mark Pollack</author>
public class ObjectDefinitionVisitor
{
public delegate string ResolveHandler(string rawStringValue);
private readonly ResolveHandler resolveHandler;
/// <summary>
/// Initializes a new instance of the <see cref="ObjectDefinitionVisitor"/> class.
/// </summary>
/// <param name="resolveHandler">The handler to be called for resolving variables contained in a string.</param>
public ObjectDefinitionVisitor(ResolveHandler resolveHandler)
{
AssertUtils.ArgumentNotNull(resolveHandler, "ResovleHandler");
this.resolveHandler = resolveHandler;
}
/// <summary>
/// Initializes a new instance of the <see cref="ObjectDefinitionVisitor"/> class
/// for subclassing
/// </summary>
/// <remarks>Subclasses should override the <code>ResolveStringValue</code> method</remarks>
protected ObjectDefinitionVisitor()
{
}
/// <summary>
/// Traverse the given ObjectDefinition object and the MutablePropertyValues
/// and ConstructorArgumentValues contained in them.
/// </summary>
/// <param name="definition">The object definition to traverse.</param>
public virtual void VisitObjectDefinition(IObjectDefinition definition)
{
VisitObjectTypeName(definition);
VisitPropertyValues(definition);
ConstructorArgumentValues cas = definition.ConstructorArgumentValues;
if (cas != null)
{
VisitIndexedArgumentValues(cas.IndexedArgumentValues);
VisitNamedArgumentValues(cas.NamedArgumentValues);
VisitGenericArgumentValues(cas.GenericArgumentValues);
}
}
/// <summary>
/// Visits the ObjectDefinition property ObjectTypeName, replacing string values using
/// the specified IVariableSource.
/// </summary>
/// <param name="objectDefinition">The object definition.</param>
protected virtual void VisitObjectTypeName(IObjectDefinition objectDefinition)
{
string objectTypeName = objectDefinition.ObjectTypeName;
if (objectTypeName != null)
{
string resolvedName = ResolveStringValue(objectTypeName);
if (!objectTypeName.Equals(resolvedName))
{
objectDefinition.ObjectTypeName = resolvedName;
}
}
}
/// <summary>
/// Visits the property values of the ObjectDefinition, replacing string values
/// using the specified IVariableSource.
/// </summary>
/// <param name="objectDefinition">The object definition.</param>
protected virtual void VisitPropertyValues(IObjectDefinition objectDefinition)
{
MutablePropertyValues pvs = objectDefinition.PropertyValues;
if (pvs != null)
{
for (int j = 0; j < pvs.PropertyValues.Count; j++)
{
PropertyValue pv = pvs.PropertyValues[j];
object newVal = ResolveValue(pv.Value);
if (!ObjectUtils.NullSafeEquals(newVal, pv.Value))
{
pvs.Add(pv.Name, newVal);
}
}
}
}
/// <summary>
/// Visits the indexed constructor argument values, replacing string values using the
/// specified IVariableSource.
/// </summary>
/// <param name="ias">The indexed argument values.</param>
protected virtual void VisitIndexedArgumentValues(IReadOnlyDictionary<int, ConstructorArgumentValues.ValueHolder> ias)
{
foreach (ConstructorArgumentValues.ValueHolder valueHolder in ias.Values)
{
ConfigureConstructorArgument(valueHolder);
}
}
/// <summary>
/// Visits the named constructor argument values, replacing string values using the
/// specified IVariableSource.
/// </summary>
/// <param name="nav">The named argument values.</param>
protected virtual void VisitNamedArgumentValues(IReadOnlyDictionary<string, ConstructorArgumentValues.ValueHolder> nav)
{
foreach (ConstructorArgumentValues.ValueHolder valueHolder in nav.Values)
{
ConfigureConstructorArgument(valueHolder);
}
}
/// <summary>
/// Visits the generic constructor argument values, replacing string values using
/// the specified IVariableSource.
/// </summary>
/// <param name="gav">The genreic argument values.</param>
protected virtual void VisitGenericArgumentValues(IReadOnlyList<ConstructorArgumentValues.ValueHolder> gav)
{
for (var i = 0; i < gav.Count; i++)
{
ConfigureConstructorArgument(gav[i]);
}
}
/// <summary>
/// Configures the constructor argument ValueHolder.
/// </summary>
/// <param name="valueHolder">The vconstructor alue holder.</param>
protected void ConfigureConstructorArgument(ConstructorArgumentValues.ValueHolder valueHolder)
{
object newVal = ResolveValue(valueHolder.Value);
if (!ObjectUtils.NullSafeEquals(newVal, valueHolder.Value))
{
valueHolder.Value = newVal;
}
}
/// <summary>
/// Resolves the given value taken from an object definition according to its type
/// </summary>
/// <param name="value">the value to resolve</param>
/// <returns>the resolved value</returns>
protected virtual object ResolveValue(object value)
{
if (value is IObjectDefinition definition)
{
VisitObjectDefinition(definition);
}
else if (value is ObjectDefinitionHolder definitionHolder)
{
VisitObjectDefinition( definitionHolder.ObjectDefinition);
}
else if (value is RuntimeObjectReference ror)
{
//name has to be of string type.
string newObjectName = ResolveStringValue(ror.ObjectName);
if (!newObjectName.Equals(ror.ObjectName))
{
return new RuntimeObjectReference(newObjectName);
}
}
else if (value is ManagedList list)
{
VisitManagedList(list);
}
else if (value is ManagedSet set)
{
VisitManagedSet(set);
}
else if (value is ManagedDictionary dictionary)
{
VisitManagedDictionary(dictionary);
}
else if (value is NameValueCollection collection)
{
VisitNameValueCollection(collection);
}
else if (value is TypedStringValue typedStringValue)
{
String stringValue = typedStringValue.Value;
if (stringValue != null)
{
String visitedString = ResolveStringValue(stringValue);
typedStringValue.Value = visitedString;
}
}
else if (value is string s)
{
return ResolveStringValue(s);
}
else if (value is ExpressionHolder holder)
{
string newExpressionString = ResolveStringValue(holder.ExpressionString);
return new ExpressionHolder(newExpressionString);
}
return value;
}
/// <summary>
/// Visits the ManagedList property ElementTypeName and
/// calls <see cref="ResolveValue"/> for list element.
/// </summary>
protected virtual void VisitManagedList(ManagedList listVal)
{
string elementTypeName = listVal.ElementTypeName;
if (elementTypeName != null)
{
string resolvedName = ResolveStringValue(elementTypeName);
if (!elementTypeName.Equals(resolvedName))
{
listVal.ElementTypeName = resolvedName;
}
}
for (int i = 0; i < listVal.Count; ++i)
{
object oldValue = listVal[i];
object newValue = ResolveValue(oldValue);
if (!ObjectUtils.NullSafeEquals(newValue, oldValue))
{
listVal[i] = newValue;
}
}
}
/// <summary>
/// Visits the ManagedSet property ElementTypeName and
/// calls <see cref="ResolveValue"/> for list element.
/// </summary>
protected virtual void VisitManagedSet(ManagedSet setVal)
{
string elementTypeName = setVal.ElementTypeName;
if (elementTypeName != null)
{
string resolvedName = ResolveStringValue(elementTypeName);
if (!elementTypeName.Equals(resolvedName))
{
setVal.ElementTypeName = resolvedName;
}
}
ISet clone = (ISet)setVal.Clone();
foreach (object oldValue in clone)
{
object newValue = ResolveValue(oldValue);
if (!ObjectUtils.NullSafeEquals(newValue, oldValue))
{
setVal.Remove(oldValue);
setVal.Add(newValue);
}
}
}
/// <summary>
/// Visits the ManagedSet properties KeyTypeName and ValueTypeName and
/// calls <see cref="ResolveValue"/> for dictionary's value element.
/// </summary>
protected virtual void VisitManagedDictionary(ManagedDictionary dictVal)
{
string keyTypeName = dictVal.KeyTypeName;
if (keyTypeName != null)
{
string resolvedName = ResolveStringValue(keyTypeName);
if (!keyTypeName.Equals(resolvedName))
{
dictVal.KeyTypeName = resolvedName;
}
}
string valueTypeName = dictVal.ValueTypeName;
if (valueTypeName != null)
{
string resolvedName = ResolveStringValue(valueTypeName);
if (!valueTypeName.Equals(resolvedName))
{
dictVal.ValueTypeName = resolvedName;
}
}
Hashtable mods = new Hashtable();
bool entriesModified = false;
foreach (DictionaryEntry entry in dictVal)
{
/*
object oldValue = entry.Value;
object newValue = ResolveValue(oldValue);
if (!ObjectUtils.NullSafeEquals(newValue, oldValue))
{
mods[entry.Key] = newValue;
}*/
object key = entry.Key;
object newKey = ResolveValue(key);
object oldValue = entry.Value;
object newValue = ResolveValue(oldValue);
if (!ObjectUtils.NullSafeEquals(newValue, oldValue) || key != newKey)
{
entriesModified = true;
}
mods[newKey] = newValue;
}
if (entriesModified)
{
dictVal.Clear();
foreach (DictionaryEntry entry in mods)
{
dictVal[entry.Key] = entry.Value;
}
}
}
/// <summary>
/// Visits the elements of a NameValueCollection and calls
/// <see cref="ResolveValue"/> for value of each element.
/// </summary>
protected virtual void VisitNameValueCollection(NameValueCollection collection)
{
foreach (string key in collection.AllKeys)
{
string oldValue = collection[key];
string newValue = ResolveValue(oldValue) as string;
if (!ObjectUtils.NullSafeEquals(newValue, oldValue))
{
collection[key] = newValue;
}
}
}
/// <summary>
/// calls the <see cref="ResolveHandler"/> to resolve any variables contained in the raw string.
/// </summary>
/// <param name="rawStringValue">the raw string value containing variable placeholders to be resolved</param>
/// <exception cref="InvalidOperationException">If no <see cref="IVariableSource"/> has been configured.</exception>
/// <returns>the resolved string, having variables being replaced, if any</returns>
protected virtual string ResolveStringValue(string rawStringValue)
{
if (resolveHandler == null)
{
throw new InvalidOperationException("No resolveHandler specified - pass an instance " +
"into the constructor or override the 'ResolveStringValue' method");
}
return resolveHandler(rawStringValue);
}
}
}
| |
// 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.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.Net;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Principal;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Security;
using System.ServiceModel.Security.Tokens;
using System.Threading;
using System.Threading.Tasks;
namespace System.ServiceModel
{
public class ClientCredentialsSecurityTokenManager : SecurityTokenManager
{
private ClientCredentials _parent;
public ClientCredentialsSecurityTokenManager(ClientCredentials clientCredentials)
{
if (clientCredentials == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("clientCredentials");
}
_parent = clientCredentials;
}
public ClientCredentials ClientCredentials
{
get { return _parent; }
}
private string GetServicePrincipalName(InitiatorServiceModelSecurityTokenRequirement initiatorRequirement)
{
EndpointAddress targetAddress = initiatorRequirement.TargetAddress;
if (targetAddress == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(string.Format(SRServiceModel.TokenRequirementDoesNotSpecifyTargetAddress, initiatorRequirement));
}
IdentityVerifier identityVerifier;
SecurityBindingElement securityBindingElement = initiatorRequirement.SecurityBindingElement;
if (securityBindingElement != null)
{
identityVerifier = securityBindingElement.LocalClientSettings.IdentityVerifier;
}
else
{
identityVerifier = IdentityVerifier.CreateDefault();
}
EndpointIdentity identity;
identityVerifier.TryGetIdentity(targetAddress, out identity);
return SecurityUtils.GetSpnFromIdentity(identity, targetAddress);
}
private bool IsDigestAuthenticationScheme(SecurityTokenRequirement requirement)
{
if (requirement.Properties.ContainsKey(ServiceModelSecurityTokenRequirement.HttpAuthenticationSchemeProperty))
{
AuthenticationSchemes authScheme = (AuthenticationSchemes)requirement.Properties[ServiceModelSecurityTokenRequirement.HttpAuthenticationSchemeProperty];
if (!authScheme.IsSingleton())
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("authScheme", string.Format(SRServiceModel.HttpRequiresSingleAuthScheme, authScheme));
}
return (authScheme == AuthenticationSchemes.Digest);
}
else
{
return false;
}
}
internal protected bool IsIssuedSecurityTokenRequirement(SecurityTokenRequirement requirement)
{
if (requirement != null && requirement.Properties.ContainsKey(ServiceModelSecurityTokenRequirement.IssuerAddressProperty))
{
// handle all issued token requirements except for spnego, tlsnego and secure conversation
if (requirement.TokenType == ServiceModelSecurityTokenTypes.AnonymousSslnego || requirement.TokenType == ServiceModelSecurityTokenTypes.MutualSslnego
|| requirement.TokenType == ServiceModelSecurityTokenTypes.SecureConversation || requirement.TokenType == ServiceModelSecurityTokenTypes.Spnego)
{
return false;
}
else
{
return true;
}
}
return false;
}
public override SecurityTokenProvider CreateSecurityTokenProvider(SecurityTokenRequirement tokenRequirement)
{
if (tokenRequirement == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokenRequirement");
}
SecurityTokenProvider result = null;
if (tokenRequirement is RecipientServiceModelSecurityTokenRequirement && tokenRequirement.TokenType == SecurityTokenTypes.X509Certificate && tokenRequirement.KeyUsage == SecurityKeyUsage.Exchange)
{
// this is the uncorrelated duplex case
if (_parent.ClientCertificate.Certificate == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SRServiceModel.ClientCertificateNotProvidedOnClientCredentials));
}
result = new X509SecurityTokenProvider(_parent.ClientCertificate.Certificate);
}
else if (tokenRequirement is InitiatorServiceModelSecurityTokenRequirement)
{
InitiatorServiceModelSecurityTokenRequirement initiatorRequirement = tokenRequirement as InitiatorServiceModelSecurityTokenRequirement;
string tokenType = initiatorRequirement.TokenType;
if (IsIssuedSecurityTokenRequirement(initiatorRequirement))
{
throw ExceptionHelper.PlatformNotSupported("CreateSecurityTokenProvider (IsIssuedSecurityTokenRequirement(initiatorRequirement)");
}
else if (tokenType == SecurityTokenTypes.X509Certificate)
{
if (initiatorRequirement.Properties.ContainsKey(SecurityTokenRequirement.KeyUsageProperty) && initiatorRequirement.KeyUsage == SecurityKeyUsage.Exchange)
{
throw ExceptionHelper.PlatformNotSupported("CreateSecurityTokenProvider X509Certificate - SecurityKeyUsage.Exchange");
}
else
{
if (_parent.ClientCertificate.Certificate == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SRServiceModel.ClientCertificateNotProvidedOnClientCredentials));
}
result = new X509SecurityTokenProvider(_parent.ClientCertificate.Certificate);
}
}
else if (tokenType == SecurityTokenTypes.Kerberos)
{
string spn = GetServicePrincipalName(initiatorRequirement);
result = new KerberosSecurityTokenProviderWrapper(
new KerberosSecurityTokenProvider(spn, _parent.Windows.AllowedImpersonationLevel, SecurityUtils.GetNetworkCredentialOrDefault(_parent.Windows.ClientCredential)));
}
else if (tokenType == SecurityTokenTypes.UserName)
{
if (_parent.UserName.UserName == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SRServiceModel.UserNamePasswordNotProvidedOnClientCredentials));
}
result = new UserNameSecurityTokenProvider(_parent.UserName.UserName, _parent.UserName.Password);
}
else if (tokenType == ServiceModelSecurityTokenTypes.SspiCredential)
{
if (IsDigestAuthenticationScheme(initiatorRequirement))
{
result = new SspiSecurityTokenProvider(SecurityUtils.GetNetworkCredentialOrDefault(_parent.HttpDigest.ClientCredential), true, TokenImpersonationLevel.Delegation);
}
else
{
#pragma warning disable 618 // to disable AllowNtlm obsolete wanring.
result = new SspiSecurityTokenProvider(SecurityUtils.GetNetworkCredentialOrDefault(_parent.Windows.ClientCredential),
_parent.Windows.AllowNtlm,
_parent.Windows.AllowedImpersonationLevel);
#pragma warning restore 618
}
}
}
if ((result == null) && !tokenRequirement.IsOptionalToken)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(string.Format(SRServiceModel.SecurityTokenManagerCannotCreateProviderForRequirement, tokenRequirement)));
}
return result;
}
public override SecurityTokenSerializer CreateSecurityTokenSerializer(SecurityTokenVersion version)
{
// not referenced anywhere in current code, but must implement abstract.
throw ExceptionHelper.PlatformNotSupported("CreateSecurityTokenSerializer(SecurityTokenVersion version) not supported");
}
private X509SecurityTokenAuthenticator CreateServerX509TokenAuthenticator()
{
return new X509SecurityTokenAuthenticator(_parent.ServiceCertificate.Authentication.GetCertificateValidator(), false);
}
private X509SecurityTokenAuthenticator CreateServerSslX509TokenAuthenticator()
{
if (_parent.ServiceCertificate.SslCertificateAuthentication != null)
{
return new X509SecurityTokenAuthenticator(_parent.ServiceCertificate.SslCertificateAuthentication.GetCertificateValidator(), false);
}
return CreateServerX509TokenAuthenticator();
}
public override SecurityTokenAuthenticator CreateSecurityTokenAuthenticator(SecurityTokenRequirement tokenRequirement, out SecurityTokenResolver outOfBandTokenResolver)
{
if (tokenRequirement == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokenRequirement");
}
outOfBandTokenResolver = null;
SecurityTokenAuthenticator result = null;
InitiatorServiceModelSecurityTokenRequirement initiatorRequirement = tokenRequirement as InitiatorServiceModelSecurityTokenRequirement;
if (initiatorRequirement != null)
{
string tokenType = initiatorRequirement.TokenType;
if (IsIssuedSecurityTokenRequirement(initiatorRequirement))
{
throw ExceptionHelper.PlatformNotSupported("CreateSecurityTokenAuthenticator : GenericXmlSecurityTokenAuthenticator");
}
else if (tokenType == SecurityTokenTypes.X509Certificate)
{
if (initiatorRequirement.IsOutOfBandToken)
{
// when the client side soap security asks for a token authenticator, its for doing
// identity checks on the out of band server certificate
result = new X509SecurityTokenAuthenticator(X509CertificateValidator.None);
}
else if (initiatorRequirement.PreferSslCertificateAuthenticator)
{
result = CreateServerSslX509TokenAuthenticator();
}
else
{
result = CreateServerX509TokenAuthenticator();
}
}
else if (tokenType == SecurityTokenTypes.Rsa)
{
throw ExceptionHelper.PlatformNotSupported("CreateSecurityTokenAuthenticator : SecurityTokenTypes.Rsa");
}
else if (tokenType == SecurityTokenTypes.Kerberos)
{
throw ExceptionHelper.PlatformNotSupported("CreateSecurityTokenAuthenticator : SecurityTokenTypes.Kerberos");
}
else if (tokenType == ServiceModelSecurityTokenTypes.SecureConversation
|| tokenType == ServiceModelSecurityTokenTypes.MutualSslnego
|| tokenType == ServiceModelSecurityTokenTypes.AnonymousSslnego
|| tokenType == ServiceModelSecurityTokenTypes.Spnego)
{
throw ExceptionHelper.PlatformNotSupported("CreateSecurityTokenAuthenticator : GenericXmlSecurityTokenAuthenticator");
}
}
else if ((tokenRequirement is RecipientServiceModelSecurityTokenRequirement) && tokenRequirement.TokenType == SecurityTokenTypes.X509Certificate)
{
// uncorrelated duplex case
result = CreateServerX509TokenAuthenticator();
}
if (result == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(string.Format(SRServiceModel.SecurityTokenManagerCannotCreateAuthenticatorForRequirement, tokenRequirement)));
}
return result;
}
}
internal class KerberosSecurityTokenProviderWrapper : CommunicationObjectSecurityTokenProvider
{
private KerberosSecurityTokenProvider _innerProvider;
public KerberosSecurityTokenProviderWrapper(KerberosSecurityTokenProvider innerProvider)
{
_innerProvider = innerProvider;
}
internal Task<SecurityToken> GetTokenAsync(CancellationToken cancellationToken, ChannelBinding channelbinding)
{
return Task.FromResult((SecurityToken)new KerberosRequestorSecurityToken(_innerProvider.ServicePrincipalName,
_innerProvider.TokenImpersonationLevel, _innerProvider.NetworkCredential,
SecurityUniqueId.Create().Value));
}
protected override Task<SecurityToken> GetTokenCoreAsync(CancellationToken cancellationToken)
{
return GetTokenAsync(cancellationToken, null);
}
}
}
| |
namespace CodeFirst_MigratWithExistDB
{
using System;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
public partial class SWDEContext : DbContext
{
public SWDEContext()
: base("name=SWDEContext")
{
}
public virtual DbSet<G5ADR> G5ADR { get; set; }
public virtual DbSet<G5DOK> G5DOK { get; set; }
public virtual DbSet<G5RCBUD> G5RCBUD { get; set; }
public virtual DbSet<G5RCDZE> G5RCDZE { get; set; }
public virtual DbSet<G5RCLKL> G5RCLKL { get; set; }
public virtual DbSet<G5RCNIER> G5RCNIER { get; set; }
public virtual DbSet<G5RCOBC> G5RCOBC { get; set; }
public virtual DbSet<G5RCW> G5RCW { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<G5ADR>()
.Property(e => e.typBaz)
.IsUnicode(false);
modelBuilder.Entity<G5ADR>()
.Property(e => e.idO)
.IsUnicode(false);
modelBuilder.Entity<G5ADR>()
.Property(e => e.idR)
.IsUnicode(false);
modelBuilder.Entity<G5ADR>()
.Property(e => e.st_obj)
.IsUnicode(false);
modelBuilder.Entity<G5ADR>()
.Property(e => e.G5NAZ)
.IsUnicode(false);
modelBuilder.Entity<G5ADR>()
.Property(e => e.G5ULC)
.IsUnicode(false);
modelBuilder.Entity<G5ADR>()
.Property(e => e.G5NRA)
.IsUnicode(false);
modelBuilder.Entity<G5ADR>()
.Property(e => e.G5NRL)
.IsUnicode(false);
modelBuilder.Entity<G5ADR>()
.Property(e => e.G5MSC)
.IsUnicode(false);
modelBuilder.Entity<G5ADR>()
.Property(e => e.G5KOD)
.IsUnicode(false);
modelBuilder.Entity<G5ADR>()
.Property(e => e.G5PCZ)
.IsUnicode(false);
modelBuilder.Entity<G5DOK>()
.Property(e => e.typBaz)
.IsUnicode(false);
modelBuilder.Entity<G5DOK>()
.Property(e => e.idO)
.IsUnicode(false);
modelBuilder.Entity<G5DOK>()
.Property(e => e.idR)
.IsUnicode(false);
modelBuilder.Entity<G5DOK>()
.Property(e => e.st_obj)
.IsUnicode(false);
modelBuilder.Entity<G5DOK>()
.Property(e => e.G5SYG)
.IsUnicode(false);
modelBuilder.Entity<G5DOK>()
.Property(e => e.G5NSR)
.IsUnicode(false);
modelBuilder.Entity<G5DOK>()
.Property(e => e.G5OPD)
.IsUnicode(false);
modelBuilder.Entity<G5DOK>()
.HasMany(e => e.G5RCW)
.WithOptional(e => e.G5DOK)
.HasForeignKey(e => e.id_G5DOK);
modelBuilder.Entity<G5RCBUD>()
.Property(e => e.typBaz)
.IsUnicode(false);
modelBuilder.Entity<G5RCBUD>()
.Property(e => e.idO)
.IsUnicode(false);
modelBuilder.Entity<G5RCBUD>()
.Property(e => e.idR)
.IsUnicode(false);
modelBuilder.Entity<G5RCBUD>()
.Property(e => e.st_obj)
.IsUnicode(false);
modelBuilder.Entity<G5RCBUD>()
.Property(e => e.G5IDB)
.IsUnicode(false);
modelBuilder.Entity<G5RCBUD>()
.Property(e => e.G5LL)
.IsUnicode(false);
modelBuilder.Entity<G5RCBUD>()
.Property(e => e.G5RZ)
.IsUnicode(false);
modelBuilder.Entity<G5RCBUD>()
.Property(e => e.G5UD)
.IsUnicode(false);
modelBuilder.Entity<G5RCBUD>()
.Property(e => e.G5RADR)
.IsUnicode(false);
modelBuilder.Entity<G5RCBUD>()
.Property(e => e.G5RSKL)
.IsUnicode(false);
modelBuilder.Entity<G5RCDZE>()
.Property(e => e.typBaz)
.IsUnicode(false);
modelBuilder.Entity<G5RCDZE>()
.Property(e => e.idO)
.IsUnicode(false);
modelBuilder.Entity<G5RCDZE>()
.Property(e => e.idR)
.IsUnicode(false);
modelBuilder.Entity<G5RCDZE>()
.Property(e => e.st_obj)
.IsUnicode(false);
modelBuilder.Entity<G5RCDZE>()
.Property(e => e.G5IDD)
.IsUnicode(false);
modelBuilder.Entity<G5RCDZE>()
.Property(e => e.G5FDZ)
.IsUnicode(false);
modelBuilder.Entity<G5RCDZE>()
.Property(e => e.G5RZ)
.IsUnicode(false);
modelBuilder.Entity<G5RCDZE>()
.Property(e => e.G5UD)
.IsUnicode(false);
modelBuilder.Entity<G5RCDZE>()
.Property(e => e.G5RADR)
.IsUnicode(false);
modelBuilder.Entity<G5RCDZE>()
.Property(e => e.G5RSKL)
.IsUnicode(false);
modelBuilder.Entity<G5RCLKL>()
.Property(e => e.typBaz)
.IsUnicode(false);
modelBuilder.Entity<G5RCLKL>()
.Property(e => e.idO)
.IsUnicode(false);
modelBuilder.Entity<G5RCLKL>()
.Property(e => e.idR)
.IsUnicode(false);
modelBuilder.Entity<G5RCLKL>()
.Property(e => e.st_obj)
.IsUnicode(false);
modelBuilder.Entity<G5RCLKL>()
.Property(e => e.G5IDL)
.IsUnicode(false);
modelBuilder.Entity<G5RCLKL>()
.Property(e => e.G5UD)
.IsUnicode(false);
modelBuilder.Entity<G5RCLKL>()
.Property(e => e.G5RADR)
.IsUnicode(false);
modelBuilder.Entity<G5RCLKL>()
.Property(e => e.G5RSKL)
.IsUnicode(false);
modelBuilder.Entity<G5RCNIER>()
.Property(e => e.typBaz)
.IsUnicode(false);
modelBuilder.Entity<G5RCNIER>()
.Property(e => e.idO)
.IsUnicode(false);
modelBuilder.Entity<G5RCNIER>()
.Property(e => e.idR)
.IsUnicode(false);
modelBuilder.Entity<G5RCNIER>()
.Property(e => e.st_obj)
.IsUnicode(false);
modelBuilder.Entity<G5RCNIER>()
.Property(e => e.G5OPIS)
.IsUnicode(false);
modelBuilder.Entity<G5RCNIER>()
.Property(e => e.G5RPTW)
.IsUnicode(false);
modelBuilder.Entity<G5RCNIER>()
.Property(e => e.G5ROBCN)
.IsUnicode(false);
modelBuilder.Entity<G5RCNIER>()
.HasMany(e => e.G5RCDZE)
.WithOptional(e => e.G5RCNIER)
.HasForeignKey(e => e.id_G5RCNIER);
modelBuilder.Entity<G5RCNIER>()
.HasMany(e => e.G5RCLKL)
.WithOptional(e => e.G5RCNIER)
.HasForeignKey(e => e.id_G5RCNIER);
modelBuilder.Entity<G5RCOBC>()
.Property(e => e.typBaz)
.IsUnicode(false);
modelBuilder.Entity<G5RCOBC>()
.Property(e => e.idO)
.IsUnicode(false);
modelBuilder.Entity<G5RCOBC>()
.Property(e => e.idR)
.IsUnicode(false);
modelBuilder.Entity<G5RCOBC>()
.Property(e => e.st_obj)
.IsUnicode(false);
modelBuilder.Entity<G5RCOBC>()
.Property(e => e.G5OPIS)
.IsUnicode(false);
modelBuilder.Entity<G5RCOBC>()
.Property(e => e.G5ROBCN)
.IsUnicode(false);
modelBuilder.Entity<G5RCW>()
.Property(e => e.typBaz)
.IsUnicode(false);
modelBuilder.Entity<G5RCW>()
.Property(e => e.idO)
.IsUnicode(false);
modelBuilder.Entity<G5RCW>()
.Property(e => e.idR)
.IsUnicode(false);
modelBuilder.Entity<G5RCW>()
.Property(e => e.st_obj)
.IsUnicode(false);
modelBuilder.Entity<G5RCW>()
.Property(e => e.G5IRCW)
.IsUnicode(false);
modelBuilder.Entity<G5RCW>()
.Property(e => e.G5NRPR)
.IsUnicode(false);
modelBuilder.Entity<G5RCW>()
.Property(e => e.G5RDOK)
.IsUnicode(false);
modelBuilder.Entity<G5RCW>()
.HasMany(e => e.G5RCNIER)
.WithOptional(e => e.G5RCW)
.HasForeignKey(e => e.id_G5RCW);
}
}
}
| |
namespace StockSharp.Algo.Storages
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Linq;
using Ecng.Collections;
using Ecng.Common;
using Ecng.Serialization;
using StockSharp.Logging;
using StockSharp.Messages;
/// <summary>
/// Extended info <see cref="Message.ExtensionInfo"/> storage.
/// </summary>
public interface IExtendedInfoStorageItem
{
/// <summary>
/// Extended fields (names and types).
/// </summary>
IEnumerable<Tuple<string, Type>> Fields { get; }
/// <summary>
/// Get all security identifiers.
/// </summary>
IEnumerable<SecurityId> Securities { get; }
/// <summary>
/// Storage name.
/// </summary>
string StorageName { get; }
/// <summary>
/// Initialize the storage.
/// </summary>
void Init();
/// <summary>
/// Add extended info.
/// </summary>
/// <param name="securityId">Security identifier.</param>
/// <param name="extensionInfo">Extended information.</param>
void Add(SecurityId securityId, IDictionary<string, object> extensionInfo);
/// <summary>
/// Load extended info.
/// </summary>
/// <returns>Extended information.</returns>
IEnumerable<Tuple<SecurityId, IDictionary<string, object>>> Load();
/// <summary>
/// Load extended info.
/// </summary>
/// <param name="securityId">Security identifier.</param>
/// <returns>Extended information.</returns>
IDictionary<string, object> Load(SecurityId securityId);
/// <summary>
/// Delete extended info.
/// </summary>
/// <param name="securityId">Security identifier.</param>
void Delete(SecurityId securityId);
}
/// <summary>
/// Extended info <see cref="Message.ExtensionInfo"/> storage.
/// </summary>
public interface IExtendedInfoStorage
{
/// <summary>
/// Get all extended storages.
/// </summary>
IEnumerable<IExtendedInfoStorageItem> Storages { get; }
/// <summary>
/// Initialize the storage.
/// </summary>
/// <returns>Possible errors with storage names. Empty dictionary means initialization without any issues.</returns>
IDictionary<IExtendedInfoStorageItem, Exception> Init();
/// <summary>
/// To get storage for the specified name.
/// </summary>
/// <param name="storageName">Storage name.</param>
/// <returns>Storage.</returns>
IExtendedInfoStorageItem Get(string storageName);
/// <summary>
/// To create storage.
/// </summary>
/// <param name="storageName">Storage name.</param>
/// <param name="fields">Extended fields (names and types).</param>
/// <returns>Storage.</returns>
IExtendedInfoStorageItem Create(string storageName, IEnumerable<Tuple<string, Type>> fields);
/// <summary>
/// Delete storage.
/// </summary>
/// <param name="storage">Storage.</param>
void Delete(IExtendedInfoStorageItem storage);
/// <summary>
/// The storage was created.
/// </summary>
event Action<IExtendedInfoStorageItem> Created;
/// <summary>
/// The storage was deleted.
/// </summary>
event Action<IExtendedInfoStorageItem> Deleted;
}
/// <summary>
/// Extended info <see cref="Message.ExtensionInfo"/> storage, used csv files.
/// </summary>
public class CsvExtendedInfoStorage : IExtendedInfoStorage
{
private class CsvExtendedInfoStorageItem : IExtendedInfoStorageItem
{
private readonly CsvExtendedInfoStorage _storage;
private readonly string _fileName;
private Tuple<string, Type>[] _fields;
private readonly SyncObject _lock = new();
//private readonly Dictionary<string, Type> _fieldTypes = new Dictionary<string, Type>(StringComparer.InvariantCultureIgnoreCase);
private readonly Dictionary<SecurityId, Dictionary<string, object>> _cache = new();
public CsvExtendedInfoStorageItem(CsvExtendedInfoStorage storage, string fileName)
{
if (fileName.IsEmpty())
throw new ArgumentNullException(nameof(fileName));
_storage = storage ?? throw new ArgumentNullException(nameof(storage));
_fileName = fileName;
}
public CsvExtendedInfoStorageItem(CsvExtendedInfoStorage storage, string fileName, IEnumerable<Tuple<string, Type>> fields)
: this(storage, fileName)
{
if (fields == null)
throw new ArgumentNullException(nameof(fields));
_fields = fields.ToArray();
if (_fields.IsEmpty())
throw new ArgumentOutOfRangeException(nameof(fields));
}
public string StorageName => Path.GetFileNameWithoutExtension(_fileName);
public void Init()
{
if (File.Exists(_fileName))
{
Do.Invariant(() =>
{
using (var stream = new FileStream(_fileName, FileMode.Open, FileAccess.Read))
{
var reader = new FastCsvReader(stream, Encoding.UTF8);
reader.NextLine();
reader.Skip();
var fields = new string[reader.ColumnCount - 1];
for (var i = 0; i < fields.Length; i++)
fields[i] = reader.ReadString();
reader.NextLine();
reader.Skip();
var types = new Type[reader.ColumnCount - 1];
for (var i = 0; i < types.Length; i++)
{
types[i] = reader.ReadString().To<Type>();
//_fieldTypes.Add(fields[i], types[i]);
}
if (_fields == null)
{
if (fields.Length != types.Length)
throw new InvalidOperationException($"{fields.Length} != {types.Length}");
_fields = fields.Select((f, i) => Tuple.Create(f, types[i])).ToArray();
}
while (reader.NextLine())
{
var secId = reader.ReadString().ToSecurityId();
var values = new Dictionary<string, object>();
for (var i = 0; i < fields.Length; i++)
{
values[fields[i]] = reader.ReadString().To(types[i]);
}
_cache.Add(secId, values);
}
}
});
}
else
{
if (_fields == null)
throw new InvalidOperationException();
Write(Enumerable.Empty<Tuple<SecurityId, IDictionary<string, object>>>());
}
}
private void Flush()
{
_storage.DelayAction.DefaultGroup.Add(() => Write(((IExtendedInfoStorageItem)this).Load()));
}
private void Write(IEnumerable<Tuple<SecurityId, IDictionary<string, object>>> values)
{
if (values == null)
throw new ArgumentNullException(nameof(values));
using (var writer = new CsvFileWriter(new TransactionFileStream(_fileName, FileMode.Create)))
{
writer.WriteRow(new[] { nameof(SecurityId) }.Concat(_fields.Select(f => f.Item1)));
writer.WriteRow(new[] { typeof(string) }.Concat(_fields.Select(f => f.Item2)).Select(t => t.TryGetCSharpAlias() ?? t.GetTypeName(false)));
foreach (var pair in values)
{
writer.WriteRow(new[] { pair.Item1.ToStringId() }.Concat(_fields.Select(f => pair.Item2.TryGetValue(f.Item1)?.To<string>())));
}
}
}
public void Delete()
{
_storage.DelayAction.DefaultGroup.Add(() =>
{
File.Delete(_fileName);
});
_storage._deleted?.Invoke(this);
}
IEnumerable<Tuple<string, Type>> IExtendedInfoStorageItem.Fields => _fields;
void IExtendedInfoStorageItem.Add(SecurityId securityId, IDictionary<string, object> extensionInfo)
{
lock (_lock)
{
var dict = _cache.SafeAdd(securityId);
foreach (var field in _fields)
{
var value = extensionInfo.TryGetValue(field.Item1);
if (value == null)
continue;
dict[field.Item1] = value;
//_fieldTypes.TryAdd(field, value.GetType());
}
}
Flush();
}
IEnumerable<Tuple<SecurityId, IDictionary<string, object>>> IExtendedInfoStorageItem.Load()
{
lock (_lock)
{
var retVal = new Tuple<SecurityId, IDictionary<string, object>>[_cache.Count];
var i = 0;
foreach (var pair in _cache)
{
retVal[i] = Tuple.Create(pair.Key, pair.Value.ToDictionary());
i++;
}
return retVal;
}
}
IDictionary<string, object> IExtendedInfoStorageItem.Load(SecurityId securityId)
{
lock (_lock)
return _cache.TryGetValue(securityId)?.ToDictionary();
}
void IExtendedInfoStorageItem.Delete(SecurityId securityId)
{
lock (_lock)
_cache.Remove(securityId);
Flush();
}
IEnumerable<SecurityId> IExtendedInfoStorageItem.Securities
{
get
{
lock (_lock)
return _cache.Keys.ToArray();
}
}
}
private readonly CachedSynchronizedDictionary<string, CsvExtendedInfoStorageItem> _items = new(StringComparer.InvariantCultureIgnoreCase);
private readonly string _path;
/// <summary>
/// Initializes a new instance of the <see cref="CsvExtendedInfoStorage"/>.
/// </summary>
/// <param name="path">Path to storage.</param>
public CsvExtendedInfoStorage(string path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
_path = path.ToFullPath();
Directory.CreateDirectory(path);
_delayAction = new DelayAction(ex => ex.LogError());
}
private DelayAction _delayAction;
/// <summary>
/// The time delayed action.
/// </summary>
public DelayAction DelayAction
{
get => _delayAction;
set => _delayAction = value ?? throw new ArgumentNullException(nameof(value));
}
IExtendedInfoStorageItem IExtendedInfoStorage.Create(string storageName, IEnumerable<Tuple<string, Type>> fields)
{
if (storageName.IsEmpty())
throw new ArgumentNullException(nameof(storageName));
var retVal = _items.SafeAdd(storageName, key =>
{
var item = new CsvExtendedInfoStorageItem(this, Path.Combine(_path, key + ".csv"), fields);
item.Init();
return item;
}, out var isNew);
if (isNew)
_created?.Invoke(retVal);
return retVal;
}
void IExtendedInfoStorage.Delete(IExtendedInfoStorageItem storage)
{
if (storage == null)
throw new ArgumentNullException(nameof(storage));
if (_items.Remove(storage.StorageName))
{
((CsvExtendedInfoStorageItem)storage).Delete();
}
}
private Action<IExtendedInfoStorageItem> _created;
event Action<IExtendedInfoStorageItem> IExtendedInfoStorage.Created
{
add => _created += value;
remove => _created -= value;
}
private Action<IExtendedInfoStorageItem> _deleted;
event Action<IExtendedInfoStorageItem> IExtendedInfoStorage.Deleted
{
add => _deleted += value;
remove => _deleted -= value;
}
IExtendedInfoStorageItem IExtendedInfoStorage.Get(string storageName)
{
if (storageName.IsEmpty())
throw new ArgumentNullException(nameof(storageName));
return _items.TryGetValue(storageName);
}
IEnumerable<IExtendedInfoStorageItem> IExtendedInfoStorage.Storages => _items.CachedValues;
/// <inheritdoc />
public IDictionary<IExtendedInfoStorageItem, Exception> Init()
{
var errors = new Dictionary<IExtendedInfoStorageItem, Exception>();
foreach (var fileName in Directory.GetFiles(_path, "*.csv"))
{
var item = new CsvExtendedInfoStorageItem(this, fileName);
_items.Add(Path.GetFileNameWithoutExtension(fileName), item);
try
{
item.Init();
}
catch (Exception ex)
{
errors.Add(item, ex);
}
}
return errors;
}
}
}
| |
/*
* @author Valentin Simonov / http://va.lent.in/
*/
using System;
using System.Collections.Generic;
using TouchScript.Utils;
using UnityEngine;
namespace TouchScript.Gestures.Simple
{
/// <summary>
/// Simple Pan gesture which only relies on the first touch.
/// </summary>
[AddComponentMenu("TouchScript/Gestures/Simple Pan Gesture")]
public class SimplePanGesture : Transform2DGestureBase
{
#region Constants
/// <summary>
/// Message name when gesture starts
/// </summary>
public const string PAN_START_MESSAGE = "OnPanStart";
/// <summary>
/// Message name when gesture updates
/// </summary>
public const string PAN_MESSAGE = "OnPan";
/// <summary>
/// Message name when gesture ends
/// </summary>
public const string PAN_COMPLETE_MESSAGE = "OnPanComplete";
#endregion
#region Events
/// <summary>
/// Occurs when gesture starts.
/// </summary>
public event EventHandler<EventArgs> PanStarted
{
add { panStartedInvoker += value; }
remove { panStartedInvoker -= value; }
}
/// <summary>
/// Occurs when gesture updates.
/// </summary>
public event EventHandler<EventArgs> Panned
{
add { pannedInvoker += value; }
remove { pannedInvoker -= value; }
}
/// <summary>
/// Occurs when gesture ends.
/// </summary>
public event EventHandler<EventArgs> PanCompleted
{
add { panCompletedInvoker += value; }
remove { panCompletedInvoker -= value; }
}
// iOS Events AOT hack
private EventHandler<EventArgs> panStartedInvoker, pannedInvoker, panCompletedInvoker;
#endregion
#region Public properties
/// <summary>
/// Gets or sets minimum distance in cm for touch points to move for gesture to begin.
/// </summary>
/// <value>Minimum value in cm user must move their fingers to start this gesture.</value>
public float MovementThreshold
{
get { return movementThreshold; }
set { movementThreshold = value; }
}
/// <summary>
/// Gets delta position in world coordinates.
/// </summary>
/// <value>Delta position between this frame and the last frame in world coordinates.</value>
public Vector3 WorldDeltaPosition { get; private set; }
/// <summary>
/// Gets delta position in local coordinates.
/// </summary>
/// <value>Delta position between this frame and the last frame in local coordinates.</value>
public Vector3 LocalDeltaPosition
{
get { return TransformUtils.GlobalToLocalVector(cachedTransform, WorldDeltaPosition); }
}
/// <inheritdoc />
public override Vector2 ScreenPosition
{
get
{
if (activeTouches.Count < 2) return base.ScreenPosition;
return (activeTouches[0].Position + activeTouches[1].Position) * .5f;
}
}
/// <inheritdoc />
public override Vector2 PreviousScreenPosition
{
get
{
if (activeTouches.Count < 2) return base.PreviousScreenPosition;
return (activeTouches[0].PreviousPosition + activeTouches[1].PreviousPosition) * .5f;
}
}
#endregion
#region Private variables
[SerializeField]
private float movementThreshold = 0.5f;
private Vector2 movementBuffer;
private bool isMoving = false;
#endregion
#region Gesture callbacks
/// <inheritdoc />
protected override void touchesMoved(IList<ITouch> touches)
{
base.touchesMoved(touches);
var worldDelta = Vector3.zero;
Vector3 oldWorldCenter, newWorldCenter;
Vector2 oldScreenCenter = PreviousScreenPosition;
Vector2 newScreenCenter = ScreenPosition;
if (isMoving)
{
oldWorldCenter = projectionLayer.ProjectTo(oldScreenCenter, WorldTransformPlane);
newWorldCenter = projectionLayer.ProjectTo(newScreenCenter, WorldTransformPlane);
worldDelta = newWorldCenter - oldWorldCenter;
}
else
{
movementBuffer += newScreenCenter - oldScreenCenter;
var dpiMovementThreshold = MovementThreshold * touchManager.DotsPerCentimeter;
if (movementBuffer.sqrMagnitude > dpiMovementThreshold * dpiMovementThreshold)
{
isMoving = true;
oldWorldCenter = projectionLayer.ProjectTo(oldScreenCenter - movementBuffer, WorldTransformPlane);
newWorldCenter = projectionLayer.ProjectTo(newScreenCenter, WorldTransformPlane);
worldDelta = newWorldCenter - oldWorldCenter;
}
else
{
newWorldCenter = projectionLayer.ProjectTo(newScreenCenter - movementBuffer, WorldTransformPlane);
oldWorldCenter = newWorldCenter;
}
}
if (worldDelta != Vector3.zero)
{
switch (State)
{
case GestureState.Possible:
case GestureState.Began:
case GestureState.Changed:
PreviousWorldTransformCenter = oldWorldCenter;
WorldTransformCenter = newWorldCenter;
WorldDeltaPosition = worldDelta;
if (State == GestureState.Possible)
{
setState(GestureState.Began);
}
else
{
setState(GestureState.Changed);
}
break;
}
}
}
/// <inheritdoc />
protected override void onBegan()
{
base.onBegan();
panStartedInvoker.InvokeHandleExceptions(this, EventArgs.Empty);
pannedInvoker.InvokeHandleExceptions(this, EventArgs.Empty);
if (UseSendMessage && SendMessageTarget != null)
{
SendMessageTarget.SendMessage(PAN_START_MESSAGE, this, SendMessageOptions.DontRequireReceiver);
SendMessageTarget.SendMessage(PAN_MESSAGE, this, SendMessageOptions.DontRequireReceiver);
}
}
/// <inheritdoc />
protected override void onChanged()
{
base.onChanged();
pannedInvoker.InvokeHandleExceptions(this, EventArgs.Empty);
if (UseSendMessage && SendMessageTarget != null) SendMessageTarget.SendMessage(PAN_MESSAGE, this, SendMessageOptions.DontRequireReceiver);
}
/// <inheritdoc />
protected override void onRecognized()
{
base.onRecognized();
panCompletedInvoker.InvokeHandleExceptions(this, EventArgs.Empty);
if (UseSendMessage && SendMessageTarget != null) SendMessageTarget.SendMessage(PAN_COMPLETE_MESSAGE, this, SendMessageOptions.DontRequireReceiver);
}
/// <inheritdoc />
protected override void onFailed()
{
base.onFailed();
if (PreviousState != GestureState.Possible)
{
panCompletedInvoker.InvokeHandleExceptions(this, EventArgs.Empty);
if (UseSendMessage && SendMessageTarget != null) SendMessageTarget.SendMessage(PAN_COMPLETE_MESSAGE, this, SendMessageOptions.DontRequireReceiver);
}
}
/// <inheritdoc />
protected override void onCancelled()
{
base.onCancelled();
if (PreviousState != GestureState.Possible)
{
panCompletedInvoker.InvokeHandleExceptions(this, EventArgs.Empty);
if (UseSendMessage && SendMessageTarget != null) SendMessageTarget.SendMessage(PAN_COMPLETE_MESSAGE, this, SendMessageOptions.DontRequireReceiver);
}
}
/// <inheritdoc />
protected override void reset()
{
base.reset();
WorldDeltaPosition = Vector3.zero;
movementBuffer = Vector2.zero;
isMoving = false;
}
#endregion
}
}
| |
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Backoffice_Controls_EditRekamMedisRI : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request["RawatInapId"] != null && Request["RawatInapId"] != "")
{
FillDataRawatInap(int.Parse(Request["RawatInapId"]));
}
}
}
public void GetListJenisPenyakit()
{
string JenisPenyakitId = "";
SIMRS.DataAccess.RS_JenisPenyakit myObj = new SIMRS.DataAccess.RS_JenisPenyakit();
DataTable dt = myObj.GetList();
lbJenisPenyakitAvaliable.Items.Clear();
int i = 0;
foreach (DataRow dr in dt.Rows)
{
lbJenisPenyakitAvaliable.Items.Add("");
lbJenisPenyakitAvaliable.Items[i].Text = dr["Kode"].ToString() + " " + dr["Nama"].ToString();
lbJenisPenyakitAvaliable.Items[i].Value = dr["Id"].ToString();
if (dr["Id"].ToString() == JenisPenyakitId)
{
lbJenisPenyakitAvaliable.SelectedIndex = i;
}
i++;
}
}
public void GetListStatusRM(string StatusRMId)
{
SIMRS.DataAccess.RS_StatusRM myObj = new SIMRS.DataAccess.RS_StatusRM();
myObj.JenisPoliklinikId = 3;//Rawat Inap
DataTable dt = myObj.GetListWJenisPoliklinikId();
cmbStatusRM.Items.Clear();
int i = 0;
cmbStatusRM.Items.Add("");
cmbStatusRM.Items[i].Text = "";
cmbStatusRM.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbStatusRM.Items.Add("");
cmbStatusRM.Items[i].Text = dr["Nama"].ToString();
cmbStatusRM.Items[i].Value = dr["StatusRMId"].ToString();
if (dr["StatusRMId"].ToString() == StatusRMId)
{
cmbStatusRM.SelectedIndex = i;
}
i++;
}
}
public void FillDataRawatInap(Int64 RawatInapId)
{
SIMRS.DataAccess.RS_RawatInap myObj = new SIMRS.DataAccess.RS_RawatInap();
myObj.RawatInapId = RawatInapId;
DataTable dt = myObj.SelectOne();
if (dt.Rows.Count > 0)
{
DataRow row = dt.Rows[0];
txtRegistrasiId.Value = row["RegistrasiId"].ToString();
txtRawatInapId.Value = row["RawatInapId"].ToString();
txtPasienId.Value = row["PasienId"].ToString();
txtStatusRawatInap.Value = row["StatusRawatInap"].ToString();
lblNoRMHeader.Text = row["NoRM"].ToString();
lblNamaPasienHeader.Text = row["Nama"].ToString();
txtTanggalMasuk.Value = ((DateTime)row["TanggalMasuk"]).ToString("dd/MM/yyyy");
txtJamMasuk.Value = ((DateTime)row["TanggalMasuk"]).ToString("HH:mm");
lblNoRegistrasi.Text = row["NoRegistrasi"].ToString();
lblTanggalMasuk.Text = ((DateTime)row["TanggalMasuk"]).ToString("dd/MM/yyyy HH:mm");
lblRuangRawat.Text = row["KelasNama"].ToString() + " - " + row["RuangNama"].ToString() + " - " + row["NomorRuang"].ToString();
lblDokter.Text = row["DokterNama"].ToString();
GetDataRekamMedis(int.Parse(txtRegistrasiId.Value));
GetListJenisPenyakit();
}
}
public void GetDataRekamMedis(Int64 RegistrasiId)
{
SIMRS.DataAccess.RS_RM myObj = new SIMRS.DataAccess.RS_RM();
myObj.RegistrasiId = RegistrasiId;
DataTable dt = myObj.SelectOne();
if (dt.Rows.Count > 0)
{
DataRow row = dt.Rows[0];
txtTanggalKeluar.Text = ((DateTime)row["TanggalKeluar"]).ToString("dd/MM/yyyy");
txtJamKeluar.Text = ((DateTime)row["TanggalKeluar"]).ToString("HH:mm");
txtKeluhanUtama.Text = row["KeluhanUtama"].ToString();
txtKeluhanTambahan.Text = row["KeluhanTambahan"].ToString();
txtDiagnosa.Text = row["Diagnosa"].ToString();
txtTindakanMedis.Text = row["TindakanMedis"].ToString();
txtObat.Text = row["Obat"].ToString();
GetListStatusRM(row["StatusRMId"].ToString());
txtKeteranganStatusRM.Text = row["KeteranganStatus"].ToString();
txtKeteranganLain.Text = row["Keterangan"].ToString();
SIMRS.DataAccess.RS_RMJenisPenyakit myPenyakit = new SIMRS.DataAccess.RS_RMJenisPenyakit();
myPenyakit.RegistrasiId = RegistrasiId;
DataTable dtPenyakit = myPenyakit.SelectAllWRegistrasiIdLogic();
if (dtPenyakit.Rows.Count > 0)
{
int i = 0;
foreach (DataRow dr in dtPenyakit.Rows)
{
lbJenisPenyakit.Items.Add("");
lbJenisPenyakit.Items[i].Value = dr["JenisPenyakitId"].ToString();
lbJenisPenyakit.Items[i].Text = dr["JenisPenyakitKode"].ToString() + ". " + dr["JenisPenyakitNama"].ToString();
i++;
}
}
}
else
{
EmptyFormRekamMedis();
}
}
public void EmptyFormRekamMedis()
{
txtTanggalKeluar.Text = "";
txtJamKeluar.Text = "";
txtKeluhanUtama.Text = "";
txtKeluhanTambahan.Text = "";
txtDiagnosa.Text = "";
txtTindakanMedis.Text = "";
txtObat.Text = "";
GetListStatusRM("");
txtKeteranganStatusRM.Text = "";
txtKeteranganLain.Text = "";
lbJenisPenyakit.Items.Clear();
}
protected void btnAddJenisPenyakit_Click(object sender, EventArgs e)
{
if (lbJenisPenyakitAvaliable.SelectedIndex != -1)
{
int i = lbJenisPenyakit.Items.Count;
bool exist = false;
for (int j = 0; j < i; j++)
{
if (lbJenisPenyakit.Items[j].Value == lbJenisPenyakitAvaliable.SelectedItem.Value)
{
exist = true;
break;
}
}
if (!exist)
{
lbJenisPenyakit.Items.Add("");
lbJenisPenyakit.Items[i].Value = lbJenisPenyakitAvaliable.SelectedItem.Value;
lbJenisPenyakit.Items[i].Text = lbJenisPenyakitAvaliable.SelectedItem.Text;
}
lbJenisPenyakitAvaliable.SelectedIndex = -1;
}
}
protected void btnRemoveJenisPenyakit_Click(object sender, EventArgs e)
{
if (lbJenisPenyakit.SelectedIndex != -1)
{
lbJenisPenyakit.Items.RemoveAt(lbJenisPenyakit.SelectedIndex);
}
}
public bool OnSave()
{
bool result = false;
lblError.Text = "";
if (Session["SIMRS.UserId"] == null)
{
Response.Redirect(Request.ApplicationPath + "/Backoffice/login.aspx");
}
int UserId = (int)Session["SIMRS.UserId"];
if (!Page.IsValid)
{
return false;
}
SIMRS.DataAccess.RS_RM myObj = new SIMRS.DataAccess.RS_RM();
myObj.RegistrasiId = Int64.Parse(txtRegistrasiId.Value);
DataTable dtRM = myObj.SelectOne();
DateTime TanggalMasuk = DateTime.Parse(txtTanggalMasuk.Value);
TanggalMasuk = TanggalMasuk.AddHours(double.Parse(txtJamMasuk.Value.Substring(0, 2)));
TanggalMasuk = TanggalMasuk.AddMinutes(double.Parse(txtJamMasuk.Value.Substring(3, 2)));
myObj.TanggalMasuk = TanggalMasuk;
DateTime TanggalKeluar = DateTime.Parse(txtTanggalKeluar.Text);
TanggalKeluar = TanggalKeluar.AddHours(double.Parse(txtJamKeluar.Text.Substring(0, 2)));
TanggalKeluar = TanggalKeluar.AddMinutes(double.Parse(txtJamKeluar.Text.Substring(3, 2)));
myObj.TanggalKeluar = TanggalKeluar;
myObj.KeluhanUtama = txtKeluhanUtama.Text;
myObj.KeluhanTambahan = txtKeluhanTambahan.Text;
myObj.Diagnosa = txtDiagnosa.Text;
myObj.TindakanMedis = txtTindakanMedis.Text;
myObj.Obat = txtObat.Text;
if (cmbStatusRM.SelectedIndex> 0)
myObj.StatusRMId = int.Parse(cmbStatusRM.SelectedItem.Value);
myObj.KeteranganStatus = txtKeteranganStatusRM.Text;
myObj.Keterangan = txtKeteranganLain.Text;
if (dtRM.Rows.Count == 0)
{
myObj.CreatedBy = UserId;
myObj.CreatedDate = DateTime.Now;
result = myObj.Insert();
}
else {
myObj.ModifiedBy = UserId;
myObj.ModifiedDate = DateTime.Now;
result = myObj.Update();
}
if (lbJenisPenyakit.Items.Count > 0)
{
SIMRS.DataAccess.RS_RMJenisPenyakit myPenyakit = new SIMRS.DataAccess.RS_RMJenisPenyakit();
myPenyakit.RegistrasiId = Int64.Parse(txtRegistrasiId.Value);
myPenyakit.DeleteAllWRegistrasiIdLogic();
for (int i = 0; i < lbJenisPenyakit.Items.Count; i++)
{
myPenyakit.JenisPenyakitId = int.Parse(lbJenisPenyakit.Items[i].Value);
result = myPenyakit.Insert();
}
}
return result;
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
// ERROR: Not supported in C#: OptionDeclaration
using Microsoft.VisualBasic.PowerPacks;
namespace _4PosBackOffice.NET
{
internal partial class frmStockBarcode : System.Windows.Forms.Form
{
int gID;
private void loadLanguage()
{
//frmStockBarcode = No Code [Maintain Stock Item Barcodes]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then frmStockBarcode.Caption = rsLang("LanguageLayoutLnk_Description"): frmStockBarcode.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1074;
//Undo|Checked
if (modRecordSet.rsLang.RecordCount){cmdCancel.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdCancel.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
//cmdBuildBarcodes = No Code [&Build Barcode]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then cmdBuildBarcode.Caption = rsLang("LanguageLayoutLnk_Description"): cmdBuildBarcode.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//cmdBuildSPLU = No Code [Build Scale PLU]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then cmdBuildSPLU.Caption = rsLang("LanguageLayoutLnk_Description"): cmdBuildSPLU.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//NOTE: DB entry 1004 requires "&" for accelerator key!!!!
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1004;
//Exit|Checked
if (modRecordSet.rsLang.RecordCount){cmdClose.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdClose.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
//lblHeading = No Code/Dynamic/NA!
//_lbl_2 = No Code [Barcodes]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then _lbl_2.Caption = rsLang("LanguageLayoutLnk_Description"): _lbl_2.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//NOTE: DB Entry 2192 wrong case: "shrink" instead of "shrink"!!!
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2192;
//shrink|Checked
if (modRecordSet.rsLang.RecordCount){_lbl_13.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lbl_13.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
//lbl(12) = No Code [Bar Code]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then lbl(12).Caption = rsLang("LanguageLayoutLnk_Description"): lbl(12).RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1195;
//Disable|Checked
if (modRecordSet.rsLang.RecordCount){_lbl_14.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lbl_14.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
//lblBarcode(0) = No Code [Bonne]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then lblBarcode(0).Caption = rsLang("LanguageLayoutLnk_Description"): lblBarcode(0).RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
modRecordSet.rsHelp.filter = "Help_Section=0 AND Help_Form='" + this.Name + "'";
//UPGRADE_ISSUE: Form property frmStockBarcode.ToolTip1 was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"'
if (modRecordSet.rsHelp.RecordCount)
this.ToolTip1 = modRecordSet.rsHelp.Fields("Help_ContextID").Value;
}
public void loadItem(ref int id)
{
ADODB.Recordset rs = default(ADODB.Recordset);
string sql = null;
short x = 0;
gID = id;
rs = modRecordSet.getRS(ref "SELECT StockItem_Name FROM StockItem WHERE StockItemID = " + gID);
if (rs.EOF | rs.EOF) {
} else {
lblHeading.Text = rs.Fields("StockItem_Name").Value;
}
sql = "INSERT INTO Catalogue ( Catalogue_StockItemID, Catalogue_Quantity, Catalogue_Barcode, Catalogue_Deposit, Catalogue_Content, Catalogue_Disabled ) ";
sql = sql + "SELECT theJoin.StockItemID, theJoin.ShrinkItem_Quantity, 'CODE' AS Expr1, 0 AS deposit, 0 AS content, 0 AS disabled FROM [SELECT StockItem.StockItemID, ShrinkItem.ShrinkItem_Quantity FROM ShrinkItem INNER JOIN ";
sql = sql + "StockItem ON ShrinkItem.ShrinkItem_ShrinkID = StockItem.StockItem_ShrinkID]. AS theJoin LEFT JOIN Catalogue ON (theJoin.ShrinkItem_Quantity = Catalogue.Catalogue_Quantity) AND (theJoin.StockItemID = Catalogue.Catalogue_StockItemID) ";
sql = sql + "WHERE (((theJoin.StockItemID)=" + id + ") AND ((Catalogue.Catalogue_StockItemID) Is Null));";
modRecordSet.cnnDB.Execute(sql);
rs = modRecordSet.getRS(ref "SELECT Catalogue.Catalogue_StockItemID, Catalogue.Catalogue_Quantity, Catalogue.Catalogue_Barcode, Catalogue.Catalogue_Deposit, Catalogue.Catalogue_Content, Catalogue.Catalogue_Disabled, ShrinkItem.ShrinkItem_Code FROM Catalogue INNER JOIN (StockItem INNER JOIN ShrinkItem ON StockItem.StockItem_ShrinkID = ShrinkItem.ShrinkItem_ShrinkID) ON (ShrinkItem.ShrinkItem_Quantity = Catalogue.Catalogue_Quantity) AND (Catalogue.Catalogue_StockItemID = StockItem.StockItemID) Where (((Catalogue.Catalogue_StockItemID) = " + gID + ")) ORDER BY Catalogue.Catalogue_Quantity;");
//Set rs = getRS("SELECT Catalogue.Catalogue_Quantity, Catalogue.Catalogue_Barcode, Catalogue.Catalogue_Disabled From Catalogue Where (((Catalogue.Catalogue_StockItemID) = " & gID & ")) ORDER BY Catalogue.Catalogue_Quantity;")
//For x = 1 To lblBarcode.Count - 1
//lblBarcode.Unload(x)
//txtBarcode.Unload(x)
//chkBarcode.Unload(x)
//Next
x = -1;
while (!(rs.EOF)) {
x = x + 1;
if (x) {
//txtBarcode.Load(x)
_txtBarcode_0.Top = sizeConvertors.twipsToPixels(sizeConvertors.pixelToTwips(_txtBarcode_0.Top, false) + sizeConvertors.pixelToTwips(_txtBarcode_0.Height, false) + 30, false);
_txtBarcode_0.Visible = true;
_txtBarcode_0.TabIndex = _txtBarcode_0.TabIndex + 1;
//lblBarcode.Load(x)
_lblBarcode_0.Top = sizeConvertors.twipsToPixels(sizeConvertors.pixelToTwips(_txtBarcode_0.Top, false) + sizeConvertors.pixelToTwips(_txtBarcode_0.Height, false) + 60, false);
_lblBarcode_0.Visible = true;
_lblBarcode_0.BringToFront();
//chkBarcode.Load(x)
_chkBarcode_0.Top = sizeConvertors.twipsToPixels(sizeConvertors.pixelToTwips(_txtBarcode_0.Top, false) + sizeConvertors.pixelToTwips(_txtBarcode_0.Height, false) + 90, false);
_chkBarcode_0.Visible = true;
}
_lblBarcode_0.Text = rs.Fields("Catalogue_Quantity").Value;
_txtBarcode_0.Text = rs.Fields("Catalogue_Barcode").Value;
_txtBarcode_0.Tag = _txtBarcode_0.Text;
_chkBarcode_0.CheckState = System.Math.Abs(Convert.ToInt16(rs.Fields("Catalogue_Disabled").Value));
_chkBarcode_0.Tag = _chkBarcode_0.CheckState;
rs.MoveNext();
}
Shape1.Height = sizeConvertors.twipsToPixels(sizeConvertors.pixelToTwips(_lblBarcode_0.Top, false) + sizeConvertors.pixelToTwips(_lblBarcode_0.Height, false) + 240 - sizeConvertors.pixelToTwips(Shape1.Top, false), false);
Height = sizeConvertors.twipsToPixels(sizeConvertors.pixelToTwips(Shape1.Top, false) + sizeConvertors.pixelToTwips(Shape1.Height, false) + 560, false);
}
private void cmdBuildBarcodes_Click(System.Object eventSender, System.EventArgs eventArgs)
{
modApplication.buildBarcodes(ref gID);
loadItem(ref gID);
}
private void cmdBuildSPLU_Click(System.Object eventSender, System.EventArgs eventArgs)
{
ADODB.Recordset rsChk = default(ADODB.Recordset);
rsChk = modRecordSet.getRS(ref "SELECT TOP 1 Catalogue.Catalogue_StockItemID, Catalogue.Catalogue_Quantity, Catalogue.Catalogue_Barcode From Catalogue Where (((CDbl(IIf(IsNumeric([Catalogue].[Catalogue_Barcode]), [Catalogue].[Catalogue_Barcode], 0))) > 0 And (CDbl(IIf(IsNumeric([Catalogue].[Catalogue_Barcode]), [Catalogue].[Catalogue_Barcode], 0))) < 99999)) ORDER BY CLng(Catalogue.Catalogue_Barcode) DESC;");
if (rsChk.RecordCount) {
_txtBarcode_0.Text = Convert.ToString(Convert.ToDouble(rsChk.Fields("Catalogue_Barcode").Value) + 1);
} else {
_txtBarcode_0.Text = Convert.ToString(1);
}
}
private void cmdCancel_Click(System.Object eventSender, System.EventArgs eventArgs)
{
//Dim x As Short
//For x = 0 To txtBarcode.UBound
_txtBarcode_0.Text = _txtBarcode_0.Tag;
_chkBarcode_0.CheckState = Convert.ToInt16(_chkBarcode_0.Tag);
//Next
}
private void cmdClose_Click(System.Object eventSender, System.EventArgs eventArgs)
{
short x = 0;
ADODB.Recordset rsChk = default(ADODB.Recordset);
if (modApplication.bGRVNewItemBarcode == true) {
//For x = 0 To txtBarcode.UBound
//Set rsChk = getRS("SELECT Catalogue_Barcode FROM Catalogue WHERE Catalogue_Barcode = '" & Replace(_txtBarcode_0.Text, "'", "''") & "' AND Catalogue_StockItemID <> " & gID & " AND Catalogue_Disabled=False;")
rsChk = modRecordSet.getRS(ref "SELECT Catalogue.Catalogue_Barcode, StockItem.StockItem_Name FROM StockItem INNER JOIN Catalogue ON StockItem.StockItemID = Catalogue.Catalogue_StockItemID WHERE (((Catalogue.Catalogue_Barcode)='" + Strings.Replace(_txtBarcode_0.Text, "'", "''") + "') AND ((Catalogue.Catalogue_StockItemID)<>" + gID + ") AND ((Catalogue.Catalogue_Disabled)=False) AND ((StockItem.StockItem_Disabled)=False) AND ((StockItem.StockItem_Discontinued)=False));");
if (rsChk.RecordCount) {
Interaction.MsgBox("'" + rsChk.Fields("Catalogue_Barcode").Value + "' Barcode has already been used by '" + rsChk.Fields("StockItem_Name").Value + "' , Please type in different Barcode or use Build Barcode option.", MsgBoxStyle.ApplicationModal + MsgBoxStyle.Information + MsgBoxStyle.OkOnly, _4PosBackOffice.NET.My.MyProject.Application.Info.Title);
return;
}
//If _txtBarcode_0.Text <> _txtBarcode_0.Tag Then
// sql = "UPDATE Catalogue SET Catalogue_Barcode = '" & Replace(_txtBarcode_0.Text, "'", "''") & "' WHERE Catalogue_StockItemID = " & gID & " AND Catalogue_Quantity = " & _lblBarcode_0.Caption
// cnnDB.Execute sql
//End If
//If _chkBarcode_0.value <> _chkBarcode_0.Tag Then
// sql = "UPDATE Catalogue SET Catalogue_Disabled = '" & _chkBarcode_0.value & "' WHERE Catalogue_StockItemID = " & gID & " AND Catalogue_Quantity = " & _lblBarcode_0.Caption
// cnnDB.Execute sql
//End If
//Next
this.Close();
} else {
this.Close();
}
}
private void frmStockBarcode_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
{
short KeyAscii = Strings.Asc(eventArgs.KeyChar);
switch (KeyAscii) {
case System.Windows.Forms.Keys.Escape:
KeyAscii = 0;
System.Windows.Forms.Application.DoEvents();
cmdClose_Click(cmdClose, new System.EventArgs());
break;
}
eventArgs.KeyChar = Strings.Chr(KeyAscii);
if (KeyAscii == 0) {
eventArgs.Handled = true;
}
}
private void frmStockBarcode_Load(System.Object eventSender, System.EventArgs eventArgs)
{
loadLanguage();
}
private void frmStockBarcode_FormClosed(System.Object eventSender, System.Windows.Forms.FormClosedEventArgs eventArgs)
{
short x = 0;
string sql = null;
//For x = 0 To txtBarcode.UBound
if (_txtBarcode_0.Text != _txtBarcode_0.Tag) {
sql = "UPDATE Catalogue SET Catalogue_Barcode = '" + Strings.Replace(_txtBarcode_0.Text, "'", "''") + "' WHERE Catalogue_StockItemID = " + gID + " AND Catalogue_Quantity = " + _lblBarcode_0.Text;
modRecordSet.cnnDB.Execute(sql);
}
if (_chkBarcode_0.CheckState != Convert.ToDouble(_chkBarcode_0.Tag)) {
sql = "UPDATE Catalogue SET Catalogue_Disabled = '" + _chkBarcode_0.CheckState + "' WHERE Catalogue_StockItemID = " + gID + " AND Catalogue_Quantity = " + _lblBarcode_0.Text;
modRecordSet.cnnDB.Execute(sql);
}
// Next
}
//Handles txtBarcode.Enter
private void txtBarcode_Enter(System.Object eventSender, System.EventArgs eventArgs)
{
//Dim Index As Short = txtBarcode.GetIndex(eventSender)
TextBox txtBox = new TextBox();
txtBox = (TextBox)eventSender;
txtBox.SelectionStart = 0;
txtBox.SelectionLength = Strings.Len(txtBox.Text);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Globalization;
using Xunit;
namespace System.Tests
{
public static class Int64Tests
{
[Fact]
public static void Ctor_Empty()
{
var i = new long();
Assert.Equal(0, i);
}
[Fact]
public static void Ctor_Value()
{
long i = 41;
Assert.Equal(41, i);
}
[Fact]
public static void MaxValue()
{
Assert.Equal(0x7FFFFFFFFFFFFFFF, long.MaxValue);
}
[Fact]
public static void MinValue()
{
Assert.Equal(unchecked((long)0x8000000000000000), long.MinValue);
}
[Theory]
[InlineData((long)234, (long)234, 0)]
[InlineData((long)234, long.MinValue, 1)]
[InlineData((long)234, (long)-123, 1)]
[InlineData((long)234, (long)0, 1)]
[InlineData((long)234, (long)123, 1)]
[InlineData((long)234, (long)456, -1)]
[InlineData((long)234, long.MaxValue, -1)]
[InlineData((long)-234, (long)-234, 0)]
[InlineData((long)-234, (long)234, -1)]
[InlineData((long)-234, (long)-432, 1)]
[InlineData((long)234, null, 1)]
public static void CompareTo(long i, object value, long expected)
{
if (value is long)
{
Assert.Equal(expected, Math.Sign(i.CompareTo((long)value)));
}
IComparable comparable = i;
Assert.Equal(expected, Math.Sign(comparable.CompareTo(value)));
}
[Fact]
public static void CompareTo_ObjectNotLong_ThrowsArgumentException()
{
IComparable comparable = (long)234;
Assert.Throws<ArgumentException>(null, () => comparable.CompareTo("a")); // Obj is not a long
Assert.Throws<ArgumentException>(null, () => comparable.CompareTo(234)); // Obj is not a long
}
[Theory]
[InlineData((long)789, (long)789, true)]
[InlineData((long)789, (long)-789, false)]
[InlineData((long)789, (long)0, false)]
[InlineData((long)0, (long)0, true)]
[InlineData((long)-789, (long)-789, true)]
[InlineData((long)-789, (long)789, false)]
[InlineData((long)789, null, false)]
[InlineData((long)789, "789", false)]
[InlineData((long)789, 789, false)]
public static void Equals(long i1, object obj, bool expected)
{
if (obj is long)
{
long i2 = (long)obj;
Assert.Equal(expected, i1.Equals(i2));
Assert.Equal(expected, i1.GetHashCode().Equals(i2.GetHashCode()));
}
Assert.Equal(expected, i1.Equals(obj));
}
public static IEnumerable<object[]> ToString_TestData()
{
NumberFormatInfo emptyFormat = NumberFormatInfo.CurrentInfo;
yield return new object[] { long.MinValue, "G", emptyFormat, "-9223372036854775808" };
yield return new object[] { (long)-4567, "G", emptyFormat, "-4567" };
yield return new object[] { (long)0, "G", emptyFormat, "0" };
yield return new object[] { (long)4567, "G", emptyFormat, "4567" };
yield return new object[] { long.MaxValue, "G", emptyFormat, "9223372036854775807" };
yield return new object[] { (long)0x2468, "x", emptyFormat, "2468" };
yield return new object[] { (long)2468, "N", emptyFormat, string.Format("{0:N}", 2468.00) };
NumberFormatInfo customFormat = new NumberFormatInfo();
customFormat.NegativeSign = "#";
customFormat.NumberDecimalSeparator = "~";
customFormat.NumberGroupSeparator = "*";
yield return new object[] { (long)-2468, "N", customFormat, "#2*468~00" };
yield return new object[] { (long)2468, "N", customFormat, "2*468~00" };
}
[Theory]
[MemberData(nameof(ToString_TestData))]
public static void ToString(long i, string format, IFormatProvider provider, string expected)
{
// Format is case insensitive
string upperFormat = format.ToUpperInvariant();
string lowerFormat = format.ToLowerInvariant();
string upperExpected = expected.ToUpperInvariant();
string lowerExpected = expected.ToLowerInvariant();
bool isDefaultProvider = (provider == null || provider == NumberFormatInfo.CurrentInfo);
if (string.IsNullOrEmpty(format) || format.ToUpperInvariant() == "G")
{
if (isDefaultProvider)
{
Assert.Equal(upperExpected, i.ToString());
Assert.Equal(upperExpected, i.ToString((IFormatProvider)null));
}
Assert.Equal(upperExpected, i.ToString(provider));
}
if (isDefaultProvider)
{
Assert.Equal(upperExpected, i.ToString(upperFormat));
Assert.Equal(lowerExpected, i.ToString(lowerFormat));
Assert.Equal(upperExpected, i.ToString(upperFormat, null));
Assert.Equal(lowerExpected, i.ToString(lowerFormat, null));
}
Assert.Equal(upperExpected, i.ToString(upperFormat, provider));
Assert.Equal(lowerExpected, i.ToString(lowerFormat, provider));
}
[Fact]
public static void ToString_InvalidFormat_ThrowsFormatException()
{
long i = 123;
Assert.Throws<FormatException>(() => i.ToString("Y")); // Invalid format
Assert.Throws<FormatException>(() => i.ToString("Y", null)); // Invalid format
}
public static IEnumerable<object[]> Parse_Valid_TestData()
{
NumberStyles defaultStyle = NumberStyles.Integer;
NumberFormatInfo emptyFormat = new NumberFormatInfo();
NumberFormatInfo customFormat = new NumberFormatInfo();
customFormat.CurrencySymbol = "$";
yield return new object[] { "-9223372036854775808", defaultStyle, null, -9223372036854775808 };
yield return new object[] { "-123", defaultStyle, null, (long)-123 };
yield return new object[] { "0", defaultStyle, null, (long)0 };
yield return new object[] { "123", defaultStyle, null, (long)123 };
yield return new object[] { "+123", defaultStyle, null, (long)123 };
yield return new object[] { " 123 ", defaultStyle, null, (long)123 };
yield return new object[] { "9223372036854775807", defaultStyle, null, 9223372036854775807 };
yield return new object[] { "123", NumberStyles.HexNumber, null, (long)0x123 };
yield return new object[] { "abc", NumberStyles.HexNumber, null, (long)0xabc };
yield return new object[] { "ABC", NumberStyles.HexNumber, null, (long)0xabc };
yield return new object[] { "1000", NumberStyles.AllowThousands, null, (long)1000 };
yield return new object[] { "(123)", NumberStyles.AllowParentheses, null, (long)-123 }; // Parentheses = negative
yield return new object[] { "123", defaultStyle, emptyFormat, (long)123 };
yield return new object[] { "123", NumberStyles.Any, emptyFormat, (long)123 };
yield return new object[] { "12", NumberStyles.HexNumber, emptyFormat, (long)0x12 };
yield return new object[] { "$1,000", NumberStyles.Currency, customFormat, (long)1000 };
}
[Theory]
[MemberData(nameof(Parse_Valid_TestData))]
public static void Parse(string value, NumberStyles style, IFormatProvider provider, long expected)
{
long result;
// If no style is specified, use the (String) or (String, IFormatProvider) overload
if (style == NumberStyles.Integer)
{
Assert.True(long.TryParse(value, out result));
Assert.Equal(expected, result);
Assert.Equal(expected, long.Parse(value));
// If a format provider is specified, but the style is the default, use the (String, IFormatProvider) overload
if (provider != null)
{
Assert.Equal(expected, long.Parse(value, provider));
}
}
// If a format provider isn't specified, test the default one, using a new instance of NumberFormatInfo
Assert.True(long.TryParse(value, style, provider ?? new NumberFormatInfo(), out result));
Assert.Equal(expected, result);
// If a format provider isn't specified, test the default one, using the (String, NumberStyles) overload
if (provider == null)
{
Assert.Equal(expected, long.Parse(value, style));
}
Assert.Equal(expected, long.Parse(value, style, provider ?? new NumberFormatInfo()));
}
public static IEnumerable<object[]> Parse_Invalid_TestData()
{
NumberStyles defaultStyle = NumberStyles.Integer;
NumberFormatInfo customFormat = new NumberFormatInfo();
customFormat.CurrencySymbol = "$";
customFormat.NumberDecimalSeparator = ".";
yield return new object[] { null, defaultStyle, null, typeof(ArgumentNullException) };
yield return new object[] { "", defaultStyle, null, typeof(FormatException) };
yield return new object[] { " \t \n \r ", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "Garbage", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "abc", defaultStyle, null, typeof(FormatException) }; // Hex value
yield return new object[] { "1E23", defaultStyle, null, typeof(FormatException) }; // Exponent
yield return new object[] { "(123)", defaultStyle, null, typeof(FormatException) }; // Parentheses
yield return new object[] { 1000.ToString("C0"), defaultStyle, null, typeof(FormatException) }; // Currency
yield return new object[] { 1000.ToString("N0"), defaultStyle, null, typeof(FormatException) }; // Thousands
yield return new object[] { 678.90.ToString("F2"), defaultStyle, null, typeof(FormatException) }; // Decimal
yield return new object[] { "+-123", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "-+123", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "+abc", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { "-abc", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { "- 123", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "+ 123", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "abc", NumberStyles.None, null, typeof(FormatException) }; // Hex value
yield return new object[] { " 123 ", NumberStyles.None, null, typeof(FormatException) }; // Trailing and leading whitespace
yield return new object[] { "67.90", defaultStyle, customFormat, typeof(FormatException) }; // Decimal
yield return new object[] { "-9223372036854775809", defaultStyle, null, typeof(OverflowException) }; // < min value
yield return new object[] { "9223372036854775808", defaultStyle, null, typeof(OverflowException) }; // > max value
}
[Theory]
[MemberData(nameof(Parse_Invalid_TestData))]
public static void Parse_Invalid(string value, NumberStyles style, IFormatProvider provider, Type exceptionType)
{
long result;
// If no style is specified, use the (String) or (String, IFormatProvider) overload
if (style == NumberStyles.Integer)
{
Assert.False(long.TryParse(value, out result));
Assert.Equal(default(long), result);
Assert.Throws(exceptionType, () => long.Parse(value));
// If a format provider is specified, but the style is the default, use the (String, IFormatProvider) overload
if (provider != null)
{
Assert.Throws(exceptionType, () => long.Parse(value, provider));
}
}
// If a format provider isn't specified, test the default one, using a new instance of NumberFormatInfo
Assert.False(long.TryParse(value, style, provider ?? new NumberFormatInfo(), out result));
Assert.Equal(default(long), result);
// If a format provider isn't specified, test the default one, using the (String, NumberStyles) overload
if (provider == null)
{
Assert.Throws(exceptionType, () => long.Parse(value, style));
}
Assert.Throws(exceptionType, () => long.Parse(value, style, provider ?? new NumberFormatInfo()));
}
[Theory]
[InlineData(NumberStyles.HexNumber | NumberStyles.AllowParentheses)]
[InlineData(unchecked((NumberStyles)0xFFFFFC00))]
public static void TryParse_InvalidNumberStyle_ThrowsArgumentException(NumberStyles style)
{
long result = 0;
Assert.Throws<ArgumentException>(() => long.TryParse("1", style, null, out result));
Assert.Equal(default(long), result);
Assert.Throws<ArgumentException>(() => long.Parse("1", style));
Assert.Throws<ArgumentException>(() => long.Parse("1", style, null));
}
}
}
| |
/*
* Qa full api
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: all
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using 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;
namespace HostMe.Sdk.Model
{
/// <summary>
/// Waiter
/// </summary>
[DataContract]
public partial class Waiter : IEquatable<Waiter>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="Waiter" /> class.
/// </summary>
/// <param name="Id">Id.</param>
/// <param name="FullName">FullName.</param>
/// <param name="Email">Email.</param>
/// <param name="Color">Color.</param>
/// <param name="Tables">Tables.</param>
/// <param name="TotalTables">TotalTables.</param>
/// <param name="BusyTables">BusyTables.</param>
/// <param name="WorkLoad">WorkLoad.</param>
/// <param name="Image">Image.</param>
public Waiter(int? Id = null, string FullName = null, string Email = null, string Color = null, List<string> Tables = null, int? TotalTables = null, int? BusyTables = null, int? WorkLoad = null, string Image = null)
{
this.Id = Id;
this.FullName = FullName;
this.Email = Email;
this.Color = Color;
this.Tables = Tables;
this.TotalTables = TotalTables;
this.BusyTables = BusyTables;
this.WorkLoad = WorkLoad;
this.Image = Image;
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id", EmitDefaultValue=true)]
public int? Id { get; set; }
/// <summary>
/// Gets or Sets FullName
/// </summary>
[DataMember(Name="fullName", EmitDefaultValue=true)]
public string FullName { get; set; }
/// <summary>
/// Gets or Sets Email
/// </summary>
[DataMember(Name="email", EmitDefaultValue=true)]
public string Email { get; set; }
/// <summary>
/// Gets or Sets Color
/// </summary>
[DataMember(Name="color", EmitDefaultValue=true)]
public string Color { get; set; }
/// <summary>
/// Gets or Sets Tables
/// </summary>
[DataMember(Name="tables", EmitDefaultValue=true)]
public List<string> Tables { get; set; }
/// <summary>
/// Gets or Sets TotalTables
/// </summary>
[DataMember(Name="totalTables", EmitDefaultValue=true)]
public int? TotalTables { get; set; }
/// <summary>
/// Gets or Sets BusyTables
/// </summary>
[DataMember(Name="busyTables", EmitDefaultValue=true)]
public int? BusyTables { get; set; }
/// <summary>
/// Gets or Sets WorkLoad
/// </summary>
[DataMember(Name="workLoad", EmitDefaultValue=true)]
public int? WorkLoad { get; set; }
/// <summary>
/// Gets or Sets Image
/// </summary>
[DataMember(Name="image", EmitDefaultValue=true)]
public string Image { 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 Waiter {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" FullName: ").Append(FullName).Append("\n");
sb.Append(" Email: ").Append(Email).Append("\n");
sb.Append(" Color: ").Append(Color).Append("\n");
sb.Append(" Tables: ").Append(Tables).Append("\n");
sb.Append(" TotalTables: ").Append(TotalTables).Append("\n");
sb.Append(" BusyTables: ").Append(BusyTables).Append("\n");
sb.Append(" WorkLoad: ").Append(WorkLoad).Append("\n");
sb.Append(" Image: ").Append(Image).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 string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as Waiter);
}
/// <summary>
/// Returns true if Waiter instances are equal
/// </summary>
/// <param name="other">Instance of Waiter to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(Waiter other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Id == other.Id ||
this.Id != null &&
this.Id.Equals(other.Id)
) &&
(
this.FullName == other.FullName ||
this.FullName != null &&
this.FullName.Equals(other.FullName)
) &&
(
this.Email == other.Email ||
this.Email != null &&
this.Email.Equals(other.Email)
) &&
(
this.Color == other.Color ||
this.Color != null &&
this.Color.Equals(other.Color)
) &&
(
this.Tables == other.Tables ||
this.Tables != null &&
this.Tables.SequenceEqual(other.Tables)
) &&
(
this.TotalTables == other.TotalTables ||
this.TotalTables != null &&
this.TotalTables.Equals(other.TotalTables)
) &&
(
this.BusyTables == other.BusyTables ||
this.BusyTables != null &&
this.BusyTables.Equals(other.BusyTables)
) &&
(
this.WorkLoad == other.WorkLoad ||
this.WorkLoad != null &&
this.WorkLoad.Equals(other.WorkLoad)
) &&
(
this.Image == other.Image ||
this.Image != null &&
this.Image.Equals(other.Image)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Id != null)
hash = hash * 59 + this.Id.GetHashCode();
if (this.FullName != null)
hash = hash * 59 + this.FullName.GetHashCode();
if (this.Email != null)
hash = hash * 59 + this.Email.GetHashCode();
if (this.Color != null)
hash = hash * 59 + this.Color.GetHashCode();
if (this.Tables != null)
hash = hash * 59 + this.Tables.GetHashCode();
if (this.TotalTables != null)
hash = hash * 59 + this.TotalTables.GetHashCode();
if (this.BusyTables != null)
hash = hash * 59 + this.BusyTables.GetHashCode();
if (this.WorkLoad != null)
hash = hash * 59 + this.WorkLoad.GetHashCode();
if (this.Image != null)
hash = hash * 59 + this.Image.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using Test.Cryptography;
using Xunit;
namespace System.Security.Cryptography.Encryption.TripleDes.Tests
{
public static class TripleDESCipherTests
{
[Fact]
public static void TripleDESDefaults()
{
using (TripleDES des = TripleDESFactory.Create())
{
Assert.Equal(192, des.KeySize);
Assert.Equal(64, des.BlockSize);
}
}
[Fact]
public static void TripleDESRoundTrip192BitsNoneECB()
{
byte[] key = "c5629363d957054eba793093b83739bb78711db221a82379".HexToByteArray();
using (TripleDES alg = TripleDESFactory.Create())
{
alg.Key = key;
alg.Padding = PaddingMode.None;
alg.Mode = CipherMode.ECB;
byte[] plainText = "de7d2dddea96b691e979e647dc9d3ca27d7f1ad673ca9570".HexToByteArray();
byte[] cipher = alg.Encrypt(plainText);
byte[] expectedCipher = "e56f72478c7479d169d54c0548b744af5b53efb1cdd26037".HexToByteArray();
Assert.Equal<byte>(expectedCipher, cipher);
byte[] decrypted = alg.Decrypt(cipher);
byte[] expectedDecrypted = "de7d2dddea96b691e979e647dc9d3ca27d7f1ad673ca9570".HexToByteArray();
Assert.Equal<byte>(expectedDecrypted, decrypted);
}
}
[Fact]
public static void TripleDESRoundTrip192BitsNoneCBC()
{
byte[] key = "b43eaf0260813fb47c87ae073a146006d359ad04061eb0e6".HexToByteArray();
byte[] iv = "5fbc5bc21b8597d8".HexToByteArray();
using (TripleDES alg = TripleDESFactory.Create())
{
alg.Key = key;
alg.IV = iv;
alg.Padding = PaddingMode.None;
alg.Mode = CipherMode.CBC;
byte[] plainText = "79a86903608e133e020e1dc68c9835250c2f17b0ebeed91b".HexToByteArray();
byte[] cipher = alg.Encrypt(plainText);
byte[] expectedCipher = "dea36279600f19c602b6ed9bf3ffdac5ebf25c1c470eb61c".HexToByteArray();
Assert.Equal<byte>(expectedCipher, cipher);
byte[] decrypted = alg.Decrypt(cipher);
byte[] expectedDecrypted = "79a86903608e133e020e1dc68c9835250c2f17b0ebeed91b".HexToByteArray();
Assert.Equal<byte>(expectedDecrypted, decrypted);
}
}
[Fact]
public static void TripleDESRoundTrip192BitsZerosECB()
{
byte[] key = "9da5b265179d65f634dfc95513f25094411e51bb3be877ef".HexToByteArray();
using (TripleDES alg = TripleDESFactory.Create())
{
alg.Key = key;
alg.Padding = PaddingMode.Zeros;
alg.Mode = CipherMode.ECB;
byte[] plainText = "77a8b2efb45addb38d7ef3aa9e6ab5d71957445ab8".HexToByteArray();
byte[] cipher = alg.Encrypt(plainText);
byte[] expectedCipher = "149ec32f558b27c7e4151e340d8184f18b4e25d2518f69d9".HexToByteArray();
Assert.Equal<byte>(expectedCipher, cipher);
byte[] decrypted = alg.Decrypt(cipher);
byte[] expectedDecrypted = "77a8b2efb45addb38d7ef3aa9e6ab5d71957445ab8000000".HexToByteArray();
Assert.Equal<byte>(expectedDecrypted, decrypted);
}
}
[Fact]
public static void TripleDESRoundTrip192BitsISO10126ECB()
{
byte[] key = "9da5b265179d65f634dfc95513f25094411e51bb3be877ef".HexToByteArray();
using (TripleDES alg = TripleDESFactory.Create())
{
alg.Key = key;
alg.Padding = PaddingMode.ISO10126;
alg.Mode = CipherMode.ECB;
byte[] plainText = "77a8b2efb45addb38d7ef3aa9e6ab5d71957445ab8".HexToByteArray();
byte[] cipher = alg.Encrypt(plainText);
// the padding data for ISO10126 is made up of random bytes, so we cannot actually test
// the full encrypted text. We need to strip the padding and then compare
byte[] decrypted = alg.Decrypt(cipher);
Assert.Equal<byte>(plainText, decrypted);
}
}
[Fact]
public static void TripleDESRoundTrip192BitsANSIX923ECB()
{
byte[] key = "9da5b265179d65f634dfc95513f25094411e51bb3be877ef".HexToByteArray();
using (TripleDES alg = TripleDESFactory.Create())
{
alg.Key = key;
alg.Padding = PaddingMode.ANSIX923;
alg.Mode = CipherMode.ECB;
byte[] plainText = "77a8b2efb45addb38d7ef3aa9e6ab5d71957445ab8".HexToByteArray();
byte[] cipher = alg.Encrypt(plainText);
byte[] expectedCipher = "149ec32f558b27c7e4151e340d8184f1c90f0a499e20fda9".HexToByteArray();
Assert.Equal<byte>(expectedCipher, cipher);
byte[] decrypted = alg.Decrypt(cipher);
byte[] expectedDecrypted = "77a8b2efb45addb38d7ef3aa9e6ab5d71957445ab8".HexToByteArray();
Assert.Equal<byte>(plainText, decrypted);
}
}
[Fact]
public static void TripleDES_FailureToRoundTrip192Bits_DifferentPadding_ANSIX923_ZerosECB()
{
byte[] key = "9da5b265179d65f634dfc95513f25094411e51bb3be877ef".HexToByteArray();
using (TripleDES alg = TripleDESFactory.Create())
{
alg.Key = key;
alg.Padding = PaddingMode.ANSIX923;
alg.Mode = CipherMode.ECB;
byte[] plainText = "77a8b2efb45addb38d7ef3aa9e6ab5d71957445ab8".HexToByteArray();
byte[] cipher = alg.Encrypt(plainText);
byte[] expectedCipher = "149ec32f558b27c7e4151e340d8184f1c90f0a499e20fda9".HexToByteArray();
Assert.Equal<byte>(expectedCipher, cipher);
alg.Padding = PaddingMode.Zeros;
byte[] decrypted = alg.Decrypt(cipher);
byte[] expectedDecrypted = "77a8b2efb45addb38d7ef3aa9e6ab5d71957445ab8".HexToByteArray();
// They should not decrypt to the same value
Assert.NotEqual<byte>(plainText, decrypted);
}
}
[Fact]
public static void TripleDESRoundTrip192BitsZerosCBC()
{
byte[] key = "5e970c0d2323d53b28fa3de507d6d20f9f0cd97123398b4d".HexToByteArray();
byte[] iv = "95498b5bf570f4c8".HexToByteArray();
using (TripleDES alg = TripleDESFactory.Create())
{
alg.Key = key;
alg.IV = iv;
alg.Padding = PaddingMode.Zeros;
alg.Mode = CipherMode.CBC;
byte[] plainText = "f9e9a1385bf3bd056d6a06eac662736891bd3e6837".HexToByteArray();
byte[] cipher = alg.Encrypt(plainText);
byte[] expectedCipher = "65f3dc211876a9daad238aa7d0c7ed7a3662296faf77dff9".HexToByteArray();
Assert.Equal<byte>(expectedCipher, cipher);
byte[] decrypted = alg.Decrypt(cipher);
byte[] expectedDecrypted = "f9e9a1385bf3bd056d6a06eac662736891bd3e6837000000".HexToByteArray();
Assert.Equal<byte>(expectedDecrypted, decrypted);
}
}
[Fact]
public static void TripleDESRoundTrip192BitsPKCS7ECB()
{
byte[] key = "155425f12109cd89378795a4ca337b3264689dca497ba2fa".HexToByteArray();
using (TripleDES alg = TripleDESFactory.Create())
{
alg.Key = key;
alg.Padding = PaddingMode.PKCS7;
alg.Mode = CipherMode.ECB;
byte[] plainText = "5bd3c4e16a723a17ac60dd0efdb158e269cddfd0fa".HexToByteArray();
byte[] cipher = alg.Encrypt(plainText);
byte[] expectedCipher = "7b8d982ee0c14821daf1b8cf4e407c2eb328627b696ac36e".HexToByteArray();
Assert.Equal<byte>(expectedCipher, cipher);
byte[] decrypted = alg.Decrypt(cipher);
byte[] expectedDecrypted = "5bd3c4e16a723a17ac60dd0efdb158e269cddfd0fa".HexToByteArray();
Assert.Equal<byte>(expectedDecrypted, decrypted);
}
}
[Fact]
public static void TripleDESRoundTrip192BitsPKCS7CBC()
{
byte[] key = "6b42da08f93e819fbd26fce0785b0eec3d0cb6bfa053c505".HexToByteArray();
byte[] iv = "8fc67ce5e7f28cde".HexToByteArray();
using (TripleDES alg = TripleDESFactory.Create())
{
alg.Key = key;
alg.IV = iv;
alg.Padding = PaddingMode.PKCS7;
alg.Mode = CipherMode.CBC;
byte[] plainText = "e867f915e275eab27d6951165d26dec6dd0acafcfc".HexToByteArray();
byte[] cipher = alg.Encrypt(plainText);
byte[] expectedCipher = "446f57875e107702afde16b57eaf250b87b8110bef29af89".HexToByteArray();
Assert.Equal<byte>(expectedCipher, cipher);
byte[] decrypted = alg.Decrypt(cipher);
byte[] expectedDecrypted = "e867f915e275eab27d6951165d26dec6dd0acafcfc".HexToByteArray();
Assert.Equal<byte>(expectedDecrypted, decrypted);
}
}
}
}
| |
namespace Microsoft.Azure.Management.StorSimple8000Series
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// BackupSchedulesOperations operations.
/// </summary>
public partial interface IBackupSchedulesOperations
{
/// <summary>
/// Gets all the backup schedules in a backup policy.
/// </summary>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='backupPolicyName'>
/// The backup policy name.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IEnumerable<BackupSchedule>>> ListByBackupPolicyWithHttpMessagesAsync(string deviceName, string backupPolicyName, string resourceGroupName, string managerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the properties of the specified backup schedule name.
/// </summary>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='backupPolicyName'>
/// The backup policy name.
/// </param>
/// <param name='backupScheduleName'>
/// The name of the backup schedule to be fetched
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<BackupSchedule>> GetWithHttpMessagesAsync(string deviceName, string backupPolicyName, string backupScheduleName, string resourceGroupName, string managerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates the backup schedule.
/// </summary>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='backupPolicyName'>
/// The backup policy name.
/// </param>
/// <param name='backupScheduleName'>
/// The backup schedule name.
/// </param>
/// <param name='parameters'>
/// The backup schedule.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<BackupSchedule>> CreateOrUpdateWithHttpMessagesAsync(string deviceName, string backupPolicyName, string backupScheduleName, BackupSchedule parameters, string resourceGroupName, string managerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the backup schedule.
/// </summary>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='backupPolicyName'>
/// The backup policy name.
/// </param>
/// <param name='backupScheduleName'>
/// The name the backup schedule.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string deviceName, string backupPolicyName, string backupScheduleName, string resourceGroupName, string managerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates the backup schedule.
/// </summary>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='backupPolicyName'>
/// The backup policy name.
/// </param>
/// <param name='backupScheduleName'>
/// The backup schedule name.
/// </param>
/// <param name='parameters'>
/// The backup schedule.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<BackupSchedule>> BeginCreateOrUpdateWithHttpMessagesAsync(string deviceName, string backupPolicyName, string backupScheduleName, BackupSchedule parameters, string resourceGroupName, string managerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the backup schedule.
/// </summary>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='backupPolicyName'>
/// The backup policy name.
/// </param>
/// <param name='backupScheduleName'>
/// The name the backup schedule.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string deviceName, string backupPolicyName, string backupScheduleName, string resourceGroupName, string managerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
using System;
using System.Threading.Tasks;
using VerifyXunit;
using Xunit;
[UsesVerify]
public class RewritingMethods
{
[Fact]
public Task RequiresNonNullArgumentForExplicitInterface()
{
var type = AssemblyWeaver.Assembly.GetType("ClassWithExplicitInterface");
var sample = (IComparable<string>)Activator.CreateInstance(type);
var exception = Assert.Throws<ArgumentNullException>(() => sample.CompareTo(null));
return Verifier.Verify(exception.Message);
}
[Fact]
public Task RequiresNonNullArgument()
{
var type = AssemblyWeaver.Assembly.GetType("SimpleClass");
var sample = (dynamic)Activator.CreateInstance(type);
var exception = Assert.Throws<ArgumentNullException>(() =>
{
sample.SomeMethod(null, "");
});
Assert.Equal("nonNullArg", exception.ParamName);
return Verifier.Verify(exception.Message);
}
[Fact]
public void AllowsNullWhenAttributeApplied()
{
var type = AssemblyWeaver.Assembly.GetType("SimpleClass");
var sample = (dynamic)Activator.CreateInstance(type);
sample.SomeMethod("", null);
}
[Fact]
public Task RequiresNonNullMethodReturnValue()
{
var type = AssemblyWeaver.Assembly.GetType("SimpleClass");
var sample = (dynamic)Activator.CreateInstance(type);
var exception = Assert.Throws<InvalidOperationException>(() => sample.MethodWithReturnValue(true));
return Verifier.Verify(exception.Message);
}
[Fact]
public Task RequiresNonNullGenericMethodReturnValue()
{
var type = AssemblyWeaver.Assembly.GetType("SimpleClass");
var sample = (dynamic)Activator.CreateInstance(type);
var exception = Assert.Throws<InvalidOperationException>(() => sample.MethodWithGenericReturn<object>(true));
return Verifier.Verify(exception.Message);
}
[Fact]
public void AllowsNullReturnValueWhenAttributeApplied()
{
var type = AssemblyWeaver.Assembly.GetType("SimpleClass");
var sample = (dynamic)Activator.CreateInstance(type);
sample.MethodAllowsNullReturnValue();
}
[Fact]
public Task RequiresNonNullOutValue()
{
var type = AssemblyWeaver.Assembly.GetType("SimpleClass");
var sample = (dynamic)Activator.CreateInstance(type);
string value;
var exception = Assert.Throws<InvalidOperationException>(() =>
{
sample.MethodWithOutValue(out value);
});
return Verifier.Verify(exception.Message);
}
[Fact]
public void AllowsNullOutValue()
{
var type = AssemblyWeaver.Assembly.GetType("SimpleClass");
var sample = (dynamic)Activator.CreateInstance(type);
string value;
sample.MethodWithAllowedNullOutValue(out value);
}
[Fact]
public void DoesNotRequireNonNullForNonPublicMethod()
{
var type = AssemblyWeaver.Assembly.GetType("SimpleClass");
var sample = (dynamic)Activator.CreateInstance(type);
sample.PublicWrapperOfPrivateMethod();
}
[Fact]
public void DoesNotRequireNonNullForOptionalParameter()
{
var type = AssemblyWeaver.Assembly.GetType("SimpleClass");
var sample = (dynamic)Activator.CreateInstance(type);
sample.MethodWithOptionalParameter(optional: null);
}
[Fact]
public Task RequiresNonNullForOptionalParameterWithNonNullDefaultValue()
{
var type = AssemblyWeaver.Assembly.GetType("SimpleClass");
var sample = (dynamic)Activator.CreateInstance(type);
var exception = Assert.Throws<ArgumentNullException>(() =>
{
sample.MethodWithOptionalParameterWithNonNullDefaultValue(optional: null);
});
return Verifier.Verify(exception.Message);
}
[Fact]
public void DoesNotRequireNonNullForOptionalParameterWithNonNullDefaultValueButAllowNullAttribute()
{
var type = AssemblyWeaver.Assembly.GetType("SimpleClass");
var sample = (dynamic)Activator.CreateInstance(type);
sample.MethodWithOptionalParameterWithNonNullDefaultValueButAllowNullAttribute(optional: null);
}
[Fact]
public Task RequiresNonNullForNonPublicMethodWhenAttributeSpecifiesNonPublic()
{
var type = AssemblyWeaver.Assembly.GetType("ClassWithPrivateMethod");
var sample = (dynamic)Activator.CreateInstance(type);
var exception = Assert.Throws<ArgumentNullException>(() =>
{
sample.PublicWrapperOfPrivateMethod();
});
return Verifier.Verify(exception.Message);
}
[Fact]
public void ReturnGuardDoesNotInterfereWithIteratorMethod()
{
var type = AssemblyWeaver.Assembly.GetType("SpecialClass");
var sample = (dynamic)Activator.CreateInstance(type);
Assert.Equal(new[] { 0, 1, 2, 3, 4 }, sample.CountTo(5));
}
#if (DEBUG)
[Fact]
public Task RequiresNonNullArgumentAsync()
{
var type = AssemblyWeaver.Assembly.GetType("SpecialClass");
var sample = (dynamic)Activator.CreateInstance(type);
var exception = Assert.Throws<ArgumentNullException>(() => sample.SomeMethodAsync(null, ""));
return Verifier.Verify(exception.Message);
}
[Fact]
public void AllowsNullWhenAttributeAppliedAsync()
{
var type = AssemblyWeaver.Assembly.GetType("SpecialClass");
var sample = (dynamic)Activator.CreateInstance(type);
sample.SomeMethodAsync("", null);
}
[Fact]
public Task RequiresNonNullMethodReturnValueAsync()
{
var type = AssemblyWeaver.Assembly.GetType("SpecialClass");
var sample = (dynamic)Activator.CreateInstance(type);
Exception exception = null;
((Task<string>)sample.MethodWithReturnValueAsync(true))
.ContinueWith(t =>
{
if (t.IsFaulted)
{
exception = t.Exception.Flatten().InnerException;
}
})
.Wait();
Assert.NotNull(exception);
Assert.IsType<InvalidOperationException>(exception);
return Verifier.Verify(exception.Message);
}
[Fact]
public void AllowsNullReturnValueWhenAttributeAppliedAsync()
{
var type = AssemblyWeaver.Assembly.GetType("SpecialClass");
var sample = (dynamic)Activator.CreateInstance(type);
Exception ex = null;
((Task<string>)sample.MethodAllowsNullReturnValueAsync())
.ContinueWith(t =>
{
if (t.IsFaulted)
ex = t.Exception.Flatten().InnerException;
})
.Wait();
Assert.Null(ex);
}
[Fact]
public void NoAwaitWillCompile()
{
var type = AssemblyWeaver.Assembly.GetType("SpecialClass");
var instance = (dynamic)Activator.CreateInstance(type);
Assert.Equal(42, instance.NoAwaitCode().Result);
}
#endif
[Fact]
public void AllowsNullWhenClassMatchExcludeRegex()
{
var type = AssemblyWeaver.Assembly.GetType("ClassToExclude");
var ClassToExclude = (dynamic)Activator.CreateInstance(type, "");
ClassToExclude.Test(null);
}
[Fact]
public void ReturnValueChecksWithBranchToRetInstruction()
{
// This is a regression test for the "Branch to RET" issue described in https://github.com/Fody/NullGuard/issues/61.
var type = AssemblyWeaver.Assembly.GetType("SimpleClass");
var sample = (dynamic)Activator.CreateInstance(type);
var exception = Assert.Throws<InvalidOperationException>(() => sample.ReturnValueChecksWithBranchToRetInstruction());
Assert.Equal("[NullGuard] Return value of method 'System.String SimpleClass::ReturnValueChecksWithBranchToRetInstruction()' is null.", exception.Message);
}
[Fact]
public void OutValueChecksWithRetInstructionAsSwitchCase()
{
// This is a regression test for the "Branch to RET" issue described in https://github.com/Fody/NullGuard/issues/61.
var type = AssemblyWeaver.Assembly.GetType("SimpleClass");
var sample = (dynamic)Activator.CreateInstance(type);
string value;
var exception = Assert.Throws<InvalidOperationException>(() =>
{
sample.OutValueChecksWithRetInstructionAsSwitchCase(0, out value);
});
Assert.Equal("[NullGuard] Out parameter 'outParam' is null.", exception.Message);
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Buffers;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute;
using EditorBrowsableState = System.ComponentModel.EditorBrowsableState;
namespace System
{
/// <summary>
/// ReadOnlyMemory represents a contiguous region of arbitrary similar to ReadOnlySpan.
/// Unlike ReadOnlySpan, it is not a byref-like type.
/// </summary>
[DebuggerDisplay("{DebuggerDisplay,nq}")]
[DebuggerTypeProxy(typeof(MemoryDebugView<>))]
public readonly struct ReadOnlyMemory<T>
{
// NOTE: With the current implementation, Memory<T> and ReadOnlyMemory<T> must have the same layout,
// as code uses Unsafe.As to cast between them.
// The highest order bit of _index is used to discern whether _object is an array/string or an owned memory
// if (_index >> 31) == 1, _object is an OwnedMemory<T>
// else, _object is a T[] or string
private readonly object _object;
private readonly int _index;
private readonly int _length;
internal const int RemoveOwnedFlagBitMask = 0x7FFFFFFF;
/// <summary>
/// Creates a new memory over the entirety of the target array.
/// </summary>
/// <param name="array">The target array.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
/// reference (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlyMemory(T[] array)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
_object = array;
_index = 0;
_length = array.Length;
}
/// <summary>
/// Creates a new memory over the portion of the target array beginning
/// at 'start' index and ending at 'end' index (exclusive).
/// </summary>
/// <param name="array">The target array.</param>
/// <param name="start">The index at which to begin the memory.</param>
/// <param name="length">The number of items in the memory.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
/// reference (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in the range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlyMemory(T[] array, int start, int length)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
_object = array;
_index = start;
_length = length;
}
/// <summary>Creates a new memory over the existing object, start, and length. No validation is performed.</summary>
/// <param name="obj">The target object.</param>
/// <param name="start">The index at which to begin the memory.</param>
/// <param name="length">The number of items in the memory.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal ReadOnlyMemory(object obj, int start, int length)
{
// No validation performed; caller must provide any necessary validation.
_object = obj;
_index = start;
_length = length;
}
//Debugger Display = {T[length]}
private string DebuggerDisplay => string.Format("{{{0}[{1}]}}", typeof(T).Name, _length);
/// <summary>
/// Defines an implicit conversion of an array to a <see cref="ReadOnlyMemory{T}"/>
/// </summary>
public static implicit operator ReadOnlyMemory<T>(T[] array) => new ReadOnlyMemory<T>(array);
/// <summary>
/// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="ReadOnlyMemory{T}"/>
/// </summary>
public static implicit operator ReadOnlyMemory<T>(ArraySegment<T> arraySegment) => new ReadOnlyMemory<T>(arraySegment.Array, arraySegment.Offset, arraySegment.Count);
/// <summary>
/// Returns an empty <see cref="ReadOnlyMemory{T}"/>
/// </summary>
public static ReadOnlyMemory<T> Empty => default;
/// <summary>
/// The number of items in the memory.
/// </summary>
public int Length => _length;
/// <summary>
/// Returns true if Length is 0.
/// </summary>
public bool IsEmpty => _length == 0;
/// <summary>
/// Forms a slice out of the given memory, beginning at 'start'.
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> index is not in range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlyMemory<T> Slice(int start)
{
if ((uint)start > (uint)_length)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
return new ReadOnlyMemory<T>(_object, _index + start, _length - start);
}
/// <summary>
/// Forms a slice out of the given memory, beginning at 'start', of given length
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <param name="length">The desired length for the slice (exclusive).</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlyMemory<T> Slice(int start, int length)
{
if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
return new ReadOnlyMemory<T>(_object, _index + start, length);
}
/// <summary>
/// Returns a span from the memory.
/// </summary>
public ReadOnlySpan<T> Span
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if (_index < 0)
{
return ((OwnedMemory<T>)_object).Span.Slice(_index & RemoveOwnedFlagBitMask, _length);
}
else if (typeof(T) == typeof(char) && _object is string s)
{
return new ReadOnlySpan<T>(Unsafe.As<Pinnable<T>>(s), MemoryExtensions.StringAdjustment, s.Length).Slice(_index, _length);
}
else if (_object != null)
{
return new ReadOnlySpan<T>((T[])_object, _index, _length);
}
else
{
return default;
}
}
}
/// <summary>
/// Copies the contents of the read-only memory into the destination. If the source
/// and destination overlap, this method behaves as if the original values are in
/// a temporary location before the destination is overwritten.
///
/// <param name="destination">The Memory to copy items into.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when the destination is shorter than the source.
/// </exception>
/// </summary>
public void CopyTo(Memory<T> destination) => Span.CopyTo(destination.Span);
/// <summary>
/// Copies the contents of the readonly-only memory into the destination. If the source
/// and destination overlap, this method behaves as if the original values are in
/// a temporary location before the destination is overwritten.
///
/// <returns>If the destination is shorter than the source, this method
/// return false and no data is written to the destination.</returns>
/// </summary>
/// <param name="destination">The span to copy items into.</param>
public bool TryCopyTo(Memory<T> destination) => Span.TryCopyTo(destination.Span);
/// <summary>
/// Returns a handle for the array.
/// <param name="pin">If pin is true, the GC will not move the array and hence its address can be taken</param>
/// </summary>
public unsafe MemoryHandle Retain(bool pin = false)
{
MemoryHandle memoryHandle = default;
if (pin)
{
if (_index < 0)
{
memoryHandle = ((OwnedMemory<T>)_object).Pin();
memoryHandle.AddOffset((_index & RemoveOwnedFlagBitMask) * Unsafe.SizeOf<T>());
}
else if (typeof(T) == typeof(char) && _object is string s)
{
GCHandle handle = GCHandle.Alloc(s, GCHandleType.Pinned);
void* pointer = Unsafe.Add<T>((void*)handle.AddrOfPinnedObject(), _index);
memoryHandle = new MemoryHandle(null, pointer, handle);
}
else if (_object is T[] array)
{
var handle = GCHandle.Alloc(array, GCHandleType.Pinned);
void* pointer = Unsafe.Add<T>((void*)handle.AddrOfPinnedObject(), _index);
memoryHandle = new MemoryHandle(null, pointer, handle);
}
}
else
{
if (_index < 0)
{
((OwnedMemory<T>)_object).Retain();
memoryHandle = new MemoryHandle((OwnedMemory<T>)_object);
}
}
return memoryHandle;
}
/// <summary>
/// Copies the contents from the memory into a new array. This heap
/// allocates, so should generally be avoided, however it is sometimes
/// necessary to bridge the gap with APIs written in terms of arrays.
/// </summary>
public T[] ToArray() => Span.ToArray();
/// <summary>
/// Determines whether the specified object is equal to the current object.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj)
{
if (obj is ReadOnlyMemory<T> readOnlyMemory)
{
return Equals(readOnlyMemory);
}
else if (obj is Memory<T> memory)
{
return Equals(memory);
}
else
{
return false;
}
}
/// <summary>
/// Returns true if the memory points to the same array and has the same length. Note that
/// this does *not* check to see if the *contents* are equal.
/// </summary>
public bool Equals(ReadOnlyMemory<T> other)
{
return
_object == other._object &&
_index == other._index &&
_length == other._length;
}
/// <summary>
/// Serves as the default hash function.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode()
{
return _object != null ? CombineHashCodes(_object.GetHashCode(), _index.GetHashCode(), _length.GetHashCode()) : 0;
}
private static int CombineHashCodes(int left, int right)
{
return ((left << 5) + left) ^ right;
}
private static int CombineHashCodes(int h1, int h2, int h3)
{
return CombineHashCodes(CombineHashCodes(h1, h2), h3);
}
/// <summary>Gets the state of the memory as individual fields.</summary>
/// <param name="start">The offset.</param>
/// <param name="length">The count.</param>
/// <returns>The object.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal object GetObjectStartLength(out int start, out int length)
{
start = _index;
length = _length;
return _object;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace PluralizeSample
{
internal class EnglishPluralizerData
{
// http://www.csse.monash.edu.au/~damian/papers/HTML/Plurals.html
// perhaps also http://www.clips.ua.ac.be/pages/pattern-en
// http://www.visca.com/regexdict/ lookup suffixes here
public readonly List<IInflection> CustomInflections = new List<IInflection>();
/// <summary>
/// Inflections that replace the suffix in a word with a different suffix.
/// Matches on the exact word.
/// </summary>
public readonly Dictionary<string, IPluralForm> SingularCategorySuffix = new Dictionary<string, IPluralForm>();
public readonly List<IInflection> SingularSuffix = new List<IInflection>();
/// <summary>
/// Hardcoded mappings from a singular word to its plural.
/// </summary>
public readonly List<IInflection> SingularIrregular = new List<IInflection>();
/// <summary>
/// The singular pronoun inflections.
/// </summary>
public readonly Dictionary<string, IPluralForm> SingularPronoun = new Dictionary<string, IPluralForm>();
public readonly List<string> InflectionlessSuffixes = new List<string>();
public readonly List<Regex> InflectionlessRegex = new List<Regex>();
public EnglishPluralizerData()
{
#region hardcoded suffix mappings
AddSuffixCategory("a", null, "ae", new[] {
"alumna", "alga", "vertebra"
});
AddSuffixCategory("a", "as", "ae", new[] {
"abscissa", "formula", "medusa", "amoeba", "hydra", "nebula",
"antenna", "hyperbola", "nova", "aurora", "lacuna", "parabola"
});
AddSuffixCategory("a", "as", "ata", new[] {
"anathema", "enema", "oedema", "bema", "enigma", "sarcoma",
"carcinoma", "gumma", "charisma", "lemma", "soma", "diploma",
"lymphoma", "dogma", "magma", "stoma", "drama", "melisma",
"trauma", "edema", "miasma"
}, PluralFormPreference.Anglicized);
AddSuffixCategory("a", "as", "ata", new[] {
"stigma", "schema"
}, PluralFormPreference.Classical);
AddSuffixCategory("en", "ens", "ina", new[] {
"stamen", "foramen", "lumen"
});
AddSuffixCategory("ex", null, "ices", new[] {
"codex", "murex", "silex"
});
AddSuffixCategory("ex", "exes", "ices", new[] {
"apex", "latex", "vertex", "cortex", "pontifex", "vortex",
"index", "simplex"
});
AddSuffixCategory("is", "ises", "ides", new[] {
"iris", "clitoris"
}, PluralFormPreference.Anglicized);
AddSuffixCategory("o", "os", null, new[] {
"albino", "generalissimo", "manifesto", "archipelago",
"ghetto", "medico", "armadillo", "guano", "octavo",
"commando", "inferno", "photo", "ditto", "jumbo", "pro",
"dynamo", "lingo", "quarto", "embryo", "lumbago", "rhino",
"fiasco", "magneto", "stylo"
});
AddSuffixCategory("o", "os", "i", new[] {
"alto", "contralto", "soprano", "basso", "crescendo",
"tempo", "canto", "solo"
}, PluralFormPreference.Anglicized);
AddSuffixCategory("on", null, "a", new[] {
"aphelion", "hyperbaton", "perihelion", "asyndeton",
"noumenon", "phenomenon", "criterion", "organon",
"prolegomenon"
});
AddSuffixCategory("um", null, "a", new[] {
"agendum", "datum", "extremum", "bacterium", "desideratum",
"stratum", "candelabrum", "erratum", "ovum"
});
AddSuffixCategory("um", "ums", "a", new[] {
"aquarium", "interregnum", "quantum", "compendium",
"lustrum", "rostrum", "consortium", "maximum",
"spectrum", "cranium", "medium", "speculum",
"curriculum", "memorandum", "stadium", "dictum",
"millenium", "trapezium", "emporium", "minimum",
"ultimatum", "enconium", "momentum", "vacuum",
"gymnasium", "optimum", "velum", "honorarium",
"phylum"
});
AddSuffixCategory("us", "uses", "i", new[] {
"focus", "nimbus", "succubus", "fungus", "nucleolus",
"torus", "genius", "radius", "umbilicus", "incubus",
"stylus", "syllabus", "thrombus", "uterus"
});
AddSuffixCategory("us", "uses", "us", new[] {
"apparatus", "impetus", "prospectus", "cantus",
"nexus", "sinus", "coitus", "plexus", "status",
"hiatus"
}, PluralFormPreference.Anglicized);
AddSuffixCategory("", null, "im", new[] {
"cherub", "goy", "seraph"
});
#endregion
#region pronouns
SingularPronoun.Add("I", new SimplePluralForm("we"));
SingularPronoun.Add("you", new SimplePluralForm("you")); // y'all
SingularPronoun.Add("thou", new SimplePluralForm("you"));
SingularPronoun.Add("she", new SimplePluralForm("they"));
SingularPronoun.Add("he", new SimplePluralForm("they"));
SingularPronoun.Add("it", new SimplePluralForm("they"));
SingularPronoun.Add("they", new SimplePluralForm("they"));
SingularPronoun.Add("me", new SimplePluralForm("us"));
SingularPronoun.Add("thee", new SimplePluralForm("you"));
SingularPronoun.Add("her", new SimplePluralForm("them"));
SingularPronoun.Add("him", new SimplePluralForm("them"));
//SingularPronoun.Add("it", new SimplePluralForm("them")); // duplicate key "it" -> "they"
SingularPronoun.Add("them", new SimplePluralForm("them"));
SingularPronoun.Add("myself", new SimplePluralForm("ourselves"));
SingularPronoun.Add("yourself", new SimplePluralForm("yourself"));
SingularPronoun.Add("thyself", new SimplePluralForm("yourself"));
SingularPronoun.Add("herself", new SimplePluralForm("themselves"));
SingularPronoun.Add("himself", new SimplePluralForm("themselves"));
SingularPronoun.Add("itself", new SimplePluralForm("themselves"));
SingularPronoun.Add("themself", new SimplePluralForm("themselves"));
SingularPronoun.Add("oneself", new SimplePluralForm("oneselves"));
#endregion
#region inflectionless words
InflectionlessSuffixes.Add("aircraft");
InflectionlessSuffixes.Add("bison");
InflectionlessSuffixes.Add("bream");
InflectionlessSuffixes.Add("breeches");
InflectionlessSuffixes.Add("britches");
InflectionlessSuffixes.Add("carp");
InflectionlessSuffixes.Add("chassis");
InflectionlessSuffixes.Add("clippers");
InflectionlessSuffixes.Add("cod");
InflectionlessSuffixes.Add("contretemps");
InflectionlessSuffixes.Add("corps");
InflectionlessSuffixes.Add("debris");
InflectionlessSuffixes.Add("deer");
InflectionlessSuffixes.Add("diabetes");
InflectionlessSuffixes.Add("djinn");
InflectionlessSuffixes.Add("eland");
InflectionlessSuffixes.Add("elk");
InflectionlessSuffixes.Add("equipment");
InflectionlessSuffixes.Add("fish");
InflectionlessSuffixes.Add("flounder");
InflectionlessSuffixes.Add("gallows");
InflectionlessSuffixes.Add("graffiti");
InflectionlessSuffixes.Add("headquarters");
InflectionlessSuffixes.Add("herpes");
InflectionlessSuffixes.Add("high-jinks");
InflectionlessSuffixes.Add("homework");
InflectionlessSuffixes.Add("information");
InflectionlessSuffixes.Add("innings");
InflectionlessSuffixes.Add("jackanapes");
InflectionlessSuffixes.Add("mackerel");
InflectionlessSuffixes.Add("measles");
InflectionlessSuffixes.Add("mews");
InflectionlessSuffixes.Add("mumps");
InflectionlessSuffixes.Add("news");
InflectionlessSuffixes.Add("offspring");
InflectionlessSuffixes.Add("pincers");
InflectionlessSuffixes.Add("pliers");
InflectionlessSuffixes.Add("proceedings");
InflectionlessSuffixes.Add("rabies");
InflectionlessSuffixes.Add("rice");
InflectionlessSuffixes.Add("salmon");
InflectionlessSuffixes.Add("scissors");
InflectionlessSuffixes.Add("sea-bass");
InflectionlessSuffixes.Add("series");
InflectionlessSuffixes.Add("shears");
InflectionlessSuffixes.Add("sheep");
InflectionlessSuffixes.Add("species");
InflectionlessSuffixes.Add("swine");
InflectionlessSuffixes.Add("travois");
InflectionlessSuffixes.Add("trout");
InflectionlessSuffixes.Add("tuna");
InflectionlessSuffixes.Add("whiting");
InflectionlessSuffixes.Add("wildebeest");
InflectionlessSuffixes.Add("deaf"); // otherwise, rule for "leaf" -> "leaves" will take over
InflectionlessSuffixes.Add("ois");
InflectionlessSuffixes.Add("pox");
InflectionlessSuffixes.Add("itis");
InflectionlessSuffixes.Add("ese");
#endregion
#region irregular plurals
SingularIrregular.Add(CreateEnglishComposite(
new ExactInflection("beef", "beefs"),
new ExactInflection("beef", "beeves")));
SingularIrregular.Add(CreateEnglishComposite(
new ExactInflection("brother", "brothers"),
new ExactInflection("brother", "brethren"),
PluralFormPreference.Anglicized));
SingularIrregular.Add(
new ExactInflection("child", "children"));
SingularIrregular.Add(CreateEnglishComposite(
new ExactInflection("cow", "cows"),
new ExactInflection("cow", "kine"),
PluralFormPreference.Anglicized));
SingularIrregular.Add(
new ExactInflection("ephermeris", "ephemerides"));
SingularIrregular.Add(CreateEnglishComposite(
new ExactInflection("genie", "genies"),
new ExactInflection("genie", "genii")));
SingularIrregular.Add(CreateEnglishComposite(
new ExactInflection("hoof", "hoofs"),
new ExactInflection("hoof", "hooves")));
SingularIrregular.Add(CreateEnglishComposite(
new ExactInflection("money", "moneys"),
new ExactInflection("money", "monies")));
SingularIrregular.Add(
new ExactInflection("mongoose", "mongooses"));
SingularIrregular.Add(
new ExactInflection("mythos", "mythoi"));
SingularIrregular.Add(CreateEnglishComposite(
new ExactInflection("octopus", "octopuses"),
new ExactInflection("octopus", "octopodes")));
SingularIrregular.Add(new RegexInflection("[bcd]ox", "es"));
SingularIrregular.Add(
new ExactInflection("ox", "oxen"));
SingularIrregular.Add(
new ExactInflection("soliloquy", "soliloquies"));
SingularIrregular.Add(
new ExactInflection("trilby", "trilbys"));
SingularIrregular.Add(CreateEnglishComposite(
new ExactInflection("person", "persons"),
new ExactInflection("person", "people")));
SingularIrregular.Add(CreateEnglishComposite(
new ExactInflection("appendix", "appendixes"),
new ExactInflection("appendix", "appendices")));
SingularIrregular.Add(CreateEnglishComposite(
new ExactInflection("vacuum", "vacuums"),
new ExactInflection("vacuum", "vacua"),
PluralFormPreference.Anglicized));
SingularIrregular.Add(
new ExactInflection("corpus", "corpora"));
SingularIrregular.Add(
new ExactInflection("genus", "genera"));
SingularIrregular.Add(
new ExactInflection("cheese", "cheeses"));
#endregion
#region irregular suffixes
SingularSuffix.Add(new SuffixReplaceInflection("man", "men"));
SingularSuffix.Add(new SuffixReplaceInflection("louse", "lice"));
SingularSuffix.Add(new SuffixReplaceInflection("mouse", "mice"));
SingularSuffix.Add(new SuffixReplaceInflection("goose", "geese"));
SingularSuffix.Add(new SuffixReplaceInflection("foot", "feet"));
SingularSuffix.Add(new SuffixReplaceInflection("zoon", "zoa"));
SingularSuffix.Add(new SuffixReplaceInflection("zoan", "zoa"));
SingularSuffix.Add(new SuffixReplaceInflection("cis", "is", "es"));
SingularSuffix.Add(new SuffixReplaceInflection("sis", "is", "es"));
SingularSuffix.Add(new SuffixReplaceInflection("xis", "is", "es"));
SingularSuffix.Add(new SuffixAppendInflection("bus", "es"));
SingularSuffix.Add(new SuffixReplaceInflection("tooth", "teeth"));
SingularSuffix.Add(new SuffixReplaceInflection("thief", "thieves"));
#endregion
#region assimilated classical inflections
SingularSuffix.Add(CreateEnglishComposite(
new RegexInflection("[td]ex", "es"),
new RegexInflection("[td](ex)", "ices")));
SingularSuffix.Add(new SuffixAppendInflection("ex", "es"));
SingularSuffix.Add(new SuffixReplaceInflection("um", "a"));
SingularSuffix.Add(new SuffixReplaceInflection("on", "a"));
SingularSuffix.Add(new SuffixReplaceInflection("a", "ae"));
#endregion
#region classical variants of modern inflections
SingularSuffix.Add(CreateEnglishComposite(
new SuffixReplaceInflection("trix", "trixes"),
new SuffixReplaceInflection("trix", "trices")));
SingularSuffix.Add(new SuffixReplaceInflection("eau", "eaux"));
SingularSuffix.Add(new SuffixReplaceInflection("ieu", "ieux"));
// nx -> nges in author's algorithm, but it just doesn't sound right...
SingularSuffix.Add(CreateEnglishComposite(
new SuffixReplaceInflection("inx", "nx", "nxes"),
new SuffixReplaceInflection("inx", "nx", "nges"),
PluralFormPreference.Anglicized));
SingularSuffix.Add(CreateEnglishComposite(
new SuffixReplaceInflection("anx", "nx", "nxes"),
new SuffixReplaceInflection("anx", "nx", "nges"), // spanx -> spanges?
PluralFormPreference.Anglicized));
SingularSuffix.Add(CreateEnglishComposite(
new SuffixReplaceInflection("ynx", "nx", "nxes"),
new SuffixReplaceInflection("ynx", "nx", "nges"),
PluralFormPreference.Anglicized));
SingularSuffix.Add(CreateEnglishComposite(
new SuffixReplaceInflection("en", "ens"),
new SuffixReplaceInflection("en", "ina")));
SingularSuffix.Add(CreateEnglishComposite(
new SuffixReplaceInflection("a", "as"),
new SuffixReplaceInflection("a", "ata")));
SingularSuffix.Add(new SuffixReplaceInflection("is", "es"));
/*SingularSuffix.Add(CreateEnglishComposite(
new SuffixReplaceInflection("is", "ises"),
new SuffixReplaceInflection("is", "ides")));*/
AddSuffixCategory("us", "uses", "i", new []
{
"campus", "bonus", "virus",
}, PluralFormPreference.Anglicized);
SingularSuffix.Add(CreateEnglishComposite(
new SuffixReplaceInflection("us", "uses"),
new SuffixReplaceInflection("us", "i")));
/*SingularSuffix.Add(CreateEnglishComposite(
new SuffixReplaceInflection("us", "uses"), // nexuses
new SuffixReplaceInflection("us", "us")));*/ // Conflicting...
#endregion
#region singular suffix
SingularSuffix.Add(new SuffixAppendInflection("ch", "es"));
SingularSuffix.Add(new SuffixAppendInflection("sh", "es"));
SingularSuffix.Add(new SuffixAppendInflection("ss", "es"));
SingularSuffix.Add(new SuffixAppendInflection("tz", "es"));
SingularSuffix.Add(new RegexInflection("[nlw]i(fe)", "ves"));
SingularSuffix.Add(new RegexInflection("[aeo]l(f)", "ves"));
SingularSuffix.Add(new SuffixReplaceInflection("eaf", "f", "ves"));
SingularSuffix.Add(new SuffixReplaceInflection("loaf", "f", "ves"));
SingularSuffix.Add(new RegexInflection("[aou]r(f)", "ves"));
SingularSuffix.Add(new RegexInflection("[aeiou](y)", "ys"));
SingularSuffix.Add(new RegexInflection("[^aeiou](y)", "ies"));
SingularSuffix.Add(new RegexInflection("[A-Z].*?(y)", "ys"));
SingularSuffix.Add(new SuffixReplaceInflection("ay", "y", "ies"));
// lassos, solos
SingularSuffix.Add(new RegexInflection("[aeiou](o)", "os"));
SingularSuffix.Add(new SuffixReplaceInflection("o", "oes"));
// potatoes, dominoes
// quiz -> quizzes, biz -> bizzes
SingularSuffix.Add(new SuffixAppendInflection("iz", "zes"));
SingularSuffix.Add(new SuffixAppendInflection("zz", "es"));
SingularSuffix.Add(new RegexInflection("[io]x", "es"));
#endregion
}
private void AddSuffixCategory (string suffix, string anglicizedEnding,
string classicalEnding, string[] words,
PluralFormPreference pref = PluralFormPreference.Classical)
{
foreach (var word in words)
{
if(!word.EndsWith(suffix))
{
throw new ArgumentException(String.Format(
"Word {0} must end with the suffix {1}. " +
"Are you adding it to the wrong category?",
word, suffix));
}
var substr = word.Substring(0, word.Length - suffix.Length);
var angl = !String.IsNullOrEmpty(anglicizedEnding)
? substr + anglicizedEnding
: null;
var clas = !String.IsNullOrEmpty(classicalEnding)
? substr + classicalEnding
: null;
SingularCategorySuffix.Add(word, new EnglishPluralForm(
angl, clas, pref,
String.Format("{0} -> " +
angl != null && clas != null
? "{1}/{2}"
: angl != null
? "{1}"
: "{2}" // classical must not be null
, word, angl, clas)));
}
}
private IInflection CreateEnglishComposite(IInflection anglicized,
IInflection classical, string description = null)
{
return new CompositeInflection(
pl => new EnglishPluralForm(pl[0].Value, pl[1].Value, description: description),
anglicized, classical);
}
private IInflection CreateEnglishComposite(IInflection anglicized,
IInflection classical, PluralFormPreference pref, string description = null)
{
return new CompositeInflection(
pl => new EnglishPluralForm(pl[0].Value, pl[1].Value, pref, description),
anglicized, classical);
}
}
}
| |
#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 [email protected]
//
// This project is licensed under the BSD license. See the License.txt file for more information.
///////////////////////////////////////////////////////////////////////////////////////////////////
#endregion
using System;
using System.Globalization;
using System.IO;
using System.Web;
using Subtext.Framework.Components;
using Subtext.Framework.Configuration;
using Subtext.Framework.Routing;
using Subtext.Framework.Text;
using Subtext.Framework.Tracking;
using Subtext.Infrastructure;
namespace Subtext.Framework.Syndication
{
/// <summary>
/// Generates an Atom feed.
/// </summary>
public abstract class BaseAtomWriter : BaseSyndicationWriter<Entry>
{
private static string W3Utcz(IFormattable dt)
{
return dt.ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture);
}
private bool _isBuilt;
/// <summary>
/// Bases the syndication writer.
/// </summary>
protected BaseAtomWriter(TextWriter writer, DateTime dateLastViewedFeedItemPublished, bool useDeltaEncoding,
ISubtextContext context)
: base(writer, dateLastViewedFeedItemPublished, useDeltaEncoding, context)
{
}
protected override void Build()
{
if (!_isBuilt)
{
Build(DateLastViewedFeedItemPublishedUtc);
}
}
/// <summary>
/// Builds the specified last id viewed.
/// </summary>
/// <param name="dateLastViewedFeedItemPublished">Last id viewed.</param>
protected override void Build(DateTime dateLastViewedFeedItemPublished)
{
if (!_isBuilt)
{
StartDocument();
SetNamespaces();
WriteChannel();
WriteEntries();
EndDocument();
_isBuilt = true;
}
}
protected virtual void SetNamespaces()
{
WriteAttributeString("xmlns:dc", "http://purl.org/dc/elements/1.1/");
WriteAttributeString("xmlns:trackback", "http://madskills.com/public/xml/rss/module/trackback/");
WriteAttributeString("xmlns:wfw", "http://wellformedweb.org/CommentAPI/");
WriteAttributeString("xmlns:slash", "http://purl.org/rss/1.0/modules/slash/");
//(Duncanma 11/13/2005, changing atom namespace for 1.0 feed)
WriteAttributeString("xmlns", "http://www.w3.org/2005/Atom");
WriteAttributeString("xml:lang", Blog.Language);
}
protected virtual void StartDocument()
{
WriteStartElement("feed");
//(Duncanma 11/13/2005, removing version attribute for 1.0 feed)
//this.WriteAttributeString("version","0.3");
}
protected void EndDocument()
{
WriteEndElement();
}
protected virtual void WriteChannel()
{
var blogUrl = new Uri(UrlHelper.BlogUrl().ToFullyQualifiedUrl(Blog), "Default.aspx");
BuildChannel(Blog.Title, blogUrl.ToString(), Blog.SubTitle);
}
protected void BuildChannel(string title, string link, string description)
{
WriteElementString("title", HtmlHelper.RemoveHtml(title));
//(Duncanma 11/13/2005, changing link rel and href for 1.0 feed)
WriteStartElement("link");
//(Duncanma 12/28/2005, changing again... Atom vs atom was causing feed validation errors
WriteAttributeString("rel", "self");
WriteAttributeString("type", "application/atom+xml");
string currentUrl = link + "Atom.aspx";
if (HttpContext.Current.Request != null)
{
currentUrl = HttpContext.Current.Request.Url.ToString();
}
WriteAttributeString("href", currentUrl);
// this.WriteAttributeString("rel","self");
// this.WriteAttributeString("type","application/xml");
// this.WriteAttributeString("href",info.RootUrl + "atom.aspx");
WriteEndElement();
//(Duncanma 11/13/2005, changing tagline to subtitle for 1.0 feed)
WriteStartElement("subtitle");
WriteAttributeString("type", "html");
WriteString(HtmlHelper.RemoveHtml(description));
WriteEndElement();
WriteElementString("id", link);
WriteStartElement("author");
WriteElementString("name", Blog.Author);
var blogUrl = new Uri(UrlHelper.BlogUrl().ToFullyQualifiedUrl(Blog), "Default.aspx");
WriteElementString("uri", blogUrl.ToString());
WriteEndElement();
//(Duncanma 11/13/05) updated generator to reflect project name change to Subtext
WriteStartElement("generator");
//(Duncanma 11/13/2005, changing url to uri for 1.0 feed)
WriteAttributeString("uri", "http://subtextproject.com");
WriteAttributeString("version", VersionInfo.VersionDisplayText);
WriteString("Subtext");
WriteEndElement();
//(Duncanma 11/13/2005, changing modified to updated for 1.0 feed)
WriteElementString("updated", W3Utcz(Blog.DateModifiedUtc));
}
private void WriteEntries()
{
BlogConfigurationSettings settings = Config.Settings;
ClientHasAllFeedItems = true;
LatestPublishDateUtc = DateLastViewedFeedItemPublishedUtc;
foreach (Entry entry in Items)
{
// We'll show every entry if RFC3229 is not enabled.
//TODO: This is wrong. What if a post is not published and then gets published later. It will not be displayed.
if (!UseDeltaEncoding || entry.DatePublishedUtc > DateLastViewedFeedItemPublishedUtc)
{
WriteStartElement("entry");
EntryXml(entry, settings, Blog.TimeZone);
WriteEndElement();
ClientHasAllFeedItems = false;
//Update the latest publish date.
if (entry.DateSyndicated > LatestPublishDateUtc)
{
LatestPublishDateUtc = entry.DateSyndicated;
}
}
}
}
protected virtual void EntryXml(Entry entry, BlogConfigurationSettings settings, ITimeZone timezone)
{
WriteElementString("title", entry.Title);
WriteStartElement("link");
//(Duncanma 11/13/2005, changing alternate to self for 1.0 feed)
WriteAttributeString("rel", "alternate");
WriteAttributeString("type", "text/html");
WriteAttributeString("href", UrlHelper.EntryUrl(entry).ToFullyQualifiedUrl(Blog).ToString());
WriteEndElement();
WriteElementString("id", UrlHelper.EntryUrl(entry).ToFullyQualifiedUrl(Blog).ToString());
//(Duncanma 11/13/2005, hiding created, change issued to
//published and modified to updated for 1.0 feed)
//this.WriteElementString("created",W3Utcz(entry.DateCreated));
WriteElementString("published", W3Utcz(entry.DateCreatedUtc));
WriteElementString("updated", W3Utcz(entry.DateModifiedUtc));
if (entry.HasDescription)
{
WriteStartElement("summary");
//(Duncanma 11/13/2005, changing text/html to html for 1.0 feed)
WriteAttributeString("type", "html");
WriteString(entry.Description);
WriteEndElement();
}
WriteStartElement("content");
//(Duncanma 11/13/2005, changing text/html to html for 1.0 feed)
WriteAttributeString("type", "html");
//(Duncanma 11/13/2005, hiding mode for 1.0 feed)
//this.WriteAttributeString("mode","escaped");
WriteString
(
string.Format
(CultureInfo.InvariantCulture, "{0}{1}", //tag def
entry.SyndicateDescriptionOnly ? entry.Description : entry.Body, //use desc or full post
(UseAggBugs && settings.Tracking.EnableAggBugs)
? TrackingUrls.AggBugImage(UrlHelper.AggBugUrl(entry.Id))
: null //use aggbugs
)
);
WriteEndElement();
if (AllowComments && Blog.CommentsEnabled && entry.AllowComments && !entry.CommentingClosed)
{
//optional for CommentApi Post location
WriteElementString("wfw:comment", UrlHelper.CommentApiUrl(entry.Id));
//optional url for comments
//this.WriteElementString("comments",entry.Link + "#feedback");
//optional comment count
WriteElementString("slash:comments", entry.FeedBackCount.ToString(CultureInfo.InvariantCulture));
//optional commentRss feed location
WriteElementString("wfw:commentRss", UrlHelper.CommentRssUrl(entry.Id));
//optional trackback location
WriteElementString("trackback:ping", UrlHelper.TrackbacksUrl(entry.Id));
//core
}
}
}
}
| |
using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Nucleo.Web.DataFields
{
/// <summary>
/// Provides a primitive set of functions when working with custom data control fields.
/// </summary>
public abstract class BasePrimitiveDataField : DataControlField
{
private bool _insertMode = false;
#region " Properties "
/// <summary>
/// Gets whether the data field is in insert mode.
/// </summary>
[
Browsable(false)
]
protected bool InsertMode
{
get { return _insertMode; }
}
/// <summary>
/// Gets or sets whether the data field should be read-only.
/// </summary>
[
DefaultValue(false)
]
public bool ReadOnly
{
get
{
object o = ViewState["ReadOnly"];
return (o == null) ? false : (bool)o;
}
set { ViewState["ReadOnly"] = value; }
}
#endregion
#region " Methods "
/// <summary>
/// Adds or inserts a dictionary entry for the data field/value.
/// </summary>
/// <param name="dictionary">The dictionary of items.</param>
/// <param name="dataField">The name of the data field.</param>
/// <param name="value"></param>
protected virtual void AddDictionaryEntry(System.Collections.Specialized.IOrderedDictionary dictionary, string dataField, object value)
{
if (dictionary == null)
throw new ArgumentNullException("dictionary");
if (string.IsNullOrEmpty(dataField))
throw new ArgumentNullException("dataField");
if (dictionary.Contains(dataField))
dictionary[dataField] = value;
else
dictionary.Add(dataField, value);
}
/// <summary>
/// Returns a new instance of the derived data field.
/// </summary>
/// <returns></returns>
protected override DataControlField CreateField()
{
return (DataControlField)Activator.CreateInstance(this.GetType());
}
/// <summary>
/// Loops through all of the controls in the cell and returns the first control of the specified type.
/// </summary>
/// <typeparam name="T">The type to use to retrieve a specific control reference.</typeparam>
/// <param name="cell">The cell to use.</param>
/// <returns>An instance of a control, or null if not found.</returns>
protected T ExtractControl<T>(TableCell cell) where T:Control
{
if (cell == null)
throw new ArgumentNullException("cell");
foreach (Control control in cell.Controls)
{
if (control is T)
return (T)control;
}
return null;
}
/// <summary>
/// Extracts the control from the cell, at the specified cell index.
/// </summary>
/// <typeparam name="T">The type of control that is being dealt with.</typeparam>
/// <param name="cell">The cell to use to extract a control.</param>
/// <param name="controlIndex">The index of the control.</param>
/// <returns>An instance of the control that was found at the cell index, converted to the appropriate type.</returns>
protected T ExtractControl<T>(TableCell cell, int controlIndex) where T : Control
{
if (cell == null)
throw new ArgumentNullException("cell");
if (controlIndex < 0 || controlIndex >= cell.Controls.Count)
throw new ArgumentOutOfRangeException("index", Errors.OUT_OF_RANGE);
Control control = cell.Controls[controlIndex];
if (control == null)
throw new InvalidOperationException(Errors.CANT_EXTRACT_CONTROL_IN_CELL);
return (T)control;
}
/// <summary>
/// Determines whether the row is in insert mode.
/// </summary>
/// <param name="dictionary">The dictionary of items.</param>
/// <param name="cell">The cell currently being processed.</param>
/// <param name="rowState">The current state of the row.</param>
/// <param name="includeReadOnly">Whether to include read only fields.</param>
public override void ExtractValuesFromCell(System.Collections.Specialized.IOrderedDictionary dictionary, DataControlFieldCell cell, DataControlRowState rowState, bool includeReadOnly)
{
base.ExtractValuesFromCell(dictionary, cell, rowState, includeReadOnly);
_insertMode = (rowState == DataControlRowState.Insert);
}
/// <summary>
/// Gets an instance of the property
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="container"></param>
/// <param name="property"></param>
/// <returns></returns>
protected T GetDataItemValue<T>(object container, string propertyName)
{
object value = this.GetDataItemValue(container, propertyName);
if (value == null || DBNull.Value.Equals(value))
return default(T);
else
return (T)value;
}
protected object GetDataItemValue(object container, string propertyName)
{
if (container == null || this.DesignMode)
return null;
if (string.IsNullOrEmpty(propertyName))
throw new ArgumentNullException("propertyName");
//Get the data item from the container
object dataItem = DataBinder.GetDataItem(container);
if (dataItem == null) return null;
object value = null;
//TODO:Not quite working yet; figure chaining solution
if (!propertyName.Contains("."))
//Get the value from the data item
value = DataBinder.GetPropertyValue(dataItem, propertyName);
else
{
value = dataItem;
string[] propertyList = propertyName.Split('.');
foreach (string propertyItem in propertyList)
{
value = DataBinder.GetPropertyValue(value, propertyItem);
if (value == null) return null;
}
}
return value;
}
/// <summary>
/// Determines if the row state is insert or edit (read-only is left out in this situation).
/// </summary>
/// <param name="insertMode">Whether the control is in insert mode.</param>
/// <returns>The current state of the control (edit or insert).</returns>
protected DataControlRowState GetEditRowState(bool insertMode)
{
if (insertMode)
return DataControlRowState.Insert;
else
return DataControlRowState.Edit;
}
/// <summary>
/// Gets the value of the data item in read-only form.
/// </summary>
/// <param name="cell">The cell to use to retrieve data items with, or inner cell values from.</param>
/// <param name="initialValue">The value that is the initial value to be set in the cell.</param>
/// <returns>The value that is displayed in the table cell.</returns>
protected virtual string GetReadOnlyValue(TableCell cell, object initialValue)
{
if (initialValue != null)
return initialValue.ToString();
else
return null;
}
/// <summary>
/// Determines whether the cell's inner text is empty, or whether the control count is zero.
/// </summary>
/// <param name="cell">The cell to compare.</param>
/// <returns>Whether the cell's inner text is empty.</returns>
public static bool IsEmptyCell(TableCell cell)
{
if (!IsEmptyCellText(cell))
return false;
return (cell.Controls.Count == 0);
}
/// <summary>
/// Determines whether the cell's inner text is empty.
/// </summary>
/// <param name="cell">The cell to compare.</param>
/// <returns>Whether the cell's inner text is empty.</returns>
public static bool IsEmptyCellText(TableCell cell)
{
return (string.IsNullOrEmpty(cell.Text) || (string.Compare(cell.Text, " ", true) == 0));
}
protected bool IsReadMode(DataControlRowState rowState)
{
return (this.ReadOnly || rowState == DataControlRowState.Normal || rowState == DataControlRowState.Alternate || rowState == DataControlRowState.Selected);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using AxiomCoders.PdfReports.Exceptions;
using System.Runtime.InteropServices;
using System.IO;
namespace AxiomCoders.PdfReports
{
/// <summary>
/// Main class that implements pdfFactoryInterface methods
/// </summary>
internal sealed class PdfFactory
{
public PdfFactory()
{
}
/// <summary>
/// Sets reset data callback
/// </summary>
/// <param name="resetDataStreamCallback"></param>
public static void SetResetDataStreamCallback(PdfFactoryInterface.ResetDataStreamCallback resetDataStreamCallback)
{
PdfFactoryInterface.SetResetDataStreamCallback(resetDataStreamCallback);
}
/// <summary>
/// Set request data callback
/// </summary>
/// <param name="requestDataCallback"></param>
public static void SetRequestDataCallback(PdfFactoryInterface.RequestDataCallback requestDataCallback)
{
PdfFactoryInterface.SetRequestDataCallback(requestDataCallback);
}
/// <summary>
/// Set readDataCallback
/// </summary>
/// <param name="readDataCallback"></param>
public static void SetReadDataCallback(PdfFactoryInterface.ReadDataCallback readDataCallback)
{
PdfFactoryInterface.SetReadDataCallback(readDataCallback);
}
/// <summary>
/// Set Initialize DataStream callback
/// </summary>
/// <param name="initializeDataStreamCallback"></param>
public static void SetInitializeDataStreamCallback(PdfFactoryInterface.InitializeDataStreamCallback initializeDataStreamCallback)
{
PdfFactoryInterface.SetInitializeDataStreamCallback(initializeDataStreamCallback);
}
/// <summary>
/// This will initialize generator
/// </summary>
public static void InitializeGenerator(string companyName, string serialNumber)
{
try
{
PdfFactoryInterface.InitializeGenerator(companyName, serialNumber);
}
catch (Exception ex)
{
throw new PdfFactoryEngineException(Strings.FailedGeneratorInitializing, ex);
}
}
/// <summary>
/// This will shutdown generator
/// </summary>
public static void ShutdownGenerator()
{
try
{
PdfFactoryInterface.ShutdownGenerator();
}
catch (Exception ex)
{
throw new PdfFactoryEngineException(Strings.FailedGeneratorShutdown, ex);
}
}
/// <summary>
/// Attach template from File
/// </summary>
/// <param name="templateName"></param>
public static void AttachTemplate(string templateName)
{
try
{
if (PdfFactoryInterface.AttachTemplateFromFile(templateName) == 0)
{
throw new TemplateUsageException(Strings.FailedAttachingTemplateFromFile);
}
}
catch (TemplateUsageException ex)
{
throw ex;
}
catch (Exception ex)
{
throw new TemplateUsageException(Strings.FailedAttachingTemplateFromFile, ex);
}
}
/// <summary>
/// Attach template from memory
/// </summary>
/// <param name="templateName"></param>
public static void AttachTemplate(Stream templateStream)
{
try
{
byte[] templateData = new byte[templateStream.Length];
int templateSize = 0;
templateStream.Read(templateData, 0, (int)templateStream.Length);
if (PdfFactoryInterface.AttachTemplateFromMemory(templateData, templateSize) == 0)
{
throw new TemplateUsageException(Strings.FailedAttachingTemplateFromMemory);
}
}
catch (TemplateUsageException ex)
{
throw ex;
}
catch (Exception ex)
{
throw new TemplateUsageException(Strings.FailedAttachingTemplateFromMemory, ex);
}
}
/// <summary>
/// Set Logging level
/// </summary>
/// <param name="enable"></param>
/// <param name="logLevel"></param>
public static void SetLogging(bool enable, LoggingLevel logLevel)
{
PdfFactoryInterface.SetLogging(enable ? (short)1:(short)0, (short)logLevel);
}
/// <summary>
/// Generate to memory
/// </summary>
/// <param name="outputFileName"></param>
public static byte[] Generate(ref int dataSize)
{
try
{
IntPtr bufferResult = PdfFactoryInterface.GenerateToMemory(ref dataSize);
if (bufferResult == IntPtr.Zero)
{
throw new GeneratorFailureException();
}
else
{
byte[] byteResult = new byte[dataSize];
Marshal.Copy(bufferResult, byteResult, 0, dataSize);
return byteResult;
}
}
catch (PdfFactoryEngineException ex)
{
throw ex;
}
catch (Exception ex)
{
throw new PdfFactoryEngineException(Strings.FailedGeneratingPdf, ex);
}
}
/// <summary>
/// Generate to File
/// </summary>
/// <param name="outputFileName"></param>
public static void Generate(string outputFileName)
{
try
{
if (PdfFactoryInterface.GenerateToFile(outputFileName) == 0)
{
throw new GeneratorFailureException();
}
}
catch (PdfFactoryEngineException ex)
{
throw ex;
}
catch (Exception ex)
{
throw new PdfFactoryEngineException(Strings.FailedGeneratingPdf, ex);
}
}
}
}
| |
/*
* This file is part of UniERM ReportDesigner, based on reportFU by Josh Wilson,
* the work of Kim Sheffield and the fyiReporting project.
*
* Prior Copyrights:
* _________________________________________________________
* |Copyright (C) 2010 devFU Pty Ltd, Josh Wilson and Others|
* | (http://reportfu.org) |
* =========================================================
* _________________________________________________________
* |Copyright (C) 2004-2008 fyiReporting Software, LLC |
* |For additional information, email [email protected] |
* |or visit the website www.fyiReporting.com. |
* =========================================================
*
* License:
*
* 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.Xml;
using System.Data;
using System.Collections;
namespace Reporting.Data
{
/// <summary>
/// LogCommand allows specifying the command for the web log.
/// </summary>
public class GedcomCommand : IDbCommand
{
GedcomConnection _lc; // connection we're running under
string _cmd; // command to execute
// parsed constituents of the command
string _Url; // url of the file
DataParameterCollection _Parameters = new DataParameterCollection();
public GedcomCommand(GedcomConnection conn)
{
_lc = conn;
}
internal string Url
{
get
{
// Check to see if "Url" or "@Url" is a parameter
IDbDataParameter dp= _Parameters["Url"] as IDbDataParameter;
if (dp == null)
dp= _Parameters["@Url"] as IDbDataParameter;
// Then check to see if the Url value is a parameter?
if (dp == null)
dp = _Parameters[_Url] as IDbDataParameter;
if (dp != null)
return dp.Value != null? dp.Value.ToString(): _Url; // don't pass null; pass existing value
return _Url; // the value must be a constant
}
set {_Url = value;}
}
#region IDbCommand Members
public void Cancel()
{
throw new NotImplementedException("Cancel not implemented");
}
public void Prepare()
{
return; // Prepare is a noop
}
public System.Data.CommandType CommandType
{
get
{
throw new NotImplementedException("CommandType not implemented");
}
set
{
throw new NotImplementedException("CommandType not implemented");
}
}
public IDataReader ExecuteReader(System.Data.CommandBehavior behavior)
{
if (!(behavior == CommandBehavior.SingleResult ||
behavior == CommandBehavior.SchemaOnly))
throw new ArgumentException("ExecuteReader supports SingleResult and SchemaOnly only.");
return new GedcomDataReader(behavior, _lc, this);
}
IDataReader System.Data.IDbCommand.ExecuteReader()
{
return ExecuteReader(System.Data.CommandBehavior.SingleResult);
}
public object ExecuteScalar()
{
throw new NotImplementedException("ExecuteScalar not implemented");
}
public int ExecuteNonQuery()
{
throw new NotImplementedException("ExecuteNonQuery not implemented");
}
public int CommandTimeout
{
get
{
return 0;
}
set
{
throw new NotImplementedException("CommandTimeout not implemented");
}
}
public IDbDataParameter CreateParameter()
{
return new GedcomDataParameter();
}
public IDbConnection Connection
{
get
{
return this._lc;
}
set
{
throw new NotImplementedException("Setting Connection not implemented");
}
}
public System.Data.UpdateRowSource UpdatedRowSource
{
get
{
throw new NotImplementedException("UpdatedRowSource not implemented");
}
set
{
throw new NotImplementedException("UpdatedRowSource not implemented");
}
}
public string CommandText
{
get
{
return this._cmd;
}
set
{
// Parse the command string for keyword value pairs separated by ';'
string[] args = value.Split(';');
string url=null;
foreach(string arg in args)
{
string[] param = arg.Trim().Split('=');
if (param == null || param.Length != 2)
continue;
string key = param[0].Trim().ToLower();
string val = param[1];
switch (key)
{
case "url":
case "file":
url = val;
break;
default:
throw new ArgumentException(string.Format("{0} is an unknown parameter key", param[0]));
}
}
// User must specify both the url and the RowsXPath
if (url == null)
throw new ArgumentException("CommandText requires a 'Url=' parameter.");
_cmd = value;
_Url = url;
}
}
public IDataParameterCollection Parameters
{
get
{
return _Parameters;
}
}
public IDbTransaction Transaction
{
get
{
throw new NotImplementedException("Transaction not implemented");
}
set
{
throw new NotImplementedException("Transaction not implemented");
}
}
#endregion
#region IDisposable Members
public void Dispose()
{
// nothing to dispose of
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
namespace System.Diagnostics
{
public partial class Process : IDisposable
{
private static readonly UTF8Encoding s_utf8NoBom =
new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
/// <summary>
/// Puts a Process component in state to interact with operating system processes that run in a
/// special mode by enabling the native property SeDebugPrivilege on the current thread.
/// </summary>
public static void EnterDebugMode()
{
// Nop.
}
/// <summary>
/// Takes a Process component out of the state that lets it interact with operating system processes
/// that run in a special mode.
/// </summary>
public static void LeaveDebugMode()
{
// Nop.
}
/// <summary>Stops the associated process immediately.</summary>
public void Kill()
{
EnsureState(State.HaveId);
int errno = Interop.Sys.Kill(_processId, Interop.Sys.Signals.SIGKILL);
if (errno != 0)
{
throw new Win32Exception(errno); // same exception as on Windows
}
}
/// <summary>Discards any information about the associated process.</summary>
private void RefreshCore()
{
// Nop. No additional state to reset.
}
/// <summary>Additional logic invoked when the Process is closed.</summary>
private void CloseCore()
{
if (_waitStateHolder != null)
{
_waitStateHolder.Dispose();
_waitStateHolder = null;
}
}
/// <summary>
/// Instructs the Process component to wait the specified number of milliseconds for the associated process to exit.
/// </summary>
private bool WaitForExitCore(int milliseconds)
{
bool exited = GetWaitState().WaitForExit(milliseconds);
Debug.Assert(exited || milliseconds != Timeout.Infinite);
if (exited && milliseconds == Timeout.Infinite) // if we have a hard timeout, we cannot wait for the streams
{
if (_output != null)
{
_output.WaitUtilEOF();
}
if (_error != null)
{
_error.WaitUtilEOF();
}
}
return exited;
}
/// <summary>Gets the main module for the associated process.</summary>
public ProcessModule MainModule
{
get
{
ProcessModuleCollection pmc = Modules;
return pmc.Count > 0 ? pmc[0] : null;
}
}
/// <summary>Checks whether the process has exited and updates state accordingly.</summary>
private void UpdateHasExited()
{
int? exitCode;
_exited = GetWaitState().GetExited(out exitCode);
if (_exited && exitCode != null)
{
_exitCode = exitCode.Value;
}
}
/// <summary>Gets the time that the associated process exited.</summary>
private DateTime ExitTimeCore
{
get { return GetWaitState().ExitTime; }
}
/// <summary>
/// Gets or sets a value indicating whether the associated process priority
/// should be temporarily boosted by the operating system when the main window
/// has focus.
/// </summary>
private bool PriorityBoostEnabledCore
{
get { return false; } //Nop
set { } // Nop
}
/// <summary>
/// Gets or sets the overall priority category for the associated process.
/// </summary>
private ProcessPriorityClass PriorityClassCore
{
// This mapping is relatively arbitrary. 0 is normal based on the man page,
// and the other values above and below are simply distributed evenly.
get
{
EnsureState(State.HaveId);
int pri = 0;
int errno = Interop.Sys.GetPriority(Interop.Sys.PriorityWhich.PRIO_PROCESS, _processId, out pri);
if (errno != 0)
{
throw new Win32Exception(errno); // match Windows exception
}
Debug.Assert(pri >= -20 && pri <= 20);
return
pri < -15 ? ProcessPriorityClass.RealTime :
pri < -10 ? ProcessPriorityClass.High :
pri < -5 ? ProcessPriorityClass.AboveNormal :
pri == 0 ? ProcessPriorityClass.Normal :
pri <= 10 ? ProcessPriorityClass.BelowNormal :
ProcessPriorityClass.Idle;
}
set
{
int pri;
switch (value)
{
case ProcessPriorityClass.RealTime: pri = -19; break;
case ProcessPriorityClass.High: pri = -11; break;
case ProcessPriorityClass.AboveNormal: pri = -6; break;
case ProcessPriorityClass.Normal: pri = 0; break;
case ProcessPriorityClass.BelowNormal: pri = 10; break;
case ProcessPriorityClass.Idle: pri = 19; break;
default: throw new Win32Exception(); // match Windows exception
}
int result = Interop.Sys.SetPriority(Interop.Sys.PriorityWhich.PRIO_PROCESS, _processId, pri);
if (result == -1)
{
throw new Win32Exception(); // match Windows exception
}
}
}
/// <summary>Gets the ID of the current process.</summary>
private static int GetCurrentProcessId()
{
return Interop.Sys.GetPid();
}
/// <summary>
/// Gets a short-term handle to the process, with the given access. If a handle exists,
/// then it is reused. If the process has exited, it throws an exception.
/// </summary>
private SafeProcessHandle GetProcessHandle()
{
if (_haveProcessHandle)
{
if (GetWaitState().HasExited)
{
throw new InvalidOperationException(SR.Format(SR.ProcessHasExited, _processId.ToString(CultureInfo.CurrentCulture)));
}
return _processHandle;
}
EnsureState(State.HaveId | State.IsLocal);
return new SafeProcessHandle(_processId);
}
/// <summary>Starts the process using the supplied start info.</summary>
/// <param name="startInfo">The start info with which to start the process.</param>
private bool StartCore(ProcessStartInfo startInfo)
{
string filename;
string[] argv;
if (startInfo.UseShellExecute)
{
if (startInfo.RedirectStandardInput || startInfo.RedirectStandardOutput || startInfo.RedirectStandardError)
{
throw new InvalidOperationException(SR.CantRedirectStreams);
}
const string ShellPath = "/bin/sh";
filename = ShellPath;
argv = new string[3] { ShellPath, "-c", startInfo.FileName + " " + startInfo.Arguments};
}
else
{
filename = ResolvePath(startInfo.FileName);
argv = ParseArgv(startInfo);
}
string[] envp = CreateEnvp(startInfo);
string cwd = !string.IsNullOrWhiteSpace(startInfo.WorkingDirectory) ? startInfo.WorkingDirectory : null;
// Invoke the shim fork/execve routine. It will create pipes for all requested
// redirects, fork a child process, map the pipe ends onto the appropriate stdin/stdout/stderr
// descriptors, and execve to execute the requested process. The shim implementation
// is used to fork/execve as executing managed code in a forked process is not safe (only
// the calling thread will transfer, thread IDs aren't stable across the fork, etc.)
int childPid, stdinFd, stdoutFd, stderrFd;
if (Interop.Sys.ForkAndExecProcess(
filename, argv, envp, cwd,
startInfo.RedirectStandardInput, startInfo.RedirectStandardOutput, startInfo.RedirectStandardError,
out childPid,
out stdinFd, out stdoutFd, out stderrFd) != 0)
{
throw new Win32Exception();
}
// Store the child's information into this Process object.
Debug.Assert(childPid >= 0);
SetProcessHandle(new SafeProcessHandle(childPid));
SetProcessId(childPid);
// Configure the parent's ends of the redirection streams.
// We use UTF8 encoding without BOM by-default(instead of Console encoding as on Windows)
// as there is no good way to get this information from the native layer
// and we do not want to take dependency on Console contract.
if (startInfo.RedirectStandardInput)
{
Debug.Assert(stdinFd >= 0);
_standardInput = new StreamWriter(OpenStream(stdinFd, FileAccess.Write),
s_utf8NoBom, StreamBufferSize) { AutoFlush = true };
}
if (startInfo.RedirectStandardOutput)
{
Debug.Assert(stdoutFd >= 0);
_standardOutput = new StreamReader(OpenStream(stdoutFd, FileAccess.Read),
startInfo.StandardOutputEncoding ?? s_utf8NoBom, true, StreamBufferSize);
}
if (startInfo.RedirectStandardError)
{
Debug.Assert(stderrFd >= 0);
_standardError = new StreamReader(OpenStream(stderrFd, FileAccess.Read),
startInfo.StandardErrorEncoding ?? s_utf8NoBom, true, StreamBufferSize);
}
return true;
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
/// <summary>Finalizable holder for the underlying shared wait state object.</summary>
private ProcessWaitState.Holder _waitStateHolder;
/// <summary>Size to use for redirect streams and stream readers/writers.</summary>
private const int StreamBufferSize = 4096;
/// <summary>Converts the filename and arguments information from a ProcessStartInfo into an argv array.</summary>
/// <param name="psi">The ProcessStartInfo.</param>
/// <returns>The argv array.</returns>
private static string[] ParseArgv(ProcessStartInfo psi)
{
string argv0 = psi.FileName; // pass filename (instead of resolved path) as argv[0], to match what caller supplied
if (string.IsNullOrEmpty(psi.Arguments))
{
return new string[] { argv0 };
}
else
{
var argvList = new List<string>();
argvList.Add(argv0);
ParseArgumentsIntoList(psi.Arguments, argvList);
return argvList.ToArray();
}
}
/// <summary>Converts the environment variables information from a ProcessStartInfo into an envp array.</summary>
/// <param name="psi">The ProcessStartInfo.</param>
/// <returns>The envp array.</returns>
private static string[] CreateEnvp(ProcessStartInfo psi)
{
var envp = new string[psi.Environment.Count];
int index = 0;
foreach (var pair in psi.Environment)
{
envp[index++] = pair.Key + "=" + pair.Value;
}
return envp;
}
/// <summary>Resolves a path to the filename passed to ProcessStartInfo.</summary>
/// <param name="filename">The filename.</param>
/// <returns>The resolved path.</returns>
private static string ResolvePath(string filename)
{
// Follow the same resolution that Windows uses with CreateProcess:
// 1. First try the exact path provided
// 2. Then try the file relative to the executable directory
// 3. Then try the file relative to the current directory
// 4. then try the file in each of the directories specified in PATH
// Windows does additional Windows-specific steps between 3 and 4,
// and we ignore those here.
// If the filename is a complete path, use it, regardless of whether it exists.
if (Path.IsPathRooted(filename))
{
// In this case, it doesn't matter whether the file exists or not;
// it's what the caller asked for, so it's what they'll get
return filename;
}
// Then check the executable's directory
string path = GetExePath();
if (path != null)
{
try
{
path = Path.Combine(Path.GetDirectoryName(path), filename);
if (File.Exists(path))
{
return path;
}
}
catch (ArgumentException) { } // ignore any errors in data that may come from the exe path
}
// Then check the current directory
path = Path.Combine(Directory.GetCurrentDirectory(), filename);
if (File.Exists(path))
{
return path;
}
// Then check each directory listed in the PATH environment variables
string pathEnvVar = Environment.GetEnvironmentVariable("PATH");
if (pathEnvVar != null)
{
var pathParser = new StringParser(pathEnvVar, ':', skipEmpty: true);
while (pathParser.MoveNext())
{
string subPath = pathParser.ExtractCurrent();
path = Path.Combine(subPath, filename);
if (File.Exists(path))
{
return path;
}
}
}
// Could not find the file
throw new Win32Exception(Interop.Error.ENOENT.Info().RawErrno);
}
/// <summary>Convert a number of "jiffies", or ticks, to a TimeSpan.</summary>
/// <param name="ticks">The number of ticks.</param>
/// <returns>The equivalent TimeSpan.</returns>
internal static TimeSpan TicksToTimeSpan(double ticks)
{
// Look up the number of ticks per second in the system's configuration,
// then use that to convert to a TimeSpan
long ticksPerSecond = Interop.Sys.SysConf(Interop.Sys.SysConfName._SC_CLK_TCK);
if (ticksPerSecond <= 0)
{
throw new Win32Exception();
}
return TimeSpan.FromSeconds(ticks / (double)ticksPerSecond);
}
/// <summary>Computes a time based on a number of ticks since boot.</summary>
/// <param name="timespanAfterBoot">The timespan since boot.</param>
/// <returns>The converted time.</returns>
internal static DateTime BootTimeToDateTime(TimeSpan timespanAfterBoot)
{
// Use the uptime and the current time to determine the absolute boot time
DateTime bootTime = DateTime.UtcNow - TimeSpan.FromMilliseconds(Environment.TickCount);
// And use that to determine the absolute time for timespan.
DateTime dt = bootTime + timespanAfterBoot;
// The return value is expected to be in the local time zone.
// It is converted here (rather than starting with DateTime.Now) to avoid DST issues.
return dt.ToLocalTime();
}
/// <summary>Opens a stream around the specified file descriptor and with the specified access.</summary>
/// <param name="fd">The file descriptor.</param>
/// <param name="access">The access mode.</param>
/// <returns>The opened stream.</returns>
private static FileStream OpenStream(int fd, FileAccess access)
{
Debug.Assert(fd >= 0);
return new FileStream(
new SafeFileHandle((IntPtr)fd, ownsHandle: true),
access, StreamBufferSize, isAsync: false);
}
/// <summary>Parses a command-line argument string into a list of arguments.</summary>
/// <param name="arguments">The argument string.</param>
/// <param name="results">The list into which the component arguments should be stored.</param>
/// <remarks>
/// This follows the rules outlined in "Parsing C++ Command-Line Arguments" at
/// https://msdn.microsoft.com/en-us/library/17w5ykft.aspx.
/// </remarks>
private static void ParseArgumentsIntoList(string arguments, List<string> results)
{
var currentArgument = new StringBuilder();
bool inQuotes = false;
// Iterate through all of the characters in the argument string.
for (int i = 0; i < arguments.Length; i++)
{
// From the current position, iterate through contiguous backslashes.
int backslashCount = 0;
for (; i < arguments.Length && arguments[i] == '\\'; i++, backslashCount++) ;
if (backslashCount > 0)
{
if (i >= arguments.Length || arguments[i] != '"')
{
// Backslashes not followed by a double quote:
// they should all be treated as literal backslashes.
currentArgument.Append('\\', backslashCount);
i--;
}
else
{
// Backslashes followed by a double quote:
// - Output a literal slash for each complete pair of slashes
// - If one remains, use it to make the subsequent quote a literal.
currentArgument.Append('\\', backslashCount / 2);
if (backslashCount % 2 == 0)
{
i--;
}
else
{
currentArgument.Append('"');
}
}
continue;
}
char c = arguments[i];
// If this is a double quote, track whether we're inside of quotes or not.
// Anything within quotes will be treated as a single argument, even if
// it contains spaces.
if (c == '"')
{
inQuotes = !inQuotes;
continue;
}
// If this is a space/tab and we're not in quotes, we're done with the current
// argument, and if we've built up any characters in the current argument,
// it should be added to the results and then reset for the next one.
if ((c == ' ' || c == '\t') && !inQuotes)
{
if (currentArgument.Length > 0)
{
results.Add(currentArgument.ToString());
currentArgument.Clear();
}
continue;
}
// Nothing special; add the character to the current argument.
currentArgument.Append(c);
}
// If we reach the end of the string and we still have anything in our current
// argument buffer, treat it as an argument to be added to the results.
if (currentArgument.Length > 0)
{
results.Add(currentArgument.ToString());
}
}
/// <summary>Gets the wait state for this Process object.</summary>
private ProcessWaitState GetWaitState()
{
if (_waitStateHolder == null)
{
EnsureState(State.HaveId);
_waitStateHolder = new ProcessWaitState.Holder(_processId);
}
return _waitStateHolder._state;
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* 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 OpenSim 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.IO;
using System.Reflection;
using System.Text;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.Imaging;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenMetaverse.Assets;
namespace OpenSim.Region.CoreModules.Agent.TextureSender
{
public class J2KDecoderModule : IRegionModule, IJ2KDecoder
{
#region IRegionModule Members
private static readonly ILog m_log
= LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Cached Decoded Layers
/// </summary>
private bool OpenJpegFail = false;
private J2KDecodeFileCache fCache;
/// <summary>
/// List of client methods to notify of results of decode
/// </summary>
private readonly Dictionary<UUID, List<DecodedCallback>> m_notifyList = new Dictionary<UUID, List<DecodedCallback>>();
public J2KDecoderModule()
{
}
public void Initialise(Scene scene, IConfigSource source)
{
bool useFileCache = true;
IConfig myConfig = source.Configs["J2KDecoder"];
if (myConfig == null)
return;
if (myConfig.GetString("J2KDecoderModule", String.Empty) != Name)
return;
useFileCache = myConfig.GetBoolean("J2KDecoderFileCacheEnabled", true);
m_log.DebugFormat("[J2K DECODER MODULE] Using {0} decoder. File Cache is {1}",
Name, (useFileCache ? "enabled" : "disabled"));
fCache = new J2KDecodeFileCache(useFileCache, J2KDecodeFileCache.CacheFolder);
scene.RegisterModuleInterface<IJ2KDecoder>(this);
}
public void PostInitialise()
{
}
public void Close()
{
}
public string Name
{
get { return "J2KDecoderModule"; }
}
public bool IsSharedModule
{
get { return true; }
}
#endregion
#region IJ2KDecoder Members
public void BeginDecode(UUID AssetId, byte[] assetData, DecodedCallback decodedReturn)
{
// Dummy for if decoding fails.
OpenJPEG.J2KLayerInfo[] result = new OpenJPEG.J2KLayerInfo[0];
// Check if it's cached
bool cached = false;
lock (fCache)
{
cached = fCache.TryLoadCacheForAsset(AssetId, out result);
}
// If it's cached, return the cached results
if (cached)
{
decodedReturn(AssetId, result);
}
else
{
// not cached, so we need to decode it
// Add to notify list and start decoding.
// Next request for this asset while it's decoding will only be added to the notify list
// once this is decoded, requests will be served from the cache and all clients in the notifylist will be updated
bool decode = false;
lock (m_notifyList)
{
if (m_notifyList.ContainsKey(AssetId))
{
m_notifyList[AssetId].Add(decodedReturn);
}
else
{
List<DecodedCallback> notifylist = new List<DecodedCallback>();
notifylist.Add(decodedReturn);
m_notifyList.Add(AssetId, notifylist);
decode = true;
}
}
// Do Decode!
if (decode)
{
Decode(AssetId, assetData);
}
}
}
public bool Decode(UUID assetID, byte[] j2kData)
{
OpenJPEG.J2KLayerInfo[] layers;
return Decode(assetID, j2kData, out layers);
}
public bool Decode(UUID assetID, byte[] j2kData, out OpenJPEG.J2KLayerInfo[] layers)
{
bool decodedSuccessfully = true;
layers = new OpenJPEG.J2KLayerInfo[0]; // Dummy result for if it fails. Informs that there's only full quality
if (! OpenJpegFail)
{
lock (fCache)
{
decodedSuccessfully = fCache.TryLoadCacheForAsset(assetID, out layers);
}
if (!decodedSuccessfully)
decodedSuccessfully = DoJ2KDecode(assetID, j2kData, out layers);
}
// Notify Interested Parties
lock (m_notifyList)
{
if (m_notifyList.ContainsKey(assetID))
{
foreach (DecodedCallback d in m_notifyList[assetID])
{
if (d != null)
d.DynamicInvoke(assetID, layers);
}
m_notifyList.Remove(assetID);
}
}
return (decodedSuccessfully);
}
#endregion
/// <summary>
/// Decode Jpeg2000 Asset Data
/// </summary>
/// <param name="AssetId">UUID of Asset</param>
/// <param name="j2kdata">Byte Array Asset Data </param>
private bool DoJ2KDecode(UUID assetID, byte[] j2kdata, out OpenJPEG.J2KLayerInfo[] layers)
{
int DecodeTime = 0;
DecodeTime = Environment.TickCount;
bool decodedSuccessfully = true;
layers = new OpenJPEG.J2KLayerInfo[0]; // Dummy result for if it fails. Informs that there's only full quality
try
{
AssetTexture texture = new AssetTexture(assetID, j2kdata);
bool sane = false;
if (texture.DecodeLayerBoundaries())
{
sane = true;
// Sanity check all of the layers
for (int i = 0; i < texture.LayerInfo.Length; i++)
{
if (texture.LayerInfo[i].End > texture.AssetData.Length)
{
sane = false;
break;
}
}
}
if (sane)
{
m_log.InfoFormat("[J2KDecoderModule]: {0} Decode Time: {1}", Environment.TickCount - DecodeTime, assetID);
layers = texture.LayerInfo;
}
else
{
m_log.Warn("[J2KDecoderModule]: Failed to decode layer data for texture " + assetID + ", guessing sane defaults");
decodedSuccessfully = false;
// Layer decoding completely failed. Guess at sane defaults for the layer boundaries
layers = CreateDefaultLayers(j2kdata.Length);
}
fCache.SaveCacheForAsset(assetID, layers);
texture = null; // dereference and dispose of ManagedImage
}
catch (DllNotFoundException)
{
m_log.Error(
"[J2KDecoderModule]: OpenJpeg is not installed properly. Decoding disabled! This will slow down texture performance! Often times this is because of an old version of GLIBC. You must have version 2.4 or above!");
OpenJpegFail = true;
decodedSuccessfully = false;
}
catch (Exception ex)
{
m_log.WarnFormat(
"[J2KDecoderModule]: JPEG2000 texture decoding threw an exception for {0}, {1}",
assetID, ex);
decodedSuccessfully = false;
}
return (decodedSuccessfully);
}
private OpenJPEG.J2KLayerInfo[] CreateDefaultLayers(int j2kLength)
{
OpenJPEG.J2KLayerInfo[] layers = new OpenJPEG.J2KLayerInfo[5];
for (int i = 0; i < layers.Length; i++)
layers[i] = new OpenJPEG.J2KLayerInfo();
// These default layer sizes are based on a small sampling of real-world texture data
// with extra padding thrown in for good measure. This is a worst case fallback plan
// and may not gracefully handle all real world data
layers[0].Start = 0;
layers[1].Start = (int)((float)j2kLength * 0.02f);
layers[2].Start = (int)((float)j2kLength * 0.05f);
layers[3].Start = (int)((float)j2kLength * 0.20f);
layers[4].Start = (int)((float)j2kLength * 0.50f);
layers[0].End = layers[1].Start - 1;
layers[1].End = layers[2].Start - 1;
layers[2].End = layers[3].Start - 1;
layers[3].End = layers[4].Start - 1;
layers[4].End = j2kLength;
return layers;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Security;
using System.Text;
using System.Threading;
using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
namespace System.Reflection
{
internal sealed class RuntimeMethodInfo : MethodInfo, IRuntimeMethodInfo
{
#region Private Data Members
private IntPtr m_handle;
private RuntimeTypeCache m_reflectedTypeCache;
private string m_name;
private string m_toString;
private ParameterInfo[] m_parameters;
private ParameterInfo m_returnParameter;
private BindingFlags m_bindingFlags;
private MethodAttributes m_methodAttributes;
private Signature m_signature;
private RuntimeType m_declaringType;
private object m_keepalive;
private INVOCATION_FLAGS m_invocationFlags;
internal INVOCATION_FLAGS InvocationFlags
{
get
{
if ((m_invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED) == 0)
{
INVOCATION_FLAGS invocationFlags = INVOCATION_FLAGS.INVOCATION_FLAGS_UNKNOWN;
Type declaringType = DeclaringType;
//
// first take care of all the NO_INVOKE cases.
if (ContainsGenericParameters ||
ReturnType.IsByRef ||
(declaringType != null && declaringType.ContainsGenericParameters) ||
((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) ||
((Attributes & MethodAttributes.RequireSecObject) == MethodAttributes.RequireSecObject))
{
// We don't need other flags if this method cannot be invoked
invocationFlags = INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE;
}
else
{
// this should be an invocable method, determine the other flags that participate in invocation
invocationFlags = RuntimeMethodHandle.GetSecurityFlags(this);
}
m_invocationFlags = invocationFlags | INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED;
}
return m_invocationFlags;
}
}
#endregion
#region Constructor
internal RuntimeMethodInfo(
RuntimeMethodHandleInternal handle, RuntimeType declaringType,
RuntimeTypeCache reflectedTypeCache, MethodAttributes methodAttributes, BindingFlags bindingFlags, object keepalive)
{
Contract.Ensures(!m_handle.IsNull());
Debug.Assert(!handle.IsNullHandle());
Debug.Assert(methodAttributes == RuntimeMethodHandle.GetAttributes(handle));
m_bindingFlags = bindingFlags;
m_declaringType = declaringType;
m_keepalive = keepalive;
m_handle = handle.Value;
m_reflectedTypeCache = reflectedTypeCache;
m_methodAttributes = methodAttributes;
}
#endregion
#region Private Methods
RuntimeMethodHandleInternal IRuntimeMethodInfo.Value
{
get
{
return new RuntimeMethodHandleInternal(m_handle);
}
}
private RuntimeType ReflectedTypeInternal
{
get
{
return m_reflectedTypeCache.GetRuntimeType();
}
}
private ParameterInfo[] FetchNonReturnParameters()
{
if (m_parameters == null)
m_parameters = RuntimeParameterInfo.GetParameters(this, this, Signature);
return m_parameters;
}
private ParameterInfo FetchReturnParameter()
{
if (m_returnParameter == null)
m_returnParameter = RuntimeParameterInfo.GetReturnParameter(this, this, Signature);
return m_returnParameter;
}
#endregion
#region Internal Members
internal override string FormatNameAndSig(bool serialization)
{
// Serialization uses ToString to resolve MethodInfo overloads.
StringBuilder sbName = new StringBuilder(Name);
// serialization == true: use unambiguous (except for assembly name) type names to distinguish between overloads.
// serialization == false: use basic format to maintain backward compatibility of MethodInfo.ToString().
TypeNameFormatFlags format = serialization ? TypeNameFormatFlags.FormatSerialization : TypeNameFormatFlags.FormatBasic;
if (IsGenericMethod)
sbName.Append(RuntimeMethodHandle.ConstructInstantiation(this, format));
sbName.Append("(");
sbName.Append(ConstructParameters(GetParameterTypes(), CallingConvention, serialization));
sbName.Append(")");
return sbName.ToString();
}
internal override bool CacheEquals(object o)
{
RuntimeMethodInfo m = o as RuntimeMethodInfo;
if ((object)m == null)
return false;
return m.m_handle == m_handle;
}
internal Signature Signature
{
get
{
if (m_signature == null)
m_signature = new Signature(this, m_declaringType);
return m_signature;
}
}
internal BindingFlags BindingFlags { get { return m_bindingFlags; } }
internal RuntimeMethodInfo GetParentDefinition()
{
if (!IsVirtual || m_declaringType.IsInterface)
return null;
RuntimeType parent = (RuntimeType)m_declaringType.BaseType;
if (parent == null)
return null;
int slot = RuntimeMethodHandle.GetSlot(this);
if (RuntimeTypeHandle.GetNumVirtuals(parent) <= slot)
return null;
return (RuntimeMethodInfo)RuntimeType.GetMethodBase(parent, RuntimeTypeHandle.GetMethodAt(parent, slot));
}
// Unlike DeclaringType, this will return a valid type even for global methods
internal RuntimeType GetDeclaringTypeInternal()
{
return m_declaringType;
}
#endregion
#region Object Overrides
public override String ToString()
{
if (m_toString == null)
m_toString = ReturnType.FormatTypeName() + " " + FormatNameAndSig();
return m_toString;
}
public override int GetHashCode()
{
// See RuntimeMethodInfo.Equals() below.
if (IsGenericMethod)
return ValueType.GetHashCodeOfPtr(m_handle);
else
return base.GetHashCode();
}
public override bool Equals(object obj)
{
if (!IsGenericMethod)
return obj == (object)this;
// We cannot do simple object identity comparisons for generic methods.
// Equals will be called in CerHashTable when RuntimeType+RuntimeTypeCache.GetGenericMethodInfo()
// retrieve items from and insert items into s_methodInstantiations which is a CerHashtable.
RuntimeMethodInfo mi = obj as RuntimeMethodInfo;
if (mi == null || !mi.IsGenericMethod)
return false;
// now we know that both operands are generic methods
IRuntimeMethodInfo handle1 = RuntimeMethodHandle.StripMethodInstantiation(this);
IRuntimeMethodInfo handle2 = RuntimeMethodHandle.StripMethodInstantiation(mi);
if (handle1.Value.Value != handle2.Value.Value)
return false;
Type[] lhs = GetGenericArguments();
Type[] rhs = mi.GetGenericArguments();
if (lhs.Length != rhs.Length)
return false;
for (int i = 0; i < lhs.Length; i++)
{
if (lhs[i] != rhs[i])
return false;
}
if (DeclaringType != mi.DeclaringType)
return false;
if (ReflectedType != mi.ReflectedType)
return false;
return true;
}
#endregion
#region ICustomAttributeProvider
public override Object[] GetCustomAttributes(bool inherit)
{
return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType as RuntimeType, inherit);
}
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType, inherit);
}
public override bool IsDefined(Type attributeType, bool inherit)
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
return CustomAttribute.IsDefined(this, attributeRuntimeType, inherit);
}
public override IList<CustomAttributeData> GetCustomAttributesData()
{
return CustomAttributeData.GetCustomAttributesInternal(this);
}
#endregion
#region MemberInfo Overrides
public override String Name
{
get
{
if (m_name == null)
m_name = RuntimeMethodHandle.GetName(this);
return m_name;
}
}
public override Type DeclaringType
{
get
{
if (m_reflectedTypeCache.IsGlobal)
return null;
return m_declaringType;
}
}
public sealed override bool HasSameMetadataDefinitionAs(MemberInfo other) => HasSameMetadataDefinitionAsCore<RuntimeMethodInfo>(other);
public override Type ReflectedType
{
get
{
if (m_reflectedTypeCache.IsGlobal)
return null;
return m_reflectedTypeCache.GetRuntimeType();
}
}
public override MemberTypes MemberType { get { return MemberTypes.Method; } }
public override int MetadataToken
{
get { return RuntimeMethodHandle.GetMethodDef(this); }
}
public override Module Module { get { return GetRuntimeModule(); } }
internal RuntimeType GetRuntimeType() { return m_declaringType; }
internal RuntimeModule GetRuntimeModule() { return m_declaringType.GetRuntimeModule(); }
internal RuntimeAssembly GetRuntimeAssembly() { return GetRuntimeModule().GetRuntimeAssembly(); }
public override bool IsSecurityCritical
{
get { return true; }
}
public override bool IsSecuritySafeCritical
{
get { return false; }
}
public override bool IsSecurityTransparent
{
get { return false; }
}
#endregion
#region MethodBase Overrides
internal override ParameterInfo[] GetParametersNoCopy()
{
FetchNonReturnParameters();
return m_parameters;
}
[System.Diagnostics.Contracts.Pure]
public override ParameterInfo[] GetParameters()
{
FetchNonReturnParameters();
if (m_parameters.Length == 0)
return m_parameters;
ParameterInfo[] ret = new ParameterInfo[m_parameters.Length];
Array.Copy(m_parameters, ret, m_parameters.Length);
return ret;
}
public override MethodImplAttributes GetMethodImplementationFlags()
{
return RuntimeMethodHandle.GetImplAttributes(this);
}
public override RuntimeMethodHandle MethodHandle
{
get
{
Type declaringType = DeclaringType;
if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType)
throw new InvalidOperationException(SR.InvalidOperation_NotAllowedInReflectionOnly);
return new RuntimeMethodHandle(this);
}
}
public override MethodAttributes Attributes { get { return m_methodAttributes; } }
public override CallingConventions CallingConvention
{
get
{
return Signature.CallingConvention;
}
}
public override MethodBody GetMethodBody()
{
MethodBody mb = RuntimeMethodHandle.GetMethodBody(this, ReflectedTypeInternal);
if (mb != null)
mb.m_methodBase = this;
return mb;
}
#endregion
#region Invocation Logic(On MemberBase)
private void CheckConsistency(Object target)
{
// only test instance methods
if ((m_methodAttributes & MethodAttributes.Static) != MethodAttributes.Static)
{
if (!m_declaringType.IsInstanceOfType(target))
{
if (target == null)
throw new TargetException(SR.RFLCT_Targ_StatMethReqTarg);
else
throw new TargetException(SR.RFLCT_Targ_ITargMismatch);
}
}
}
private void ThrowNoInvokeException()
{
// method is ReflectionOnly
Type declaringType = DeclaringType;
if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType)
{
throw new InvalidOperationException(SR.Arg_ReflectionOnlyInvoke);
}
// method is on a class that contains stack pointers
else if ((InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_CONTAINS_STACK_POINTERS) != 0)
{
throw new NotSupportedException();
}
// method is vararg
else if ((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs)
{
throw new NotSupportedException();
}
// method is generic or on a generic class
else if (DeclaringType.ContainsGenericParameters || ContainsGenericParameters)
{
throw new InvalidOperationException(SR.Arg_UnboundGenParam);
}
// method is abstract class
else if (IsAbstract)
{
throw new MemberAccessException();
}
// ByRef return are not allowed in reflection
else if (ReturnType.IsByRef)
{
throw new NotSupportedException(SR.NotSupported_ByRefReturn);
}
throw new TargetException();
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
{
object[] arguments = InvokeArgumentsCheck(obj, invokeAttr, binder, parameters, culture);
return UnsafeInvokeInternal(obj, parameters, arguments);
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
internal object UnsafeInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
{
object[] arguments = InvokeArgumentsCheck(obj, invokeAttr, binder, parameters, culture);
return UnsafeInvokeInternal(obj, parameters, arguments);
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
private object UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
{
if (arguments == null || arguments.Length == 0)
return RuntimeMethodHandle.InvokeMethod(obj, null, Signature, false);
else
{
Object retValue = RuntimeMethodHandle.InvokeMethod(obj, arguments, Signature, false);
// copy out. This should be made only if ByRef are present.
for (int index = 0; index < arguments.Length; index++)
parameters[index] = arguments[index];
return retValue;
}
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
private object[] InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
{
Signature sig = Signature;
// get the signature
int formalCount = sig.Arguments.Length;
int actualCount = (parameters != null) ? parameters.Length : 0;
INVOCATION_FLAGS invocationFlags = InvocationFlags;
// INVOCATION_FLAGS_CONTAINS_STACK_POINTERS means that the struct (either the declaring type or the return type)
// contains pointers that point to the stack. This is either a ByRef or a TypedReference. These structs cannot
// be boxed and thus cannot be invoked through reflection which only deals with boxed value type objects.
if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE | INVOCATION_FLAGS.INVOCATION_FLAGS_CONTAINS_STACK_POINTERS)) != 0)
ThrowNoInvokeException();
// check basic method consistency. This call will throw if there are problems in the target/method relationship
CheckConsistency(obj);
if (formalCount != actualCount)
throw new TargetParameterCountException(SR.Arg_ParmCnt);
if (actualCount != 0)
return CheckArguments(parameters, binder, invokeAttr, culture, sig);
else
return null;
}
#endregion
#region MethodInfo Overrides
public override Type ReturnType
{
get { return Signature.ReturnType; }
}
public override ICustomAttributeProvider ReturnTypeCustomAttributes
{
get { return ReturnParameter; }
}
public override ParameterInfo ReturnParameter
{
get
{
Contract.Ensures(m_returnParameter != null);
FetchReturnParameter();
return m_returnParameter as ParameterInfo;
}
}
public override MethodInfo GetBaseDefinition()
{
if (!IsVirtual || IsStatic || m_declaringType == null || m_declaringType.IsInterface)
return this;
int slot = RuntimeMethodHandle.GetSlot(this);
RuntimeType declaringType = (RuntimeType)DeclaringType;
RuntimeType baseDeclaringType = declaringType;
RuntimeMethodHandleInternal baseMethodHandle = new RuntimeMethodHandleInternal();
do
{
int cVtblSlots = RuntimeTypeHandle.GetNumVirtuals(declaringType);
if (cVtblSlots <= slot)
break;
baseMethodHandle = RuntimeTypeHandle.GetMethodAt(declaringType, slot);
baseDeclaringType = declaringType;
declaringType = (RuntimeType)declaringType.BaseType;
} while (declaringType != null);
return (MethodInfo)RuntimeType.GetMethodBase(baseDeclaringType, baseMethodHandle);
}
public override Delegate CreateDelegate(Type delegateType)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
// This API existed in v1/v1.1 and only expected to create closed
// instance delegates. Constrain the call to BindToMethodInfo to
// open delegates only for backwards compatibility. But we'll allow
// relaxed signature checking and open static delegates because
// there's no ambiguity there (the caller would have to explicitly
// pass us a static method or a method with a non-exact signature
// and the only change in behavior from v1.1 there is that we won't
// fail the call).
return CreateDelegateInternal(
delegateType,
null,
DelegateBindingFlags.OpenDelegateOnly | DelegateBindingFlags.RelaxedSignature,
ref stackMark);
}
public override Delegate CreateDelegate(Type delegateType, Object target)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
// This API is new in Whidbey and allows the full range of delegate
// flexability (open or closed delegates binding to static or
// instance methods with relaxed signature checking). The delegate
// can also be closed over null. There's no ambiguity with all these
// options since the caller is providing us a specific MethodInfo.
return CreateDelegateInternal(
delegateType,
target,
DelegateBindingFlags.RelaxedSignature,
ref stackMark);
}
private Delegate CreateDelegateInternal(Type delegateType, Object firstArgument, DelegateBindingFlags bindingFlags, ref StackCrawlMark stackMark)
{
// Validate the parameters.
if (delegateType == null)
throw new ArgumentNullException(nameof(delegateType));
Contract.EndContractBlock();
RuntimeType rtType = delegateType as RuntimeType;
if (rtType == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(delegateType));
if (!rtType.IsDelegate())
throw new ArgumentException(SR.Arg_MustBeDelegate, nameof(delegateType));
Delegate d = Delegate.CreateDelegateInternal(rtType, this, firstArgument, bindingFlags, ref stackMark);
if (d == null)
{
throw new ArgumentException(SR.Arg_DlgtTargMeth);
}
return d;
}
#endregion
#region Generics
public override MethodInfo MakeGenericMethod(params Type[] methodInstantiation)
{
if (methodInstantiation == null)
throw new ArgumentNullException(nameof(methodInstantiation));
Contract.EndContractBlock();
RuntimeType[] methodInstantionRuntimeType = new RuntimeType[methodInstantiation.Length];
if (!IsGenericMethodDefinition)
throw new InvalidOperationException(
SR.Format(SR.Arg_NotGenericMethodDefinition, this));
for (int i = 0; i < methodInstantiation.Length; i++)
{
Type methodInstantiationElem = methodInstantiation[i];
if (methodInstantiationElem == null)
throw new ArgumentNullException();
RuntimeType rtMethodInstantiationElem = methodInstantiationElem as RuntimeType;
if (rtMethodInstantiationElem == null)
{
Type[] methodInstantiationCopy = new Type[methodInstantiation.Length];
for (int iCopy = 0; iCopy < methodInstantiation.Length; iCopy++)
methodInstantiationCopy[iCopy] = methodInstantiation[iCopy];
methodInstantiation = methodInstantiationCopy;
return System.Reflection.Emit.MethodBuilderInstantiation.MakeGenericMethod(this, methodInstantiation);
}
methodInstantionRuntimeType[i] = rtMethodInstantiationElem;
}
RuntimeType[] genericParameters = GetGenericArgumentsInternal();
RuntimeType.SanityCheckGenericArguments(methodInstantionRuntimeType, genericParameters);
MethodInfo ret = null;
try
{
ret = RuntimeType.GetMethodBase(ReflectedTypeInternal,
RuntimeMethodHandle.GetStubIfNeeded(new RuntimeMethodHandleInternal(m_handle), m_declaringType, methodInstantionRuntimeType)) as MethodInfo;
}
catch (VerificationException e)
{
RuntimeType.ValidateGenericArguments(this, methodInstantionRuntimeType, e);
throw;
}
return ret;
}
internal RuntimeType[] GetGenericArgumentsInternal()
{
return RuntimeMethodHandle.GetMethodInstantiationInternal(this);
}
public override Type[] GetGenericArguments()
{
Type[] types = RuntimeMethodHandle.GetMethodInstantiationPublic(this);
if (types == null)
{
types = Array.Empty<Type>();
}
return types;
}
public override MethodInfo GetGenericMethodDefinition()
{
if (!IsGenericMethod)
throw new InvalidOperationException();
Contract.EndContractBlock();
return RuntimeType.GetMethodBase(m_declaringType, RuntimeMethodHandle.StripMethodInstantiation(this)) as MethodInfo;
}
public override bool IsGenericMethod
{
get { return RuntimeMethodHandle.HasMethodInstantiation(this); }
}
public override bool IsGenericMethodDefinition
{
get { return RuntimeMethodHandle.IsGenericMethodDefinition(this); }
}
public override bool ContainsGenericParameters
{
get
{
if (DeclaringType != null && DeclaringType.ContainsGenericParameters)
return true;
if (!IsGenericMethod)
return false;
Type[] pis = GetGenericArguments();
for (int i = 0; i < pis.Length; i++)
{
if (pis[i].ContainsGenericParameters)
return true;
}
return false;
}
}
#endregion
#region Legacy Internal
internal static MethodBase InternalGetCurrentMethod(ref StackCrawlMark stackMark)
{
IRuntimeMethodInfo method = RuntimeMethodHandle.GetCurrentMethod(ref stackMark);
if (method == null)
return null;
return RuntimeType.GetMethodBase(method);
}
#endregion
}
}
| |
// Copyright (c) 2013 SIL International
// This software is licensed under the MIT license (http://opensource.org/licenses/MIT)
using System;
using System.ComponentModel;
using System.Data;
using System.IO;
namespace Icu
{
/// <summary>
/// Error code to replace exception handling, so that the code is compatible
/// with all C++ compilers, and to use the same mechanism for C and C++.
/// Error codes should be tested using <see cref="ErrorCodeExtensions.IsFailure(ErrorCode)"/>
/// and <see cref="ErrorCodeExtensions.IsSuccess(ErrorCode)"/>
/// </summary>
public enum ErrorCode
{
/// <summary>A resource bundle lookup returned a fallback result (not an error)</summary>
USING_FALLBACK_WARNING = -128,
/// <summary>Start of information results (semantically successful)</summary>
ERROR_WARNING_START = -128,
/// <summary>A resource bundle lookup returned a result from the root locale (not an error)</summary>
USING_DEFAULT_WARNING = -127,
/// <summary>A SafeClone operation required allocating memory (informational only)</summary>
SAFECLONE_ALLOCATED_WARNING = -126,
/// <summary>ICU has to use compatibility layer to construct the service. Expect performance/memory usage degradation. Consider upgrading</summary>
STATE_OLD_WARNING = -125,
/// <summary>An output string could not be NUL-terminated because output length==destCapacity.</summary>
STRING_NOT_TERMINATED_WARNING = -124,
/// <summary>Number of levels requested in getBound is higher than the number of levels in the sort key</summary>
SORT_KEY_TOO_SHORT_WARNING = -123,
/// <summary>This converter alias can go to different converter implementations</summary>
AMBIGUOUS_ALIAS_WARNING = -122,
/// <summary>ucol_open encountered a mismatch between UCA version and collator image version, so the collator was constructed from rules. No impact to further function</summary>
DIFFERENT_UCA_VERSION = -121,
/// <summary>This must always be the last warning value to indicate the limit for UErrorCode warnings (last warning code +1)</summary>
ERROR_WARNING_LIMIT,
/// <summary>No error, no warning.</summary>
ZERO_ERROR = 0,
/// <summary>No error, no warning.</summary>
NoErrors = ZERO_ERROR,
/// <summary>Start of codes indicating failure</summary>
ILLEGAL_ARGUMENT_ERROR = 1,
/// <summary>The requested resource cannot be found</summary>
MISSING_RESOURCE_ERROR = 2,
/// <summary>Data format is not what is expected</summary>
INVALID_FORMAT_ERROR = 3,
/// <summary>The requested file cannot be found</summary>
FILE_ACCESS_ERROR = 4,
/// <summary>Indicates a bug in the library code</summary>
INTERNAL_PROGRAM_ERROR = 5,
/// <summary>Unable to parse a message (message format)</summary>
MESSAGE_PARSE_ERROR = 6,
/// <summary>Memory allocation error</summary>
MEMORY_ALLOCATION_ERROR = 7,
/// <summary>Trying to access the index that is out of bounds</summary>
INDEX_OUTOFBOUNDS_ERROR = 8,
/// <summary>Equivalent to Java ParseException</summary>
PARSE_ERROR = 9,
/// <summary>Character conversion: Unmappable input sequence. In other APIs: Invalid character.</summary>
INVALID_CHAR_FOUND = 10,
/// <summary>Character conversion: Incomplete input sequence.</summary>
TRUNCATED_CHAR_FOUND = 11,
/// <summary>Character conversion: Illegal input sequence/combination of input units.</summary>
ILLEGAL_CHAR_FOUND = 12,
/// <summary>Conversion table file found, but corrupted</summary>
INVALID_TABLE_FORMAT = 13,
/// <summary>Conversion table file not found</summary>
INVALID_TABLE_FILE = 14,
/// <summary>A result would not fit in the supplied buffer</summary>
BUFFER_OVERFLOW_ERROR = 15,
/// <summary>Requested operation not supported in current context</summary>
UNSUPPORTED_ERROR = 16,
/// <summary>an operation is requested over a resource that does not support it</summary>
RESOURCE_TYPE_MISMATCH = 17,
/// <summary>ISO-2022 illlegal escape sequence</summary>
ILLEGAL_ESCAPE_SEQUENCE = 18,
/// <summary>ISO-2022 unsupported escape sequence</summary>
UNSUPPORTED_ESCAPE_SEQUENCE = 19,
/// <summary>No space available for in-buffer expansion for Arabic shaping</summary>
NO_SPACE_AVAILABLE = 20,
/// <summary>Currently used only while setting variable top, but can be used generally</summary>
CE_NOT_FOUND_ERROR = 21,
/// <summary>User tried to set variable top to a primary that is longer than two bytes</summary>
PRIMARY_TOO_LONG_ERROR = 22,
/// <summary>ICU cannot construct a service from this state, as it is no longer supported</summary>
STATE_TOO_OLD_ERROR = 23,
/// <summary>
/// There are too many aliases in the path to the requested resource.
/// It is very possible that a circular alias definition has occured
/// </summary>
TOO_MANY_ALIASES_ERROR = 24,
/// <summary>UEnumeration out of sync with underlying collection</summary>
ENUM_OUT_OF_SYNC_ERROR = 25,
/// <summary>Unable to convert a UChar* string to char* with the invariant converter.</summary>
INVARIANT_CONVERSION_ERROR = 26,
/// <summary>Requested operation can not be completed with ICU in its current state</summary>
INVALID_STATE_ERROR = 27,
/// <summary>Collator version is not compatible with the base version</summary>
COLLATOR_VERSION_MISMATCH = 28,
/// <summary>Collator is options only and no base is specified</summary>
USELESS_COLLATOR_ERROR = 29,
/// <summary>Attempt to modify read-only or constant data.</summary>
NO_WRITE_PERMISSION = 30,
/// <summary>This must always be the last value to indicate the limit for standard errors</summary>
STANDARD_ERROR_LIMIT,
/*
* the error code range 0x10000 0x10100 are reserved for Transliterator
*/
/// <summary>Missing '$' or duplicate variable name</summary>
BAD_VARIABLE_DEFINITION = 0x10000,
/// <summary>Start of Transliterator errors</summary>
PARSE_ERROR_START = 0x10000,
/// <summary>Elements of a rule are misplaced</summary>
MALFORMED_RULE,
/// <summary>A UnicodeSet pattern is invalid</summary>
MALFORMED_SET,
/// <summary>UNUSED as of ICU 2.4</summary>
MALFORMED_SYMBOL_REFERENCE,
/// <summary>A Unicode escape pattern is invalid</summary>
MALFORMED_UNICODE_ESCAPE,
/// <summary>A variable definition is invalid</summary>
MALFORMED_VARIABLE_DEFINITION,
/// <summary>A variable reference is invalid</summary>
MALFORMED_VARIABLE_REFERENCE,
/// <summary>UNUSED as of ICU 2.4</summary>
MISMATCHED_SEGMENT_DELIMITERS,
/// <summary>A start anchor appears at an illegal position</summary>
MISPLACED_ANCHOR_START,
/// <summary>A cursor offset occurs at an illegal position</summary>
MISPLACED_CURSOR_OFFSET,
/// <summary>A quantifier appears after a segment close delimiter</summary>
MISPLACED_QUANTIFIER,
/// <summary>A rule contains no operator</summary>
MISSING_OPERATOR,
/// <summary>UNUSED as of ICU 2.4</summary>
MISSING_SEGMENT_CLOSE,
/// <summary>More than one ante context</summary>
MULTIPLE_ANTE_CONTEXTS,
/// <summary>More than one cursor</summary>
MULTIPLE_CURSORS,
/// <summary>More than one post context</summary>
MULTIPLE_POST_CONTEXTS,
/// <summary>A dangling backslash</summary>
TRAILING_BACKSLASH,
/// <summary>A segment reference does not correspond to a defined segment</summary>
UNDEFINED_SEGMENT_REFERENCE,
/// <summary>A variable reference does not correspond to a defined variable</summary>
UNDEFINED_VARIABLE,
/// <summary>A special character was not quoted or escaped</summary>
UNQUOTED_SPECIAL,
/// <summary>A closing single quote is missing</summary>
UNTERMINATED_QUOTE,
/// <summary>A rule is hidden by an earlier more general rule</summary>
RULE_MASK_ERROR,
/// <summary>A compound filter is in an invalid location</summary>
MISPLACED_COMPOUND_FILTER,
/// <summary>More than one compound filter</summary>
MULTIPLE_COMPOUND_FILTERS,
/// <summary>A "::id" rule was passed to the RuleBasedTransliterator parser</summary>
INVALID_RBT_SYNTAX,
/// <summary>UNUSED as of ICU 2.4</summary>
INVALID_PROPERTY_PATTERN,
/// <summary>A 'use' pragma is invlalid</summary>
MALFORMED_PRAGMA,
/// <summary>A closing ')' is missing</summary>
UNCLOSED_SEGMENT,
/// <summary>UNUSED as of ICU 2.4</summary>
ILLEGAL_CHAR_IN_SEGMENT,
/// <summary>Too many stand-ins generated for the given variable range</summary>
VARIABLE_RANGE_EXHAUSTED,
/// <summary>The variable range overlaps characters used in rules</summary>
VARIABLE_RANGE_OVERLAP,
/// <summary>A special character is outside its allowed context</summary>
ILLEGAL_CHARACTER,
/// <summary>Internal transliterator system error</summary>
INTERNAL_TRANSLITERATOR_ERROR,
/// <summary>A "::id" rule specifies an unknown transliterator</summary>
INVALID_ID,
/// <summary>A "&fn()" rule specifies an unknown transliterator</summary>
INVALID_FUNCTION,
/// <summary>The limit for Transliterator errors</summary>
PARSE_ERROR_LIMIT,
/*
* the error code range 0x10100 0x10200 are reserved for formatting API parsing error
*/
/// <summary>Syntax error in format pattern</summary>
UNEXPECTED_TOKEN = 0x10100,
/// <summary>Start of format library errors</summary>
FMT_PARSE_ERROR_START = 0x10100,
/// <summary>More than one decimal separator in number pattern</summary>
MULTIPLE_DECIMAL_SEPARATORS,
/// <summary>More than one exponent symbol in number pattern</summary>
MULTIPLE_EXPONENTIAL_SYMBOLS,
/// <summary>Grouping symbol in exponent pattern</summary>
MALFORMED_EXPONENTIAL_PATTERN,
/// <summary>More than one percent symbol in number pattern</summary>
MULTIPLE_PERCENT_SYMBOLS,
/// <summary>More than one permill symbol in number pattern</summary>
MULTIPLE_PERMILL_SYMBOLS,
/// <summary>More than one pad symbol in number pattern</summary>
MULTIPLE_PAD_SPECIFIERS,
/// <summary>Syntax error in format pattern</summary>
PATTERN_SYNTAX_ERROR,
/// <summary>Pad symbol misplaced in number pattern</summary>
ILLEGAL_PAD_POSITION,
/// <summary>Braces do not match in message pattern</summary>
UNMATCHED_BRACES,
/// <summary>UNUSED as of ICU 2.4</summary>
UNSUPPORTED_PROPERTY,
/// <summary>UNUSED as of ICU 2.4</summary>
UNSUPPORTED_ATTRIBUTE,
/// <summary>Argument name and argument index mismatch in MessageFormat functions.</summary>
ARGUMENT_TYPE_MISMATCH,
/// <summary>Duplicate keyword in PluralFormat.</summary>
DUPLICATE_KEYWORD,
/// <summary>Undefined Plural keyword.</summary>
UNDEFINED_KEYWORD,
/// <summary>Missing DEFAULT rule in plural rules.</summary>
DEFAULT_KEYWORD_MISSING,
/// <summary>The limit for format library errors</summary>
FMT_PARSE_ERROR_LIMIT,
/*
* the error code range 0x10200 0x102ff are reserved for Break Iterator related error
*/
/// <summary>An internal error (bug) was detected.</summary>
BRK_INTERNAL_ERROR = 0x10200,
/// <summary>Start of codes indicating Break Iterator failures</summary>
BRK_ERROR_START = 0x10200,
/// <summary>Hex digits expected as part of a escaped char in a rule.</summary>
BRK_HEX_DIGITS_EXPECTED,
/// <summary>Missing ';' at the end of a RBBI rule.</summary>
BRK_SEMICOLON_EXPECTED,
/// <summary>Syntax error in RBBI rule.</summary>
BRK_RULE_SYNTAX,
/// <summary>UnicodeSet witing an RBBI rule missing a closing ']'.</summary>
BRK_UNCLOSED_SET,
/// <summary>Syntax error in RBBI rule assignment statement.</summary>
BRK_ASSIGN_ERROR,
/// <summary>RBBI rule $Variable redefined.</summary>
BRK_VARIABLE_REDFINITION,
/// <summary>Mis-matched parentheses in an RBBI rule.</summary>
BRK_MISMATCHED_PAREN,
/// <summary>Missing closing quote in an RBBI rule.</summary>
BRK_NEW_LINE_IN_QUOTED_STRING,
/// <summary>Use of an undefined $Variable in an RBBI rule.</summary>
BRK_UNDEFINED_VARIABLE,
/// <summary>Initialization failure. Probable missing ICU Data.</summary>
BRK_INIT_ERROR,
/// <summary>Rule contains an empty Unicode Set.</summary>
BRK_RULE_EMPTY_SET,
/// <summary>!!option in RBBI rules not recognized.</summary>
BRK_UNRECOGNIZED_OPTION,
/// <summary>The {nnn} tag on a rule is mal formed</summary>
BRK_MALFORMED_RULE_TAG,
/// <summary>This must always be the last value to indicate the limit for Break Iterator failures</summary>
BRK_ERROR_LIMIT,
/*
* The error codes in the range 0x10300-0x103ff are reserved for regular expression related errrs
*/
/// <summary>An internal error (bug) was detected.</summary>
REGEX_INTERNAL_ERROR = 0x10300,
/// <summary>Start of codes indicating Regexp failures</summary>
REGEX_ERROR_START = 0x10300,
/// <summary>Syntax error in regexp pattern.</summary>
REGEX_RULE_SYNTAX,
/// <summary>RegexMatcher in invalid state for requested operation</summary>
REGEX_INVALID_STATE,
/// <summary>Unrecognized backslash escape sequence in pattern</summary>
REGEX_BAD_ESCAPE_SEQUENCE,
/// <summary>Incorrect Unicode property</summary>
REGEX_PROPERTY_SYNTAX,
/// <summary>Use of regexp feature that is not yet implemented.</summary>
REGEX_UNIMPLEMENTED,
/// <summary>Incorrectly nested parentheses in regexp pattern.</summary>
REGEX_MISMATCHED_PAREN,
/// <summary>Decimal number is too large.</summary>
REGEX_NUMBER_TOO_BIG,
/// <summary>Error in {min,max} interval</summary>
REGEX_BAD_INTERVAL,
/// <summary>In {min,max}, max is less than min.</summary>
REGEX_MAX_LT_MIN,
/// <summary>Back-reference to a non-existent capture group.</summary>
REGEX_INVALID_BACK_REF,
/// <summary>Invalid value for match mode flags.</summary>
REGEX_INVALID_FLAG,
/// <summary>Look-Behind pattern matches must have a bounded maximum length.</summary>
REGEX_LOOK_BEHIND_LIMIT,
/// <summary>Regexps cannot have UnicodeSets containing strings.</summary>
REGEX_SET_CONTAINS_STRING,
/// <summary>Octal character constants must be <= 0377.</summary>
REGEX_OCTAL_TOO_BIG,
/// <summary>Missing closing bracket on a bracket expression.</summary>
REGEX_MISSING_CLOSE_BRACKET,
/// <summary>In a character range [x-y], x is greater than y.</summary>
REGEX_INVALID_RANGE,
/// <summary>Regular expression backtrack stack overflow.</summary>
REGEX_STACK_OVERFLOW,
/// <summary>Maximum allowed match time exceeded.</summary>
REGEX_TIME_OUT,
/// <summary>Matching operation aborted by user callback fn.</summary>
REGEX_STOPPED_BY_CALLER,
/// <summary>This must always be the last value to indicate the limit for regexp errors</summary>
REGEX_ERROR_LIMIT,
/*
* The error code in the range 0x10400-0x104ff are reserved for IDNA related error codes
*/
/// <summary></summary>
IDNA_PROHIBITED_ERROR = 0x10400,
/// <summary>Start of codes indicating IDNA failures</summary>
IDNA_ERROR_START = 0x10400,
/// <summary></summary>
IDNA_UNASSIGNED_ERROR,
/// <summary></summary>
IDNA_CHECK_BIDI_ERROR,
/// <summary></summary>
IDNA_STD3_ASCII_RULES_ERROR,
/// <summary></summary>
IDNA_ACE_PREFIX_ERROR,
/// <summary></summary>
IDNA_VERIFICATION_ERROR,
/// <summary></summary>
IDNA_LABEL_TOO_LONG_ERROR,
/// <summary></summary>
IDNA_ZERO_LENGTH_LABEL_ERROR,
/// <summary></summary>
IDNA_DOMAIN_NAME_TOO_LONG_ERROR,
/// <summary>This must always be the last value to indicate the limit for IDNA errors</summary>
IDNA_ERROR_LIMIT,
/*
* Aliases for StringPrep
*/
/// <summary></summary>
STRINGPREP_PROHIBITED_ERROR = IDNA_PROHIBITED_ERROR,
/// <summary></summary>
STRINGPREP_UNASSIGNED_ERROR = IDNA_UNASSIGNED_ERROR,
/// <summary></summary>
STRINGPREP_CHECK_BIDI_ERROR = IDNA_CHECK_BIDI_ERROR,
/// <summary>This must always be the last value to indicate the limit for UErrorCode (last error code +1)</summary>
ERROR_LIMIT = IDNA_ERROR_LIMIT
}
internal static class ErrorCodeExtensions
{
/// <summary>
/// Determines whether the operation was successful or not.
/// http://icu-project.org/apiref/icu4c/utypes_8h_source.html#l00709
/// </summary>
public static bool IsSuccess(this ErrorCode errorCode)
{
return errorCode <= ErrorCode.ZERO_ERROR;
}
/// <summary>
/// Determines whether the operation resulted in an error.
/// http://icu-project.org/apiref/icu4c/utypes_8h_source.html#l00714
/// </summary>
public static bool IsFailure(this ErrorCode errorCode)
{
return errorCode > ErrorCode.ZERO_ERROR;
}
}
internal class ExceptionFromErrorCode
{
public static void ThrowIfError(ErrorCode e)
{
ThrowIfError(e, string.Empty, false);
}
public static void ThrowIfErrorOrWarning(ErrorCode e)
{
ThrowIfError(e, string.Empty, true);
}
public static void ThrowIfError(ErrorCode e, string extraInfo)
{
ThrowIfError(e, extraInfo, false);
}
public static void ThrowIfErrorOrWarning(ErrorCode e, string extraInfo)
{
ThrowIfError(e, extraInfo, true);
}
private static void ThrowIfError(ErrorCode e, string extraInfo, bool throwOnWarnings)
{
switch (e)
{
case ErrorCode.ZERO_ERROR: // the only case to not throw!
break;
case ErrorCode.USING_FALLBACK_WARNING:
if (throwOnWarnings)
{
throw new WarningException("Warning: A resource bundle lookup returned a fallback result " + extraInfo);
}
break;
case ErrorCode.USING_DEFAULT_WARNING:
if (throwOnWarnings)
{
throw new WarningException("Warning: A resource bundle lookup returned a result from the root locale " + extraInfo);
}
break;
case ErrorCode.SAFECLONE_ALLOCATED_WARNING:
if (throwOnWarnings)
{
throw new WarningException("Notice: A SafeClone operation required allocating memory " + extraInfo);
}
break;
case ErrorCode.STATE_OLD_WARNING:
throw new WarningException("ICU has to use compatibility layer to construct the service. Expect performance/memory usage degradation. Consider upgrading " + extraInfo);
case ErrorCode.STRING_NOT_TERMINATED_WARNING:
throw new WarningException("An output string could not be NUL-terminated because output length==destCapacity. " + extraInfo);
case ErrorCode.SORT_KEY_TOO_SHORT_WARNING:
throw new WarningException("Number of levels requested in getBound is higher than the number of levels in the sort key " + extraInfo);
case ErrorCode.AMBIGUOUS_ALIAS_WARNING:
throw new WarningException("This converter alias can go to different converter implementations " + extraInfo);
case ErrorCode.DIFFERENT_UCA_VERSION:
if (throwOnWarnings)
{
throw new WarningException(
"Warning: ucol_open encountered a mismatch between UCA version and collator image version, so the collator was constructed from rules. No impact to further function " + extraInfo);
}
break;
case ErrorCode.ILLEGAL_ARGUMENT_ERROR:
throw new ArgumentException(extraInfo);
case ErrorCode.MISSING_RESOURCE_ERROR:
throw new ApplicationException("The requested resource cannot be found " + extraInfo);
case ErrorCode.INVALID_FORMAT_ERROR:
throw new ApplicationException("Data format is not what is expected " + extraInfo);
case ErrorCode.FILE_ACCESS_ERROR:
throw new FileNotFoundException("The requested file cannot be found " + extraInfo);
case ErrorCode.INTERNAL_PROGRAM_ERROR:
throw new InvalidOperationException("Indicates a bug in the library code " + extraInfo);
case ErrorCode.MESSAGE_PARSE_ERROR:
throw new ApplicationException("Unable to parse a message (message format) " + extraInfo);
case ErrorCode.MEMORY_ALLOCATION_ERROR:
throw new OutOfMemoryException(extraInfo);
case ErrorCode.INDEX_OUTOFBOUNDS_ERROR:
throw new IndexOutOfRangeException(extraInfo);
case ErrorCode.PARSE_ERROR:
throw new SyntaxErrorException("Parse Error " + extraInfo);
case ErrorCode.INVALID_CHAR_FOUND:
throw new ArgumentException("Character conversion: Unmappable input sequence. In other APIs: Invalid character. " + extraInfo);
case ErrorCode.TRUNCATED_CHAR_FOUND:
throw new ArgumentException("Character conversion: Incomplete input sequence. " + extraInfo);
case ErrorCode.ILLEGAL_CHAR_FOUND:
throw new ArgumentException("Character conversion: Illegal input sequence/combination of input units. " + extraInfo);
case ErrorCode.INVALID_TABLE_FORMAT:
throw new InvalidDataException("Conversion table file found, but corrupted " + extraInfo);
case ErrorCode.INVALID_TABLE_FILE:
throw new FileNotFoundException("Conversion table file not found " + extraInfo);
case ErrorCode.BUFFER_OVERFLOW_ERROR:
throw new InternalBufferOverflowException("A result would not fit in the supplied buffer " + extraInfo);
case ErrorCode.UNSUPPORTED_ERROR:
throw new InvalidOperationException("Requested operation not supported in current context " + extraInfo);
case ErrorCode.RESOURCE_TYPE_MISMATCH:
throw new InvalidOperationException("an operation is requested over a resource that does not support it " + extraInfo);
case ErrorCode.ILLEGAL_ESCAPE_SEQUENCE:
throw new ArgumentException("ISO-2022 illlegal escape sequence " + extraInfo);
case ErrorCode.UNSUPPORTED_ESCAPE_SEQUENCE:
throw new ArgumentException("ISO-2022 unsupported escape sequence " + extraInfo);
case ErrorCode.NO_SPACE_AVAILABLE:
throw new ArgumentException("No space available for in-buffer expansion for Arabic shaping " + extraInfo);
case ErrorCode.CE_NOT_FOUND_ERROR:
throw new ArgumentException("Collation Element not found " + extraInfo);
case ErrorCode.PRIMARY_TOO_LONG_ERROR:
throw new ArgumentException("User tried to set variable top to a primary that is longer than two bytes " + extraInfo);
case ErrorCode.STATE_TOO_OLD_ERROR:
throw new NotSupportedException("ICU cannot construct a service from this state, as it is no longer supported " + extraInfo);
case ErrorCode.TOO_MANY_ALIASES_ERROR:
throw new ApplicationException("There are too many aliases in the path to the requested resource.\nIt is very possible that a circular alias definition has occured " + extraInfo);
case ErrorCode.ENUM_OUT_OF_SYNC_ERROR:
throw new InvalidOperationException("Enumeration out of sync with underlying collection " + extraInfo);
case ErrorCode.INVARIANT_CONVERSION_ERROR:
throw new ApplicationException("Unable to convert a UChar* string to char* with the invariant converter " + extraInfo);
case ErrorCode.INVALID_STATE_ERROR:
throw new InvalidOperationException("Requested operation can not be completed with ICU in its current state " + extraInfo);
case ErrorCode.COLLATOR_VERSION_MISMATCH:
throw new InvalidOperationException("Collator version is not compatible with the base version " + extraInfo);
case ErrorCode.USELESS_COLLATOR_ERROR:
throw new ApplicationException("Collator is options only and no base is specified " + extraInfo);
case ErrorCode.NO_WRITE_PERMISSION:
throw new ApplicationException("Attempt to modify read-only or constant data. " + extraInfo);
case ErrorCode.BAD_VARIABLE_DEFINITION:
throw new ApplicationException("Transliterator Parse Error: Missing '$' or duplicate variable name " + extraInfo);
case ErrorCode.MALFORMED_RULE:
throw new ApplicationException("Transliterator Parse Error: Elements of a rule are misplaced " + extraInfo);
case ErrorCode.MALFORMED_SET:
throw new ApplicationException("Transliterator Parse Error: A UnicodeSet pattern is invalid " + extraInfo);
case ErrorCode.MALFORMED_UNICODE_ESCAPE:
throw new ApplicationException("Transliterator Parse Error: A Unicode escape pattern is invalid " + extraInfo);
case ErrorCode.MALFORMED_VARIABLE_DEFINITION:
throw new ApplicationException("Transliterator Parse Error: A variable definition is invalid " + extraInfo);
case ErrorCode.MALFORMED_VARIABLE_REFERENCE:
throw new ApplicationException("Transliterator Parse Error: A variable reference is invalid " + extraInfo);
case ErrorCode.MISPLACED_ANCHOR_START:
throw new ApplicationException("Transliterator Parse Error: A start anchor appears at an illegal position " + extraInfo);
case ErrorCode.MISPLACED_CURSOR_OFFSET:
throw new ApplicationException("Transliterator Parse Error: A cursor offset occurs at an illegal position " + extraInfo);
case ErrorCode.MISPLACED_QUANTIFIER:
throw new ApplicationException("Transliterator Parse Error: A quantifier appears after a segment close delimiter " + extraInfo);
case ErrorCode.MISSING_OPERATOR:
throw new ApplicationException("Transliterator Parse Error: A rule contains no operator " + extraInfo);
case ErrorCode.MULTIPLE_ANTE_CONTEXTS:
throw new ApplicationException("Transliterator Parse Error: More than one ante context " + extraInfo);
case ErrorCode.MULTIPLE_CURSORS:
throw new ApplicationException("Transliterator Parse Error: More than one cursor " + extraInfo);
case ErrorCode.MULTIPLE_POST_CONTEXTS:
throw new ApplicationException("Transliterator Parse Error: More than one post context " + extraInfo);
case ErrorCode.TRAILING_BACKSLASH:
throw new ApplicationException("Transliterator Parse Error: A dangling backslash " + extraInfo);
case ErrorCode.UNDEFINED_SEGMENT_REFERENCE:
throw new ApplicationException("Transliterator Parse Error: A segment reference does not correspond to a defined segment " + extraInfo);
case ErrorCode.UNDEFINED_VARIABLE:
throw new ApplicationException("Transliterator Parse Error: A variable reference does not correspond to a defined variable " + extraInfo);
case ErrorCode.UNQUOTED_SPECIAL:
throw new ApplicationException("Transliterator Parse Error: A special character was not quoted or escaped " + extraInfo);
case ErrorCode.UNTERMINATED_QUOTE:
throw new ApplicationException("Transliterator Parse Error: A closing single quote is missing " + extraInfo);
case ErrorCode.RULE_MASK_ERROR:
throw new ApplicationException("Transliterator Parse Error: A rule is hidden by an earlier more general rule " + extraInfo);
case ErrorCode.MISPLACED_COMPOUND_FILTER:
throw new ApplicationException("Transliterator Parse Error: A compound filter is in an invalid location " + extraInfo);
case ErrorCode.MULTIPLE_COMPOUND_FILTERS:
throw new ApplicationException("Transliterator Parse Error: More than one compound filter " + extraInfo);
case ErrorCode.INVALID_RBT_SYNTAX:
throw new ApplicationException("Transliterator Parse Error: A '::id' rule was passed to the RuleBasedTransliterator parser " + extraInfo);
case ErrorCode.MALFORMED_PRAGMA:
throw new ApplicationException("Transliterator Parse Error: A 'use' pragma is invlalid " + extraInfo);
case ErrorCode.UNCLOSED_SEGMENT:
throw new ApplicationException("Transliterator Parse Error: A closing ')' is missing " + extraInfo);
case ErrorCode.VARIABLE_RANGE_EXHAUSTED:
throw new ApplicationException("Transliterator Parse Error: Too many stand-ins generated for the given variable range " + extraInfo);
case ErrorCode.VARIABLE_RANGE_OVERLAP:
throw new ApplicationException("Transliterator Parse Error: The variable range overlaps characters used in rules " + extraInfo);
case ErrorCode.ILLEGAL_CHARACTER:
throw new ApplicationException("Transliterator Parse Error: A special character is outside its allowed context " + extraInfo);
case ErrorCode.INTERNAL_TRANSLITERATOR_ERROR:
throw new ApplicationException("Transliterator Parse Error: Internal transliterator system error " + extraInfo);
case ErrorCode.INVALID_ID:
throw new ApplicationException("Transliterator Parse Error: A '::id' rule specifies an unknown transliterator " + extraInfo);
case ErrorCode.INVALID_FUNCTION:
throw new ApplicationException("Transliterator Parse Error: A '&fn()' rule specifies an unknown transliterator " + extraInfo);
case ErrorCode.UNEXPECTED_TOKEN:
throw new SyntaxErrorException("Format Parse Error: Unexpected token in format pattern " + extraInfo);
case ErrorCode.MULTIPLE_DECIMAL_SEPARATORS:
throw new SyntaxErrorException("Format Parse Error: More than one decimal separator in number pattern " + extraInfo);
case ErrorCode.MULTIPLE_EXPONENTIAL_SYMBOLS:
throw new SyntaxErrorException("Format Parse Error: More than one exponent symbol in number pattern " + extraInfo);
case ErrorCode.MALFORMED_EXPONENTIAL_PATTERN:
throw new SyntaxErrorException("Format Parse Error: Grouping symbol in exponent pattern " + extraInfo);
case ErrorCode.MULTIPLE_PERCENT_SYMBOLS:
throw new SyntaxErrorException("Format Parse Error: More than one percent symbol in number pattern " + extraInfo);
case ErrorCode.MULTIPLE_PERMILL_SYMBOLS:
throw new SyntaxErrorException("Format Parse Error: More than one permill symbol in number pattern " + extraInfo);
case ErrorCode.MULTIPLE_PAD_SPECIFIERS:
throw new SyntaxErrorException("Format Parse Error: More than one pad symbol in number pattern " + extraInfo);
case ErrorCode.PATTERN_SYNTAX_ERROR:
throw new SyntaxErrorException("Format Parse Error: Syntax error in format pattern " + extraInfo);
case ErrorCode.ILLEGAL_PAD_POSITION:
throw new SyntaxErrorException("Format Parse Error: Pad symbol misplaced in number pattern " + extraInfo);
case ErrorCode.UNMATCHED_BRACES:
throw new SyntaxErrorException("Format Parse Error: Braces do not match in message pattern " + extraInfo);
case ErrorCode.ARGUMENT_TYPE_MISMATCH:
throw new SyntaxErrorException("Format Parse Error: Argument name and argument index mismatch in MessageFormat functions. " + extraInfo);
case ErrorCode.DUPLICATE_KEYWORD:
throw new SyntaxErrorException("Format Parse Error: Duplicate keyword in PluralFormat. " + extraInfo);
case ErrorCode.UNDEFINED_KEYWORD:
throw new SyntaxErrorException("Format Parse Error: Undefined Plural keyword. " + extraInfo);
case ErrorCode.DEFAULT_KEYWORD_MISSING:
throw new SyntaxErrorException("Format Parse Error: Missing DEFAULT rule in plural rules. " + extraInfo);
case ErrorCode.BRK_INTERNAL_ERROR:
throw new ApplicationException("Break Error: An internal error (bug) was detected. " + extraInfo);
case ErrorCode.BRK_HEX_DIGITS_EXPECTED:
throw new ApplicationException("Break Error: Hex digits expected as part of a escaped char in a rule. " + extraInfo);
case ErrorCode.BRK_SEMICOLON_EXPECTED:
throw new ApplicationException("Break Error: Missing ';' at the end of a RBBI rule. " + extraInfo);
case ErrorCode.BRK_RULE_SYNTAX:
throw new ApplicationException("Break Error: Syntax error in RBBI rule. " + extraInfo);
case ErrorCode.BRK_UNCLOSED_SET:
throw new ApplicationException("Break Error: UnicodeSet witing an RBBI rule missing a closing ']'. " + extraInfo);
case ErrorCode.BRK_ASSIGN_ERROR:
throw new ApplicationException("Break Error: Syntax error in RBBI rule assignment statement. " + extraInfo);
case ErrorCode.BRK_VARIABLE_REDFINITION:
throw new ApplicationException("Break Error: RBBI rule $Variable redefined. " + extraInfo);
case ErrorCode.BRK_MISMATCHED_PAREN:
throw new ApplicationException("Break Error: Mis-matched parentheses in an RBBI rule. " + extraInfo);
case ErrorCode.BRK_NEW_LINE_IN_QUOTED_STRING:
throw new ApplicationException("Break Error: Missing closing quote in an RBBI rule. " + extraInfo);
case ErrorCode.BRK_UNDEFINED_VARIABLE:
throw new ApplicationException("Break Error: Use of an undefined $Variable in an RBBI rule. " + extraInfo);
case ErrorCode.BRK_INIT_ERROR:
throw new ApplicationException("Break Error: Initialization failure. Probable missing ICU Data. " + extraInfo);
case ErrorCode.BRK_RULE_EMPTY_SET:
throw new ApplicationException("Break Error: Rule contains an empty Unicode Set. " + extraInfo);
case ErrorCode.BRK_UNRECOGNIZED_OPTION:
throw new ApplicationException("Break Error: !!option in RBBI rules not recognized. " + extraInfo);
case ErrorCode.BRK_MALFORMED_RULE_TAG:
throw new ApplicationException("Break Error: The {nnn} tag on a rule is mal formed " + extraInfo);
case ErrorCode.BRK_ERROR_LIMIT:
throw new ApplicationException("Break Error: This must always be the last value to indicate the limit for Break Iterator failures " + extraInfo);
case ErrorCode.REGEX_INTERNAL_ERROR:
throw new ApplicationException("RegEx Error: An internal error (bug) was detected. " + extraInfo);
case ErrorCode.REGEX_RULE_SYNTAX:
throw new ApplicationException("RegEx Error: Syntax error in regexp pattern. " + extraInfo);
case ErrorCode.REGEX_INVALID_STATE:
throw new ApplicationException("RegEx Error: RegexMatcher in invalid state for requested operation " + extraInfo);
case ErrorCode.REGEX_BAD_ESCAPE_SEQUENCE:
throw new ApplicationException("RegEx Error: Unrecognized backslash escape sequence in pattern " + extraInfo);
case ErrorCode.REGEX_PROPERTY_SYNTAX:
throw new ApplicationException("RegEx Error: Incorrect Unicode property " + extraInfo);
case ErrorCode.REGEX_UNIMPLEMENTED:
throw new ApplicationException("RegEx Error: Use of regexp feature that is not yet implemented. " + extraInfo);
case ErrorCode.REGEX_MISMATCHED_PAREN:
throw new ApplicationException("RegEx Error: Incorrectly nested parentheses in regexp pattern. " + extraInfo);
case ErrorCode.REGEX_NUMBER_TOO_BIG:
throw new ApplicationException("RegEx Error: Decimal number is too large. " + extraInfo);
case ErrorCode.REGEX_BAD_INTERVAL:
throw new ApplicationException("RegEx Error: Error in {min,max} interval " + extraInfo);
case ErrorCode.REGEX_MAX_LT_MIN:
throw new ApplicationException("RegEx Error: In {min,max}, max is less than min. " + extraInfo);
case ErrorCode.REGEX_INVALID_BACK_REF:
throw new ApplicationException("RegEx Error: Back-reference to a non-existent capture group. " + extraInfo);
case ErrorCode.REGEX_INVALID_FLAG:
throw new ApplicationException("RegEx Error: Invalid value for match mode flags. " + extraInfo);
case ErrorCode.REGEX_LOOK_BEHIND_LIMIT:
throw new ApplicationException("RegEx Error: Look-Behind pattern matches must have a bounded maximum length. " + extraInfo);
case ErrorCode.REGEX_SET_CONTAINS_STRING:
throw new ApplicationException("RegEx Error: Regexps cannot have UnicodeSets containing strings. " + extraInfo);
case ErrorCode.REGEX_OCTAL_TOO_BIG:
throw new ApplicationException("Regex Error: Octal character constants must be <= 0377. " + extraInfo);
case ErrorCode.REGEX_MISSING_CLOSE_BRACKET:
throw new ApplicationException("Regex Error: Missing closing bracket on a bracket expression. " + extraInfo);
case ErrorCode.REGEX_INVALID_RANGE:
throw new ApplicationException("Regex Error: In a character range [x-y], x is greater than y. " + extraInfo);
case ErrorCode.REGEX_STACK_OVERFLOW:
throw new ApplicationException("Regex Error: Regular expression backtrack stack overflow. " + extraInfo);
case ErrorCode.REGEX_TIME_OUT:
throw new ApplicationException("Regex Error: Maximum allowed match time exceeded. " + extraInfo);
case ErrorCode.REGEX_STOPPED_BY_CALLER:
throw new ApplicationException("Regex Error: Matching operation aborted by user callback fn. " + extraInfo);
case ErrorCode.REGEX_ERROR_LIMIT:
throw new ApplicationException("RegEx Error: " + extraInfo);
case ErrorCode.IDNA_PROHIBITED_ERROR:
throw new ApplicationException("IDNA Error: Prohibited " + extraInfo);
case ErrorCode.IDNA_UNASSIGNED_ERROR:
throw new ApplicationException("IDNA Error: Unassigned " + extraInfo);
case ErrorCode.IDNA_CHECK_BIDI_ERROR:
throw new ApplicationException("IDNA Error: Check Bidi " + extraInfo);
case ErrorCode.IDNA_STD3_ASCII_RULES_ERROR:
throw new ApplicationException("IDNA Error: Std3 Ascii Rules Error " + extraInfo);
case ErrorCode.IDNA_ACE_PREFIX_ERROR:
throw new ApplicationException("IDNA Error: Ace Prefix Error " + extraInfo);
case ErrorCode.IDNA_VERIFICATION_ERROR:
throw new ApplicationException("IDNA Error: Verification Error " + extraInfo);
case ErrorCode.IDNA_LABEL_TOO_LONG_ERROR:
throw new ApplicationException("IDNA Error: Label too long " + extraInfo);
case ErrorCode.IDNA_ZERO_LENGTH_LABEL_ERROR:
throw new ApplicationException("IDNA Error: Zero length label " + extraInfo);
case ErrorCode.IDNA_DOMAIN_NAME_TOO_LONG_ERROR:
throw new ApplicationException("IDNA Error: Domain name too long " + extraInfo);
default:
throw new InvalidEnumArgumentException("Missing implementation for ErrorCode " + e);
}
}
}
}
| |
/*
* Copyright (c) 2007-2008, openmetaverse.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.
* - Neither the name of the openmetaverse.org 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 System.Threading;
using System.Text;
using OpenMetaverse.StructuredData;
using OpenMetaverse.Capabilities;
namespace OpenMetaverse
{
public class RegistrationApi
{
private struct UserInfo
{
public string FirstName;
public string LastName;
public string Password;
}
private struct RegistrationCaps
{
public Uri CreateUser;
public Uri CheckName;
public Uri GetLastNames;
public Uri GetErrorCodes;
}
public struct LastName
{
public int ID;
public string Name;
}
/// <summary>
/// See https://secure-web6.secondlife.com/developers/third_party_reg/#service_create_user or
/// https://wiki.secondlife.com/wiki/RegAPIDoc for description
/// </summary>
public class CreateUserParam
{
public string FirstName;
public LastName LastName;
public string Email;
public string Password;
public DateTime Birthdate;
// optional:
public Nullable<int> LimitedToEstate;
public string StartRegionName;
public Nullable<Vector3> StartLocation;
public Nullable<Vector3> StartLookAt;
}
private UserInfo _userInfo;
private RegistrationCaps _caps;
private int _initializing;
private List<LastName> _lastNames = new List<LastName>();
private Dictionary<int, string> _errors = new Dictionary<int, string>();
public bool Initializing
{
get
{
System.Diagnostics.Debug.Assert(_initializing <= 0);
return (_initializing < 0);
}
}
public List<LastName> LastNames
{
get
{
lock (_lastNames)
{
if (_lastNames.Count <= 0)
GatherLastNames();
}
return _lastNames;
}
}
public RegistrationApi(string firstName, string lastName, string password)
{
_initializing = -2;
_userInfo = new UserInfo();
_userInfo.FirstName = firstName;
_userInfo.LastName = lastName;
_userInfo.Password = password;
GatherCaps();
}
public void WaitForInitialization()
{
while (Initializing)
System.Threading.Thread.Sleep(10);
}
public Uri RegistrationApiCaps
{
get { return new Uri("https://cap.secondlife.com/get_reg_capabilities"); }
}
private void GatherCaps()
{
// build post data
byte[] postData = Encoding.ASCII.GetBytes(
String.Format("first_name={0}&last_name={1}&password={2}", _userInfo.FirstName, _userInfo.LastName,
_userInfo.Password));
CapsClient request = new CapsClient(RegistrationApiCaps);
request.OnComplete += new CapsClient.CompleteCallback(GatherCapsResponse);
request.StartRequest(postData);
}
private void GatherCapsResponse(CapsClient client, LLSD response, Exception error)
{
if (response is LLSDMap)
{
LLSDMap respTable = (LLSDMap)response;
// parse
_caps = new RegistrationCaps();
_caps.CreateUser = respTable["create_user"].AsUri();
_caps.CheckName = respTable["check_name"].AsUri();
_caps.GetLastNames = respTable["get_last_names"].AsUri();
_caps.GetErrorCodes = respTable["get_error_codes"].AsUri();
// finalize
_initializing++;
GatherErrorMessages();
}
}
private void GatherErrorMessages()
{
if (_caps.GetErrorCodes == null)
throw new InvalidOperationException("access denied"); // this should work even for not-approved users
CapsClient request = new CapsClient(_caps.GetErrorCodes);
request.OnComplete += new CapsClient.CompleteCallback(GatherErrorMessagesResponse);
request.StartRequest();
}
private void GatherErrorMessagesResponse(CapsClient client, LLSD response, Exception error)
{
if (response is LLSDMap)
{
// parse
//FIXME: wtf?
//foreach (KeyValuePair<string, object> error in (Dictionary<string, object>)response)
//{
//StringBuilder sb = new StringBuilder();
//sb.Append(error[1]);
//sb.Append(" (");
//sb.Append(error[0]);
//sb.Append("): ");
//sb.Append(error[2]);
//_errors.Add((int)error[0], sb.ToString());
//}
// finalize
_initializing++;
}
}
public void GatherLastNames()
{
if (Initializing)
throw new InvalidOperationException("still initializing");
if (_caps.GetLastNames == null)
throw new InvalidOperationException("access denied: only approved developers have access to the registration api");
CapsClient request = new CapsClient(_caps.GetLastNames);
request.OnComplete += new CapsClient.CompleteCallback(GatherLastNamesResponse);
request.StartRequest();
// FIXME: Block
}
private void GatherLastNamesResponse(CapsClient client, LLSD response, Exception error)
{
if (response is LLSDMap)
{
//LLSDMap respTable = (LLSDMap)response;
//FIXME:
//_lastNames = new List<LastName>(respTable.Count);
//for (Dictionary<string, object>.Enumerator it = respTable.GetEnumerator(); it.MoveNext(); )
//{
// LastName ln = new LastName();
// ln.ID = int.Parse(it.Current.Key.ToString());
// ln.Name = it.Current.Value.ToString();
// _lastNames.Add(ln);
//}
//_lastNames.Sort(new Comparison<LastName>(delegate(LastName a, LastName b) { return a.Name.CompareTo(b.Name); }));
}
}
public bool CheckName(string firstName, LastName lastName)
{
if (Initializing)
throw new InvalidOperationException("still initializing");
if (_caps.CheckName == null)
throw new InvalidOperationException("access denied; only approved developers have access to the registration api");
// Create the POST data
LLSDMap query = new LLSDMap();
query.Add("username", LLSD.FromString(firstName));
query.Add("last_name_id", LLSD.FromInteger(lastName.ID));
//byte[] postData = LLSDParser.SerializeXmlBytes(query);
CapsClient request = new CapsClient(_caps.CheckName);
request.OnComplete += new CapsClient.CompleteCallback(CheckNameResponse);
request.StartRequest();
// FIXME:
return false;
}
private void CheckNameResponse(CapsClient client, LLSD response, Exception error)
{
if (response.Type == LLSDType.Boolean)
{
// FIXME:
//(bool)response;
}
else
{
// FIXME:
}
}
/// <summary>
/// Returns the new user ID or throws an exception containing the error code
/// The error codes can be found here: https://wiki.secondlife.com/wiki/RegAPIError
/// </summary>
/// <param name="user">New user account to create</param>
/// <returns>The UUID of the new user account</returns>
public UUID CreateUser(CreateUserParam user)
{
if (Initializing)
throw new InvalidOperationException("still initializing");
if (_caps.CreateUser == null)
throw new InvalidOperationException("access denied; only approved developers have access to the registration api");
// Create the POST data
LLSDMap query = new LLSDMap();
query.Add("username", LLSD.FromString(user.FirstName));
query.Add("last_name_id", LLSD.FromInteger(user.LastName.ID));
query.Add("email", LLSD.FromString(user.Email));
query.Add("password", LLSD.FromString(user.Password));
query.Add("dob", LLSD.FromString(user.Birthdate.ToString("yyyy-MM-dd")));
if (user.LimitedToEstate != null)
query.Add("limited_to_estate", LLSD.FromInteger(user.LimitedToEstate.Value));
if (!string.IsNullOrEmpty(user.StartRegionName))
query.Add("start_region_name", LLSD.FromInteger(user.LimitedToEstate.Value));
if (user.StartLocation != null)
{
query.Add("start_local_x", LLSD.FromReal(user.StartLocation.Value.X));
query.Add("start_local_y", LLSD.FromReal(user.StartLocation.Value.Y));
query.Add("start_local_z", LLSD.FromReal(user.StartLocation.Value.Z));
}
if (user.StartLookAt != null)
{
query.Add("start_look_at_x", LLSD.FromReal(user.StartLookAt.Value.X));
query.Add("start_look_at_y", LLSD.FromReal(user.StartLookAt.Value.Y));
query.Add("start_look_at_z", LLSD.FromReal(user.StartLookAt.Value.Z));
}
//byte[] postData = LLSDParser.SerializeXmlBytes(query);
// Make the request
CapsClient request = new CapsClient(_caps.CreateUser);
request.OnComplete += new CapsClient.CompleteCallback(CreateUserResponse);
request.StartRequest();
// FIXME: Block
return UUID.Zero;
}
private void CreateUserResponse(CapsClient client, LLSD response, Exception error)
{
if (response is LLSDMap)
{
// everything is okay
// FIXME:
//return new UUID(((Dictionary<string, object>)response)["agent_id"].ToString());
}
else
{
// an error happened
LLSDArray al = (LLSDArray)response;
StringBuilder sb = new StringBuilder();
foreach (LLSD ec in al)
{
if (sb.Length > 0)
sb.Append("; ");
sb.Append(_errors[ec.AsInteger()]);
}
// FIXME:
//throw new Exception("failed to create user: " + sb.ToString());
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Buffers.Text;
namespace System.Buffers.Text
{
public static partial class CustomParser
{
public static bool TryParseByte(ReadOnlySpan<byte> text, out byte value, out int bytesConsumed, ParsedFormat format = default, SymbolTable symbolTable = null)
{
symbolTable = symbolTable ?? SymbolTable.InvariantUtf8;
if (!format.IsDefault && format.HasPrecision)
{
throw new NotImplementedException("Format with precision not supported.");
}
if (symbolTable == SymbolTable.InvariantUtf8)
{
if (Parsers.IsHexFormat(format))
{
return Utf8Parser.Hex.TryParseByte(text, out value, out bytesConsumed);
}
else
{
return Utf8Parser.TryParseByte(text, out value, out bytesConsumed);
}
}
else if (symbolTable == SymbolTable.InvariantUtf16)
{
ReadOnlySpan<char> utf16Text = text.NonPortableCast<byte, char>();
int charactersConsumed;
bool result;
if (Parsers.IsHexFormat(format))
{
result = Utf16Parser.Hex.TryParseByte(utf16Text, out value, out charactersConsumed);
}
else
{
result = Utf16Parser.TryParseByte(utf16Text, out value, out charactersConsumed);
}
bytesConsumed = charactersConsumed * sizeof(char);
return result;
}
if (Parsers.IsHexFormat(format))
{
throw new NotImplementedException("The only supported encodings for hexadecimal parsing are InvariantUtf8 and InvariantUtf16.");
}
if (!(format.IsDefault || format.Symbol == 'G' || format.Symbol == 'g'))
{
throw new NotImplementedException(String.Format("Format '{0}' not supported.", format.Symbol));
}
SymbolTable.Symbol nextSymbol;
int thisSymbolConsumed;
if (!symbolTable.TryParse(text, out nextSymbol, out thisSymbolConsumed))
{
value = default;
bytesConsumed = 0;
return false;
}
if (nextSymbol > SymbolTable.Symbol.D9)
{
value = default;
bytesConsumed = 0;
return false;
}
uint parsedValue = (uint)nextSymbol;
int index = thisSymbolConsumed;
while (index < text.Length)
{
bool success = symbolTable.TryParse(text.Slice(index), out nextSymbol, out thisSymbolConsumed);
if (!success || nextSymbol > SymbolTable.Symbol.D9)
{
bytesConsumed = index;
value = (byte)parsedValue;
return true;
}
// If parsedValue > (byte.MaxValue / 10), any more appended digits will cause overflow.
// if parsedValue == (byte.MaxValue / 10), any nextDigit greater than 5 implies overflow.
if (parsedValue > byte.MaxValue / 10 || (parsedValue == byte.MaxValue / 10 && nextSymbol > SymbolTable.Symbol.D5))
{
bytesConsumed = 0;
value = default;
return false;
}
index += thisSymbolConsumed;
parsedValue = parsedValue * 10 + (uint)nextSymbol;
}
bytesConsumed = text.Length;
value = (byte)parsedValue;
return true;
}
public static bool TryParseUInt16(ReadOnlySpan<byte> text, out ushort value, out int bytesConsumed, ParsedFormat format = default, SymbolTable symbolTable = null)
{
symbolTable = symbolTable ?? SymbolTable.InvariantUtf8;
if (!format.IsDefault && format.HasPrecision)
{
throw new NotImplementedException("Format with precision not supported.");
}
if (symbolTable == SymbolTable.InvariantUtf8)
{
if (Parsers.IsHexFormat(format))
{
return Utf8Parser.Hex.TryParseUInt16(text, out value, out bytesConsumed);
}
else
{
return Utf8Parser.TryParseUInt16(text, out value, out bytesConsumed);
}
}
else if (symbolTable == SymbolTable.InvariantUtf16)
{
ReadOnlySpan<char> utf16Text = text.NonPortableCast<byte, char>();
int charactersConsumed;
bool result;
if (Parsers.IsHexFormat(format))
{
result = Utf16Parser.Hex.TryParseUInt16(utf16Text, out value, out charactersConsumed);
}
else
{
result = Utf16Parser.TryParseUInt16(utf16Text, out value, out charactersConsumed);
}
bytesConsumed = charactersConsumed * sizeof(char);
return result;
}
if (Parsers.IsHexFormat(format))
{
throw new NotImplementedException("The only supported encodings for hexadecimal parsing are InvariantUtf8 and InvariantUtf16.");
}
if (!(format.IsDefault || format.Symbol == 'G' || format.Symbol == 'g'))
{
throw new NotImplementedException(String.Format("Format '{0}' not supported.", format.Symbol));
}
SymbolTable.Symbol nextSymbol;
int thisSymbolConsumed;
if (!symbolTable.TryParse(text, out nextSymbol, out thisSymbolConsumed))
{
value = default;
bytesConsumed = 0;
return false;
}
if (nextSymbol > SymbolTable.Symbol.D9)
{
value = default;
bytesConsumed = 0;
return false;
}
uint parsedValue = (uint)nextSymbol;
int index = thisSymbolConsumed;
while (index < text.Length)
{
bool success = symbolTable.TryParse(text.Slice(index), out nextSymbol, out thisSymbolConsumed);
if (!success || nextSymbol > SymbolTable.Symbol.D9)
{
bytesConsumed = index;
value = (ushort)parsedValue;
return true;
}
// If parsedValue > (ushort.MaxValue / 10), any more appended digits will cause overflow.
// if parsedValue == (ushort.MaxValue / 10), any nextDigit greater than 5 implies overflow.
if (parsedValue > ushort.MaxValue / 10 || (parsedValue == ushort.MaxValue / 10 && nextSymbol > SymbolTable.Symbol.D5))
{
bytesConsumed = 0;
value = default;
return false;
}
index += thisSymbolConsumed;
parsedValue = parsedValue * 10 + (uint)nextSymbol;
}
bytesConsumed = text.Length;
value = (ushort)parsedValue;
return true;
}
public static bool TryParseUInt32(ReadOnlySpan<byte> text, out uint value, out int bytesConsumed, ParsedFormat format = default, SymbolTable symbolTable = null)
{
symbolTable = symbolTable ?? SymbolTable.InvariantUtf8;
if (!format.IsDefault && format.HasPrecision)
{
throw new NotImplementedException("Format with precision not supported.");
}
if (symbolTable == SymbolTable.InvariantUtf8)
{
if (Parsers.IsHexFormat(format))
{
return Utf8Parser.Hex.TryParseUInt32(text, out value, out bytesConsumed);
}
else
{
return Utf8Parser.TryParseUInt32(text, out value, out bytesConsumed);
}
}
else if (symbolTable == SymbolTable.InvariantUtf16)
{
ReadOnlySpan<char> utf16Text = text.NonPortableCast<byte, char>();
int charactersConsumed;
bool result;
if (Parsers.IsHexFormat(format))
{
result = Utf16Parser.Hex.TryParseUInt32(utf16Text, out value, out charactersConsumed);
}
else
{
result = Utf16Parser.TryParseUInt32(utf16Text, out value, out charactersConsumed);
}
bytesConsumed = charactersConsumed * sizeof(char);
return result;
}
if (Parsers.IsHexFormat(format))
{
throw new NotImplementedException("The only supported encodings for hexadecimal parsing are InvariantUtf8 and InvariantUtf16.");
}
if (!(format.IsDefault || format.Symbol == 'G' || format.Symbol == 'g'))
{
throw new NotImplementedException(String.Format("Format '{0}' not supported.", format.Symbol));
}
SymbolTable.Symbol nextSymbol;
int thisSymbolConsumed;
if (!symbolTable.TryParse(text, out nextSymbol, out thisSymbolConsumed))
{
value = default;
bytesConsumed = 0;
return false;
}
if (nextSymbol > SymbolTable.Symbol.D9)
{
value = default;
bytesConsumed = 0;
return false;
}
uint parsedValue = (uint)nextSymbol;
int index = thisSymbolConsumed;
while (index < text.Length)
{
bool success = symbolTable.TryParse(text.Slice(index), out nextSymbol, out thisSymbolConsumed);
if (!success || nextSymbol > SymbolTable.Symbol.D9)
{
bytesConsumed = index;
value = (uint)parsedValue;
return true;
}
// If parsedValue > (uint.MaxValue / 10), any more appended digits will cause overflow.
// if parsedValue == (uint.MaxValue / 10), any nextDigit greater than 5 implies overflow.
if (parsedValue > uint.MaxValue / 10 || (parsedValue == uint.MaxValue / 10 && nextSymbol > SymbolTable.Symbol.D5))
{
bytesConsumed = 0;
value = default;
return false;
}
index += thisSymbolConsumed;
parsedValue = parsedValue * 10 + (uint)nextSymbol;
}
bytesConsumed = text.Length;
value = (uint)parsedValue;
return true;
}
public static bool TryParseUInt64(ReadOnlySpan<byte> text, out ulong value, out int bytesConsumed, ParsedFormat format = default, SymbolTable symbolTable = null)
{
symbolTable = symbolTable ?? SymbolTable.InvariantUtf8;
if (!format.IsDefault && format.HasPrecision)
{
throw new NotImplementedException("Format with precision not supported.");
}
if (symbolTable == SymbolTable.InvariantUtf8)
{
if (Parsers.IsHexFormat(format))
{
return Utf8Parser.Hex.TryParseUInt64(text, out value, out bytesConsumed);
}
else
{
return Utf8Parser.TryParseUInt64(text, out value, out bytesConsumed);
}
}
else if (symbolTable == SymbolTable.InvariantUtf16)
{
ReadOnlySpan<char> utf16Text = text.NonPortableCast<byte, char>();
int charactersConsumed;
bool result;
if (Parsers.IsHexFormat(format))
{
result = Utf16Parser.Hex.TryParseUInt64(utf16Text, out value, out charactersConsumed);
}
else
{
result = Utf16Parser.TryParseUInt64(utf16Text, out value, out charactersConsumed);
}
bytesConsumed = charactersConsumed * sizeof(char);
return result;
}
if (Parsers.IsHexFormat(format))
{
throw new NotImplementedException("The only supported encodings for hexadecimal parsing are InvariantUtf8 and InvariantUtf16.");
}
if (!(format.IsDefault || format.Symbol == 'G' || format.Symbol == 'g'))
{
throw new NotImplementedException(String.Format("Format '{0}' not supported.", format.Symbol));
}
SymbolTable.Symbol nextSymbol;
int thisSymbolConsumed;
if (!symbolTable.TryParse(text, out nextSymbol, out thisSymbolConsumed))
{
value = default;
bytesConsumed = 0;
return false;
}
if (nextSymbol > SymbolTable.Symbol.D9)
{
value = default;
bytesConsumed = 0;
return false;
}
ulong parsedValue = (uint)nextSymbol;
int index = thisSymbolConsumed;
while (index < text.Length)
{
bool success = symbolTable.TryParse(text.Slice(index), out nextSymbol, out thisSymbolConsumed);
if (!success || nextSymbol > SymbolTable.Symbol.D9)
{
bytesConsumed = index;
value = (ulong)parsedValue;
return true;
}
// If parsedValue > (ulong.MaxValue / 10), any more appended digits will cause overflow.
// if parsedValue == (ulong.MaxValue / 10), any nextDigit greater than 5 implies overflow.
if (parsedValue > ulong.MaxValue / 10 || (parsedValue == ulong.MaxValue / 10 && nextSymbol > SymbolTable.Symbol.D5))
{
bytesConsumed = 0;
value = default;
return false;
}
index += thisSymbolConsumed;
parsedValue = parsedValue * 10 + (uint)nextSymbol;
}
bytesConsumed = text.Length;
value = (ulong)parsedValue;
return true;
}
}
}
| |
// 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.Threading;
using System.Linq;
using Microsoft.Build.Shared;
using Shouldly;
using Xunit;
namespace Microsoft.Build.UnitTests
{
public class FileUtilities_Tests
{
/// <summary>
/// Exercises FileUtilities.ItemSpecModifiers.GetItemSpecModifier
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
[Trait("Category", "netcore-osx-failing")]
[Trait("Category", "netcore-linux-failing")]
public void GetItemSpecModifier()
{
TestGetItemSpecModifier(Directory.GetCurrentDirectory());
TestGetItemSpecModifier(null);
}
private static void TestGetItemSpecModifier(string currentDirectory)
{
string cache = null;
string modifier = FileUtilities.ItemSpecModifiers.GetItemSpecModifier(currentDirectory, "foo", String.Empty, FileUtilities.ItemSpecModifiers.RecursiveDir, ref cache);
Assert.Equal(String.Empty, modifier);
cache = null;
modifier = FileUtilities.ItemSpecModifiers.GetItemSpecModifier(currentDirectory, "foo", String.Empty, FileUtilities.ItemSpecModifiers.ModifiedTime, ref cache);
Assert.Equal(String.Empty, modifier);
cache = null;
modifier = FileUtilities.ItemSpecModifiers.GetItemSpecModifier(currentDirectory, @"foo\goo", String.Empty, FileUtilities.ItemSpecModifiers.RelativeDir, ref cache);
Assert.Equal(@"foo" + Path.DirectorySeparatorChar, modifier);
// confirm we get the same thing back the second time
modifier = FileUtilities.ItemSpecModifiers.GetItemSpecModifier(currentDirectory, @"foo\goo", String.Empty, FileUtilities.ItemSpecModifiers.RelativeDir, ref cache);
Assert.Equal(@"foo" + Path.DirectorySeparatorChar, modifier);
cache = null;
string itemSpec = NativeMethodsShared.IsWindows ? @"c:\foo.txt" : "/foo.txt";
string itemSpecDir = NativeMethodsShared.IsWindows ? @"c:\" : "/";
modifier = FileUtilities.ItemSpecModifiers.GetItemSpecModifier(currentDirectory, itemSpec, String.Empty, FileUtilities.ItemSpecModifiers.FullPath, ref cache);
Assert.Equal(itemSpec, modifier);
Assert.Equal(itemSpec, cache);
modifier = FileUtilities.ItemSpecModifiers.GetItemSpecModifier(currentDirectory, itemSpec, String.Empty, FileUtilities.ItemSpecModifiers.RootDir, ref cache);
Assert.Equal(itemSpecDir, modifier);
modifier = FileUtilities.ItemSpecModifiers.GetItemSpecModifier(currentDirectory, itemSpec, String.Empty, FileUtilities.ItemSpecModifiers.Filename, ref cache);
Assert.Equal(@"foo", modifier);
modifier = FileUtilities.ItemSpecModifiers.GetItemSpecModifier(currentDirectory, itemSpec, String.Empty, FileUtilities.ItemSpecModifiers.Extension, ref cache);
Assert.Equal(@".txt", modifier);
modifier = FileUtilities.ItemSpecModifiers.GetItemSpecModifier(currentDirectory, itemSpec, String.Empty, FileUtilities.ItemSpecModifiers.Directory, ref cache);
Assert.Equal(String.Empty, modifier);
modifier = FileUtilities.ItemSpecModifiers.GetItemSpecModifier(currentDirectory, itemSpec, String.Empty, FileUtilities.ItemSpecModifiers.Identity, ref cache);
Assert.Equal(itemSpec, modifier);
string projectPath = NativeMethodsShared.IsWindows ? @"c:\abc\goo.proj" : @"/abc/goo.proj";
string projectPathDir = NativeMethodsShared.IsWindows ? @"c:\abc\" : @"/abc/";
modifier = FileUtilities.ItemSpecModifiers.GetItemSpecModifier(currentDirectory, itemSpec, projectPath, FileUtilities.ItemSpecModifiers.DefiningProjectDirectory, ref cache);
Assert.Equal(projectPathDir, modifier);
modifier = FileUtilities.ItemSpecModifiers.GetItemSpecModifier(currentDirectory, itemSpec, projectPath, FileUtilities.ItemSpecModifiers.DefiningProjectExtension, ref cache);
Assert.Equal(@".proj", modifier);
modifier = FileUtilities.ItemSpecModifiers.GetItemSpecModifier(currentDirectory, itemSpec, projectPath, FileUtilities.ItemSpecModifiers.DefiningProjectFullPath, ref cache);
Assert.Equal(projectPath, modifier);
modifier = FileUtilities.ItemSpecModifiers.GetItemSpecModifier(currentDirectory, itemSpec, projectPath, FileUtilities.ItemSpecModifiers.DefiningProjectName, ref cache);
Assert.Equal(@"goo", modifier);
}
[Fact]
public void MakeRelativeTests()
{
if (NativeMethodsShared.IsWindows)
{
Assert.Equal(@"foo.cpp", FileUtilities.MakeRelative(@"c:\abc\def", @"c:\abc\def\foo.cpp"));
Assert.Equal(@"def\foo.cpp", FileUtilities.MakeRelative(@"c:\abc\", @"c:\abc\def\foo.cpp"));
Assert.Equal(@"..\foo.cpp", FileUtilities.MakeRelative(@"c:\abc\def\xyz", @"c:\abc\def\foo.cpp"));
Assert.Equal(@"..\ttt\foo.cpp", FileUtilities.MakeRelative(@"c:\abc\def\xyz\", @"c:\abc\def\ttt\foo.cpp"));
Assert.Equal(@"e:\abc\def\foo.cpp", FileUtilities.MakeRelative(@"c:\abc\def", @"e:\abc\def\foo.cpp"));
Assert.Equal(@"foo.cpp", FileUtilities.MakeRelative(@"\\aaa\abc\def", @"\\aaa\abc\def\foo.cpp"));
Assert.Equal(@"foo.cpp", FileUtilities.MakeRelative(@"c:\abc\def", @"foo.cpp"));
Assert.Equal(@"\\host\path\file", FileUtilities.MakeRelative(@"c:\abc\def", @"\\host\path\file"));
Assert.Equal(@"\\host\d$\file", FileUtilities.MakeRelative(@"c:\abc\def", @"\\host\d$\file"));
Assert.Equal(@"..\fff\ggg.hh", FileUtilities.MakeRelative(@"c:\foo\bar\..\abc\cde", @"c:\foo\bar\..\abc\fff\ggg.hh"));
/* Directories */
Assert.Equal(@"def\", FileUtilities.MakeRelative(@"c:\abc\", @"c:\abc\def\"));
Assert.Equal(@"..\", FileUtilities.MakeRelative(@"c:\abc\def\xyz\", @"c:\abc\def\"));
Assert.Equal(@"..\ttt\", FileUtilities.MakeRelative(@"c:\abc\def\xyz\", @"c:\abc\def\ttt\"));
Assert.Equal(@".", FileUtilities.MakeRelative(@"c:\abc\def\", @"c:\abc\def\"));
/* Directory + File */
Assert.Equal(@"def", FileUtilities.MakeRelative(@"c:\abc\", @"c:\abc\def"));
Assert.Equal(@"..\..\ghi", FileUtilities.MakeRelative(@"c:\abc\def\xyz\", @"c:\abc\ghi"));
Assert.Equal(@"..\ghi", FileUtilities.MakeRelative(@"c:\abc\def\xyz\", @"c:\abc\def\ghi"));
Assert.Equal(@"..\ghi", FileUtilities.MakeRelative(@"c:\abc\def\", @"c:\abc\ghi"));
/* File + Directory */
Assert.Equal(@"def\", FileUtilities.MakeRelative(@"c:\abc", @"c:\abc\def\"));
Assert.Equal(@"..\", FileUtilities.MakeRelative(@"c:\abc\def\xyz", @"c:\abc\def\"));
Assert.Equal(@"..\ghi\", FileUtilities.MakeRelative(@"c:\abc\def\xyz", @"c:\abc\def\ghi\"));
Assert.Equal(@".", FileUtilities.MakeRelative(@"c:\abc\def", @"c:\abc\def\"));
}
else
{
Assert.Equal(@"bar.cpp", FileUtilities.MakeRelative(@"/abc/def", @"/abc/def/bar.cpp"));
Assert.Equal(@"def/foo.cpp", FileUtilities.MakeRelative(@"/abc/", @"/abc/def/foo.cpp"));
Assert.Equal(@"../foo.cpp", FileUtilities.MakeRelative(@"/abc/def/xyz", @"/abc/def/foo.cpp"));
Assert.Equal(@"../ttt/foo.cpp", FileUtilities.MakeRelative(@"/abc/def/xyz/", @"/abc/def/ttt/foo.cpp"));
Assert.Equal(@"foo.cpp", FileUtilities.MakeRelative(@"/abc/def", @"foo.cpp"));
Assert.Equal(@"../fff/ggg.hh", FileUtilities.MakeRelative(@"/foo/bar/../abc/cde", @"/foo/bar/../abc/fff/ggg.hh"));
/* Directories */
Assert.Equal(@"def/", FileUtilities.MakeRelative(@"/abc/", @"/abc/def/"));
Assert.Equal(@"../", FileUtilities.MakeRelative(@"/abc/def/xyz/", @"/abc/def/"));
Assert.Equal(@"../ttt/", FileUtilities.MakeRelative(@"/abc/def/xyz/", @"/abc/def/ttt/"));
Assert.Equal(@".", FileUtilities.MakeRelative(@"/abc/def/", @"/abc/def/"));
/* Directory + File */
Assert.Equal(@"def", FileUtilities.MakeRelative(@"/abc/", @"/abc/def"));
Assert.Equal(@"../../ghi", FileUtilities.MakeRelative(@"/abc/def/xyz/", @"/abc/ghi"));
Assert.Equal(@"../ghi", FileUtilities.MakeRelative(@"/abc/def/xyz/", @"/abc/def/ghi"));
Assert.Equal(@"../ghi", FileUtilities.MakeRelative(@"/abc/def/", @"/abc/ghi"));
/* File + Directory */
Assert.Equal(@"def/", FileUtilities.MakeRelative(@"/abc", @"/abc/def/"));
Assert.Equal(@"../", FileUtilities.MakeRelative(@"/abc/def/xyz", @"/abc/def/"));
Assert.Equal(@"../ghi/", FileUtilities.MakeRelative(@"/abc/def/xyz", @"/abc/def/ghi/"));
Assert.Equal(@".", FileUtilities.MakeRelative(@"/abc/def", @"/abc/def/"));
}
}
/// <summary>
/// Exercises FileUtilities.ItemSpecModifiers.GetItemSpecModifier on a bad path.
/// </summary>
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // On Unix there no invalid file name characters
[SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp, ".NET Core 2.1+ no longer validates paths: https://github.com/dotnet/corefx/issues/27779#issuecomment-371253486")]
public void GetItemSpecModifierOnBadPath()
{
Assert.Throws<InvalidOperationException>(() =>
{
TestGetItemSpecModifierOnBadPath(Directory.GetCurrentDirectory());
}
);
}
/// <summary>
/// Exercises FileUtilities.ItemSpecModifiers.GetItemSpecModifier on a bad path.
/// </summary>
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // On Unix there no invalid file name characters
[SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp, ".NET Core 2.1+ no longer validates paths: https://github.com/dotnet/corefx/issues/27779#issuecomment-371253486")]
public void GetItemSpecModifierOnBadPath2()
{
Assert.Throws<InvalidOperationException>(() =>
{
TestGetItemSpecModifierOnBadPath(null);
}
);
}
private static void TestGetItemSpecModifierOnBadPath(string currentDirectory)
{
try
{
string cache = null;
FileUtilities.ItemSpecModifiers.GetItemSpecModifier(currentDirectory, @"http://www.microsoft.com", String.Empty, FileUtilities.ItemSpecModifiers.RootDir, ref cache);
}
catch (Exception e)
{
// so I can see the exception message in NUnit's "Standard Out" window
Console.WriteLine(e.Message);
throw;
}
}
[Fact]
public void GetFileInfoNoThrowBasic()
{
string file = null;
try
{
file = FileUtilities.GetTemporaryFile();
FileInfo info = FileUtilities.GetFileInfoNoThrow(file);
Assert.Equal(info.LastWriteTime, new FileInfo(file).LastWriteTime);
}
finally
{
if (file != null) File.Delete(file);
}
}
[Fact]
public void GetFileInfoNoThrowNonexistent()
{
FileInfo info = FileUtilities.GetFileInfoNoThrow("this_file_is_nonexistent");
Assert.Null(info);
}
/// <summary>
/// Exercises FileUtilities.EndsWithSlash
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
[Trait("Category", "netcore-osx-failing")]
[Trait("Category", "netcore-linux-failing")]
public void EndsWithSlash()
{
Assert.True(FileUtilities.EndsWithSlash(@"C:\foo\"));
Assert.True(FileUtilities.EndsWithSlash(@"C:\"));
Assert.True(FileUtilities.EndsWithSlash(@"\"));
Assert.True(FileUtilities.EndsWithSlash(@"http://www.microsoft.com/"));
Assert.True(FileUtilities.EndsWithSlash(@"//server/share/"));
Assert.True(FileUtilities.EndsWithSlash(@"/"));
Assert.False(FileUtilities.EndsWithSlash(@"C:\foo"));
Assert.False(FileUtilities.EndsWithSlash(@"C:"));
Assert.False(FileUtilities.EndsWithSlash(@"foo"));
// confirm that empty string doesn't barf
Assert.False(FileUtilities.EndsWithSlash(String.Empty));
}
/// <summary>
/// Exercises FileUtilities.GetDirectory
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
[Trait("Category", "netcore-osx-failing")]
[Trait("Category", "netcore-linux-failing")]
public void GetDirectoryWithTrailingSlash()
{
Assert.Equal(NativeMethodsShared.IsWindows ? @"c:\" : "/", FileUtilities.GetDirectory(NativeMethodsShared.IsWindows ? @"c:\" : "/"));
Assert.Equal(NativeMethodsShared.IsWindows ? @"c:\" : "/", FileUtilities.GetDirectory(NativeMethodsShared.IsWindows ? @"c:\foo" : "/foo"));
Assert.Equal(NativeMethodsShared.IsWindows ? @"c:" : "/", FileUtilities.GetDirectory(NativeMethodsShared.IsWindows ? @"c:" : "/"));
Assert.Equal(FileUtilities.FixFilePath(@"\"), FileUtilities.GetDirectory(@"\"));
Assert.Equal(FileUtilities.FixFilePath(@"\"), FileUtilities.GetDirectory(@"\foo"));
Assert.Equal(FileUtilities.FixFilePath(@"..\"), FileUtilities.GetDirectory(@"..\foo"));
Assert.Equal(FileUtilities.FixFilePath(@"\foo\"), FileUtilities.GetDirectory(@"\foo\"));
Assert.Equal(FileUtilities.FixFilePath(@"\\server\share"), FileUtilities.GetDirectory(@"\\server\share"));
Assert.Equal(FileUtilities.FixFilePath(@"\\server\share\"), FileUtilities.GetDirectory(@"\\server\share\"));
Assert.Equal(FileUtilities.FixFilePath(@"\\server\share\"), FileUtilities.GetDirectory(@"\\server\share\file"));
Assert.Equal(FileUtilities.FixFilePath(@"\\server\share\directory\"), FileUtilities.GetDirectory(@"\\server\share\directory\"));
Assert.Equal(FileUtilities.FixFilePath(@"foo\"), FileUtilities.GetDirectory(@"foo\bar"));
Assert.Equal(FileUtilities.FixFilePath(@"\foo\bar\"), FileUtilities.GetDirectory(@"\foo\bar\"));
Assert.Equal(String.Empty, FileUtilities.GetDirectory("foo"));
}
[Theory]
[InlineData("foo.txt", new[] { ".txt" })]
[InlineData("foo.txt", new[] { ".TXT" })]
[InlineData("foo.txt", new[] { ".EXE", ".TXT" })]
public void HasExtension_WhenFileNameHasExtension_ReturnsTrue(string fileName, string[] allowedExtensions)
{
var result = FileUtilities.HasExtension(fileName, allowedExtensions);
if (!FileUtilities.GetIsFileSystemCaseSensitive() || allowedExtensions.Any(extension => fileName.Contains(extension)))
{
result.ShouldBeTrue();
}
}
[Theory]
[InlineData("foo.txt", new[] { ".DLL" })]
[InlineData("foo.txt", new[] { ".EXE", ".DLL" })]
[InlineData("foo.exec", new[] { ".exe", })]
[InlineData("foo.exe", new[] { ".exec", })]
[InlineData("foo", new[] { ".exe", })]
[InlineData("", new[] { ".exe" })]
[InlineData(null, new[] { ".exe" })]
public void HasExtension_WhenFileNameDoesNotHaveExtension_ReturnsFalse(string fileName, string[] allowedExtensions)
{
var result = FileUtilities.HasExtension(fileName, allowedExtensions);
Assert.False(result);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
[SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp)]
public void HasExtension_WhenInvalidFileName_ThrowsArgumentException()
{
Assert.Throws<ArgumentException>(() =>
{
FileUtilities.HasExtension("|/", new[] { ".exe" });
});
}
[Fact]
public void HasExtension_UsesOrdinalIgnoreCase()
{
var currentCulture = Thread.CurrentThread.CurrentCulture;
try
{
Thread.CurrentThread.CurrentCulture = new CultureInfo("tr-TR"); // Turkish
var result = FileUtilities.HasExtension("foo.ini", new string[] { ".INI" });
result.ShouldBe(!FileUtilities.GetIsFileSystemCaseSensitive());
}
finally
{
Thread.CurrentThread.CurrentCulture = currentCulture;
}
}
/// <summary>
/// Exercises FileUtilities.EnsureTrailingSlash
/// </summary>
[Fact]
public void EnsureTrailingSlash()
{
// Doesn't have a trailing slash to start with.
Assert.Equal(FileUtilities.FixFilePath(@"foo\bar\"), FileUtilities.EnsureTrailingSlash(@"foo\bar")); // "test 1"
Assert.Equal(FileUtilities.FixFilePath(@"foo/bar\"), FileUtilities.EnsureTrailingSlash(@"foo/bar")); // "test 2"
// Already has a trailing slash to start with.
Assert.Equal(FileUtilities.FixFilePath(@"foo/bar/"), FileUtilities.EnsureTrailingSlash(@"foo/bar/")); //test 3"
Assert.Equal(FileUtilities.FixFilePath(@"foo\bar\"), FileUtilities.EnsureTrailingSlash(@"foo\bar\")); //test 4"
Assert.Equal(FileUtilities.FixFilePath(@"foo/bar\"), FileUtilities.EnsureTrailingSlash(@"foo/bar\")); //test 5"
Assert.Equal(FileUtilities.FixFilePath(@"foo\bar/"), FileUtilities.EnsureTrailingSlash(@"foo\bar/")); //"test 5"
}
/// <summary>
/// Exercises FileUtilities.ItemSpecModifiers.IsItemSpecModifier
/// </summary>
[Fact]
public void IsItemSpecModifier()
{
// Positive matches using exact case.
Assert.True(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("FullPath")); // "test 1"
Assert.True(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("RootDir")); // "test 2"
Assert.True(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("Filename")); // "test 3"
Assert.True(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("Extension")); // "test 4"
Assert.True(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("RelativeDir")); // "test 5"
Assert.True(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("Directory")); // "test 6"
Assert.True(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("RecursiveDir")); // "test 7"
Assert.True(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("Identity")); // "test 8"
Assert.True(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("ModifiedTime")); // "test 9"
Assert.True(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("CreatedTime")); // "test 10"
Assert.True(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("AccessedTime")); // "test 11"
// Positive matches using different case.
Assert.True(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("fullPath")); // "test 21"
Assert.True(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("rootDir")); // "test 22"
Assert.True(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("filename")); // "test 23"
Assert.True(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("extension")); // "test 24"
Assert.True(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("relativeDir")); // "test 25"
Assert.True(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("directory")); // "test 26"
Assert.True(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("recursiveDir")); // "test 27"
Assert.True(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("identity")); // "test 28"
Assert.True(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("modifiedTime")); // "test 29"
Assert.True(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("createdTime")); // "test 30"
Assert.True(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("accessedTime")); // "test 31"
// Negative tests to get maximum code coverage inside the many different branches
// of FileUtilities.ItemSpecModifiers.IsItemSpecModifier.
Assert.False(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("rootxxx")); // "test 41"
Assert.False(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("Rootxxx")); // "test 42"
Assert.False(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("xxxxxxx")); // "test 43"
Assert.False(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("filexxxx")); // "test 44"
Assert.False(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("Filexxxx")); // "test 45"
Assert.False(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("idenxxxx")); // "test 46"
Assert.False(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("Idenxxxx")); // "test 47"
Assert.False(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("xxxxxxxx")); // "test 48"
Assert.False(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("extenxxxx")); // "test 49"
Assert.False(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("Extenxxxx")); // "test 50"
Assert.False(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("direcxxxx")); // "test 51"
Assert.False(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("Direcxxxx")); // "test 52"
Assert.False(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("xxxxxxxxx")); // "test 53"
Assert.False(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("xxxxxxxxxx")); // "test 54"
Assert.False(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("relativexxx")); // "test 55"
Assert.False(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("Relativexxx")); // "test 56"
Assert.False(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("createdxxxx")); // "test 57"
Assert.False(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("Createdxxxx")); // "test 58"
Assert.False(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("xxxxxxxxxxx")); // "test 59"
Assert.False(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("recursivexxx")); // "test 60"
Assert.False(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("Recursivexxx")); // "test 61"
Assert.False(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("accessedxxxx")); // "test 62"
Assert.False(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("Accessedxxxx")); // "test 63"
Assert.False(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("modifiedxxxx")); // "test 64"
Assert.False(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("Modifiedxxxx")); // "test 65"
Assert.False(FileUtilities.ItemSpecModifiers.IsItemSpecModifier("xxxxxxxxxxxx")); // "test 66"
Assert.False(FileUtilities.ItemSpecModifiers.IsItemSpecModifier(null)); // "test 67"
}
[Fact]
public void CheckDerivableItemSpecModifiers()
{
Assert.True(FileUtilities.ItemSpecModifiers.IsDerivableItemSpecModifier("Filename"));
Assert.False(FileUtilities.ItemSpecModifiers.IsDerivableItemSpecModifier("RecursiveDir"));
Assert.False(FileUtilities.ItemSpecModifiers.IsDerivableItemSpecModifier("recursivedir"));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void NormalizePathThatFitsIntoMaxPath()
{
string currentDirectory = @"c:\aardvark\aardvark\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890";
string filePath = @"..\..\..\..\..\..\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\a.cs";
string fullPath = @"c:\aardvark\aardvark\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\a.cs";
Assert.Equal(fullPath, FileUtilities.NormalizePath(Path.Combine(currentDirectory, filePath)));
}
[ConditionalFact(typeof(NativeMethodsShared), nameof(NativeMethodsShared.IsMaxPathLegacyWindows))]
[PlatformSpecific(TestPlatforms.Windows)]
[SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp, "https://github.com/microsoft/msbuild/issues/4363")]
public void NormalizePathThatDoesntFitIntoMaxPath()
{
Assert.Throws<PathTooLongException>(() =>
{
string currentDirectory = @"c:\aardvark\aardvark\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890";
string filePath = @"..\..\..\..\..\..\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\a.cs";
// This path ends up over 420 characters long
string fullPath = @"c:\aardvark\aardvark\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\a.cs";
Assert.Equal(fullPath, FileUtilities.NormalizePath(Path.Combine(currentDirectory, filePath)));
}
);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void GetItemSpecModifierRootDirThatFitsIntoMaxPath()
{
string currentDirectory = @"c:\aardvark\aardvark\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890";
string fullPath = @"c:\aardvark\aardvark\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\a.cs";
string cache = fullPath;
Assert.Equal(@"c:\", FileUtilities.ItemSpecModifiers.GetItemSpecModifier(currentDirectory, fullPath, String.Empty, FileUtilities.ItemSpecModifiers.RootDir, ref cache));
}
[Fact]
public void NormalizePathNull()
{
Assert.Throws<ArgumentNullException>(() =>
{
Assert.Null(FileUtilities.NormalizePath(null, null));
}
);
}
[Fact]
public void NormalizePathEmpty()
{
Assert.Throws<ArgumentException>(() =>
{
Assert.Null(FileUtilities.NormalizePath(String.Empty));
}
);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
[SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp, ".NET Core 2.1+ no longer validates paths: https://github.com/dotnet/corefx/issues/27779#issuecomment-371253486")]
public void NormalizePathBadUNC1()
{
Assert.Throws<ArgumentException>(() =>
{
Assert.Null(FileUtilities.NormalizePath(@"\\"));
}
);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
[SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp, ".NET Core 2.1+ no longer validates paths: https://github.com/dotnet/corefx/issues/27779#issuecomment-371253486")]
public void NormalizePathBadUNC2()
{
Assert.Throws<ArgumentException>(() =>
{
Assert.Null(FileUtilities.NormalizePath(@"\\XXX\"));
}
);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
[SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp, ".NET Core 2.1+ no longer validates paths: https://github.com/dotnet/corefx/issues/27779#issuecomment-371253486")]
public void NormalizePathBadUNC3()
{
Assert.Throws<ArgumentException>(() =>
{
Assert.Equal(@"\\localhost", FileUtilities.NormalizePath(@"\\localhost"));
}
);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void NormalizePathGoodUNC()
{
Assert.Equal(@"\\localhost\share", FileUtilities.NormalizePath(@"\\localhost\share"));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void NormalizePathTooLongWithDots()
{
string longPart = new string('x', 300);
Assert.Equal(@"c:\abc\def", FileUtilities.NormalizePath(@"c:\abc\" + longPart + @"\..\def"));
}
#if FEATURE_LEGACY_GETFULLPATH
[Fact(Skip="https://github.com/Microsoft/msbuild/issues/4205")]
[PlatformSpecific(TestPlatforms.Windows)]
public void NormalizePathBadGlobalroot()
{
Assert.Throws<ArgumentException>(() =>
{
/*
From Path.cs
// Check for \\?\Globalroot, an internal mechanism to the kernel
// that provides aliases for drives and other undocumented stuff.
// The kernel team won't even describe the full set of what
// is available here - we don't want managed apps mucking
// with this for security reasons.
* */
Assert.Null(FileUtilities.NormalizePath(@"\\?\globalroot\XXX"));
}
);
}
#endif
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
[SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp, ".NET Core 2.1+ no longer validates paths: https://github.com/dotnet/corefx/issues/27779#issuecomment-371253486")]
public void NormalizePathInvalid()
{
string filePath = @"c:\aardvark\|||";
Assert.Throws<ArgumentException>(() =>
{
FileUtilities.NormalizePath(filePath);
});
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void CannotNormalizePathWithNewLineAndSpace()
{
string filePath = "\r\n C:\\work\\sdk3\\artifacts\\tmp\\Debug\\SimpleNamesWi---6143883E\\NETFrameworkLibrary\\bin\\Debug\\net462\\NETFrameworkLibrary.dll\r\n ";
#if FEATURE_LEGACY_GETFULLPATH
Assert.Throws<ArgumentException>(() => FileUtilities.NormalizePath(filePath));
#else
Assert.NotEqual("C:\\work\\sdk3\\artifacts\\tmp\\Debug\\SimpleNamesWi---6143883E\\NETFrameworkLibrary\\bin\\Debug\\net462\\NETFrameworkLibrary.dll", FileUtilities.NormalizePath(filePath));
#endif
}
[Fact]
public void FileOrDirectoryExistsNoThrow()
{
var isWindows = NativeMethodsShared.IsWindows;
Assert.False(FileUtilities.FileOrDirectoryExistsNoThrow("||"));
Assert.False(FileUtilities.FileOrDirectoryExistsNoThrow(isWindows ? @"c:\doesnot_exist" : "/doesnot_exist"));
Assert.True(FileUtilities.FileOrDirectoryExistsNoThrow(isWindows ? @"c:\" : "/"));
Assert.True(FileUtilities.FileOrDirectoryExistsNoThrow(Path.GetTempPath()));
string path = null;
try
{
path = FileUtilities.GetTemporaryFile();
Assert.True(FileUtilities.FileOrDirectoryExistsNoThrow(path));
}
finally
{
File.Delete(path);
}
}
#if FEATURE_ENVIRONMENT_SYSTEMDIRECTORY
// These tests will need to be redesigned for Linux
[ConditionalFact(nameof(RunTestsThatDependOnWindowsShortPathBehavior_Workaround4241))]
[Trait("Category", "mono-osx-failing")]
public void FileOrDirectoryExistsNoThrowTooLongWithDots()
{
int length = (Environment.SystemDirectory + @"\" + @"\..\..\..\" + Environment.SystemDirectory.Substring(3)).Length;
string longPart = new string('x', 260 - length); // We want the shortest that is > max path.
string inputPath = Environment.SystemDirectory + @"\" + longPart + @"\..\..\..\" + Environment.SystemDirectory.Substring(3);
Console.WriteLine(inputPath.Length);
// "c:\windows\system32\<verylong>\..\..\windows\system32" exists
Assert.True(FileUtilities.FileOrDirectoryExistsNoThrow(inputPath));
Assert.False(FileUtilities.FileOrDirectoryExistsNoThrow(inputPath.Replace('\\', 'X')));
}
[ConditionalFact(nameof(RunTestsThatDependOnWindowsShortPathBehavior_Workaround4241))]
[Trait("Category", "mono-osx-failing")]
public void FileOrDirectoryExistsNoThrowTooLongWithDotsRelative()
{
int length = (Environment.SystemDirectory + @"\" + @"\..\..\..\" + Environment.SystemDirectory.Substring(3)).Length;
string longPart = new string('x', 260 - length); // We want the shortest that is > max path.
string inputPath = longPart + @"\..\..\..\" + Environment.SystemDirectory.Substring(3);
Console.WriteLine(inputPath.Length);
// "c:\windows\system32\<verylong>\..\..\windows\system32" exists
string currentDirectory = Directory.GetCurrentDirectory();
try
{
Directory.SetCurrentDirectory(Environment.SystemDirectory);
Assert.True(FileUtilities.FileOrDirectoryExistsNoThrow(inputPath));
Assert.False(FileUtilities.FileOrDirectoryExistsNoThrow(inputPath.Replace('\\', 'X')));
}
finally
{
Directory.SetCurrentDirectory(currentDirectory);
}
}
[Fact]
public void DirectoryExistsNoThrowTooLongWithDots()
{
string path = Path.Combine(Environment.SystemDirectory, "..", "..", "..") + Path.DirectorySeparatorChar;
if (NativeMethodsShared.IsWindows)
{
path += Environment.SystemDirectory.Substring(3);
}
int length = path.Length;
string longPart = new string('x', 260 - length); // We want the shortest that is > max path.
string inputPath = Path.Combine(new[] { Environment.SystemDirectory, longPart, "..", "..", ".." })
+ Path.DirectorySeparatorChar;
if (NativeMethodsShared.IsWindows)
{
path += Environment.SystemDirectory.Substring(3);
}
Console.WriteLine(inputPath.Length);
// "c:\windows\system32\<verylong>\..\..\windows\system32" exists
Assert.True(FileUtilities.DirectoryExistsNoThrow(inputPath));
}
[ConditionalFact(nameof(RunTestsThatDependOnWindowsShortPathBehavior_Workaround4241))]
[Trait("Category", "mono-osx-failing")]
public void DirectoryExistsNoThrowTooLongWithDotsRelative()
{
int length = (Environment.SystemDirectory + @"\" + @"\..\..\..\" + Environment.SystemDirectory.Substring(3)).Length;
string longPart = new string('x', 260 - length); // We want the shortest that is > max path.
string inputPath = longPart + @"\..\..\..\" + Environment.SystemDirectory.Substring(3);
Console.WriteLine(inputPath.Length);
// "c:\windows\system32\<verylong>\..\..\..\windows\system32" exists
string currentDirectory = Directory.GetCurrentDirectory();
try
{
Directory.SetCurrentDirectory(Environment.SystemDirectory);
FileUtilities.DirectoryExistsNoThrow(inputPath).ShouldBeTrue();
FileUtilities.DirectoryExistsNoThrow(inputPath.Replace('\\', 'X')).ShouldBeFalse();
}
finally
{
Directory.SetCurrentDirectory(currentDirectory);
}
}
public static bool RunTestsThatDependOnWindowsShortPathBehavior_Workaround4241()
{
// Run these tests only when we're not on Windows
return !NativeMethodsShared.IsWindows ||
// OR we're on Windows and long paths aren't enabled
// https://github.com/Microsoft/msbuild/issues/4241
NativeMethodsShared.IsMaxPathLegacyWindows();
}
[ConditionalFact(nameof(RunTestsThatDependOnWindowsShortPathBehavior_Workaround4241))]
[Trait("Category", "mono-osx-failing")]
public void FileExistsNoThrowTooLongWithDots()
{
int length = (Environment.SystemDirectory + @"\" + @"\..\..\..\" + Environment.SystemDirectory.Substring(3) + @"\..\explorer.exe").Length;
string longPart = new string('x', 260 - length); // We want the shortest that is > max path.
string inputPath = Environment.SystemDirectory + @"\" + longPart + @"\..\..\..\" + Environment.SystemDirectory.Substring(3) + @"\..\explorer.exe";
Console.WriteLine(inputPath.Length);
Console.WriteLine(inputPath);
// "c:\windows\system32\<verylong>\..\..\windows\system32" exists
Assert.True(FileUtilities.FileExistsNoThrow(inputPath));
}
[ConditionalFact(nameof(RunTestsThatDependOnWindowsShortPathBehavior_Workaround4241))]
[Trait("Category", "mono-osx-failing")]
public void FileExistsNoThrowTooLongWithDotsRelative()
{
int length = (Environment.SystemDirectory + @"\" + @"\..\..\..\" + Environment.SystemDirectory.Substring(3) + @"\..\explorer.exe").Length;
string longPart = new string('x', 260 - length); // We want the shortest that is > max path.
string inputPath = longPart + @"\..\..\..\" + Environment.SystemDirectory.Substring(3) + @"\..\explorer.exe";
Console.WriteLine(inputPath.Length);
// "c:\windows\system32\<verylong>\..\..\windows\system32" exists
string currentDirectory = Directory.GetCurrentDirectory();
try
{
Directory.SetCurrentDirectory(Environment.SystemDirectory);
Assert.True(FileUtilities.FileExistsNoThrow(inputPath));
Assert.False(FileUtilities.FileExistsNoThrow(inputPath.Replace('\\', 'X')));
}
finally
{
Directory.SetCurrentDirectory(currentDirectory);
}
}
[Fact]
[Trait("Category", "mono-osx-failing")]
public void GetFileInfoNoThrowTooLongWithDots()
{
int length = (Environment.SystemDirectory + @"\" + @"\..\..\..\" + Environment.SystemDirectory.Substring(3) + @"\..\explorer.exe").Length;
string longPart = new string('x', 260 - length); // We want the shortest that is > max path.
string inputPath = Environment.SystemDirectory + @"\" + longPart + @"\..\..\..\" + Environment.SystemDirectory.Substring(3) + @"\..\explorer.exe";
Console.WriteLine(inputPath.Length);
// "c:\windows\system32\<verylong>\..\..\windows\system32" exists
Assert.True(FileUtilities.GetFileInfoNoThrow(inputPath) != null);
Assert.False(FileUtilities.GetFileInfoNoThrow(inputPath.Replace('\\', 'X')) != null);
}
[Fact]
[Trait("Category", "mono-osx-failing")]
public void GetFileInfoNoThrowTooLongWithDotsRelative()
{
int length = (Environment.SystemDirectory + @"\" + @"\..\..\..\" + Environment.SystemDirectory.Substring(3) + @"\..\explorer.exe").Length;
string longPart = new string('x', 260 - length); // We want the shortest that is > max path.
string inputPath = longPart + @"\..\..\..\" + Environment.SystemDirectory.Substring(3) + @"\..\explorer.exe";
Console.WriteLine(inputPath.Length);
// "c:\windows\system32\<verylong>\..\..\windows\system32" exists
string currentDirectory = Directory.GetCurrentDirectory();
try
{
Directory.SetCurrentDirectory(Environment.SystemDirectory);
Assert.True(FileUtilities.GetFileInfoNoThrow(inputPath) != null);
Assert.False(FileUtilities.GetFileInfoNoThrow(inputPath.Replace('\\', 'X')) != null);
}
finally
{
Directory.SetCurrentDirectory(currentDirectory);
}
}
#endif
/// <summary>
/// Simple test, neither the base file nor retry files exist
/// </summary>
[Fact]
public void GenerateTempFileNameSimple()
{
string path = null;
try
{
path = FileUtilities.GetTemporaryFile();
Assert.EndsWith(".tmp", path);
Assert.True(File.Exists(path));
Assert.StartsWith(Path.GetTempPath(), path);
}
finally
{
File.Delete(path);
}
}
/// <summary>
/// Choose an extension
/// </summary>
[Fact]
public void GenerateTempFileNameWithExtension()
{
string path = null;
try
{
path = FileUtilities.GetTemporaryFile(".bat");
Assert.EndsWith(".bat", path);
Assert.True(File.Exists(path));
Assert.StartsWith(Path.GetTempPath(), path);
}
finally
{
File.Delete(path);
}
}
/// <summary>
/// Choose a (missing) directory and extension
/// </summary>
[Fact]
public void GenerateTempFileNameWithDirectoryAndExtension()
{
string path = null;
string directory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "subfolder");
try
{
path = FileUtilities.GetTemporaryFile(directory, ".bat");
Assert.EndsWith(".bat", path);
Assert.True(File.Exists(path));
Assert.StartsWith(directory, path);
}
finally
{
File.Delete(path);
FileUtilities.DeleteWithoutTrailingBackslash(directory);
}
}
/// <summary>
/// Extension without a period
/// </summary>
[Fact]
public void GenerateTempFileNameWithExtensionNoPeriod()
{
string path = null;
try
{
path = FileUtilities.GetTemporaryFile("bat");
Assert.EndsWith(".bat", path);
Assert.True(File.Exists(path));
Assert.StartsWith(Path.GetTempPath(), path);
}
finally
{
File.Delete(path);
}
}
/// <summary>
/// Extension is invalid
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
[Trait("Category", "netcore-osx-failing")]
[Trait("Category", "netcore-linux-failing")]
public void GenerateTempBatchFileWithBadExtension()
{
Assert.Throws<IOException>(() =>
{
FileUtilities.GetTemporaryFile("|");
}
);
}
/// <summary>
/// No extension is given
/// </summary>
[Fact]
public void GenerateTempBatchFileWithEmptyExtension()
{
Assert.Throws<ArgumentException>(() =>
{
FileUtilities.GetTemporaryFile(String.Empty);
}
);
}
/// <summary>
/// Directory is invalid
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
[Trait("Category", "netcore-osx-failing")]
[Trait("Category", "netcore-linux-failing")]
public void GenerateTempBatchFileWithBadDirectory()
{
Assert.Throws<IOException>(() =>
{
FileUtilities.GetTemporaryFile("|", ".tmp");
}
);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public void AbsolutePathLooksLikeUnixPathOnUnix()
{
var secondSlash = SystemSpecificAbsolutePath.Substring(1).IndexOf(Path.DirectorySeparatorChar) + 1;
var rootLevelPath = SystemSpecificAbsolutePath.Substring(0, secondSlash);
Assert.True(FileUtilities.LooksLikeUnixFilePath(SystemSpecificAbsolutePath));
Assert.True(FileUtilities.LooksLikeUnixFilePath(rootLevelPath));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void PathDoesNotLookLikeUnixPathOnWindows()
{
Assert.False(FileUtilities.LooksLikeUnixFilePath(SystemSpecificAbsolutePath));
Assert.False(FileUtilities.LooksLikeUnixFilePath("/path/that/looks/unixy"));
Assert.False(FileUtilities.LooksLikeUnixFilePath("/root"));
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public void RelativePathLooksLikeUnixPathOnUnixWithBaseDirectory()
{
string filePath = ObjectModelHelpers.CreateFileInTempProjectDirectory("first/second/file.txt", String.Empty);
string oldCWD = Directory.GetCurrentDirectory();
try
{
// <tmp_dir>/first
string firstDirectory = Path.GetDirectoryName(Path.GetDirectoryName(filePath));
string tmpDirectory = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(filePath)));
Directory.SetCurrentDirectory(tmpDirectory);
// We are in <tmp_dir> and second is not under that, so this will be false
Assert.False(FileUtilities.LooksLikeUnixFilePath("second/file.txt"));
// .. but if we have baseDirectory:firstDirectory, then it will be true
Assert.True(FileUtilities.LooksLikeUnixFilePath("second/file.txt", firstDirectory));
}
finally
{
if (filePath != null)
{
File.Delete(filePath);
}
Directory.SetCurrentDirectory(oldCWD);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public void RelativePathMaybeAdjustFilePathWithBaseDirectory()
{
// <tmp_dir>/first/second/file.txt
string filePath = ObjectModelHelpers.CreateFileInTempProjectDirectory("first/second/file.txt", String.Empty);
string oldCWD = Directory.GetCurrentDirectory();
try
{
// <tmp_dir>/first
string firstDirectory = Path.GetDirectoryName(Path.GetDirectoryName(filePath));
string tmpDirectory = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(filePath)));
Directory.SetCurrentDirectory(tmpDirectory);
// We are in <tmp_dir> and second is not under that, so this won't convert
Assert.Equal("second\\file.txt", FileUtilities.MaybeAdjustFilePath("second\\file.txt"));
// .. but if we have baseDirectory:firstDirectory, then it will
Assert.Equal("second/file.txt", FileUtilities.MaybeAdjustFilePath("second\\file.txt", firstDirectory));
}
finally
{
if (filePath != null)
{
File.Delete(filePath);
}
Directory.SetCurrentDirectory(oldCWD);
}
}
private static string SystemSpecificAbsolutePath => FileUtilities.ExecutingAssemblyPath;
[Fact]
public void GetFolderAboveTest()
{
string root = NativeMethodsShared.IsWindows ? @"c:\" : "/";
string path = Path.Combine(root, "1", "2", "3", "4", "5");
Assert.Equal(Path.Combine(root, "1", "2", "3", "4", "5"), FileUtilities.GetFolderAbove(path, 0));
Assert.Equal(Path.Combine(root, "1", "2", "3", "4"), FileUtilities.GetFolderAbove(path));
Assert.Equal(Path.Combine(root, "1", "2", "3"), FileUtilities.GetFolderAbove(path, 2));
Assert.Equal(Path.Combine(root, "1", "2"), FileUtilities.GetFolderAbove(path, 3));
Assert.Equal(Path.Combine(root, "1"), FileUtilities.GetFolderAbove(path, 4));
Assert.Equal(root, FileUtilities.GetFolderAbove(path, 5));
Assert.Equal(root, FileUtilities.GetFolderAbove(path, 99));
Assert.Equal(root, FileUtilities.GetFolderAbove(root, 99));
}
[Fact]
public void CombinePathsTest()
{
// These tests run in .NET 4+, so we can cheat
var root = @"c:\";
Assert.Equal(
Path.Combine(root, "path1"),
FileUtilities.CombinePaths(root, "path1"));
Assert.Equal(
Path.Combine(root, "path1", "path2", "file.txt"),
FileUtilities.CombinePaths(root, "path1", "path2", "file.txt"));
}
[Theory]
[InlineData(@"c:\a\.\b", true)]
[InlineData(@"c:\a\..\b", true)]
[InlineData(@"c:\a\..", true)]
[InlineData(@"c:\a\.", true)]
[InlineData(@".\a", true)]
[InlineData(@"..\b", true)]
[InlineData(@"..", true)]
[InlineData(@".", true)]
[InlineData(@"..\", true)]
[InlineData(@".\", true)]
[InlineData(@"\..", true)]
[InlineData(@"\.", true)]
[InlineData(@"..\..\a", true)]
[InlineData(@"..\..\..\a", true)]
[InlineData(@"b..\", false)]
[InlineData(@"b.\", false)]
[InlineData(@"\b..", false)]
[InlineData(@"\b.", false)]
[InlineData(@"\b..\", false)]
[InlineData(@"\b.\", false)]
[InlineData(@"...", false)]
[InlineData(@"....", false)]
public void ContainsRelativeSegmentsTest(string path, bool expectedResult)
{
FileUtilities.ContainsRelativePathSegments(path).ShouldBe(expectedResult);
}
[Theory]
[InlineData("a/b/c/d", 0, "")]
[InlineData("a/b/c/d", 1, "d")]
[InlineData("a/b/c/d", 2, "c/d")]
[InlineData("a/b/c/d", 3, "b/c/d")]
[InlineData("a/b/c/d", 4, "a/b/c/d")]
[InlineData("a/b/c/d", 5, "a/b/c/d")]
[InlineData(@"a\/\/\//b/\/\/\//c//\/\/\/d/\//\/\/", 2, "c/d")]
public static void TestTruncatePathToTrailingSegments(string path, int trailingSegments, string expectedTruncatedPath)
{
expectedTruncatedPath = expectedTruncatedPath.Replace('/', Path.DirectorySeparatorChar);
FileUtilities.TruncatePathToTrailingSegments(path, trailingSegments).ShouldBe(expectedTruncatedPath);
}
}
}
| |
/*
* Copyright 2008 Matthias Sessler
*
* This file is part of LibMpc.net.
*
* LibMpc.net is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 2.1 of the License, or
* (at your option) any later version.
*
* LibMpc.net is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with LibMpc.net. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
namespace Libmpc
{
/// <summary>
/// The delegate for the <see cref="MpcConnection.OnConnected"/> and <see cref="MpcConnection.OnDisconnected"/> events.
/// </summary>
/// <param name="connection">The connection firing the event.</param>
public delegate void MpcConnectionEventDelegate(MpcConnection connection);
public delegate void MpcConnectionIdleEventDelegate(MpcConnection connection, Mpc.Subsystems subsystems);
/// <summary>
/// Keeps the connection to the MPD server and handels the most basic structure of the
/// MPD protocol. The high level commands are handeled in the <see cref="Libmpc.Mpc"/>
/// class.
/// </summary>
public class MpcConnection
{
/// <summary>
/// Is fired when a connection to a MPD server is established.
/// </summary>
public event MpcConnectionEventDelegate OnConnected;
/// <summary>
/// Is fired when the connection to the MPD server is closed.
/// </summary>
public event MpcConnectionEventDelegate OnDisconnected;
public event MpcConnectionIdleEventDelegate OnSubsystemsChanged;
private static readonly string FIRST_LINE_PREFIX = "OK MPD ";
private static readonly string OK = "OK";
private static readonly string ACK = "ACK";
private static readonly Regex ACK_REGEX = new Regex("^ACK \\[(?<code>[0-9]*)@(?<nr>[0-9]*)] \\{(?<command>[a-z]*)} (?<message>.*)$");
private List<string> m_Commands = null;
private Mutex m_Mutex = new Mutex();
private IPEndPoint ipEndPoint = null;
private SocketManager m_SocketManager = null;
private string version;
/// <summary>
/// If the connection to the MPD is connected.
/// </summary>
public bool Connected { get { return (m_SocketManager != null) && m_SocketManager.Connected; } }
/// <summary>
/// The version of the MPD.
/// </summary>
public string Version { get { return this.version; } }
private bool autoConnect = false;
/// <summary>
/// If a connection should be established when a command is to be
/// executed in disconnected state.
/// </summary>
public bool AutoConnect
{
get { return this.autoConnect; }
set { this.autoConnect = value; }
}
public List<string> Commands
{
get { return m_Commands; }
}
/// <summary>
/// Creates a new MpdConnection.
/// </summary>
public MpcConnection() { }
/// <summary>
/// Creates a new MpdConnection.
/// </summary>
/// <param name="server">The IPEndPoint of the MPD server.</param>
public MpcConnection(IPEndPoint server) { this.Connect(server); }
/// <summary>
/// The IPEndPoint of the MPD server.
/// </summary>
/// <exception cref="AlreadyConnectedException">When a conenction to a MPD server is already established.</exception>
public IPEndPoint Server
{
get { return this.ipEndPoint; }
set
{
if (this.Connected)
throw new AlreadyConnectedException();
this.ipEndPoint = value;
this.ClearConnectionFields();
}
}
/// <summary>
/// Connects to a MPD server.
/// </summary>
/// <param name="server">The IPEndPoint of the server.</param>
public void Connect(IPEndPoint server)
{
this.Server = server;
this.Connect();
}
/// <summary>
/// Connects to the MPD server who's IPEndPoint was set in the Server property.
/// </summary>
/// <exception cref="InvalidOperationException">If no IPEndPoint was set to the Server property.</exception>
public void Connect()
{
if (this.ipEndPoint == null)
throw new InvalidOperationException("Server IPEndPoint not set.");
if (this.Connected)
throw new AlreadyConnectedException();
if (m_SocketManager != null) {
m_SocketManager.Dispose();
}
m_SocketManager = new SocketManager();
m_SocketManager.Connect(ipEndPoint);
string firstLine = m_SocketManager.ReadLine();
if (!firstLine.StartsWith(FIRST_LINE_PREFIX)) {
this.Disconnect();
throw new InvalidDataException("Response of mpd does not start with \"" + FIRST_LINE_PREFIX + "\".");
}
this.version = firstLine.Substring(FIRST_LINE_PREFIX.Length);
//m_SocketManager.WriteLine(string.Empty);
//this.readResponse();
MpdResponse response = Exec("commands");
m_Commands = response.getValueList();
if (this.OnConnected != null)
this.OnConnected.Invoke(this);
}
/// <summary>
/// Disconnects from the current MPD server.
/// </summary>
public void Disconnect()
{
if (m_SocketManager == null)
return;
m_SocketManager.Socket.Close();
m_SocketManager.Socket.Dispose();
this.ClearConnectionFields();
if (this.OnDisconnected != null)
this.OnDisconnected.Invoke(this);
}
/// <summary>
/// Puts the client in idle mode for the given subsystems
/// </summary>
/// <param name="subsystems">The subsystems to listen to.</param>
public void Idle(Mpc.Subsystems subsystems)
{
StringBuilder subs = new StringBuilder();
foreach (Mpc.Subsystems s in Enum.GetValues(typeof(Mpc.Subsystems))){
if (s != Mpc.Subsystems.All && (subsystems & s) != 0)
subs.AppendFormat(" {0}", s.ToString());
}
string command = string.Format("idle {0}", subs.ToString());
try {
while (true){
this.CheckConnected();
m_SocketManager.WriteLine(command);
MpdResponse res = this.readResponse();
Mpc.Subsystems eventSubsystems = Mpc.Subsystems.None;
foreach (string m in res.Message){
List<string> values = res.getValueList();
foreach (string sub in values){
Mpc.Subsystems s = Mpc.Subsystems.None;
if (Enum.TryParse<Mpc.Subsystems>(sub, out s)){
eventSubsystems |= s;
}
}
}
if (eventSubsystems != Mpc.Subsystems.None && this.OnSubsystemsChanged != null)
this.OnSubsystemsChanged(this, eventSubsystems);
}
}
catch (Exception) {
try {
this.Disconnect();
}
catch (Exception) { }
}
}
/// <summary>
/// Executes a simple command without arguments on the MPD server and returns the response.
/// </summary>
/// <param name="command">The command to execute.</param>
/// <returns>The MPD server response parsed into a basic object.</returns>
/// <exception cref="ArgumentException">If the command contains a space of a newline charakter.</exception>
public MpdResponse Exec(string command)
{
if (command == null)
throw new ArgumentNullException("command");
if (command.Contains(" "))
throw new ArgumentException("command contains space");
if (command.Contains("\n"))
throw new ArgumentException("command contains newline");
//if (m_Commands != null && !m_Commands.Contains(command))
// return new MpdResponse(new ReadOnlyCollection<string>(new List<string>()));
try {
this.CheckConnected();
m_Mutex.WaitOne();
m_SocketManager.WriteLine(command);
MpdResponse res = this.readResponse();
m_Mutex.ReleaseMutex();
return res;
}
catch (Exception ex) {
System.Diagnostics.Debug.WriteLine(string.Format("Exec: {0}", ex.Message));
try {
this.Disconnect();
}
catch (Exception) { }
return new MpdResponse(new ReadOnlyCollection<string>(new List<string>()));
//throw;
}
}
/// <summary>
/// Executes a MPD command with arguments on the MPD server.
/// </summary>
/// <param name="command">The command to execute.</param>
/// <param name="argument">The arguments of the command.</param>
/// <returns>The MPD server response parsed into a basic object.</returns>
/// <exception cref="ArgumentException">If the command contains a space of a newline charakter.</exception>
public MpdResponse Exec(string command, string[] argument)
{
if (command == null)
throw new ArgumentNullException("command");
if (command.Contains(" "))
throw new ArgumentException("command contains space");
if (command.Contains("\n"))
throw new ArgumentException("command contains newline");
if (argument == null)
throw new ArgumentNullException("argument");
for (int i = 0; i < argument.Length; i++) {
if (argument[i] == null)
throw new ArgumentNullException("argument[" + i + "]");
if (argument[i].Contains("\n"))
throw new ArgumentException("argument[" + i + "] contains newline");
}
//if (m_Commands != null && !m_Commands.Contains(command))
// return new MpdResponse(new ReadOnlyCollection<string>(new List<string>()));
try {
this.CheckConnected();
m_Mutex.WaitOne();
m_SocketManager.WriteLine(string.Format("{0} {1}", command, string.Join(" ", argument)));
MpdResponse res = this.readResponse();
m_Mutex.ReleaseMutex();
return res;
}
catch (Exception) {
try { this.Disconnect(); }
catch (Exception) { }
return new MpdResponse(new ReadOnlyCollection<string>(new List<string>()));
//throw;
}
}
private void CheckConnected()
{
if (!this.Connected) {
if (this.autoConnect)
this.Connect();
else
if (this.OnDisconnected != null)
this.OnDisconnected.Invoke(this);
throw new NotConnectedException();
}
}
private void WriteToken(string token)
{
if (token.Contains(" ")) {
m_SocketManager.Write("\"");
foreach (char chr in token)
if (chr == '"')
m_SocketManager.Write("\\\"");
else
m_SocketManager.Write(chr);
}
else
m_SocketManager.Write(token);
}
private MpdResponse readResponse()
{
List<string> ret = new List<string>();
string line = m_SocketManager.ReadLine();
while (line != null && !(line.Equals(OK) || line.StartsWith(ACK))) {
ret.Add(line);
line = m_SocketManager.ReadLine();
}
if (line == null)
line = string.Empty;
if (line.Equals(OK))
return new MpdResponse(new ReadOnlyCollection<string>(ret));
else {
Match match = ACK_REGEX.Match(line);
if (match.Groups.Count != 5)
throw new InvalidDataException("Error response not as expected");
return new MpdResponse(
int.Parse(match.Result("${code}")),
int.Parse(match.Result("${nr}")),
match.Result("${command}"),
match.Result("${message}"),
new ReadOnlyCollection<string>(ret)
);
}
}
private void ClearConnectionFields()
{
m_SocketManager = null;
this.version = null;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Globalization;
using System.Security.Principal;
using System.Collections.Generic;
using System.ComponentModel;
using System.Collections;
namespace System.DirectoryServices.AccountManagement
{
[System.Diagnostics.DebuggerDisplay("Name ( {Name} )")]
abstract public class Principal : IDisposable
{
//
// Public properties
//
public override string ToString()
{
return Name;
}
// Context property
public PrincipalContext Context
{
get
{
// Make sure we're not disposed or deleted.
CheckDisposedOrDeleted();
// The only way we can't have a PrincipalContext is if we're unpersisted
Debug.Assert(_ctx != null || this.unpersisted == true);
return _ctx;
}
}
// ContextType property
public ContextType ContextType
{
get
{
// Make sure we're not disposed or deleted.
CheckDisposedOrDeleted();
// The only way we can't have a PrincipalContext is if we're unpersisted
Debug.Assert(_ctx != null || this.unpersisted == true);
if (_ctx == null)
throw new InvalidOperationException(SR.PrincipalMustSetContextForProperty);
return _ctx.ContextType;
}
}
// Description property
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private string _description = null; // the actual property value
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private LoadState _descriptionChanged = LoadState.NotSet; // change-tracking
public string Description
{
get
{
return HandleGet<string>(ref _description, PropertyNames.PrincipalDescription, ref _descriptionChanged);
}
set
{
if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.PrincipalDescription))
throw new InvalidOperationException(SR.InvalidPropertyForStore);
HandleSet<string>(ref _description, value, ref _descriptionChanged, PropertyNames.PrincipalDescription);
}
}
// DisplayName property
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private string _displayName = null; // the actual property value
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private LoadState _displayNameChanged = LoadState.NotSet; // change-tracking
public string DisplayName
{
get
{
return HandleGet<string>(ref _displayName, PropertyNames.PrincipalDisplayName, ref _displayNameChanged);
}
set
{
if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.PrincipalDisplayName))
throw new InvalidOperationException(SR.InvalidPropertyForStore);
HandleSet<string>(ref _displayName, value, ref _displayNameChanged, PropertyNames.PrincipalDisplayName);
}
}
//
// Convenience wrappers for the IdentityClaims property
// SAM Account Name
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private string _samName = null; // the actual property value
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private LoadState _samNameChanged = LoadState.NotSet; // change-tracking
public string SamAccountName
{
get
{
return HandleGet<string>(ref _samName, PropertyNames.PrincipalSamAccountName, ref _samNameChanged);
}
set
{
if (null == value || 0 == value.Length)
throw new ArgumentNullException(PropertyNames.PrincipalSamAccountName);
if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.PrincipalSamAccountName))
throw new InvalidOperationException(SR.InvalidPropertyForStore);
HandleSet<string>(ref _samName, value, ref _samNameChanged, PropertyNames.PrincipalSamAccountName);
}
}
// UPN
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private string _userPrincipalName = null; // the actual property value
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private LoadState _userPrincipalNameChanged = LoadState.NotSet; // change-tracking
public string UserPrincipalName
{
get
{
return HandleGet<string>(ref _userPrincipalName, PropertyNames.PrincipalUserPrincipalName, ref _userPrincipalNameChanged);
}
set
{
if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.PrincipalUserPrincipalName))
throw new InvalidOperationException(SR.InvalidPropertyForStore);
HandleSet<string>(ref _userPrincipalName, value, ref _userPrincipalNameChanged, PropertyNames.PrincipalUserPrincipalName);
}
}
// SID
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private SecurityIdentifier _sid = null;
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private LoadState _sidChanged = LoadState.NotSet;
public SecurityIdentifier Sid
{
get
{
return HandleGet<SecurityIdentifier>(ref _sid, PropertyNames.PrincipalSid, ref _sidChanged);
}
}
// GUID
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private Nullable<Guid> _guid = null;
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private LoadState _guidChanged = LoadState.NotSet;
public Nullable<Guid> Guid
{
get
{
return HandleGet<Nullable<Guid>>(ref _guid, PropertyNames.PrincipalGuid, ref _guidChanged);
}
}
// DistinguishedName
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private string _distinguishedName = null;
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private LoadState _distinguishedNameChanged = LoadState.NotSet;
public string DistinguishedName
{
get
{
return HandleGet<string>(ref _distinguishedName, PropertyNames.PrincipalDistinguishedName, ref _distinguishedNameChanged);
}
}
// DistinguishedName
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private string _structuralObjectClass = null;
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private LoadState _structuralObjectClassChanged = LoadState.NotSet;
public string StructuralObjectClass
{
get
{
return HandleGet<string>(ref _structuralObjectClass, PropertyNames.PrincipalStructuralObjectClass, ref _structuralObjectClassChanged);
}
}
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private string _name = null;
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private LoadState _nameChanged = LoadState.NotSet;
public string Name
{
get
{
// TODO Store should be mapping both to the same property already....
// TQ Special case to map name and SamAccountNAme to same cache variable.
// This should be removed in the future.
// Context type could be null for an unpersisted user.
// Default to the original domain behavior if a context is not set.
ContextType ct = (_ctx == null) ? ContextType.Domain : _ctx.ContextType;
if (ct == ContextType.Machine)
{
return HandleGet<string>(ref _samName, PropertyNames.PrincipalSamAccountName, ref _samNameChanged);
}
else
{
return HandleGet<string>(ref _name, PropertyNames.PrincipalName, ref _nameChanged);
}
}
set
{
if (null == value || 0 == value.Length)
throw new ArgumentNullException(PropertyNames.PrincipalName);
if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.PrincipalName))
throw new InvalidOperationException(SR.InvalidPropertyForStore);
ContextType ct = (_ctx == null) ? ContextType.Domain : _ctx.ContextType;
if (ct == ContextType.Machine)
{
HandleSet<string>(ref _samName, value, ref _samNameChanged, PropertyNames.PrincipalSamAccountName);
}
else
{
HandleSet<string>(ref _name, value, ref _nameChanged, PropertyNames.PrincipalName);
}
}
}
private ExtensionHelper _extensionHelper;
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal ExtensionHelper ExtensionHelper
{
get
{
if (null == _extensionHelper)
_extensionHelper = new ExtensionHelper(this);
return _extensionHelper;
}
}
//
// Public methods
//
public static Principal FindByIdentity(PrincipalContext context, string identityValue)
{
return FindByIdentityWithType(context, typeof(Principal), identityValue);
}
public static Principal FindByIdentity(PrincipalContext context, IdentityType identityType, string identityValue)
{
return FindByIdentityWithType(context, typeof(Principal), identityType, identityValue);
}
public void Save()
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "Entering Save");
// Make sure we're not disposed or deleted.
CheckDisposedOrDeleted();
// Make sure we're not a fake principal
CheckFakePrincipal();
// We must have a PrincipalContext to save into. This should always be the case, unless we're unpersisted
// and they never set a PrincipalContext.
if (_ctx == null)
{
Debug.Assert(this.unpersisted == true);
throw new InvalidOperationException(SR.PrincipalMustSetContextForSave);
}
// Call the appropriate operation depending on whether this is an insert or update
StoreCtx storeCtxToUse = GetStoreCtxToUse();
Debug.Assert(storeCtxToUse != null); // since we know this.ctx isn't null
if (this.unpersisted)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "Save: inserting principal of type {0} using {1}", this.GetType(), storeCtxToUse.GetType());
Debug.Assert(storeCtxToUse == _ctx.ContextForType(this.GetType()));
storeCtxToUse.Insert(this);
this.unpersisted = false; // once we persist, we're no longer in the unpersisted state
}
else
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "Save: updating principal of type {0} using {1}", this.GetType(), storeCtxToUse.GetType());
Debug.Assert(storeCtxToUse == _ctx.QueryCtx);
storeCtxToUse.Update(this);
}
}
public void Save(PrincipalContext context)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "Entering Save(Context)");
// Make sure we're not disposed or deleted.
CheckDisposedOrDeleted();
// Make sure we're not a fake principal
CheckFakePrincipal();
if (context.ContextType == ContextType.Machine || _ctx.ContextType == ContextType.Machine)
{
throw new InvalidOperationException(SR.SaveToNotSupportedAgainstMachineStore);
}
// We must have a PrincipalContext to save into. This should always be the case, unless we're unpersisted
// and they never set a PrincipalContext.
if (context == null)
{
Debug.Assert(this.unpersisted == true);
throw new InvalidOperationException(SR.NullArguments);
}
// If the user is trying to save to the same context we are already set to then just save the changes
if (context == _ctx)
{
Save();
return;
}
// If we already have a context set on this object then make sure the new
// context is of the same type.
if (context.ContextType != _ctx.ContextType)
{
Debug.Assert(this.unpersisted == true);
throw new InvalidOperationException(SR.SaveToMustHaveSamecontextType);
}
StoreCtx originalStoreCtx = GetStoreCtxToUse();
_ctx = context;
// Call the appropriate operation depending on whether this is an insert or update
StoreCtx newStoreCtx = GetStoreCtxToUse();
Debug.Assert(newStoreCtx != null); // since we know this.ctx isn't null
Debug.Assert(originalStoreCtx != null); // since we know this.ctx isn't null
if (this.unpersisted)
{
// We have an unpersisted principal so we just want to create a principal in the new store.
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "Save(context): inserting new principal of type {0} using {1}", this.GetType(), newStoreCtx.GetType());
Debug.Assert(newStoreCtx == _ctx.ContextForType(this.GetType()));
newStoreCtx.Insert(this);
this.unpersisted = false; // once we persist, we're no longer in the unpersisted state
}
else
{
// We have a principal that already exists. We need to move it to the new store.
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "Save(context): Moving principal of type {0} using {1}", this.GetType(), newStoreCtx.GetType());
// we are now saving to a new store so this principal is unpersisted.
this.unpersisted = true;
// If the user has modified the name save away the current name so
// if the move succeeds and the update fails we will move the item back to the original
// store with the original name.
bool nameModified = _nameChanged == LoadState.Changed;
string previousName = null;
if (nameModified)
{
string newName = _name;
_ctx.QueryCtx.Load(this, PropertyNames.PrincipalName);
previousName = _name;
this.Name = newName;
}
newStoreCtx.Move(originalStoreCtx, this);
try
{
this.unpersisted = false; // once we persist, we're no longer in the unpersisted state
newStoreCtx.Update(this);
}
catch (System.SystemException e)
{
try
{
GlobalDebug.WriteLineIf(GlobalDebug.Error, "Principal", "Save(context):, Update Failed (attempting to move back) Exception {0} ", e.Message);
if (nameModified)
this.Name = previousName;
originalStoreCtx.Move(newStoreCtx, this);
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "Move back succeeded");
}
catch (System.SystemException deleteFail)
{
// The move back failed. Just continue we will throw the original exception below.
GlobalDebug.WriteLineIf(GlobalDebug.Error, "Principal", "Save(context):, Move back Failed {0} ", deleteFail.Message);
}
if (e is System.Runtime.InteropServices.COMException)
throw ExceptionHelper.GetExceptionFromCOMException((System.Runtime.InteropServices.COMException)e);
else
throw e;
}
}
_ctx.QueryCtx = newStoreCtx; // so Updates go to the right StoreCtx
}
public void Delete()
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "Entering Delete");
// Make sure we're not disposed or deleted.
CheckDisposedOrDeleted();
// Make sure we're not a fake principal
CheckFakePrincipal();
// If we're unpersisted, nothing to delete
if (this.unpersisted)
throw new InvalidOperationException(SR.PrincipalCantDeleteUnpersisted);
// Since we're not unpersisted, we must have come back from a query, and the query logic would
// have filled in a PrincipalContext on us.
Debug.Assert(_ctx != null);
_ctx.QueryCtx.Delete(this);
_isDeleted = true;
}
public override bool Equals(object o)
{
Principal that = o as Principal;
if (that == null)
return false;
if (object.ReferenceEquals(this, that))
return true;
if ((_key != null) && (that._key != null) && (_key.Equals(that._key)))
return true;
return false;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public object GetUnderlyingObject()
{
// Make sure we're not disposed or deleted.
CheckDisposedOrDeleted();
// Make sure we're not a fake principal
CheckFakePrincipal();
if (this.UnderlyingObject == null)
{
throw new InvalidOperationException(SR.PrincipalMustPersistFirst);
}
return this.UnderlyingObject;
}
public Type GetUnderlyingObjectType()
{
// Make sure we're not disposed or deleted.
CheckDisposedOrDeleted();
// Make sure we're not a fake principal
CheckFakePrincipal();
if (this.unpersisted)
{
// If we're unpersisted, we can't determine the native type until our PrincipalContext has been set.
if (_ctx != null)
{
return _ctx.ContextForType(this.GetType()).NativeType(this);
}
else
{
throw new InvalidOperationException(SR.PrincipalMustSetContextForNative);
}
}
else
{
Debug.Assert(_ctx != null);
return _ctx.QueryCtx.NativeType(this);
}
}
public PrincipalSearchResult<Principal> GetGroups()
{
return new PrincipalSearchResult<Principal>(GetGroupsHelper());
}
public PrincipalSearchResult<Principal> GetGroups(PrincipalContext contextToQuery)
{
if (contextToQuery == null)
throw new ArgumentNullException(nameof(contextToQuery));
return new PrincipalSearchResult<Principal>(GetGroupsHelper(contextToQuery));
}
public bool IsMemberOf(GroupPrincipal group)
{
// Make sure we're not disposed or deleted.
CheckDisposedOrDeleted();
if (group == null)
throw new ArgumentNullException(nameof(group));
return group.Members.Contains(this);
}
public bool IsMemberOf(PrincipalContext context, IdentityType identityType, string identityValue)
{
// Make sure we're not disposed or deleted.
CheckDisposedOrDeleted();
if (context == null)
throw new ArgumentNullException(nameof(context));
if (identityValue == null)
throw new ArgumentNullException(nameof(identityValue));
GroupPrincipal g = GroupPrincipal.FindByIdentity(context, identityType, identityValue);
if (g != null)
{
return IsMemberOf(g);
}
else
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "Principal", "IsMemberOf(urn/urn): no matching principal");
throw new NoMatchingPrincipalException(SR.NoMatchingGroupExceptionText);
}
}
//
// IDisposable
//
public virtual void Dispose()
{
if (!_disposed)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "Dispose: disposing");
if ((this.UnderlyingObject != null) && (this.UnderlyingObject is IDisposable))
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "Dispose: disposing underlying object");
((IDisposable)this.UnderlyingObject).Dispose();
}
if ((this.UnderlyingSearchObject != null) && (this.UnderlyingSearchObject is IDisposable))
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "Dispose: disposing underlying search object");
((IDisposable)this.UnderlyingSearchObject).Dispose();
}
_disposed = true;
GC.SuppressFinalize(this);
}
}
//
//
//
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
protected Principal()
{
}
//------------------------------------------------
// Protected functions for use by derived classes.
//------------------------------------------------
// Stores all values from derived classes for use at attributes or search filter.
private ExtensionCache _extensionCache = new ExtensionCache();
private LoadState _extensionCacheChanged = LoadState.NotSet;
protected object[] ExtensionGet(string attribute)
{
if (null == attribute)
throw new ArgumentException(SR.NullArguments);
ExtensionCacheValue val;
if (_extensionCache.TryGetValue(attribute, out val))
{
if (val.Filter)
{
return null;
}
return val.Value;
}
else if (this.unpersisted)
{
return Array.Empty<object>();
}
else
{
Debug.Assert(this.GetUnderlyingObjectType() == typeof(DirectoryEntry));
DirectoryEntry de = (DirectoryEntry)this.GetUnderlyingObject();
int valCount = de.Properties[attribute].Count;
if (valCount == 0)
return Array.Empty<object>();
else
{
object[] objectArray = new object[valCount];
de.Properties[attribute].CopyTo(objectArray, 0);
return objectArray;
}
}
}
private void ValidateExtensionObject(object value)
{
if (value is object[])
{
if (((object[])value).Length == 0)
throw new ArgumentException(SR.InvalidExtensionCollectionType);
foreach (object o in (object[])value)
{
if (o is ICollection)
throw new ArgumentException(SR.InvalidExtensionCollectionType);
}
}
if (value is byte[])
{
if (((byte[])value).Length == 0)
{
throw new ArgumentException(SR.InvalidExtensionCollectionType);
}
}
else
{
if (value != null && value is ICollection)
{
ICollection collection = (ICollection)value;
if (collection.Count == 0)
throw new ArgumentException(SR.InvalidExtensionCollectionType);
foreach (object o in collection)
{
if (o is ICollection)
throw new ArgumentException(SR.InvalidExtensionCollectionType);
}
}
}
}
protected void ExtensionSet(string attribute, object value)
{
if (null == attribute)
throw new ArgumentException(SR.NullArguments);
ValidateExtensionObject(value);
if (value is object[])
_extensionCache.properties[attribute] = new ExtensionCacheValue((object[])value);
else
_extensionCache.properties[attribute] = new ExtensionCacheValue(new object[] { value });
_extensionCacheChanged = LoadState.Changed;
}
internal void AdvancedFilterSet(string attribute, object value, Type objectType, MatchType mt)
{
if (null == attribute)
throw new ArgumentException(SR.NullArguments);
ValidateExtensionObject(value);
if (value is object[])
_extensionCache.properties[attribute] = new ExtensionCacheValue((object[])value, objectType, mt);
else
_extensionCache.properties[attribute] = new ExtensionCacheValue(new object[] { value }, objectType, mt);
_extensionCacheChanged = LoadState.Changed; ;
}
//
// Internal implementation
//
// True indicates this is a new Principal object that has not yet been persisted to the store
internal bool unpersisted = false;
// True means our store object has been deleted
private bool _isDeleted = false;
// True means that StoreCtx.Load() has been called on this Principal to load in the values
// of all the delay-loaded properties.
private bool _loaded = false;
// True means this principal corresponds to one of the well-known SIDs that do not have a
// corresponding store object (e.g., NT AUTHORITY\NETWORK SERVICE). Such principals
// should be treated as read-only.
internal bool fakePrincipal = false;
// Directly corresponds to the Principal.PrincipalContext public property
private PrincipalContext _ctx = null;
internal bool Loaded
{
set
{
_loaded = value;
}
get
{
return _loaded;
}
}
// A low-level way for derived classes to access the ctx field. Note this is intended for internal use only,
// hence the LinkDemand.
[System.ComponentModel.Browsable(false)]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
internal protected PrincipalContext ContextRaw
{
get
{ return _ctx; }
set
{
// Verify that the passed context is not disposed.
if (value != null)
value.CheckDisposed();
_ctx = value;
}
}
static internal Principal MakePrincipal(PrincipalContext ctx, Type principalType)
{
Principal p = null;
System.Reflection.ConstructorInfo CI = principalType.GetConstructor(new Type[] { typeof(PrincipalContext) });
if (null == CI)
{
throw new NotSupportedException(SR.ExtensionInvalidClassDefinitionConstructor);
}
p = (Principal)CI.Invoke(new object[] { ctx });
if (null == p)
{
throw new NotSupportedException(SR.ExtensionInvalidClassDefinitionConstructor);
}
p.unpersisted = false;
return p;
}
// Depending on whether we're to-be-inserted or were retrieved from a query,
// returns the appropriate StoreCtx from the PrincipalContext that we should use for
// all StoreCtx-related operations.
// Returns null if no context has been set yet.
internal StoreCtx GetStoreCtxToUse()
{
if (_ctx == null)
{
Debug.Assert(this.unpersisted == true);
return null;
}
if (this.unpersisted)
{
return _ctx.ContextForType(this.GetType());
}
else
{
return _ctx.QueryCtx;
}
}
// The underlying object (e.g., DirectoryEntry, Item) corresponding to this Principal.
// Set by StoreCtx.GetAsPrincipal when this Principal was instantiated by it.
// If not set, this is a unpersisted principal and StoreCtx.PushChangesToNative()
// has not yet been called on it
private object _underlyingObject = null;
internal object UnderlyingObject
{
get
{
if (_underlyingObject != null)
return _underlyingObject;
return null;
}
set
{
_underlyingObject = value;
}
}
// The underlying search object (e.g., SearcResult, Item) corresponding to this Principal.
// Set by StoreCtx.GetAsPrincipal when this Principal was instantiated by it.
// If not set, this object was not created from a search. We need to store the searchresult until the object is persisted because
// we may need to load properties from it.
private object _underlyingSearchObject = null;
internal object UnderlyingSearchObject
{
get
{
if (_underlyingSearchObject != null)
return _underlyingSearchObject;
return null;
}
set
{
_underlyingSearchObject = value;
}
}
// Optional. This property exists entirely for the use of the StoreCtxs. When UnderlyingObject
// can correspond to more than one possible principal in the store (e.g., WinFS's "multiple principals
// per contact" model), the StoreCtx can use this to track and discern which principal in the
// UnderlyingObject this Principal object corresponds to. Set by GetAsPrincipal(), if set at all.
private object _discriminant = null;
internal object Discriminant
{
get { return _discriminant; }
set { _discriminant = value; }
}
// A store-specific key, used to determine if two CLR Principal objects represent the same store principal.
// Set by GetAsPrincipal when Principal is created from a query, or when a unpersisted Principal is persisted.
private StoreKey _key = null;
internal StoreKey Key
{
get { return _key; }
set { _key = value; }
}
private bool _disposed = false;
// Checks if the principal has been disposed or deleted, and throws an appropriate exception if it has.
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
protected void CheckDisposedOrDeleted()
{
if (_disposed)
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "Principal", "CheckDisposedOrDeleted: accessing disposed object");
throw new ObjectDisposedException(this.GetType().ToString());
}
if (_isDeleted)
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "Principal", "CheckDisposedOrDeleted: accessing deleted object");
throw new InvalidOperationException(SR.PrincipalDeleted);
}
}
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
protected static Principal FindByIdentityWithType(PrincipalContext context, Type principalType, string identityValue)
{
if (context == null)
throw new ArgumentNullException(nameof(context));
if (identityValue == null)
throw new ArgumentNullException(nameof(identityValue));
return FindByIdentityWithTypeHelper(context, principalType, null, identityValue, DateTime.UtcNow);
}
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
protected static Principal FindByIdentityWithType(PrincipalContext context, Type principalType, IdentityType identityType, string identityValue)
{
if (context == null)
throw new ArgumentNullException(nameof(context));
if (identityValue == null)
throw new ArgumentNullException(nameof(identityValue));
if ((identityType < IdentityType.SamAccountName) || (identityType > IdentityType.Guid))
throw new InvalidEnumArgumentException(nameof(identityType), (int)identityType, typeof(IdentityType));
return FindByIdentityWithTypeHelper(context, principalType, identityType, identityValue, DateTime.UtcNow);
}
private static Principal FindByIdentityWithTypeHelper(PrincipalContext context, Type principalType, Nullable<IdentityType> identityType, string identityValue, DateTime refDate)
{
// Ask the store to find a Principal based on this IdentityReference info.
Principal p = context.QueryCtx.FindPrincipalByIdentRef(principalType, (identityType == null) ? null : (string)IdentMap.StringMap[(int)identityType, 1], identityValue, refDate);
// Did we find a match?
if (p != null)
{
// Given the native object, ask the StoreCtx to construct a Principal object for us.
return p;
}
else
{
// No match.
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "Principal", "FindByIdentityWithTypeHelper: no match");
return null;
}
}
private ResultSet GetGroupsHelper()
{
// Make sure we're not disposed or deleted.
CheckDisposedOrDeleted();
// Unpersisted principals are not members of any group
if (this.unpersisted)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "GetGroupsHelper: returning empty set");
return new EmptySet();
}
StoreCtx storeCtx = GetStoreCtxToUse();
Debug.Assert(storeCtx != null);
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "GetGroupsHelper: querying");
ResultSet resultSet = storeCtx.GetGroupsMemberOf(this);
return resultSet;
}
private ResultSet GetGroupsHelper(PrincipalContext contextToQuery)
{
// Make sure we're not disposed or deleted.
CheckDisposedOrDeleted();
if (_ctx == null)
throw new InvalidOperationException(SR.UserMustSetContextForMethod);
StoreCtx storeCtx = GetStoreCtxToUse();
Debug.Assert(storeCtx != null);
return contextToQuery.QueryCtx.GetGroupsMemberOf(this, storeCtx);
}
// If we're the result of a query and our properties haven't been loaded yet, do so now
// We'd like this to be marked protected AND internal, but that's not possible, so we'll settle for
// internal and treat it as if it were also protected.
internal void LoadIfNeeded(string principalPropertyName)
{
// Fake principals have nothing to load, since they have no store object.
// Just set the loaded flag.
if (this.fakePrincipal)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "LoadIfNeeded: not needed, fake principal");
Debug.Assert(this.unpersisted == false);
}
else if (!this.unpersisted)
{
// We came back from a query --> our PrincipalContext must be filled in
Debug.Assert(_ctx != null);
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "LoadIfNeeded: loading");
// Just load the requested property...
_ctx.QueryCtx.Load(this, principalPropertyName);
}
}
// Checks if this is a fake principal, and throws an appropriate exception if so.
// We'd like this to be marked protected AND internal, but that's not possible, so we'll settle for
// internal and treat it as if it were also protected.
internal void CheckFakePrincipal()
{
if (this.fakePrincipal)
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "Principal", "CheckFakePrincipal: fake principal");
throw new InvalidOperationException(SR.PrincipalNotSupportedOnFakePrincipal);
}
}
// These methods implement the logic shared by all the get/set accessors for the public properties.
// We pass currentValue by ref, even though we don't directly modify it, because if the LoadIfNeeded()
// call causes the data to be loaded, we need to pick up the post-load value, not the (empty) value at the point
// HandleGet<T> was called.
//
// We'd like this to be marked protected AND internal, but that's not possible, so we'll settle for
// internal and treat it as if it were also protected.
internal T HandleGet<T>(ref T currentValue, string name, ref LoadState state)
{
// Make sure we're not disposed or deleted.
CheckDisposedOrDeleted();
// Check that we actually support this propery in our store
//CheckSupportedProperty(name);
if (state == LoadState.NotSet)
{
// Load in the value, if not yet done so
LoadIfNeeded(name);
state = LoadState.Loaded;
}
return currentValue;
}
// We'd like this to be marked protected AND internal, but that's not possible, so we'll settle for
// internal and treat it as if it were also protected.
internal void HandleSet<T>(ref T currentValue, T newValue, ref LoadState state, string name)
{
// Make sure we're not disposed or deleted.
CheckDisposedOrDeleted();
// Check that we actually support this propery in our store
//CheckSupportedProperty(name);
// Need to do this now so that newly-set value doesn't get overwritten by later load
// LoadIfNeeded(name);
currentValue = newValue;
state = LoadState.Changed;
}
//
// Load/Store implementation
//
//
// Loading with query results
//
// Given a property name like "Principal.DisplayName",
// writes the value into the internal field backing that property and
// resets the change-tracking for that property to "unchanged".
//
// If the property is a scalar property, then value is simply an object of the property type
// (e.g., a string for a string-valued property).
// If the property is an IdentityClaimCollection property, then value must be a List<IdentityClaim>.
// If the property is a ValueCollection<T>, then value must be a List<T>.
// If the property is a X509Certificate2Collection, then value must be a List<byte[]>, where
// each byte[] is a certificate.
// (The property can never be a PrincipalCollection, since such properties
// are not loaded by StoreCtx.Load()).
// ExtensionCache is never directly loaded by the store hence it does not exist in the switch
internal virtual void LoadValueIntoProperty(string propertyName, object value)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "LoadValueIntoProperty: name=" + propertyName + " value=" + (value == null ? "null" : value.ToString()));
switch (propertyName)
{
case PropertyNames.PrincipalDisplayName:
_displayName = (string)value;
_displayNameChanged = LoadState.Loaded;
break;
case PropertyNames.PrincipalDescription:
_description = (string)value;
_descriptionChanged = LoadState.Loaded;
break;
case PropertyNames.PrincipalSamAccountName:
_samName = (string)value;
_samNameChanged = LoadState.Loaded;
break;
case PropertyNames.PrincipalUserPrincipalName:
_userPrincipalName = (string)value;
_userPrincipalNameChanged = LoadState.Loaded;
break;
case PropertyNames.PrincipalSid:
SecurityIdentifier SID = (SecurityIdentifier)value;
_sid = SID;
_sidChanged = LoadState.Loaded;
break;
case PropertyNames.PrincipalGuid:
Guid PrincipalGuid = (Guid)value;
_guid = PrincipalGuid;
_guidChanged = LoadState.Loaded;
break;
case PropertyNames.PrincipalDistinguishedName:
_distinguishedName = (string)value;
_distinguishedNameChanged = LoadState.Loaded;
break;
case PropertyNames.PrincipalStructuralObjectClass:
_structuralObjectClass = (string)value;
_structuralObjectClassChanged = LoadState.Loaded;
break;
case PropertyNames.PrincipalName:
_name = (string)value;
_nameChanged = LoadState.Loaded;
break;
default:
// If we're here, we didn't find the property. They probably asked for a property we don't
// support (e.g., we're a Group, and they asked for PropertyNames.UserEmailAddress).
break;
}
}
//
// Getting changes to persist (or to build a query from a QBE filter)
//
// Given a property name, returns true if that property has changed since it was loaded, false otherwise.
internal virtual bool GetChangeStatusForProperty(string propertyName)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "GetChangeStatusForProperty: name=" + propertyName);
LoadState currentPropState;
switch (propertyName)
{
case PropertyNames.PrincipalDisplayName:
currentPropState = _displayNameChanged;
break;
case PropertyNames.PrincipalDescription:
currentPropState = _descriptionChanged;
break;
case PropertyNames.PrincipalSamAccountName:
currentPropState = _samNameChanged;
break;
case PropertyNames.PrincipalUserPrincipalName:
currentPropState = _userPrincipalNameChanged;
break;
case PropertyNames.PrincipalSid:
currentPropState = _sidChanged;
break;
case PropertyNames.PrincipalGuid:
currentPropState = _guidChanged;
break;
case PropertyNames.PrincipalDistinguishedName:
currentPropState = _distinguishedNameChanged;
break;
case PropertyNames.PrincipalStructuralObjectClass:
currentPropState = _structuralObjectClassChanged;
break;
case PropertyNames.PrincipalName:
currentPropState = _nameChanged;
break;
case PropertyNames.PrincipalExtensionCache:
currentPropState = _extensionCacheChanged;
break;
default:
// If we're here, we didn't find the property. They probably asked for a property we don't
// support (e.g., we're a User, and they asked for PropertyNames.GroupMembers). Since we don't
// have it, it didn't change.
currentPropState = LoadState.NotSet;
break;
}
return (currentPropState == LoadState.Changed);
}
// Given a property name, returns the current value for the property.
// Generally, this method is called only if GetChangeStatusForProperty indicates there are changes on the
// property specified.
//
// If the property is a scalar property, the return value is an object of the property type.
// If the property is an IdentityClaimCollection property, the return value is the IdentityClaimCollection
// itself.
// If the property is a ValueCollection<T>, the return value is the ValueCollection<T> itself.
// If the property is a X509Certificate2Collection, the return value is the X509Certificate2Collection itself.
// If the property is a PrincipalCollection, the return value is the PrincipalCollection itself.
internal virtual object GetValueForProperty(string propertyName)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "GetValueForProperty: name=" + propertyName);
switch (propertyName)
{
case PropertyNames.PrincipalDisplayName:
return _displayName;
case PropertyNames.PrincipalDescription:
return _description;
case PropertyNames.PrincipalSamAccountName:
return _samName;
case PropertyNames.PrincipalUserPrincipalName:
return _userPrincipalName;
case PropertyNames.PrincipalSid:
return _sid;
case PropertyNames.PrincipalGuid:
return _guid;
case PropertyNames.PrincipalDistinguishedName:
return _distinguishedName;
case PropertyNames.PrincipalStructuralObjectClass:
return _structuralObjectClass;
case PropertyNames.PrincipalName:
return _name;
case PropertyNames.PrincipalExtensionCache:
return _extensionCache;
default:
Debug.Fail($"Principal.GetValueForProperty: Ran off end of list looking for {propertyName}");
return null;
}
}
// Reset all change-tracking status for all properties on the object to "unchanged".
// This is used by StoreCtx.Insert() and StoreCtx.Update() to reset the change-tracking after they
// have persisted all current changes to the store.
internal virtual void ResetAllChangeStatus()
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "ResetAllChangeStatus");
_displayNameChanged = (_displayNameChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_descriptionChanged = (_descriptionChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_samNameChanged = (_samNameChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_userPrincipalNameChanged = (_userPrincipalNameChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_sidChanged = (_sidChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_guidChanged = (_guidChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_distinguishedNameChanged = (_distinguishedNameChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_nameChanged = (_nameChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_extensionCacheChanged = (_extensionCacheChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2007 Charlie Poole
//
// 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.Collections;
using NUnit.Framework;
namespace NUnitLite
{
public class TestCase : ITest
{
#region Instance Variables
private string name;
private string fullName;
private object fixture;
private MethodInfo method;
private MethodInfo setup;
private MethodInfo teardown;
private RunState runState = RunState.Runnable;
private string ignoreReason;
private IDictionary properties;
#endregion
#region Constructors
public TestCase(string name)
{
this.name = this.fullName = name;
}
public TestCase(MethodInfo method)
{
Initialize(method, null);
}
public TestCase(string name, object fixture)
{
Initialize(fixture.GetType().GetMethod(name), fixture);
}
private void Initialize(MethodInfo method, object fixture)
{
this.name = method.Name;
this.method = method;
this.fullName = method.ReflectedType.FullName + "." + name;
this.fixture = fixture;
if ( fixture == null )
this.fixture = Reflect.Construct(method.ReflectedType, null);
if (!HasValidSignature(method))
{
this.runState = RunState.NotRunnable;
this.ignoreReason = "Test methods must have signature void MethodName()";
}
else
{
IgnoreAttribute ignore = (IgnoreAttribute)Reflect.GetAttribute(this.method, typeof(IgnoreAttribute));
if (ignore != null)
{
this.runState = RunState.Ignored;
this.ignoreReason = ignore.Reason;
}
}
foreach (MethodInfo m in method.ReflectedType.GetMethods())
{
if (Reflect.HasAttribute(m, typeof(SetUpAttribute)))
this.setup = m;
if (Reflect.HasAttribute(m, typeof(TearDownAttribute)))
this.teardown = m;
}
}
#endregion
#region Properties
public string Name
{
get { return name; }
}
public string FullName
{
get { return fullName; }
}
public RunState RunState
{
get { return runState; }
}
public string IgnoreReason
{
get { return ignoreReason; }
}
public System.Collections.IDictionary Properties
{
get
{
if (properties == null)
{
properties = new Hashtable();
object[] attrs = this.method.GetCustomAttributes(typeof(PropertyAttribute), true);
foreach (PropertyAttribute attr in attrs)
foreach( DictionaryEntry entry in attr.Properties )
this.Properties[entry.Key] = entry.Value;
}
return properties;
}
}
public int TestCaseCount
{
get { return 1; }
}
#endregion
#region Public Methods
public static bool IsTestMethod(MethodInfo method)
{
return Reflect.HasAttribute(method, typeof(TestAttribute));
}
public TestResult Run()
{
return Run( new NullListener() );
}
public TestResult Run(ITestListener listener)
{
listener.TestStarted(this);
TestResult result = new TestResult(this);
Run(result, listener);
listener.TestFinished(result);
return result;
}
#endregion
#region Protected Methods
protected virtual void SetUp()
{
if (setup != null)
{
Assert.That(HasValidSetUpTearDownSignature(setup), "Invalid SetUp method: must return void and have no arguments");
InvokeMethod(setup);
}
}
protected virtual void TearDown()
{
if (teardown != null)
{
Assert.That(HasValidSetUpTearDownSignature(teardown), "Invalid TearDown method: must return void and have no arguments");
InvokeMethod(teardown);
}
}
protected virtual void Run(TestResult result, ITestListener listener)
{
IgnoreAttribute ignore = (IgnoreAttribute)Reflect.GetAttribute(method, typeof(IgnoreAttribute));
if (this.RunState == RunState.NotRunnable)
result.Failure(this.ignoreReason);
else if ( ignore != null )
result.NotRun(ignore.Reason);
else
{
try
{
RunBare();
result.Success();
}
catch (NUnitLiteException nex)
{
result.RecordException(nex.InnerException);
}
#if !NETCF_1_0
catch (System.Threading.ThreadAbortException)
{
throw;
}
#endif
catch (Exception ex)
{
result.RecordException(ex);
}
}
}
protected void RunBare()
{
SetUp();
try
{
RunTest();
}
finally
{
TearDown();
}
}
protected virtual void RunTest()
{
try
{
InvokeMethod( this.method );
ProcessNoException(this.method);
}
catch (NUnitLiteException ex)
{
ProcessException(this.method, ex.InnerException);
}
}
protected void InvokeMethod(MethodInfo method, params object[] args)
{
Reflect.InvokeMethod(method, this.fixture, args);
}
#endregion
#region Private Methods
public static bool HasValidSignature(MethodInfo method)
{
return method != null
&& method.ReturnType == typeof(void)
&& method.GetParameters().Length == 0; ;
}
private static bool HasValidSetUpTearDownSignature(MethodInfo method)
{
return method.ReturnType == typeof(void)
&& method.GetParameters().Length == 0; ;
}
private static void ProcessNoException(MethodInfo method)
{
ExpectedExceptionAttribute exceptionAttribute =
(ExpectedExceptionAttribute)Reflect.GetAttribute(method, typeof(ExpectedExceptionAttribute));
if (exceptionAttribute != null)
Assert.Fail("Expected Exception of type <{0}>, but none was thrown", exceptionAttribute.ExceptionType);
}
private void ProcessException(MethodInfo method, Exception caughtException)
{
ExpectedExceptionAttribute exceptionAttribute =
(ExpectedExceptionAttribute)Reflect.GetAttribute(method, typeof(ExpectedExceptionAttribute));
if (exceptionAttribute == null)
throw new NUnitLiteException("", caughtException);
Type expectedType = exceptionAttribute.ExceptionType;
if ( expectedType != null && expectedType != caughtException.GetType() )
Assert.Fail("Expected Exception of type <{0}>, but was <{1}>", exceptionAttribute.ExceptionType, caughtException.GetType());
MethodInfo handler = GetExceptionHandler(method.ReflectedType, exceptionAttribute.Handler);
if (handler != null)
InvokeMethod( handler, caughtException );
}
private MethodInfo GetExceptionHandler(Type type, string handlerName)
{
if (handlerName == null && Reflect.HasInterface( type, typeof(IExpectException) ) )
handlerName = "HandleException";
if (handlerName == null)
return null;
MethodInfo handler = Reflect.GetMethod( type, handlerName,
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static,
new Type[] { typeof(Exception) });
if (handler == null)
Assert.Fail("The specified exception handler {0} was not found", handlerName);
return handler;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using Microsoft.Win32;
namespace Universe.SqlTrace.LocalInstances
{
public class LocalInstancesDiscovery
{
/*
static LocalInstancesDiscovery()
{
try
{
LocalInstanceInfo i = new LocalInstanceInfo();
StringBuilder dump = new StringBuilder();
var stringWriter = new StringWriter(dump);
i.WriteToXml(stringWriter);
Trace.WriteLine("");
}
catch (Exception)
{
}
}
*/
public static LocalInstanceInfo GetFull(TimeSpan timeout)
{
LocalInstanceInfo ret = new LocalInstanceInfo();
GetList(ret);
BuildDescription(ret, timeout);
ret.SortByVersionDescending();
return ret;
}
public static LocalInstanceInfo Get()
{
LocalInstanceInfo ret = new LocalInstanceInfo();
GetList(ret);
var filtered = new List<LocalInstanceInfo.SqlInstance>();
foreach (LocalInstanceInfo.SqlInstance i in ret.Instances)
{
string path;
Version version;
ServiceControllerStatus status;
if (TryService(LocalInstanceInfo.GetServiceKey(i.Name), out path, out version, out status))
{
i.Status = status;
filtered.Add(i);
}
}
ret.Instances.Clear();
ret.Instances.AddRange(filtered);
ret.SortByVersionDescending();
return ret;
}
private static void GetList(LocalInstanceInfo ret)
{
using (RegistryKey lm = Registry.LocalMachine)
{
// default instance
using (RegistryKey k0 = lm.OpenSubKey(@"SOFTWARE\Microsoft\MSSQLServer"))
if (k0 != null)
TryKey(k0, ret, string.Empty);
// named instances
using (RegistryKey k1 = lm.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server", false))
if (k1 != null)
foreach (string subKeyName in new List<string>(k1.GetSubKeyNames() ?? new string[0]))
using (RegistryKey candidate = k1.OpenSubKey(subKeyName))
if (candidate != null)
TryKey(candidate, ret, subKeyName);
}
}
private static void TryKey(RegistryKey k1, LocalInstanceInfo ret, string instanceName)
{
string rawVersion = null;
using (RegistryKey rk = k1.OpenSubKey(@"MSSQLServer\CurrentVersion", false))
if (rk != null)
rawVersion = rk.GetValue("CurrentVersion") as string;
/*
string rawPath = null;
using (RegistryKey rk = k1.OpenSubKey(@"Setup", false))
if (rk != null)
rawPath = rk.GetValue("SQLPath") as string;
*/
if (!string.IsNullOrEmpty(rawVersion) /* && rawPath != null && Directory.Exists(rawPath) */)
{
try
{
Version ver = new Version(rawVersion);
var i = new LocalInstanceInfo.SqlInstance(instanceName);
i.FileVer = ver;
ret.Instances.Add(i);
}
catch
{
}
}
}
static void BuildDescription(LocalInstanceInfo info, TimeSpan timeout)
{
if (info.Instances.Count > 0)
{
List<ManualResetEvent> events = new List<ManualResetEvent>();
foreach (LocalInstanceInfo.SqlInstance instance in info.Instances)
{
// description
LocalInstanceInfo.SqlInstance sqlInstance = instance;
ManualResetEvent ev = new ManualResetEvent(false);
events.Add(ev);
ThreadPool.QueueUserWorkItem(
delegate
{
try
{
// Console.WriteLine(i2.FullLocalName + ": " + Thread.CurrentThread.ManagedThreadId);
// Thread.Sleep(3000);
string fullPath;
Version productVersion;
ServiceControllerStatus status;
if (TryService(LocalInstanceInfo.GetServiceKey(sqlInstance.Name), out fullPath, out productVersion, out status))
{
sqlInstance.Status = status;
sqlInstance.Ver = productVersion;
if (sqlInstance.Status == ServiceControllerStatus.Running)
{
string cs = "Data Source=" + sqlInstance.FullLocalName + ";Integrated Security=SSPI;Pooling=False;";
using (SqlConnection con = new SqlConnection(cs))
using (SqlCommand cmd = new SqlCommand("Select @@version, SERVERPROPERTY('ProductLevel'), SERVERPROPERTY('Edition')", con))
{
cmd.CommandTimeout = (int) timeout.TotalSeconds;
con.Open();
using (SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
if (rdr.Read())
{
string description = (string) rdr.GetString(0);
string level = (string) rdr.GetString(1);
string edition = (string) rdr.GetString(2);
description =
description.Replace("\t", " ").Replace("\r", " ").Replace("\n", " ");
while (description.IndexOf(" ") >= 0)
description = description.Replace(" ", " ");
sqlInstance.IsOK = true;
sqlInstance.Description = description;
sqlInstance.Level = level;
bool isExpress =
edition.IndexOf("Desktop Engine") >= 0
|| edition.IndexOf("Express Edition") >= 0;
sqlInstance.Edition = isExpress ? SqlEdition.Express : SqlEdition.LeastStandard;
}
}
}
}
}
}
catch (Exception ex)
{
Debug.WriteLine(
"Failed to connect to " + sqlInstance.FullLocalName + ". See Details Below" + Environment.NewLine +
ex + Environment.NewLine);
}
finally
{
ev.Set();
}
});
} // done: description
WaitHandle.WaitAll(events.ToArray());
List<LocalInstanceInfo.SqlInstance> normal = info.Instances.FindAll(delegate(LocalInstanceInfo.SqlInstance i) { return i.Ver != null; });
info.Instances.Clear();
info.Instances.AddRange(normal);
}
}
private static bool TryService(string serviceKey, out string fullPath, out Version productVersion, out ServiceControllerStatus status)
{
fullPath = null;
productVersion = null;
status = 0;
try
{
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Services\" + serviceKey, false))
{
if (key != null)
{
object obj2 = key.GetValue("ImagePath");
string fp = (obj2 == null) ? null : obj2.ToString().Trim(new char[] { ' ' });
if (!string.IsNullOrEmpty(fp))
{
if (fp.StartsWith("\""))
{
int p = fp.IndexOf('\"', 1);
if (p >= 0)
fp = fp.Substring(1, p - 1);
}
else
{
// MSDE FIX
int p2 = fp.LastIndexOf(' ');
if (p2 > 0 && p2 < fp.Length - 1 && fp.Substring(p2).Trim().StartsWith("-s"))
{
string tryFp = fp.Substring(0, p2);
if (File.Exists(tryFp))
fp = tryFp;
}
}
fullPath = fp;
productVersion = new Version(FileVersionInfo.GetVersionInfo(fullPath).ProductVersion);
}
}
}
if (fullPath == null)
return false;
ServiceController controller = new ServiceController(serviceKey);
try
{
controller.Refresh();
status = controller.Status;
return true;
}
catch(InvalidOperationException ex)
{
Win32Exception iex = ex.InnerException as Win32Exception;
if (iex != null && iex.NativeErrorCode == 1060)
return false;
else throw;
}
}
catch(Exception ex)
{
Debug.WriteLine("Failed to get info of service " + serviceKey + ". See Details Below" + Environment.NewLine + ex + Environment.NewLine);
return false;
}
}
}
}
| |
using ObjCRuntime;
using System;
namespace Estimote
{
using ObjCRuntime;
public enum Color
{
Unknown,
MintCocktail,
IcyMarshmallow,
BlueberryPie,
SweetBeetroot,
CandyFloss,
LemonTart,
VanillaJello,
LiquoriceSwirl,
White,
Black,
Transparent
}
public enum FirmwareUpdate
{
None,
Available,
Unsupported
}
public enum ConnectionStatus
{
Disconnected,
Connecting,
Connected,
Updating
}
public enum BroadcastingScheme : sbyte
{
Unknown,
Estimote,
IBeacon,
EddystoneURL,
EddystoneUID
}
[Native]
public enum NearableType : long
{
Unknown = 0,
Dog,
Car,
Fridge,
Bag,
Bike,
Chair,
Bed,
Door,
Shoe,
Generic,
All
}
[Native]
public enum NearableOrientation : long
{
Unknown = 0,
Horizontal,
HorizontalUpsideDown,
Vertical,
VerticalUpsideDown,
LeftSide,
RightSide
}
[Native]
public enum NearableZone : long
{
Unknown = 0,
Immediate,
Near,
Far
}
[Native]
public enum NearableFirmwareState : long
{
Boot = 0,
App
}
public enum BeaconPower : sbyte
{
BeaconPowerLevel1 = -30,
BeaconPowerLevel2 = -20,
BeaconPowerLevel3 = -16,
BeaconPowerLevel4 = -12,
BeaconPowerLevel5 = -8,
BeaconPowerLevel6 = -4,
BeaconPowerLevel7 = 0,
BeaconPowerLevel8 = 4
}
public enum BeaconBatteryType
{
Unknown = 0,
Cr2450,
Cr2477
}
[Native]
public enum BeaconFirmwareState : long
{
Boot,
App
}
[Native]
public enum BeaconPowerSavingMode : long
{
Unknown,
Unsupported,
On,
Off
}
[Native]
public enum BeaconEstimoteSecureUUID : long
{
Unknown,
Unsupported,
On,
Off
}
[Native]
public enum BeaconMotionUUID : long
{
Unknown,
Unsupported,
On,
Off
}
[Native]
public enum BeaconMotionState : long
{
Unknown,
Unsupported,
Moving,
NotMoving
}
[Native]
public enum BeaconTemperatureState : long
{
Unknown,
Unsupported,
Supported
}
[Native]
public enum BeaconMotionDetection : long
{
Unknown,
Unsupported,
On,
Off
}
[Native]
public enum BeaconConditionalBroadcasting : long
{
Unknown,
Unsupported,
Off,
MotionOnly,
FlipToStop
}
[Native]
public enum BeaconCharInfoType : long
{
Read,
Only
}
public enum Connection : uint
{
InternetConnectionError,
IdentifierMissingError,
NotAuthorizedError,
NotConnectedToReadWrite
}
[Native]
public enum UtilitManagerState : long
{
Idle,
Scanning
}
[Native]
public enum Notification : long
{
SaveNearableZoneDescription,
SaveNearable,
BeaconEnterRegion,
BeaconExitRegion,
NearableEnterRegion,
NearableExitRegion,
RangeNearables
}
[Native]
public enum BeaconUpdateInfoStatus : long
{
Idle,
ReadyToUpdate,
Updating,
UpdateSuccess,
UpdateFailed
}
[Native]
public enum BulkUpdaterStatus : long
{
Idle,
Updating,
Completed
}
[Native]
public enum BulkUpdaterMode : long
{
Foreground,
Background
}
[Native]
public enum EddystoneProximity : long
{
Unknown,
Immediate,
Near,
Far
}
[Native]
public enum EddystoneManagerState : long
{
Idle,
Scanning
}
[Native]
public enum BeaconManagerError : long
{
InvalidRegion = 1,
LocationServicesUnauthorized
}
[Native]
public enum NearableDeviceError : long
{
DeviceNotConnected,
ConnectionOwnershipVerificationFail,
DisconnectDuringConnection,
ConnectionVersionReadFailed,
SettingNotSupported,
SettingWriteValueMissing,
ConnectionCloudConfirmationFailed,
UpdateNotAvailable,
FailedToDownloadFirmware,
FailedToConfirmUpdate
}
[Native]
public enum GPIOConfigError : long
{
ValueNotAllowed = 1
}
public enum GPIOConfig : byte
{
InputNoPull = 0,
InputPullDown = 1,
InputPullUp = 2,
Output = 3,
Uart = 4
}
[Native]
public enum GPIOPort : long
{
Port0,
Port1
}
[Native]
public enum GPIOPortsDataError : long
{
Port,
Value
}
[Native]
public enum GPIOPortValue : long
{
Unknown = -1,
Low = 0,
High = 1
}
[Native]
public enum AnalyticsEventType : long
{
EnterRegion,
ExitRegion,
InFar,
InNear,
InImmediate,
InUnknown
}
[Native]
public enum SettingOperationType : long
{
Read,
Write
}
[Native]
public enum SettingStorageType : ulong
{
DeviceCloud,
CloudOnly,
DeviceOnly
}
public enum LogLevel
{
None,
Error,
Warning,
Debug,
Info,
Verbose
}
public enum EddystoneTLMPower : sbyte
{
Level1 = -30,
Level2 = -20,
Level3 = -16,
Level4 = -12,
Level5 = -8,
Level6 = -4,
Level7 = 0,
Level8 = 4
}
[Native]
public enum BulkUpdaterDeviceUpdateStatus : long
{
Unknown,
Scanning,
PendingUpdate,
Updating,
Succeeded,
Failed
}
[Native]
public enum PeripheralFirmwareState : long
{
Unknown,
Boot,
App
}
[Native]
public enum BeaconPublicDetailsFields : ulong
{
AllFields = 1 << 0,
FieldMac = 1 << 1,
FieldColor = 1 << 2,
FieldPublicIdentifier = 1 << 3,
AllSettings = 1 << 4,
FieldPower = 1 << 5,
FieldSecurity = 1 << 6,
FieldBroadcastingScheme = 1 << 7,
FieldUUIDMajorMinor = 1 << 8,
FieldEddystoneNamespaceID = 1 << 9,
FieldEddystoneInstanceID = 1 << 10
}
public enum ConnectablePowerLevel : sbyte
{
Level1 = -30,
Level2 = -20,
Level3 = -16,
Level4 = -12,
Level5 = -8,
Level6 = -4,
Level7 = 0,
Level8 = 4
}
public enum EddystoneUIDPower : sbyte
{
Level1 = -30,
Level2 = -20,
Level3 = -16,
Level4 = -12,
Level5 = -8,
Level6 = -4,
Level7 = 0,
Level8 = 4
}
public enum EddystoneURLPower : sbyte
{
Level1 = -30,
Level2 = -20,
Level3 = -16,
Level4 = -12,
Level5 = -8,
Level6 = -4,
Level7 = 0,
Level8 = 4
}
public enum EddystoneEIDPower : sbyte
{
Level1 = -30,
Level2 = -20,
Level3 = -16,
Level4 = -12,
Level5 = -8,
Level6 = -4,
Level7 = 0,
Level8 = 4
}
public enum EstimoteLocationPower : sbyte
{
Level1 = -30,
Level2 = -20,
Level3 = -16,
Level4 = -12,
Level5 = -8,
Level6 = -4,
Level7 = 0,
Level8 = 4
}
public enum EstimoteTLMPower : sbyte
{
Level1 = -30,
Level2 = -20,
Level3 = -16,
Level4 = -12,
Level5 = -8,
Level6 = -4,
Level7 = 0,
Level8 = 4
}
public enum IBeaconPower : sbyte
{
Level1 = -30,
Level2 = -20,
Level3 = -16,
Level4 = -12,
Level5 = -8,
Level6 = -4,
Level7 = 0,
Level8 = 4
}
public enum NearablePower : sbyte
{
Level1 = -30,
Level2 = -20,
Level3 = -16,
Level4 = -12,
Level5 = -8,
Level6 = -4,
Level7 = 0,
Level8 = 4
}
[Native]
public enum SettingOperationStatus : long
{
InProgress,
Complete,
Failed
}
[Native]
public enum RequestBaseError : long
{
ConnectionFail = -1,
NoData = -2,
BadRequest = 400,
Unauthorized = 401,
Forbidden = 403,
NotFound = 404,
InternalServerError = 500
}
[Native]
public enum BeaconDetailsFields : ulong
{
AllFields = 1 << 0,
Mac = 1 << 1,
Color = 1 << 2,
Name = 1 << 3,
GPSLocation = 1 << 4,
IndoorLocation = 1 << 5,
PublicIdentifier = 1 << 6,
RemainingBatteryLifetime = 1 << 7,
AllSettings = 1 << 8,
Battery = 1 << 9,
Power = 1 << 10,
Interval = 1 << 11,
Hardware = 1 << 12,
Firmware = 1 << 13,
BasicPowerMode = 1 << 14,
SmartPowerMode = 1 << 15,
TimeZone = 1 << 16,
Security = 1 << 17,
MotionDetection = 1 << 18,
ConditionalBroadcasting = 1 << 19,
BroadcastingScheme = 1 << 20,
UUIDMajorMinor = 1 << 21,
EddystoneNamespaceID = 1 << 22,
EddystoneInstanceID = 1 << 23
}
[Native]
public enum SettingIBeaconProximityUUIDError : ulong
{
InvalidValue = 1
}
// typedef NS_ENUM(char, ESTNearableBroadcastingScheme)
public enum NearableBroadcastingScheme : sbyte
{
Unknown = -1,
Nearable,
IBeacon,
EddystoneUrl
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Input;
using EnvDTE;
using EnvDTE80;
using Microsoft.PythonTools.Project.Automation;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudioTools.Project.Automation;
using TestUtilities;
using TestUtilities.Python;
using TestUtilities.UI;
using Keyboard = TestUtilities.UI.Keyboard;
using Mouse = TestUtilities.UI.Mouse;
using Path = System.IO.Path;
namespace PythonToolsUITests {
[TestClass]
public class ProjectHomeTests {
[ClassInitialize]
public static void DoDeployment(TestContext context) {
AssertListener.Initialize();
PythonTestData.Deploy();
}
[TestMethod, Priority(1)]
[HostType("VSTestHost"), TestCategory("Installed")]
public void LoadRelativeProjects() {
using (var app = new VisualStudioApp()) {
string fullPath = TestData.GetPath(@"TestData\ProjectHomeProjects.sln");
app.OpenProject(@"TestData\ProjectHomeProjects.sln", expectedProjects: 9);
foreach (var project in app.Dte.Solution.Projects.OfType<Project>()) {
var name = Path.GetFileName(project.FileName);
if (name.StartsWith("ProjectA")) {
// Should have ProgramA.py, Subfolder\ProgramB.py and Subfolder\Subsubfolder\ProgramC.py
var programA = project.ProjectItems.Item("ProgramA.py");
Assert.IsNotNull(programA);
var subfolder = project.ProjectItems.Item("Subfolder");
var programB = subfolder.ProjectItems.Item("ProgramB.py");
Assert.IsNotNull(programB);
var subsubfolder = subfolder.ProjectItems.Item("Subsubfolder");
var programC = subsubfolder.ProjectItems.Item("ProgramC.py");
Assert.IsNotNull(programC);
} else if (name.StartsWith("ProjectB")) {
// Should have ProgramB.py and Subsubfolder\ProgramC.py
var programB = project.ProjectItems.Item("ProgramB.py");
Assert.IsNotNull(programB);
var subsubfolder = project.ProjectItems.Item("Subsubfolder");
var programC = subsubfolder.ProjectItems.Item("ProgramC.py");
Assert.IsNotNull(programC);
} else if (name.StartsWith("ProjectSln")) {
// Should have ProjectHomeProjects\ProgramA.py,
// ProjectHomeProjects\Subfolder\ProgramB.py and
// ProjectHomeProjects\Subfolder\Subsubfolder\ProgramC.py
var projectHome = project.ProjectItems.Item("ProjectHomeProjects");
var programA = projectHome.ProjectItems.Item("ProgramA.py");
Assert.IsNotNull(programA);
var subfolder = projectHome.ProjectItems.Item("Subfolder");
var programB = subfolder.ProjectItems.Item("ProgramB.py");
Assert.IsNotNull(programB);
var subsubfolder = subfolder.ProjectItems.Item("Subsubfolder");
var programC = subsubfolder.ProjectItems.Item("ProgramC.py");
Assert.IsNotNull(programC);
} else {
Assert.Fail("Wrong project file name", name);
}
}
}
}
[TestMethod, Priority(1)]
[HostType("VSTestHost"), TestCategory("Installed")]
public void AddDeleteItem() {
using (var app = new VisualStudioApp()) {
var project = app.OpenProject(@"TestData\ProjectHomeSingleProject.sln");
Assert.AreEqual("ProjectSingle.pyproj", Path.GetFileName(project.FileName));
project.ProjectItems.AddFromTemplate(((Solution2)app.Dte.Solution).GetProjectItemTemplate("PyClass.zip", "pyproj"), "TemplateItem.py");
var newItem = project.ProjectItems.Item("TemplateItem.py");
Assert.IsNotNull(newItem);
Assert.AreEqual(false, project.Saved);
project.Save();
Assert.AreEqual(true, project.Saved);
Assert.IsTrue(File.Exists(TestData.GetPath(@"TestData\ProjectHomeProjects\TemplateItem.py")));
newItem.Delete();
Assert.AreEqual(false, project.Saved);
project.Save();
Assert.AreEqual(true, project.Saved);
Assert.IsFalse(File.Exists(TestData.GetPath(@"TestData\ProjectHomeProjects\TemplateItem.py")));
}
}
[TestMethod, Priority(1)]
[HostType("VSTestHost"), TestCategory("Installed")]
public void AddDeleteItem2() {
using (var app = new VisualStudioApp()) {
var project = app.OpenProject(@"TestData\ProjectHomeSingleProject.sln");
var folder = project.ProjectItems.Item("Subfolder");
Assert.AreEqual("ProjectSingle.pyproj", Path.GetFileName(project.FileName));
folder.ProjectItems.AddFromTemplate(((Solution2)app.Dte.Solution).GetProjectItemTemplate("PyClass.zip", "pyproj"), "TemplateItem.py");
var newItem = folder.ProjectItems.Item("TemplateItem.py");
Assert.IsNotNull(newItem);
Assert.AreEqual(false, project.Saved);
project.Save();
Assert.AreEqual(true, project.Saved);
Assert.IsTrue(File.Exists(TestData.GetPath(@"TestData\ProjectHomeProjects\Subfolder\TemplateItem.py")));
newItem.Delete();
Assert.AreEqual(false, project.Saved);
project.Save();
Assert.AreEqual(true, project.Saved);
Assert.IsFalse(File.Exists(TestData.GetPath(@"TestData\ProjectHomeProjects\Subfolder\TemplateItem.py")));
}
}
[TestMethod, Priority(1)]
[HostType("VSTestHost"), TestCategory("Installed")]
public void AddDeleteFolder() {
using (var app = new VisualStudioApp()) {
var project = app.OpenProject(@"TestData\ProjectHomeSingleProject.sln");
Assert.AreEqual("ProjectSingle.pyproj", Path.GetFileName(project.FileName));
project.ProjectItems.AddFolder("NewFolder");
var newFolder = project.ProjectItems.Item("NewFolder");
Assert.IsNotNull(newFolder);
Assert.AreEqual(TestData.GetPath(@"TestData\ProjectHomeProjects\NewFolder\"), newFolder.Properties.Item("FullPath").Value);
newFolder.Delete();
}
}
[TestMethod, Priority(1)]
[HostType("VSTestHost"), TestCategory("Installed")]
public void AddDeleteSubfolder() {
using (var app = new VisualStudioApp()) {
var project = app.OpenProject(@"TestData\ProjectHomeSingleProject.sln");
var folder = project.ProjectItems.Item("Subfolder");
Assert.AreEqual("ProjectSingle.pyproj", Path.GetFileName(project.FileName));
folder.ProjectItems.AddFolder("NewFolder");
var newFolder = folder.ProjectItems.Item("NewFolder");
Assert.IsNotNull(newFolder);
Assert.AreEqual(TestData.GetPath(@"TestData\ProjectHomeProjects\Subfolder\NewFolder\"), newFolder.Properties.Item("FullPath").Value);
newFolder.Delete();
}
}
[TestMethod, Priority(1)]
[HostType("VSTestHost"), TestCategory("Installed")]
public void SaveProjectAs() {
using (var app = new VisualStudioApp()) {
EnvDTE.Project project;
try {
project = app.OpenProject(@"TestData\HelloWorld.sln");
project.SaveAs(TestData.GetPath(@"TestData\ProjectHomeProjects\TempFile.pyproj"));
Assert.AreEqual(TestData.GetPath(@"TestData\HelloWorld\"),
((OAProject)project).ProjectNode.ProjectHome);
app.Dte.Solution.SaveAs("HelloWorldRelocated.sln");
} finally {
app.Dte.Solution.Close();
GC.Collect();
GC.WaitForPendingFinalizers();
}
project = app.OpenProject(@"TestData\HelloWorldRelocated.sln");
Assert.AreEqual("TempFile.pyproj", project.FileName);
Assert.AreEqual(TestData.GetPath(@"TestData\HelloWorld\"),
((OAProject)project).ProjectNode.ProjectHome);
}
}
[TestMethod, Priority(1)]
[HostType("VSTestHost"), TestCategory("Installed")]
public void DragDropTest() {
using (var app = new VisualStudioApp()) {
app.OpenProject(@"TestData\DragDropRelocatedTest.sln");
app.OpenSolutionExplorer();
var window = app.SolutionExplorerTreeView;
var folder = window.FindItem("Solution 'DragDropRelocatedTest' (1 project)", "DragDropTest", "TestFolder", "SubItem.py");
var point = folder.GetClickablePoint();
Mouse.MoveTo(point);
Mouse.Down(MouseButton.Left);
var projectItem = window.FindItem("Solution 'DragDropRelocatedTest' (1 project)", "DragDropTest");
point = projectItem.GetClickablePoint();
Mouse.MoveTo(point);
Mouse.Up(MouseButton.Left);
Assert.AreNotEqual(null, window.WaitForItem("Solution 'DragDropRelocatedTest' (1 project)", "DragDropTest", "SubItem.py"));
app.Dte.Solution.Close(true);
// Ensure file was moved and the path was updated correctly.
var project = app.OpenProject(@"TestData\DragDropRelocatedTest.sln");
foreach (var item in project.ProjectItems.OfType<OAFileItem>()) {
Assert.IsTrue(File.Exists((string)item.Properties.Item("FullPath").Value), (string)item.Properties.Item("FullPath").Value);
}
}
}
[TestMethod, Priority(1)]
[HostType("VSTestHost"), TestCategory("Installed")]
public void CutPasteTest() {
using (var app = new VisualStudioApp()) {
app.OpenProject(@"TestData\CutPasteRelocatedTest.sln");
app.OpenSolutionExplorer();
var window = app.SolutionExplorerTreeView;
var folder = window.FindItem("Solution 'CutPasteRelocatedTest' (1 project)", "CutPasteTest", "TestFolder", "SubItem.py");
AutomationWrapper.Select(folder);
app.ExecuteCommand("Edit.Cut");
var projectItem = window.FindItem("Solution 'CutPasteRelocatedTest' (1 project)", "CutPasteTest");
AutomationWrapper.Select(projectItem);
app.ExecuteCommand("Edit.Paste");
Assert.IsNotNull(window.WaitForItem("Solution 'CutPasteRelocatedTest' (1 project)", "CutPasteTest", "SubItem.py"));
app.Dte.Solution.Close(true);
// Ensure file was moved and the path was updated correctly.
var project = app.OpenProject(@"TestData\CutPasteRelocatedTest.sln");
foreach (var item in project.ProjectItems.OfType<OAFileItem>()) {
Assert.IsTrue(File.Exists((string)item.Properties.Item("FullPath").Value), (string)item.Properties.Item("FullPath").Value);
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Security.Policy;
using System.Text;
using System.Xml;
namespace System.Security.Cryptography.Xml
{
public class EncryptedXml
{
//
// public constant Url identifiers used within the XML Encryption classes
//
public const string XmlEncNamespaceUrl = "http://www.w3.org/2001/04/xmlenc#";
public const string XmlEncElementUrl = "http://www.w3.org/2001/04/xmlenc#Element";
public const string XmlEncElementContentUrl = "http://www.w3.org/2001/04/xmlenc#Content";
public const string XmlEncEncryptedKeyUrl = "http://www.w3.org/2001/04/xmlenc#EncryptedKey";
//
// Symmetric Block Encryption
//
public const string XmlEncDESUrl = "http://www.w3.org/2001/04/xmlenc#des-cbc";
public const string XmlEncTripleDESUrl = "http://www.w3.org/2001/04/xmlenc#tripledes-cbc";
public const string XmlEncAES128Url = "http://www.w3.org/2001/04/xmlenc#aes128-cbc";
public const string XmlEncAES256Url = "http://www.w3.org/2001/04/xmlenc#aes256-cbc";
public const string XmlEncAES192Url = "http://www.w3.org/2001/04/xmlenc#aes192-cbc";
//
// Key Transport
//
public const string XmlEncRSA15Url = "http://www.w3.org/2001/04/xmlenc#rsa-1_5";
public const string XmlEncRSAOAEPUrl = "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p";
//
// Symmetric Key Wrap
//
public const string XmlEncTripleDESKeyWrapUrl = "http://www.w3.org/2001/04/xmlenc#kw-tripledes";
public const string XmlEncAES128KeyWrapUrl = "http://www.w3.org/2001/04/xmlenc#kw-aes128";
public const string XmlEncAES256KeyWrapUrl = "http://www.w3.org/2001/04/xmlenc#kw-aes256";
public const string XmlEncAES192KeyWrapUrl = "http://www.w3.org/2001/04/xmlenc#kw-aes192";
//
// Message Digest
//
public const string XmlEncSHA256Url = "http://www.w3.org/2001/04/xmlenc#sha256";
public const string XmlEncSHA512Url = "http://www.w3.org/2001/04/xmlenc#sha512";
//
// private members
//
private readonly XmlDocument _document;
private Evidence _evidence;
private XmlResolver _xmlResolver;
// hash table defining the key name mapping
private const int _capacity = 4; // 4 is a reasonable capacity for
// the key name mapping hash table
private readonly Hashtable _keyNameMapping;
private PaddingMode _padding;
private CipherMode _mode;
private Encoding _encoding;
private string _recipient;
private int _xmlDsigSearchDepthCounter = 0;
private int _xmlDsigSearchDepth;
//
// public constructors
//
public EncryptedXml() : this(new XmlDocument()) { }
public EncryptedXml(XmlDocument document) : this(document, null) { }
public EncryptedXml(XmlDocument document, Evidence evidence)
{
_document = document;
_evidence = evidence;
_xmlResolver = null;
// set the default padding to ISO-10126
_padding = PaddingMode.ISO10126;
// set the default cipher mode to CBC
_mode = CipherMode.CBC;
// By default the encoding is going to be UTF8
_encoding = Encoding.UTF8;
_keyNameMapping = new Hashtable(_capacity);
_xmlDsigSearchDepth = Utils.XmlDsigSearchDepth;
}
/// <summary>
/// This method validates the _xmlDsigSearchDepthCounter counter
/// if the counter is over the limit defined by admin or developer.
/// </summary>
/// <returns>returns true if the limit has reached otherwise false</returns>
private bool IsOverXmlDsigRecursionLimit()
{
if (_xmlDsigSearchDepthCounter > XmlDSigSearchDepth)
{
return true;
}
return false;
}
/// <summary>
/// Gets / Sets the max limit for recursive search of encryption key in signed XML
/// </summary>
public int XmlDSigSearchDepth
{
get
{
return _xmlDsigSearchDepth;
}
set
{
_xmlDsigSearchDepth = value;
}
}
// The evidence of the document being loaded: will be used to resolve external URIs
public Evidence DocumentEvidence
{
get { return _evidence; }
set { _evidence = value; }
}
// The resolver to use for external entities
public XmlResolver Resolver
{
get { return _xmlResolver; }
set { _xmlResolver = value; }
}
// The padding to be used. XML Encryption uses ISO 10126
// but it's nice to provide a way to extend this to include other forms of paddings
public PaddingMode Padding
{
get { return _padding; }
set { _padding = value; }
}
// The cipher mode to be used. XML Encryption uses CBC padding
// but it's nice to provide a way to extend this to include other cipher modes
public CipherMode Mode
{
get { return _mode; }
set { _mode = value; }
}
// The encoding of the XML document
public Encoding Encoding
{
get { return _encoding; }
set { _encoding = value; }
}
// This is used to specify the EncryptedKey elements that should be considered
// when an EncyptedData references an EncryptedKey using a CarriedKeyName and Recipient
public string Recipient
{
get
{
// an unspecified value for an XmlAttribute is string.Empty
if (_recipient == null)
_recipient = string.Empty;
return _recipient;
}
set { _recipient = value; }
}
//
// private methods
//
private byte[] GetCipherValue(CipherData cipherData)
{
if (cipherData == null)
throw new ArgumentNullException(nameof(cipherData));
Stream inputStream = null;
if (cipherData.CipherValue != null)
{
return cipherData.CipherValue;
}
else if (cipherData.CipherReference != null)
{
if (cipherData.CipherReference.CipherValue != null)
return cipherData.CipherReference.CipherValue;
Stream decInputStream = null;
if (cipherData.CipherReference.Uri == null)
{
throw new CryptographicException(SR.Cryptography_Xml_UriNotSupported);
}
// See if the CipherReference is a local URI
if (cipherData.CipherReference.Uri.Length == 0)
{
// self referenced Uri
string baseUri = (_document == null ? null : _document.BaseURI);
TransformChain tc = cipherData.CipherReference.TransformChain;
if (tc == null)
{
throw new CryptographicException(SR.Cryptography_Xml_UriNotSupported);
}
decInputStream = tc.TransformToOctetStream(_document, _xmlResolver, baseUri);
}
else if (cipherData.CipherReference.Uri[0] == '#')
{
string idref = Utils.ExtractIdFromLocalUri(cipherData.CipherReference.Uri);
// Serialize
XmlElement idElem = GetIdElement(_document, idref);
if (idElem == null || idElem.OuterXml == null)
{
throw new CryptographicException(SR.Cryptography_Xml_UriNotSupported);
}
inputStream = new MemoryStream(_encoding.GetBytes(idElem.OuterXml));
string baseUri = (_document == null ? null : _document.BaseURI);
TransformChain tc = cipherData.CipherReference.TransformChain;
if (tc == null)
{
throw new CryptographicException(SR.Cryptography_Xml_UriNotSupported);
}
decInputStream = tc.TransformToOctetStream(inputStream, _xmlResolver, baseUri);
}
else
{
throw new CryptographicException(SR.Cryptography_Xml_UriNotResolved, cipherData.CipherReference.Uri);
}
// read the output stream into a memory stream
byte[] cipherValue = null;
using (MemoryStream ms = new MemoryStream())
{
Utils.Pump(decInputStream, ms);
cipherValue = ms.ToArray();
// Close the stream and return
if (inputStream != null)
inputStream.Close();
decInputStream.Close();
}
// cache the cipher value for Perf reasons in case we call this routine twice
cipherData.CipherReference.CipherValue = cipherValue;
return cipherValue;
}
// Throw a CryptographicException if we were unable to retrieve the cipher data.
throw new CryptographicException(SR.Cryptography_Xml_MissingCipherData);
}
//
// public virtual methods
//
// This describes how the application wants to associate id references to elements
public virtual XmlElement GetIdElement(XmlDocument document, string idValue)
{
return SignedXml.DefaultGetIdElement(document, idValue);
}
// default behaviour is to look for the IV in the CipherValue
public virtual byte[] GetDecryptionIV(EncryptedData encryptedData, string symmetricAlgorithmUri)
{
if (encryptedData == null)
throw new ArgumentNullException(nameof(encryptedData));
int initBytesSize = 0;
// If the Uri is not provided by the application, try to get it from the EncryptionMethod
if (symmetricAlgorithmUri == null)
{
if (encryptedData.EncryptionMethod == null)
throw new CryptographicException(SR.Cryptography_Xml_MissingAlgorithm);
symmetricAlgorithmUri = encryptedData.EncryptionMethod.KeyAlgorithm;
}
switch (symmetricAlgorithmUri)
{
case EncryptedXml.XmlEncDESUrl:
case EncryptedXml.XmlEncTripleDESUrl:
initBytesSize = 8;
break;
case EncryptedXml.XmlEncAES128Url:
case EncryptedXml.XmlEncAES192Url:
case EncryptedXml.XmlEncAES256Url:
initBytesSize = 16;
break;
default:
// The Uri is not supported.
throw new CryptographicException(SR.Cryptography_Xml_UriNotSupported);
}
byte[] IV = new byte[initBytesSize];
byte[] cipherValue = GetCipherValue(encryptedData.CipherData);
Buffer.BlockCopy(cipherValue, 0, IV, 0, IV.Length);
return IV;
}
// default behaviour is to look for keys defined by an EncryptedKey clause
// either directly or through a KeyInfoRetrievalMethod, and key names in the key mapping
public virtual SymmetricAlgorithm GetDecryptionKey(EncryptedData encryptedData, string symmetricAlgorithmUri)
{
if (encryptedData == null)
throw new ArgumentNullException(nameof(encryptedData));
if (encryptedData.KeyInfo == null)
return null;
IEnumerator keyInfoEnum = encryptedData.KeyInfo.GetEnumerator();
KeyInfoRetrievalMethod kiRetrievalMethod;
KeyInfoName kiName;
KeyInfoEncryptedKey kiEncKey;
EncryptedKey ek = null;
while (keyInfoEnum.MoveNext())
{
kiName = keyInfoEnum.Current as KeyInfoName;
if (kiName != null)
{
// Get the decryption key from the key mapping
string keyName = kiName.Value;
if ((SymmetricAlgorithm)_keyNameMapping[keyName] != null)
return (SymmetricAlgorithm)_keyNameMapping[keyName];
// try to get it from a CarriedKeyName
XmlNamespaceManager nsm = new XmlNamespaceManager(_document.NameTable);
nsm.AddNamespace("enc", EncryptedXml.XmlEncNamespaceUrl);
XmlNodeList encryptedKeyList = _document.SelectNodes("//enc:EncryptedKey", nsm);
if (encryptedKeyList != null)
{
foreach (XmlNode encryptedKeyNode in encryptedKeyList)
{
XmlElement encryptedKeyElement = encryptedKeyNode as XmlElement;
EncryptedKey ek1 = new EncryptedKey();
ek1.LoadXml(encryptedKeyElement);
if (ek1.CarriedKeyName == keyName && ek1.Recipient == Recipient)
{
ek = ek1;
break;
}
}
}
break;
}
kiRetrievalMethod = keyInfoEnum.Current as KeyInfoRetrievalMethod;
if (kiRetrievalMethod != null)
{
string idref = Utils.ExtractIdFromLocalUri(kiRetrievalMethod.Uri);
ek = new EncryptedKey();
ek.LoadXml(GetIdElement(_document, idref));
break;
}
kiEncKey = keyInfoEnum.Current as KeyInfoEncryptedKey;
if (kiEncKey != null)
{
ek = kiEncKey.EncryptedKey;
break;
}
}
// if we have an EncryptedKey, decrypt to get the symmetric key
if (ek != null)
{
// now process the EncryptedKey, loop recursively
// If the Uri is not provided by the application, try to get it from the EncryptionMethod
if (symmetricAlgorithmUri == null)
{
if (encryptedData.EncryptionMethod == null)
throw new CryptographicException(SR.Cryptography_Xml_MissingAlgorithm);
symmetricAlgorithmUri = encryptedData.EncryptionMethod.KeyAlgorithm;
}
byte[] key = DecryptEncryptedKey(ek);
if (key == null)
throw new CryptographicException(SR.Cryptography_Xml_MissingDecryptionKey);
SymmetricAlgorithm symAlg = CryptoHelpers.CreateFromName<SymmetricAlgorithm>(symmetricAlgorithmUri);
if (symAlg == null)
{
throw new CryptographicException(SR.Cryptography_Xml_MissingAlgorithm);
}
symAlg.Key = key;
return symAlg;
}
return null;
}
// Try to decrypt the EncryptedKey given the key mapping
public virtual byte[] DecryptEncryptedKey(EncryptedKey encryptedKey)
{
if (encryptedKey == null)
throw new ArgumentNullException(nameof(encryptedKey));
if (encryptedKey.KeyInfo == null)
return null;
IEnumerator keyInfoEnum = encryptedKey.KeyInfo.GetEnumerator();
KeyInfoName kiName;
KeyInfoX509Data kiX509Data;
KeyInfoRetrievalMethod kiRetrievalMethod;
KeyInfoEncryptedKey kiEncKey;
EncryptedKey ek = null;
bool fOAEP = false;
while (keyInfoEnum.MoveNext())
{
kiName = keyInfoEnum.Current as KeyInfoName;
if (kiName != null)
{
// Get the decryption key from the key mapping
string keyName = kiName.Value;
object kek = _keyNameMapping[keyName];
if (kek != null)
{
if (encryptedKey.CipherData == null || encryptedKey.CipherData.CipherValue == null)
{
throw new CryptographicException(SR.Cryptography_Xml_MissingAlgorithm);
}
// kek is either a SymmetricAlgorithm or an RSA key, otherwise, we wouldn't be able to insert it in the hash table
if (kek is SymmetricAlgorithm)
return EncryptedXml.DecryptKey(encryptedKey.CipherData.CipherValue, (SymmetricAlgorithm)kek);
// kek is an RSA key: get fOAEP from the algorithm, default to false
fOAEP = (encryptedKey.EncryptionMethod != null && encryptedKey.EncryptionMethod.KeyAlgorithm == EncryptedXml.XmlEncRSAOAEPUrl);
return EncryptedXml.DecryptKey(encryptedKey.CipherData.CipherValue, (RSA)kek, fOAEP);
}
break;
}
kiX509Data = keyInfoEnum.Current as KeyInfoX509Data;
if (kiX509Data != null)
{
X509Certificate2Collection collection = Utils.BuildBagOfCerts(kiX509Data, CertUsageType.Decryption);
foreach (X509Certificate2 certificate in collection)
{
using (RSA privateKey = certificate.GetRSAPrivateKey())
{
if (privateKey != null)
{
if (encryptedKey.CipherData == null || encryptedKey.CipherData.CipherValue == null)
{
throw new CryptographicException(SR.Cryptography_Xml_MissingAlgorithm);
}
fOAEP = (encryptedKey.EncryptionMethod != null && encryptedKey.EncryptionMethod.KeyAlgorithm == EncryptedXml.XmlEncRSAOAEPUrl);
return EncryptedXml.DecryptKey(encryptedKey.CipherData.CipherValue, privateKey, fOAEP);
}
}
}
break;
}
kiRetrievalMethod = keyInfoEnum.Current as KeyInfoRetrievalMethod;
if (kiRetrievalMethod != null)
{
string idref = Utils.ExtractIdFromLocalUri(kiRetrievalMethod.Uri);
ek = new EncryptedKey();
ek.LoadXml(GetIdElement(_document, idref));
try
{
//Following checks if XML dsig processing is in loop and within the limit defined by machine
// admin or developer. Once the recursion depth crosses the defined limit it will throw exception.
_xmlDsigSearchDepthCounter++;
if (IsOverXmlDsigRecursionLimit())
{
//Throw exception once recursion limit is hit.
throw new CryptoSignedXmlRecursionException();
}
else
{
return DecryptEncryptedKey(ek);
}
}
finally
{
_xmlDsigSearchDepthCounter--;
}
}
kiEncKey = keyInfoEnum.Current as KeyInfoEncryptedKey;
if (kiEncKey != null)
{
ek = kiEncKey.EncryptedKey;
// recursively process EncryptedKey elements
byte[] encryptionKey = DecryptEncryptedKey(ek);
if (encryptionKey != null)
{
// this is a symmetric algorithm for sure
SymmetricAlgorithm symAlg = CryptoHelpers.CreateFromName<SymmetricAlgorithm>(encryptedKey.EncryptionMethod.KeyAlgorithm);
if (symAlg == null)
{
throw new CryptographicException(SR.Cryptography_Xml_MissingAlgorithm);
}
symAlg.Key = encryptionKey;
if (encryptedKey.CipherData == null || encryptedKey.CipherData.CipherValue == null)
{
throw new CryptographicException(SR.Cryptography_Xml_MissingAlgorithm);
}
symAlg.Key = encryptionKey;
return EncryptedXml.DecryptKey(encryptedKey.CipherData.CipherValue, symAlg);
}
}
}
return null;
}
//
// public methods
//
// defines a key name mapping. Default behaviour is to require the key object
// to be an RSA key or a SymmetricAlgorithm
public void AddKeyNameMapping(string keyName, object keyObject)
{
if (keyName == null)
throw new ArgumentNullException(nameof(keyName));
if (keyObject == null)
throw new ArgumentNullException(nameof(keyObject));
if (!(keyObject is SymmetricAlgorithm) && !(keyObject is RSA))
throw new CryptographicException(SR.Cryptography_Xml_NotSupportedCryptographicTransform);
_keyNameMapping.Add(keyName, keyObject);
}
public void ClearKeyNameMappings()
{
_keyNameMapping.Clear();
}
// Encrypts the given element with the certificate specified. The certificate is added as
// an X509Data KeyInfo to an EncryptedKey (AES session key) generated randomly.
public EncryptedData Encrypt(XmlElement inputElement, X509Certificate2 certificate)
{
if (inputElement == null)
throw new ArgumentNullException(nameof(inputElement));
if (certificate == null)
throw new ArgumentNullException(nameof(certificate));
using (RSA rsaPublicKey = certificate.GetRSAPublicKey())
{
if (rsaPublicKey == null)
throw new NotSupportedException(SR.NotSupported_KeyAlgorithm);
// Create the EncryptedData object, using an AES-256 session key by default.
EncryptedData ed = new EncryptedData();
ed.Type = EncryptedXml.XmlEncElementUrl;
ed.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url);
// Include the certificate in the EncryptedKey KeyInfo.
EncryptedKey ek = new EncryptedKey();
ek.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url);
ek.KeyInfo.AddClause(new KeyInfoX509Data(certificate));
// Create a random AES session key and encrypt it with the public key associated with the certificate.
RijndaelManaged rijn = new RijndaelManaged();
ek.CipherData.CipherValue = EncryptedXml.EncryptKey(rijn.Key, rsaPublicKey, false);
// Encrypt the input element with the random session key that we've created above.
KeyInfoEncryptedKey kek = new KeyInfoEncryptedKey(ek);
ed.KeyInfo.AddClause(kek);
ed.CipherData.CipherValue = EncryptData(inputElement, rijn, false);
return ed;
}
}
// Encrypts the given element with the key name specified. A corresponding key name mapping
// has to be defined before calling this method. The key name is added as
// a KeyNameInfo KeyInfo to an EncryptedKey (AES session key) generated randomly.
public EncryptedData Encrypt(XmlElement inputElement, string keyName)
{
if (inputElement == null)
throw new ArgumentNullException(nameof(inputElement));
if (keyName == null)
throw new ArgumentNullException(nameof(keyName));
object encryptionKey = null;
if (_keyNameMapping != null)
encryptionKey = _keyNameMapping[keyName];
if (encryptionKey == null)
throw new CryptographicException(SR.Cryptography_Xml_MissingEncryptionKey);
// kek is either a SymmetricAlgorithm or an RSA key, otherwise, we wouldn't be able to insert it in the hash table
SymmetricAlgorithm symKey = encryptionKey as SymmetricAlgorithm;
RSA rsa = encryptionKey as RSA;
// Create the EncryptedData object, using an AES-256 session key by default.
EncryptedData ed = new EncryptedData();
ed.Type = EncryptedXml.XmlEncElementUrl;
ed.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url);
// Include the key name in the EncryptedKey KeyInfo.
string encryptionMethod = null;
if (symKey == null)
{
encryptionMethod = EncryptedXml.XmlEncRSA15Url;
}
else if (symKey is TripleDES)
{
// CMS Triple DES Key Wrap
encryptionMethod = EncryptedXml.XmlEncTripleDESKeyWrapUrl;
}
else if (symKey is Rijndael || symKey is Aes)
{
// FIPS AES Key Wrap
switch (symKey.KeySize)
{
case 128:
encryptionMethod = EncryptedXml.XmlEncAES128KeyWrapUrl;
break;
case 192:
encryptionMethod = EncryptedXml.XmlEncAES192KeyWrapUrl;
break;
case 256:
encryptionMethod = EncryptedXml.XmlEncAES256KeyWrapUrl;
break;
}
}
else
{
// throw an exception if the transform is not in the previous categories
throw new CryptographicException(SR.Cryptography_Xml_NotSupportedCryptographicTransform);
}
EncryptedKey ek = new EncryptedKey();
ek.EncryptionMethod = new EncryptionMethod(encryptionMethod);
ek.KeyInfo.AddClause(new KeyInfoName(keyName));
// Create a random AES session key and encrypt it with the public key associated with the certificate.
RijndaelManaged rijn = new RijndaelManaged();
ek.CipherData.CipherValue = (symKey == null ? EncryptedXml.EncryptKey(rijn.Key, rsa, false) : EncryptedXml.EncryptKey(rijn.Key, symKey));
// Encrypt the input element with the random session key that we've created above.
KeyInfoEncryptedKey kek = new KeyInfoEncryptedKey(ek);
ed.KeyInfo.AddClause(kek);
ed.CipherData.CipherValue = EncryptData(inputElement, rijn, false);
return ed;
}
// decrypts the document using the defined key mapping in GetDecryptionKey
// The behaviour of this method can be extended because GetDecryptionKey is virtual
// the document is decrypted in place
public void DecryptDocument()
{
// Look for all EncryptedData elements and decrypt them
XmlNamespaceManager nsm = new XmlNamespaceManager(_document.NameTable);
nsm.AddNamespace("enc", EncryptedXml.XmlEncNamespaceUrl);
XmlNodeList encryptedDataList = _document.SelectNodes("//enc:EncryptedData", nsm);
if (encryptedDataList != null)
{
foreach (XmlNode encryptedDataNode in encryptedDataList)
{
XmlElement encryptedDataElement = encryptedDataNode as XmlElement;
EncryptedData ed = new EncryptedData();
ed.LoadXml(encryptedDataElement);
SymmetricAlgorithm symAlg = GetDecryptionKey(ed, null);
if (symAlg == null)
throw new CryptographicException(SR.Cryptography_Xml_MissingDecryptionKey);
byte[] decrypted = DecryptData(ed, symAlg);
ReplaceData(encryptedDataElement, decrypted);
}
}
}
// encrypts the supplied arbitrary data
public byte[] EncryptData(byte[] plaintext, SymmetricAlgorithm symmetricAlgorithm)
{
if (plaintext == null)
throw new ArgumentNullException(nameof(plaintext));
if (symmetricAlgorithm == null)
throw new ArgumentNullException(nameof(symmetricAlgorithm));
// save the original symmetric algorithm
CipherMode origMode = symmetricAlgorithm.Mode;
PaddingMode origPadding = symmetricAlgorithm.Padding;
byte[] cipher = null;
try
{
symmetricAlgorithm.Mode = _mode;
symmetricAlgorithm.Padding = _padding;
ICryptoTransform enc = symmetricAlgorithm.CreateEncryptor();
cipher = enc.TransformFinalBlock(plaintext, 0, plaintext.Length);
}
finally
{
// now restore the original symmetric algorithm
symmetricAlgorithm.Mode = origMode;
symmetricAlgorithm.Padding = origPadding;
}
byte[] output = null;
if (_mode == CipherMode.ECB)
{
output = cipher;
}
else
{
byte[] IV = symmetricAlgorithm.IV;
output = new byte[cipher.Length + IV.Length];
Buffer.BlockCopy(IV, 0, output, 0, IV.Length);
Buffer.BlockCopy(cipher, 0, output, IV.Length, cipher.Length);
}
return output;
}
// encrypts the supplied input element
public byte[] EncryptData(XmlElement inputElement, SymmetricAlgorithm symmetricAlgorithm, bool content)
{
if (inputElement == null)
throw new ArgumentNullException(nameof(inputElement));
if (symmetricAlgorithm == null)
throw new ArgumentNullException(nameof(symmetricAlgorithm));
byte[] plainText = (content ? _encoding.GetBytes(inputElement.InnerXml) : _encoding.GetBytes(inputElement.OuterXml));
return EncryptData(plainText, symmetricAlgorithm);
}
// decrypts the supplied EncryptedData
public byte[] DecryptData(EncryptedData encryptedData, SymmetricAlgorithm symmetricAlgorithm)
{
if (encryptedData == null)
throw new ArgumentNullException(nameof(encryptedData));
if (symmetricAlgorithm == null)
throw new ArgumentNullException(nameof(symmetricAlgorithm));
// get the cipher value and decrypt
byte[] cipherValue = GetCipherValue(encryptedData.CipherData);
// save the original symmetric algorithm
CipherMode origMode = symmetricAlgorithm.Mode;
PaddingMode origPadding = symmetricAlgorithm.Padding;
byte[] origIV = symmetricAlgorithm.IV;
// read the IV from cipherValue
byte[] decryptionIV = null;
if (_mode != CipherMode.ECB)
decryptionIV = GetDecryptionIV(encryptedData, null);
byte[] output = null;
try
{
int lengthIV = 0;
if (decryptionIV != null)
{
symmetricAlgorithm.IV = decryptionIV;
lengthIV = decryptionIV.Length;
}
symmetricAlgorithm.Mode = _mode;
symmetricAlgorithm.Padding = _padding;
ICryptoTransform dec = symmetricAlgorithm.CreateDecryptor();
output = dec.TransformFinalBlock(cipherValue, lengthIV, cipherValue.Length - lengthIV);
}
finally
{
// now restore the original symmetric algorithm
symmetricAlgorithm.Mode = origMode;
symmetricAlgorithm.Padding = origPadding;
symmetricAlgorithm.IV = origIV;
}
return output;
}
// This method replaces an EncryptedData element with the decrypted sequence of bytes
public void ReplaceData(XmlElement inputElement, byte[] decryptedData)
{
if (inputElement == null)
throw new ArgumentNullException(nameof(inputElement));
if (decryptedData == null)
throw new ArgumentNullException(nameof(decryptedData));
XmlNode parent = inputElement.ParentNode;
if (parent.NodeType == XmlNodeType.Document)
{
// We're replacing the root element, but we can't just wholesale replace the owner
// document's InnerXml, since we need to preserve any other top-level XML elements (such as
// comments or the XML entity declaration. Instead, create a new document with the
// decrypted XML, import it into the existing document, and replace just the root element.
XmlDocument importDocument = new XmlDocument();
importDocument.PreserveWhitespace = true;
string decryptedString = _encoding.GetString(decryptedData);
using (StringReader sr = new StringReader(decryptedString))
{
using (XmlReader xr = XmlReader.Create(sr, Utils.GetSecureXmlReaderSettings(_xmlResolver)))
{
importDocument.Load(xr);
}
}
XmlNode importedNode = inputElement.OwnerDocument.ImportNode(importDocument.DocumentElement, true);
parent.RemoveChild(inputElement);
parent.AppendChild(importedNode);
}
else
{
XmlNode dummy = parent.OwnerDocument.CreateElement(parent.Prefix, parent.LocalName, parent.NamespaceURI);
try
{
parent.AppendChild(dummy);
// Replace the children of the dummy node with the sequence of bytes passed in.
// The string will be parsed into DOM objects in the context of the parent of the EncryptedData element.
dummy.InnerXml = _encoding.GetString(decryptedData);
// Move the children of the dummy node up to the parent.
XmlNode child = dummy.FirstChild;
XmlNode sibling = inputElement.NextSibling;
XmlNode nextChild = null;
while (child != null)
{
nextChild = child.NextSibling;
parent.InsertBefore(child, sibling);
child = nextChild;
}
}
finally
{
// Remove the dummy element.
parent.RemoveChild(dummy);
}
// Remove the EncryptedData element
parent.RemoveChild(inputElement);
}
}
//
// public static methods
//
// replaces the inputElement with the provided EncryptedData
public static void ReplaceElement(XmlElement inputElement, EncryptedData encryptedData, bool content)
{
if (inputElement == null)
throw new ArgumentNullException(nameof(inputElement));
if (encryptedData == null)
throw new ArgumentNullException(nameof(encryptedData));
// First, get the XML representation of the EncryptedData object
XmlElement elemED = encryptedData.GetXml(inputElement.OwnerDocument);
switch (content)
{
case true:
// remove all children of the input element
Utils.RemoveAllChildren(inputElement);
// then append the encrypted data as a child of the input element
inputElement.AppendChild(elemED);
break;
case false:
XmlNode parentNode = inputElement.ParentNode;
// remove the input element from the containing document
parentNode.ReplaceChild(elemED, inputElement);
break;
}
}
// wraps the supplied input key data using the provided symmetric algorithm
public static byte[] EncryptKey(byte[] keyData, SymmetricAlgorithm symmetricAlgorithm)
{
if (keyData == null)
throw new ArgumentNullException(nameof(keyData));
if (symmetricAlgorithm == null)
throw new ArgumentNullException(nameof(symmetricAlgorithm));
if (symmetricAlgorithm is TripleDES)
{
// CMS Triple DES Key Wrap
return SymmetricKeyWrap.TripleDESKeyWrapEncrypt(symmetricAlgorithm.Key, keyData);
}
else if (symmetricAlgorithm is Rijndael || symmetricAlgorithm is Aes)
{
// FIPS AES Key Wrap
return SymmetricKeyWrap.AESKeyWrapEncrypt(symmetricAlgorithm.Key, keyData);
}
// throw an exception if the transform is not in the previous categories
throw new CryptographicException(SR.Cryptography_Xml_NotSupportedCryptographicTransform);
}
// encrypts the supplied input key data using an RSA key and specifies whether we want to use OAEP
// padding or PKCS#1 v1.5 padding as described in the PKCS specification
public static byte[] EncryptKey(byte[] keyData, RSA rsa, bool useOAEP)
{
if (keyData == null)
throw new ArgumentNullException(nameof(keyData));
if (rsa == null)
throw new ArgumentNullException(nameof(rsa));
if (useOAEP)
{
RSAOAEPKeyExchangeFormatter rsaFormatter = new RSAOAEPKeyExchangeFormatter(rsa);
return rsaFormatter.CreateKeyExchange(keyData);
}
else
{
RSAPKCS1KeyExchangeFormatter rsaFormatter = new RSAPKCS1KeyExchangeFormatter(rsa);
return rsaFormatter.CreateKeyExchange(keyData);
}
}
// decrypts the supplied wrapped key using the provided symmetric algorithm
public static byte[] DecryptKey(byte[] keyData, SymmetricAlgorithm symmetricAlgorithm)
{
if (keyData == null)
throw new ArgumentNullException(nameof(keyData));
if (symmetricAlgorithm == null)
throw new ArgumentNullException(nameof(symmetricAlgorithm));
if (symmetricAlgorithm is TripleDES)
{
// CMS Triple DES Key Wrap
return SymmetricKeyWrap.TripleDESKeyWrapDecrypt(symmetricAlgorithm.Key, keyData);
}
else if (symmetricAlgorithm is Rijndael || symmetricAlgorithm is Aes)
{
// FIPS AES Key Wrap
return SymmetricKeyWrap.AESKeyWrapDecrypt(symmetricAlgorithm.Key, keyData);
}
// throw an exception if the transform is not in the previous categories
throw new CryptographicException(SR.Cryptography_Xml_NotSupportedCryptographicTransform);
}
// decrypts the supplied data using an RSA key and specifies whether we want to use OAEP
// padding or PKCS#1 v1.5 padding as described in the PKCS specification
public static byte[] DecryptKey(byte[] keyData, RSA rsa, bool useOAEP)
{
if (keyData == null)
throw new ArgumentNullException(nameof(keyData));
if (rsa == null)
throw new ArgumentNullException(nameof(rsa));
if (useOAEP)
{
RSAOAEPKeyExchangeDeformatter rsaDeformatter = new RSAOAEPKeyExchangeDeformatter(rsa);
return rsaDeformatter.DecryptKeyExchange(keyData);
}
else
{
RSAPKCS1KeyExchangeDeformatter rsaDeformatter = new RSAPKCS1KeyExchangeDeformatter(rsa);
return rsaDeformatter.DecryptKeyExchange(keyData);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Build.Framework;
using Newtonsoft.Json;
using NuGet.RuntimeModel;
using NuGet.Versioning;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Microsoft.DotNet.Build.Tasks.Packaging
{
public class GenerateRuntimeDependencies : PackagingTask
{
private const string c_emptyDependency = "none";
[Required]
public ITaskItem[] Dependencies
{
get;
set;
}
[Required]
public string PackageId
{
get;
set;
}
public ITaskItem RuntimeJsonTemplate
{
get;
set;
}
[Required]
public ITaskItem RuntimeJson
{
get;
set;
}
public override bool Execute()
{
if (Dependencies == null || Dependencies.Length == 0)
{
Log.LogError("Dependencies argument must be specified");
return false;
}
if (String.IsNullOrEmpty(PackageId))
{
Log.LogError("PackageID argument must be specified");
return false;
}
if (RuntimeJson == null)
{
Log.LogError("RuntimeJson argument must be specified");
return false;
}
string sourceRuntimeFilePath = null;
if (RuntimeJsonTemplate != null)
{
sourceRuntimeFilePath = RuntimeJsonTemplate.GetMetadata("FullPath");
}
string destRuntimeFilePath = RuntimeJson.GetMetadata("FullPath");
Dictionary<string, string> packageAliases = new Dictionary<string, string>();
foreach (var dependency in Dependencies)
{
string alias = dependency.GetMetadata("PackageAlias");
if (String.IsNullOrEmpty(alias))
{
continue;
}
Log.LogMessage(LogImportance.Low, "Aliasing {0} -> {1}", alias, dependency.ItemSpec);
packageAliases[alias] = dependency.ItemSpec;
}
var runtimeGroups = Dependencies.GroupBy(d => d.GetMetadata("TargetRuntime"));
List<RuntimeDescription> runtimes = new List<RuntimeDescription>();
foreach (var runtimeGroup in runtimeGroups)
{
string targetRuntimeId = runtimeGroup.Key;
if (String.IsNullOrEmpty(targetRuntimeId))
{
Log.LogMessage(LogImportance.Low, "Skipping dependencies {0} since they don't have a TargetRuntime.", String.Join(", ", runtimeGroup.Select(d => d.ItemSpec)));
continue;
}
if (runtimeGroup.Any(d => d.ItemSpec == c_emptyDependency))
{
runtimes.Add(new RuntimeDescription(targetRuntimeId));
continue;
}
List<RuntimeDependencySet> runtimeDependencySets = new List<RuntimeDependencySet>();
var targetPackageGroups = runtimeGroup.GroupBy(d => GetTargetPackageId(d, packageAliases));
foreach (var targetPackageGroup in targetPackageGroups)
{
string targetPackageId = targetPackageGroup.Key;
List<RuntimePackageDependency> runtimePackageDependencies = new List<RuntimePackageDependency>();
var dependencyGroups = targetPackageGroup.GroupBy(d => d.ItemSpec);
foreach (var dependencyGroup in dependencyGroups)
{
string dependencyId = dependencyGroup.Key;
var dependencyVersions = dependencyGroup.Select(d => GetDependencyVersion(d));
var maxDependencyVersion = dependencyVersions.Max();
runtimePackageDependencies.Add(new RuntimePackageDependency(dependencyId, new VersionRange(maxDependencyVersion)));
}
runtimeDependencySets.Add(new RuntimeDependencySet(targetPackageId, runtimePackageDependencies));
}
runtimes.Add(new RuntimeDescription(targetRuntimeId, runtimeDependencySets));
}
RuntimeGraph runtimeGraph = new RuntimeGraph(runtimes);
// read in existing JSON, if it was provided so that we preserve any
// hand authored #imports or dependencies
if (!String.IsNullOrEmpty(sourceRuntimeFilePath))
{
RuntimeGraph existingGraph = JsonRuntimeFormat.ReadRuntimeGraph(sourceRuntimeFilePath);
runtimeGraph = RuntimeGraph.Merge(existingGraph, runtimeGraph);
}
string destRuntimeFileDir = Path.GetDirectoryName(destRuntimeFilePath);
if (!String.IsNullOrEmpty(destRuntimeFileDir) && !Directory.Exists(destRuntimeFileDir))
{
Directory.CreateDirectory(destRuntimeFileDir);
}
SaveRuntimeGraph(destRuntimeFilePath, runtimeGraph);
return true;
}
private string GetTargetPackageId(ITaskItem dependency, IDictionary<string, string> packageAliases)
{
string targetPackageId = dependency.GetMetadata("TargetPackage");
string targetPackageAlias = dependency.GetMetadata("TargetPackageAlias");
if (!String.IsNullOrEmpty(targetPackageAlias) && !packageAliases.TryGetValue(targetPackageAlias, out targetPackageId))
{
Log.LogWarning("Dependency {0} specified TargetPackageAlias {1} but no package was found defining this alias.", dependency.ItemSpec, targetPackageAlias);
}
else
{
Log.LogMessage(LogImportance.Low, "Using {0} for TargetPackageAlias {1}", targetPackageId, targetPackageAlias);
}
if (String.IsNullOrEmpty(targetPackageId))
{
Log.LogMessage(LogImportance.Low, "Dependency {0} has no parent so will assume {1}.", dependency.ItemSpec, PackageId);
targetPackageId = PackageId;
}
return targetPackageId;
}
private NuGetVersion GetDependencyVersion(ITaskItem dependency)
{
NuGetVersion dependencyVersion;
string dependencyVersionString = dependency.GetMetadata("version");
if (String.IsNullOrEmpty(dependencyVersionString))
{
Log.LogWarning("Dependency {0} has no version", dependency.ItemSpec);
dependencyVersion = new NuGetVersion(0, 0, 0);
}
else if (!NuGetVersion.TryParse(dependencyVersionString, out dependencyVersion))
{
Log.LogError("Dependency {0} has invalid version {1}", dependency.ItemSpec, dependencyVersionString);
dependencyVersion = new NuGetVersion(0, 0, 0);
}
return dependencyVersion;
}
public static void SaveRuntimeGraph(string filePath, RuntimeGraph runtimeGraph)
{
var jsonObjectWriter = new JsonObjectWriter();
var runtimeJsonWriter = new RuntimeJsonWriter(jsonObjectWriter);
JsonRuntimeFormat.WriteRuntimeGraph(runtimeJsonWriter, runtimeGraph);
using (var file = File.CreateText(filePath))
using (var jsonWriter = new JsonTextWriter(file))
{
jsonWriter.StringEscapeHandling = StringEscapeHandling.EscapeNonAscii;
jsonWriter.Formatting = Formatting.Indented;
jsonObjectWriter.WriteTo(jsonWriter);
}
}
/// <summary>
/// works around a bug in NuGet that writes an empty import array,
/// also another bug that writes open ranges rather than single versions.
/// </summary>
private class RuntimeJsonWriter : IObjectWriter
{
private IObjectWriter innerWriter;
public RuntimeJsonWriter(IObjectWriter writer)
{
innerWriter = writer;
}
public void WriteNameArray(string name, IEnumerable<string> values)
{
// if we are writing an empty import array, skip it.
if (name == "#import" && !values.Any())
{
return;
}
innerWriter.WriteNameArray(name, values);
}
public void WriteNameValue(string name, string value)
{
// if we are writing a version range with no upper bound, only write the lower bound
if (value.Length > 4 &&
value[0] == '[' &&
value.EndsWith(", )"))
{
innerWriter.WriteNameValue(name, value.Substring(1, value.Length - 4));
}
else
{
innerWriter.WriteNameValue(name, value);
}
}
public void WriteNameValue(string name, int value)
{
innerWriter.WriteNameValue(name, value);
}
public void WriteObjectEnd()
{
innerWriter.WriteObjectEnd();
}
public void WriteObjectStart(string name)
{
innerWriter.WriteObjectStart(name);
}
}
}
}
| |
#region MigraDoc - Creating Documents on the Fly
//
// Authors:
// Stefan Lange (mailto:[email protected])
// Klaus Potzesny (mailto:[email protected])
// David Stephensen (mailto:[email protected])
//
// Copyright (c) 2001-2009 empira Software GmbH, Cologne (Germany)
//
// http://www.pdfsharp.com
// http://www.migradoc.com
// http://sourceforge.net/projects/pdfsharp
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Diagnostics;
using System.Reflection;
using MigraDoc.DocumentObjectModel.Internals;
using MigraDoc.DocumentObjectModel.Visitors;
namespace MigraDoc.DocumentObjectModel.Tables
{
/// <summary>
/// Represents the collection of all rows of a table.
/// </summary>
public class Rows : DocumentObjectCollection, IVisitable
{
/// <summary>
/// Initializes a new instance of the Rows class.
/// </summary>
public Rows()
{
}
/// <summary>
/// Initializes a new instance of the Rows class with the specified parent.
/// </summary>
internal Rows(DocumentObject parent) : base(parent) { }
#region Methods
/// <summary>
/// Creates a deep copy of this object.
/// </summary>
public new Rows Clone()
{
return (Rows)base.DeepCopy();
}
/// <summary>
/// Adds a new row to the rows collection. Allowed only if at least one column exists.
/// </summary>
public Row AddRow()
{
if (Table.Columns.Count == 0)
throw new InvalidOperationException("Cannot add row, because no columns exists.");
Row row = new Row();
Add(row);
return row;
}
#endregion
#region Properties
/// <summary>
/// Gets the table the rows collection belongs to.
/// </summary>
public Table Table
{
get { return this.parent as Table; }
}
/// <summary>
/// Gets a row by its index.
/// </summary>
public new Row this[int index]
{
get { return base[index] as Row; }
}
/// <summary>
/// Gets or sets the row alignment of the table.
/// </summary>
public RowAlignment Alignment
{
get { return (RowAlignment)this.alignment.Value; }
set { this.alignment.Value = (int)value; }
}
[DV(Type = typeof(RowAlignment))]
internal NEnum alignment = NEnum.NullValue(typeof(RowAlignment));
/// <summary>
/// Gets or sets the left indent of the table. If row alignment is not Left,
/// the value is ignored.
/// </summary>
public Unit LeftIndent
{
get { return this.leftIndent; }
set { this.leftIndent = value; }
}
[DV]
internal Unit leftIndent = Unit.NullValue;
/// <summary>
/// Gets or sets the default vertical alignment for all rows.
/// </summary>
public VerticalAlignment VerticalAlignment
{
get { return (VerticalAlignment)this.verticalAlignment.Value; }
set { this.verticalAlignment.Value = (int)value; }
}
[DV(Type = typeof(VerticalAlignment))]
internal NEnum verticalAlignment = NEnum.NullValue(typeof(VerticalAlignment));
/// <summary>
/// Gets or sets the height of the rows.
/// </summary>
public Unit Height
{
get { return this.height; }
set { this.height = value; }
}
[DV]
internal Unit height = Unit.NullValue;
/// <summary>
/// Gets or sets the rule which is used to determine the height of the rows.
/// </summary>
public RowHeightRule HeightRule
{
get { return (RowHeightRule)this.heightRule.Value; }
set { this.heightRule.Value = (int)value; }
}
[DV(Type = typeof(RowHeightRule))]
internal NEnum heightRule = NEnum.NullValue(typeof(RowHeightRule));
/// <summary>
/// Gets or sets a comment associated with this object.
/// </summary>
public string Comment
{
get { return this.comment.Value; }
set { this.comment.Value = value; }
}
[DV]
internal NString comment = NString.NullValue;
#endregion
#region Internal
/// <summary>
/// Converts Rows into DDL.
/// </summary>
internal override void Serialize(Serializer serializer)
{
serializer.WriteComment(this.comment.Value);
serializer.WriteLine("\\rows");
int pos = serializer.BeginAttributes();
if (!this.alignment.IsNull)
serializer.WriteSimpleAttribute("Alignment", this.Alignment);
if (!this.height.IsNull)
serializer.WriteSimpleAttribute("Height", this.Height);
if (!this.heightRule.IsNull)
serializer.WriteSimpleAttribute("HeightRule", this.HeightRule);
if (!this.leftIndent.IsNull)
serializer.WriteSimpleAttribute("LeftIndent", this.LeftIndent);
if (!this.verticalAlignment.IsNull)
serializer.WriteSimpleAttribute("VerticalAlignment", this.VerticalAlignment);
serializer.EndAttributes(pos);
serializer.BeginContent();
int rows = Count;
if (rows > 0)
{
for (int row = 0; row < rows; row++)
this[row].Serialize(serializer);
}
else
serializer.WriteComment("Invalid - no rows defined. Table will not render.");
serializer.EndContent();
}
/// <summary>
/// Allows the visitor object to visit the document object and it's child objects.
/// </summary>
void IVisitable.AcceptVisitor(DocumentObjectVisitor visitor, bool visitChildren)
{
visitor.VisitRows(this);
foreach (Row row in this)
((IVisitable)row).AcceptVisitor(visitor, visitChildren);
}
/// <summary>
/// Returns the meta object of this instance.
/// </summary>
internal override Meta Meta
{
get
{
if (meta == null)
meta = new Meta(typeof(Rows));
return meta;
}
}
static Meta meta;
/// <summary>
/// Set row.Index for each row in collection
/// optimization from AndrewT's patch - http://www.pakeha_by.my-webs.org/downloads/MigraDoc-1.32-TablePatch.patch
/// </summary>
internal void PopulateItemIndexes()
{
for (int index = 0; index < this.Count; index++)
this[index].index = index;
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="Program.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <disclaimer>
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
// PURPOSE.
// </disclaimer>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
namespace SpawningTutorial {
using System.Threading;
using System;
using Microsoft.Research.Joins;
public class SpawningTutorial {
static readonly Asynchronous.Channel<string> m;
static SpawningTutorial() {
Join join = Join.Create();
join.Initialize(out m);
join.When(m).Do(delegate(string s)
{
while (true) {
Console.WriteLine(s);
Thread.Sleep(1000);
};
});
}
static void Main_() {
m("thread one");
m("thread two");
}
}
}
namespace Counter.Counter1 {
public class Counter {
long i;
public Counter() {
i = 0;
}
public void Inc() {
lock (this) { // acquire the lock on this object
i = i + 1; // update the state
} // release the lock
}
public long Value() {
lock (this) {
return i; // release the lock & return state
}
}
}
}
namespace Counter.Counter2 {
using Microsoft.Research.Joins;
public class Counter {
long i;
Asynchronous.Channel mylock;
public Synchronous.Channel Inc;
public Synchronous<long>.Channel Value;
public Counter() {
Join join = Join.Create();
join.Initialize(out mylock);
join.Initialize(out Inc);
join.Initialize(out Value);
join.When(Inc).And(mylock).Do(delegate
{ // acquire the lock
i = i + 1; // update the state
mylock();
});
join.When(Value).And(mylock).Do(delegate
{ // acquire the lock
long r = i; // read the state
mylock(); // release the lock
return r; // return state;
});
i = 0;
mylock();
}
}
}
namespace Counter.Counter3 {
using Microsoft.Research.Joins;
public class Counter {
Asynchronous.Channel<long> mystate;
public Synchronous.Channel Inc;
public Synchronous<long>.Channel Value;
public Counter() {
Join join = Join.Create();
join.Initialize(out mystate);
join.Initialize(out Inc);
join.Initialize(out Value);
join.When(Inc).And(mystate).Do(delegate(long i)
{ // acquire the state
mystate(i + 1);// reissue the updated the state
});
join.When(Value).And(mystate).Do(delegate(long i)
{ // acquire the state
mystate(i); // reissue the state
return i; // return state
});
mystate(0);
}
}
}
namespace ReaderWriter {
using Microsoft.Research.Joins;
public class ReaderWriter {
private readonly Asynchronous.Channel Idle;
private readonly Asynchronous.Channel<int> Sharing;
public readonly Synchronous.Channel Shared, ReleaseShared;
public readonly Synchronous.Channel Exclusive, ReleaseExclusive;
public ReaderWriter() {
Join j = Join.Create();
j.Initialize(out Idle);
j.Initialize(out Sharing);
j.Initialize(out Shared);
j.Initialize(out ReleaseShared);
j.Initialize(out Exclusive);
j.Initialize(out ReleaseExclusive);
j.When(Shared).And(Idle).Do(delegate { Sharing(1); });
j.When(Shared).And(Sharing).Do(delegate(int n)
{
Sharing(n + 1);
});
j.When(ReleaseShared).And(Sharing).Do(delegate(int n)
{
if (n == 1) Idle(); else Sharing(n - 1);
});
j.When(Exclusive).And(Idle).Do(delegate { });
j.When(ReleaseExclusive).Do(delegate { Idle(); });
Idle();
}
}
}
namespace BoundedBuffer {
using Microsoft.Research.Joins;
public class BufferN<T> {
private readonly Asynchronous.Channel Token;
private readonly Asynchronous.Channel<T> Value;
public readonly Synchronous.Channel<T> Put;
public readonly Synchronous<T>.Channel Get;
public BufferN(int size) {
Join join = Join.Create();
join.Initialize(out Token);
join.Initialize(out Value);
join.Initialize(out Put);
join.Initialize(out Get);
join.When(Put).And(Token).Do(delegate(T t)
{
Value(t);
});
join.When(Get).And(Value).Do(delegate(T t)
{
Token();
return t;
});
for (int i = 0; i < size; i++) {
Token();
}
}
}
}
namespace Semaphore {
using Microsoft.Research.Joins;
public class Semaphore {
public readonly Asynchronous.Channel Signal;
public readonly Synchronous.Channel Wait;
public Semaphore() {
Join join = Join.Create();
join.Initialize(out Signal);
join.Initialize(out Wait);
join.When(Wait).And(Signal).Do(delegate { });
}
}
public struct Pair<A, B> {
public readonly A Fst; public readonly B Snd;
public Pair(A Fst, B Snd) { this.Fst = Fst; this.Snd = Snd; }
}
public class MyApp {
static Asynchronous.Channel<Pair<int, Semaphore>> Task1, Task2;
public static void Main2() {
Semaphore s = new Semaphore();
Task1(new Pair<int, Semaphore>(1, s));
Task2(new Pair<int, Semaphore>(2, s));
// do something in main thread
s.Wait(); // wait for one to finish
s.Wait(); // wait for another to finish
Console.WriteLine("both tasks finished");
}
static MyApp() {
Join join = Join.Create();
join.Initialize(out Task1);
join.Initialize(out Task2);
join.When(Task1).Do(delegate(Pair<int, Semaphore> p)
{
// do something with p.Fst
p.Snd.Signal();
});
join.When(Task2).Do(delegate(Pair<int, Semaphore> p)
{
// do something else with p.Fst
p.Snd.Signal();
});
}
}
}
namespace Asynchronous.ChannelService {
using System.Threading;
using Microsoft.Research.Joins;
interface IService<R, A> {
Asynchronous.Channel<Pair<A, Asynchronous.Channel<R>>> Service { get;}
}
public class SimpleService : IService<string, int> {
readonly Asynchronous.Channel<Pair<int, Asynchronous.Channel<string>>> Service;
Asynchronous.Channel<Pair<int, Asynchronous.Channel<string>>> IService<string,int>.Service { get { return Service; } }
public SimpleService() {
Join j = Join.Create();
j.Initialize(out Service);
j.When(Service).Do(delegate(Pair<int, Asynchronous.Channel<string>> p)
{
string result = p.Fst.ToString(); // do some work with p.Fst
p.Snd(result); // send the result on p.Snd
});
}
}
public class JoinTwo<R1, R2> {
public readonly Asynchronous.Channel<R1> First;
public readonly Asynchronous.Channel<R2> Second;
public readonly Synchronous<Pair<R1, R2>>.Channel Wait;
public JoinTwo() {
Join j = Join.Create();
j.Initialize(out First);
j.Initialize(out Second);
j.Initialize(out Wait);
j.When(Wait).And(First).And(Second).Do(
delegate(R1 r1, R2 r2)
{
return new Pair<R1, R2>(r1, r2);
});
}
}
namespace Client {
using Request = Pair<int, Asynchronous.Channel<string>>;
class Client {
public static void Main_() {
IService<string, int> s1, s2;
s1 = new SimpleService();
s2 = new SimpleService();
JoinTwo<string, string> j = new JoinTwo<string, string>();
s1.Service(new Request(10, j.First));
s2.Service(new Request(30, j.Second));
for (int i = 0; i < 7; i++) {
Thread.Sleep(i);
Console.WriteLine("Main {0}", i);
}
Pair<string, string> result = j.Wait(); // wait for both results to come back
Console.WriteLine("first result={0}, second result={1}", result.Fst, result.Snd);
Console.ReadLine();
}
}
}
}
namespace ActiveObjects {
using System.Collections;
using Microsoft.Research.Joins;
public abstract class ActiveObject {
protected bool done = false;
private readonly Asynchronous.Channel Start;
protected Synchronous.Channel ProcessMessage;
protected Join join;
public ActiveObject() {
join = Join.Create();
join.Initialize(out ProcessMessage);
join.Initialize(out Start);
join.When(Start).Do(delegate
{
while (!done) ProcessMessage();
});
Start();
}
}
public interface EventSink {
Asynchronous.Channel<string> Post { get; }
}
public class Distributor : ActiveObject, EventSink {
private ArrayList subscribers = new ArrayList();
private string myname;
public readonly Asynchronous.Channel<EventSink> Subscribe;
public readonly Asynchronous.Channel<string> Post;
Asynchronous.Channel<string> EventSink.Post { get { return Post; } }
public Distributor(string name) {
join.Initialize(out Post);
join.Initialize(out Subscribe);
join.When(ProcessMessage).And(Subscribe).Do(
delegate(EventSink sink)
{
subscribers.Add(sink);
});
join.When(ProcessMessage).And(Post).Do(
delegate(string message)
{
foreach (EventSink sink in subscribers) {
sink.Post(myname + ":" + message);
}
});
myname = name;
}
}
}
namespace RemotingActiveObjects {
using System.Collections;
using System.Runtime.Remoting.Messaging;
using Microsoft.Research.Joins;
public abstract class ActiveObject : MarshalByRefObject {
protected bool done = false;
private readonly Asynchronous.Channel Start;
protected Synchronous.Channel ProcessMessage;
protected Join join;
public ActiveObject() {
join = Join.Create();
join.Initialize(out ProcessMessage);
join.Initialize(out Start);
join.When(Start).Do(delegate
{
while (!done) ProcessMessage();
});
Start();
}
}
public interface EventSink {
[OneWay]
void Post(string message);
}
public class Distributor : ActiveObject, EventSink {
private ArrayList subscribers = new ArrayList();
private string myname;
private Asynchronous.Channel<EventSink> subscribe;
private Asynchronous.Channel<string> post;
[OneWay]
public void Post(string s) {
post(s);
}
[OneWay]
public void Subscribe(EventSink s) {
subscribe(s);
}
public Distributor(string name) {
join.Initialize(out post);
join.Initialize(out subscribe);
join.When(ProcessMessage).And(subscribe).Do(
delegate(EventSink sink)
{
subscribers.Add(sink);
});
join.When(ProcessMessage).And(post).Do(
delegate(string message)
{
foreach (EventSink sink in subscribers) {
sink.Post(myname + ":" + message);
}
});
myname = name;
}
}
}
namespace JoinMany {
using Microsoft.Research.Joins;
public class JoinMany<R> {
private readonly Asynchronous.Channel<R>[] Responses;
public readonly Synchronous<R[]>.Channel Wait;
public Asynchronous.Channel<R> Response(int i) {
return Responses[i];
}
public JoinMany(int n) {
Join j = Join.Create(n + 1);
j.Initialize(out Responses, n);
j.Initialize(out Wait);
j.When(Wait).And(Responses).Do(delegate(R[] results)
{
return results;
});
}
}
public class JoinMany {
private readonly Asynchronous.Channel[] Responses;
public readonly Synchronous.Channel Wait;
public Asynchronous.Channel Response(int i) {
return Responses[i];
}
public JoinMany(int n) {
Join j = Join.Create(n + 1);
j.Initialize(out Responses, n);
j.Initialize(out Wait);
j.When(Wait).And(Responses).Do(delegate () { });
}
}
}
| |
#region License
/*
* Copyright 2013 Weswit Srl
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion License
using System;
using System.Collections;
using System.Threading;
using System.IO;
using System.Net.Sockets;
using log4net;
using Lightstreamer.DotNet.Server;
[assembly:log4net.Config.XmlConfigurator()]
namespace Lightstreamer.Adapters.StockListDemo {
public class ServerMain {
private static ILog _log= LogManager.GetLogger("Lightstreamer.Adapters.StockListDemo.ServerMain");
public const string PREFIX1= "-";
public const string PREFIX2= "/";
public const char SEP= '=';
public const string ARG_HELP_LONG= "help";
public const string ARG_HELP_SHORT= "?";
public const string ARG_HOST= "host";
public const string ARG_METADATA_RR_PORT= "metadata_rrport";
public const string ARG_DATA_RR_PORT= "data_rrport";
public const string ARG_DATA_NOTIF_PORT= "data_notifport";
public const string ARG_NAME= "name";
public static void Main(string [] args) {
if (args.Length == 0) Help();
_log.Info("Lightstreamer StockListDemo .NET Adapter Standalone Server starting...");
Server.SetLoggerProvider(new Log4NetLoggerProviderWrapper());
IDictionary parameters = new Hashtable();
string host= null;
int rrPortMD= -1;
int rrPortD= -1;
int notifPortD= -1;
string name= null;
for (int i= 0; i < args.Length; i++) {
string arg= args[i];
if (arg.StartsWith(PREFIX1) || arg.StartsWith(PREFIX2)) {
arg= arg.Substring(1).ToLower();
if (arg.Equals(ARG_HELP_SHORT) || arg.Equals(ARG_HELP_LONG)) {
Help();
}
else if (arg.Equals(ARG_HOST)) {
i++;
host= args[i];
_log.Debug("Found argument: '" + ARG_HOST + "' with value: '" + host + "'");
}
else if (arg.Equals(ARG_METADATA_RR_PORT)) {
i++;
rrPortMD= Int32.Parse(args[i]);
_log.Debug("Found argument: '" + ARG_METADATA_RR_PORT + "' with value: '" + rrPortMD + "'");
}
else if (arg.Equals(ARG_DATA_RR_PORT)) {
i++;
rrPortD= Int32.Parse(args[i]);
_log.Debug("Found argument: '" + ARG_DATA_RR_PORT + "' with value: '" + rrPortD + "'");
}
else if (arg.Equals(ARG_DATA_NOTIF_PORT)) {
i++;
notifPortD= Int32.Parse(args[i]);
_log.Debug("Found argument: '" + ARG_DATA_NOTIF_PORT + "' with value: '" + notifPortD + "'");
}
else if (arg.Equals(ARG_NAME)) {
i++;
name= args[i];
_log.Debug("Found argument: '" + ARG_NAME + "' with value: '" + name + "'");
}
}
else {
int sep= arg.IndexOf(SEP);
if (sep < 1) {
_log.Warn("Skipping unrecognizable argument: '" + arg + "'");
}
else {
string par= arg.Substring(0, sep).Trim();
string val= arg.Substring(sep +1).Trim();
parameters[par]= val;
_log.Debug("Found parameter: '" + par + "' with value: '" + val + "'");
}
}
}
try {
{
MetadataProviderServer server = new MetadataProviderServer();
server.Adapter = new Lightstreamer.Adapters.Metadata.LiteralBasedProvider();
server.AdapterParams = parameters;
// server.AdapterConfig not needed by LiteralBasedProvider
if (name != null) server.Name = name;
_log.Debug("Remote Metadata Adapter initialized");
ServerStarter starter = new ServerStarter(host, rrPortMD, -1);
starter.Launch(server);
}
{
DataProviderServer server = new DataProviderServer();
server.Adapter = new Lightstreamer.Adapters.StockListDemo.Data.StockListDemoAdapter();
// server.AdapterParams not needed by StockListDemoAdapter
// server.AdapterConfig not needed by StockListDemoAdapter
if (name != null) server.Name = name;
_log.Debug("Remote Data Adapter initialized");
ServerStarter starter = new ServerStarter(host, rrPortD, notifPortD);
starter.Launch(server);
}
}
catch (Exception e) {
_log.Fatal("Exception caught while starting the server: " + e.Message + ", aborting...", e);
}
_log.Info("Lightstreamer StockListDemo .NET Adapter Standalone Server running");
}
private static void Help() {
_log.Fatal("Lightstreamer StockListDemo .NET Adapter Standalone Server Help");
_log.Fatal("Usage: DotNetStockListDemoLauncher");
_log.Fatal(" [/name <name>] /host <address>");
_log.Fatal(" /metadata_rrport <port> /data_rrport <port> /data_notifport <port>");
_log.Fatal(" [\"<param1>=<value1>\" ... \"<paramN>=<valueN>\"]");
_log.Fatal("Where: <name> is the symbolic name for both the adapters (1)");
_log.Fatal(" <address> is the host name or ip address of LS server (2)");
_log.Fatal(" <port> is the tcp port number where LS proxy is listening on (3)");
_log.Fatal(" <paramN> is the Nth metadata adapter parameter name (4)");
_log.Fatal(" <valueN> is the value of the Nth metadata adapter parameter (4)");
_log.Fatal("Notes: (1) The adapter name is optional, if it is not given the adapter will be");
_log.Fatal(" assigned a progressive number name like \"#1\", \"#2\" and so on");
_log.Fatal(" (2) The communication will be from here to LS, not viceversa");
_log.Fatal(" (3) The notification port is necessary for a Data Adapter, while it is");
_log.Fatal(" not needed for a Metadata Adapter");
_log.Fatal(" (4) The parameters name/value pairs will be passed to the LiteralBasedProvider");
_log.Fatal(" Metadata Adapter as a Hashtable in the \"parameters\" Init() argument");
_log.Fatal(" The StockListDemo Data Adapter requires no parameters");
_log.Fatal("Aborting...");
System.Environment.Exit(9);
}
}
public class ServerStarter : IExceptionHandler {
private static ILog _log= LogManager.GetLogger("Lightstreamer.Adapters.StockListDemo.ServerStarter");
private Server _server;
private bool _closed;
private string _host;
private int _rrPort;
private int _notifPort;
public ServerStarter(string host, int rrPort, int notifPort) {
_host= host;
_rrPort= rrPort;
_notifPort= notifPort;
}
public void Launch(Server server) {
_server = server;
_closed = false;
_server.ExceptionHandler = this;
Thread t= new Thread(new ThreadStart(Run));
t.Start();
}
public void Run() {
TcpClient _rrSocket = null;
TcpClient _notifSocket = null;
do {
_log.Info("Connecting...");
try {
_log.Info("Opening connection on port " + _rrPort + "...");
_rrSocket = new TcpClient(_host, _rrPort);
if (_notifPort >= 0)
{
_log.Info("Opening connection on port " + _notifPort + "...");
_notifSocket = new TcpClient(_host, _notifPort);
}
_log.Info("Connected");
break;
}
catch (SocketException) {
_log.Warn("Connection failed, retrying in 10 seconds...");
Thread.Sleep(10000);
}
} while (true);
_server.RequestStream= _rrSocket.GetStream();
_server.ReplyStream= _rrSocket.GetStream();
if (_notifSocket != null) _server.NotifyStream= _notifSocket.GetStream();
_server.Start();
}
public bool handleIOException(Exception exception) {
_log.Error("Connection to Lightstreamer Server closed");
_closed = true;
_server.Close();
System.Environment.Exit(0);
return false;
}
public bool handleException(Exception exception) {
if (! _closed) {
_log.Error("Caught exception: " + exception.Message, exception);
_server.Close();
System.Environment.Exit(1);
}
return false;
}
// Notes about exception handling.
//
// In case of exception, the whole Remote Server process instance
// can no longer be used;
// closing it also ensures that the Proxy Adapter closes
// (thus causing Lightstreamer Server to close)
// or recovers by accepting connections from a new Remote
// Server process instance.
//
// Keeping the process instance alive and replacing the Server
// class instances would be possible.
// This would issue new connections with Lightstreamer Server.
// However, new instances of the Remote Adapters would also be needed
// and a cleanup of the current instances should be performed,
// by invoking them directly through a custom method.
}
}
| |
//Some of this file was refactored by 'veer' of http://www.moparscape.org.
using System;
namespace Rs317.Sharp
{
sealed class Instrument
{
public static void initialise()
{
noise = new int[32768];
for(int noiseId = 0; noiseId < 32768; noiseId++)
if(StaticRandomGenerator.Next() > 0.5D)
noise[noiseId] = 1;
else
noise[noiseId] = -1;
sine = new int[32768];
for(int sineId = 0; sineId < 32768; sineId++)
sine[sineId] = (int)(Math.Sin(sineId / 5215.1903000000002D) * 16384D);
output = new int[0x35d54];
}
/*
* an impl of a wavetable synthesizer that generates square/sine/saw/noise/flat
* tables and supports phase and amplitude modulation
*
* more: http://musicdsp.org/files/Wavetable-101.pdf
*/
private Envelope pitchEnvelope;
private Envelope volumeEnvelope;
private Envelope pitchModulationEnvelope;
private Envelope pitchModulationAmplitudeEnvelope;
private Envelope volumeModulationEnvelope;
private Envelope volumeModulationAmplitude;
private Envelope gatingReleaseEnvelope;
private Envelope gatingAttackEnvelope;
private int[] oscillationVolume;
private int[] oscillationPitch;
private int[] oscillationDelay;
private int delayTime;
private int delayFeedback;
private SoundFilter filter;
private Envelope filterEnvelope;
public int duration { get; internal set; }
public int begin { get; internal set; }
private static int[] output;
private static int[] noise;
private static int[] sine;
private static int[] phases = new int[5];
private static int[] delays = new int[5];
private static int[] volumeStep = new int[5];
private static int[] pitchStep = new int[5];
private static int[] pitchBaseStep = new int[5];
public Instrument()
{
oscillationVolume = new int[5];
oscillationPitch = new int[5];
oscillationDelay = new int[5];
delayFeedback = 100;
duration = 500;
}
public void decode(Default317Buffer stream)
{
pitchEnvelope = new Envelope();
pitchEnvelope.decode(stream);
volumeEnvelope = new Envelope();
volumeEnvelope.decode(stream);
int option = stream.getUnsignedByte();
if(option != 0)
{
stream.position--;
pitchModulationEnvelope = new Envelope();
pitchModulationEnvelope.decode(stream);
pitchModulationAmplitudeEnvelope = new Envelope();
pitchModulationAmplitudeEnvelope.decode(stream);
}
option = stream.getUnsignedByte();
if(option != 0)
{
stream.position--;
volumeModulationEnvelope = new Envelope();
volumeModulationEnvelope.decode(stream);
volumeModulationAmplitude = new Envelope();
volumeModulationAmplitude.decode(stream);
}
option = stream.getUnsignedByte();
if(option != 0)
{
stream.position--;
gatingReleaseEnvelope = new Envelope();
gatingReleaseEnvelope.decode(stream);
gatingAttackEnvelope = new Envelope();
gatingAttackEnvelope.decode(stream);
}
for(int oscillationId = 0; oscillationId < 10; oscillationId++)
{
int volume = stream.getSmartB();
if(volume == 0)
break;
oscillationVolume[oscillationId] = volume;
oscillationPitch[oscillationId] = stream.getSmartA();
oscillationDelay[oscillationId] = stream.getSmartB();
}
delayTime = stream.getSmartB();
delayFeedback = stream.getSmartB();
duration = stream.getUnsignedLEShort();
begin = stream.getUnsignedLEShort();
filter = new SoundFilter();
filterEnvelope = new Envelope();
filter.decode(stream, filterEnvelope);
}
private int evaluateWave(int amplitude, int phase, int table)
{
if(table == 1)
if((phase & 0x7fff) < 16384)
return amplitude;
else
return -amplitude;
if(table == 2)
return sine[phase & 0x7fff] * amplitude >> 14;
if(table == 3)
return ((phase & 0x7fff) * amplitude >> 14) - amplitude;
if(table == 4)
return noise[phase / 2607 & 0x7fff] * amplitude;
else
return 0;
}
public int[] synthesise(int steps, int j)
{
for(int position = 0; position < steps; position++)
output[position] = 0;
if(j < 10)
return output;
double d = steps / (j + 0.0D);
pitchEnvelope.resetValues();
volumeEnvelope.resetValues();
int pitchModulationStep = 0;
int pitchModulationBaseStep = 0;
int pitchModulationPhase = 0;
if(pitchModulationEnvelope != null)
{
pitchModulationEnvelope.resetValues();
pitchModulationAmplitudeEnvelope.resetValues();
pitchModulationStep = (int)(((pitchModulationEnvelope.end - pitchModulationEnvelope.start)
* 32.768000000000001D) / d);
pitchModulationBaseStep = (int)((pitchModulationEnvelope.start * 32.768000000000001D) / d);
}
int volumeModulationStep = 0;
int volumeModulationBaseStep = 0;
int volumeModulationPhase = 0;
if(volumeModulationEnvelope != null)
{
volumeModulationEnvelope.resetValues();
volumeModulationAmplitude.resetValues();
volumeModulationStep = (int)(((volumeModulationEnvelope.end - volumeModulationEnvelope.start)
* 32.768000000000001D) / d);
volumeModulationBaseStep = (int)((volumeModulationEnvelope.start * 32.768000000000001D) / d);
}
for(int oscillationVolumeId = 0; oscillationVolumeId < 5; oscillationVolumeId++)
if(oscillationVolume[oscillationVolumeId] != 0)
{
phases[oscillationVolumeId] = 0;
delays[oscillationVolumeId] = (int)(oscillationDelay[oscillationVolumeId] * d);
volumeStep[oscillationVolumeId] = (oscillationVolume[oscillationVolumeId] << 14) / 100;
pitchStep[oscillationVolumeId] = (int)(((pitchEnvelope.end - pitchEnvelope.start) * 32.768000000000001D
* Math.Pow(1.0057929410678534D, oscillationPitch[oscillationVolumeId])) / d);
pitchBaseStep[oscillationVolumeId] = (int)((pitchEnvelope.start * 32.768000000000001D) / d);
}
for(int offset = 0; offset < steps; offset++)
{
int pitchChange = pitchEnvelope.step(steps);
int volumeChange = volumeEnvelope.step(steps);
if(pitchModulationEnvelope != null)
{
int modulation = pitchModulationEnvelope.step(steps);
int modulationAmplitude = pitchModulationAmplitudeEnvelope.step(steps);
pitchChange += evaluateWave(modulationAmplitude, pitchModulationPhase,
pitchModulationEnvelope.form) >> 1;
pitchModulationPhase += (modulation * pitchModulationStep >> 16) + pitchModulationBaseStep;
}
if(volumeModulationEnvelope != null)
{
int modulation = volumeModulationEnvelope.step(steps);
int modulationAmplitude = volumeModulationAmplitude.step(steps);
volumeChange = volumeChange * ((evaluateWave(modulationAmplitude, volumeModulationPhase,
volumeModulationEnvelope.form) >> 1) + 32768) >> 15;
volumeModulationPhase += (modulation * volumeModulationStep >> 16) + volumeModulationBaseStep;
}
for(int oscillationId = 0; oscillationId < 5; oscillationId++)
if(oscillationVolume[oscillationId] != 0)
{
int position = offset + delays[oscillationId];
if(position < steps)
{
output[position] += evaluateWave(volumeChange * volumeStep[oscillationId] >> 15,
phases[oscillationId], pitchEnvelope.form);
phases[oscillationId] += (pitchChange * pitchStep[oscillationId] >> 16)
+ pitchBaseStep[oscillationId];
}
}
}
if(gatingReleaseEnvelope != null)
{
gatingReleaseEnvelope.resetValues();
gatingAttackEnvelope.resetValues();
int counter = 0;
bool muted = true;
for(int position = 0; position < steps; position++)
{
int stepOn = gatingReleaseEnvelope.step(steps);
int stepOff = gatingAttackEnvelope.step(steps);
int threshold;
if(muted)
threshold = gatingReleaseEnvelope.start
+ ((gatingReleaseEnvelope.end - gatingReleaseEnvelope.start) * stepOn >> 8);
else
threshold = gatingReleaseEnvelope.start
+ ((gatingReleaseEnvelope.end - gatingReleaseEnvelope.start) * stepOff >> 8);
if((counter += 256) >= threshold)
{
counter = 0;
muted = !muted;
}
if(muted)
output[position] = 0;
}
}
if(delayTime > 0 && delayFeedback > 0)
{
int delay = (int)(delayTime * d);
for(int position = delay; position < steps; position++)
output[position] += (output[position - delay] * delayFeedback) / 100;
}
if(filter.pairCount[0] > 0 || filter.pairCount[1] > 0)
{
filterEnvelope.resetValues();
int t = filterEnvelope.step(steps + 1);
int M = filter.compute(0, t / 65536F);
int N = filter.compute(1, t / 65536F);
if(steps >= M + N)
{
int n = 0;
int delay = N;
if(delay > steps - M)
delay = steps - M;
for(; n < delay; n++)
{
int y = (int)((long)output[n + M] * (long)SoundFilter.invUnity >> 16);
for(int k8 = 0; k8 < M; k8++)
y += (int)((long)output[(n + M) - 1 - k8] * (long)SoundFilter.coefficient[0, k8] >> 16);
for(int j9 = 0; j9 < n; j9++)
y -= (int)((long)output[n - 1 - j9] * (long)SoundFilter.coefficient[1, j9] >> 16);
output[n] = y;
t = filterEnvelope.step(steps + 1);
}
//Thanks to RS2Sharp
char offset = (char)128; // 128
delay = offset;
do
{
if(delay > steps - M)
delay = steps - M;
for(; n < delay; n++)
{
int y = (int)((long)output[n + M] * (long)SoundFilter.invUnity >> 16);
for(int position = 0; position < M; position++)
y += (int)((long)output[(n + M) - 1 - position]
* (long)SoundFilter.coefficient[0, position] >> 16);
for(int position = 0; position < N; position++)
y -= (int)((long)output[n - 1 - position]
* (long)SoundFilter.coefficient[1, position] >> 16);
output[n] = y;
t = filterEnvelope.step(steps + 1);
}
if(n >= steps - M)
break;
M = filter.compute(0, t / 65536F);
N = filter.compute(1, t / 65536F);
delay += offset;
} while(true);
for(; n < steps; n++)
{
int y = 0;
for(int position = (n + M) - steps; position < M; position++)
y += (int)((long)output[(n + M) - 1 - position]
* (long)SoundFilter.coefficient[0, position] >> 16);
for(int position = 0; position < N; position++)
y -= (int)((long)output[n - 1 - position]
* (long)SoundFilter.coefficient[1, position] >> 16);
output[n] = y;
}
}
}
for(int position = 0; position < steps; position++)
{
if(output[position] < -32768)
output[position] = -32768;
if(output[position] > 32767)
output[position] = 32767;
}
return output;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Analysis
{
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// ServersOperations operations.
/// </summary>
public partial interface IServersOperations
{
/// <summary>
/// Gets details about the specified Analysis Services server
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Azure Resource group which a given Analysis Services
/// server is part of.
/// </param>
/// <param name='serverName'>
/// Name of the Analysis Services server
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<AnalysisServicesServer>> GetDetailsWithHttpMessagesAsync(string resourceGroupName, string serverName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Provisions the specified Analysis Services server based on the
/// configuration specified in the request
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Azure Resource group which a given Analysis Services
/// server is part of.
/// </param>
/// <param name='serverName'>
/// Name of the Analysis Services server
/// </param>
/// <param name='serverParameters'>
/// Request body for provisioning
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<AnalysisServicesServer>> CreateWithHttpMessagesAsync(string resourceGroupName, string serverName, AnalysisServicesServer serverParameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Provisions the specified Analysis Services server based on the
/// configuration specified in the request
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Azure Resource group which a given Analysis Services
/// server is part of.
/// </param>
/// <param name='serverName'>
/// Name of the Analysis Services server
/// </param>
/// <param name='serverParameters'>
/// Request body for provisioning
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<AnalysisServicesServer>> BeginCreateWithHttpMessagesAsync(string resourceGroupName, string serverName, AnalysisServicesServer serverParameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Deletes the specified Analysis Services server.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Azure Resource group which a given Analysis Services
/// server is part of.
/// </param>
/// <param name='serverName'>
/// Name of the Analysis Services server
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string serverName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Deletes the specified Analysis Services server.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Azure Resource group which a given Analysis Services
/// server is part of.
/// </param>
/// <param name='serverName'>
/// Name of the Analysis Services server
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string serverName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Updates the current state of the specified Analysis Services server
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Azure Resource group which a given Analysis Services
/// server is part of.
/// </param>
/// <param name='serverName'>
/// Name of the Analysis Services server
/// </param>
/// <param name='serverUpdateParameters'>
/// Request object for updating the server
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<AnalysisServicesServer>> UpdateWithHttpMessagesAsync(string resourceGroupName, string serverName, AnalysisServicesServerUpdateParameters serverUpdateParameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Supends the specified Analysis Services server instance
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Azure Resource group which a given Analysis Services
/// server is part of.
/// </param>
/// <param name='serverName'>
/// Name of the Analysis Services server
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> SuspendWithHttpMessagesAsync(string resourceGroupName, string serverName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Supends the specified Analysis Services server instance
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Azure Resource group which a given Analysis Services
/// server is part of.
/// </param>
/// <param name='serverName'>
/// Name of the Analysis Services server
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> BeginSuspendWithHttpMessagesAsync(string resourceGroupName, string serverName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Resumes the specified Analysis Services server instance
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Azure Resource group which a given Analysis Services
/// server is part of.
/// </param>
/// <param name='serverName'>
/// Name of the Analysis Services server
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> ResumeWithHttpMessagesAsync(string resourceGroupName, string serverName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Resumes the specified Analysis Services server instance
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Azure Resource group which a given Analysis Services
/// server is part of.
/// </param>
/// <param name='serverName'>
/// Name of the Analysis Services server
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> BeginResumeWithHttpMessagesAsync(string resourceGroupName, string serverName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Gets all the Analysis Services servers for the given resource group
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Azure Resource group which a given Analysis Services
/// server is part of.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<System.Collections.Generic.IEnumerable<AnalysisServicesServer>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// List all the Analysis Services servers for the given subscription
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<System.Collections.Generic.IEnumerable<AnalysisServicesServer>>> ListWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
}
}
| |
#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.Collections.ObjectModel;
using System.Reflection;
using System.Text;
using System.Collections;
using System.Linq;
using System.Globalization;
namespace Newtonsoft.Json.Utilities
{
internal static class CollectionUtils
{
public static IEnumerable<T> CastValid<T>(this IEnumerable enumerable)
{
ValidationUtils.ArgumentNotNull(enumerable, "enumerable");
return enumerable.Cast<object>().Where(o => o is T).Cast<T>();
}
public static List<T> CreateList<T>(params T[] values)
{
return new List<T>(values);
}
/// <summary>
/// Determines whether the collection is null or empty.
/// </summary>
/// <param name="collection">The collection.</param>
/// <returns>
/// <c>true</c> if the collection is null or empty; otherwise, <c>false</c>.
/// </returns>
public static bool IsNullOrEmpty(ICollection collection)
{
if (collection != null)
{
return (collection.Count == 0);
}
return true;
}
/// <summary>
/// Determines whether the collection is null or empty.
/// </summary>
/// <param name="collection">The collection.</param>
/// <returns>
/// <c>true</c> if the collection is null or empty; otherwise, <c>false</c>.
/// </returns>
public static bool IsNullOrEmpty<T>(ICollection<T> collection)
{
if (collection != null)
{
return (collection.Count == 0);
}
return true;
}
/// <summary>
/// Determines whether the collection is null, empty or its contents are uninitialized values.
/// </summary>
/// <param name="list">The list.</param>
/// <returns>
/// <c>true</c> if the collection is null or empty or its contents are uninitialized values; otherwise, <c>false</c>.
/// </returns>
public static bool IsNullOrEmptyOrDefault<T>(IList<T> list)
{
if (IsNullOrEmpty<T>(list))
return true;
return ReflectionUtils.ItemsUnitializedValue<T>(list);
}
/// <summary>
/// Makes a slice of the specified list in between the start and end indexes.
/// </summary>
/// <param name="list">The list.</param>
/// <param name="start">The start index.</param>
/// <param name="end">The end index.</param>
/// <returns>A slice of the list.</returns>
public static IList<T> Slice<T>(IList<T> list, int? start, int? end)
{
return Slice<T>(list, start, end, null);
}
/// <summary>
/// Makes a slice of the specified list in between the start and end indexes,
/// getting every so many items based upon the step.
/// </summary>
/// <param name="list">The list.</param>
/// <param name="start">The start index.</param>
/// <param name="end">The end index.</param>
/// <param name="step">The step.</param>
/// <returns>A slice of the list.</returns>
public static IList<T> Slice<T>(IList<T> list, int? start, int? end, int? step)
{
if (list == null)
throw new ArgumentNullException("list");
if (step == 0)
throw new ArgumentException("Step cannot be zero.", "step");
List<T> slicedList = new List<T>();
// nothing to slice
if (list.Count == 0)
return slicedList;
// set defaults for null arguments
int s = step ?? 1;
int startIndex = start ?? 0;
int endIndex = end ?? list.Count;
// start from the end of the list if start is negitive
startIndex = (startIndex < 0) ? list.Count + startIndex : startIndex;
// end from the start of the list if end is negitive
endIndex = (endIndex < 0) ? list.Count + endIndex : endIndex;
// ensure indexes keep within collection bounds
startIndex = Math.Max(startIndex, 0);
endIndex = Math.Min(endIndex, list.Count - 1);
// loop between start and end indexes, incrementing by the step
for (int i = startIndex; i < endIndex; i += s)
{
slicedList.Add(list[i]);
}
return slicedList;
}
/// <summary>
/// Group the collection using a function which returns the key.
/// </summary>
/// <param name="source">The source collection to group.</param>
/// <param name="keySelector">The key selector.</param>
/// <returns>A Dictionary with each key relating to a list of objects in a list grouped under it.</returns>
public static Dictionary<K, List<V>> GroupBy<K, V>(ICollection<V> source, Func<V, K> keySelector)
{
if (keySelector == null)
throw new ArgumentNullException("keySelector");
Dictionary<K, List<V>> groupedValues = new Dictionary<K, List<V>>();
foreach (V value in source)
{
// using delegate to get the value's key
K key = keySelector(value);
List<V> groupedValueList;
// add a list for grouped values if the key is not already in Dictionary
if (!groupedValues.TryGetValue(key, out groupedValueList))
{
groupedValueList = new List<V>();
groupedValues.Add(key, groupedValueList);
}
groupedValueList.Add(value);
}
return groupedValues;
}
/// <summary>
/// Adds the elements of the specified collection to the specified generic IList.
/// </summary>
/// <param name="initial">The list to add to.</param>
/// <param name="collection">The collection of elements to add.</param>
public static void AddRange<T>(this IList<T> initial, IEnumerable<T> collection)
{
if (initial == null)
throw new ArgumentNullException("initial");
if (collection == null)
return;
foreach (T value in collection)
{
initial.Add(value);
}
}
public static void AddRange(this IList initial, IEnumerable collection)
{
ValidationUtils.ArgumentNotNull(initial, "initial");
ListWrapper<object> wrapper = new ListWrapper<object>(initial);
wrapper.AddRange(collection.Cast<object>());
}
public static List<T> Distinct<T>(List<T> collection)
{
List<T> distinctList = new List<T>();
foreach (T value in collection)
{
if (!distinctList.Contains(value))
distinctList.Add(value);
}
return distinctList;
}
public static List<List<T>> Flatten<T>(params IList<T>[] lists)
{
List<List<T>> flattened = new List<List<T>>();
Dictionary<int, T> currentList = new Dictionary<int, T>();
Recurse<T>(new List<IList<T>>(lists), 0, currentList, flattened);
return flattened;
}
private static void Recurse<T>(IList<IList<T>> global, int current, Dictionary<int, T> currentSet, List<List<T>> flattenedResult)
{
IList<T> currentArray = global[current];
for (int i = 0; i < currentArray.Count; i++)
{
currentSet[current] = currentArray[i];
if (current == global.Count - 1)
{
List<T> items = new List<T>();
for (int k = 0; k < currentSet.Count; k++)
{
items.Add(currentSet[k]);
}
flattenedResult.Add(items);
}
else
{
Recurse(global, current + 1, currentSet, flattenedResult);
}
}
}
public static List<T> CreateList<T>(ICollection collection)
{
if (collection == null)
throw new ArgumentNullException("collection");
T[] array = new T[collection.Count];
collection.CopyTo(array, 0);
return new List<T>(array);
}
public static bool ListEquals<T>(IList<T> a, IList<T> b)
{
if (a == null || b == null)
return (a == null && b == null);
if (a.Count != b.Count)
return false;
EqualityComparer<T> comparer = EqualityComparer<T>.Default;
for (int i = 0; i < a.Count; i++)
{
if (!comparer.Equals(a[i], b[i]))
return false;
}
return true;
}
#region GetSingleItem
public static bool TryGetSingleItem<T>(IList<T> list, out T value)
{
return TryGetSingleItem<T>(list, false, out value);
}
public static bool TryGetSingleItem<T>(IList<T> list, bool returnDefaultIfEmpty, out T value)
{
return MiscellaneousUtils.TryAction<T>(delegate { return GetSingleItem(list, returnDefaultIfEmpty); }, out value);
}
public static T GetSingleItem<T>(IList<T> list)
{
return GetSingleItem<T>(list, false);
}
public static T GetSingleItem<T>(IList<T> list, bool returnDefaultIfEmpty)
{
if (list.Count == 1)
return list[0];
else if (returnDefaultIfEmpty && list.Count == 0)
return default(T);
else
throw new Exception("Expected single {0} in list but got {1}.".FormatWith(CultureInfo.InvariantCulture, typeof(T), list.Count));
}
#endregion
public static IList<T> Minus<T>(IList<T> list, IList<T> minus)
{
ValidationUtils.ArgumentNotNull(list, "list");
List<T> result = new List<T>(list.Count);
foreach (T t in list)
{
if (minus == null || !minus.Contains(t))
result.Add(t);
}
return result;
}
public static T[] CreateArray<T>(IEnumerable<T> enumerable)
{
ValidationUtils.ArgumentNotNull(enumerable, "enumerable");
if (enumerable is T[])
return (T[])enumerable;
List<T> tempList = new List<T>(enumerable);
return tempList.ToArray();
}
public static IList CreateGenericList(Type listType)
{
ValidationUtils.ArgumentNotNull(listType, "listType");
return (IList)ReflectionUtils.CreateGeneric(typeof(List<>), listType);
}
public static IDictionary CreateGenericDictionary(Type keyType, Type valueType)
{
ValidationUtils.ArgumentNotNull(keyType, "keyType");
ValidationUtils.ArgumentNotNull(valueType, "valueType");
return (IDictionary)ReflectionUtils.CreateGeneric(typeof(Dictionary<,>), keyType, valueType);
}
public static bool IsListType(Type type)
{
ValidationUtils.ArgumentNotNull(type, "type");
if (type.IsArray)
return true;
if (typeof(IList).IsAssignableFrom(type))
return true;
if (ReflectionUtils.ImplementsGenericDefinition(type, typeof(IList<>)))
return true;
return false;
}
public static bool IsCollectionType(Type type)
{
ValidationUtils.ArgumentNotNull(type, "type");
if (type.IsArray)
return true;
if (typeof(ICollection).IsAssignableFrom(type))
return true;
if (ReflectionUtils.ImplementsGenericDefinition(type, typeof(ICollection<>)))
return true;
return false;
}
public static bool IsDictionaryType(Type type)
{
ValidationUtils.ArgumentNotNull(type, "type");
if (typeof(IDictionary).IsAssignableFrom(type))
return true;
if (ReflectionUtils.ImplementsGenericDefinition(type, typeof (IDictionary<,>)))
return true;
return false;
}
public static IWrappedCollection CreateCollectionWrapper(object list)
{
ValidationUtils.ArgumentNotNull(list, "list");
Type collectionDefinition;
if (ReflectionUtils.ImplementsGenericDefinition(list.GetType(), typeof(ICollection<>), out collectionDefinition))
{
Type collectionItemType = ReflectionUtils.GetCollectionItemType(collectionDefinition);
// Activator.CreateInstance throws AmbiguousMatchException. Manually invoke constructor
Func<Type, IList<object>, object> instanceCreator = (t, a) =>
{
ConstructorInfo c = t.GetConstructor(new[] { collectionDefinition });
return c.Invoke(new[] { list });
};
return (IWrappedCollection)ReflectionUtils.CreateGeneric(typeof(CollectionWrapper<>), new[] { collectionItemType }, instanceCreator, list);
}
else if (list is IList)
{
return new CollectionWrapper<object>((IList)list);
}
else
{
throw new Exception("Can not create ListWrapper for type {0}.".FormatWith(CultureInfo.InvariantCulture, list.GetType()));
}
}
public static IWrappedList CreateListWrapper(object list)
{
ValidationUtils.ArgumentNotNull(list, "list");
Type listDefinition;
if (ReflectionUtils.ImplementsGenericDefinition(list.GetType(), typeof(IList<>), out listDefinition))
{
Type collectionItemType = ReflectionUtils.GetCollectionItemType(listDefinition);
// Activator.CreateInstance throws AmbiguousMatchException. Manually invoke constructor
Func<Type, IList<object>, object> instanceCreator = (t, a) =>
{
ConstructorInfo c = t.GetConstructor(new[] {listDefinition});
return c.Invoke(new[] { list });
};
return (IWrappedList)ReflectionUtils.CreateGeneric(typeof(ListWrapper<>), new[] { collectionItemType }, instanceCreator, list);
}
else if (list is IList)
{
return new ListWrapper<object>((IList)list);
}
else
{
throw new Exception("Can not create ListWrapper for type {0}.".FormatWith(CultureInfo.InvariantCulture, list.GetType()));
}
}
public static IWrappedDictionary CreateDictionaryWrapper(object dictionary)
{
ValidationUtils.ArgumentNotNull(dictionary, "dictionary");
Type dictionaryDefinition;
if (ReflectionUtils.ImplementsGenericDefinition(dictionary.GetType(), typeof(IDictionary<,>), out dictionaryDefinition))
{
Type dictionaryKeyType = ReflectionUtils.GetDictionaryKeyType(dictionaryDefinition);
Type dictionaryValueType = ReflectionUtils.GetDictionaryValueType(dictionaryDefinition);
// Activator.CreateInstance throws AmbiguousMatchException. Manually invoke constructor
Func<Type, IList<object>, object> instanceCreator = (t, a) =>
{
ConstructorInfo c = t.GetConstructor(new[] { dictionaryDefinition });
return c.Invoke(new[] { dictionary });
};
return (IWrappedDictionary)ReflectionUtils.CreateGeneric(typeof(DictionaryWrapper<,>), new[] { dictionaryKeyType, dictionaryValueType }, instanceCreator, dictionary);
}
else if (dictionary is IDictionary)
{
return new DictionaryWrapper<object, object>((IDictionary)dictionary);
}
else
{
throw new Exception("Can not create DictionaryWrapper for type {0}.".FormatWith(CultureInfo.InvariantCulture, dictionary.GetType()));
}
}
public static IList CreateAndPopulateList(Type listType, Action<IList> populateList)
{
ValidationUtils.ArgumentNotNull(listType, "listType");
ValidationUtils.ArgumentNotNull(populateList, "populateList");
IList list;
Type collectionType;
bool isReadOnlyOrFixedSize = false;
if (listType.IsArray)
{
// have to use an arraylist when creating array
// there is no way to know the size until it is finised
list = new List<object>();
isReadOnlyOrFixedSize = true;
}
else if (ReflectionUtils.InheritsGenericDefinition(listType, typeof(ReadOnlyCollection<>), out collectionType))
{
Type readOnlyCollectionContentsType = collectionType.GetGenericArguments()[0];
Type genericEnumerable = ReflectionUtils.MakeGenericType(typeof(IEnumerable<>), readOnlyCollectionContentsType);
bool suitableConstructor = false;
foreach (ConstructorInfo constructor in listType.GetConstructors())
{
IList<ParameterInfo> parameters = constructor.GetParameters();
if (parameters.Count == 1)
{
if (genericEnumerable.IsAssignableFrom(parameters[0].ParameterType))
{
suitableConstructor = true;
break;
}
}
}
if (!suitableConstructor)
throw new Exception("Read-only type {0} does not have a public constructor that takes a type that implements {1}.".FormatWith(CultureInfo.InvariantCulture, listType, genericEnumerable));
// can't add or modify a readonly list
// use List<T> and convert once populated
list = (IList)CreateGenericList(readOnlyCollectionContentsType);
isReadOnlyOrFixedSize = true;
}
else if (typeof(IList).IsAssignableFrom(listType))
{
if (ReflectionUtils.IsInstantiatableType(listType))
list = (IList)Activator.CreateInstance(listType);
else if (listType == typeof(IList))
list = new List<object>();
else
list = null;
}
else if (listType.IsGenericType && listType.GetGenericTypeDefinition() == typeof(IList<>))
{
list = CollectionUtils.CreateGenericList(ReflectionUtils.GetCollectionItemType(listType));
}
else
{
list = null;
}
if (list == null)
throw new Exception("Cannot create and populate list type {0}.".FormatWith(CultureInfo.InvariantCulture, listType));
populateList(list);
// create readonly and fixed sized collections using the temporary list
if (isReadOnlyOrFixedSize)
{
if (listType.IsArray)
list = ToArray(((List<object>)list).ToArray(), ReflectionUtils.GetCollectionItemType(listType));
else if (ReflectionUtils.InheritsGenericDefinition(listType, typeof(ReadOnlyCollection<>)))
list = (IList)ReflectionUtils.CreateInstance(listType, list);
}
return list;
}
public static Array ToArray(Array initial, Type type)
{
if (type == null)
throw new ArgumentNullException("type");
Array destinationArray = Array.CreateInstance(type, initial.Length);
Array.Copy(initial, 0, destinationArray, 0, initial.Length);
return destinationArray;
}
public static bool AddDistinct<T>(this IList<T> list, T value)
{
return list.AddDistinct(value, EqualityComparer<T>.Default);
}
public static bool AddDistinct<T>(this IList<T> list, T value, IEqualityComparer<T> comparer)
{
if (list.Contains(value, comparer))
return false;
list.Add(value);
return true;
}
public static bool AddRangeDistinct<T>(this IList<T> list, IEnumerable<T> values)
{
return list.AddRangeDistinct(values, EqualityComparer<T>.Default);
}
public static bool AddRangeDistinct<T>(this IList<T> list, IEnumerable<T> values, IEqualityComparer<T> comparer)
{
bool allAdded = true;
foreach (T value in values)
{
if (!list.AddDistinct(value, comparer))
allAdded = false;
}
return allAdded;
}
}
}
| |
//---------------------------------------------------------------------------
//
// File: HtmlFromXamlConverter.cs
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// Description: Prototype for Xaml - Html conversion
//
//---------------------------------------------------------------------------
namespace HtmlToXamlConversion
{
using System;
using System.Diagnostics;
using System.Text;
using System.IO;
using System.Xml;
/// <summary>
/// HtmlToXamlConverter is a static class that takes an HTML string
/// and converts it into XAML
/// </summary>
internal static class HtmlFromXamlConverter
{
// ---------------------------------------------------------------------
//
// Internal Methods
//
// ---------------------------------------------------------------------
#region Internal Methods
/// <summary>
/// Main entry point for Xaml-to-Html converter.
/// Converts a xaml string into html string.
/// </summary>
/// <param name="xamlString">
/// Xaml strinng to convert.
/// </param>
/// <returns>
/// Html string produced from a source xaml.
/// </returns>
internal static string ConvertXamlToHtml(string xamlString)
{
XmlTextReader xamlReader;
StringBuilder htmlStringBuilder;
XmlTextWriter htmlWriter;
xamlReader = new XmlTextReader(new StringReader(xamlString));
htmlStringBuilder = new StringBuilder(100);
htmlWriter = new XmlTextWriter(new StringWriter(htmlStringBuilder));
if (!WriteFlowDocument(xamlReader, htmlWriter))
{
return "";
}
string htmlString = htmlStringBuilder.ToString();
return htmlString;
}
#endregion Internal Methods
// ---------------------------------------------------------------------
//
// Private Methods
//
// ---------------------------------------------------------------------
#region Private Methods
/// <summary>
/// Processes a root level element of XAML (normally it's FlowDocument element).
/// </summary>
/// <param name="xamlReader">
/// XmlTextReader for a source xaml.
/// </param>
/// <param name="htmlWriter">
/// XmlTextWriter producing resulting html
/// </param>
private static bool WriteFlowDocument(XmlTextReader xamlReader, XmlTextWriter htmlWriter)
{
if (!ReadNextToken(xamlReader))
{
// Xaml content is empty - nothing to convert
return false;
}
if (xamlReader.NodeType != XmlNodeType.Element || xamlReader.Name != "FlowDocument")
{
// Root FlowDocument elemet is missing
return false;
}
// Create a buffer StringBuilder for collecting css properties for inline STYLE attributes
// on every element level (it will be re-initialized on every level).
StringBuilder inlineStyle = new StringBuilder();
htmlWriter.WriteStartElement("HTML");
htmlWriter.WriteStartElement("BODY");
WriteFormattingProperties(xamlReader, htmlWriter, inlineStyle);
WriteElementContent(xamlReader, htmlWriter, inlineStyle);
htmlWriter.WriteEndElement();
htmlWriter.WriteEndElement();
return true;
}
/// <summary>
/// Reads attributes of the current xaml element and converts
/// them into appropriate html attributes or css styles.
/// </summary>
/// <param name="xamlReader">
/// XmlTextReader which is expected to be at XmlNodeType.Element
/// (opening element tag) position.
/// The reader will remain at the same level after function complete.
/// </param>
/// <param name="htmlWriter">
/// XmlTextWriter for output html, which is expected to be in
/// after WriteStartElement state.
/// </param>
/// <param name="inlineStyle">
/// String builder for collecting css properties for inline STYLE attribute.
/// </param>
private static void WriteFormattingProperties(XmlTextReader xamlReader, XmlTextWriter htmlWriter, StringBuilder inlineStyle)
{
Debug.Assert(xamlReader.NodeType == XmlNodeType.Element);
// Clear string builder for the inline style
inlineStyle.Remove(0, inlineStyle.Length);
if (!xamlReader.HasAttributes)
{
return;
}
bool borderSet = false;
while (xamlReader.MoveToNextAttribute())
{
string css = null;
switch (xamlReader.Name)
{
// Character fomatting properties
// ------------------------------
case "Background":
css = "background-color:" + ParseXamlColor(xamlReader.Value) + ";";
break;
case "FontFamily":
css = "font-family:" + xamlReader.Value + ";";
break;
case "FontStyle":
css = "font-style:" + xamlReader.Value.ToLower() + ";";
break;
case "FontWeight":
css = "font-weight:" + xamlReader.Value.ToLower() + ";";
break;
case "FontStretch":
break;
case "FontSize":
css = "font-size:" + xamlReader.Value + ";";
break;
case "Foreground":
css = "color:" + ParseXamlColor(xamlReader.Value) + ";";
break;
case "TextDecorations":
css = "text-decoration:underline;";
break;
case "TextEffects":
break;
case "Emphasis":
break;
case "StandardLigatures":
break;
case "Variants":
break;
case "Capitals":
break;
case "Fraction":
break;
// Paragraph formatting properties
// -------------------------------
case "Padding":
css = "padding:" + ParseXamlThickness(xamlReader.Value) + ";";
break;
case "Margin":
css = "margin:" + ParseXamlThickness(xamlReader.Value) + ";";
break;
case "BorderThickness":
css = "border-width:" + ParseXamlThickness(xamlReader.Value) + ";";
borderSet = true;
break;
case "BorderBrush":
css = "border-color:" + ParseXamlColor(xamlReader.Value) + ";";
borderSet = true;
break;
case "LineHeight":
break;
case "TextIndent":
css = "text-indent:" + xamlReader.Value + ";";
break;
case "TextAlignment":
css = "text-align:" + xamlReader.Value + ";";
break;
case "IsKeptTogether":
break;
case "IsKeptWithNext":
break;
case "ColumnBreakBefore":
break;
case "PageBreakBefore":
break;
case "FlowDirection":
break;
// Table attributes
// ----------------
case "Width":
css = "width:" + xamlReader.Value + ";";
break;
case "ColumnSpan":
htmlWriter.WriteAttributeString("COLSPAN", xamlReader.Value);
break;
case "RowSpan":
htmlWriter.WriteAttributeString("ROWSPAN", xamlReader.Value);
break;
}
if (css != null)
{
inlineStyle.Append(css);
}
}
if (borderSet)
{
inlineStyle.Append("border-style:solid;mso-element:para-border-div;");
}
// Return the xamlReader back to element level
xamlReader.MoveToElement();
Debug.Assert(xamlReader.NodeType == XmlNodeType.Element);
}
private static string ParseXamlColor(string color)
{
if (color.StartsWith("#"))
{
// Remove transparancy value
color = "#" + color.Substring(3);
}
return color;
}
private static string ParseXamlThickness(string thickness)
{
string[] values = thickness.Split(',');
for (int i = 0; i < values.Length; i++)
{
double value;
if (double.TryParse(values[i], out value))
{
values[i] = Math.Ceiling(value).ToString();
}
else
{
values[i] = "1";
}
}
string cssThickness;
switch (values.Length)
{
case 1:
cssThickness = thickness;
break;
case 2:
cssThickness = values[1] + " " + values[0];
break;
case 4:
cssThickness = values[1] + " " + values[2] + " " + values[3] + " " + values[0];
break;
default:
cssThickness = values[0];
break;
}
return cssThickness;
}
/// <summary>
/// Reads a content of current xaml element, converts it
/// </summary>
/// <param name="xamlReader">
/// XmlTextReader which is expected to be at XmlNodeType.Element
/// (opening element tag) position.
/// </param>
/// <param name="htmlWriter">
/// May be null, in which case we are skipping the xaml element;
/// witout producing any output to html.
/// </param>
/// <param name="inlineStyle">
/// StringBuilder used for collecting css properties for inline STYLE attribute.
/// </param>
private static void WriteElementContent(XmlTextReader xamlReader, XmlTextWriter htmlWriter, StringBuilder inlineStyle)
{
Debug.Assert(xamlReader.NodeType == XmlNodeType.Element);
bool elementContentStarted = false;
if (xamlReader.IsEmptyElement)
{
if (htmlWriter != null && !elementContentStarted && inlineStyle.Length > 0)
{
// Output STYLE attribute and clear inlineStyle buffer.
htmlWriter.WriteAttributeString("STYLE", inlineStyle.ToString());
inlineStyle.Remove(0, inlineStyle.Length);
}
elementContentStarted = true;
}
else
{
while (ReadNextToken(xamlReader) && xamlReader.NodeType != XmlNodeType.EndElement)
{
switch (xamlReader.NodeType)
{
case XmlNodeType.Element:
if (xamlReader.Name.Contains("."))
{
AddComplexProperty(xamlReader, inlineStyle);
}
else
{
if (htmlWriter != null && !elementContentStarted && inlineStyle.Length > 0)
{
// Output STYLE attribute and clear inlineStyle buffer.
htmlWriter.WriteAttributeString("STYLE", inlineStyle.ToString());
inlineStyle.Remove(0, inlineStyle.Length);
}
elementContentStarted = true;
WriteElement(xamlReader, htmlWriter, inlineStyle);
}
Debug.Assert(xamlReader.NodeType == XmlNodeType.EndElement || xamlReader.NodeType == XmlNodeType.Element && xamlReader.IsEmptyElement);
break;
case XmlNodeType.Comment:
if (htmlWriter != null)
{
if (!elementContentStarted && inlineStyle.Length > 0)
{
htmlWriter.WriteAttributeString("STYLE", inlineStyle.ToString());
}
htmlWriter.WriteComment(xamlReader.Value);
}
elementContentStarted = true;
break;
case XmlNodeType.CDATA:
case XmlNodeType.Text:
case XmlNodeType.SignificantWhitespace:
if (htmlWriter != null)
{
if (!elementContentStarted && inlineStyle.Length > 0)
{
htmlWriter.WriteAttributeString("STYLE", inlineStyle.ToString());
}
htmlWriter.WriteString(xamlReader.Value);
}
elementContentStarted = true;
break;
}
}
Debug.Assert(xamlReader.NodeType == XmlNodeType.EndElement);
}
}
/// <summary>
/// Conberts an element notation of complex property into
/// </summary>
/// <param name="xamlReader">
/// On entry this XmlTextReader must be on Element start tag;
/// on exit - on EndElement tag.
/// </param>
/// <param name="inlineStyle">
/// StringBuilder containing a value for STYLE attribute.
/// </param>
private static void AddComplexProperty(XmlTextReader xamlReader, StringBuilder inlineStyle)
{
Debug.Assert(xamlReader.NodeType == XmlNodeType.Element);
if (inlineStyle != null && xamlReader.Name.EndsWith(".TextDecorations"))
{
inlineStyle.Append("text-decoration:underline;");
}
// Skip the element representing the complex property
WriteElementContent(xamlReader, /*htmlWriter:*/null, /*inlineStyle:*/null);
}
/// <summary>
/// Converts a xaml element into an appropriate html element.
/// </summary>
/// <param name="xamlReader">
/// On entry this XmlTextReader must be on Element start tag;
/// on exit - on EndElement tag.
/// </param>
/// <param name="htmlWriter">
/// May be null, in which case we are skipping xaml content
/// without producing any html output
/// </param>
/// <param name="inlineStyle">
/// StringBuilder used for collecting css properties for inline STYLE attributes on every level.
/// </param>
private static void WriteElement(XmlTextReader xamlReader, XmlTextWriter htmlWriter, StringBuilder inlineStyle)
{
Debug.Assert(xamlReader.NodeType == XmlNodeType.Element);
if (htmlWriter == null)
{
// Skipping mode; recurse into the xaml element without any output
WriteElementContent(xamlReader, /*htmlWriter:*/null, null);
}
else
{
string htmlElementName = null;
switch (xamlReader.Name)
{
case "Run" :
case "Span":
htmlElementName = "SPAN";
break;
case "InlineUIContainer":
htmlElementName = "SPAN";
break;
case "Bold":
htmlElementName = "B";
break;
case "Italic" :
htmlElementName = "I";
break;
case "Paragraph" :
htmlElementName = "P";
break;
case "BlockUIContainer":
htmlElementName = "DIV";
break;
case "Section":
htmlElementName = "DIV";
break;
case "Table":
htmlElementName = "TABLE";
break;
case "TableColumn":
htmlElementName = "COL";
break;
case "TableRowGroup" :
htmlElementName = "TBODY";
break;
case "TableRow" :
htmlElementName = "TR";
break;
case "TableCell" :
htmlElementName = "TD";
break;
case "List" :
string marker = xamlReader.GetAttribute("MarkerStyle");
if (marker == null || marker == "None" || marker == "Disc" || marker == "Circle" || marker == "Square" || marker == "Box")
{
htmlElementName = "UL";
}
else
{
htmlElementName = "OL";
}
break;
case "ListItem" :
htmlElementName = "LI";
break;
default :
htmlElementName = null; // Ignore the element
break;
}
if (htmlWriter != null && htmlElementName != null)
{
htmlWriter.WriteStartElement(htmlElementName);
WriteFormattingProperties(xamlReader, htmlWriter, inlineStyle);
WriteElementContent(xamlReader, htmlWriter, inlineStyle);
htmlWriter.WriteEndElement();
}
else
{
// Skip this unrecognized xaml element
WriteElementContent(xamlReader, /*htmlWriter:*/null, null);
}
}
}
// Reader advance helpers
// ----------------------
/// <summary>
/// Reads several items from xamlReader skipping all non-significant stuff.
/// </summary>
/// <param name="xamlReader">
/// XmlTextReader from tokens are being read.
/// </param>
/// <returns>
/// True if new token is available; false if end of stream reached.
/// </returns>
private static bool ReadNextToken(XmlReader xamlReader)
{
while (xamlReader.Read())
{
Debug.Assert(xamlReader.ReadState == ReadState.Interactive, "Reader is expected to be in Interactive state (" + xamlReader.ReadState + ")");
switch (xamlReader.NodeType)
{
case XmlNodeType.Element:
case XmlNodeType.EndElement:
case XmlNodeType.None:
case XmlNodeType.CDATA:
case XmlNodeType.Text:
case XmlNodeType.SignificantWhitespace:
return true;
case XmlNodeType.Whitespace:
if (xamlReader.XmlSpace == XmlSpace.Preserve)
{
return true;
}
// ignore insignificant whitespace
break;
case XmlNodeType.EndEntity:
case XmlNodeType.EntityReference:
// Implement entity reading
//xamlReader.ResolveEntity();
//xamlReader.Read();
//ReadChildNodes( parent, parentBaseUri, xamlReader, positionInfo);
break; // for now we ignore entities as insignificant stuff
case XmlNodeType.Comment:
return true;
case XmlNodeType.ProcessingInstruction:
case XmlNodeType.DocumentType:
case XmlNodeType.XmlDeclaration:
default:
// Ignorable stuff
break;
}
}
return false;
}
#endregion Private Methods
// ---------------------------------------------------------------------
//
// Private Fields
//
// ---------------------------------------------------------------------
#region Private Fields
#endregion Private Fields
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Operators.Twoclass2operates.binary.overload001.overload001
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Operators.Twoclass2operates.binary.overload001.overload001;
// <Title> Tests overload resolution for 2 class and 2 methods</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
//<Expects Status=warning>\(11,23\).*CS0649</Expects>
public class Base
{
public static int Status;
public static int operator +(short x, Base b)
{
return int.MinValue;
}
}
public class Derived : Base
{
public static int operator +(int x, Derived d)
{
return int.MaxValue;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new Derived();
short x = 3;
int xx = x + d;
if (xx == int.MaxValue)
return 0;
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Operators.Twoclass2operates.binary.overload002.overload002
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Operators.Twoclass2operates.binary.overload002.overload002;
// <Title> Tests overload resolution for 2 class and 2 methods</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Base
{
public static float operator -(short x, Base b)
{
return float.Epsilon;
}
}
public class Derived : Base
{
public static float operator -(int x, Derived d)
{
return float.NegativeInfinity;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new Derived();
int x = 3;
float f = x - d;
if (float.IsNegativeInfinity(f))
return 0;
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Operators.Twoclass2operates.binary.overload003.overload003
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Operators.Twoclass2operates.binary.overload003.overload003;
// <Title> Tests overload resolution for 2 class and 2 methods</Title>
// <Description>
// Call methods with different accessibility level and selecting the right one.:)
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Base
{
public static double operator *(Base b, short x)
{
return double.MinValue;
}
}
public class Derived : Base
{
public static double operator *(Derived d, int x)
{
return double.MaxValue;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new Derived();
int x = 3;
double dd = d * x;
if (dd == double.MaxValue)
return 0;
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Operators.Twoclass2operates.binary.overload004.overload004
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Operators.Twoclass2operates.binary.overload004.overload004;
// <Title> Tests overload resolution for 2 class and 2 methods</Title>
// <Description>
// Call methods with different accessibility level and selecting the right one.:)
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Base
{
public static short operator /(Base x, short d)
{
return short.MinValue;
}
}
public class Derived : Base
{
public static short operator /(Derived x, int d)
{
return short.MaxValue;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new Derived();
int x = 3;
short s = d / x;
if (s == short.MaxValue)
return 0;
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Operators.Twoclass2operates.binary.overload005.overload005
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Operators.Twoclass2operates.binary.overload005.overload005;
// <Title> Tests overload resolution for 2 class and 2 methods</Title>
// <Description>
// Call methods with different accessibility level and selecting the right one.:)
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Base
{
public static int?[] operator %(short x, Base b)
{
return new int?[]
{
1, 2, null
}
;
}
}
public class Derived : Base
{
public static int?[] operator %(int x, Derived d)
{
return new int?[]
{
null, null
}
;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new Derived();
int x = 3;
int?[] xx = x % d;
if (xx.Length == 2)
return 0;
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Operators.Twoclass2operates.binary.overload006.overload006
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Operators.Twoclass2operates.binary.overload006.overload006;
// <Title> Tests overload resolution for 2 class and 2 methods</Title>
// <Description>
// Call methods with different accessibility level and selecting the right one.:)
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Base
{
public static string operator &(Base b, short x)
{
return string.Empty;
}
}
public class Derived : Base
{
public static string operator &(Derived d, int x)
{
return "foo";
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new Derived();
int x = 3;
string s = d & x;
if (s == "foo")
return 0;
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Operators.Twoclass2operates.binary.overload007.overload007
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Operators.Twoclass2operates.binary.overload007.overload007;
// <Title> Tests overload resolution for 2 class and 2 methods</Title>
// <Description>
// Call methods with different accessibility level and selecting the right one.:)
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Base
{
public static byte[] operator |(short x, Base b)
{
return new byte[]
{
1, 2, 3
}
;
}
}
public class Derived : Base
{
public static byte[] operator |(int x, Derived d)
{
return new byte[]
{
1, 2
}
;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new Derived();
int x = 3;
byte[] b = x | d;
if (b.Length == 2)
return 0;
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Operators.Twoclass2operates.binary.overload008.overload008
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Operators.Twoclass2operates.binary.overload008.overload008;
// <Title> Tests overload resolution for 2 class and 2 methods</Title>
// <Description>
// Select the best method to call.
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Base
{
public static decimal operator ^(dynamic x, Base b)
{
return decimal.Zero;
}
public static decimal operator ^(short x, Base b)
{
return decimal.One;
}
}
public class Derived : Base
{
public static decimal operator ^(int x, Derived d)
{
return decimal.MinusOne;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new Derived();
dynamic x = 3;
decimal dec = x ^ d;
if (dec == decimal.MinusOne)
return 0;
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Operators.Twoclass2operates.binary.overload009.overload009
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Operators.Twoclass2operates.binary.overload009.overload009;
// <Title> Tests overload resolution for 2 class and 2 methods</Title>
// <Description>
// Select the best method to call.
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Base
{
public static decimal operator ^(dynamic x, Base b)
{
return decimal.Zero;
}
public static decimal operator ^(short x, Base b)
{
return decimal.One;
}
}
public class Derived : Base
{
public static decimal operator ^(int x, Derived d)
{
return decimal.MinusOne;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new Base();
dynamic x = 3;
decimal dec = x ^ d;
if (dec == decimal.Zero)
return 0;
return 1;
}
}
// </Code>
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Controls.dll
// Description: The core libraries for the DotSpatial project.
//
// ********************************************************************************************************
// The contents of this file are subject to the MIT License (MIT)
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
// http://dotspatial.codeplex.com/license
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
// ANY KIND, either expressed or implied. See the License for the specific language governing rights and
// limitations under the License.
//
// The Original Code is DotSpatial.dll for the DotSpatial project
//
// The Initial Developer of this Original Code is Ted Dunsford. Created in August, 2007.
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
// Modified to do 3D in January 2008 by Ted Dunsford
// ********************************************************************************************************
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Windows.Forms;
using DotSpatial.Data;
using DotSpatial.Symbology;
using GeoAPI.Geometries;
namespace DotSpatial.Controls
{
/// <summary>
/// This is a specialized FeatureLayer that specifically handles point drawing
/// </summary>
public class MapPointLayer : PointLayer, IMapPointLayer
{
#region Events
/// <summary>
/// Occurs when drawing content has changed on the buffer for this layer
/// </summary>
public event EventHandler<ClipArgs> BufferChanged;
#endregion
#region Constructors
/// <summary>
/// This creates a blank MapPointLayer with the DataSet set to an empty new featureset of the Point featuretype.
/// </summary>
public MapPointLayer()
{
Configure();
}
/// <summary>
/// Creates a new instance of a GeoPointLayer without sending any status messages
/// </summary>
/// <param name="featureSet">The IFeatureLayer of data values to turn into a graphical GeoPointLayer</param>
public MapPointLayer(IFeatureSet featureSet)
: base(featureSet)
{
// this simply handles the default case where no status messages are requested
Configure();
OnFinishedLoading();
}
/// <summary>
/// Creates a new instance of the point layer where the container is specified
/// </summary>
/// <param name="featureSet"></param>
/// <param name="container"></param>
public MapPointLayer(IFeatureSet featureSet, ICollection<ILayer> container)
: base(featureSet, container, null)
{
Configure();
OnFinishedLoading();
}
/// <summary>
/// Creates a new instance of the point layer where the container is specified
/// </summary>
/// <param name="featureSet"></param>
/// <param name="container"></param>
/// <param name="notFinished"></param>
public MapPointLayer(IFeatureSet featureSet, ICollection<ILayer> container, bool notFinished)
: base(featureSet, container, null)
{
Configure();
if (notFinished == false) OnFinishedLoading();
}
private void Configure()
{
ChunkSize = 50000;
}
#endregion
#region Methods
/// <summary>
/// This will draw any features that intersect this region. To specify the features
/// directly, use OnDrawFeatures. This will not clear existing buffer content.
/// For that call Initialize instead.
/// </summary>
/// <param name="args">A GeoArgs clarifying the transformation from geographic to image space</param>
/// <param name="regions">The geographic regions to draw</param>
public virtual void DrawRegions(MapArgs args, List<Extent> regions)
{
// First determine the number of features we are talking about based on region.
List<Rectangle> clipRects = args.ProjToPixel(regions);
if (EditMode)
{
List<IFeature> drawList = new List<IFeature>();
foreach (Extent region in regions)
{
if (region != null)
{
// Use union to prevent duplicates. No sense in drawing more than we have to.
drawList = drawList.Union(DataSet.Select(region)).ToList();
}
}
DrawFeatures(args, drawList, clipRects, true);
}
else
{
List<int> drawList = new List<int>();
double[] verts = DataSet.Vertex;
if (DataSet.FeatureType == FeatureType.Point)
{
for (int shp = 0; shp < verts.Length / 2; shp++)
{
foreach (Extent extent in regions)
{
if (extent.Intersects(verts[shp * 2], verts[shp * 2 + 1]))
{
drawList.Add(shp);
}
}
}
}
else
{
List<ShapeRange> shapes = DataSet.ShapeIndices;
for (int shp = 0; shp < shapes.Count; shp++)
{
foreach (Extent region in regions)
{
if (!shapes[shp].Extent.Intersects(region)) continue;
drawList.Add(shp);
break;
}
}
}
DrawFeatures(args, drawList, clipRects, true);
}
}
/// <summary>
/// Call StartDrawing before using this.
/// </summary>
/// <param name="rectangles">The rectangular region in pixels to clear.</param>
/// <param name= "color">The color to use when clearing. Specifying transparent
/// will replace content with transparent pixels.</param>
public void Clear(List<Rectangle> rectangles, Color color)
{
if (BackBuffer == null) return;
Graphics g = Graphics.FromImage(BackBuffer);
foreach (Rectangle r in rectangles)
{
if (r.IsEmpty == false)
{
g.Clip = new Region(r);
g.Clear(color);
}
}
g.Dispose();
}
/// <summary>
/// This is testing the idea of using an input parameter type that is marked as out
/// instead of a return type.
/// </summary>
/// <param name="result">The result of the creation</param>
/// <returns>Boolean, true if a layer can be created</returns>
public override bool CreateLayerFromSelectedFeatures(out IFeatureLayer result)
{
MapPointLayer temp;
bool resultOk = CreateLayerFromSelectedFeatures(out temp);
result = temp;
return resultOk;
}
/// <summary>
/// This is the strong typed version of the same process that is specific to geo point layers.
/// </summary>
/// <param name="result">The new GeoPointLayer to be created</param>
/// <returns>Boolean, true if there were any values in the selection</returns>
public virtual bool CreateLayerFromSelectedFeatures(out MapPointLayer result)
{
result = null;
if (Selection == null || Selection.Count == 0) return false;
FeatureSet fs = Selection.ToFeatureSet();
result = new MapPointLayer(fs);
return true;
}
/// <summary>
/// If useChunks is true, then this method
/// </summary>
/// <param name="args">The GeoArgs that control how these features should be drawn.</param>
/// <param name="features">The features that should be drawn.</param>
/// <param name="clipRectangles">If an entire chunk is drawn and an update is specified, this clarifies the changed rectangles.</param>
/// <param name="useChunks">Boolean, if true, this will refresh the buffer in chunks.</param>
public virtual void DrawFeatures(MapArgs args, List<IFeature> features, List<Rectangle> clipRectangles, bool useChunks)
{
if (useChunks == false || features.Count < ChunkSize)
{
DrawFeatures(args, features);
return;
}
int count = features.Count;
int numChunks = (int)Math.Ceiling(count / (double)ChunkSize);
for (int chunk = 0; chunk < numChunks; chunk++)
{
int groupSize = ChunkSize;
if (chunk == numChunks - 1) groupSize = count - chunk * ChunkSize;
List<IFeature> subset = features.GetRange(chunk * ChunkSize, groupSize);
DrawFeatures(args, subset);
if (numChunks <= 0 || chunk >= numChunks - 1) continue;
FinishDrawing();
OnBufferChanged(clipRectangles);
Application.DoEvents();
}
}
/// <summary>
/// If useChunks is true, then this method
/// </summary>
/// <param name="args">The GeoArgs that control how these features should be drawn.</param>
/// <param name="indices">The features that should be drawn.</param>
/// <param name="clipRectangles">If an entire chunk is drawn and an update is specified, this clarifies the changed rectangles.</param>
/// <param name="useChunks">Boolean, if true, this will refresh the buffer in chunks.</param>
public virtual void DrawFeatures(MapArgs args, List<int> indices, List<Rectangle> clipRectangles, bool useChunks)
{
if (!useChunks)
{
DrawFeatures(args, indices);
return;
}
int count = indices.Count;
int numChunks = (int)Math.Ceiling(count / (double)ChunkSize);
for (int chunk = 0; chunk < numChunks; chunk++)
{
int numFeatures = ChunkSize;
if (chunk == numChunks - 1) numFeatures = indices.Count - (chunk * ChunkSize);
DrawFeatures(args, indices.GetRange(chunk * ChunkSize, numFeatures));
if (numChunks > 0 && chunk < numChunks - 1)
{
// FinishDrawing();
OnBufferChanged(clipRectangles);
Application.DoEvents();
// this.StartDrawing();
}
}
}
/// <summary>
/// Indicates that the drawing process has been finalized and swaps the back buffer
/// to the front buffer.
/// </summary>
public void FinishDrawing()
{
OnFinishDrawing();
if (Buffer != null && Buffer != BackBuffer) Buffer.Dispose();
Buffer = BackBuffer;
}
/// <summary>
/// Copies any current content to the back buffer so that drawing should occur on the
/// back buffer (instead of the fore-buffer). Calling draw methods without
/// calling this may cause exceptions.
/// </summary>
/// <param name="preserve">Boolean, true if the front buffer content should be copied to the back buffer
/// where drawing will be taking place.</param>
public void StartDrawing(bool preserve)
{
Bitmap backBuffer = new Bitmap(BufferRectangle.Width, BufferRectangle.Height);
if (Buffer != null)
{
if (Buffer.Width == backBuffer.Width && Buffer.Height == backBuffer.Height)
{
if (preserve)
{
Graphics g = Graphics.FromImage(backBuffer);
g.DrawImageUnscaled(Buffer, 0, 0);
}
}
}
if (BackBuffer != null && BackBuffer != Buffer) BackBuffer.Dispose();
BackBuffer = backBuffer;
OnStartDrawing();
}
#endregion
#region Protected Methods
/// <summary>
/// Fires the OnBufferChanged event
/// </summary>
/// <param name="clipRectangles">The Rectangle in pixels</param>
protected virtual void OnBufferChanged(List<Rectangle> clipRectangles)
{
if (BufferChanged != null)
{
ClipArgs e = new ClipArgs(clipRectangles);
BufferChanged(this, e);
}
}
/// <summary>
/// A default method to generate a label layer.
/// </summary>
protected override void OnCreateLabels()
{
LabelLayer = new MapLabelLayer(this);
}
/// <summary>
/// Indiciates that whatever drawing is going to occur has finished and the contents
/// are about to be flipped forward to the front buffer.
/// </summary>
protected virtual void OnFinishDrawing()
{
}
/// <summary>
/// Occurs when a new drawing is started, but after the BackBuffer has been established.
/// </summary>
protected virtual void OnStartDrawing()
{
}
#endregion
#region Private Methods
// This draws the individual point features
private void DrawFeatures(MapArgs e, IEnumerable<int> indices)
{
Graphics g = e.Device ?? Graphics.FromImage(BackBuffer);
Matrix origTransform = g.Transform;
FeatureType featureType = DataSet.FeatureType;
if (!DrawnStatesNeeded)
{
if (Symbology == null || Symbology.Categories.Count == 0) return;
FastDrawnState state = new FastDrawnState(false, Symbology.Categories[0]);
IPointCategory pc = state.Category as IPointCategory;
if (pc == null) return;
IPointSymbolizer ps = pc.Symbolizer;
if (ps == null) return;
double[] vertices = DataSet.Vertex;
foreach (int index in indices)
{
if (DrawnStates != null && DrawnStates.Length > index && !DrawnStates[index].Visible) continue;
if (featureType == FeatureType.Point)
{
DrawPoint(vertices[index * 2], vertices[index * 2 + 1], e, ps, g, origTransform);
}
else
{
// multi-point
ShapeRange range = DataSet.ShapeIndices[index];
for (int i = range.StartIndex; i <= range.EndIndex(); i++)
{
DrawPoint(vertices[i * 2], vertices[i * 2 + 1], e, ps, g, origTransform);
}
}
}
}
else
{
FastDrawnState[] states = DrawnStates;
double[] vertices = DataSet.Vertex;
foreach (int index in indices)
{
if (index >= states.Length) break;
FastDrawnState state = states[index];
if (!state.Visible || state.Category == null) continue;
IPointCategory pc = state.Category as IPointCategory;
if (pc == null) continue;
IPointSymbolizer ps = state.Selected ? pc.SelectionSymbolizer : pc.Symbolizer;
if (ps == null) continue;
if (featureType == FeatureType.Point)
{
DrawPoint(vertices[index * 2], vertices[index * 2 + 1], e, ps, g, origTransform);
}
else
{
ShapeRange range = DataSet.ShapeIndices[index];
for (int i = range.StartIndex; i <= range.EndIndex(); i++)
{
DrawPoint(vertices[i * 2], vertices[i * 2 + 1], e, ps, g, origTransform);
}
}
}
}
if (e.Device == null) g.Dispose();
else g.Transform = origTransform;
}
// This draws the individual point features
private void DrawFeatures(MapArgs e, IEnumerable<IFeature> features)
{
Graphics g = e.Device ?? Graphics.FromImage(BackBuffer);
Matrix origTransform = g.Transform;
IDictionary<IFeature, IDrawnState> states = DrawingFilter.DrawnStates;
if (states == null) return;
foreach (IFeature feature in features)
{
if (!states.ContainsKey(feature)) continue;
IDrawnState ds = states[feature];
if (ds == null || !ds.IsVisible || ds.SchemeCategory == null) continue;
IPointCategory pc = ds.SchemeCategory as IPointCategory;
if (pc == null) continue;
IPointSymbolizer ps = ds.IsSelected ? pc.SelectionSymbolizer : pc.Symbolizer;
if (ps == null) continue;
foreach (Coordinate c in feature.Geometry.Coordinates)
{
DrawPoint(c.X, c.Y, e, ps, g, origTransform);
}
}
if (e.Device == null) g.Dispose();
else g.Transform = origTransform;
}
/// <summary>
/// Draws a point at the given location.
/// </summary>
/// <param name="ptX">X-Coordinate of the point, that should be drawn.</param>
/// <param name="ptY">Y-Coordinate of the point, that should be drawn.</param>
/// <param name="e">MapArgs for calculating the scaleSize.</param>
/// <param name="ps">PointSymbolizer with which the point gets drawn.</param>
/// <param name="g">Graphics-Object that should be used by the PointSymbolizer.</param>
/// <param name="origTransform">The original transformation that is used to position the point.</param>
private void DrawPoint(double ptX, double ptY, MapArgs e, IPointSymbolizer ps, Graphics g, Matrix origTransform)
{
var pt = new Point
{
X = Convert.ToInt32((ptX - e.MinX) * e.Dx),
Y = Convert.ToInt32((e.MaxY - ptY) * e.Dy)
};
double scaleSize = ps.ScaleMode == ScaleMode.Geographic ? e.ImageRectangle.Width / e.GeographicExtents.Width : 1;
Matrix shift = origTransform.Clone();
shift.Translate(pt.X, pt.Y);
g.Transform = shift;
ps.Draw(g, scaleSize);
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the back buffer that will be drawn to as part of the initialization process.
/// </summary>
[ShallowCopy, Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Image BackBuffer { get; set; }
/// <summary>
/// Gets the current buffer.
/// </summary>
[ShallowCopy, Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Image Buffer { get; set; }
/// <summary>
/// Gets or sets the geographic region represented by the buffer
/// Calling Initialize will set this automatically.
/// </summary>
[ShallowCopy, Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Envelope BufferEnvelope { get; set; }
/// <summary>
/// Gets or sets the rectangle in pixels to use as the back buffer.
/// Calling Initialize will set this automatically.
/// </summary>
[ShallowCopy, Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Rectangle BufferRectangle { get; set; }
/// <summary>
/// Gets or sets the label layer that is associated with this point layer.
/// </summary>
[ShallowCopy]
public new IMapLabelLayer LabelLayer
{
get { return base.LabelLayer as IMapLabelLayer; }
set { base.LabelLayer = value; }
}
#endregion
#region Static Methods
/// <summary>
/// Attempts to create a new GeoPointLayer using the specified file. If the filetype is not
/// does not generate a point layer, an exception will be thrown.
/// </summary>
/// <param name="fileName">A string fileName to create a point layer for.</param>
/// <param name="progressHandler">Any valid implementation of IProgressHandler for receiving progress messages</param>
/// <returns>A GeoPointLayer created from the specified fileName.</returns>
public static new MapPointLayer OpenFile(string fileName, IProgressHandler progressHandler)
{
ILayer fl = LayerManager.DefaultLayerManager.OpenLayer(fileName, progressHandler);
return fl as MapPointLayer;
}
/// <summary>
/// Attempts to create a new GeoPointLayer using the specified file. If the filetype is not
/// does not generate a point layer, an exception will be thrown.
/// </summary>
/// <param name="fileName">A string fileName to create a point layer for.</param>
/// <returns>A GeoPointLayer created from the specified fileName.</returns>
public static new MapPointLayer OpenFile(string fileName)
{
IFeatureLayer fl = LayerManager.DefaultLayerManager.OpenVectorLayer(fileName);
return fl as MapPointLayer;
}
#endregion
}
}
| |
// 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.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by google-apis-code-generator 1.5.1
// C# generator version: 1.27.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
/**
* \brief
* Google Cloud Functions API Version v1
*
* \section ApiInfo API Version Information
* <table>
* <tr><th>API
* <td><a href='https://cloud.google.com/functions'>Google Cloud Functions API</a>
* <tr><th>API Version<td>v1
* <tr><th>API Rev<td>20170714 (925)
* <tr><th>API Docs
* <td><a href='https://cloud.google.com/functions'>
* https://cloud.google.com/functions</a>
* <tr><th>Discovery Name<td>cloudfunctions
* </table>
*
* \section ForMoreInfo For More Information
*
* The complete API documentation for using Google Cloud Functions API can be found at
* <a href='https://cloud.google.com/functions'>https://cloud.google.com/functions</a>.
*
* For more information about the Google APIs Client Library for .NET, see
* <a href='https://developers.google.com/api-client-library/dotnet/get_started'>
* https://developers.google.com/api-client-library/dotnet/get_started</a>
*/
namespace Google.Apis.CloudFunctions.v1
{
/// <summary>The CloudFunctions Service.</summary>
public class CloudFunctionsService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v1";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed =
Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public CloudFunctionsService() :
this(new Google.Apis.Services.BaseClientService.Initializer()) {}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public CloudFunctionsService(Google.Apis.Services.BaseClientService.Initializer initializer)
: base(initializer)
{
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features
{
get { return new string[0]; }
}
/// <summary>Gets the service name.</summary>
public override string Name
{
get { return "cloudfunctions"; }
}
/// <summary>Gets the service base URI.</summary>
public override string BaseUri
{
get { return "https://cloudfunctions.googleapis.com/"; }
}
/// <summary>Gets the service base path.</summary>
public override string BasePath
{
get { return ""; }
}
#if !NET40
/// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary>
public override string BatchUri
{
get { return "https://cloudfunctions.googleapis.com/batch"; }
}
/// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary>
public override string BatchPath
{
get { return "batch"; }
}
#endif
}
///<summary>A base abstract class for CloudFunctions requests.</summary>
public abstract class CloudFunctionsBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
///<summary>Constructs a new CloudFunctionsBaseServiceRequest instance.</summary>
protected CloudFunctionsBaseServiceRequest(Google.Apis.Services.IClientService service)
: base(service)
{
}
/// <summary>V1 error format.</summary>
[Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<XgafvEnum> Xgafv { get; set; }
/// <summary>V1 error format.</summary>
public enum XgafvEnum
{
/// <summary>v1 error format</summary>
[Google.Apis.Util.StringValueAttribute("1")]
Value1,
/// <summary>v2 error format</summary>
[Google.Apis.Util.StringValueAttribute("2")]
Value2,
}
/// <summary>OAuth access token.</summary>
[Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string AccessToken { get; set; }
/// <summary>Data format for response.</summary>
/// [default: json]
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json,
/// <summary>Media download with context-dependent Content-Type</summary>
[Google.Apis.Util.StringValueAttribute("media")]
Media,
/// <summary>Responses with Content-Type of application/x-protobuf</summary>
[Google.Apis.Util.StringValueAttribute("proto")]
Proto,
}
/// <summary>OAuth bearer token.</summary>
[Google.Apis.Util.RequestParameterAttribute("bearer_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string BearerToken { get; set; }
/// <summary>JSONP</summary>
[Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Callback { get; set; }
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports.
/// Required unless you provide an OAuth 2.0 token.</summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Pretty-print response.</summary>
/// [default: true]
[Google.Apis.Util.RequestParameterAttribute("pp", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> Pp { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
/// [default: true]
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string
/// assigned to a user, but should not exceed 40 characters.</summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadType { get; set; }
/// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadProtocol { get; set; }
/// <summary>Initializes CloudFunctions parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"$.xgafv", new Google.Apis.Discovery.Parameter
{
Name = "$.xgafv",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"access_token", new Google.Apis.Discovery.Parameter
{
Name = "access_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add(
"bearer_token", new Google.Apis.Discovery.Parameter
{
Name = "bearer_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"callback", new Google.Apis.Discovery.Parameter
{
Name = "callback",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pp", new Google.Apis.Discovery.Parameter
{
Name = "pp",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add(
"prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add(
"quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"uploadType", new Google.Apis.Discovery.Parameter
{
Name = "uploadType",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"upload_protocol", new Google.Apis.Discovery.Parameter
{
Name = "upload_protocol",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
namespace Google.Apis.CloudFunctions.v1.Data
{
/// <summary>Metadata describing an Operation</summary>
public class OperationMetadataV1Beta2 : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The original request that started the operation.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("request")]
public virtual System.Collections.Generic.IDictionary<string,object> Request { get; set; }
/// <summary>Target of the operation - for example
/// projects/project-1/locations/region-1/functions/function-1</summary>
[Newtonsoft.Json.JsonPropertyAttribute("target")]
public virtual string Target { get; set; }
/// <summary>Type of operation.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("type")]
public virtual string Type { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| |
/// This code is taken from
/// http://www.codeproject.com/dotnet/nhibernatept1.asp
using System;
using NHibernate;
using NHibernate.Cfg;
using System.Collections;
using nhibernator.BLL;
//using NHibernate.Expression;
using Iesi.Collections;
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
namespace nhibernator.DLL
{
/// <summary>
/// Data Layer Logic for loading/saving Customers
/// </summary>
public class CustomerFactory : IDisposable
{
Configuration config;
ISessionFactory factory;
ISession session;
/// <summary>
/// Get All Customers, should rarely be used...
/// </summary>
/// <returns>Complete list of customers</returns>
public IList GetCustomers()
{
IList customers = new System.Collections.ArrayList();
ITransaction tx = null;
string id = string.Empty;
try
{
if (!session.IsConnected)
{
session.Reconnect();
}
tx = session.BeginTransaction();
IQuery qry = session.CreateQuery("from Customer c")
.SetCacheable(true);
customers = qry.List();
tx.Commit();
}
catch (Exception ex)
{
tx.Rollback();
session.Clear();
session.Disconnect();
throw ex;
}
return customers;
}
/// <summary>
/// Gets a Customer
/// </summary>
/// <param name="CustomerID">string representing customer id</param>
/// <returns>Object representing customer of "Customer" type. </returns>
public Customer GetCustomer(string CustomerID)
{
Customer customer = null;
ITransaction tx = null;
try
{
if (!session.IsConnected)
{
session.Reconnect();
}
tx = session.BeginTransaction();
customer = (Customer)session.Get(typeof(Customer), CustomerID);
tx.Commit();
}
catch (Exception ex)
{
tx.Rollback();
session.Clear();
session.Disconnect();
throw ex;
}
return customer;
}
public Customer GetCustomerOrders(string CustomerID)
{
Customer customer = null;
ITransaction tx = null;
try
{
if (!session.IsConnected)
{
session.Reconnect();
}
tx = session.BeginTransaction();
customer = (Customer)session.Get(typeof(Customer), CustomerID);
tx.Commit();
}
catch (Exception ex)
{
tx.Rollback();
throw ex;
}
return customer;
}
/// <summary>
/// Add current customer in database.
/// </summary>
/// <param name="cust">Customer to save.</param>
public void SaveCustomer(Customer customer)
{
ITransaction tx = null;
try
{
if(!session.IsConnected)
{
session.Reconnect();
}
tx = session.BeginTransaction();
session.Save(customer);
session.Flush();
tx.Commit();
Console.WriteLine("\nCustomer with ID: " + customer.CustomerID + " succefully added into database");
}
catch (Exception ex)
{
tx.Rollback();
session.Clear();
session.Disconnect();
throw ex.InnerException;
}
}
/// <summary>
/// Insert/Update current customer in database.
/// </summary>
/// <param name="cust">Customer to update.</param>
public void UpdateCustomer(Customer customer)
{
ITransaction tx = null;
try
{
if (!session.IsConnected)
{
session.Reconnect();
}
tx = session.BeginTransaction();
session.Merge(customer);
session.Flush();
tx.Commit();
Console.WriteLine("\nCustomer with ID: " + customer.CustomerID + " succefully updated into database");
}
catch (Exception ex)
{
tx.Rollback();
session.Clear();
session.Disconnect();
throw ex.InnerException;
// handle exception
}
}
/// <summary>
/// Removes the customer with customerID
/// </summary>
/// <param name="CustomerID"></param>
public void RemoveCustomer(string CustomerID)
{
ITransaction tx = null;
Customer customer;
try
{
if (!session.IsConnected)
{
session.Reconnect();
}
tx = session.BeginTransaction();
IEnumerator enumerator = session.CreateQuery("select cust " + "from Customer cust where " +
"cust.CustomerID = '" + CustomerID + "'").Enumerable().GetEnumerator();
enumerator.MoveNext();
customer = (Customer)enumerator.Current;
if (customer != null)
{
session.Delete(customer);
factory.Evict(typeof(Customer), CustomerID);
factory.EvictCollection(typeof(Customer).ToString() + ".Orders", CustomerID);
Console.WriteLine("\nCustomer with ID: " + CustomerID + " succefully deleted from database");
}
else
{
Console.WriteLine("No such customer exist.");
}
tx.Commit();
}
catch (Exception ex)
{
tx.Rollback();
session.Clear();
session.Disconnect();
throw ex;
// handle exception
}
}
/// <summary>
/// Clears and dissconnects the session
/// </summary>
public void SessionDisconnect()
{
session.Clear();
session.Disconnect();
}
/// <summary>
/// Create a customer factory based on the configuration given in the configuration file
/// </summary>
public CustomerFactory()
{
this.ConfigureLog4Net();
config = new Configuration();
config.AddAssembly("nhibernator");
factory = config.BuildSessionFactory();
session = factory.OpenSession();
}
/// <summary>
/// Reads Log4Net configurations from application configuration file
/// </summary>
private void ConfigureLog4Net()
{
log4net.Config.XmlConfigurator.Configure();
}
/// <summary>
/// Make sure we clean up session etc.
/// </summary>
public void Dispose()
{
session.Dispose();
factory.Close();
}
}
}
| |
// 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Data.SqlClient.ManualTesting.Tests
{
[Trait("connection", "tcp")]
public static class BaseProviderAsyncTest
{
[CheckConnStrSetupFact]
public static void TestDbConnection()
{
MockConnection connection = new MockConnection();
CancellationTokenSource source = new CancellationTokenSource();
// ensure OpenAsync() calls OpenAsync(CancellationToken.None)
DataTestUtility.AssertEqualsWithDescription(ConnectionState.Closed, connection.State, "Connection state should have been marked as Closed");
connection.OpenAsync().Wait();
Assert.False(connection.CancellationToken.CanBeCanceled, "Default cancellation token should not be cancellable");
DataTestUtility.AssertEqualsWithDescription(ConnectionState.Open, connection.State, "Connection state should have been marked as Open");
connection.Close();
// Verify cancellationToken over-ride
DataTestUtility.AssertEqualsWithDescription(ConnectionState.Closed, connection.State, "Connection state should have been marked as Closed");
connection.OpenAsync(source.Token).Wait();
DataTestUtility.AssertEqualsWithDescription(ConnectionState.Open, connection.State, "Connection state should have been marked as Open");
connection.Close();
// Verify exceptions are routed through task
MockConnection connectionFail = new MockConnection()
{
Fail = true
};
connectionFail.OpenAsync().ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
connectionFail.OpenAsync(source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
// Verify base implementation does not call Open when passed an already cancelled cancellation token
source.Cancel();
DataTestUtility.AssertEqualsWithDescription(ConnectionState.Closed, connection.State, "Connection state should have been marked as Closed");
connection.OpenAsync(source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnCanceled).Wait();
DataTestUtility.AssertEqualsWithDescription(ConnectionState.Closed, connection.State, "Connection state should have been marked as Closed");
}
[CheckConnStrSetupFact]
public static void TestDbCommand()
{
MockCommand command = new MockCommand()
{
ScalarResult = 1,
Results = Enumerable.Range(1, 5).Select((x) => new object[] { x, x.ToString() })
};
CancellationTokenSource source = new CancellationTokenSource();
// Verify parameter routing and correct synchronous implementation is called
command.ExecuteNonQueryAsync().Wait();
Assert.False(command.CancellationToken.CanBeCanceled, "Default cancellation token should not be cancellable");
DataTestUtility.AssertEqualsWithDescription("ExecuteNonQuery", command.LastCommand, "Last command was not as expected");
command.ExecuteReaderAsync().Wait();
DataTestUtility.AssertEqualsWithDescription(CommandBehavior.Default, command.CommandBehavior, "Command behavior should have been marked as Default");
Assert.False(command.CancellationToken.CanBeCanceled, "Default cancellation token should not be cancellable");
DataTestUtility.AssertEqualsWithDescription("ExecuteReader", command.LastCommand, "Last command was not as expected");
command.ExecuteScalarAsync().Wait();
Assert.False(command.CancellationToken.CanBeCanceled, "Default cancellation token should not be cancellable");
DataTestUtility.AssertEqualsWithDescription("ExecuteScalar", command.LastCommand, "Last command was not as expected");
command.ExecuteNonQueryAsync(source.Token).Wait();
DataTestUtility.AssertEqualsWithDescription("ExecuteNonQuery", command.LastCommand, "Last command was not as expected");
command.ExecuteReaderAsync(source.Token).Wait();
DataTestUtility.AssertEqualsWithDescription("ExecuteReader", command.LastCommand, "Last command was not as expected");
command.ExecuteScalarAsync(source.Token).Wait();
DataTestUtility.AssertEqualsWithDescription("ExecuteScalar", command.LastCommand, "Last command was not as expected");
command.ExecuteReaderAsync(CommandBehavior.SequentialAccess).Wait();
DataTestUtility.AssertEqualsWithDescription(CommandBehavior.SequentialAccess, command.CommandBehavior, "Command behavior should have been marked as SequentialAccess");
Assert.False(command.CancellationToken.CanBeCanceled, "Default cancellation token should not be cancellable");
DataTestUtility.AssertEqualsWithDescription("ExecuteReader", command.LastCommand, "Last command was not as expected");
command.ExecuteReaderAsync(CommandBehavior.SingleRow, source.Token).Wait();
DataTestUtility.AssertEqualsWithDescription(CommandBehavior.SingleRow, command.CommandBehavior, "Command behavior should have been marked as SingleRow");
DataTestUtility.AssertEqualsWithDescription("ExecuteReader", command.LastCommand, "Last command was not as expected");
// Verify exceptions are routed through task
MockCommand commandFail = new MockCommand
{
Fail = true
};
commandFail.ExecuteNonQueryAsync().ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
commandFail.ExecuteNonQueryAsync(source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
commandFail.ExecuteReaderAsync().ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
commandFail.ExecuteReaderAsync(CommandBehavior.SequentialAccess).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
commandFail.ExecuteReaderAsync(source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
commandFail.ExecuteReaderAsync(CommandBehavior.SequentialAccess, source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
commandFail.ExecuteScalarAsync().ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
commandFail.ExecuteScalarAsync(source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
// Verify base implementation does not call Open when passed an already cancelled cancellation token
source.Cancel();
command.LastCommand = "Nothing";
command.ExecuteNonQueryAsync(source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnCanceled).Wait();
DataTestUtility.AssertEqualsWithDescription("Nothing", command.LastCommand, "Expected last command to be 'Nothing'");
command.ExecuteReaderAsync(source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnCanceled).Wait();
DataTestUtility.AssertEqualsWithDescription("Nothing", command.LastCommand, "Expected last command to be 'Nothing'");
command.ExecuteReaderAsync(CommandBehavior.SequentialAccess, source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnCanceled).Wait();
DataTestUtility.AssertEqualsWithDescription("Nothing", command.LastCommand, "Expected last command to be 'Nothing'");
command.ExecuteScalarAsync(source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnCanceled).Wait();
DataTestUtility.AssertEqualsWithDescription("Nothing", command.LastCommand, "Expected last command to be 'Nothing'");
// Verify cancellation
command.WaitForCancel = true;
source = new CancellationTokenSource();
Task.Factory.StartNew(() => { command.WaitForWaitingForCancel(); source.Cancel(); });
Task result = command.ExecuteNonQueryAsync(source.Token);
Assert.True(result.IsFaulted, "Task result should be faulted");
source = new CancellationTokenSource();
Task.Factory.StartNew(() => { command.WaitForWaitingForCancel(); source.Cancel(); });
result = command.ExecuteReaderAsync(source.Token);
Assert.True(result.IsFaulted, "Task result should be faulted");
source = new CancellationTokenSource();
Task.Factory.StartNew(() => { command.WaitForWaitingForCancel(); source.Cancel(); });
result = command.ExecuteScalarAsync(source.Token);
Assert.True(result.IsFaulted, "Task result should be faulted");
}
[CheckConnStrSetupFact]
public static void TestDbDataReader()
{
var query = Enumerable.Range(1, 2).Select((x) => new object[] { x, x.ToString(), DBNull.Value });
MockDataReader reader = new MockDataReader { Results = query.GetEnumerator() };
CancellationTokenSource source = new CancellationTokenSource();
Task<bool> result;
result = reader.ReadAsync(); result.Wait();
DataTestUtility.AssertEqualsWithDescription("Read", reader.LastCommand, "Last command was not as expected");
Assert.True(result.Result, "Should have received a Result from the ReadAsync");
Assert.False(reader.CancellationToken.CanBeCanceled, "Default cancellation token should not be cancellable");
GetFieldValueAsync(reader, 0, 1);
Assert.False(reader.CancellationToken.CanBeCanceled, "Default cancellation token should not be cancellable");
GetFieldValueAsync(reader, source.Token, 1, "1");
result = reader.ReadAsync(source.Token); result.Wait();
DataTestUtility.AssertEqualsWithDescription("Read", reader.LastCommand, "Last command was not as expected");
Assert.True(result.Result, "Should have received a Result from the ReadAsync");
GetFieldValueAsync<object>(reader, 2, DBNull.Value);
GetFieldValueAsync<DBNull>(reader, 2, DBNull.Value);
reader.GetFieldValueAsync<int?>(2).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
reader.GetFieldValueAsync<string>(2).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
reader.GetFieldValueAsync<bool>(2).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
DataTestUtility.AssertEqualsWithDescription("GetValue", reader.LastCommand, "Last command was not as expected");
result = reader.ReadAsync(); result.Wait();
DataTestUtility.AssertEqualsWithDescription("Read", reader.LastCommand, "Last command was not as expected");
Assert.False(result.Result, "Should NOT have received a Result from the ReadAsync");
result = reader.NextResultAsync();
DataTestUtility.AssertEqualsWithDescription("NextResult", reader.LastCommand, "Last command was not as expected");
Assert.False(result.Result, "Should NOT have received a Result from NextResultAsync");
Assert.False(reader.CancellationToken.CanBeCanceled, "Default cancellation token should not be cancellable");
result = reader.NextResultAsync(source.Token);
DataTestUtility.AssertEqualsWithDescription("NextResult", reader.LastCommand, "Last command was not as expected");
Assert.False(result.Result, "Should NOT have received a Result from NextResultAsync");
MockDataReader readerFail = new MockDataReader { Results = query.GetEnumerator(), Fail = true };
readerFail.ReadAsync().ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
readerFail.ReadAsync(source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
readerFail.NextResultAsync().ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
readerFail.NextResultAsync(source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
readerFail.GetFieldValueAsync<object>(0).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
readerFail.GetFieldValueAsync<object>(0, source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
source.Cancel();
reader.LastCommand = "Nothing";
reader.ReadAsync(source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnCanceled).Wait();
DataTestUtility.AssertEqualsWithDescription("Nothing", reader.LastCommand, "Expected last command to be 'Nothing'");
reader.NextResultAsync(source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnCanceled).Wait();
DataTestUtility.AssertEqualsWithDescription("Nothing", reader.LastCommand, "Expected last command to be 'Nothing'");
reader.GetFieldValueAsync<object>(0, source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnCanceled).Wait();
DataTestUtility.AssertEqualsWithDescription("Nothing", reader.LastCommand, "Expected last command to be 'Nothing'");
}
private static void GetFieldValueAsync<T>(MockDataReader reader, int ordinal, T expected)
{
Task<T> result = reader.GetFieldValueAsync<T>(ordinal);
result.Wait();
DataTestUtility.AssertEqualsWithDescription("GetValue", reader.LastCommand, "Last command was not as expected");
DataTestUtility.AssertEqualsWithDescription(expected, result.Result, "GetFieldValueAsync did not return expected value");
}
private static void GetFieldValueAsync<T>(MockDataReader reader, CancellationToken cancellationToken, int ordinal, T expected)
{
Task<T> result = reader.GetFieldValueAsync<T>(ordinal, cancellationToken);
result.Wait();
DataTestUtility.AssertEqualsWithDescription("GetValue", reader.LastCommand, "Last command was not as expected");
DataTestUtility.AssertEqualsWithDescription(expected, result.Result, "GetFieldValueAsync did not return expected value");
}
}
}
| |
#region License
// Distributed under the MIT License
// ============================================================
// Copyright (c) 2019 Hotcakes Commerce, LLC
//
// 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;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
namespace Hotcakes.Shipping.Ups
{
[Serializable]
public sealed class XmlTools
{
private XmlTools()
{
}
/// -----------------------------------------------------------------------------
/// <summary>
/// builds XML access key for UPS requests
/// </summary>
/// <param name="settings"></param>
/// <returns></returns>
/// <remarks>
/// </remarks>
/// -----------------------------------------------------------------------------
public static string BuildAccessKey(UpsSettings settings)
{
var sXML = string.Empty;
var strWriter = new StringWriter();
var xw = new XmlTextWriter(strWriter)
{
Formatting = Formatting.Indented,
Indentation = 3
};
xw.WriteStartDocument();
//--------------------------------------------
// Agreement Request
xw.WriteStartElement("AccessRequest");
xw.WriteElementString("AccessLicenseNumber", settings.License);
xw.WriteElementString("UserId", settings.UserID);
xw.WriteElementString("Password", settings.Password);
xw.WriteEndElement();
// End Agreement Request
//--------------------------------------------
xw.WriteEndDocument();
xw.Flush();
xw.Close();
sXML = strWriter.GetStringBuilder().ToString();
xw = null;
return sXML;
}
public static string ReadHtmlPage_POST(string sURL, string sPostData)
{
HttpWebResponse objResponse;
HttpWebRequest objRequest;
var result = string.Empty;
byte[] bytes;
// Encode Post Stream
try
{
bytes = Encoding.Default.GetBytes(sPostData);
}
catch (Exception Ex1)
{
throw new ArgumentException("Setup Bytes Exception: " + Ex1.Message);
}
// Create Request
try
{
objRequest = (HttpWebRequest) WebRequest.Create(sURL);
objRequest.Method = "POST";
objRequest.ContentLength = bytes.Length;
objRequest.ContentType = "application/x-www-form-urlencoded";
}
catch (Exception E)
{
throw new ArgumentException("Error Creating Web Request: " + E.Message);
}
// Dump Post Data to Request Stream
try
{
var OutStream = objRequest.GetRequestStream();
OutStream.Write(bytes, 0, bytes.Length);
OutStream.Close();
}
catch (Exception Ex)
{
throw new ArgumentException("Error Posting Data: " + Ex.Message + " " + Ex.Source + " " + Ex.StackTrace);
}
finally
{
}
// Read Response
try
{
objResponse = (HttpWebResponse) objRequest.GetResponse();
var sr = new StreamReader(objResponse.GetResponseStream(), Encoding.Default, true);
result += sr.ReadToEnd();
sr.Close();
}
catch (Exception Exx)
{
throw new ArgumentException("Stream Reader Error: " + Exx.Message + " " + Exx.Source);
}
return result;
}
public static string CleanPhoneNumber(string sNumber)
{
var input = sNumber.Trim();
input = Regex.Replace(input, @"[^0-9]", string.Empty);
return input;
}
public static string TrimToLength(string input, int maxLength)
{
if (input == null)
{
return string.Empty;
}
if (input.Length < 1)
{
return input;
}
if (maxLength < 0)
{
maxLength = input.Length;
}
if (input.Length > maxLength)
{
return input.Substring(0, maxLength);
}
return input;
}
#region " Conversion Methods "
public static string ConvertCurrencyCodeToString(CurrencyCode c)
{
var result = "USD";
switch (c)
{
case CurrencyCode.AustalianDollar:
result = "AUD";
break;
case CurrencyCode.Baht:
result = "THB";
break;
case CurrencyCode.BritishPounds:
result = "GBP";
break;
case CurrencyCode.CanadianDollar:
result = "CAD";
break;
case CurrencyCode.DenmarkKrone:
result = "DKK";
break;
case CurrencyCode.Drachma:
result = "GRD";
break;
case CurrencyCode.Euro:
result = "EUR";
break;
case CurrencyCode.HongKongDollar:
result = "HKD";
break;
case CurrencyCode.NewZealandDollar:
result = "NZD";
break;
case CurrencyCode.NorwayKrone:
result = "NOK";
break;
case CurrencyCode.Peso:
result = "MXN";
break;
case CurrencyCode.Ringgit:
result = "MYR";
break;
case CurrencyCode.SingaporeDollar:
result = "SGD";
break;
case CurrencyCode.SwedishKrona:
result = "SEK";
break;
case CurrencyCode.SwissFranc:
result = "CHF";
break;
case CurrencyCode.TaiwanDollar:
result = "TWD";
break;
case CurrencyCode.UsDollar:
result = "USD";
break;
default:
result = "USD";
break;
}
return result;
}
public static CurrencyCode ConvertStringToCurrencyCode(string s)
{
var result = CurrencyCode.UsDollar;
switch (s.ToUpper())
{
case "AUD":
result = CurrencyCode.AustalianDollar;
break;
case "THB":
result = CurrencyCode.Baht;
break;
case "GBP":
result = CurrencyCode.BritishPounds;
break;
case "CAD":
result = CurrencyCode.CanadianDollar;
break;
case "DKK":
result = CurrencyCode.DenmarkKrone;
break;
case "GRD":
result = CurrencyCode.Drachma;
break;
case "EUR":
result = CurrencyCode.Euro;
break;
case "HKD":
result = CurrencyCode.HongKongDollar;
break;
case "NZD":
result = CurrencyCode.NewZealandDollar;
break;
case "NOK":
result = CurrencyCode.NorwayKrone;
break;
case "MXN":
result = CurrencyCode.Peso;
break;
case "MYR":
result = CurrencyCode.Ringgit;
break;
case "SGD":
result = CurrencyCode.SingaporeDollar;
break;
case "SEK":
result = CurrencyCode.SwedishKrona;
break;
case "CHF":
result = CurrencyCode.SwissFranc;
break;
case "TWD":
result = CurrencyCode.TaiwanDollar;
break;
case "USD":
result = CurrencyCode.UsDollar;
break;
default:
result = CurrencyCode.UsDollar;
break;
}
return result;
}
public static UnitsType ConvertStringToUnits(string s)
{
var result = UnitsType.Imperial;
switch (s.ToUpper())
{
case "LBS":
result = UnitsType.Imperial;
break;
case "IN":
result = UnitsType.Imperial;
break;
case "KGS":
result = UnitsType.Metric;
break;
case "CM":
result = UnitsType.Metric;
break;
default:
result = UnitsType.Imperial;
break;
}
return result;
}
public static ShipLabelFormat ConvertStringToLabelFormat(string s)
{
var result = ShipLabelFormat.Gif;
switch (s.ToUpper())
{
case "GIF":
result = ShipLabelFormat.Gif;
break;
case "EPL":
result = ShipLabelFormat.Epl2;
break;
default:
result = ShipLabelFormat.Gif;
break;
}
return result;
}
public static string ConvertReferenceNumberCodeToString(ReferenceNumberCode c)
{
var result = "TN";
switch (c)
{
case ReferenceNumberCode.AccountsRecievableCustomerAccount:
result = "AJ";
break;
case ReferenceNumberCode.AppropriationNumber:
result = "AT";
break;
case ReferenceNumberCode.BillOfLadingNumber:
result = "BM";
break;
case ReferenceNumberCode.CodNumber:
result = "9V";
break;
case ReferenceNumberCode.DealerOrderNumber:
result = "ON";
break;
case ReferenceNumberCode.DepartmentNumber:
result = "DP";
break;
case ReferenceNumberCode.EmployersIDNumber:
result = "EI";
break;
case ReferenceNumberCode.FdaProductCode:
result = "3Q";
break;
case ReferenceNumberCode.FederalTaxPayerIDNumber:
result = "TJ";
break;
case ReferenceNumberCode.InvoiceNumber:
result = "IK";
break;
case ReferenceNumberCode.ManifestKeyNumber:
result = "MK";
break;
case ReferenceNumberCode.ModelNumber:
result = "MJ";
break;
case ReferenceNumberCode.PartNumber:
result = "PM";
break;
case ReferenceNumberCode.ProductionCode:
result = "PC";
break;
case ReferenceNumberCode.PurchaseOrderNumber:
result = "PO";
break;
case ReferenceNumberCode.PurchaseRequisitionNumber:
result = "RQ";
break;
case ReferenceNumberCode.ReturnAuthorizationNumber:
result = "RZ";
break;
case ReferenceNumberCode.SalesPersonNumber:
result = "SA";
break;
case ReferenceNumberCode.SerialNumber:
result = "SE";
break;
case ReferenceNumberCode.SocialSecurityNumber:
result = "SY";
break;
case ReferenceNumberCode.StoreNumber:
result = "ST";
break;
case ReferenceNumberCode.TransactionReferenceNumber:
result = "TN";
break;
default:
result = "TN";
break;
}
return result;
}
#endregion
#region " Write Entity Methods "
public static bool WriteSingleUpsPackage(ref XmlTextWriter xw, ref Package p)
{
var result = true;
decimal dGirth = 0;
decimal dLength = 0;
decimal dHeight = 0;
decimal dwidth = 0;
var sar = new SortedList(2) {{1, p.Length}, {2, p.Width}, {3, p.Height}};
var myEnumerator = sar.GetEnumerator();
var place = 0;
while (myEnumerator.MoveNext())
{
place += 1;
switch (place)
{
case 1:
dLength = Convert.ToDecimal(myEnumerator.Value);
break;
case 2:
dwidth = Convert.ToDecimal(myEnumerator.Value);
break;
case 3:
dHeight = Convert.ToDecimal(myEnumerator.Value);
break;
}
}
myEnumerator = null;
dGirth = dwidth + dwidth + dHeight + dHeight;
//--------------------------------------------
// Package
xw.WriteStartElement("Package");
xw.WriteStartElement("PackagingType");
var packagingCode = Convert.ToInt32(p.Packaging).ToString();
if (packagingCode.Length < 2)
{
packagingCode = "0" + packagingCode;
}
xw.WriteElementString("Code", packagingCode);
if (p.Description != string.Empty)
{
xw.WriteElementString("Description", p.Description);
}
xw.WriteEndElement();
if (p.Packaging == PackagingType.CustomerSupplied)
{
if (dLength > 0 | dHeight > 0 | dwidth > 0)
{
xw.WriteStartElement("Dimensions");
xw.WriteStartElement("UnitOfMeasure");
switch (p.DimensionalUnits)
{
case UnitsType.Imperial:
xw.WriteElementString("Code", "IN");
break;
case UnitsType.Metric:
xw.WriteElementString("Code", "CM");
break;
default:
xw.WriteElementString("Code", "IN");
break;
}
xw.WriteEndElement();
xw.WriteElementString("Length", Math.Round(dLength, 0).ToString());
xw.WriteElementString("Width", Math.Round(dwidth, 0).ToString());
xw.WriteElementString("Height", Math.Round(dHeight, 0).ToString());
xw.WriteEndElement();
}
}
// Weight
if (p.Weight > 0)
{
xw.WriteStartElement("PackageWeight");
xw.WriteStartElement("UnitOfMeasure");
switch (p.WeightUnits)
{
case UnitsType.Imperial:
xw.WriteElementString("Code", "LBS");
break;
case UnitsType.Metric:
xw.WriteElementString("Code", "KGS");
break;
default:
xw.WriteElementString("Code", "LBS");
break;
}
xw.WriteEndElement();
xw.WriteElementString("Weight", Math.Round(p.Weight, 1).ToString());
xw.WriteEndElement();
}
// Oversize Checks
var oversizeCheck = dGirth + dLength;
if (oversizeCheck > 84)
{
if (oversizeCheck < 108 & p.Weight < 30)
{
xw.WriteElementString("OversizePackage", "1");
}
else
{
if (p.Weight < 70)
{
xw.WriteElementString("OversizePackage", "2");
}
else
{
xw.WriteElementString("OversizePackage", "0");
}
}
}
// ReferenceNumber
if (p.ReferenceNumber != string.Empty)
{
xw.WriteStartElement("ReferenceNumber");
var codeType = ConvertReferenceNumberCodeToString(p.ReferenceNumberType);
xw.WriteElementString("Code", codeType);
xw.WriteElementString("Value", TrimToLength(p.ReferenceNumber, 35));
xw.WriteEndElement();
}
// ReferenceNumber2
if (p.ReferenceNumber2 != string.Empty)
{
xw.WriteStartElement("ReferenceNumber");
var codeType = ConvertReferenceNumberCodeToString(p.ReferenceNumber2Type);
xw.WriteElementString("Code", codeType);
xw.WriteElementString("Value", TrimToLength(p.ReferenceNumber2, 35));
xw.WriteEndElement();
}
// Additional Handling
if (p.AdditionalHandlingIsRequired)
{
xw.WriteElementString("AdditionalHandling", "");
}
//-------------------------------------------
// Start Service Options
xw.WriteStartElement("PackageServiceOptions");
// Delivery Confirmation
if (p.DeliveryConfirmation)
{
xw.WriteStartElement("DeliveryConfirmation");
xw.WriteElementString("DCISType", Convert.ToInt32(p.DeliveryConfirmationType).ToString());
if (p.DeliveryConfirmationControlNumber != string.Empty)
{
xw.WriteElementString("DCISNumber", TrimToLength(p.DeliveryConfirmationControlNumber, 11));
}
xw.WriteEndElement();
}
// InsuredValue
if (p.InsuredValue > 0)
{
xw.WriteStartElement("InsuredValue");
xw.WriteElementString("MonetaryValue", p.InsuredValue.ToString());
xw.WriteElementString("CurrencyCode", ConvertCurrencyCodeToString(p.InsuredValueCurrency));
xw.WriteEndElement();
}
// COD
if (p.COD)
{
xw.WriteStartElement("COD");
xw.WriteElementString("CODCode", "3");
xw.WriteElementString("CODFundsCode", Convert.ToInt32(p.CODPaymentType).ToString());
xw.WriteStartElement("CODAmount");
xw.WriteElementString("CurrencyCode", ConvertCurrencyCodeToString(p.CODCurrencyCode));
xw.WriteElementString("MonetaryValue", p.CODAmount.ToString());
xw.WriteEndElement();
xw.WriteEndElement();
}
// Verbal Confirmation
if (p.VerbalConfirmation)
{
xw.WriteStartElement("VerbalConfirmation");
xw.WriteStartElement("ContactInfo");
if (p.VerbalConfirmationName != string.Empty)
{
xw.WriteElementString("Name", p.VerbalConfirmationName);
}
if (p.VerbalConfirmationPhoneNumber != string.Empty)
{
xw.WriteElementString("PhoneNumber", p.VerbalConfirmationPhoneNumber);
}
xw.WriteEndElement();
xw.WriteEndElement();
}
xw.WriteEndElement();
// End Service Options
//-------------------------------------------
xw.WriteEndElement();
// End Package
//--------------------------------------------
return result;
}
public static bool WriteShipperXml(ref XmlTextWriter xw, ref Entity e)
{
return WriteEntity(ref xw, ref e, EntityType.Shipper);
}
public static bool WriteShipToXml(ref XmlTextWriter xw, ref Entity e)
{
return WriteEntity(ref xw, ref e, EntityType.ShipTo);
}
public static bool WriteShipFromXml(ref XmlTextWriter xw, ref Entity e)
{
return WriteEntity(ref xw, ref e, EntityType.ShipFrom);
}
private static bool WriteEntity(ref XmlTextWriter xw, ref Entity e, EntityType et)
{
var result = true;
//--------------------------------------------
// Start Opening Tag
switch (et)
{
case EntityType.ShipFrom:
xw.WriteStartElement("ShipFrom");
xw.WriteElementString("CompanyName", TrimToLength(e.CompanyOrContactName, 35));
break;
case EntityType.Shipper:
xw.WriteStartElement("Shipper");
xw.WriteElementString("Name", TrimToLength(e.CompanyOrContactName, 35));
xw.WriteElementString("ShipperNumber", e.AccountNumber);
if (e.TaxIDNumber != string.Empty)
{
xw.WriteElementString("TaxIdentificationNumber", e.TaxIDNumber);
}
break;
case EntityType.ShipTo:
xw.WriteStartElement("ShipTo");
xw.WriteElementString("CompanyName", TrimToLength(e.CompanyOrContactName, 35));
if (e.TaxIDNumber != string.Empty)
{
xw.WriteElementString("TaxIdentificationNumber", e.TaxIDNumber);
}
break;
}
if (e.AttentionName != string.Empty)
{
xw.WriteElementString("AttentionName", TrimToLength(e.AttentionName, 35));
}
if (e.PhoneNumber != string.Empty)
{
xw.WriteElementString("PhoneNumber", e.PhoneNumber);
}
if (e.FaxNumber != string.Empty)
{
xw.WriteElementString("FaxNumber", e.FaxNumber);
}
//-------------------------------------------
// Start Address
xw.WriteStartElement("Address");
xw.WriteElementString("AddressLine1", TrimToLength(e.AddressLine1, 35));
if (e.AddressLine2 != string.Empty)
{
xw.WriteElementString("AddressLine2", TrimToLength(e.AddressLine2, 35));
}
if (e.AddressLine3 != string.Empty)
{
xw.WriteElementString("AddressLine3", TrimToLength(e.AddressLine3, 35));
}
xw.WriteElementString("City", e.City);
if (e.StateProvinceCode != string.Empty)
{
xw.WriteElementString("StateProvinceCode", TrimToLength(e.StateProvinceCode, 5));
}
if (e.PostalCode != string.Empty)
{
xw.WriteElementString("PostalCode", TrimToLength(e.PostalCode, 10));
}
xw.WriteElementString("CountryCode", TrimToLength(e.CountryCode, 2));
if (et == EntityType.ShipTo)
{
if (e.ResidentialAddress)
{
xw.WriteElementString("ResidentialAddress", "");
}
}
xw.WriteEndElement();
// End Address
//-------------------------------------------
xw.WriteEndElement();
// End Opening Tag
//--------------------------------------------
return result;
}
#endregion
#region " XPath Parsing Methods "
public static string XPathToString(ref XmlDocument xdoc, string xpath)
{
var result = string.Empty;
var node = xdoc.SelectSingleNode(xpath);
if (node != null)
{
result = node.InnerText;
}
return result;
}
public static decimal XPathToInteger(ref XmlDocument xdoc, string xpath)
{
var result = 0;
var node = xdoc.SelectSingleNode(xpath);
if (node != null)
{
result = int.Parse(node.InnerText);
}
return result;
}
public static decimal XPathToDecimal(ref XmlDocument xdoc, string xpath)
{
decimal result = 0;
var node = xdoc.SelectSingleNode(xpath);
if (node != null)
{
result = decimal.Parse(node.InnerText);
}
return result;
}
public static CurrencyCode XPathToCurrencyCode(ref XmlDocument xdoc, string xpath)
{
var result = CurrencyCode.UsDollar;
var node = xdoc.SelectSingleNode(xpath);
if (node != null)
{
result = ConvertStringToCurrencyCode(node.InnerText);
}
return result;
}
public static UnitsType XPathToUnits(ref XmlDocument xdoc, string xpath)
{
var result = UnitsType.Imperial;
var node = xdoc.SelectSingleNode(xpath);
if (node != null)
{
result = ConvertStringToUnits(node.InnerText);
}
return result;
}
public static ShipLabelFormat XPathToLabelFormat(ref XmlDocument xdoc, string xpath)
{
var result = ShipLabelFormat.Gif;
var node = xdoc.SelectSingleNode(xpath);
if (node != null)
{
result = ConvertStringToLabelFormat(node.InnerText);
}
return result;
}
#endregion
#region " Shipment Confirm "
public static ShipResponse SendConfirmRequest(ref ShipRequest req)
{
var result = new ShipResponse();
// Build Request and save output
var requestXml = BuildShipConfirmRequest(ref req);
req.XmlConfirmRequest = requestXml;
// Build Url for UPS Service
var actionUrl = req.Settings.ServerUrl;
actionUrl += "ShipConfirm";
// Send Request and Store Response
var responseXml = string.Empty;
responseXml = ReadHtmlPage_POST(actionUrl, requestXml);
req.XmlConfirmResponse = responseXml;
// Parse Response
result = ParseShipConfirmResponse(responseXml);
return result;
}
private static string BuildShipConfirmRequest(ref ShipRequest req)
{
var strWriter = new StringWriter();
var xw = new XmlTextWriter(strWriter)
{
Formatting = Formatting.Indented,
Indentation = 3
};
xw.WriteStartDocument();
//--------------------------------------------
// Start Shipment Confirm Request
xw.WriteStartElement("ShipmentConfirmRequest");
//--------------------------------------------
// Request
xw.WriteStartElement("Request");
//--------------------------------------------
// TransactionReference
xw.WriteStartElement("TransactionReference");
xw.WriteElementString("CustomerContext", "Shipment Confirm Request");
xw.WriteElementString("XpciVersion", "1.0001");
xw.WriteEndElement();
// End TransactionReference
//--------------------------------------------
xw.WriteElementString("RequestAction", "ShipConfirm");
if (req.AddressVerification)
{
xw.WriteElementString("RequestOption", "validate");
}
else
{
xw.WriteElementString("RequestOption", "nonvalidate");
}
xw.WriteEndElement();
// End Request
//--------------------------------------------
//--------------------------------------------
// Start Label Specification
xw.WriteStartElement("LabelSpecification");
// Label Print Method
xw.WriteStartElement("LabelPrintMethod");
switch (req.LabelFormat)
{
case ShipLabelFormat.Epl2:
xw.WriteElementString("Code", "EPL");
break;
case ShipLabelFormat.Gif:
xw.WriteElementString("Code", "GIF");
break;
default:
xw.WriteElementString("Code", "GIF");
break;
}
xw.WriteEndElement();
// Image Label Format
xw.WriteStartElement("LabelImageFormat");
xw.WriteElementString("Code", "GIF");
xw.WriteEndElement();
// Http User Agent
if (req.BrowserHttpUserAgentString != string.Empty)
{
xw.WriteElementString("HTTPUserAgent", req.BrowserHttpUserAgentString);
}
// Stock Size
if ((req.LabelStockSizeHeight != 0) & (req.LabelStockSizeWidth != 0))
{
xw.WriteStartElement("LabelStockSize");
if (req.LabelFormat == ShipLabelFormat.Epl2)
{
// Only 4 is valid for Epl
xw.WriteElementString("Height", "4");
// Only 6 and 8 are valid
if ((req.LabelStockSizeWidth != 6) & (req.LabelStockSizeWidth != 8))
{
xw.WriteElementString("Width", "6");
// Pick a default
}
else
{
xw.WriteElementString("Width", req.LabelStockSizeWidth.ToString());
}
}
else
{
xw.WriteElementString("Height", req.LabelStockSizeHeight.ToString());
xw.WriteElementString("Width", req.LabelStockSizeWidth.ToString());
}
xw.WriteEndElement();
}
xw.WriteEndElement();
// End Label Specification
//--------------------------------------------
//--------------------------------------------
// Shipment
xw.WriteStartElement("Shipment");
if (req.ShipmentDescription != string.Empty)
{
xw.WriteElementString("Description", TrimToLength(req.ShipmentDescription, 35));
}
if (req.NonValuedDocumentsOnly)
{
xw.WriteElementString("DocumentsOnly", "");
}
// Shipper
var tempShipper = req.Shipper;
WriteShipperXml(ref xw, ref tempShipper);
// ShipTo
var tempShipTo = req.ShipTo;
WriteShipToXml(ref xw, ref tempShipTo);
// ShipFrom
var tempShipFrom = req.ShipFrom;
WriteShipFromXml(ref xw, ref tempShipFrom);
// Start Payment Information
xw.WriteStartElement("PaymentInformation");
switch (req.BillTo)
{
case PaymentType.ReceiverUpsAccount:
xw.WriteStartElement("FreightCollect");
xw.WriteStartElement("BillReceiver");
xw.WriteElementString("AccountNumber", req.BillToAccountNumber);
if (req.BillToPostalCode != string.Empty)
{
xw.WriteStartElement("Address");
xw.WriteElementString("PostalCode", req.BillToPostalCode);
xw.WriteEndElement();
}
xw.WriteEndElement();
xw.WriteEndElement();
break;
case PaymentType.ShipperCreditCard:
xw.WriteStartElement("Prepaid");
xw.WriteStartElement("BillShipper");
xw.WriteStartElement("CreditCard");
xw.WriteElementString("Type", "0" + Convert.ToInt32(req.BillToCreditCardType));
xw.WriteElementString("Number", req.BillToCreditCardNumber);
var expDate = "";
if (req.BillToCreditCardExpirationMonth < 10)
{
expDate = "0" + req.BillToCreditCardExpirationMonth;
}
else
{
expDate = req.BillToCreditCardExpirationMonth.ToString();
}
expDate = expDate + req.BillToCreditCardExpirationYear;
xw.WriteElementString("ExpirationDate", expDate);
xw.WriteEndElement();
xw.WriteEndElement();
xw.WriteEndElement();
break;
case PaymentType.ShipperUpsAccount:
xw.WriteStartElement("Prepaid");
xw.WriteStartElement("BillShipper");
xw.WriteElementString("AccountNumber", req.BillToAccountNumber);
xw.WriteEndElement();
xw.WriteEndElement();
break;
case PaymentType.ThirdPartyUpsAccount:
xw.WriteStartElement("BillThirdParty");
xw.WriteStartElement("BillThirdPartyShipper");
xw.WriteElementString("AccountNumber", req.BillToAccountNumber);
xw.WriteStartElement("ThirdParty");
xw.WriteStartElement("Address");
if (!string.IsNullOrEmpty(req.BillToPostalCode))
{
xw.WriteElementString("PostalCode", req.BillToPostalCode);
}
xw.WriteElementString("CountryCode", req.BillToCountryCode);
xw.WriteEndElement();
xw.WriteEndElement();
xw.WriteEndElement();
xw.WriteEndElement();
break;
}
xw.WriteEndElement();
// End Payment Information
// Reference Number
if (!string.IsNullOrEmpty(req.ReferenceNumber))
{
xw.WriteStartElement("ReferenceNumber");
xw.WriteElementString("Value", TrimToLength(req.ReferenceNumber, 35));
var codeType = ConvertReferenceNumberCodeToString(req.ReferenceNumberType);
xw.WriteElementString("Code", codeType);
xw.WriteEndElement();
}
// Start Service
xw.WriteStartElement("Service");
var stringServiceCode = Convert.ToInt32(req.Service).ToString();
if (stringServiceCode.Length < 2)
{
stringServiceCode = "0" + stringServiceCode;
}
xw.WriteElementString("Code", stringServiceCode);
xw.WriteEndElement();
// End Service
// Invoice Line Total
if (req.InvoiceLineTotal)
{
xw.WriteStartElement("InvoiceLineTotal");
xw.WriteElementString("MonetaryValue", req.InvoiceLineTotalAmount.ToString());
xw.WriteElementString("CurrencyCode", ConvertCurrencyCodeToString(req.InvoiceLineTotalCurrency));
xw.WriteEndElement();
}
for (var i = 0; i <= req.Packages.Count - 1; i++)
{
var tempPackage = (Package) req.Packages[i];
WriteSingleUpsPackage(ref xw, ref tempPackage);
}
//-------------------------------------------
// Start Shipment Service Options
xw.WriteStartElement("ShipmentServiceOptions");
// SaturdayDelivery
if (req.SaturdayDelivery)
{
xw.WriteElementString("SaturdayDelivery", string.Empty);
}
// COD
if (req.COD)
{
xw.WriteStartElement("COD");
xw.WriteElementString("CODCode", "3");
xw.WriteElementString("CODFundsCode", Convert.ToInt32(req.CODPaymentType).ToString());
xw.WriteStartElement("CODAmount");
xw.WriteElementString("CurrencyCode", ConvertCurrencyCodeToString(req.CODCurrencyCode));
xw.WriteElementString("MonetaryValue", req.CODAmount.ToString());
xw.WriteEndElement();
xw.WriteEndElement();
}
// Notification
if (req.Notification)
{
xw.WriteStartElement("Notification");
xw.WriteElementString("NotificationCode", Convert.ToInt32(req.NotificationType).ToString());
xw.WriteStartElement("EMailMessage");
xw.WriteElementString("EMailAddress", req.NotificationEmailAddress);
if (!string.IsNullOrEmpty(req.NotificationUndeliverableEmailAddress))
{
xw.WriteElementString("UndeliverableEMailAddress", req.NotificationUndeliverableEmailAddress);
}
if (!string.IsNullOrEmpty(req.NotificationFromName))
{
xw.WriteElementString("FromName", req.NotificationFromName);
}
if (!string.IsNullOrEmpty(req.NotificationMemo))
{
xw.WriteElementString("Memo", req.NotificationMemo);
}
if (req.NotificationSubjectType != NotificationSubjectCode.DefaultCode)
{
xw.WriteElementString("SubjectCode", "0" + Convert.ToInt32(req.NotificationSubjectType));
}
xw.WriteEndElement();
xw.WriteEndElement();
}
xw.WriteEndElement();
// End Shipment Service Options
//-------------------------------------------
xw.WriteEndElement();
// End Shipment
//--------------------------------------------
xw.WriteEndElement();
// End Shipment Confirm Request
//--------------------------------------------
xw.WriteEndDocument();
xw.Flush();
xw.Close();
// Output Xml As String with Access Key
var sXML = string.Empty;
sXML = BuildAccessKey(req.Settings);
sXML += "\n";
sXML += strWriter.GetStringBuilder().ToString();
return sXML;
}
private static ShipResponse ParseShipConfirmResponse(string xml)
{
var result = new ShipResponse();
try
{
XmlDocument xDoc;
xDoc = new XmlDocument();
xDoc.LoadXml(xml);
var nodeResponseCode = xDoc.SelectSingleNode("ShipmentConfirmResponse/Response/ResponseStatusCode");
if (nodeResponseCode != null)
{
var responseCode = 0;
responseCode = int.Parse(nodeResponseCode.InnerText);
if (responseCode == 1)
{
result.Success = true;
// Parse appropriate info
result.ShipmentDigest = XPathToString(ref xDoc, "ShipmentConfirmResponse/ShipmentDigest");
result.TrackingNumber = XPathToString(ref xDoc,
"ShipmentConfirmResponse/ShipmentIdentificationNumber");
result.BillingWeight = XPathToDecimal(ref xDoc, "ShipmentConfirmResponse/BillingWeight/Weight");
result.BillingWeightUnits = XPathToUnits(ref xDoc,
"ShipmentConfirmResponse/BillingWeight/UnitOfMeasurement/Code");
result.ServiceOptionsCharge = XPathToDecimal(ref xDoc,
"ShipmentConfirmResponse/ShipmentCharges/ServiceOptionsCharges/MonetaryValue");
result.ServiceOptionsChargeCurrency = XPathToCurrencyCode(ref xDoc,
"ShipmentConfirmResponse/ShipmentCharges/ServiceOptionsCharges/CurrencyCode");
result.TotalCharge = XPathToDecimal(ref xDoc,
"ShipmentConfirmResponse/ShipmentCharges/TotalCharges/MonetaryValue");
result.TotalChargeCurrency = XPathToCurrencyCode(ref xDoc,
"ShipmentConfirmResponse/ShipmentCharges/TotalCharges/CurrencyCode");
result.TransportationCharge = XPathToDecimal(ref xDoc,
"ShipmentConfirmResponse/ShipmentCharges/TransportationCharges/MonetaryValue");
result.TransportationChargeCurrency = XPathToCurrencyCode(ref xDoc,
"ShipmentConfirmResponse/ShipmentCharges/TransportationCharges/CurrencyCode");
}
else
{
result.Success = false;
// Parse error
result.ErrorMessage = XPathToString(ref xDoc,
"ShipmentConfirmResponse/Response/Error/ErrorDescription");
}
}
else
{
result.Success = false;
result.ErrorMessage = "Unable to Parse Response Code.";
}
}
catch (Exception Exx)
{
result.ErrorMessage = "Parsing Error: " + Exx.Message;
result.Success = false;
}
return result;
}
#endregion
#region " Shipment Accept "
public static ShipAcceptResponse SendShipAcceptRequest(ref ShipAcceptRequest req)
{
var result = new ShipAcceptResponse();
// Build Request and save output
var requestXml = BuildShipAcceptRequest(ref req);
req.XmlAcceptRequest = requestXml;
// Build Url for UPS Service
var actionUrl = req.Settings.ServerUrl;
actionUrl += "ShipAccept";
// Send Request and Store Response
var responseXml = string.Empty;
responseXml = ReadHtmlPage_POST(actionUrl, requestXml);
req.XmlAcceptResponse = responseXml;
// Parse Response
result = ParseShipAcceptResponse(responseXml);
return result;
}
private static string BuildShipAcceptRequest(ref ShipAcceptRequest req)
{
var strWriter = new StringWriter();
var xw = new XmlTextWriter(strWriter)
{
Formatting = Formatting.Indented,
Indentation = 3
};
xw.WriteStartDocument();
//--------------------------------------------
// Start Shipment Accept Request
xw.WriteStartElement("ShipmentAcceptRequest");
//--------------------------------------------
// Request
xw.WriteStartElement("Request");
//--------------------------------------------
// TransactionReference
xw.WriteStartElement("TransactionReference");
xw.WriteElementString("CustomerContext", "Shipment Confirm Request");
xw.WriteElementString("XpciVersion", "1.0001");
xw.WriteEndElement();
// End TransactionReference
//--------------------------------------------
xw.WriteElementString("RequestAction", "ShipAccept");
xw.WriteEndElement();
// End Request
//--------------------------------------------
xw.WriteElementString("ShipmentDigest", req.ShipDigest);
xw.WriteEndElement();
// End Shipment Accept Request
//--------------------------------------------
xw.WriteEndDocument();
xw.Flush();
xw.Close();
// Output Xml As String with Access Key
var sXML = string.Empty;
sXML = BuildAccessKey(req.Settings);
sXML += "\n";
sXML += strWriter.GetStringBuilder().ToString();
return sXML;
}
private static ShipAcceptResponse ParseShipAcceptResponse(string xml)
{
var result = new ShipAcceptResponse();
try
{
XmlDocument xDoc;
xDoc = new XmlDocument();
xDoc.LoadXml(xml);
var nodeResponseCode = xDoc.SelectSingleNode("ShipmentAcceptResponse/Response/ResponseStatusCode");
if (nodeResponseCode != null)
{
var responseCode = 0;
responseCode = int.Parse(nodeResponseCode.InnerText);
if (responseCode == 1)
{
result.Success = true;
// Parse appropriate info
result.TrackingNumber = XPathToString(ref xDoc,
"ShipmentAcceptResponse/ShipmentResults/ShipmentIdentificationNumber");
result.BillingWeight = XPathToDecimal(ref xDoc,
"ShipmentAcceptResponse/ShipmentResults/BillingWeight/Weight");
result.BillingWeightUnits = XPathToUnits(ref xDoc,
"ShipmentAcceptResponse/ShipmentResults/BillingWeight/UnitOfMeasurement/Code");
result.ServiceOptionsCharge = XPathToDecimal(ref xDoc,
"ShipmentAcceptResponse/ShipmentResults/ShipmentCharges/ServiceOptionsCharges/MonetaryValue");
result.ServiceOptionsChargeCurrency = XPathToCurrencyCode(ref xDoc,
"ShipmentAcceptResponse/ShipmentResults/ShipmentCharges/ServiceOptionsCharges/CurrencyCode");
result.TotalCharge = XPathToDecimal(ref xDoc,
"ShipmentAcceptResponse/ShipmentCharges/ShipmentResults/TotalCharges/MonetaryValue");
result.TotalChargeCurrency = XPathToCurrencyCode(ref xDoc,
"ShipmentAcceptResponse/ShipmentResults/ShipmentCharges/TotalCharges/CurrencyCode");
result.TransportationCharge = XPathToDecimal(ref xDoc,
"ShipmentAcceptResponse/ShipmentResults/ShipmentCharges/TransportationCharges/MonetaryValue");
result.TransportationChargeCurrency = XPathToCurrencyCode(ref xDoc,
"ShipmentAcceptResponse/ShipmentResults/ShipmentCharges/TransportationCharges/CurrencyCode");
var packages = xDoc.SelectNodes("/ShipmentAcceptResponse/ShipmentResults/PackageResults");
if (packages != null)
{
ParseShipAcceptResponsePackages(ref result, ref packages);
}
}
else
{
result.Success = false;
// Parse error
result.ErrorMessage = XPathToString(ref xDoc,
"ShipmentAcceptResponse/Response/Error/ErrorDescription");
}
}
else
{
result.Success = false;
result.ErrorMessage = "Unable to Parse Response Code.";
}
}
catch (Exception Exx)
{
result.ErrorMessage = "Parsing Error: " + Exx.Message;
result.Success = false;
}
return result;
}
private static void ParseShipAcceptResponsePackages(ref ShipAcceptResponse res, ref XmlNodeList packages)
{
foreach (XmlNode node in packages)
{
try
{
var xp = new XmlDocument();
xp.LoadXml(node.OuterXml);
var _package = new ShippedPackageInformation
{
TrackingNumber = XPathToString(ref xp, "PackageResults/TrackingNumber"),
Base64Image = XPathToString(ref xp, "PackageResults/LabelImage/GraphicImage"),
Base64Html = XPathToString(ref xp, "PackageResults/LabelImage/HTMLImage"),
Base64Signature = XPathToString(ref xp, "PackageResults/InternationalSignatureGraphicImage"),
LabelFormat = XPathToLabelFormat(ref xp, "PackageResults/LabelImage/LabelImageFormat/Code"),
ServiceOptionsCharge = XPathToDecimal(ref xp,
"PackageResults/ServiceOptionsCharge/MonetaryValue"),
ServiceOptionsChargeCurrency = XPathToCurrencyCode(ref xp,
"PackageResults/ServiceOptionsCharge/CurrencyCode")
};
res.AddPackage(ref _package);
}
catch
{
}
}
}
#endregion
#region "Void Shipment"
public static VoidShipmentResponse SendVoidShipmentRequest(ref VoidShipmentRequest req)
{
var result = new VoidShipmentResponse();
// Build Request and save output
var requestXml = BuildVoidShipRequest(ref req);
req.XmlRequest = requestXml;
// Build Url for UPS Service
var actionUrl = req.Settings.ServerUrl;
actionUrl += "Void";
// Send Request and Store Response
var responseXml = string.Empty;
responseXml = ReadHtmlPage_POST(actionUrl, requestXml);
req.XmlResponse = responseXml;
// Parse Response
result = ParseVoidShipmentResponse(responseXml);
return result;
}
private static string BuildVoidShipRequest(ref VoidShipmentRequest req)
{
var strWriter = new StringWriter();
var xw = new XmlTextWriter(strWriter)
{
Formatting = Formatting.Indented,
Indentation = 3
};
xw.WriteStartDocument();
//--------------------------------------------
// Start Void Shipment Request
xw.WriteStartElement("VoidShipmentRequest");
//--------------------------------------------
// Request
xw.WriteStartElement("Request");
//--------------------------------------------
// TransactionReference
xw.WriteStartElement("TransactionReference");
xw.WriteElementString("CustomerContext", "Void Shipment Request");
xw.WriteElementString("XpciVersion", "1.0001");
xw.WriteEndElement();
// End TransactionReference
//--------------------------------------------
xw.WriteElementString("RequestAction", "1");
xw.WriteElementString("RequestOption", string.Empty);
xw.WriteEndElement();
// End Request
//--------------------------------------------
xw.WriteElementString("ShipmentIdentificationNumber", req.ShipmentIdentificationNumber);
xw.WriteEndElement();
// End Void Shipment Request
//--------------------------------------------
xw.WriteEndDocument();
xw.Flush();
xw.Close();
// Output Xml As String with Access Key
var sXML = string.Empty;
sXML = BuildAccessKey(req.Settings);
sXML += "\n";
sXML += strWriter.GetStringBuilder().ToString();
return sXML;
}
private static VoidShipmentResponse ParseVoidShipmentResponse(string xml)
{
var result = new VoidShipmentResponse();
try
{
XmlDocument xDoc;
xDoc = new XmlDocument();
xDoc.LoadXml(xml);
var nodeResponseCode = xDoc.SelectSingleNode("VoidShipmentResponse/Response/ResponseStatusCode");
if (nodeResponseCode != null)
{
var responseCode = 0;
responseCode = int.Parse(nodeResponseCode.InnerText);
if (responseCode == 1)
{
result.Success = true;
}
else
{
result.Success = false;
// Parse error
result.ErrorMessage = XPathToString(ref xDoc,
"VoidShipmentResponse/Response/Error/ErrorDescription");
}
}
else
{
result.Success = false;
result.ErrorMessage = "Unable to Parse Response Code.";
}
}
catch (Exception Exx)
{
result.ErrorMessage = "Parsing Error: " + Exx.Message;
result.Success = false;
}
return result;
}
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.