context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyrightD
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using OMV = OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Physics.Manager;
namespace OpenSim.Region.Physics.BulletSPlugin
{
/*
* Class to wrap all objects.
* The rest of BulletSim doesn't need to keep checking for avatars or prims
* unless the difference is significant.
*
* Variables in the physicsl objects are in three forms:
* VariableName: used by the simulator and performs taint operations, etc
* RawVariableName: direct reference to the BulletSim storage for the variable value
* ForceVariableName: direct reference (store and fetch) to the value in the physics engine.
* The last one should only be referenced in taint-time.
*/
/*
* As of 20121221, the following are the call sequences (going down) for different script physical functions:
* llApplyImpulse llApplyRotImpulse llSetTorque llSetForce
* SOP.ApplyImpulse SOP.ApplyAngularImpulse SOP.SetAngularImpulse SOP.SetForce
* SOG.ApplyImpulse SOG.ApplyAngularImpulse SOG.SetAngularImpulse
* PA.AddForce PA.AddAngularForce PA.Torque = v PA.Force = v
* BS.ApplyCentralForce BS.ApplyTorque
*/
// Flags used to denote which properties updates when making UpdateProperties calls to linksets, etc.
public enum UpdatedProperties : uint
{
Position = 1 << 0,
Orientation = 1 << 1,
Velocity = 1 << 2,
Acceleration = 1 << 3,
RotationalVelocity = 1 << 4,
EntPropUpdates = Position | Orientation | Velocity | Acceleration | RotationalVelocity,
}
public abstract class BSPhysObject : PhysicsActor
{
protected BSPhysObject()
{
}
protected BSPhysObject(BSScene parentScene, uint localID, string name, string typeName)
{
IsInitialized = false;
PhysScene = parentScene;
LocalID = localID;
PhysObjectName = name;
Name = name; // PhysicsActor also has the name of the object. Someday consolidate.
TypeName = typeName;
// The collection of things that push me around
PhysicalActors = new BSActorCollection(PhysScene);
// Initialize variables kept in base.
GravModifier = 1.0f;
Gravity = new OMV.Vector3(0f, 0f, BSParam.Gravity);
HoverActive = false;
// We don't have any physical representation yet.
PhysBody = new BulletBody(localID);
PhysShape = new BSShapeNull();
UserSetCenterOfMassDisplacement = null;
PrimAssetState = PrimAssetCondition.Unknown;
// Default material type. Also sets Friction, Restitution and Density.
SetMaterial((int)MaterialAttributes.Material.Wood);
CollisionCollection = new CollisionEventUpdate();
CollisionsLastReported = CollisionCollection;
CollisionsLastTick = new CollisionEventUpdate();
CollisionsLastTickStep = -1;
SubscribedEventsMs = 0;
// Crazy values that will never be true
CollidingStep = BSScene.NotASimulationStep;
CollidingGroundStep = BSScene.NotASimulationStep;
CollisionAccumulation = BSScene.NotASimulationStep;
ColliderIsMoving = false;
CollisionScore = 0;
// All axis free.
LockedLinearAxis = LockedAxisFree;
LockedAngularAxis = LockedAxisFree;
}
// Tell the object to clean up.
public virtual void Destroy()
{
PhysicalActors.Enable(false);
PhysScene.TaintedObject(LocalID, "BSPhysObject.Destroy", delegate()
{
PhysicalActors.Dispose();
});
}
public BSScene PhysScene { get; protected set; }
// public override uint LocalID { get; set; } // Use the LocalID definition in PhysicsActor
public string PhysObjectName { get; protected set; }
public string TypeName { get; protected set; }
// Set to 'true' when the object is completely initialized.
// This mostly prevents property updates and collisions until the object is completely here.
public bool IsInitialized { get; protected set; }
// Return the object mass without calculating it or having side effects
public abstract float RawMass { get; }
// Set the raw mass but also update physical mass properties (inertia, ...)
// 'inWorld' true if the object has already been added to the dynamic world.
public abstract void UpdatePhysicalMassProperties(float mass, bool inWorld);
// The gravity being applied to the object. A function of default grav, GravityModifier and Buoyancy.
public virtual OMV.Vector3 Gravity { get; set; }
// The last value calculated for the prim's inertia
public OMV.Vector3 Inertia { get; set; }
// Reference to the physical body (btCollisionObject) of this object
public BulletBody PhysBody;
// Reference to the physical shape (btCollisionShape) of this object
public BSShape PhysShape;
// The physical representation of the prim might require an asset fetch.
// The asset state is first 'Unknown' then 'Waiting' then either 'Failed' or 'Fetched'.
public enum PrimAssetCondition
{
Unknown, Waiting, FailedAssetFetch, FailedMeshing, Fetched
}
public PrimAssetCondition PrimAssetState { get; set; }
public virtual bool AssetFailed()
{
return ( (this.PrimAssetState == PrimAssetCondition.FailedAssetFetch)
|| (this.PrimAssetState == PrimAssetCondition.FailedMeshing) );
}
// The objects base shape information. Null if not a prim type shape.
public PrimitiveBaseShape BaseShape { get; protected set; }
// When the physical properties are updated, an EntityProperty holds the update values.
// Keep the current and last EntityProperties to enable computation of differences
// between the current update and the previous values.
public EntityProperties CurrentEntityProperties { get; set; }
public EntityProperties LastEntityProperties { get; set; }
public virtual OMV.Vector3 Scale { get; set; }
// It can be confusing for an actor to know if it should move or update an object
// depeneding on the setting of 'selected', 'physical, ...
// This flag is the true test -- if true, the object is being acted on in the physical world
public abstract bool IsPhysicallyActive { get; }
// Detailed state of the object.
public abstract bool IsSolid { get; }
public abstract bool IsStatic { get; }
public abstract bool IsSelected { get; }
public abstract bool IsVolumeDetect { get; }
// Materialness
public MaterialAttributes.Material Material { get; private set; }
public override void SetMaterial(int material)
{
Material = (MaterialAttributes.Material)material;
// Setting the material sets the material attributes also.
// TODO: decide if this is necessary -- the simulator does this.
MaterialAttributes matAttrib = BSMaterials.GetAttributes(Material, false);
Friction = matAttrib.friction;
Restitution = matAttrib.restitution;
Density = matAttrib.density;
// DetailLog("{0},{1}.SetMaterial,Mat={2},frict={3},rest={4},den={5}", LocalID, TypeName, Material, Friction, Restitution, Density);
}
public override float Density
{
get
{
return base.Density;
}
set
{
DetailLog("{0},BSPhysObject.Density,set,den={1}", LocalID, value);
base.Density = value;
}
}
// Stop all physical motion.
public abstract void ZeroMotion(bool inTaintTime);
public abstract void ZeroAngularMotion(bool inTaintTime);
// Update the physical location and motion of the object. Called with data from Bullet.
public abstract void UpdateProperties(EntityProperties entprop);
public virtual OMV.Vector3 RawPosition { get; set; }
public abstract OMV.Vector3 ForcePosition { get; set; }
public virtual OMV.Quaternion RawOrientation { get; set; }
public abstract OMV.Quaternion ForceOrientation { get; set; }
public OMV.Vector3 RawVelocity { get; set; }
public abstract OMV.Vector3 ForceVelocity { get; set; }
public OMV.Vector3 RawForce { get; set; }
public OMV.Vector3 RawTorque { get; set; }
public override void AddAngularForce(OMV.Vector3 force, bool pushforce)
{
AddAngularForce(force, pushforce, false);
}
public abstract void AddAngularForce(OMV.Vector3 force, bool pushforce, bool inTaintTime);
public abstract void AddForce(OMV.Vector3 force, bool pushforce, bool inTaintTime);
public abstract OMV.Vector3 ForceRotationalVelocity { get; set; }
public abstract float ForceBuoyancy { get; set; }
public virtual bool ForceBodyShapeRebuild(bool inTaintTime) { return false; }
public override bool PIDActive { set { MoveToTargetActive = value; } }
public override OMV.Vector3 PIDTarget { set { MoveToTargetTarget = value; } }
public override float PIDTau { set { MoveToTargetTau = value; } }
public bool MoveToTargetActive { get; set; }
public OMV.Vector3 MoveToTargetTarget { get; set; }
public float MoveToTargetTau { get; set; }
// Used for llSetHoverHeight and maybe vehicle height. Hover Height will override MoveTo target's Z
public override bool PIDHoverActive { set { HoverActive = value; } }
public override float PIDHoverHeight { set { HoverHeight = value; } }
public override PIDHoverType PIDHoverType { set { HoverType = value; } }
public override float PIDHoverTau { set { HoverTau = value; } }
public bool HoverActive { get; set; }
public float HoverHeight { get; set; }
public PIDHoverType HoverType { get; set; }
public float HoverTau { get; set; }
// For RotLookAt
public override OMV.Quaternion APIDTarget { set { return; } }
public override bool APIDActive { set { return; } }
public override float APIDStrength { set { return; } }
public override float APIDDamping { set { return; } }
// The current velocity forward
public virtual float ForwardSpeed
{
get
{
OMV.Vector3 characterOrientedVelocity = RawVelocity * OMV.Quaternion.Inverse(OMV.Quaternion.Normalize(RawOrientation));
return characterOrientedVelocity.X;
}
}
// The forward speed we are trying to achieve (TargetVelocity)
public virtual float TargetVelocitySpeed
{
get
{
OMV.Vector3 characterOrientedVelocity = TargetVelocity * OMV.Quaternion.Inverse(OMV.Quaternion.Normalize(RawOrientation));
return characterOrientedVelocity.X;
}
}
// The user can optionally set the center of mass. The user's setting will override any
// computed center-of-mass (like in linksets).
// Note this is a displacement from the root's coordinates. Zero means use the root prim as center-of-mass.
public OMV.Vector3? UserSetCenterOfMassDisplacement { get; set; }
public OMV.Vector3 LockedLinearAxis { get; set; } // zero means locked. one means free.
public OMV.Vector3 LockedAngularAxis { get; set; } // zero means locked. one means free.
public const float FreeAxis = 1f;
public readonly OMV.Vector3 LockedAxisFree = new OMV.Vector3(FreeAxis, FreeAxis, FreeAxis); // All axis are free
// Enable physical actions. Bullet will keep sleeping non-moving physical objects so
// they need waking up when parameters are changed.
// Called in taint-time!!
public void ActivateIfPhysical(bool forceIt)
{
if (PhysBody.HasPhysicalBody)
{
if (IsPhysical)
{
// Physical objects might need activating
PhysScene.PE.Activate(PhysBody, forceIt);
}
else
{
// Clear the collision cache since we've changed some properties.
PhysScene.PE.ClearCollisionProxyCache(PhysScene.World, PhysBody);
}
}
}
// 'actors' act on the physical object to change or constrain its motion. These can range from
// hovering to complex vehicle motion.
// May be called at non-taint time as this just adds the actor to the action list and the real
// work is done during the simulation step.
// Note that, if the actor is already in the list and we are disabling same, the actor is just left
// in the list disabled.
public delegate BSActor CreateActor();
public void EnableActor(bool enableActor, string actorName, CreateActor creator)
{
lock (PhysicalActors)
{
BSActor theActor;
if (PhysicalActors.TryGetActor(actorName, out theActor))
{
// The actor already exists so just turn it on or off
DetailLog("{0},BSPhysObject.EnableActor,enablingExistingActor,name={1},enable={2}", LocalID, actorName, enableActor);
theActor.Enabled = enableActor;
}
else
{
// The actor does not exist. If it should, create it.
if (enableActor)
{
DetailLog("{0},BSPhysObject.EnableActor,creatingActor,name={1}", LocalID, actorName);
theActor = creator();
PhysicalActors.Add(actorName, theActor);
theActor.Enabled = true;
}
else
{
DetailLog("{0},BSPhysObject.EnableActor,notCreatingActorSinceNotEnabled,name={1}", LocalID, actorName);
}
}
}
}
#region Collisions
// Requested number of milliseconds between collision events. Zero means disabled.
protected int SubscribedEventsMs { get; set; }
// Given subscription, the time that a collision may be passed up
protected int NextCollisionOkTime { get; set; }
// The simulation step that last had a collision
protected long CollidingStep { get; set; }
// The simulation step that last had a collision with the ground
protected long CollidingGroundStep { get; set; }
// The simulation step that last collided with an object
protected long CollidingObjectStep { get; set; }
// The collision flags we think are set in Bullet
protected CollisionFlags CurrentCollisionFlags { get; set; }
// On a collision, check the collider and remember if the last collider was moving
// Used to modify the standing of avatars (avatars on stationary things stand still)
public bool ColliderIsMoving;
// 'true' if the last collider was a volume detect object
public bool ColliderIsVolumeDetect;
// Used by BSCharacter to manage standing (and not slipping)
public bool IsStationary;
// Count of collisions for this object
protected long CollisionAccumulation { get; set; }
public override bool IsColliding {
get { return (CollidingStep == PhysScene.SimulationStep); }
set {
if (value)
CollidingStep = PhysScene.SimulationStep;
else
CollidingStep = BSScene.NotASimulationStep;
}
}
// Complex objects (like linksets) need to know if there is a collision on any part of
// their shape. 'IsColliding' has an existing definition of reporting a collision on
// only this specific prim or component of linksets.
// 'HasSomeCollision' is defined as reporting if there is a collision on any part of
// the complex body that this prim is the root of.
public virtual bool HasSomeCollision
{
get { return IsColliding; }
set { IsColliding = value; }
}
public override bool CollidingGround {
get { return (CollidingGroundStep == PhysScene.SimulationStep); }
set
{
if (value)
CollidingGroundStep = PhysScene.SimulationStep;
else
CollidingGroundStep = BSScene.NotASimulationStep;
}
}
public override bool CollidingObj {
get { return (CollidingObjectStep == PhysScene.SimulationStep); }
set {
if (value)
CollidingObjectStep = PhysScene.SimulationStep;
else
CollidingObjectStep = BSScene.NotASimulationStep;
}
}
// The collisions that have been collected for the next collision reporting (throttled by subscription)
protected CollisionEventUpdate CollisionCollection;
// This is the collision collection last reported to the Simulator.
public CollisionEventUpdate CollisionsLastReported;
// Remember the collisions recorded in the last tick for fancy collision checking
// (like a BSCharacter walking up stairs).
public CollisionEventUpdate CollisionsLastTick;
private long CollisionsLastTickStep = -1;
// The simulation step is telling this object about a collision.
// Return 'true' if a collision was processed and should be sent up.
// Return 'false' if this object is not enabled/subscribed/appropriate for or has already seen this collision.
// Called at taint time from within the Step() function
public delegate bool CollideCall(uint collidingWith, BSPhysObject collidee, OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth);
public virtual bool Collide(uint collidingWith, BSPhysObject collidee,
OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth)
{
bool ret = false;
// The following lines make IsColliding(), CollidingGround() and CollidingObj work
CollidingStep = PhysScene.SimulationStep;
if (collidingWith <= PhysScene.TerrainManager.HighestTerrainID)
{
CollidingGroundStep = PhysScene.SimulationStep;
}
else
{
CollidingObjectStep = PhysScene.SimulationStep;
}
CollisionAccumulation++;
// For movement tests, remember if we are colliding with an object that is moving.
ColliderIsMoving = collidee != null ? (collidee.RawVelocity != OMV.Vector3.Zero) : false;
ColliderIsVolumeDetect = collidee != null ? (collidee.IsVolumeDetect) : false;
// Make a collection of the collisions that happened the last simulation tick.
// This is different than the collection created for sending up to the simulator as it is cleared every tick.
if (CollisionsLastTickStep != PhysScene.SimulationStep)
{
CollisionsLastTick = new CollisionEventUpdate();
CollisionsLastTickStep = PhysScene.SimulationStep;
}
CollisionsLastTick.AddCollider(collidingWith, new ContactPoint(contactPoint, contactNormal, pentrationDepth));
// If someone has subscribed for collision events log the collision so it will be reported up
if (SubscribedEvents()) {
lock (PhysScene.CollisionLock)
{
CollisionCollection.AddCollider(collidingWith, new ContactPoint(contactPoint, contactNormal, pentrationDepth));
}
DetailLog("{0},{1}.Collison.AddCollider,call,with={2},point={3},normal={4},depth={5},colliderMoving={6}",
LocalID, TypeName, collidingWith, contactPoint, contactNormal, pentrationDepth, ColliderIsMoving);
ret = true;
}
return ret;
}
// Send the collected collisions into the simulator.
// Called at taint time from within the Step() function thus no locking problems
// with CollisionCollection and ObjectsWithNoMoreCollisions.
// Called with BSScene.CollisionLock locked to protect the collision lists.
// Return 'true' if there were some actual collisions passed up
public virtual bool SendCollisions()
{
bool ret = true;
// If no collisions this call but there were collisions last call, force the collision
// event to be happen right now so quick collision_end.
bool force = (CollisionCollection.Count == 0 && CollisionsLastReported.Count != 0);
// throttle the collisions to the number of milliseconds specified in the subscription
if (force || (PhysScene.SimulationNowTime >= NextCollisionOkTime))
{
NextCollisionOkTime = PhysScene.SimulationNowTime + SubscribedEventsMs;
// We are called if we previously had collisions. If there are no collisions
// this time, send up one last empty event so OpenSim can sense collision end.
if (CollisionCollection.Count == 0)
{
// If I have no collisions this time, remove me from the list of objects with collisions.
ret = false;
}
DetailLog("{0},{1}.SendCollisionUpdate,call,numCollisions={2}", LocalID, TypeName, CollisionCollection.Count);
base.SendCollisionUpdate(CollisionCollection);
// Remember the collisions from this tick for some collision specific processing.
CollisionsLastReported = CollisionCollection;
// The CollisionCollection instance is passed around in the simulator.
// Make sure we don't have a handle to that one and that a new one is used for next time.
// This fixes an interesting 'gotcha'. If we call CollisionCollection.Clear() here,
// a race condition is created for the other users of this instance.
CollisionCollection = new CollisionEventUpdate();
}
return ret;
}
// Subscribe for collision events.
// Parameter is the millisecond rate the caller wishes collision events to occur.
public override void SubscribeEvents(int ms) {
// DetailLog("{0},{1}.SubscribeEvents,subscribing,ms={2}", LocalID, TypeName, ms);
SubscribedEventsMs = ms;
if (ms > 0)
{
// make sure first collision happens
NextCollisionOkTime = Util.EnvironmentTickCountSubtract(SubscribedEventsMs);
PhysScene.TaintedObject(LocalID, TypeName+".SubscribeEvents", delegate()
{
if (PhysBody.HasPhysicalBody)
CurrentCollisionFlags = PhysScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS);
});
}
else
{
// Subscribing for zero or less is the same as unsubscribing
UnSubscribeEvents();
}
}
public override void UnSubscribeEvents() {
// DetailLog("{0},{1}.UnSubscribeEvents,unsubscribing", LocalID, TypeName);
SubscribedEventsMs = 0;
PhysScene.TaintedObject(LocalID, TypeName+".UnSubscribeEvents", delegate()
{
// Make sure there is a body there because sometimes destruction happens in an un-ideal order.
if (PhysBody.HasPhysicalBody)
CurrentCollisionFlags = PhysScene.PE.RemoveFromCollisionFlags(PhysBody, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS);
});
}
// Return 'true' if the simulator wants collision events
public override bool SubscribedEvents() {
return (SubscribedEventsMs > 0);
}
// Because 'CollisionScore' is called many times while sorting, it should not be recomputed
// each time called. So this is built to be light weight for each collision and to do
// all the processing when the user asks for the info.
public void ComputeCollisionScore()
{
// Scale the collision count by the time since the last collision.
// The "+1" prevents dividing by zero.
long timeAgo = PhysScene.SimulationStep - CollidingStep + 1;
CollisionScore = CollisionAccumulation / timeAgo;
}
public override float CollisionScore { get; set; }
#endregion // Collisions
#region Per Simulation Step actions
public BSActorCollection PhysicalActors;
// When an update to the physical properties happens, this event is fired to let
// different actors to modify the update before it is passed around
public delegate void PreUpdatePropertyAction(ref EntityProperties entprop);
public event PreUpdatePropertyAction OnPreUpdateProperty;
protected void TriggerPreUpdatePropertyAction(ref EntityProperties entprop)
{
PreUpdatePropertyAction actions = OnPreUpdateProperty;
if (actions != null)
actions(ref entprop);
}
#endregion // Per Simulation Step actions
// High performance detailed logging routine used by the physical objects.
protected void DetailLog(string msg, params Object[] args)
{
if (PhysScene.PhysicsLogging.Enabled)
PhysScene.DetailLog(msg, args);
}
}
}
| |
//
// Copyright 2011-2013, Xamarin Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using AddressBook;
using Foundation;
namespace Xamarin.Contacts
{
internal static class ContactHelper
{
internal static AddressType GetAddressType( String label )
{
if(label == ABLabel.Home)
{
return AddressType.Home;
}
if(label == ABLabel.Work)
{
return AddressType.Work;
}
return AddressType.Other;
}
internal static IContact GetContact( ABPerson person )
{
var contact = new Contact( person )
{
DisplayName = person.ToString(),
Prefix = person.Prefix,
FirstName = person.FirstName,
MiddleName = person.MiddleName,
LastName = person.LastName,
Suffix = person.Suffix,
Nickname = person.Nickname,
Notes = (person.Note != null) ? new[] {new Note {Contents = person.Note}} : new Note[0],
};
try
{
contact.Emails =
person.GetEmails()
.Select(
e =>
new Email
{
Address = e.Value,
Type = GetEmailType( e.Label ),
Label = (e.Label != null) ? GetLabel( e.Label ) : GetLabel( ABLabel.Other )
} );
}
catch(Exception)
{
contact.Emails = new List<Email>();
}
try
{
contact.Phones =
person.GetPhones()
.Select(
p =>
new Phone
{
Number = p.Value,
Type = GetPhoneType( p.Label ),
Label = (p.Label != null) ? GetLabel( p.Label ) : GetLabel( ABLabel.Other )
} );
}
catch(Exception)
{
contact.Phones = new List<Phone>();
}
Organization[] orgs;
if(person.Organization != null)
{
orgs = new Organization[1];
orgs[0] = new Organization
{
Name = person.Organization,
ContactTitle = person.JobTitle,
Type = OrganizationType.Work,
Label = GetLabel( ABLabel.Work )
};
}
else
{
orgs = new Organization[0];
}
contact.Organizations = orgs;
contact.InstantMessagingAccounts =
person.GetInstantMessageServices()
.Select(
ima =>
new InstantMessagingAccount()
{
Service = GetImService( (NSString)ima.Value.Dictionary[ABPersonInstantMessageKey.Service] ),
ServiceLabel = ima.Value.ServiceName,
Account = ima.Value.Username
} );
contact.Addresses =
person.GetAllAddresses()
.Select(
a =>
new Address()
{
Type = GetAddressType( a.Label ),
Label = (a.Label != null) ? GetLabel( a.Label ) : GetLabel( ABLabel.Other ),
StreetAddress = a.Value.Street,
City = a.Value.City,
Region = a.Value.State,
Country = a.Value.Country,
PostalCode = a.Value.Zip
} );
try
{
contact.Websites = person.GetUrls().Select( url => new Website {Address = url.Value} );
}
catch(Exception)
{
contact.Websites = new List<Website>();
}
contact.Relationships =
person.GetRelatedNames().Select( p => new Relationship {Name = p.Value, Type = GetRelationType( p.Label )} );
return contact;
}
internal static EmailType GetEmailType( String label )
{
if(label == ABLabel.Home)
{
return EmailType.Home;
}
if(label == ABLabel.Work)
{
return EmailType.Work;
}
return EmailType.Other;
}
internal static InstantMessagingService GetImService( String service )
{
if(service == ABPersonInstantMessageService.Aim)
{
return InstantMessagingService.Aim;
}
if(service == ABPersonInstantMessageService.Icq)
{
return InstantMessagingService.Icq;
}
if(service == ABPersonInstantMessageService.Jabber)
{
return InstantMessagingService.Jabber;
}
if(service == ABPersonInstantMessageService.Msn)
{
return InstantMessagingService.Msn;
}
if(service == ABPersonInstantMessageService.Yahoo)
{
return InstantMessagingService.Yahoo;
}
if(service == ABPersonInstantMessageService.Facebook)
{
return InstantMessagingService.Facebook;
}
if(service == ABPersonInstantMessageService.Skype)
{
return InstantMessagingService.Skype;
}
if(service == ABPersonInstantMessageService.GoogleTalk)
{
return InstantMessagingService.Google;
}
if(service == ABPersonInstantMessageService.GaduGadu)
{
return InstantMessagingService.GaduGadu;
}
if(service == ABPersonInstantMessageService.QQ)
{
return InstantMessagingService.QQ;
}
return InstantMessagingService.Other;
}
internal static String GetLabel( NSString label )
{
return CultureInfo.CurrentCulture.TextInfo.ToTitleCase( ABAddressBook.LocalizedLabel( label ) );
}
internal static PhoneType GetPhoneType( String label )
{
if(label == ABLabel.Home)
{
return PhoneType.Home;
}
if(label == ABLabel.Work)
{
return PhoneType.Work;
}
if(label == ABPersonPhoneLabel.Mobile || label == ABPersonPhoneLabel.iPhone)
{
return PhoneType.Mobile;
}
if(label == ABPersonPhoneLabel.Pager)
{
return PhoneType.Pager;
}
if(label == ABPersonPhoneLabel.HomeFax)
{
return PhoneType.HomeFax;
}
if(label == ABPersonPhoneLabel.WorkFax)
{
return PhoneType.WorkFax;
}
return PhoneType.Other;
}
internal static RelationshipType GetRelationType( String label )
{
if(label == ABPersonRelatedNamesLabel.Spouse || label == ABPersonRelatedNamesLabel.Friend)
{
return RelationshipType.SignificantOther;
}
if(label == ABPersonRelatedNamesLabel.Child)
{
return RelationshipType.Child;
}
return RelationshipType.Other;
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace XenAPI
{
/// <summary>
/// Represents a patch stored on a server
/// First published in XenServer 4.0.
/// </summary>
public partial class Host_patch : XenObject<Host_patch>
{
public Host_patch()
{
}
public Host_patch(string uuid,
string name_label,
string name_description,
string version,
XenRef<Host> host,
bool applied,
DateTime timestamp_applied,
long size,
XenRef<Pool_patch> pool_patch,
Dictionary<string, string> other_config)
{
this.uuid = uuid;
this.name_label = name_label;
this.name_description = name_description;
this.version = version;
this.host = host;
this.applied = applied;
this.timestamp_applied = timestamp_applied;
this.size = size;
this.pool_patch = pool_patch;
this.other_config = other_config;
}
/// <summary>
/// Creates a new Host_patch from a Proxy_Host_patch.
/// </summary>
/// <param name="proxy"></param>
public Host_patch(Proxy_Host_patch proxy)
{
this.UpdateFromProxy(proxy);
}
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given Host_patch.
/// </summary>
public override void UpdateFrom(Host_patch update)
{
uuid = update.uuid;
name_label = update.name_label;
name_description = update.name_description;
version = update.version;
host = update.host;
applied = update.applied;
timestamp_applied = update.timestamp_applied;
size = update.size;
pool_patch = update.pool_patch;
other_config = update.other_config;
}
internal void UpdateFromProxy(Proxy_Host_patch proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
name_label = proxy.name_label == null ? null : (string)proxy.name_label;
name_description = proxy.name_description == null ? null : (string)proxy.name_description;
version = proxy.version == null ? null : (string)proxy.version;
host = proxy.host == null ? null : XenRef<Host>.Create(proxy.host);
applied = (bool)proxy.applied;
timestamp_applied = proxy.timestamp_applied;
size = proxy.size == null ? 0 : long.Parse((string)proxy.size);
pool_patch = proxy.pool_patch == null ? null : XenRef<Pool_patch>.Create(proxy.pool_patch);
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
}
public Proxy_Host_patch ToProxy()
{
Proxy_Host_patch result_ = new Proxy_Host_patch();
result_.uuid = uuid ?? "";
result_.name_label = name_label ?? "";
result_.name_description = name_description ?? "";
result_.version = version ?? "";
result_.host = host ?? "";
result_.applied = applied;
result_.timestamp_applied = timestamp_applied;
result_.size = size.ToString();
result_.pool_patch = pool_patch ?? "";
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
return result_;
}
/// <summary>
/// Creates a new Host_patch from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public Host_patch(Hashtable table) : this()
{
UpdateFrom(table);
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this Host_patch
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("name_label"))
name_label = Marshalling.ParseString(table, "name_label");
if (table.ContainsKey("name_description"))
name_description = Marshalling.ParseString(table, "name_description");
if (table.ContainsKey("version"))
version = Marshalling.ParseString(table, "version");
if (table.ContainsKey("host"))
host = Marshalling.ParseRef<Host>(table, "host");
if (table.ContainsKey("applied"))
applied = Marshalling.ParseBool(table, "applied");
if (table.ContainsKey("timestamp_applied"))
timestamp_applied = Marshalling.ParseDateTime(table, "timestamp_applied");
if (table.ContainsKey("size"))
size = Marshalling.ParseLong(table, "size");
if (table.ContainsKey("pool_patch"))
pool_patch = Marshalling.ParseRef<Pool_patch>(table, "pool_patch");
if (table.ContainsKey("other_config"))
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
}
public bool DeepEquals(Host_patch other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._name_label, other._name_label) &&
Helper.AreEqual2(this._name_description, other._name_description) &&
Helper.AreEqual2(this._version, other._version) &&
Helper.AreEqual2(this._host, other._host) &&
Helper.AreEqual2(this._applied, other._applied) &&
Helper.AreEqual2(this._timestamp_applied, other._timestamp_applied) &&
Helper.AreEqual2(this._size, other._size) &&
Helper.AreEqual2(this._pool_patch, other._pool_patch) &&
Helper.AreEqual2(this._other_config, other._other_config);
}
internal static List<Host_patch> ProxyArrayToObjectList(Proxy_Host_patch[] input)
{
var result = new List<Host_patch>();
foreach (var item in input)
result.Add(new Host_patch(item));
return result;
}
public override string SaveChanges(Session session, string opaqueRef, Host_patch server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
if (!Helper.AreEqual2(_other_config, server._other_config))
{
Host_patch.set_other_config(session, opaqueRef, _other_config);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given host_patch.
/// First published in XenServer 4.0.
/// Deprecated since XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
[Deprecated("XenServer 7.1")]
public static Host_patch get_record(Session session, string _host_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_patch_get_record(session.opaque_ref, _host_patch);
else
return new Host_patch((Proxy_Host_patch)session.proxy.host_patch_get_record(session.opaque_ref, _host_patch ?? "").parse());
}
/// <summary>
/// Get a reference to the host_patch instance with the specified UUID.
/// First published in XenServer 4.0.
/// Deprecated since XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
[Deprecated("XenServer 7.1")]
public static XenRef<Host_patch> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_patch_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<Host_patch>.Create(session.proxy.host_patch_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Get all the host_patch instances with the given label.
/// First published in XenServer 4.0.
/// Deprecated since XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_label">label of object to return</param>
[Deprecated("XenServer 7.1")]
public static List<XenRef<Host_patch>> get_by_name_label(Session session, string _label)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_patch_get_by_name_label(session.opaque_ref, _label);
else
return XenRef<Host_patch>.Create(session.proxy.host_patch_get_by_name_label(session.opaque_ref, _label ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given host_patch.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
public static string get_uuid(Session session, string _host_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_patch_get_uuid(session.opaque_ref, _host_patch);
else
return (string)session.proxy.host_patch_get_uuid(session.opaque_ref, _host_patch ?? "").parse();
}
/// <summary>
/// Get the name/label field of the given host_patch.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
public static string get_name_label(Session session, string _host_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_patch_get_name_label(session.opaque_ref, _host_patch);
else
return (string)session.proxy.host_patch_get_name_label(session.opaque_ref, _host_patch ?? "").parse();
}
/// <summary>
/// Get the name/description field of the given host_patch.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
public static string get_name_description(Session session, string _host_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_patch_get_name_description(session.opaque_ref, _host_patch);
else
return (string)session.proxy.host_patch_get_name_description(session.opaque_ref, _host_patch ?? "").parse();
}
/// <summary>
/// Get the version field of the given host_patch.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
public static string get_version(Session session, string _host_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_patch_get_version(session.opaque_ref, _host_patch);
else
return (string)session.proxy.host_patch_get_version(session.opaque_ref, _host_patch ?? "").parse();
}
/// <summary>
/// Get the host field of the given host_patch.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
public static XenRef<Host> get_host(Session session, string _host_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_patch_get_host(session.opaque_ref, _host_patch);
else
return XenRef<Host>.Create(session.proxy.host_patch_get_host(session.opaque_ref, _host_patch ?? "").parse());
}
/// <summary>
/// Get the applied field of the given host_patch.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
public static bool get_applied(Session session, string _host_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_patch_get_applied(session.opaque_ref, _host_patch);
else
return (bool)session.proxy.host_patch_get_applied(session.opaque_ref, _host_patch ?? "").parse();
}
/// <summary>
/// Get the timestamp_applied field of the given host_patch.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
public static DateTime get_timestamp_applied(Session session, string _host_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_patch_get_timestamp_applied(session.opaque_ref, _host_patch);
else
return session.proxy.host_patch_get_timestamp_applied(session.opaque_ref, _host_patch ?? "").parse();
}
/// <summary>
/// Get the size field of the given host_patch.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
public static long get_size(Session session, string _host_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_patch_get_size(session.opaque_ref, _host_patch);
else
return long.Parse((string)session.proxy.host_patch_get_size(session.opaque_ref, _host_patch ?? "").parse());
}
/// <summary>
/// Get the pool_patch field of the given host_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
public static XenRef<Pool_patch> get_pool_patch(Session session, string _host_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_patch_get_pool_patch(session.opaque_ref, _host_patch);
else
return XenRef<Pool_patch>.Create(session.proxy.host_patch_get_pool_patch(session.opaque_ref, _host_patch ?? "").parse());
}
/// <summary>
/// Get the other_config field of the given host_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
public static Dictionary<string, string> get_other_config(Session session, string _host_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_patch_get_other_config(session.opaque_ref, _host_patch);
else
return Maps.convert_from_proxy_string_string(session.proxy.host_patch_get_other_config(session.opaque_ref, _host_patch ?? "").parse());
}
/// <summary>
/// Set the other_config field of the given host_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
/// <param name="_other_config">New value to set</param>
public static void set_other_config(Session session, string _host_patch, Dictionary<string, string> _other_config)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_patch_set_other_config(session.opaque_ref, _host_patch, _other_config);
else
session.proxy.host_patch_set_other_config(session.opaque_ref, _host_patch ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
/// <summary>
/// Add the given key-value pair to the other_config field of the given host_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_other_config(Session session, string _host_patch, string _key, string _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_patch_add_to_other_config(session.opaque_ref, _host_patch, _key, _value);
else
session.proxy.host_patch_add_to_other_config(session.opaque_ref, _host_patch ?? "", _key ?? "", _value ?? "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the other_config field of the given host_patch. If the key is not in that Map, then do nothing.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_other_config(Session session, string _host_patch, string _key)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_patch_remove_from_other_config(session.opaque_ref, _host_patch, _key);
else
session.proxy.host_patch_remove_from_other_config(session.opaque_ref, _host_patch ?? "", _key ?? "").parse();
}
/// <summary>
/// Destroy the specified host patch, removing it from the disk. This does NOT reverse the patch
/// First published in XenServer 4.0.
/// Deprecated since XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
[Deprecated("XenServer 4.1")]
public static void destroy(Session session, string _host_patch)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_patch_destroy(session.opaque_ref, _host_patch);
else
session.proxy.host_patch_destroy(session.opaque_ref, _host_patch ?? "").parse();
}
/// <summary>
/// Destroy the specified host patch, removing it from the disk. This does NOT reverse the patch
/// First published in XenServer 4.0.
/// Deprecated since XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
[Deprecated("XenServer 4.1")]
public static XenRef<Task> async_destroy(Session session, string _host_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_patch_destroy(session.opaque_ref, _host_patch);
else
return XenRef<Task>.Create(session.proxy.async_host_patch_destroy(session.opaque_ref, _host_patch ?? "").parse());
}
/// <summary>
/// Apply the selected patch and return its output
/// First published in XenServer 4.0.
/// Deprecated since XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
[Deprecated("XenServer 4.1")]
public static string apply(Session session, string _host_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_patch_apply(session.opaque_ref, _host_patch);
else
return (string)session.proxy.host_patch_apply(session.opaque_ref, _host_patch ?? "").parse();
}
/// <summary>
/// Apply the selected patch and return its output
/// First published in XenServer 4.0.
/// Deprecated since XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
[Deprecated("XenServer 4.1")]
public static XenRef<Task> async_apply(Session session, string _host_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_patch_apply(session.opaque_ref, _host_patch);
else
return XenRef<Task>.Create(session.proxy.async_host_patch_apply(session.opaque_ref, _host_patch ?? "").parse());
}
/// <summary>
/// Return a list of all the host_patchs known to the system.
/// First published in XenServer 4.0.
/// Deprecated since XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
[Deprecated("XenServer 7.1")]
public static List<XenRef<Host_patch>> get_all(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_patch_get_all(session.opaque_ref);
else
return XenRef<Host_patch>.Create(session.proxy.host_patch_get_all(session.opaque_ref).parse());
}
/// <summary>
/// Get all the host_patch Records at once, in a single XML RPC call
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<Host_patch>, Host_patch> get_all_records(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_patch_get_all_records(session.opaque_ref);
else
return XenRef<Host_patch>.Create<Proxy_Host_patch>(session.proxy.host_patch_get_all_records(session.opaque_ref).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
/// <summary>
/// a human-readable name
/// </summary>
public virtual string name_label
{
get { return _name_label; }
set
{
if (!Helper.AreEqual(value, _name_label))
{
_name_label = value;
Changed = true;
NotifyPropertyChanged("name_label");
}
}
}
private string _name_label = "";
/// <summary>
/// a notes field containing human-readable description
/// </summary>
public virtual string name_description
{
get { return _name_description; }
set
{
if (!Helper.AreEqual(value, _name_description))
{
_name_description = value;
Changed = true;
NotifyPropertyChanged("name_description");
}
}
}
private string _name_description = "";
/// <summary>
/// Patch version number
/// </summary>
public virtual string version
{
get { return _version; }
set
{
if (!Helper.AreEqual(value, _version))
{
_version = value;
Changed = true;
NotifyPropertyChanged("version");
}
}
}
private string _version = "";
/// <summary>
/// Host the patch relates to
/// </summary>
[JsonConverter(typeof(XenRefConverter<Host>))]
public virtual XenRef<Host> host
{
get { return _host; }
set
{
if (!Helper.AreEqual(value, _host))
{
_host = value;
Changed = true;
NotifyPropertyChanged("host");
}
}
}
private XenRef<Host> _host = new XenRef<Host>(Helper.NullOpaqueRef);
/// <summary>
/// True if the patch has been applied
/// </summary>
public virtual bool applied
{
get { return _applied; }
set
{
if (!Helper.AreEqual(value, _applied))
{
_applied = value;
Changed = true;
NotifyPropertyChanged("applied");
}
}
}
private bool _applied;
/// <summary>
/// Time the patch was applied
/// </summary>
[JsonConverter(typeof(XenDateTimeConverter))]
public virtual DateTime timestamp_applied
{
get { return _timestamp_applied; }
set
{
if (!Helper.AreEqual(value, _timestamp_applied))
{
_timestamp_applied = value;
Changed = true;
NotifyPropertyChanged("timestamp_applied");
}
}
}
private DateTime _timestamp_applied;
/// <summary>
/// Size of the patch
/// </summary>
public virtual long size
{
get { return _size; }
set
{
if (!Helper.AreEqual(value, _size))
{
_size = value;
Changed = true;
NotifyPropertyChanged("size");
}
}
}
private long _size;
/// <summary>
/// The patch applied
/// First published in XenServer 4.1.
/// </summary>
[JsonConverter(typeof(XenRefConverter<Pool_patch>))]
public virtual XenRef<Pool_patch> pool_patch
{
get { return _pool_patch; }
set
{
if (!Helper.AreEqual(value, _pool_patch))
{
_pool_patch = value;
Changed = true;
NotifyPropertyChanged("pool_patch");
}
}
}
private XenRef<Pool_patch> _pool_patch = new XenRef<Pool_patch>(Helper.NullOpaqueRef);
/// <summary>
/// additional configuration
/// First published in XenServer 4.1.
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> other_config
{
get { return _other_config; }
set
{
if (!Helper.AreEqual(value, _other_config))
{
_other_config = value;
Changed = true;
NotifyPropertyChanged("other_config");
}
}
}
private Dictionary<string, string> _other_config = new Dictionary<string, string>() {};
}
}
| |
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
// StringBuilder
// important TODOS:
// TODO 1. Start tags: The ParseXmlElement function has been modified to be called after both the
// angle bracket < and element name have been read, instead of just the < bracket and some valid name character,
// previously the case. This change was made so that elements with optional closing tags could read a new
// element's start tag and decide whether they were required to close. However, there is a question of whether to
// handle this in the parser or lexical analyzer. It is currently handled in the parser - the lexical analyzer still
// recognizes a start tag opener as a '<' + valid name start char; it is the parser that reads the actual name.
// this is correct behavior assuming that the name is a valid html name, because the lexical analyzer should not know anything
// about optional closing tags, etc. UPDATED: 10/13/2004: I am updating this to read the whole start tag of something
// that is not an HTML, treat it as empty, and add it to the tree. That way the converter will know it's there, but
// it will hvae no content. We could also partially recover by trying to look up and match names if they are similar
// TODO 2. Invalid element names: However, it might make sense to give the lexical analyzer the ability to identify
// a valid html element name and not return something as a start tag otherwise. For example, if we type <good>, should
// the lexical analyzer return that it has found the start of an element when this is not the case in HTML? But this will
// require implementing a lookahead token in the lexical analyzer so that it can treat an invalid element name as text. One
// character of lookahead will not be enough.
// TODO 3. Attributes: The attribute recovery is poor when reading attribute values in quotes - if no closing quotes are found,
// the lexical analyzer just keeps reading and if it eventually reaches the end of file, it would have just skipped everything.
// There are a couple of ways to deal with this: 1) stop reading attributes when we encounter a '>' character - this doesn't allow
// the '>' character to be used in attribute values, but it can still be used as an entity. 2) Maintain a HTML-specific list
// of attributes and their values that each html element can take, and if we find correct attribute namesand values for an
// element we use them regardless of the quotes, this way we could just ignore something invalid. One more option: 3) Read ahead
// in the quoted value and if we find an end of file, we can return to where we were and process as text. However this requires
// a lot of lookahead and a resettable reader.
// TODO 4: elements with optional closing tags: For elements with optional closing tags, we always close the element if we find
// that one of it's ancestors has closed. This condition may be too broad and we should develop a better heuristic. We should also
// improve the heuristics for closing certain elements when the next element starts
// TODO 5. Nesting: Support for unbalanced nesting, e.g. <b> <i> </b> </i>: this is not presently supported. To support it we may need
// to maintain two xml elements, one the element that represents what has already been read and another represents what we are presently reading.
// Then if we encounter an unbalanced nesting tag we could close the element that was supposed to close, save the current element
// and store it in the list of already-read content, and then open a new element to which all tags that are currently open
// can be applied. Is there a better way to do this? Should we do it at all?
// TODO 6. Elements with optional starting tags: there are 4 such elements in the HTML 4 specification - html, tbody, body and head.
// The current recovery doesn;t do anything for any of these elements except the html element, because it's not critical - head
// and body elementscan be contained within html element, and tbody is contained within table. To extend this for XHTML
// extensions, and to recover in case other elements are missing start tags, we would need to insert an extra recursive call
// to ParseXmlElement for the missing start tag. It is suggested to do this by giving ParseXmlElement an argument that specifies
// a name to use. If this argument is null, it assumes its name is the next token from the lexical analyzer and continues
// exactly as it does now. However, if the argument contains a valid html element name then it takes that value as its name
// and continues as before. This way, if the next token is the element that should actually be its child, it will see
// the name in the next step and initiate a recursive call. We would also need to add some logic in the loop for when a start tag
// is found - if the start tag is not compatible with current context and indicates that a start tag has been missed, then we
// can initiate the extra recursive call and give it the name of the missed start tag. The issues are when to insert this logic,
// and if we want to support it over multiple missing start tags. If we insert it at the time a start tag is read in element
// text, then we can support only one missing start tag, since the extra call will read the next start tag and make a recursive
// call without checking the context. This is a conceptual problem, and the check should be made just before a recursive call,
// with the choice being whether we should supply an element name as argument, or leave it as NULL and read from the input
// TODO 7: Context: Is it appropriate to keep track of context here? For example, should we only expect td, tr elements when
// reading a table and ignore them otherwise? This may be too much of a load on the parser, I think it's better if the converter
// deals with it
namespace HtmlToXamlDemo
{
/// <summary>
/// HtmlParser class accepts a string of possibly badly formed Html, parses it and returns a string
/// of well-formed Html that is as close to the original string in content as possible
/// </summary>
internal class HtmlParser
{
// ---------------------------------------------------------------------
//
// Constructors
//
// ---------------------------------------------------------------------
#region Constructors
/// <summary>
/// Constructor. Initializes the _htmlLexicalAnalayzer element with the given input string
/// </summary>
/// <param name="inputString">
/// string to parsed into well-formed Html
/// </param>
private HtmlParser(string inputString)
{
// Create an output xml document
_document = new XmlDocument();
// initialize open tag stack
_openedElements = new Stack<XmlElement>();
_pendingInlineElements = new Stack<XmlElement>();
// initialize lexical analyzer
_htmlLexicalAnalyzer = new HtmlLexicalAnalyzer(inputString);
// get first token from input, expecting text
_htmlLexicalAnalyzer.GetNextContentToken();
}
#endregion Constructors
// ---------------------------------------------------------------------
//
// Internal Methods
//
// ---------------------------------------------------------------------
#region Internal Methods
/// <summary>
/// Instantiates an HtmlParser element and calls the parsing function on the given input string
/// </summary>
/// <param name="htmlString">
/// Input string of pssibly badly-formed Html to be parsed into well-formed Html
/// </param>
/// <returns>
/// XmlElement rep
/// </returns>
internal static XmlElement ParseHtml(string htmlString)
{
var htmlParser = new HtmlParser(htmlString);
var htmlRootElement = htmlParser.ParseHtmlContent();
return htmlRootElement;
}
// .....................................................................
//
// Html Header on Clipboard
//
// .....................................................................
// Html header structure.
// Version:1.0
// StartHTML:000000000
// EndHTML:000000000
// StartFragment:000000000
// EndFragment:000000000
// StartSelection:000000000
// EndSelection:000000000
internal const string HtmlHeader =
"Version:1.0\r\nStartHTML:{0:D10}\r\nEndHTML:{1:D10}\r\nStartFragment:{2:D10}\r\nEndFragment:{3:D10}\r\nStartSelection:{4:D10}\r\nEndSelection:{5:D10}\r\n";
internal const string HtmlStartFragmentComment = "<!--StartFragment-->";
internal const string HtmlEndFragmentComment = "<!--EndFragment-->";
/// <summary>
/// Extracts Html string from clipboard data by parsing header information in htmlDataString
/// </summary>
/// <param name="htmlDataString">
/// String representing Html clipboard data. This includes Html header
/// </param>
/// <returns>
/// String containing only the Html data part of htmlDataString, without header
/// </returns>
internal static string ExtractHtmlFromClipboardData(string htmlDataString)
{
var startHtmlIndex = htmlDataString.IndexOf("StartHTML:", StringComparison.Ordinal);
if (startHtmlIndex < 0)
{
return "ERROR: Urecognized html header";
}
// TODO: We assume that indices represented by strictly 10 zeros ("0123456789".Length),
// which could be wrong assumption. We need to implement more flrxible parsing here
startHtmlIndex =
int.Parse(htmlDataString.Substring(startHtmlIndex + "StartHTML:".Length, "0123456789".Length));
if (startHtmlIndex < 0 || startHtmlIndex > htmlDataString.Length)
{
return "ERROR: Urecognized html header";
}
var endHtmlIndex = htmlDataString.IndexOf("EndHTML:", StringComparison.Ordinal);
if (endHtmlIndex < 0)
{
return "ERROR: Urecognized html header";
}
// TODO: We assume that indices represented by strictly 10 zeros ("0123456789".Length),
// which could be wrong assumption. We need to implement more flrxible parsing here
endHtmlIndex = int.Parse(htmlDataString.Substring(endHtmlIndex + "EndHTML:".Length, "0123456789".Length));
if (endHtmlIndex > htmlDataString.Length)
{
endHtmlIndex = htmlDataString.Length;
}
return htmlDataString.Substring(startHtmlIndex, endHtmlIndex - startHtmlIndex);
}
/// <summary>
/// Adds Xhtml header information to Html data string so that it can be placed on clipboard
/// </summary>
/// <param name="htmlString">
/// Html string to be placed on clipboard with appropriate header
/// </param>
/// <returns>
/// String wrapping htmlString with appropriate Html header
/// </returns>
internal static string AddHtmlClipboardHeader(string htmlString)
{
var stringBuilder = new StringBuilder();
// each of 6 numbers is represented by "{0:D10}" in the format string
// must actually occupy 10 digit positions ("0123456789")
var startHtml = HtmlHeader.Length + 6*("0123456789".Length - "{0:D10}".Length);
var endHtml = startHtml + htmlString.Length;
var startFragment = htmlString.IndexOf(HtmlStartFragmentComment, 0, StringComparison.Ordinal);
if (startFragment >= 0)
{
startFragment = startHtml + startFragment + HtmlStartFragmentComment.Length;
}
else
{
startFragment = startHtml;
}
var endFragment = htmlString.IndexOf(HtmlEndFragmentComment, 0, StringComparison.Ordinal);
if (endFragment >= 0)
{
endFragment = startHtml + endFragment;
}
else
{
endFragment = endHtml;
}
// Create HTML clipboard header string
stringBuilder.AppendFormat(HtmlHeader, startHtml, endHtml, startFragment, endFragment, startFragment,
endFragment);
// Append HTML body.
stringBuilder.Append(htmlString);
return stringBuilder.ToString();
}
#endregion Internal Methods
// ---------------------------------------------------------------------
//
// Private methods
//
// ---------------------------------------------------------------------
#region Private Methods
private void InvariantAssert(bool condition, string message)
{
if (!condition)
{
throw new Exception("Assertion error: " + message);
}
}
/// <summary>
/// Parses the stream of html tokens starting
/// from the name of top-level element.
/// Returns XmlElement representing the top-level
/// html element
/// </summary>
private XmlElement ParseHtmlContent()
{
// Create artificial root elelemt to be able to group multiple top-level elements
// We create "html" element which may be a duplicate of real HTML element, which is ok, as HtmlConverter will swallow it painlessly..
var htmlRootElement = _document.CreateElement("html", XhtmlNamespace);
OpenStructuringElement(htmlRootElement);
while (_htmlLexicalAnalyzer.NextTokenType != HtmlTokenType.Eof)
{
if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.OpeningTagStart)
{
_htmlLexicalAnalyzer.GetNextTagToken();
if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.Name)
{
var htmlElementName = _htmlLexicalAnalyzer.NextToken.ToLower();
_htmlLexicalAnalyzer.GetNextTagToken();
// Create an element
var htmlElement = _document.CreateElement(htmlElementName, XhtmlNamespace);
// Parse element attributes
ParseAttributes(htmlElement);
if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.EmptyTagEnd ||
HtmlSchema.IsEmptyElement(htmlElementName))
{
// It is an element without content (because of explicit slash or based on implicit knowledge aboout html)
AddEmptyElement(htmlElement);
}
else if (HtmlSchema.IsInlineElement(htmlElementName))
{
// Elements known as formatting are pushed to some special
// pending stack, which allows them to be transferred
// over block tags - by doing this we convert
// overlapping tags into normal heirarchical element structure.
OpenInlineElement(htmlElement);
}
else if (HtmlSchema.IsBlockElement(htmlElementName) ||
HtmlSchema.IsKnownOpenableElement(htmlElementName))
{
// This includes no-scope elements
OpenStructuringElement(htmlElement);
}
}
}
else if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.ClosingTagStart)
{
_htmlLexicalAnalyzer.GetNextTagToken();
if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.Name)
{
var htmlElementName = _htmlLexicalAnalyzer.NextToken.ToLower();
// Skip the name token. Assume that the following token is end of tag,
// but do not check this. If it is not true, we simply ignore one token
// - this is our recovery from bad xml in this case.
_htmlLexicalAnalyzer.GetNextTagToken();
CloseElement(htmlElementName);
}
}
else if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.Text)
{
AddTextContent(_htmlLexicalAnalyzer.NextToken);
}
else if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.Comment)
{
AddComment(_htmlLexicalAnalyzer.NextToken);
}
_htmlLexicalAnalyzer.GetNextContentToken();
}
// Get rid of the artificial root element
if (htmlRootElement.FirstChild is XmlElement &&
htmlRootElement.FirstChild == htmlRootElement.LastChild &&
htmlRootElement.FirstChild.LocalName.ToLower() == "html")
{
htmlRootElement = (XmlElement) htmlRootElement.FirstChild;
}
return htmlRootElement;
}
private XmlElement CreateElementCopy(XmlElement htmlElement)
{
var htmlElementCopy = _document.CreateElement(htmlElement.LocalName, XhtmlNamespace);
for (var i = 0; i < htmlElement.Attributes.Count; i++)
{
var attribute = htmlElement.Attributes[i];
htmlElementCopy.SetAttribute(attribute.Name, attribute.Value);
}
return htmlElementCopy;
}
private void AddEmptyElement(XmlElement htmlEmptyElement)
{
InvariantAssert(_openedElements.Count > 0,
"AddEmptyElement: Stack of opened elements cannot be empty, as we have at least one artificial root element");
var htmlParent = _openedElements.Peek();
htmlParent.AppendChild(htmlEmptyElement);
}
private void OpenInlineElement(XmlElement htmlInlineElement)
{
_pendingInlineElements.Push(htmlInlineElement);
}
// Opens structurig element such as Div or Table etc.
private void OpenStructuringElement(XmlElement htmlElement)
{
// Close all pending inline elements
// All block elements are considered as delimiters for inline elements
// which forces all inline elements to be closed and re-opened in the following
// structural element (if any).
// By doing that we guarantee that all inline elements appear only within most nested blocks
if (HtmlSchema.IsBlockElement(htmlElement.LocalName))
{
while (_openedElements.Count > 0 && HtmlSchema.IsInlineElement(_openedElements.Peek().LocalName))
{
var htmlInlineElement = _openedElements.Pop();
InvariantAssert(_openedElements.Count > 0,
"OpenStructuringElement: stack of opened elements cannot become empty here");
_pendingInlineElements.Push(CreateElementCopy(htmlInlineElement));
}
}
// Add this block element to its parent
if (_openedElements.Count > 0)
{
var htmlParent = _openedElements.Peek();
// Check some known block elements for auto-closing (LI and P)
if (HtmlSchema.ClosesOnNextElementStart(htmlParent.LocalName, htmlElement.LocalName))
{
_openedElements.Pop();
htmlParent = _openedElements.Count > 0 ? _openedElements.Peek() : null;
}
// NOTE:
// Actually we never expect null - it would mean two top-level P or LI (without a parent).
// In such weird case we will loose all paragraphs except the first one...
htmlParent?.AppendChild(htmlElement);
}
// Push it onto a stack
_openedElements.Push(htmlElement);
}
private bool IsElementOpened(string htmlElementName) => _openedElements.Any(openedElement => openedElement.LocalName == htmlElementName);
private void CloseElement(string htmlElementName)
{
// Check if the element is opened and already added to the parent
InvariantAssert(_openedElements.Count > 0,
"CloseElement: Stack of opened elements cannot be empty, as we have at least one artificial root element");
// Check if the element is opened and still waiting to be added to the parent
if (_pendingInlineElements.Count > 0 && _pendingInlineElements.Peek().LocalName == htmlElementName)
{
// Closing an empty inline element.
// Note that HtmlConverter will skip empty inlines, but for completeness we keep them here on parser level.
var htmlInlineElement = _pendingInlineElements.Pop();
InvariantAssert(_openedElements.Count > 0,
"CloseElement: Stack of opened elements cannot be empty, as we have at least one artificial root element");
var htmlParent = _openedElements.Peek();
htmlParent.AppendChild(htmlInlineElement);
}
else if (IsElementOpened(htmlElementName))
{
while (_openedElements.Count > 1) // we never pop the last element - the artificial root
{
// Close all unbalanced elements.
var htmlOpenedElement = _openedElements.Pop();
if (htmlOpenedElement.LocalName == htmlElementName)
{
return;
}
if (HtmlSchema.IsInlineElement(htmlOpenedElement.LocalName))
{
// Unbalances Inlines will be transfered to the next element content
_pendingInlineElements.Push(CreateElementCopy(htmlOpenedElement));
}
}
}
// If element was not opened, we simply ignore the unbalanced closing tag
}
private void AddTextContent(string textContent)
{
OpenPendingInlineElements();
InvariantAssert(_openedElements.Count > 0,
"AddTextContent: Stack of opened elements cannot be empty, as we have at least one artificial root element");
var htmlParent = _openedElements.Peek();
var textNode = _document.CreateTextNode(textContent);
htmlParent.AppendChild(textNode);
}
private void AddComment(string comment)
{
OpenPendingInlineElements();
InvariantAssert(_openedElements.Count > 0,
"AddComment: Stack of opened elements cannot be empty, as we have at least one artificial root element");
var htmlParent = _openedElements.Peek();
var xmlComment = _document.CreateComment(comment);
htmlParent.AppendChild(xmlComment);
}
// Moves all inline elements pending for opening to actual document
// and adds them to current open stack.
private void OpenPendingInlineElements()
{
if (_pendingInlineElements.Count > 0)
{
var htmlInlineElement = _pendingInlineElements.Pop();
OpenPendingInlineElements();
InvariantAssert(_openedElements.Count > 0,
"OpenPendingInlineElements: Stack of opened elements cannot be empty, as we have at least one artificial root element");
var htmlParent = _openedElements.Peek();
htmlParent.AppendChild(htmlInlineElement);
_openedElements.Push(htmlInlineElement);
}
}
private void ParseAttributes(XmlElement xmlElement)
{
while (_htmlLexicalAnalyzer.NextTokenType != HtmlTokenType.Eof && //
_htmlLexicalAnalyzer.NextTokenType != HtmlTokenType.TagEnd && //
_htmlLexicalAnalyzer.NextTokenType != HtmlTokenType.EmptyTagEnd)
{
// read next attribute (name=value)
if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.Name)
{
var attributeName = _htmlLexicalAnalyzer.NextToken;
_htmlLexicalAnalyzer.GetNextEqualSignToken();
_htmlLexicalAnalyzer.GetNextAtomToken();
var attributeValue = _htmlLexicalAnalyzer.NextToken;
xmlElement.SetAttribute(attributeName, attributeValue);
}
_htmlLexicalAnalyzer.GetNextTagToken();
}
}
#endregion Private Methods
// ---------------------------------------------------------------------
//
// Private Fields
//
// ---------------------------------------------------------------------
#region Private Fields
internal const string XhtmlNamespace = "http://www.w3.org/1999/xhtml";
private readonly HtmlLexicalAnalyzer _htmlLexicalAnalyzer;
// document from which all elements are created
private readonly XmlDocument _document;
// stack for open elements
private readonly Stack<XmlElement> _openedElements;
private readonly Stack<XmlElement> _pendingInlineElements;
#endregion Private Fields
}
}
| |
namespace NEventStore.Contrib.Persistence.SqlDialects
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Transactions;
using NEventStore.Logging;
using NEventStore.Persistence;
public class PagedEnumerationCollection : IEnumerable<IDataRecord>, IEnumerator<IDataRecord>
{
private static readonly ILog Logger = LogFactory.BuildLogger(typeof (PagedEnumerationCollection));
private readonly IDbCommand _command;
private readonly IContribSqlDialect _dialect;
private readonly IEnumerable<IDisposable> _disposable = new IDisposable[] {};
private readonly NextPageDelegate _nextpage;
private readonly int _pageSize;
private readonly TransactionScope _scope;
private IDataRecord _current;
private bool _disposed;
private int _position;
private IDataReader _reader;
public PagedEnumerationCollection(
TransactionScope scope,
IContribSqlDialect dialect,
IDbCommand command,
NextPageDelegate nextpage,
int pageSize,
params IDisposable[] disposable)
{
this._scope = scope;
this._dialect = dialect;
this._command = command;
this._nextpage = nextpage;
this._pageSize = pageSize;
this._disposable = disposable ?? this._disposable;
}
public virtual IEnumerator<IDataRecord> GetEnumerator()
{
if (this._disposed)
{
throw new ObjectDisposedException(Messages.ObjectAlreadyDisposed);
}
return this;
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
bool IEnumerator.MoveNext()
{
if (this._disposed)
{
throw new ObjectDisposedException(Messages.ObjectAlreadyDisposed);
}
if (this.MoveToNextRecord())
{
return true;
}
Logger.Verbose(Messages.QueryCompleted);
return false;
}
public virtual void Reset()
{
throw new NotSupportedException("Forward-only readers.");
}
public virtual IDataRecord Current
{
get
{
if (this._disposed)
{
throw new ObjectDisposedException(Messages.ObjectAlreadyDisposed);
}
return this._current = this._reader;
}
}
object IEnumerator.Current
{
get { return ((IEnumerator<IDataRecord>) this).Current; }
}
protected virtual void Dispose(bool disposing)
{
if (!disposing || this._disposed)
{
return;
}
this._disposed = true;
this._position = 0;
this._current = null;
if (this._reader != null)
{
this._reader.Dispose();
}
this._reader = null;
if (this._command != null)
{
this._command.Dispose();
}
// queries do not modify state and thus calling Complete() on a so-called 'failed' query only
// allows any outer transaction scope to decide the fate of the transaction
if (this._scope != null)
{
this._scope.Complete(); // caller will dispose scope.
}
foreach (var dispose in this._disposable)
{
dispose.Dispose();
}
}
private bool MoveToNextRecord()
{
if (this._pageSize > 0 && this._position >= this._pageSize)
{
this._command.SetParameter(this._dialect.Skip, this._position);
this._nextpage(this._command, this._current);
}
this._reader = this._reader ?? this.OpenNextPage();
if (this._reader.Read())
{
return this.IncrementPosition();
}
if (!this.PagingEnabled())
{
return false;
}
if (!this.PageCompletelyEnumerated())
{
return false;
}
Logger.Verbose(Messages.EnumeratedRowCount, this._position);
this._reader.Dispose();
this._reader = this.OpenNextPage();
if (this._reader.Read())
{
return this.IncrementPosition();
}
return false;
}
private bool IncrementPosition()
{
this._position++;
return true;
}
private bool PagingEnabled()
{
return this._pageSize > 0;
}
private bool PageCompletelyEnumerated()
{
return this._position > 0 && 0 == this._position%this._pageSize;
}
private IDataReader OpenNextPage()
{
try
{
return this._command.ExecuteReader();
}
catch (Exception e)
{
Logger.Debug(Messages.EnumerationThrewException, e.GetType());
throw new StorageUnavailableException(e.Message, e);
}
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace SelfLoadSoftDelete.Business.ERCLevel
{
/// <summary>
/// H12Level111111 (editable child object).<br/>
/// This is a generated base class of <see cref="H12Level111111"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="H11Level111111Coll"/> collection.
/// </remarks>
[Serializable]
public partial class H12Level111111 : BusinessBase<H12Level111111>
{
#region Static Fields
private static int _lastID;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Level_1_1_1_1_1_1_ID"/> property.
/// </summary>
public static readonly PropertyInfo<int> Level_1_1_1_1_1_1_IDProperty = RegisterProperty<int>(p => p.Level_1_1_1_1_1_1_ID, "Level_1_1_1_1_1_1 ID");
/// <summary>
/// Gets the Level_1_1_1_1_1_1 ID.
/// </summary>
/// <value>The Level_1_1_1_1_1_1 ID.</value>
public int Level_1_1_1_1_1_1_ID
{
get { return GetProperty(Level_1_1_1_1_1_1_IDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="Level_1_1_1_1_1_1_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Level_1_1_1_1_1_1_NameProperty = RegisterProperty<string>(p => p.Level_1_1_1_1_1_1_Name, "Level_1_1_1_1_1_1 Name");
/// <summary>
/// Gets or sets the Level_1_1_1_1_1_1 Name.
/// </summary>
/// <value>The Level_1_1_1_1_1_1 Name.</value>
public string Level_1_1_1_1_1_1_Name
{
get { return GetProperty(Level_1_1_1_1_1_1_NameProperty); }
set { SetProperty(Level_1_1_1_1_1_1_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="H12Level111111"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="H12Level111111"/> object.</returns>
internal static H12Level111111 NewH12Level111111()
{
return DataPortal.CreateChild<H12Level111111>();
}
/// <summary>
/// Factory method. Loads a <see cref="H12Level111111"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="H12Level111111"/> object.</returns>
internal static H12Level111111 GetH12Level111111(SafeDataReader dr)
{
H12Level111111 obj = new H12Level111111();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
obj.MarkOld();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="H12Level111111"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
private H12Level111111()
{
// Prevent direct creation
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="H12Level111111"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
LoadProperty(Level_1_1_1_1_1_1_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID));
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="H12Level111111"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Level_1_1_1_1_1_1_IDProperty, dr.GetInt32("Level_1_1_1_1_1_1_ID"));
LoadProperty(Level_1_1_1_1_1_1_NameProperty, dr.GetString("Level_1_1_1_1_1_1_Name"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="H12Level111111"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(H10Level11111 parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddH12Level111111", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_ID", parent.Level_1_1_1_1_1_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_1_ID", ReadProperty(Level_1_1_1_1_1_1_IDProperty)).Direction = ParameterDirection.Output;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_1_Name", ReadProperty(Level_1_1_1_1_1_1_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
LoadProperty(Level_1_1_1_1_1_1_IDProperty, (int) cmd.Parameters["@Level_1_1_1_1_1_1_ID"].Value);
}
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="H12Level111111"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("UpdateH12Level111111", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_1_ID", ReadProperty(Level_1_1_1_1_1_1_IDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_1_Name", ReadProperty(Level_1_1_1_1_1_1_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
}
}
}
/// <summary>
/// Self deletes the <see cref="H12Level111111"/> object from database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("DeleteH12Level111111", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_1_ID", ReadProperty(Level_1_1_1_1_1_1_IDProperty)).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
}
}
#endregion
#region Pseudo Events
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
namespace System.Workflow.ComponentModel.Compiler
{
using System;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Workflow.ComponentModel.Design;
using System.Workflow.ComponentModel.Serialization;
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public class DependencyObjectValidator : Validator
{
public override ValidationErrorCollection Validate(ValidationManager manager, object obj)
{
if (manager == null)
throw new ArgumentNullException("manager");
if (obj == null)
throw new ArgumentNullException("obj");
ValidationErrorCollection validationErrors = base.Validate(manager, obj);
DependencyObject dependencyObject = obj as DependencyObject;
if (dependencyObject == null)
throw new ArgumentException(SR.GetString(SR.Error_UnexpectedArgumentType, typeof(DependencyObject).FullName), "obj");
ArrayList allProperties = new ArrayList();
// Validate all the settable dependency properties
// attached property can not be found through the call to DependencyProperty.FromType()
foreach (DependencyProperty prop in DependencyProperty.FromType(dependencyObject.GetType()))
{
// This property is attached to some other object. We should not validate it here
// because the context is wrong.
if (!prop.IsAttached)
allProperties.Add(prop);
}
//
foreach (DependencyProperty prop in dependencyObject.MetaDependencyProperties)
{
if (prop.IsAttached)
{
if (obj.GetType().GetProperty(prop.Name, BindingFlags.Public | BindingFlags.Instance) == null)
allProperties.Add(prop);
}
}
foreach (DependencyProperty prop in allProperties)
{
object[] validationVisibilityAtrributes = prop.DefaultMetadata.GetAttributes(typeof(ValidationOptionAttribute));
ValidationOption validationVisibility = (validationVisibilityAtrributes.Length > 0) ? ((ValidationOptionAttribute)validationVisibilityAtrributes[0]).ValidationOption : ValidationOption.Optional;
if (validationVisibility != ValidationOption.None)
validationErrors.AddRange(ValidateDependencyProperty(dependencyObject, prop, manager));
}
return validationErrors;
}
private ValidationErrorCollection ValidateDependencyProperty(DependencyObject dependencyObject, DependencyProperty dependencyProperty, ValidationManager manager)
{
ValidationErrorCollection errors = new ValidationErrorCollection();
Attribute[] validationVisibilityAtrributes = dependencyProperty.DefaultMetadata.GetAttributes(typeof(ValidationOptionAttribute));
ValidationOption validationVisibility = (validationVisibilityAtrributes.Length > 0) ? ((ValidationOptionAttribute)validationVisibilityAtrributes[0]).ValidationOption : ValidationOption.Optional;
Activity activity = manager.Context[typeof(Activity)] as Activity;
if (activity == null)
throw new InvalidOperationException(SR.GetString(SR.Error_ContextStackItemMissing, typeof(Activity).FullName));
PropertyValidationContext propertyValidationContext = new PropertyValidationContext(activity, dependencyProperty);
manager.Context.Push(propertyValidationContext);
try
{
if (dependencyProperty.DefaultMetadata.DefaultValue != null)
{
if (!dependencyProperty.PropertyType.IsValueType &&
dependencyProperty.PropertyType != typeof(string))
{
errors.Add(new ValidationError(SR.GetString(SR.Error_PropertyDefaultIsReference, dependencyProperty.Name), ErrorNumbers.Error_PropertyDefaultIsReference));
}
else if (!dependencyProperty.PropertyType.IsAssignableFrom(dependencyProperty.DefaultMetadata.DefaultValue.GetType()))
{
errors.Add(new ValidationError(SR.GetString(SR.Error_PropertyDefaultTypeMismatch, dependencyProperty.Name, dependencyProperty.PropertyType.FullName, dependencyProperty.DefaultMetadata.DefaultValue.GetType().FullName), ErrorNumbers.Error_PropertyDefaultTypeMismatch));
}
}
// If an event is of type Bind, GetBinding will return the Bind object.
object propValue = null;
if (dependencyObject.IsBindingSet(dependencyProperty))
propValue = dependencyObject.GetBinding(dependencyProperty);
else if (!dependencyProperty.IsEvent)
propValue = dependencyObject.GetValue(dependencyProperty);
if (propValue == null || propValue == dependencyProperty.DefaultMetadata.DefaultValue)
{
if (dependencyProperty.IsEvent)
{
// Is this added through "+=" in InitializeComponent? If so, the value should be in the instance properties hashtable
// If none of these, its value is stored in UserData at design time.
propValue = dependencyObject.GetHandler(dependencyProperty);
if (propValue == null)
propValue = WorkflowMarkupSerializationHelpers.GetEventHandlerName(dependencyObject, dependencyProperty.Name);
if (propValue is string && !string.IsNullOrEmpty((string)propValue))
errors.AddRange(ValidateEvent(activity, dependencyProperty, propValue, manager));
}
else
{
// Maybe this is an instance property.
propValue = dependencyObject.GetValue(dependencyProperty);
}
}
// Be careful before changing this. This is the (P || C) validation validation
// i.e. validate properties being set only if Parent is set or
// a child exists.
bool checkNotSet = (activity.Parent != null) || ((activity is CompositeActivity) && (((CompositeActivity)activity).EnabledActivities.Count != 0));
if (validationVisibility == ValidationOption.Required &&
(propValue == null || (propValue is string && string.IsNullOrEmpty((string)propValue))) &&
(dependencyProperty.DefaultMetadata.IsMetaProperty) &&
checkNotSet)
{
errors.Add(ValidationError.GetNotSetValidationError(GetFullPropertyName(manager)));
}
else if (propValue != null)
{
if (propValue is IList)
{
PropertyValidationContext childContext = new PropertyValidationContext(propValue, null, String.Empty);
manager.Context.Push(childContext);
try
{
foreach (object child in (IList)propValue)
errors.AddRange(ValidationHelpers.ValidateObject(manager, child));
}
finally
{
System.Diagnostics.Debug.Assert(manager.Context.Current == childContext, "Unwinding contextStack: the item that is about to be popped is not the one we pushed.");
manager.Context.Pop();
}
}
else if (dependencyProperty.ValidatorType != null)
{
Validator validator = null;
try
{
validator = Activator.CreateInstance(dependencyProperty.ValidatorType) as Validator;
if (validator == null)
errors.Add(new ValidationError(SR.GetString(SR.Error_CreateValidator, dependencyProperty.ValidatorType.FullName), ErrorNumbers.Error_CreateValidator));
else
errors.AddRange(validator.Validate(manager, propValue));
}
catch
{
errors.Add(new ValidationError(SR.GetString(SR.Error_CreateValidator, dependencyProperty.ValidatorType.FullName), ErrorNumbers.Error_CreateValidator));
}
}
else
{
errors.AddRange(ValidationHelpers.ValidateObject(manager, propValue));
}
}
}
finally
{
System.Diagnostics.Debug.Assert(manager.Context.Current == propertyValidationContext, "Unwinding contextStack: the item that is about to be popped is not the one we pushed.");
manager.Context.Pop();
}
return errors;
}
private ValidationErrorCollection ValidateEvent(Activity activity, DependencyProperty dependencyProperty, object propValue, ValidationManager manager)
{
ValidationErrorCollection validationErrors = new ValidationErrorCollection();
if (propValue is string && !string.IsNullOrEmpty((string)propValue))
{
bool handlerExists = false;
Type objType = null;
Activity rootActivity = Helpers.GetRootActivity(activity);
Activity enclosingActivity = Helpers.GetEnclosingActivity(activity);
string typeName = rootActivity.GetValue(WorkflowMarkupSerializer.XClassProperty) as string;
if (rootActivity == enclosingActivity && !string.IsNullOrEmpty(typeName))
{
ITypeProvider typeProvider = manager.GetService(typeof(ITypeProvider)) as ITypeProvider;
if (typeProvider == null)
throw new InvalidOperationException(SR.GetString(SR.General_MissingService, typeof(ITypeProvider).FullName));
objType = typeProvider.GetType(typeName);
}
else
objType = enclosingActivity.GetType();
if (objType != null)
{
MethodInfo invokeMethod = dependencyProperty.PropertyType.GetMethod("Invoke");
if (invokeMethod != null)
{
// resolve the method
List<Type> paramTypes = new List<Type>();
foreach (ParameterInfo paramInfo in invokeMethod.GetParameters())
paramTypes.Add(paramInfo.ParameterType);
MethodInfo methodInfo = Helpers.GetMethodExactMatch(objType, propValue as string, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy, null, paramTypes.ToArray(), null);
if (methodInfo != null && TypeProvider.IsAssignable(invokeMethod.ReturnType, methodInfo.ReturnType))
handlerExists = true;
}
}
if (!handlerExists)
{
ValidationError error = new ValidationError(SR.GetString(SR.Error_CantResolveEventHandler, dependencyProperty.Name, propValue as string), ErrorNumbers.Error_CantResolveEventHandler);
error.PropertyName = GetFullPropertyName(manager);
validationErrors.Add(error);
}
}
return validationErrors;
}
}
}
| |
using System;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using TIKSN.Finance.ForeignExchange.Bank;
using TIKSN.Globalization;
using TIKSN.Time;
using Xunit;
namespace TIKSN.Finance.ForeignExchange.Tests
{
public class SwissNationalBankTests
{
private readonly ICurrencyFactory _currencyFactory;
private readonly ITimeProvider _timeProvider;
public SwissNationalBankTests()
{
var services = new ServiceCollection();
_ = services.AddMemoryCache();
_ = services.AddSingleton<ICurrencyFactory, CurrencyFactory>();
_ = services.AddSingleton<IRegionFactory, RegionFactory>();
_ = services.AddSingleton<ITimeProvider, TimeProvider>();
var serviceProvider = services.BuildServiceProvider();
this._currencyFactory = serviceProvider.GetRequiredService<ICurrencyFactory>();
this._timeProvider = serviceProvider.GetRequiredService<ITimeProvider>();
}
[Fact]
public async Task Calculation001Async()
{
var Bank = new SwissNationalBank(this._currencyFactory, this._timeProvider);
var AtTheMoment = DateTimeOffset.Now;
foreach (var pair in await Bank.GetCurrencyPairsAsync(AtTheMoment, default).ConfigureAwait(true))
{
var Before = new Money(pair.BaseCurrency, 100m);
var After = await Bank.ConvertCurrencyAsync(Before, pair.CounterCurrency, AtTheMoment, default).ConfigureAwait(true);
var rate = await Bank.GetExchangeRateAsync(pair, AtTheMoment, default).ConfigureAwait(true);
Assert.True(After.Amount == Before.Amount * rate);
Assert.Equal(pair.CounterCurrency, After.Currency);
}
}
[Fact]
public async Task ConvertCurrency001Async()
{
var Bank = new SwissNationalBank(this._currencyFactory, this._timeProvider);
var AtTheMoment = DateTimeOffset.Now;
foreach (var Pair in await Bank.GetCurrencyPairsAsync(AtTheMoment, default).ConfigureAwait(true))
{
var Before = new Money(Pair.BaseCurrency, 100m);
var After = await Bank.ConvertCurrencyAsync(Before, Pair.CounterCurrency, AtTheMoment, default).ConfigureAwait(true);
Assert.True(After.Amount > decimal.Zero);
Assert.Equal(Pair.CounterCurrency, After.Currency);
}
}
[Fact]
public async Task ConvertCurrency002Async()
{
var Bank = new SwissNationalBank(this._currencyFactory, this._timeProvider);
var moment = DateTimeOffset.Now.AddMinutes(10d);
foreach (var pair in await Bank.GetCurrencyPairsAsync(DateTimeOffset.Now, default).ConfigureAwait(true))
{
var Before = new Money(pair.BaseCurrency, 100m);
_ = await
Assert.ThrowsAsync<ArgumentException>(
async () =>
await Bank.ConvertCurrencyAsync(Before, pair.CounterCurrency, moment, default).ConfigureAwait(true)).ConfigureAwait(true);
}
}
[Fact]
public async Task ConvertCurrency004Async()
{
var Bank = new SwissNationalBank(this._currencyFactory, this._timeProvider);
var moment = DateTimeOffset.Now.AddDays(-10d);
foreach (var pair in await Bank.GetCurrencyPairsAsync(DateTimeOffset.Now, default).ConfigureAwait(true))
{
var Before = new Money(pair.BaseCurrency, 100m);
_ = await
Assert.ThrowsAsync<ArgumentException>(
async () =>
await Bank.ConvertCurrencyAsync(Before, pair.CounterCurrency, moment, default).ConfigureAwait(true)).ConfigureAwait(true);
}
}
[Fact]
public async Task CounterCurrency003Async()
{
var Bank = new SwissNationalBank(this._currencyFactory, this._timeProvider);
var AO = new RegionInfo("AO");
var BW = new RegionInfo("BW");
var AOA = new CurrencyInfo(AO);
var BWP = new CurrencyInfo(BW);
var Before = new Money(AOA, 100m);
_ = await Assert.ThrowsAsync<ArgumentException>(
async () =>
await Bank.ConvertCurrencyAsync(Before, BWP, DateTimeOffset.Now, default).ConfigureAwait(true)).ConfigureAwait(true);
}
[Fact]
public async Task GetCurrencyPairs001Async()
{
var Bank = new SwissNationalBank(this._currencyFactory, this._timeProvider);
var moment = DateTimeOffset.Now.AddMinutes(10d);
_ = await Assert.ThrowsAsync<ArgumentException>(async () => await Bank.GetCurrencyPairsAsync(moment, default).ConfigureAwait(true)).ConfigureAwait(true);
}
[Fact]
public async Task GetCurrencyPairs002Async()
{
var Bank = new SwissNationalBank(this._currencyFactory, this._timeProvider);
var Pairs = await Bank.GetCurrencyPairsAsync(DateTimeOffset.Now, default).ConfigureAwait(true);
var DistinctPairs = Pairs.Distinct();
Assert.True(Pairs.Count() == DistinctPairs.Count());
}
[Fact]
public async Task GetCurrencyPairs003Async()
{
var Bank = new SwissNationalBank(this._currencyFactory, this._timeProvider);
var moment = DateTimeOffset.Now.AddDays(-10d);
_ = await Assert.ThrowsAsync<ArgumentException>(async () => await Bank.GetCurrencyPairsAsync(moment, default).ConfigureAwait(true)).ConfigureAwait(true);
}
[Fact]
public async Task GetCurrencyPairs004Async()
{
var Bank = new SwissNationalBank(this._currencyFactory, this._timeProvider);
var Pairs = await Bank.GetCurrencyPairsAsync(DateTimeOffset.Now, default).ConfigureAwait(true);
foreach (var pair in Pairs)
{
var reversed = new CurrencyPair(pair.CounterCurrency, pair.BaseCurrency);
Assert.Contains(Pairs, P => P == reversed);
}
}
[Fact]
public async Task GetCurrencyPairs005Async()
{
var Bank = new SwissNationalBank(this._currencyFactory, this._timeProvider);
var Pairs = await Bank.GetCurrencyPairsAsync(DateTimeOffset.Now, default).ConfigureAwait(true);
Assert.Contains(Pairs, P => P.ToString() == "EUR/CHF");
Assert.Contains(Pairs, P => P.ToString() == "USD/CHF");
Assert.Contains(Pairs, P => P.ToString() == "JPY/CHF");
Assert.Contains(Pairs, P => P.ToString() == "GBP/CHF");
Assert.Contains(Pairs, P => P.ToString() == "CHF/EUR");
Assert.Contains(Pairs, P => P.ToString() == "CHF/USD");
Assert.Contains(Pairs, P => P.ToString() == "CHF/JPY");
Assert.Contains(Pairs, P => P.ToString() == "CHF/GBP");
Assert.Equal(8, Pairs.Count());
}
[Fact]
public async Task GetExchangeRate001Async()
{
var Bank = new SwissNationalBank(this._currencyFactory, this._timeProvider);
var AtTheMoment = DateTimeOffset.Now;
foreach (var Pair in await Bank.GetCurrencyPairsAsync(AtTheMoment, default).ConfigureAwait(true))
{
var rate = await Bank.GetExchangeRateAsync(Pair, AtTheMoment, default).ConfigureAwait(true);
Assert.True(rate > decimal.Zero);
}
}
[Fact]
public async Task GetExchangeRate002Async()
{
var Bank = new SwissNationalBank(this._currencyFactory, this._timeProvider);
var moment = DateTimeOffset.Now.AddMinutes(10d);
foreach (var pair in await Bank.GetCurrencyPairsAsync(DateTimeOffset.Now, default).ConfigureAwait(true))
{
_ = await Assert.ThrowsAsync<ArgumentException>(async () => await Bank.GetExchangeRateAsync(pair, moment, default).ConfigureAwait(true)).ConfigureAwait(true);
}
}
[Fact]
public async Task GetExchangeRate003Async()
{
var Bank = new SwissNationalBank(this._currencyFactory, this._timeProvider);
var AO = new RegionInfo("AO");
var BW = new RegionInfo("BW");
var AOA = new CurrencyInfo(AO);
var BWP = new CurrencyInfo(BW);
var Pair = new CurrencyPair(AOA, BWP);
_ = await Assert.ThrowsAsync<ArgumentException>(async () => await Bank.GetExchangeRateAsync(Pair, DateTimeOffset.Now, default).ConfigureAwait(true)).ConfigureAwait(true);
}
[Fact]
public async Task GetExchangeRate004Async()
{
var Bank = new SwissNationalBank(this._currencyFactory, this._timeProvider);
var moment = DateTimeOffset.Now.AddDays(-10d);
foreach (var pair in await Bank.GetCurrencyPairsAsync(DateTimeOffset.Now, default).ConfigureAwait(true))
{
_ = await Assert.ThrowsAsync<ArgumentException>(async () => await Bank.GetExchangeRateAsync(pair, moment, default).ConfigureAwait(true)).ConfigureAwait(true);
}
}
}
}
| |
#nullable enable annotations
using System.Threading.Tasks;
using Content.Client.Items.Components;
using Content.Server.Hands.Components;
using Content.Server.Interaction;
using Content.Shared.Hands.Components;
using Content.Shared.Interaction;
using Content.Shared.Item;
using Content.Shared.Weapons.Melee;
using NUnit.Framework;
using Robust.Shared.Containers;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Map;
using Robust.Shared.Maths;
using Robust.Shared.Reflection;
using ItemComponent = Content.Server.Clothing.Components.ItemComponent;
namespace Content.IntegrationTests.Tests.Interaction.Click
{
[TestFixture]
[TestOf(typeof(InteractionSystem))]
public sealed class InteractionSystemTests : ContentIntegrationTest
{
const string PROTOTYPES = @"
- type: entity
id: DummyDebugWall
components:
- type: Physics
bodyType: Dynamic
- type: Fixtures
fixtures:
- shape:
!type:PhysShapeAabb
bounds: ""-0.25,-0.25,0.25,0.25""
layer:
- MobMask
mask:
- MobMask
";
[Test]
public async Task InteractionTest()
{
var server = StartServer(new ServerContentIntegrationOption
{
ContentBeforeIoC = () =>
{
IoCManager.Resolve<IEntitySystemManager>().LoadExtraSystemType<TestInteractionSystem>();
}
});
await server.WaitIdleAsync();
var sEntities = server.ResolveDependency<IEntityManager>();
var mapManager = server.ResolveDependency<IMapManager>();
var mapId = MapId.Nullspace;
var coords = MapCoordinates.Nullspace;
server.Assert(() =>
{
mapId = mapManager.CreateMap();
coords = new MapCoordinates(Vector2.Zero, mapId);
});
await server.WaitIdleAsync();
EntityUid user = default;
EntityUid target = default;
EntityUid item = default;
server.Assert(() =>
{
user = sEntities.SpawnEntity(null, coords);
user.EnsureComponent<HandsComponent>().AddHand("hand", HandLocation.Left);
target = sEntities.SpawnEntity(null, coords);
item = sEntities.SpawnEntity(null, coords);
item.EnsureComponent<ItemComponent>();
});
await server.WaitRunTicks(1);
var entitySystemManager = server.ResolveDependency<IEntitySystemManager>();
Assert.That(entitySystemManager.TryGetEntitySystem<InteractionSystem>(out var interactionSystem));
Assert.That(entitySystemManager.TryGetEntitySystem<TestInteractionSystem>(out var testInteractionSystem));
var attack = false;
var interactUsing = false;
var interactHand = false;
server.Assert(() =>
{
testInteractionSystem.AttackEvent = (_, _, ev) => { Assert.That(ev.Target, Is.EqualTo(target)); attack = true; };
testInteractionSystem.InteractUsingEvent = (ev) => { Assert.That(ev.Target, Is.EqualTo(target)); interactUsing = true; };
testInteractionSystem.InteractHandEvent = (ev) => { Assert.That(ev.Target, Is.EqualTo(target)); interactHand = true; };
interactionSystem.DoAttack(user, sEntities.GetComponent<TransformComponent>(target).Coordinates, false, target);
interactionSystem.UserInteraction(user, sEntities.GetComponent<TransformComponent>(target).Coordinates, target);
Assert.That(attack);
Assert.That(interactUsing, Is.False);
Assert.That(interactHand);
Assert.That(sEntities.TryGetComponent<HandsComponent>(user, out var hands));
Assert.That(hands.PutInHand(sEntities.GetComponent<SharedItemComponent>(item)));
interactionSystem.UserInteraction(user, sEntities.GetComponent<TransformComponent>(target).Coordinates, target);
Assert.That(interactUsing);
});
await server.WaitIdleAsync();
}
[Test]
public async Task InteractionObstructionTest()
{
var server = StartServer(new ServerContentIntegrationOption
{
ContentBeforeIoC = () =>
{
IoCManager.Resolve<IEntitySystemManager>().LoadExtraSystemType<TestInteractionSystem>();
},
ExtraPrototypes = PROTOTYPES
});
await server.WaitIdleAsync();
var sEntities = server.ResolveDependency<IEntityManager>();
var mapManager = server.ResolveDependency<IMapManager>();
var mapId = MapId.Nullspace;
var coords = MapCoordinates.Nullspace;
server.Assert(() =>
{
mapId = mapManager.CreateMap();
coords = new MapCoordinates(Vector2.Zero, mapId);
});
await server.WaitIdleAsync();
EntityUid user = default;
EntityUid target = default;
EntityUid item = default;
EntityUid wall = default;
server.Assert(() =>
{
user = sEntities.SpawnEntity(null, coords);
user.EnsureComponent<HandsComponent>().AddHand("hand", HandLocation.Left);
target = sEntities.SpawnEntity(null, new MapCoordinates((1.9f, 0), mapId));
item = sEntities.SpawnEntity(null, coords);
item.EnsureComponent<ItemComponent>();
wall = sEntities.SpawnEntity("DummyDebugWall", new MapCoordinates((1, 0), sEntities.GetComponent<TransformComponent>(user).MapID));
});
await server.WaitRunTicks(1);
var entitySystemManager = server.ResolveDependency<IEntitySystemManager>();
Assert.That(entitySystemManager.TryGetEntitySystem<InteractionSystem>(out var interactionSystem));
Assert.That(entitySystemManager.TryGetEntitySystem<TestInteractionSystem>(out var testInteractionSystem));
var attack = false;
var interactUsing = false;
var interactHand = false;
server.Assert(() =>
{
testInteractionSystem.AttackEvent = (_, _, ev) => { Assert.That(ev.Target, Is.EqualTo(target)); attack = true; };
testInteractionSystem.InteractUsingEvent = (ev) => { Assert.That(ev.Target, Is.EqualTo(target)); interactUsing = true; };
testInteractionSystem.InteractHandEvent = (ev) => { Assert.That(ev.Target, Is.EqualTo(target)); interactHand = true; };
interactionSystem.DoAttack(user, sEntities.GetComponent<TransformComponent>(target).Coordinates, false, target);
interactionSystem.UserInteraction(user, sEntities.GetComponent<TransformComponent>(target).Coordinates, target);
Assert.That(attack, Is.False);
Assert.That(interactUsing, Is.False);
Assert.That(interactHand, Is.False);
Assert.That(sEntities.TryGetComponent<HandsComponent?>(user, out var hands));
Assert.That(hands.PutInHand(sEntities.GetComponent<SharedItemComponent>(item)));
interactionSystem.UserInteraction(user, sEntities.GetComponent<TransformComponent>(target).Coordinates, target);
Assert.That(interactUsing, Is.False);
});
await server.WaitIdleAsync();
}
[Test]
public async Task InteractionInRangeTest()
{
var server = StartServer(new ServerContentIntegrationOption
{
ContentBeforeIoC = () =>
{
IoCManager.Resolve<IEntitySystemManager>().LoadExtraSystemType<TestInteractionSystem>();
}
});
await server.WaitIdleAsync();
var sEntities = server.ResolveDependency<IEntityManager>();
var mapManager = server.ResolveDependency<IMapManager>();
var mapId = MapId.Nullspace;
var coords = MapCoordinates.Nullspace;
server.Assert(() =>
{
mapId = mapManager.CreateMap();
coords = new MapCoordinates(Vector2.Zero, mapId);
});
await server.WaitIdleAsync();
EntityUid user = default;
EntityUid target = default;
EntityUid item = default;
server.Assert(() =>
{
user = sEntities.SpawnEntity(null, coords);
user.EnsureComponent<HandsComponent>().AddHand("hand", HandLocation.Left);
target = sEntities.SpawnEntity(null, new MapCoordinates((InteractionSystem.InteractionRange - 0.1f, 0), mapId));
item = sEntities.SpawnEntity(null, coords);
item.EnsureComponent<ItemComponent>();
});
await server.WaitRunTicks(1);
var entitySystemManager = server.ResolveDependency<IEntitySystemManager>();
Assert.That(entitySystemManager.TryGetEntitySystem<InteractionSystem>(out var interactionSystem));
Assert.That(entitySystemManager.TryGetEntitySystem<TestInteractionSystem>(out var testInteractionSystem));
var attack = false;
var interactUsing = false;
var interactHand = false;
server.Assert(() =>
{
testInteractionSystem.AttackEvent = (_, _, ev) => { Assert.That(ev.Target, Is.EqualTo(target)); attack = true; };
testInteractionSystem.InteractUsingEvent = (ev) => { Assert.That(ev.Target, Is.EqualTo(target)); interactUsing = true; };
testInteractionSystem.InteractHandEvent = (ev) => { Assert.That(ev.Target, Is.EqualTo(target)); interactHand = true; };
interactionSystem.DoAttack(user, sEntities.GetComponent<TransformComponent>(target).Coordinates, false, target);
interactionSystem.UserInteraction(user, sEntities.GetComponent<TransformComponent>(target).Coordinates, target);
Assert.That(attack);
Assert.That(interactUsing, Is.False);
Assert.That(interactHand);
Assert.That(sEntities.TryGetComponent<HandsComponent>(user, out var hands));
Assert.That(hands.PutInHand(sEntities.GetComponent<SharedItemComponent>(item)));
interactionSystem.UserInteraction(user, sEntities.GetComponent<TransformComponent>(target).Coordinates, target);
Assert.That(interactUsing);
});
await server.WaitIdleAsync();
}
[Test]
public async Task InteractionOutOfRangeTest()
{
var server = StartServer(new ServerContentIntegrationOption
{
ContentBeforeIoC = () =>
{
IoCManager.Resolve<IEntitySystemManager>().LoadExtraSystemType<TestInteractionSystem>();
}
});
await server.WaitIdleAsync();
var sEntities = server.ResolveDependency<IEntityManager>();
var mapManager = server.ResolveDependency<IMapManager>();
var mapId = MapId.Nullspace;
var coords = MapCoordinates.Nullspace;
server.Assert(() =>
{
mapId = mapManager.CreateMap();
coords = new MapCoordinates(Vector2.Zero, mapId);
});
await server.WaitIdleAsync();
EntityUid user = default;
EntityUid target = default;
EntityUid item = default;
server.Assert(() =>
{
user = sEntities.SpawnEntity(null, coords);
user.EnsureComponent<HandsComponent>().AddHand("hand", HandLocation.Left);
target = sEntities.SpawnEntity(null, new MapCoordinates((SharedInteractionSystem.InteractionRange + 0.01f, 0), mapId));
item = sEntities.SpawnEntity(null, coords);
item.EnsureComponent<ItemComponent>();
});
await server.WaitRunTicks(1);
var entitySystemManager = server.ResolveDependency<IEntitySystemManager>();
Assert.That(entitySystemManager.TryGetEntitySystem<InteractionSystem>(out var interactionSystem));
Assert.That(entitySystemManager.TryGetEntitySystem<TestInteractionSystem>(out var testInteractionSystem));
var attack = false;
var interactUsing = false;
var interactHand = false;
server.Assert(() =>
{
testInteractionSystem.AttackEvent = (_, _, ev) => { Assert.That(ev.Target, Is.EqualTo(target)); attack = true; };
testInteractionSystem.InteractUsingEvent = (ev) => { Assert.That(ev.Target, Is.EqualTo(target)); interactUsing = true; };
testInteractionSystem.InteractHandEvent = (ev) => { Assert.That(ev.Target, Is.EqualTo(target)); interactHand = true; };
interactionSystem.DoAttack(user, sEntities.GetComponent<TransformComponent>(target).Coordinates, false, target);
interactionSystem.UserInteraction(user, sEntities.GetComponent<TransformComponent>(target).Coordinates, target);
Assert.That(attack, Is.False);
Assert.That(interactUsing, Is.False);
Assert.That(interactHand, Is.False);
Assert.That(sEntities.TryGetComponent<HandsComponent?>(user, out var hands));
Assert.That(hands.PutInHand(sEntities.GetComponent<SharedItemComponent>(item)));
interactionSystem.UserInteraction(user, sEntities.GetComponent<TransformComponent>(target).Coordinates, target);
Assert.That(interactUsing, Is.False);
});
await server.WaitIdleAsync();
}
[Test]
public async Task InsideContainerInteractionBlockTest()
{
var server = StartServer(new ServerContentIntegrationOption
{
ContentBeforeIoC = () =>
{
IoCManager.Resolve<IEntitySystemManager>().LoadExtraSystemType<TestInteractionSystem>();
},
FailureLogLevel = Robust.Shared.Log.LogLevel.Error
});
await server.WaitIdleAsync();
var sEntities = server.ResolveDependency<IEntityManager>();
var mapManager = server.ResolveDependency<IMapManager>();
var mapId = MapId.Nullspace;
var coords = MapCoordinates.Nullspace;
server.Assert(() =>
{
mapId = mapManager.CreateMap();
coords = new MapCoordinates(Vector2.Zero, mapId);
});
await server.WaitIdleAsync();
EntityUid user = default;
EntityUid target = default;
EntityUid item = default;
EntityUid containerEntity = default;
IContainer container = null;
server.Assert(() =>
{
user = sEntities.SpawnEntity(null, coords);
user.EnsureComponent<HandsComponent>().AddHand("hand", HandLocation.Left);
target = sEntities.SpawnEntity(null, coords);
item = sEntities.SpawnEntity(null, coords);
item.EnsureComponent<ItemComponent>();
containerEntity = sEntities.SpawnEntity(null, coords);
container = containerEntity.EnsureContainer<Container>("InteractionTestContainer");
});
await server.WaitRunTicks(1);
var entitySystemManager = server.ResolveDependency<IEntitySystemManager>();
Assert.That(entitySystemManager.TryGetEntitySystem<InteractionSystem>(out var interactionSystem));
Assert.That(entitySystemManager.TryGetEntitySystem<TestInteractionSystem>(out var testInteractionSystem));
await server.WaitIdleAsync();
var attack = false;
var interactUsing = false;
var interactHand = false;
server.Assert(() =>
{
Assert.That(container.Insert(user));
Assert.That(sEntities.GetComponent<TransformComponent>(user).Parent.Owner, Is.EqualTo(containerEntity));
testInteractionSystem.AttackEvent = (_, _, ev) => { Assert.That(ev.Target, Is.EqualTo(containerEntity)); attack = true; };
testInteractionSystem.InteractUsingEvent = (ev) => { Assert.That(ev.Target, Is.EqualTo(containerEntity)); interactUsing = true; };
testInteractionSystem.InteractHandEvent = (ev) => { Assert.That(ev.Target, Is.EqualTo(containerEntity)); interactHand = true; };
interactionSystem.DoAttack(user, sEntities.GetComponent<TransformComponent>(target).Coordinates, false, target);
interactionSystem.UserInteraction(user, sEntities.GetComponent<TransformComponent>(target).Coordinates, target);
Assert.That(attack, Is.False);
Assert.That(interactUsing, Is.False);
Assert.That(interactHand, Is.False);
interactionSystem.DoAttack(user, sEntities.GetComponent<TransformComponent>(containerEntity).Coordinates, false, containerEntity);
interactionSystem.UserInteraction(user, sEntities.GetComponent<TransformComponent>(containerEntity).Coordinates, containerEntity);
Assert.That(attack);
Assert.That(interactUsing, Is.False);
Assert.That(interactHand);
Assert.That(sEntities.TryGetComponent<HandsComponent?>(user, out var hands));
Assert.That(hands.PutInHand(sEntities.GetComponent<SharedItemComponent>(item)));
interactionSystem.UserInteraction(user, sEntities.GetComponent<TransformComponent>(target).Coordinates, target);
Assert.That(interactUsing, Is.False);
interactionSystem.UserInteraction(user, sEntities.GetComponent<TransformComponent>(containerEntity).Coordinates, containerEntity);
Assert.That(interactUsing, Is.True);
});
await server.WaitIdleAsync();
}
[Reflect(false)]
private sealed class TestInteractionSystem : EntitySystem
{
public ComponentEventHandler<HandsComponent, ClickAttackEvent>? AttackEvent;
public EntityEventHandler<InteractUsingEvent>? InteractUsingEvent;
public EntityEventHandler<InteractHandEvent>? InteractHandEvent;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<HandsComponent, ClickAttackEvent>((u, c, e) => AttackEvent?.Invoke(u, c, e));
SubscribeLocalEvent<InteractUsingEvent>((e) => InteractUsingEvent?.Invoke(e));
SubscribeLocalEvent<InteractHandEvent>((e) => InteractHandEvent?.Invoke(e));
}
}
}
}
| |
using Lucene.Net.Index;
using Lucene.Net.Support;
using Lucene.Net.Util;
using System;
namespace Lucene.Net.Search
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// A base class for all collectors that return a <see cref="TopDocs"/> output. This
/// collector allows easy extension by providing a single constructor which
/// accepts a <see cref="Util.PriorityQueue{T}"/> as well as protected members for that
/// priority queue and a counter of the number of total hits.
/// <para/>
/// Extending classes can override any of the methods to provide their own
/// implementation, as well as avoid the use of the priority queue entirely by
/// passing null to <see cref="TopDocsCollector(Util.PriorityQueue{T})"/>. In that case
/// however, you might want to consider overriding all methods, in order to avoid
/// a <see cref="NullReferenceException"/>.
/// </summary>
public abstract class TopDocsCollector<T> : ICollector, ITopDocsCollector where T : ScoreDoc
{
/// <summary>
/// This is used in case <see cref="GetTopDocs()"/> is called with illegal parameters, or there
/// simply aren't (enough) results.
/// </summary>
protected static readonly TopDocs EMPTY_TOPDOCS = new TopDocs(0, Arrays.Empty<ScoreDoc>(), float.NaN);
/// <summary>
/// The priority queue which holds the top documents. Note that different
/// implementations of <see cref="PriorityQueue{T}"/> give different meaning to 'top documents'.
/// <see cref="HitQueue"/> for example aggregates the top scoring documents, while other priority queue
/// implementations may hold documents sorted by other criteria.
/// </summary>
protected PriorityQueue<T> m_pq;
/// <summary>
/// The total number of documents that the collector encountered. </summary>
protected int m_totalHits;
/// <summary>
/// Sole constructor.
/// </summary>
protected TopDocsCollector(PriorityQueue<T> pq)
{
this.m_pq = pq;
}
/// <summary>
/// Populates the results array with the <see cref="ScoreDoc"/> instances. This can be
/// overridden in case a different <see cref="ScoreDoc"/> type should be returned.
/// </summary>
protected virtual void PopulateResults(ScoreDoc[] results, int howMany)
{
for (int i = howMany - 1; i >= 0; i--)
{
results[i] = m_pq.Pop();
}
}
/// <summary>
/// Returns a <see cref="TopDocs"/> instance containing the given results. If
/// <paramref name="results"/> is <c>null</c> it means there are no results to return,
/// either because there were 0 calls to <see cref="Collect(int)"/> or because the arguments to
/// <see cref="TopDocs"/> were invalid.
/// </summary>
protected virtual TopDocs NewTopDocs(ScoreDoc[] results, int start)
{
return results == null ? EMPTY_TOPDOCS : new TopDocs(m_totalHits, results);
}
/// <summary>
/// The total number of documents that matched this query. </summary>
public virtual int TotalHits
{
get => m_totalHits;
internal set => m_totalHits = value;
}
/// <summary>
/// The number of valid priority queue entries
/// </summary>
protected virtual int TopDocsCount =>
// In case pq was populated with sentinel values, there might be less
// results than pq.size(). Therefore return all results until either
// pq.size() or totalHits.
m_totalHits < m_pq.Count ? m_totalHits : m_pq.Count;
/// <summary>
/// Returns the top docs that were collected by this collector. </summary>
public virtual TopDocs GetTopDocs()
{
// In case pq was populated with sentinel values, there might be less
// results than pq.size(). Therefore return all results until either
// pq.size() or totalHits.
return GetTopDocs(0, TopDocsCount);
}
/// <summary>
/// Returns the documents in the rage [<paramref name="start"/> .. pq.Count) that were collected
/// by this collector. Note that if <paramref name="start"/> >= pq.Count, an empty <see cref="TopDocs"/> is
/// returned.
/// <para/>
/// This method is convenient to call if the application always asks for the
/// last results, starting from the last 'page'.
/// <para/>
/// <b>NOTE:</b> you cannot call this method more than once for each search
/// execution. If you need to call it more than once, passing each time a
/// different <paramref name="start"/>, you should call <see cref="GetTopDocs()"/> and work
/// with the returned <see cref="TopDocs"/> object, which will contain all the
/// results this search execution collected.
/// </summary>
public virtual TopDocs GetTopDocs(int start)
{
// In case pq was populated with sentinel values, there might be less
// results than pq.Count. Therefore return all results until either
// pq.Count or totalHits.
return GetTopDocs(start, TopDocsCount);
}
/// <summary>
/// Returns the documents in the rage [<paramref name="start"/> .. <paramref name="start"/>+<paramref name="howMany"/>) that were
/// collected by this collector. Note that if <paramref name="start"/> >= pq.Count, an empty
/// <see cref="TopDocs"/> is returned, and if pq.Count - <paramref name="start"/> < <paramref name="howMany"/>, then only the
/// available documents in [<paramref name="start"/> .. pq.Count) are returned.
/// <para/>
/// This method is useful to call in case pagination of search results is
/// allowed by the search application, as well as it attempts to optimize the
/// memory used by allocating only as much as requested by <paramref name="howMany"/>.
/// <para/>
/// <b>NOTE:</b> you cannot call this method more than once for each search
/// execution. If you need to call it more than once, passing each time a
/// different range, you should call <see cref="GetTopDocs()"/> and work with the
/// returned <see cref="TopDocs"/> object, which will contain all the results this
/// search execution collected.
/// </summary>
public virtual TopDocs GetTopDocs(int start, int howMany)
{
// In case pq was populated with sentinel values, there might be less
// results than pq.Count. Therefore return all results until either
// pq.Count or totalHits.
int size = TopDocsCount;
// Don't bother to throw an exception, just return an empty TopDocs in case
// the parameters are invalid or out of range.
// TODO: shouldn't we throw IAE if apps give bad params here so they dont
// have sneaky silent bugs?
if (start < 0 || start >= size || howMany <= 0)
{
return NewTopDocs(null, start);
}
// We know that start < pqsize, so just fix howMany.
howMany = Math.Min(size - start, howMany);
ScoreDoc[] results = new ScoreDoc[howMany];
// pq's pop() returns the 'least' element in the queue, therefore need
// to discard the first ones, until we reach the requested range.
// Note that this loop will usually not be executed, since the common usage
// should be that the caller asks for the last howMany results. However it's
// needed here for completeness.
for (int i = m_pq.Count - start - howMany; i > 0; i--)
{
m_pq.Pop();
}
// Get the requested results from pq.
PopulateResults(results, howMany);
return NewTopDocs(results, start);
}
// LUCENENET specific - we need to implement these here, since our abstract base class
// is now an interface.
/// <summary>
/// Called before successive calls to <see cref="Collect(int)"/>. Implementations
/// that need the score of the current document (passed-in to
/// <see cref="Collect(int)"/>), should save the passed-in <see cref="Scorer"/> and call
/// <see cref="Scorer.GetScore()"/> when needed.
/// </summary>
public abstract void SetScorer(Scorer scorer);
/// <summary>
/// Called once for every document matching a query, with the unbased document
/// number.
/// <para/>Note: The collection of the current segment can be terminated by throwing
/// a <see cref="CollectionTerminatedException"/>. In this case, the last docs of the
/// current <see cref="AtomicReaderContext"/> will be skipped and <see cref="IndexSearcher"/>
/// will swallow the exception and continue collection with the next leaf.
/// <para/>
/// Note: this is called in an inner search loop. For good search performance,
/// implementations of this method should not call <see cref="IndexSearcher.Doc(int)"/> or
/// <see cref="Lucene.Net.Index.IndexReader.Document(int)"/> on every hit.
/// Doing so can slow searches by an order of magnitude or more.
/// </summary>
public abstract void Collect(int doc);
/// <summary>
/// Called before collecting from each <see cref="AtomicReaderContext"/>. All doc ids in
/// <see cref="Collect(int)"/> will correspond to <see cref="Index.IndexReaderContext.Reader"/>.
/// <para/>
/// Add <see cref="AtomicReaderContext.DocBase"/> to the current <see cref="Index.IndexReaderContext.Reader"/>'s
/// internal document id to re-base ids in <see cref="Collect(int)"/>.
/// </summary>
/// <param name="context">Next atomic reader context </param>
public abstract void SetNextReader(AtomicReaderContext context);
/// <summary>
/// Return <c>true</c> if this collector does not
/// require the matching docIDs to be delivered in int sort
/// order (smallest to largest) to <see cref="Collect"/>.
///
/// <para> Most Lucene Query implementations will visit
/// matching docIDs in order. However, some queries
/// (currently limited to certain cases of <see cref="BooleanQuery"/>)
/// can achieve faster searching if the
/// <see cref="ICollector"/> allows them to deliver the
/// docIDs out of order.</para>
///
/// <para> Many collectors don't mind getting docIDs out of
/// order, so it's important to return <c>true</c>
/// here.</para>
/// </summary>
public abstract bool AcceptsDocsOutOfOrder { get; }
}
/// <summary>
/// LUCENENET specific interface used to reference <see cref="TopDocsCollector{T}"/>
/// without referencing its generic type.
/// </summary>
public interface ITopDocsCollector : ICollector
{
// From TopDocsCollector<T>
/// <summary>
/// The total number of documents that matched this query. </summary>
int TotalHits { get; }
/// <summary>
/// Returns the top docs that were collected by this collector. </summary>
TopDocs GetTopDocs();
/// <summary>
/// Returns the documents in the rage [<paramref name="start"/> .. pq.Count) that were collected
/// by this collector. Note that if <paramref name="start"/> >= pq.Count, an empty <see cref="TopDocs"/> is
/// returned.
/// <para/>
/// This method is convenient to call if the application always asks for the
/// last results, starting from the last 'page'.
/// <para/>
/// <b>NOTE:</b> you cannot call this method more than once for each search
/// execution. If you need to call it more than once, passing each time a
/// different <paramref name="start"/>, you should call <see cref="GetTopDocs()"/> and work
/// with the returned <see cref="TopDocs"/> object, which will contain all the
/// results this search execution collected.
/// </summary>
TopDocs GetTopDocs(int start);
/// <summary>
/// Returns the documents in the rage [<paramref name="start"/> .. <paramref name="start"/>+<paramref name="howMany"/>) that were
/// collected by this collector. Note that if <paramref name="start"/> >= pq.Count, an empty
/// <see cref="TopDocs"/> is returned, and if pq.Count - <paramref name="start"/> < <paramref name="howMany"/>, then only the
/// available documents in [<paramref name="start"/> .. pq.Count) are returned.
/// <para/>
/// This method is useful to call in case pagination of search results is
/// allowed by the search application, as well as it attempts to optimize the
/// memory used by allocating only as much as requested by <paramref name="howMany"/>.
/// <para/>
/// <b>NOTE:</b> you cannot call this method more than once for each search
/// execution. If you need to call it more than once, passing each time a
/// different range, you should call <see cref="GetTopDocs()"/> and work with the
/// returned <see cref="TopDocs"/> object, which will contain all the results this
/// search execution collected.
/// </summary>
TopDocs GetTopDocs(int start, int howMany);
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Hyak.Common;
using Hyak.Common.Internals;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Management.MediaServices;
using Microsoft.WindowsAzure.Management.MediaServices.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.WindowsAzure.Management.MediaServices
{
internal partial class AccountOperations : IServiceOperations<MediaServicesManagementClient>, IAccountOperations
{
/// <summary>
/// Initializes a new instance of the AccountOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal AccountOperations(MediaServicesManagementClient client)
{
this._client = client;
}
private MediaServicesManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.MediaServices.MediaServicesManagementClient.
/// </summary>
public MediaServicesManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// The Create Media Services Account operation creates a new media
/// services account in Windows Azure. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn194267.aspx
/// for more information)
/// </summary>
/// <param name='parameters'>
/// Required. Parameters supplied to the Create Media Services Account
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Create Media Services Account operation response.
/// </returns>
public async Task<MediaServicesAccountCreateResponse> CreateAsync(MediaServicesAccountCreateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.AccountName == null)
{
throw new ArgumentNullException("parameters.AccountName");
}
if (parameters.AccountName.Length < 3)
{
throw new ArgumentOutOfRangeException("parameters.AccountName");
}
if (parameters.AccountName.Length > 24)
{
throw new ArgumentOutOfRangeException("parameters.AccountName");
}
if (parameters.BlobStorageEndpointUri == null)
{
throw new ArgumentNullException("parameters.BlobStorageEndpointUri");
}
if (parameters.Region == null)
{
throw new ArgumentNullException("parameters.Region");
}
if (parameters.Region.Length < 3)
{
throw new ArgumentOutOfRangeException("parameters.Region");
}
if (parameters.Region.Length > 256)
{
throw new ArgumentOutOfRangeException("parameters.Region");
}
if (parameters.StorageAccountKey == null)
{
throw new ArgumentNullException("parameters.StorageAccountKey");
}
if (parameters.StorageAccountKey.Length < 14)
{
throw new ArgumentOutOfRangeException("parameters.StorageAccountKey");
}
if (parameters.StorageAccountKey.Length > 256)
{
throw new ArgumentOutOfRangeException("parameters.StorageAccountKey");
}
if (parameters.StorageAccountName == null)
{
throw new ArgumentNullException("parameters.StorageAccountName");
}
if (parameters.StorageAccountName.Length < 3)
{
throw new ArgumentOutOfRangeException("parameters.StorageAccountName");
}
if (parameters.StorageAccountName.Length > 24)
{
throw new ArgumentOutOfRangeException("parameters.StorageAccountName");
}
foreach (char storageAccountNameChar in parameters.StorageAccountName)
{
if (char.IsLower(storageAccountNameChar) == false && char.IsDigit(storageAccountNameChar) == false)
{
throw new ArgumentOutOfRangeException("parameters.StorageAccountName");
}
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/mediaservices/Accounts";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2011-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
XDocument requestDoc = new XDocument();
XElement accountCreationRequestElement = new XElement(XName.Get("AccountCreationRequest", "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models"));
requestDoc.Add(accountCreationRequestElement);
XElement accountNameElement = new XElement(XName.Get("AccountName", "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models"));
accountNameElement.Value = parameters.AccountName;
accountCreationRequestElement.Add(accountNameElement);
XElement blobStorageEndpointUriElement = new XElement(XName.Get("BlobStorageEndpointUri", "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models"));
blobStorageEndpointUriElement.Value = parameters.BlobStorageEndpointUri.AbsoluteUri;
accountCreationRequestElement.Add(blobStorageEndpointUriElement);
XElement regionElement = new XElement(XName.Get("Region", "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models"));
regionElement.Value = parameters.Region;
accountCreationRequestElement.Add(regionElement);
XElement storageAccountKeyElement = new XElement(XName.Get("StorageAccountKey", "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models"));
storageAccountKeyElement.Value = parameters.StorageAccountKey;
accountCreationRequestElement.Add(storageAccountKeyElement);
XElement storageAccountNameElement = new XElement(XName.Get("StorageAccountName", "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models"));
storageAccountNameElement.Value = parameters.StorageAccountName;
accountCreationRequestElement.Add(storageAccountNameElement);
requestContent = requestDoc.ToString();
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
MediaServicesAccountCreateResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new MediaServicesAccountCreateResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
MediaServicesCreatedAccount accountInstance = new MediaServicesCreatedAccount();
result.Account = accountInstance;
JToken accountIdValue = responseDoc["AccountId"];
if (accountIdValue != null && accountIdValue.Type != JTokenType.Null)
{
string accountIdInstance = ((string)accountIdValue);
accountInstance.AccountId = accountIdInstance;
}
JToken accountNameValue = responseDoc["AccountName"];
if (accountNameValue != null && accountNameValue.Type != JTokenType.Null)
{
string accountNameInstance = ((string)accountNameValue);
accountInstance.AccountName = accountNameInstance;
}
JToken subscriptionValue = responseDoc["Subscription"];
if (subscriptionValue != null && subscriptionValue.Type != JTokenType.Null)
{
string subscriptionInstance = ((string)subscriptionValue);
accountInstance.SubscriptionId = subscriptionInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The Delete Media Services Account operation deletes an existing
/// media services account in Windows Azure. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn194273.aspx
/// for more information)
/// </summary>
/// <param name='accountName'>
/// Required. The name of the media services account.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> DeleteAsync(string accountName, CancellationToken cancellationToken)
{
// Validate
if (accountName == null)
{
throw new ArgumentNullException("accountName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("accountName", accountName);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/mediaservices/Accounts/";
url = url + Uri.EscapeDataString(accountName);
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2011-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The Get Media Services Account operation gets detailed information
/// about a media services account in Windows Azure. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn166974.aspx
/// for more information)
/// </summary>
/// <param name='accountName'>
/// Required. The name of the Media Services account.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Get Media Services Account operation response.
/// </returns>
public async Task<MediaServicesAccountGetResponse> GetAsync(string accountName, CancellationToken cancellationToken)
{
// Validate
if (accountName == null)
{
throw new ArgumentNullException("accountName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("accountName", accountName);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/mediaservices/Accounts/";
url = url + Uri.EscapeDataString(accountName);
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2011-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
MediaServicesAccountGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new MediaServicesAccountGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
MediaServicesAccount accountInstance = new MediaServicesAccount();
result.Account = accountInstance;
JToken accountNameValue = responseDoc["AccountName"];
if (accountNameValue != null && accountNameValue.Type != JTokenType.Null)
{
string accountNameInstance = ((string)accountNameValue);
accountInstance.AccountName = accountNameInstance;
}
JToken accountKeyValue = responseDoc["AccountKey"];
if (accountKeyValue != null && accountKeyValue.Type != JTokenType.Null)
{
string accountKeyInstance = ((string)accountKeyValue);
accountInstance.AccountKey = accountKeyInstance;
}
JToken accountKeysValue = responseDoc["AccountKeys"];
if (accountKeysValue != null && accountKeysValue.Type != JTokenType.Null)
{
MediaServicesAccount.AccountKeys accountKeysInstance = new MediaServicesAccount.AccountKeys();
accountInstance.StorageAccountKeys = accountKeysInstance;
JToken primaryValue = accountKeysValue["Primary"];
if (primaryValue != null && primaryValue.Type != JTokenType.Null)
{
string primaryInstance = ((string)primaryValue);
accountKeysInstance.Primary = primaryInstance;
}
JToken secondaryValue = accountKeysValue["Secondary"];
if (secondaryValue != null && secondaryValue.Type != JTokenType.Null)
{
string secondaryInstance = ((string)secondaryValue);
accountKeysInstance.Secondary = secondaryInstance;
}
}
JToken accountRegionValue = responseDoc["AccountRegion"];
if (accountRegionValue != null && accountRegionValue.Type != JTokenType.Null)
{
string accountRegionInstance = ((string)accountRegionValue);
accountInstance.AccountRegion = accountRegionInstance;
}
JToken storageAccountNameValue = responseDoc["StorageAccountName"];
if (storageAccountNameValue != null && storageAccountNameValue.Type != JTokenType.Null)
{
string storageAccountNameInstance = ((string)storageAccountNameValue);
accountInstance.StorageAccountName = storageAccountNameInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The List Media Services Account operation gets information about
/// all existing media services accounts associated with the current
/// subscription in Windows Azure. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn166989.aspx
/// for more information)
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The List Media Accounts operation response.
/// </returns>
public async Task<MediaServicesAccountListResponse> ListAsync(CancellationToken cancellationToken)
{
// Validate
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/mediaservices/Accounts";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2011-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
MediaServicesAccountListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new MediaServicesAccountListResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement serviceResourcesSequenceElement = responseDoc.Element(XName.Get("ServiceResources", "http://schemas.microsoft.com/windowsazure"));
if (serviceResourcesSequenceElement != null)
{
foreach (XElement serviceResourcesElement in serviceResourcesSequenceElement.Elements(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure")))
{
MediaServicesAccountListResponse.MediaServiceAccount serviceResourceInstance = new MediaServicesAccountListResponse.MediaServiceAccount();
result.Accounts.Add(serviceResourceInstance);
XElement nameElement = serviceResourcesElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement != null)
{
string nameInstance = nameElement.Value;
serviceResourceInstance.Name = nameInstance;
}
XElement typeElement = serviceResourcesElement.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
if (typeElement != null)
{
string typeInstance = typeElement.Value;
serviceResourceInstance.Type = typeInstance;
}
XElement stateElement = serviceResourcesElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure"));
if (stateElement != null)
{
string stateInstance = stateElement.Value;
serviceResourceInstance.State = stateInstance;
}
XElement selfLinkElement = serviceResourcesElement.Element(XName.Get("SelfLink", "http://schemas.microsoft.com/windowsazure"));
if (selfLinkElement != null)
{
Uri selfLinkInstance = TypeConversion.TryParseUri(selfLinkElement.Value);
serviceResourceInstance.Uri = selfLinkInstance;
}
XElement parentLinkElement = serviceResourcesElement.Element(XName.Get("ParentLink", "http://schemas.microsoft.com/windowsazure"));
if (parentLinkElement != null)
{
Uri parentLinkInstance = TypeConversion.TryParseUri(parentLinkElement.Value);
serviceResourceInstance.ParentUri = parentLinkInstance;
}
XElement accountIdElement = serviceResourcesElement.Element(XName.Get("AccountId", "http://schemas.microsoft.com/windowsazure"));
if (accountIdElement != null)
{
string accountIdInstance = accountIdElement.Value;
serviceResourceInstance.AccountId = accountIdInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The Regenerate Media Services Account Key operation regenerates an
/// account key for the given Media Services account in Windows Azure.
/// (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn167010.aspx
/// for more information)
/// </summary>
/// <param name='accountName'>
/// Required. The name of the Media Services Account.
/// </param>
/// <param name='keyType'>
/// Required. The type of key to regenerate (primary or secondary)
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> RegenerateKeyAsync(string accountName, MediaServicesKeyType keyType, CancellationToken cancellationToken)
{
// Validate
if (accountName == null)
{
throw new ArgumentNullException("accountName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("keyType", keyType);
TracingAdapter.Enter(invocationId, this, "RegenerateKeyAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/mediaservices/Accounts/";
url = url + Uri.EscapeDataString(accountName);
url = url + "/AccountKeys/";
url = url + Uri.EscapeDataString(keyType.ToString());
url = url + "/Regenerate";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2011-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
using System;
/// <summary>
/// Convert.ToBoolean(Decimal)
/// Converts the value of the specified decimal value to an equivalent Boolean value.
/// </summary>
public class ConvertToBoolean
{
public static int Main()
{
ConvertToBoolean testObj = new ConvertToBoolean();
TestLibrary.TestFramework.BeginTestCase("for method: Convert.ToBoolean(Decimal)");
if(testObj.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
return retVal;
}
#region Positive tests
public bool PosTest1()
{
bool retVal = true;
string errorDesc;
decimal d;
bool expectedValue;
bool actualValue;
d = (decimal)TestLibrary.Generator.GetSingle(-55);
TestLibrary.TestFramework.BeginScenario("PosTest1: Random decimal value between 0.0 and 1.0.");
try
{
actualValue = Convert.ToBoolean(d);
expectedValue = 0 != d;
if (actualValue != expectedValue)
{
errorDesc = "The boolean value of decimal value " + d + " is not the value " + expectedValue +
" as expected: actual(" + actualValue + ")";
TestLibrary.TestFramework.LogError("001", errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpect exception:" + e;
errorDesc += "\nThe decimal value is " + d;
TestLibrary.TestFramework.LogError("002", errorDesc);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
string errorDesc;
decimal d;
bool expectedValue;
bool actualValue;
d = decimal.MaxValue;
TestLibrary.TestFramework.BeginScenario("PosTest2: value is decimal.MaxValue.");
try
{
actualValue = Convert.ToBoolean(d);
expectedValue = 0 != d;
if (actualValue != expectedValue)
{
errorDesc = "The boolean value of decimal value " + d + " is not the value " + expectedValue +
" as expected: actual(" + actualValue + ")";
TestLibrary.TestFramework.LogError("003", errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpect exception:" + e;
errorDesc += "\nThe decimal value is " + d;
TestLibrary.TestFramework.LogError("004", errorDesc);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
string errorDesc;
decimal d;
bool expectedValue;
bool actualValue;
d = decimal.MinValue;
TestLibrary.TestFramework.BeginScenario("PosTest3: value is decimal.MinValue.");
try
{
actualValue = Convert.ToBoolean(d);
expectedValue = 0 != d;
if (actualValue != expectedValue)
{
errorDesc = "The boolean value of decimal integer " + d + " is not the value " + expectedValue +
" as expected: actual(" + actualValue + ")";
TestLibrary.TestFramework.LogError("005", errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpect exception:" + e;
errorDesc += "\nThe decimal value is " + d;
TestLibrary.TestFramework.LogError("006", errorDesc);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
string errorDesc;
decimal d;
bool expectedValue;
bool actualValue;
d = decimal.Zero;
TestLibrary.TestFramework.BeginScenario("PosTest4: value is decimal.Zero.");
try
{
actualValue = Convert.ToBoolean(d);
expectedValue = 0 != d;
if (actualValue != expectedValue)
{
errorDesc = "The boolean value of decimal integer " + d + " is not the value " + expectedValue +
" as expected: actual(" + actualValue + ")";
TestLibrary.TestFramework.LogError("007", errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpect exception:" + e;
errorDesc += "\nThe decimal value is " + d;
TestLibrary.TestFramework.LogError("008", errorDesc);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
string errorDesc;
decimal d;
bool expectedValue;
bool actualValue;
d = -1 * (decimal)TestLibrary.Generator.GetSingle(-55);
TestLibrary.TestFramework.BeginScenario("PosTest5: Random decimal value between -0.0 and -1.0.");
try
{
actualValue = Convert.ToBoolean(d);
expectedValue = 0 != d;
if (actualValue != expectedValue)
{
errorDesc = "The boolean value of decimal integer " + d + " is not the value " + expectedValue +
" as expected: actual(" + actualValue + ")";
TestLibrary.TestFramework.LogError("009", errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpect exception:" + e;
errorDesc += "\nThe decimal value is " + d;
TestLibrary.TestFramework.LogError("010", errorDesc);
retVal = false;
}
return retVal;
}
#endregion
}
| |
//
// Copyright 2014-2015 Amazon.com,
// Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Amazon Software License (the "License").
// You may not use this file except in compliance with the
// License. A copy of the License is located at
//
// http://aws.amazon.com/asl/
//
// or in the "license" file accompanying this file. This file is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, express or implied. See the License
// for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using Amazon.DynamoDBv2.Model;
using Amazon.DynamoDBv2.DocumentModel;
namespace Amazon.DynamoDBv2.DataModel
{
/// <summary>
/// Represents a non-generic object for retrieving a batch of items
/// from a single DynamoDB table
/// </summary>
public abstract partial class BatchGet
{
#region Internal/protected properties
protected List<object> UntypedResults { get; set; }
internal DynamoDBContext Context { get; set; }
internal DynamoDBFlatConfig Config { get; set; }
internal List<Key> Keys { get; set; }
internal DocumentBatchGet DocumentBatch { get; set; }
internal ItemStorageConfig ItemStorageConfig { get; set; }
#endregion
#region Constructor
internal BatchGet(DynamoDBContext context, DynamoDBFlatConfig config)
{
Context = context;
Config = config;
Keys = new List<Key>();
}
#endregion
#region Public properties
/// <summary>
/// List of results retrieved from DynamoDB.
/// Populated after Execute is called.
/// </summary>
public List<object> Results { get { return UntypedResults; } }
/// <summary>
/// If set to true, a consistent read is issued. Otherwise eventually-consistent is used.
/// </summary>
public bool ConsistentRead { get; set; }
#endregion
#region Protected methods
/// <summary>
/// Executes a server call to batch-get the items requested.
/// Populates Results with the retrieved items.
/// </summary>
protected virtual void ExecuteHelper(bool isAsync)
{
}
#endregion
#region Internal methods
internal abstract void CreateDocumentBatch();
internal abstract void PopulateResults(List<Document> items);
#endregion
}
/// <summary>
/// Represents a strongly-typed object for retrieving a batch of items
/// from a single DynamoDB table
/// </summary>
public class BatchGet<T> : BatchGet
{
#region Public properties
/// <summary>
/// List of results retrieved from DynamoDB.
/// Populated after Execute is called.
/// </summary>
new public List<T> Results { get { return TypedResults; } }
#endregion
#region Public methods
/// <summary>
/// Add a single item to get, identified by its hash primary key.
/// </summary>
/// <param name="hashKey">Hash key of the item to get</param>
public void AddKey(object hashKey)
{
AddKey(hashKey, null);
}
/// <summary>
/// Add a single item to get, identified by its hash-and-range primary key.
/// </summary>
/// <param name="hashKey">Hash key of the item to get</param>
/// <param name="rangeKey">Range key of the item to get</param>
public void AddKey(object hashKey, object rangeKey)
{
Key key = Context.MakeKey(hashKey, rangeKey, ItemStorageConfig, Config);
Keys.Add(key);
}
/// <summary>
/// Add a single item to get.
/// </summary>
/// <param name="keyObject">Object key of the item to get</param>
public void AddKey(T keyObject)
{
Key key = Context.MakeKey(keyObject, ItemStorageConfig, Config);
Keys.Add(key);
}
/// <summary>
/// Creates a MultiTableBatchGet object that is a combination
/// of the current BatchGet and the specified BatchGets
/// </summary>
/// <param name="otherBatches">Other BatchGet objects</param>
/// <returns>
/// MultiTableBatchGet consisting of the multiple BatchGet objects:
/// the current batch and the passed-in batches.
/// </returns>
public MultiTableBatchGet Combine(params BatchGet[] otherBatches)
{
return new MultiTableBatchGet(this, otherBatches);
}
#endregion
#region Constructor
internal BatchGet(DynamoDBContext context, DynamoDBFlatConfig config)
: base(context, config)
{
ItemStorageConfig = context.StorageConfigCache.GetConfig<T>(config);
}
#endregion
#region Internal/protected/private members
protected override void ExecuteHelper(bool isAsync)
{
CreateDocumentBatch();
DocumentBatch.ExecuteHelper(isAsync);
PopulateResults(DocumentBatch.Results);
}
protected List<T> TypedResults { get; set; }
internal override void CreateDocumentBatch()
{
var storageConfig = Context.StorageConfigCache.GetConfig<T>(Config);
var table = Context.GetTargetTable(storageConfig, Config);
DocumentBatchGet docBatch = new DocumentBatchGet(table)
{
AttributesToGet = storageConfig.AttributesToGet,
ConsistentRead = this.ConsistentRead
};
docBatch.Keys.AddRange(Keys);
DocumentBatch = docBatch;
}
internal override void PopulateResults(List<Document> items)
{
UntypedResults = new List<object>();
TypedResults = new List<T>();
foreach (var doc in items)
{
var item = Context.FromDocumentHelper<T>(doc, Config);
TypedResults.Add(item);
UntypedResults.Add(item);
}
}
#endregion
}
/// <summary>
/// Class for retrieving a batch of items from multiple DynamoDB tables,
/// using multiple strongly-typed BatchGet objects
/// </summary>
public partial class MultiTableBatchGet
{
#region Private members
private List<BatchGet> allBatches = new List<BatchGet>();
#endregion
#region Constructor
/// <summary>
/// Constructs a MultiTableBatchGet object from a number of
/// BatchGet objects
/// </summary>
/// <param name="batches">Collection of BatchGet objects</param>
public MultiTableBatchGet(params BatchGet[] batches)
{
allBatches = new List<BatchGet>(batches);
}
internal MultiTableBatchGet(BatchGet first, params BatchGet[] rest)
{
allBatches = new List<BatchGet>();
allBatches.Add(first);
allBatches.AddRange(rest);
}
#endregion
#region Public properties
/// <summary>
/// Gets the total number of primary keys to be loaded from DynamoDB,
/// across all batches
/// </summary>
public int TotalKeys
{
get
{
int count = 0;
foreach (var batch in allBatches)
{
count += batch.Keys.Count;
}
return count;
}
}
#endregion
#region Public methods
/// <summary>
/// Add a BatchGet object to the multi-table batch request
/// </summary>
/// <param name="batch">BatchGet to add</param>
public void AddBatch(BatchGet batch)
{
allBatches.Add(batch);
}
internal void ExecuteHelper(bool isAsync)
{
MultiTableDocumentBatchGet superBatch = new MultiTableDocumentBatchGet();
foreach (var batch in allBatches)
{
batch.CreateDocumentBatch();
superBatch.AddBatch(batch.DocumentBatch);
}
superBatch.ExecuteHelper(isAsync);
foreach (var batch in allBatches)
{
batch.PopulateResults(batch.DocumentBatch.Results);
}
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using OpenMetaverse;
using System;
using System.Diagnostics;
using System.Globalization;
public class Vertex : IComparable<Vertex>
{
Vector3 vector;
public float X
{
get { return vector.X; }
set { vector.X = value; }
}
public float Y
{
get { return vector.Y; }
set { vector.Y = value; }
}
public float Z
{
get { return vector.Z; }
set { vector.Z = value; }
}
public Vertex(float x, float y, float z)
{
vector.X = x;
vector.Y = y;
vector.Z = z;
}
public Vertex normalize()
{
float tlength = vector.Length();
if (tlength != 0f)
{
float mul = 1.0f / tlength;
return new Vertex(vector.X * mul, vector.Y * mul, vector.Z * mul);
}
else
{
return new Vertex(0f, 0f, 0f);
}
}
public Vertex cross(Vertex v)
{
return new Vertex(vector.Y * v.Z - vector.Z * v.Y, vector.Z * v.X - vector.X * v.Z, vector.X * v.Y - vector.Y * v.X);
}
// disable warning: mono compiler moans about overloading
// operators hiding base operator but should not according to C#
// language spec
#pragma warning disable 0108
public static Vertex operator *(Vertex v, Quaternion q)
{
// From http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/transforms/
Vertex v2 = new Vertex(0f, 0f, 0f);
v2.X = q.W * q.W * v.X +
2f * q.Y * q.W * v.Z -
2f * q.Z * q.W * v.Y +
q.X * q.X * v.X +
2f * q.Y * q.X * v.Y +
2f * q.Z * q.X * v.Z -
q.Z * q.Z * v.X -
q.Y * q.Y * v.X;
v2.Y =
2f * q.X * q.Y * v.X +
q.Y * q.Y * v.Y +
2f * q.Z * q.Y * v.Z +
2f * q.W * q.Z * v.X -
q.Z * q.Z * v.Y +
q.W * q.W * v.Y -
2f * q.X * q.W * v.Z -
q.X * q.X * v.Y;
v2.Z =
2f * q.X * q.Z * v.X +
2f * q.Y * q.Z * v.Y +
q.Z * q.Z * v.Z -
2f * q.W * q.Y * v.X -
q.Y * q.Y * v.Z +
2f * q.W * q.X * v.Y -
q.X * q.X * v.Z +
q.W * q.W * v.Z;
return v2;
}
public static Vertex operator +(Vertex v1, Vertex v2)
{
return new Vertex(v1.X + v2.X, v1.Y + v2.Y, v1.Z + v2.Z);
}
public static Vertex operator -(Vertex v1, Vertex v2)
{
return new Vertex(v1.X - v2.X, v1.Y - v2.Y, v1.Z - v2.Z);
}
public static Vertex operator *(Vertex v1, Vertex v2)
{
return new Vertex(v1.X * v2.X, v1.Y * v2.Y, v1.Z * v2.Z);
}
public static Vertex operator +(Vertex v1, float am)
{
v1.X += am;
v1.Y += am;
v1.Z += am;
return v1;
}
public static Vertex operator -(Vertex v1, float am)
{
v1.X -= am;
v1.Y -= am;
v1.Z -= am;
return v1;
}
public static Vertex operator *(Vertex v1, float am)
{
v1.X *= am;
v1.Y *= am;
v1.Z *= am;
return v1;
}
public static Vertex operator /(Vertex v1, float am)
{
if (am == 0f)
{
return new Vertex(0f,0f,0f);
}
float mul = 1.0f / am;
v1.X *= mul;
v1.Y *= mul;
v1.Z *= mul;
return v1;
}
#pragma warning restore 0108
public float dot(Vertex v)
{
return X * v.X + Y * v.Y + Z * v.Z;
}
public Vertex(Vector3 v)
{
vector = v;
}
public Vertex Clone()
{
return new Vertex(X, Y, Z);
}
public static Vertex FromAngle(double angle)
{
return new Vertex((float) Math.Cos(angle), (float) Math.Sin(angle), 0.0f);
}
public float Length()
{
return vector.Length();
}
public virtual bool Equals(Vertex v, float tolerance)
{
Vertex diff = this - v;
float d = diff.Length();
if (d < tolerance)
return true;
return false;
}
public int CompareTo(Vertex other)
{
if (X < other.X)
return -1;
if (X > other.X)
return 1;
if (Y < other.Y)
return -1;
if (Y > other.Y)
return 1;
if (Z < other.Z)
return -1;
if (Z > other.Z)
return 1;
return 0;
}
public static bool operator >(Vertex me, Vertex other)
{
return me.CompareTo(other) > 0;
}
public static bool operator <(Vertex me, Vertex other)
{
return me.CompareTo(other) < 0;
}
public String ToRaw()
{
// Why this stuff with the number formatter?
// Well, the raw format uses the english/US notation of numbers
// where the "," separates groups of 1000 while the "." marks the border between 1 and 10E-1.
// The german notation uses these characters exactly vice versa!
// The Float.ToString() routine is a localized one, giving different results depending on the country
// settings your machine works with. Unusable for a machine readable file format :-(
NumberFormatInfo nfi = new NumberFormatInfo();
nfi.NumberDecimalSeparator = ".";
nfi.NumberDecimalDigits = 3;
String s1 = X.ToString("N2", nfi) + " " + Y.ToString("N2", nfi) + " " + Z.ToString("N2", nfi);
return s1;
}
}
public class Triangle
{
public Vertex v1;
public Vertex v2;
public Vertex v3;
private float radius_square;
private float cx;
private float cy;
public Triangle(Vertex _v1, Vertex _v2, Vertex _v3)
{
v1 = _v1;
v2 = _v2;
v3 = _v3;
CalcCircle();
}
public bool isInCircle(float x, float y)
{
float dx, dy;
float dd;
dx = x - cx;
dy = y - cy;
dd = dx*dx + dy*dy;
if (dd < radius_square)
return true;
else
return false;
}
public bool isDegraded()
{
// This means, the vertices of this triangle are somewhat strange.
// They either line up or at least two of them are identical
return (radius_square == 0.0);
}
private void CalcCircle()
{
// Calculate the center and the radius of a circle given by three points p1, p2, p3
// It is assumed, that the triangles vertices are already set correctly
double p1x, p2x, p1y, p2y, p3x, p3y;
// Deviation of this routine:
// A circle has the general equation (M-p)^2=r^2, where M and p are vectors
// this gives us three equations f(p)=r^2, each for one point p1, p2, p3
// putting respectively two equations together gives two equations
// f(p1)=f(p2) and f(p1)=f(p3)
// bringing all constant terms to one side brings them to the form
// M*v1=c1 resp.M*v2=c2 where v1=(p1-p2) and v2=(p1-p3) (still vectors)
// and c1, c2 are scalars (Naming conventions like the variables below)
// Now using the equations that are formed by the components of the vectors
// and isolate Mx lets you make one equation that only holds My
// The rest is straight forward and eaasy :-)
//
/* helping variables for temporary results */
double c1, c2;
double v1x, v1y, v2x, v2y;
double z, n;
double rx, ry;
// Readout the three points, the triangle consists of
p1x = v1.X;
p1y = v1.Y;
p2x = v2.X;
p2y = v2.Y;
p3x = v3.X;
p3y = v3.Y;
/* calc helping values first */
c1 = (p1x*p1x + p1y*p1y - p2x*p2x - p2y*p2y)/2;
c2 = (p1x*p1x + p1y*p1y - p3x*p3x - p3y*p3y)/2;
v1x = p1x - p2x;
v1y = p1y - p2y;
v2x = p1x - p3x;
v2y = p1y - p3y;
z = (c1*v2x - c2*v1x);
n = (v1y*v2x - v2y*v1x);
if (n == 0.0) // This is no triangle, i.e there are (at least) two points at the same location
{
radius_square = 0.0f;
return;
}
cy = (float) (z/n);
if (v2x != 0.0)
{
cx = (float) ((c2 - v2y*cy)/v2x);
}
else if (v1x != 0.0)
{
cx = (float) ((c1 - v1y*cy)/v1x);
}
else
{
Debug.Assert(false, "Malformed triangle"); /* Both terms zero means nothing good */
}
rx = (p1x - cx);
ry = (p1y - cy);
radius_square = (float) (rx*rx + ry*ry);
}
public override String ToString()
{
NumberFormatInfo nfi = new NumberFormatInfo();
nfi.CurrencyDecimalDigits = 2;
nfi.CurrencyDecimalSeparator = ".";
String s1 = "<" + v1.X.ToString(nfi) + "," + v1.Y.ToString(nfi) + "," + v1.Z.ToString(nfi) + ">";
String s2 = "<" + v2.X.ToString(nfi) + "," + v2.Y.ToString(nfi) + "," + v2.Z.ToString(nfi) + ">";
String s3 = "<" + v3.X.ToString(nfi) + "," + v3.Y.ToString(nfi) + "," + v3.Z.ToString(nfi) + ">";
return s1 + ";" + s2 + ";" + s3;
}
public Vector3 getNormal()
{
// Vertices
// Vectors for edges
Vector3 e1;
Vector3 e2;
e1 = new Vector3(v1.X - v2.X, v1.Y - v2.Y, v1.Z - v2.Z);
e2 = new Vector3(v1.X - v3.X, v1.Y - v3.Y, v1.Z - v3.Z);
// Cross product for normal
Vector3 n = Vector3.Cross(e1, e2);
// Length
float l = n.Length();
// Normalized "normal"
n = n/l;
return n;
}
public void invertNormal()
{
Vertex vt;
vt = v1;
v1 = v2;
v2 = vt;
}
// Dumps a triangle in the "raw faces" format, blender can import. This is for visualisation and
// debugging purposes
public String ToStringRaw()
{
String output = v1.ToRaw() + " " + v2.ToRaw() + " " + v3.ToRaw();
return output;
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Channels
{
using System.Collections.ObjectModel;
using System.IdentityModel.Claims;
using System.IdentityModel.Policy;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.Net;
using System.Net.Security;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Security.Cryptography.X509Certificates;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Security;
using System.ServiceModel.Security.Tokens;
class HttpsChannelFactory<TChannel> : HttpChannelFactory<TChannel>
{
bool requireClientCertificate;
IChannelBindingProvider channelBindingProvider;
RemoteCertificateValidationCallback remoteCertificateValidationCallback;
X509CertificateValidator sslCertificateValidator;
internal HttpsChannelFactory(HttpsTransportBindingElement httpsBindingElement, BindingContext context)
: base(httpsBindingElement, context)
{
this.requireClientCertificate = httpsBindingElement.RequireClientCertificate;
this.channelBindingProvider = new ChannelBindingProviderHelper();
ClientCredentials credentials = context.BindingParameters.Find<ClientCredentials>();
if (credentials != null && credentials.ServiceCertificate.SslCertificateAuthentication != null)
{
this.sslCertificateValidator = credentials.ServiceCertificate.SslCertificateAuthentication.GetCertificateValidator();
this.remoteCertificateValidationCallback = new RemoteCertificateValidationCallback(RemoteCertificateValidationCallback);
}
}
public override string Scheme
{
get
{
return Uri.UriSchemeHttps;
}
}
public bool RequireClientCertificate
{
get
{
return this.requireClientCertificate;
}
}
public override bool IsChannelBindingSupportEnabled
{
get
{
return this.channelBindingProvider.IsChannelBindingSupportEnabled;
}
}
public override T GetProperty<T>()
{
if (typeof(T) == typeof(IChannelBindingProvider))
{
return (T)(object)this.channelBindingProvider;
}
return base.GetProperty<T>();
}
internal override SecurityMessageProperty CreateReplySecurityProperty(HttpWebRequest request,
HttpWebResponse response)
{
SecurityMessageProperty result = null;
X509Certificate certificate = request.ServicePoint.Certificate;
if (certificate != null)
{
X509Certificate2 certificateEx = new X509Certificate2(certificate);
SecurityToken token = new X509SecurityToken(certificateEx, false);
ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies = SecurityUtils.NonValidatingX509Authenticator.ValidateToken(token);
result = new SecurityMessageProperty();
result.TransportToken = new SecurityTokenSpecification(token, authorizationPolicies);
result.ServiceSecurityContext = new ServiceSecurityContext(authorizationPolicies);
}
else
{
result = base.CreateReplySecurityProperty(request, response);
}
return result;
}
protected override void ValidateCreateChannelParameters(EndpointAddress remoteAddress, Uri via)
{
if (remoteAddress.Identity != null)
{
X509CertificateEndpointIdentity certificateIdentity =
remoteAddress.Identity as X509CertificateEndpointIdentity;
if (certificateIdentity != null)
{
if (certificateIdentity.Certificates.Count > 1)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("remoteAddress", SR.GetString(
SR.HttpsIdentityMultipleCerts, remoteAddress.Uri));
}
}
EndpointIdentity identity = remoteAddress.Identity;
bool validIdentity = (certificateIdentity != null)
|| ClaimTypes.Spn.Equals(identity.IdentityClaim.ClaimType)
|| ClaimTypes.Upn.Equals(identity.IdentityClaim.ClaimType)
|| ClaimTypes.Dns.Equals(identity.IdentityClaim.ClaimType);
if (!HttpChannelFactory<TChannel>.IsWindowsAuth(this.AuthenticationScheme)
&& !validIdentity)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("remoteAddress", SR.GetString(
SR.HttpsExplicitIdentity));
}
}
base.ValidateCreateChannelParameters(remoteAddress, via);
}
protected override TChannel OnCreateChannelCore(EndpointAddress address, Uri via)
{
ValidateCreateChannelParameters(address, via);
this.ValidateWebSocketTransportUsage();
if (typeof(TChannel) == typeof(IRequestChannel))
{
return (TChannel)(object)new HttpsRequestChannel((HttpsChannelFactory<IRequestChannel>)(object)this, address, via, ManualAddressing);
}
else
{
return (TChannel)(object)new ClientWebSocketTransportDuplexSessionChannel((HttpChannelFactory<IDuplexSessionChannel>)(object)this, this.ClientWebSocketFactory, address, via, this.WebSocketBufferPool);
}
}
protected override bool IsSecurityTokenManagerRequired()
{
return this.requireClientCertificate || base.IsSecurityTokenManagerRequired();
}
protected override string OnGetConnectionGroupPrefix(HttpWebRequest httpWebRequest, SecurityTokenContainer clientCertificateToken)
{
System.Text.StringBuilder inputStringBuilder = new System.Text.StringBuilder();
string delimiter = "\0"; // nonprintable characters are invalid for SSPI Domain/UserName/Password
if (this.RequireClientCertificate)
{
HttpsChannelFactory<TChannel>.SetCertificate(httpWebRequest, clientCertificateToken);
X509CertificateCollection certificateCollection = httpWebRequest.ClientCertificates;
for (int i = 0; i < certificateCollection.Count; i++)
{
inputStringBuilder.AppendFormat("{0}{1}", certificateCollection[i].GetCertHashString(), delimiter);
}
}
return inputStringBuilder.ToString();
}
void OnOpenCore()
{
if (this.requireClientCertificate && this.SecurityTokenManager == null)
{
throw Fx.AssertAndThrow("HttpsChannelFactory: SecurityTokenManager is null on open.");
}
}
protected override void OnEndOpen(IAsyncResult result)
{
base.OnEndOpen(result);
OnOpenCore();
}
protected override void OnOpen(TimeSpan timeout)
{
base.OnOpen(timeout);
OnOpenCore();
}
internal SecurityTokenProvider CreateAndOpenCertificateTokenProvider(EndpointAddress target, Uri via, ChannelParameterCollection channelParameters, TimeSpan timeout)
{
if (!this.RequireClientCertificate)
{
return null;
}
SecurityTokenProvider certificateProvider = TransportSecurityHelpers.GetCertificateTokenProvider(
this.SecurityTokenManager, target, via, this.Scheme, channelParameters);
SecurityUtils.OpenTokenProviderIfRequired(certificateProvider, timeout);
return certificateProvider;
}
static void SetCertificate(HttpWebRequest request, SecurityTokenContainer clientCertificateToken)
{
if (clientCertificateToken != null)
{
X509SecurityToken x509Token = (X509SecurityToken)clientCertificateToken.Token;
request.ClientCertificates.Add(x509Token.Certificate);
}
}
internal SecurityTokenContainer GetCertificateSecurityToken(SecurityTokenProvider certificateProvider,
EndpointAddress to, Uri via, ChannelParameterCollection channelParameters, ref TimeoutHelper timeoutHelper)
{
SecurityToken token = null;
SecurityTokenContainer tokenContainer = null;
SecurityTokenProvider webRequestCertificateProvider;
if (ManualAddressing && this.RequireClientCertificate)
{
webRequestCertificateProvider = CreateAndOpenCertificateTokenProvider(to, via, channelParameters, timeoutHelper.RemainingTime());
}
else
{
webRequestCertificateProvider = certificateProvider;
}
if (webRequestCertificateProvider != null)
{
token = webRequestCertificateProvider.GetToken(timeoutHelper.RemainingTime());
}
if (ManualAddressing && this.RequireClientCertificate)
{
SecurityUtils.AbortTokenProviderIfRequired(webRequestCertificateProvider);
}
if (token != null)
{
tokenContainer = new SecurityTokenContainer(token);
}
return tokenContainer;
}
void AddServerCertMappingOrSetRemoteCertificateValidationCallback(HttpWebRequest request, EndpointAddress to)
{
Fx.Assert(request != null, "request should not be null.");
if (this.sslCertificateValidator != null)
{
request.ServerCertificateValidationCallback = this.remoteCertificateValidationCallback;
}
else
{
HttpTransportSecurityHelpers.AddServerCertMapping(request, to);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage(FxCop.Category.ReliabilityBasic,
"Reliability104:CaughtAndHandledExceptionsRule",
Justification = "The exception being thrown out comes from user code. Any non-fatal exception should be handled and translated into validation failure(return false).")]
bool RemoteCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
Fx.Assert(sender is HttpWebRequest, "sender should be HttpWebRequest");
Fx.Assert(this.sslCertificateValidator != null, "sslCertificateAuthentidation should not be null.");
try
{
this.sslCertificateValidator.Validate(new X509Certificate2(certificate));
return true;
}
catch (SecurityTokenValidationException ex)
{
FxTrace.Exception.AsInformation(ex);
return false;
}
catch (Exception ex)
{
if (Fx.IsFatal(ex))
{
throw;
}
FxTrace.Exception.AsWarning(ex);
return false;
}
}
class HttpsRequestChannel : HttpRequestChannel
{
SecurityTokenProvider certificateProvider;
HttpsChannelFactory<IRequestChannel> factory;
public HttpsRequestChannel(HttpsChannelFactory<IRequestChannel> factory, EndpointAddress to, Uri via, bool manualAddressing)
: base(factory, to, via, manualAddressing)
{
this.factory = factory;
}
public new HttpsChannelFactory<IRequestChannel> Factory
{
get { return this.factory; }
}
void CreateAndOpenTokenProvider(TimeSpan timeout)
{
if (!ManualAddressing && this.Factory.RequireClientCertificate)
{
this.certificateProvider = Factory.CreateAndOpenCertificateTokenProvider(this.RemoteAddress, this.Via, this.ChannelParameters, timeout);
}
}
void CloseTokenProvider(TimeSpan timeout)
{
if (this.certificateProvider != null)
{
SecurityUtils.CloseTokenProviderIfRequired(this.certificateProvider, timeout);
}
}
void AbortTokenProvider()
{
if (this.certificateProvider != null)
{
SecurityUtils.AbortTokenProviderIfRequired(this.certificateProvider);
}
}
protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
CreateAndOpenTokenProvider(timeoutHelper.RemainingTime());
return base.OnBeginOpen(timeoutHelper.RemainingTime(), callback, state);
}
protected override void OnOpen(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
CreateAndOpenTokenProvider(timeoutHelper.RemainingTime());
base.OnOpen(timeoutHelper.RemainingTime());
}
protected override void OnAbort()
{
AbortTokenProvider();
base.OnAbort();
}
protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
CloseTokenProvider(timeoutHelper.RemainingTime());
return base.OnBeginClose(timeoutHelper.RemainingTime(), callback, state);
}
protected override void OnClose(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
CloseTokenProvider(timeoutHelper.RemainingTime());
base.OnClose(timeoutHelper.RemainingTime());
}
public IAsyncResult BeginBaseGetWebRequest(EndpointAddress to, Uri via, SecurityTokenContainer clientCertificateToken, ref TimeoutHelper timeoutHelper, AsyncCallback callback, object state)
{
return base.BeginGetWebRequest(to, via, clientCertificateToken, ref timeoutHelper, callback, state);
}
public HttpWebRequest EndBaseGetWebRequest(IAsyncResult result)
{
return base.EndGetWebRequest(result);
}
public override HttpWebRequest GetWebRequest(EndpointAddress to, Uri via, ref TimeoutHelper timeoutHelper)
{
SecurityTokenContainer clientCertificateToken = Factory.GetCertificateSecurityToken(this.certificateProvider, to, via, this.ChannelParameters, ref timeoutHelper);
HttpWebRequest request = base.GetWebRequest(to, via, clientCertificateToken, ref timeoutHelper);
this.factory.AddServerCertMappingOrSetRemoteCertificateValidationCallback(request, to);
return request;
}
public override IAsyncResult BeginGetWebRequest(EndpointAddress to, Uri via, ref TimeoutHelper timeoutHelper, AsyncCallback callback, object state)
{
return new GetWebRequestAsyncResult(this, to, via, ref timeoutHelper, callback, state);
}
public override HttpWebRequest EndGetWebRequest(IAsyncResult result)
{
return GetWebRequestAsyncResult.End(result);
}
public override bool WillGetWebRequestCompleteSynchronously()
{
if (!base.WillGetWebRequestCompleteSynchronously())
{
return false;
}
return (this.certificateProvider == null && !Factory.ManualAddressing);
}
internal override void OnWebRequestCompleted(HttpWebRequest request)
{
HttpTransportSecurityHelpers.RemoveServerCertMapping(request);
}
class GetWebRequestAsyncResult : AsyncResult
{
SecurityTokenProvider certificateProvider;
HttpsChannelFactory<IRequestChannel> factory;
HttpsRequestChannel httpsChannel;
HttpWebRequest request;
EndpointAddress to;
Uri via;
TimeoutHelper timeoutHelper;
SecurityTokenContainer tokenContainer;
static AsyncCallback onGetBaseWebRequestCallback = Fx.ThunkCallback(new AsyncCallback(OnGetBaseWebRequestCallback));
static AsyncCallback onGetTokenCallback;
public GetWebRequestAsyncResult(HttpsRequestChannel httpsChannel, EndpointAddress to, Uri via,
ref TimeoutHelper timeoutHelper,
AsyncCallback callback, object state)
: base(callback, state)
{
this.httpsChannel = httpsChannel;
this.to = to;
this.via = via;
this.timeoutHelper = timeoutHelper;
this.factory = httpsChannel.Factory;
this.certificateProvider = httpsChannel.certificateProvider;
if (this.factory.ManualAddressing && this.factory.RequireClientCertificate)
{
this.certificateProvider =
this.factory.CreateAndOpenCertificateTokenProvider(to, via, httpsChannel.ChannelParameters, timeoutHelper.RemainingTime());
}
if (!GetToken())
{
return;
}
if (!GetWebRequest())
{
return;
}
base.Complete(true);
}
bool GetWebRequest()
{
IAsyncResult result = this.httpsChannel.BeginBaseGetWebRequest(to, via, tokenContainer, ref timeoutHelper, onGetBaseWebRequestCallback, this);
if (!result.CompletedSynchronously)
{
return false;
}
this.request = this.httpsChannel.EndBaseGetWebRequest(result);
this.factory.AddServerCertMappingOrSetRemoteCertificateValidationCallback(this.request, this.to);
return true;
}
bool GetToken()
{
if (this.certificateProvider != null)
{
if (onGetTokenCallback == null)
{
onGetTokenCallback = Fx.ThunkCallback(new AsyncCallback(OnGetTokenCallback));
}
IAsyncResult result = this.certificateProvider.BeginGetToken(
timeoutHelper.RemainingTime(), onGetTokenCallback, this);
if (!result.CompletedSynchronously)
{
return false;
}
OnGetToken(result);
}
return true;
}
static void OnGetBaseWebRequestCallback(IAsyncResult result)
{
if (result.CompletedSynchronously)
return;
GetWebRequestAsyncResult thisPtr = (GetWebRequestAsyncResult)result.AsyncState;
Exception completionException = null;
try
{
thisPtr.request = thisPtr.httpsChannel.EndBaseGetWebRequest(result);
thisPtr.factory.AddServerCertMappingOrSetRemoteCertificateValidationCallback(thisPtr.request, thisPtr.to);
}
#pragma warning suppress 56500 // [....], transferring exception to another thread
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
completionException = e;
}
thisPtr.Complete(false, completionException);
}
static void OnGetTokenCallback(IAsyncResult result)
{
if (result.CompletedSynchronously)
return;
GetWebRequestAsyncResult thisPtr = (GetWebRequestAsyncResult)result.AsyncState;
Exception completionException = null;
bool completeSelf;
try
{
thisPtr.OnGetToken(result);
completeSelf = thisPtr.GetWebRequest();
}
#pragma warning suppress 56500 // [....], transferring exception to another thread
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
completeSelf = true;
completionException = e;
}
if (completeSelf)
{
thisPtr.Complete(false, completionException);
}
}
void OnGetToken(IAsyncResult result)
{
SecurityToken token = this.certificateProvider.EndGetToken(result);
if (token != null)
{
this.tokenContainer = new SecurityTokenContainer(token);
}
CloseCertificateProviderIfRequired();
}
void CloseCertificateProviderIfRequired()
{
if (this.factory.ManualAddressing && this.certificateProvider != null)
{
SecurityUtils.AbortTokenProviderIfRequired(this.certificateProvider);
}
}
public static HttpWebRequest End(IAsyncResult result)
{
GetWebRequestAsyncResult thisPtr = AsyncResult.End<GetWebRequestAsyncResult>(result);
return thisPtr.request;
}
}
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V9.Services
{
/// <summary>Settings for <see cref="ConversionAdjustmentUploadServiceClient"/> instances.</summary>
public sealed partial class ConversionAdjustmentUploadServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>
/// Get a new instance of the default <see cref="ConversionAdjustmentUploadServiceSettings"/>.
/// </summary>
/// <returns>A new instance of the default <see cref="ConversionAdjustmentUploadServiceSettings"/>.</returns>
public static ConversionAdjustmentUploadServiceSettings GetDefault() =>
new ConversionAdjustmentUploadServiceSettings();
/// <summary>
/// Constructs a new <see cref="ConversionAdjustmentUploadServiceSettings"/> object with default settings.
/// </summary>
public ConversionAdjustmentUploadServiceSettings()
{
}
private ConversionAdjustmentUploadServiceSettings(ConversionAdjustmentUploadServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
UploadConversionAdjustmentsSettings = existing.UploadConversionAdjustmentsSettings;
OnCopy(existing);
}
partial void OnCopy(ConversionAdjustmentUploadServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>ConversionAdjustmentUploadServiceClient.UploadConversionAdjustments</c> and
/// <c>ConversionAdjustmentUploadServiceClient.UploadConversionAdjustmentsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings UploadConversionAdjustmentsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="ConversionAdjustmentUploadServiceSettings"/> object.</returns>
public ConversionAdjustmentUploadServiceSettings Clone() => new ConversionAdjustmentUploadServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="ConversionAdjustmentUploadServiceClient"/> to provide simple configuration of
/// credentials, endpoint etc.
/// </summary>
internal sealed partial class ConversionAdjustmentUploadServiceClientBuilder : gaxgrpc::ClientBuilderBase<ConversionAdjustmentUploadServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public ConversionAdjustmentUploadServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public ConversionAdjustmentUploadServiceClientBuilder()
{
UseJwtAccessWithScopes = ConversionAdjustmentUploadServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref ConversionAdjustmentUploadServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<ConversionAdjustmentUploadServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override ConversionAdjustmentUploadServiceClient Build()
{
ConversionAdjustmentUploadServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<ConversionAdjustmentUploadServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<ConversionAdjustmentUploadServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private ConversionAdjustmentUploadServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return ConversionAdjustmentUploadServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<ConversionAdjustmentUploadServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return ConversionAdjustmentUploadServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => ConversionAdjustmentUploadServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() =>
ConversionAdjustmentUploadServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => ConversionAdjustmentUploadServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>ConversionAdjustmentUploadService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to upload conversion adjustments.
/// </remarks>
public abstract partial class ConversionAdjustmentUploadServiceClient
{
/// <summary>
/// The default endpoint for the ConversionAdjustmentUploadService service, which is a host of
/// "googleads.googleapis.com" and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default ConversionAdjustmentUploadService scopes.</summary>
/// <remarks>
/// The default ConversionAdjustmentUploadService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="ConversionAdjustmentUploadServiceClient"/> using the default
/// credentials, endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="ConversionAdjustmentUploadServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="ConversionAdjustmentUploadServiceClient"/>.</returns>
public static stt::Task<ConversionAdjustmentUploadServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new ConversionAdjustmentUploadServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="ConversionAdjustmentUploadServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="ConversionAdjustmentUploadServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="ConversionAdjustmentUploadServiceClient"/>.</returns>
public static ConversionAdjustmentUploadServiceClient Create() =>
new ConversionAdjustmentUploadServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="ConversionAdjustmentUploadServiceClient"/> which uses the specified call invoker for
/// remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="ConversionAdjustmentUploadServiceSettings"/>.</param>
/// <returns>The created <see cref="ConversionAdjustmentUploadServiceClient"/>.</returns>
internal static ConversionAdjustmentUploadServiceClient Create(grpccore::CallInvoker callInvoker, ConversionAdjustmentUploadServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
ConversionAdjustmentUploadService.ConversionAdjustmentUploadServiceClient grpcClient = new ConversionAdjustmentUploadService.ConversionAdjustmentUploadServiceClient(callInvoker);
return new ConversionAdjustmentUploadServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC ConversionAdjustmentUploadService client</summary>
public virtual ConversionAdjustmentUploadService.ConversionAdjustmentUploadServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Processes the given conversion adjustments.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [PartialFailureError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual UploadConversionAdjustmentsResponse UploadConversionAdjustments(UploadConversionAdjustmentsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Processes the given conversion adjustments.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [PartialFailureError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<UploadConversionAdjustmentsResponse> UploadConversionAdjustmentsAsync(UploadConversionAdjustmentsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Processes the given conversion adjustments.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [PartialFailureError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<UploadConversionAdjustmentsResponse> UploadConversionAdjustmentsAsync(UploadConversionAdjustmentsRequest request, st::CancellationToken cancellationToken) =>
UploadConversionAdjustmentsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Processes the given conversion adjustments.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [PartialFailureError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer performing the upload.
/// </param>
/// <param name="conversionAdjustments">
/// Required. The conversion adjustments that are being uploaded.
/// </param>
/// <param name="partialFailure">
/// Required. If true, successful operations will be carried out and invalid
/// operations will return errors. If false, all operations will be carried out
/// in one transaction if and only if they are all valid. This should always be
/// set to true.
/// See
/// https://developers.google.com/google-ads/api/docs/best-practices/partial-failures
/// for more information about partial failure.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual UploadConversionAdjustmentsResponse UploadConversionAdjustments(string customerId, scg::IEnumerable<ConversionAdjustment> conversionAdjustments, bool partialFailure, gaxgrpc::CallSettings callSettings = null) =>
UploadConversionAdjustments(new UploadConversionAdjustmentsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
ConversionAdjustments =
{
gax::GaxPreconditions.CheckNotNull(conversionAdjustments, nameof(conversionAdjustments)),
},
PartialFailure = partialFailure,
}, callSettings);
/// <summary>
/// Processes the given conversion adjustments.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [PartialFailureError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer performing the upload.
/// </param>
/// <param name="conversionAdjustments">
/// Required. The conversion adjustments that are being uploaded.
/// </param>
/// <param name="partialFailure">
/// Required. If true, successful operations will be carried out and invalid
/// operations will return errors. If false, all operations will be carried out
/// in one transaction if and only if they are all valid. This should always be
/// set to true.
/// See
/// https://developers.google.com/google-ads/api/docs/best-practices/partial-failures
/// for more information about partial failure.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<UploadConversionAdjustmentsResponse> UploadConversionAdjustmentsAsync(string customerId, scg::IEnumerable<ConversionAdjustment> conversionAdjustments, bool partialFailure, gaxgrpc::CallSettings callSettings = null) =>
UploadConversionAdjustmentsAsync(new UploadConversionAdjustmentsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
ConversionAdjustments =
{
gax::GaxPreconditions.CheckNotNull(conversionAdjustments, nameof(conversionAdjustments)),
},
PartialFailure = partialFailure,
}, callSettings);
/// <summary>
/// Processes the given conversion adjustments.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [PartialFailureError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer performing the upload.
/// </param>
/// <param name="conversionAdjustments">
/// Required. The conversion adjustments that are being uploaded.
/// </param>
/// <param name="partialFailure">
/// Required. If true, successful operations will be carried out and invalid
/// operations will return errors. If false, all operations will be carried out
/// in one transaction if and only if they are all valid. This should always be
/// set to true.
/// See
/// https://developers.google.com/google-ads/api/docs/best-practices/partial-failures
/// for more information about partial failure.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<UploadConversionAdjustmentsResponse> UploadConversionAdjustmentsAsync(string customerId, scg::IEnumerable<ConversionAdjustment> conversionAdjustments, bool partialFailure, st::CancellationToken cancellationToken) =>
UploadConversionAdjustmentsAsync(customerId, conversionAdjustments, partialFailure, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>ConversionAdjustmentUploadService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to upload conversion adjustments.
/// </remarks>
public sealed partial class ConversionAdjustmentUploadServiceClientImpl : ConversionAdjustmentUploadServiceClient
{
private readonly gaxgrpc::ApiCall<UploadConversionAdjustmentsRequest, UploadConversionAdjustmentsResponse> _callUploadConversionAdjustments;
/// <summary>
/// Constructs a client wrapper for the ConversionAdjustmentUploadService service, with the specified gRPC
/// client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">
/// The base <see cref="ConversionAdjustmentUploadServiceSettings"/> used within this client.
/// </param>
public ConversionAdjustmentUploadServiceClientImpl(ConversionAdjustmentUploadService.ConversionAdjustmentUploadServiceClient grpcClient, ConversionAdjustmentUploadServiceSettings settings)
{
GrpcClient = grpcClient;
ConversionAdjustmentUploadServiceSettings effectiveSettings = settings ?? ConversionAdjustmentUploadServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callUploadConversionAdjustments = clientHelper.BuildApiCall<UploadConversionAdjustmentsRequest, UploadConversionAdjustmentsResponse>(grpcClient.UploadConversionAdjustmentsAsync, grpcClient.UploadConversionAdjustments, effectiveSettings.UploadConversionAdjustmentsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callUploadConversionAdjustments);
Modify_UploadConversionAdjustmentsApiCall(ref _callUploadConversionAdjustments);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_UploadConversionAdjustmentsApiCall(ref gaxgrpc::ApiCall<UploadConversionAdjustmentsRequest, UploadConversionAdjustmentsResponse> call);
partial void OnConstruction(ConversionAdjustmentUploadService.ConversionAdjustmentUploadServiceClient grpcClient, ConversionAdjustmentUploadServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC ConversionAdjustmentUploadService client</summary>
public override ConversionAdjustmentUploadService.ConversionAdjustmentUploadServiceClient GrpcClient { get; }
partial void Modify_UploadConversionAdjustmentsRequest(ref UploadConversionAdjustmentsRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Processes the given conversion adjustments.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [PartialFailureError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override UploadConversionAdjustmentsResponse UploadConversionAdjustments(UploadConversionAdjustmentsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_UploadConversionAdjustmentsRequest(ref request, ref callSettings);
return _callUploadConversionAdjustments.Sync(request, callSettings);
}
/// <summary>
/// Processes the given conversion adjustments.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [PartialFailureError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<UploadConversionAdjustmentsResponse> UploadConversionAdjustmentsAsync(UploadConversionAdjustmentsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_UploadConversionAdjustmentsRequest(ref request, ref callSettings);
return _callUploadConversionAdjustments.Async(request, callSettings);
}
}
}
| |
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 Polacca.Api.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>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <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 factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private 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 to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified 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) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), 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="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Timers;
namespace HBus.Nodes
{
/// <summary>
/// Generic scheduler
/// Execute schedules at specific times
/// </summary>
public class Scheduler
{
private const int TimerPeriod = 1000;
private static Scheduler _scheduler;
private IList<ISchedule> _schedules;
//private readonly Timer _timer;
private Thread _thread;
private DateTime _lastTime;
private uint _time;
private bool _disable;
private bool _pause;
private int _index;
private Scheduler(int timePeriod = 0)
{
_schedules = new List<ISchedule>();
//Activate timer for output updates
_disable = false;
_pause = true;
//_timer = new Timer(timePeriod > 0 ? timePeriod : TimerPeriod);
//_timer.Elapsed += TimerOnElapsed;
//_timer.Start();
_time = 0;
}
public static Scheduler GetScheduler()
{
return _scheduler ?? (_scheduler = new Scheduler());
}
public void Start()
{
_disable = false;
_pause = false;
_index = 0;
_thread = new Thread(() =>
{
try
{
while (!_disable)
{
var now = DateTime.Now;
if (_lastTime.AddMilliseconds(TimerPeriod) <= now)
{
if (!_pause)
TimerOnElapsed(this, null);
_lastTime = DateTime.Now; //now;
}
Thread.Sleep(TimerPeriod - 10);
}
}
catch (Exception)
{
//Exit
return;
}
});
//_timer.Start();
_thread.Start();
}
public void Stop()
{
_disable = true;
//_timer.Stop();
//Thread.Sleep(TimerPeriod);
if (_thread != null)
{
_thread.Abort();
_thread.Join();
}
}
public void Clear()
{
//if (_disable) return;
//_timer.Enabled = false;
_pause = true;
_index = 0;
_schedules.Clear();
//_timer.Enabled = true;
_pause = false;
_time = 0;
}
public void AddSchedule(ISchedule schedule)
{
//if (_disable) return;
//_timer.Enabled = false;
_pause = true;
_schedules.Add(schedule);
//_timer.Enabled = true;
_pause = false;
}
public void RemoveSchedule(ISchedule schedule)
{
//if (_disable) return;
//_timer.Stop();
_pause = true;
_schedules = _schedules.Where(s => s.Name != schedule.Name && s.Date != schedule.Date).ToList();
//_timer.Start();
_pause = false;
}
public bool HasSchedules(string name)
{
var schedules = _schedules.Any(s => s.Name == name);
return schedules;
}
public void Purge(string name = null)
{
//if (_disable) return;
//Leaves only new schedules
var schedules = new List<ISchedule>();
foreach (var s in _schedules)
{
if (s.Name == name || string.IsNullOrEmpty(name) && s.Date <= DateTime.Now)
{
//Schedule expired: reschedule if necessary
switch (s.Type)
{
case ScheduleTypes.Day:
s.Date = s.Date.AddDays(1);
break;
case ScheduleTypes.Week:
s.Date = s.Date.AddDays(7);
break;
case ScheduleTypes.Month:
s.Date = s.Date.AddMonths(1);
break;
case ScheduleTypes.Year:
s.Date = s.Date.AddYears(1);
break;
case ScheduleTypes.Period:
s.Date = DateTime.Now.AddSeconds(s.Interval);
break;
default:
s.Date = DateTime.MinValue;
break;
}
}
//keep only future schedules
if (s.Date > DateTime.Now)
schedules.Add(s);
}
_schedules = schedules;
//_schedules = _schedules.Where(s => !(s.Date < DateTime.Now && (s.Name == name || string.IsNullOrEmpty(name)))).ToList();
}
public bool IsEmpty
{
get { return !_schedules.Any(); }
}
public uint TimeIndex { get { return _time; } }
#region events
public Action<uint> OnTimeElapsed;
public Action<IEnumerable<ISchedule>> SchedulerHandler { get; set; }
public void TimerOnElapsed(object sender, ElapsedEventArgs e)
{
//_timer.Enabled = false;
var now = DateTime.Now;
lock (_schedules)
{
for (var index = 0; index < _schedules.Count; index++)
{
var schedule = _schedules[index];
if (schedule.Date <= now)
{
schedule.Trigger();
switch (schedule.Type) //Reschedule if necessary
{
case ScheduleTypes.Day:
schedule.Date = schedule.Date.AddDays(1);
break;
case ScheduleTypes.Week:
schedule.Date = schedule.Date.AddDays(7);
break;
case ScheduleTypes.Month:
schedule.Date = schedule.Date.AddMonths(1);
break;
case ScheduleTypes.Year:
schedule.Date = schedule.Date.AddYears(1);
break;
case ScheduleTypes.Period:
schedule.Date = DateTime.Now.AddSeconds(schedule.Interval);
break;
default:
_schedules.Remove(schedule);
break;
}
}
//_index = _index < (_schedules.Count - 1) ? _index + 1 : 0;
}
}
/*
var expiredSchedules = _schedules.Where(s => s.Date < now).ToList();
if (expiredSchedules.Count > 0)
{
if (SchedulerHandler != null)
{
SchedulerHandler(expiredSchedules);
}
else
{
foreach (var schedule in expiredSchedules)
{
schedule.Trigger();
}
//foreach (PinSchedule schedule in expiredSchedules.Where(s => s is PinSchedule))
//{
// schedule.Pin.Change(schedule.Value);
//}
//foreach (DeviceSchedule schedule in expiredSchedules.Where(s => s is DeviceSchedule))
//{
// schedule.Device.ExecuteAction(schedule.Action);
//}
}
//_schedules = _schedules.Where(s => s.Date > now).ToList();
Purge();
}
*/
//Increment time index
_time++;
if (OnTimeElapsed != null)
OnTimeElapsed(_time);
//_timer.Enabled = true;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using OpenTK.Compute.CL10;
using System.Text;
using System.Runtime.InteropServices;
namespace scallion
{
public unsafe class CLContext
{
public readonly IntPtr DeviceId;
public readonly CLDeviceInfo Device;
public readonly IntPtr ContextId;
public readonly IntPtr CommandQueueId;
public unsafe CLContext(IntPtr deviceId)
{
DeviceId = deviceId;
Device = new CLDeviceInfo(DeviceId);
ErrorCode error;
ErrorCode[] errors = new ErrorCode[1];
ContextId = CL.CreateContext(null, 1, new IntPtr[] { DeviceId }, IntPtr.Zero, IntPtr.Zero, errors);
if (errors[0] != ErrorCode.Success) throw new System.InvalidOperationException("Error calling CreateContext");
CommandQueueId = CL.CreateCommandQueue(ContextId, DeviceId, (CommandQueueFlags)0, &error);
if (error != ErrorCode.Success) throw new System.InvalidOperationException(String.Format("Error calling CreateCommandQueue: {0}",error));
}
public IntPtr CreateAndCompileProgram(string source)
{
ErrorCode error;
IntPtr programId;
programId = CL.CreateProgramWithSource(ContextId, 1, new string[] { source }, null, &error);
if (error != ErrorCode.Success) throw new System.InvalidOperationException(String.Format("Error calling CreateProgramWithSource: {0}",error));
error = (ErrorCode)CL.BuildProgram(programId, 0, (IntPtr[])null, null, IntPtr.Zero, IntPtr.Zero);
if (error != ErrorCode.Success)
{
uint parmSize;
CL.GetProgramBuildInfo(programId, DeviceId, ProgramBuildInfo.ProgramBuildLog, IntPtr.Zero, IntPtr.Zero, (IntPtr*)&parmSize);
byte[] value = new byte[parmSize];
fixed (byte* valuePtr = value)
{
error = (ErrorCode)CL.GetProgramBuildInfo(programId, DeviceId, ProgramBuildInfo.ProgramBuildLog, new IntPtr(&parmSize), new IntPtr(valuePtr), (IntPtr*)IntPtr.Zero.ToPointer());
}
if (error != ErrorCode.Success) throw new System.InvalidOperationException(String.Format("Error calling GetProgramBuildInfo: {0}",error));
throw new System.InvalidOperationException(Encoding.ASCII.GetString(value).Trim('\0'));
}
return programId;
}
public CLKernel CreateKernel(IntPtr programId, string kernelName)
{
return new CLKernel(DeviceId, ContextId, CommandQueueId, programId, kernelName);
}
public CLBuffer<T> CreateBuffer<T>(MemFlags memFlags, T[] data) where T : struct
{
return new CLBuffer<T>(ContextId, CommandQueueId, memFlags, data);
}
private bool disposed = false;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing) { /*Dispose managed resources*/ }
CL.ReleaseCommandQueue(CommandQueueId);
CL.ReleaseContext(ContextId);
}
}
~CLContext()
{
Dispose(false);
}
}
public unsafe class CLBuffer<T> : IDisposable where T : struct
{
public GCHandle Handle { get; private set; }
public readonly IntPtr BufferId;
public readonly IntPtr CommandQueueId;
public readonly bool IsDevice64Bit;
public readonly int BufferSize;
private T[] _data;
public T[] Data
{
get { return _data;}
set
{
if (_data == value) return;
if (Handle.IsAllocated) Handle.Free();
_data = value;
Handle = GCHandle.Alloc(_data, GCHandleType.Pinned);
if (BufferSize != Marshal.SizeOf(typeof(T)) * _data.Length) throw new System.Exception("Data's length is not the same as the original buffer.");
}
}
public CLBuffer(IntPtr contextId, IntPtr commandQueueId, MemFlags memFlags, T[] data)
{
CommandQueueId = commandQueueId;
ErrorCode error = ErrorCode.Success;
BufferSize = Marshal.SizeOf(typeof(T)) * data.Length;
Data = data;
BufferId = CL.CreateBuffer(contextId, memFlags, new IntPtr(BufferSize), Handle.AddrOfPinnedObject(), &error);
if (error != ErrorCode.Success) throw new System.InvalidOperationException(String.Format("Error calling CreateBuffer: {0}",error));
}
public void EnqueueWrite()
{
EnqueueWrite(false);
}
public void EnqueueRead()
{
EnqueueRead(false);
}
public void EnqueueWrite(bool async)
{
ErrorCode error;
error = (ErrorCode)CL.EnqueueWriteBuffer(CommandQueueId, BufferId, !async, new IntPtr(0), new IntPtr(BufferSize),
Handle.AddrOfPinnedObject(), 0, (IntPtr*)IntPtr.Zero.ToPointer(), (IntPtr*)IntPtr.Zero.ToPointer());
if (error != ErrorCode.Success) throw new System.InvalidOperationException(String.Format("Error calling EnqueueWriteBuffer: {0}",error));
}
public void EnqueueRead(bool async)
{
ErrorCode error;
error = (ErrorCode)CL.EnqueueReadBuffer(CommandQueueId, BufferId, !async, new IntPtr(0), new IntPtr(BufferSize),
Handle.AddrOfPinnedObject(), 0, (IntPtr*)IntPtr.Zero.ToPointer(), (IntPtr*)IntPtr.Zero.ToPointer());
if (error != ErrorCode.Success) throw new System.InvalidOperationException(String.Format("Error calling EnqueueReadBuffer: {0}",error));
}
private bool disposed = false;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing) { /*Dispose managed resources*/ }
// Dispose unmanaged resources.
CL.ReleaseMemObject(BufferId);
Handle.Free();
}
}
~CLBuffer()
{
Dispose(false);
}
}
public unsafe class CLKernel
{
public readonly IntPtr KernelId;
public readonly IntPtr ContextId;
public readonly IntPtr CommandQueueId;
public readonly IntPtr ProgramId;
public readonly string KernelName;
public readonly IntPtr DeviceId;
public CLKernel(IntPtr deviceId, IntPtr contextId, IntPtr commandQueueId, IntPtr programId, string kernelName)
{
DeviceId = deviceId;
ContextId = contextId;
CommandQueueId = commandQueueId;
ProgramId = programId;
KernelName = kernelName;
ErrorCode error;
KernelId = CL.CreateKernel(ProgramId, KernelName, out error);
if (error != ErrorCode.Success) throw new System.InvalidOperationException(String.Format("Error calling CreateKernel: {0}",error));
}
public void EnqueueNDRangeKernel(int globalWorkSize, int localWorkSize)
{
ErrorCode error;
IntPtr pglobalWorkSize = new IntPtr(globalWorkSize);
IntPtr plocalWorkSize = new IntPtr(localWorkSize);
error = (ErrorCode)CL.EnqueueNDRangeKernel(CommandQueueId, KernelId, 1, null, &pglobalWorkSize, &plocalWorkSize, 0, null, null);
if (error != ErrorCode.Success) throw new System.InvalidOperationException(String.Format("Error calling EnqueueNDRangeKernel: {0}",error));
}
public void SetKernelArgLocal(int argIndex, int size)
{
ErrorCode error;
error = (ErrorCode)CL.SetKernelArg(KernelId, argIndex, new IntPtr(size), IntPtr.Zero);
if (error != ErrorCode.Success) throw new System.InvalidOperationException(String.Format("Error calling SetKernelArg: {0}",error));
}
public void SetKernelArg<T>(int argIndex, T value) where T : struct
{
ErrorCode error;
var handle = GCHandle.Alloc(value, GCHandleType.Pinned);
int size = Marshal.SizeOf(typeof(T));
error = (ErrorCode)CL.SetKernelArg(KernelId, argIndex, new IntPtr(size), handle.AddrOfPinnedObject());
handle.Free();
if (error != ErrorCode.Success) throw new System.InvalidOperationException(String.Format("Error calling SetKernelArg: {0}",error));
}
public void SetKernelArg<T>(int argIndex, CLBuffer<T> value) where T : struct
{
ErrorCode error;
IntPtr bufferId = value.BufferId;
error = (ErrorCode)CL.SetKernelArg(KernelId, argIndex, new IntPtr(sizeof(IntPtr)), new IntPtr(&bufferId));
if (error != ErrorCode.Success) throw new System.InvalidOperationException(String.Format("Error calling SetKernelArg: {0}",error));
}
public ulong KernelPreferredWorkGroupSizeMultiple
{
get
{
ErrorCode error;
ulong ret = 0;
error = (ErrorCode)CL.GetKernelWorkGroupInfo(KernelId, DeviceId, KernelWorkGroupInfo.KernelPreferredWorkGroupSizeMultiple, new IntPtr(sizeof(IntPtr)), ref ret, (IntPtr*)IntPtr.Zero.ToPointer());
if (error != ErrorCode.Success) throw new System.InvalidOperationException(String.Format("Error calling GetKernelWorkGroupInfo: {0}",error));
return ret;
}
}
private bool disposed = false;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing) { /*Dispose managed resources*/ }
CL.ReleaseKernel(KernelId);
}
}
~CLKernel()
{
Dispose(false);
}
}
}
| |
// ===========================================================
// 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.
// ===========================================================
//TODO: Interesting reading http://www.communicraft.com/en/blog/BlogArticle/lock_free_dictionary
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using ConcurrencyHelpers.Interfaces;
using ConcurrencyHelpers.Utils;
namespace ConcurrencyHelpers.Containers.Asyncs
{
public class AsyncLockFreeDictionary<TKey, TValue> : IDictionary<TKey, TValue>
{
// ReSharper disable once PrivateFieldCanBeConvertedToLocalVariable
private readonly ITimer _timer;
private readonly LockFreeItem<Dictionary<TKey, TValue>> _dictionary;
private readonly Dictionary<TKey, TValue> _trustedSource;
private readonly LockFreeQueue<AsyncCollectionRequest<KeyValuePair<TKey, TValue>>> _requestsQueue;
public ConcurrentInt64 MaxMessagesPerCycle { get; private set; }
private ConcurrentInt64 _opverlappingChecker;
public ITimer Timer
{
get
{
return _timer;
}
}
public AsyncLockFreeDictionary(ITimer timer = null) :
this(new Dictionary<TKey, TValue>(), timer)
{
}
public AsyncLockFreeDictionary(IDictionary<TKey, TValue> dictionary, ITimer timer = null)
{
MaxMessagesPerCycle = new ConcurrentInt64(100);
_opverlappingChecker = new ConcurrentInt64();
_timer = timer ?? new SystemTimer(10, 10);
_dictionary = new LockFreeItem<Dictionary<TKey, TValue>>(new Dictionary<TKey, TValue>(dictionary))
{
Data =
new Dictionary
<TKey, TValue>()
};
_trustedSource = new Dictionary<TKey, TValue>();
_requestsQueue = new LockFreeQueue<AsyncCollectionRequest<KeyValuePair<TKey, TValue>>>();
_timer.Elapsed += OnSynchronize;
_timer.Start();
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
var data = _dictionary.Data;
var keys = new List<TKey>(data.Keys);
return new AsyncDictionaryLockFreeEnumerator<TKey,TValue>(keys, this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public void TryAdd(KeyValuePair<TKey, TValue> item,
Func<KeyValuePair<TKey, TValue>, KeyValuePair<TKey, TValue>, KeyValuePair<TKey, TValue>> tryFunction = null)
{
if (item.Key.Equals(default(TKey))) throw new ArgumentException("Item key cannot be null");
_requestsQueue.Enqueue(new AsyncCollectionRequest<KeyValuePair<TKey, TValue>>
{
Data = item,
EventType = AsyncCollectionEventType.TryAdd,
TryFunc = tryFunction
});
}
public void Add(KeyValuePair<TKey, TValue> item)
{
TryAdd(item);
}
public void Clear()
{
_requestsQueue.Enqueue(new AsyncCollectionRequest<KeyValuePair<TKey, TValue>>
{
Data = null,
EventType = AsyncCollectionEventType.TryAdd,
TryFunc = null
});
}
public bool Contains(KeyValuePair<TKey, TValue> item)
{
return _dictionary.Data.Contains(item);
}
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
((ICollection<KeyValuePair<TKey, TValue>>)_dictionary.Data).CopyTo(array, arrayIndex);
}
public bool Remove(KeyValuePair<TKey, TValue> item)
{
return Remove(item.Key);
}
public int Count
{
get
{
return _dictionary.Data.Count;
}
}
public bool IsReadOnly { get { return false; } }
public bool ContainsKey(TKey key)
{
return _dictionary.Data.ContainsKey(key);
}
public void Add(TKey key, TValue value)
{
Add(new KeyValuePair<TKey, TValue>(key, value));
}
public void TryAdd(TKey key, TValue value,
Func<KeyValuePair<TKey, TValue>, KeyValuePair<TKey, TValue>, KeyValuePair<TKey, TValue>> tryFunction = null)
{
TryAdd(new KeyValuePair<TKey, TValue>(key, value), tryFunction);
}
public bool Remove(TKey key)
{
_requestsQueue.Enqueue(new AsyncCollectionRequest<KeyValuePair<TKey, TValue>>
{
Data = key,
EventType = AsyncCollectionEventType.Remove,
TryFunc = null
});
return true;
}
public bool TryGetValue(TKey key, out TValue value)
{
value = default(TValue);
try
{
var dict = _dictionary.Data;
if (!dict.ContainsKey(key)) return false;
value = dict[key];
return true;
}
catch (Exception)
{
}
return false;
}
public TValue this[TKey key]
{
get
{
var dict = _dictionary.Data;
return dict[key];
}
set
{
Add(key, value);
}
}
public ICollection<TKey> Keys
{
get
{
var dict = _dictionary.Data;
return new List<TKey>(dict.Keys);
}
}
public ICollection<TValue> Values
{
get
{
var dict = _dictionary.Data;
return new List<TValue>(dict.Values);
}
}
private void OnSynchronize(object sender, ElapsedTimerEventArgs e)
{
var changesMade = false;
if (1 == (int)_opverlappingChecker) return;
_opverlappingChecker = 1;
try
{
var maxMessages = (int)MaxMessagesPerCycle;
foreach (var request in _requestsQueue.Dequeue(100))
{
if (HandledEvent(request))
{
changesMade = true;
}
maxMessages--;
if (maxMessages <= 0) break;
}
if (changesMade)
{
var newData = new Dictionary<TKey, TValue>(_trustedSource);
_dictionary.Data = newData;
}
}
finally
{
_opverlappingChecker = 0;
}
}
private bool HandledEvent(AsyncCollectionRequest<KeyValuePair<TKey, TValue>> request)
{
var changesMade = false;
if (request.EventType == AsyncCollectionEventType.Clear)
{
changesMade = true;
_trustedSource.Clear();
// ReSharper disable once ConditionIsAlwaysTrueOrFalse
return changesMade;
}
switch (request.EventType)
{
case (AsyncCollectionEventType.Remove):
if (_trustedSource.ContainsKey((TKey)request.Data))
{
changesMade = true;
_trustedSource.Remove((TKey)request.Data);
}
break;
case (AsyncCollectionEventType.TryUpdate):
case (AsyncCollectionEventType.TryAdd):
{
var kvp = (KeyValuePair<TKey, TValue>)request.Data;
if (!_trustedSource.ContainsKey(kvp.Key))
{
if (AsyncCollectionEventType.TryAdd == request.EventType)
{
changesMade = true;
_trustedSource.Add(kvp.Key, kvp.Value);
}
}
else
{
changesMade = true;
if (request.TryFunc == null)
{
_trustedSource[kvp.Key] = kvp.Value;
}
else
{
var currentValue = _trustedSource[kvp.Key];
var selectedValue = request.TryFunc(new KeyValuePair<TKey, TValue>(kvp.Key, currentValue), kvp);
_trustedSource[kvp.Key] = selectedValue.Value;
}
}
}
break;
}
return changesMade;
}
~AsyncLockFreeDictionary()
{
// Finalizer calls Dispose(false)
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// free managed resources
if (_timer != null)
{
_timer.Dispose();
}
if (_dictionary != null)
{
_dictionary.Dispose();
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Drawing;
using System.Linq;
using Appccelerate.EventBroker;
using Appccelerate.EventBroker.Handlers;
using Appccelerate.Events;
using Eto.Drawing;
using Eto.Forms;
using Eto.Gl;
using Ninject;
using Ninject.Extensions.Logging;
using OpenTK.Graphics.OpenGL;
using SharpFlame.Bitmaps;
using SharpFlame.Core.Domain;
using SharpFlame.Generators;
using SharpFlame.Core;
using SharpFlame.Graphics.OpenGL;
using SharpFlame.Mapping;
using SharpFlame.Mapping.Tiles;
using SharpFlame.MouseTools;
using SharpFlame.Settings;
using Size = Eto.Drawing.Size;
namespace SharpFlame.Gui.Sections
{
public class TextureTab : Panel
{
private CheckBox chkTexture;
private CheckBox chkOrientation;
private CheckBox chkRandomize;
private CheckBox chkDisplayTileTypes;
private CheckBox chkDisplayTileNumbers;
private Button btnCircular;
private Button btnSquare;
private ImageView btnRotateAntiClockwise;
private ImageView btnRotateClockwise;
private ImageView btnFlipX;
private NumericUpDown nudRadius;
private RadioButtonList rblTerrainModifier;
private DropDown cbTileset;
private ComboBox cbTileType;
private Scrollable scrollTextureView;
[Inject]
private ILogger Logger { get; set; }
private Map map;
[Inject]
internal SettingsManager Settings { get; set; }
[Inject]
internal ToolOptions ToolOptions { get; set; }
[Inject]
internal IEventBroker EventBroker { get; set; }
[Inject]
internal DefaultGenerator DefaultGenerator { get; set; }
internal GLSurface GLSurface { get; set; }
private XYInt TextureCount { get; set; }
[EventSubscription(EventTopics.OnTextureDrawLater, typeof(OnPublisher))]
public void HandleTextureDrawLater(object sender, EventArgs e)
{
//really we should draw later....... use a timer.
this.DrawTexturesView();
}
[EventSubscription(EventTopics.OnMapLoad, typeof(OnPublisher))]
public void HandleMapLoad(Map newMap)
{
this.map = newMap;
}
public TextureTab()
{
this.TextureCount = new XYInt(0, 0);
var layout = new DynamicLayout {Padding = Padding.Empty, Spacing = Size.Empty};
this.cbTileset = TextureComboBox();
var row = layout.AddSeparateRow(null,
new Label {Text = "Tileset:", VerticalAlign = VerticalAlign.Middle},
this.cbTileset,
null);
row.Table.Visible = false;
layout.BeginVertical();
this.nudRadius = new NumericUpDown {
Size = new Size(-1, -1),
MinValue = 0,
MaxValue = Constants.MapMaxSize,
Value = ToolOptions.Textures.Brush.Radius
};
this.btnCircular = new Button {Text = "Circular", Enabled = false};
this.btnSquare = new Button {Text = "Square"};
layout.AddRow(null,
new Label {Text = "Radius:", VerticalAlign = VerticalAlign.Middle},
this.nudRadius,
this.btnCircular,
this.btnSquare,
null);
layout.EndVertical();
var textureOrientationLayout = new DynamicLayout {Padding = Padding.Empty, Spacing = Size.Empty};
textureOrientationLayout.Add(null);
textureOrientationLayout.BeginHorizontal();
textureOrientationLayout.AddRow(null, chkTexture = new CheckBox {Text = "Set Texture"}, null);
textureOrientationLayout.EndHorizontal();
textureOrientationLayout.BeginHorizontal();
textureOrientationLayout.AddRow(null, chkOrientation = new CheckBox {Text = "Set Orientation", Checked = true}, null);
textureOrientationLayout.EndHorizontal();
textureOrientationLayout.Add(null);
var buttonsRandomize = new DynamicLayout {Padding = Padding.Empty, Spacing = Size.Empty};
buttonsRandomize.Add(null);
buttonsRandomize.BeginVertical();
this.btnRotateAntiClockwise = MakeBtnRotateAntiClockwise();
this.btnRotateClockwise = MakeBtnRotateClockwise();
this.btnFlipX = MakeBtnFlipX();
buttonsRandomize.AddRow(null,
TableLayout.AutoSized(this.btnRotateAntiClockwise),
TableLayout.AutoSized(this.btnRotateClockwise),
TableLayout.AutoSized(this.btnFlipX),
null);
buttonsRandomize.EndVertical();
buttonsRandomize.BeginVertical();
this.chkRandomize = new CheckBox {Text = "Randomize"};
buttonsRandomize.AddRow(null, this.chkRandomize, null);
buttonsRandomize.EndVertical();
buttonsRandomize.Add(null);
this.rblTerrainModifier = new RadioButtonList
{
Spacing = new Size(0, 0),
Orientation = RadioButtonListOrientation.Vertical,
Items =
{
new ListItem {Text = "Ignore Terrain"},
new ListItem {Text = "Reinterpret"},
new ListItem {Text = "Remove Terrain"}
},
SelectedIndex = 1
};
row = layout.AddSeparateRow(null,
textureOrientationLayout,
buttonsRandomize,
TableLayout.AutoSized(this.rblTerrainModifier),
null);
row.Table.Visible = false;
var mainLayout = new DynamicLayout {Padding = Padding.Empty, Spacing = Size.Empty};
var tileTypeCombo = new DynamicLayout();
tileTypeCombo.BeginHorizontal();
tileTypeCombo.Add(new Label
{
Text = "Tile Type:",
VerticalAlign = VerticalAlign.Middle
});
tileTypeCombo.Add(cbTileType = TileTypeComboBox());
tileTypeCombo.EndHorizontal();
var tileTypeCheckBoxes = new DynamicLayout();
tileTypeCheckBoxes.BeginHorizontal();
this.chkDisplayTileTypes = new CheckBox {Text = "Display Tile Types"};
tileTypeCheckBoxes.Add(this.chkDisplayTileTypes);
tileTypeCheckBoxes.Add(null);
this.chkDisplayTileNumbers = new CheckBox {Text = "Display Tile Numbers"};
tileTypeCheckBoxes.Add(this.chkDisplayTileNumbers);
tileTypeCheckBoxes.EndHorizontal();
var tileTypeSetter = new DynamicLayout {Padding = Padding.Empty, Spacing = Size.Empty};
tileTypeSetter.BeginHorizontal();
tileTypeSetter.Add(null);
tileTypeSetter.Add(tileTypeCombo);
tileTypeSetter.Add(null);
tileTypeSetter.EndHorizontal();
tileTypeSetter.BeginHorizontal();
tileTypeSetter.Add(null);
tileTypeSetter.Add(tileTypeCheckBoxes);
tileTypeSetter.Add(null);
tileTypeSetter.EndHorizontal();
mainLayout.Add(layout);
this.GLSurface = new GLSurface();
this.scrollTextureView = new Scrollable {Content = this.GLSurface};
mainLayout.Add(this.scrollTextureView, true, true);
mainLayout.Add(tileTypeSetter);
//mainLayout.Add();
this.scrollTextureView.ExpandContentHeight = false;
this.scrollTextureView.ExpandContentWidth = false;
//this.scrollTextureView.UpdateScrollSizes();
//this.scrollTextureView.minim
this.scrollTextureView.SizeChanged += scrollTextureView_SizeChanged;
this.scrollTextureView.Scroll += scrollTextureView_Scroll;
this.scrollTextureView.MouseWheel += ScrollTextureView_MouseWheel;
Content = mainLayout;
this.GLSurface.GLInitalized += TextureView_OnGLControlInitialized;
SetupEventHandlers();
}
protected override void OnPreLoad(EventArgs e)
{
this.ParentWindow.GotFocus +=ParentWindow_GotFocus;
base.OnPreLoad(e);
}
void ParentWindow_GotFocus(object sender, EventArgs e)
{
this.DrawTexturesView();
}
private void SetupEventHandlers()
{
Settings.TilesetDirectories.CollectionChanged += (sender, e) =>
{
if( !this.GLSurface.IsInitialized )
{
return;
}
try
{
if( e.Action == NotifyCollectionChangedAction.Add )
{
foreach( var item in e.NewItems )
{
var result = App.LoadTilesets((string)item);
if( result.HasProblems || result.HasWarnings )
{
App.StatusDialog = new Gui.Dialogs.Status(result);
App.StatusDialog.Show();
Settings.TilesetDirectories.Remove((string)item);
}
}
}
else if( e.Action == NotifyCollectionChangedAction.Remove )
{
foreach( var item in e.OldItems )
{
var found = App.Tilesets.Where(w => w.Directory.StartsWith((string)item)).ToList();
foreach( var foundItem in found )
{
App.Tilesets.Remove(foundItem);
}
}
}
}
catch( Exception ex )
{
Logger.Error(ex, "Got an exception while loading tilesets.");
}
};
}
void scrollTextureView_Scroll(object sender, ScrollEventArgs e)
{
this.DrawTexturesView();
}
void scrollTextureView_SizeChanged(object sender, EventArgs e)
{
this.DrawTexturesView();
}
private void ScrollTextureView_MouseWheel(object sender, MouseEventArgs e)
{
this.DrawTexturesView();
}
/// <summary>
/// Sets the Bindings to uiOptions.Textures;
/// </summary>
protected override void OnLoadComplete(EventArgs lcEventArgs)
{
base.OnLoadComplete(lcEventArgs);
Textures texturesOptions = ToolOptions.Textures;
// Circular / Square Button
btnCircular.Click += (sender, e) =>
{
btnCircular.Enabled = false;
btnSquare.Enabled = true;
texturesOptions.Brush.Shape = ShapeType.Circle;
};
btnSquare.Click += (sender, e) =>
{
btnSquare.Enabled = false;
btnCircular.Enabled = true;
texturesOptions.Brush.Shape = ShapeType.Square;
};
nudRadius.ValueChanged += delegate
{
texturesOptions.Brush.Radius = nudRadius.Value;
};
// Orientation buttons
btnRotateClockwise.MouseDown += delegate
{
texturesOptions.TextureOrientation.RotateClockwise();
DrawTexturesView();
};
btnRotateAntiClockwise.MouseDown += delegate
{
texturesOptions.TextureOrientation.RotateAntiClockwise();
DrawTexturesView();
};
btnFlipX.MouseDown += delegate
{
texturesOptions.TextureOrientation.FlipX();
DrawTexturesView();
};
// Checkboxes
chkTexture.Bind(r => r.Checked, texturesOptions, t => t.SetTexture);
chkOrientation.Bind(r => r.Checked, texturesOptions, t => t.SetOrientation);
chkRandomize.Bind(r => r.Checked, texturesOptions, t => t.Randomize);
// RadiobuttonList
rblTerrainModifier.SelectedIndexChanged += delegate
{
texturesOptions.TerrainMode = (TerrainMode)rblTerrainModifier.SelectedIndex;
};
// Read Tileset Combobox
App.Tilesets.CollectionChanged += (sender, e) =>
{
if( e.Action == NotifyCollectionChangedAction.Add )
{
var list = new List<IListItem>();
foreach( var item in e.NewItems )
{
list.Add((IListItem)item);
}
cbTileset.Items.AddRange(list);
cbTileset.Visible = false;
cbTileset.Visible = true;
}
else if( e.Action == NotifyCollectionChangedAction.Remove )
{
foreach( var item in e.OldItems )
{
cbTileset.Items.Remove((IListItem)item);
}
cbTileset.Visible = false;
cbTileset.Visible = true;
}
};
ToolOptions.Textures.TilesetNumChanged += delegate
{
if (cbTileset.SelectedIndex == ToolOptions.Textures.TilesetNum) {
return;
}
cbTileset.SelectedIndex = ToolOptions.Textures.TilesetNum;
};
// Bind tileset combobox.
cbTileset.Bind(r => r.SelectedIndex, texturesOptions, t => t.TilesetNum);
cbTileset.SelectedIndexChanged += delegate
{
var tilesetNum = texturesOptions.TilesetNum;
if( map != null &&
map.Tileset != App.Tilesets[tilesetNum] )
{
map.Tileset = App.Tilesets[tilesetNum];
map.TileType_Reset();
map.SetPainterToDefaults();
map.SectorGraphicsChanges.SetAllChanged();
this.EventBroker.UpdateMap(this);
this.EventBroker.DrawLater(this);
}
DrawTexturesView();
};
chkDisplayTileTypes.CheckedChanged += delegate
{
DrawTexturesView();
};
chkDisplayTileNumbers.CheckedChanged += delegate
{
DrawTexturesView();
};
this.GLSurface.MouseDown += (sender, e) =>
{
if( ToolOptions.Textures.TilesetNum == -1 )
{
return;
}
var args = (MouseEventArgs)e;
var x = (int)Math.Floor(args.Location.X / 64);
var y = (int)Math.Floor(args.Location.Y / 64);
var tile = x + (y * TextureCount.X);
if( tile >= App.Tilesets[ToolOptions.Textures.TilesetNum].Tiles.Count )
{
return;
}
ToolOptions.Textures.SelectedTile = tile;
if (map != null) {
cbTileType.SelectedIndex = (int)map.TileTypeNum[tile];
}
DrawTexturesView();
};
cbTileType.SelectedIndexChanged += delegate
{
if (map == null) {
MessageBox.Show("Please open a map before changing tile types.");
return;
}
if (ToolOptions.Textures.SelectedTile == 0) {
MessageBox.Show("Select a tile to modify first.");
return;
}
map.TileTypeNum[ToolOptions.Textures.SelectedTile] = (byte)cbTileType.SelectedIndex;
DrawTexturesView();
};
// Set Mousetool, when we are shown.
this.Shown += (sender, args) =>
{
ToolOptions.MouseTool = MouseTool.TextureBrush;
};
// trigger the redraw on the scroll texture view scrollable.
//this.GLSurface.Resize += (sender, args) =>
// {
// DrawTexturesView();
// };
}
private void DrawTexturesView()
{
if( !GLSurface.IsInitialized )
{
return;
}
this.GLSurface.MakeCurrent();
if( ToolOptions.Textures.TilesetNum == -1 )
{
GL.ClearColor(OpenTK.Graphics.Color4.DimGray);
GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
GL.Flush();
this.GLSurface.SwapBuffers();
return;
}
var tileset = App.Tilesets[ToolOptions.Textures.TilesetNum];
var glSize = new Size (0, 0);
var columns = (int)(Math.Floor(scrollTextureView.ClientSize.Width / 64.0D));
this.TextureCount = new XYInt
{
X = columns,
Y = (int)(Math.Ceiling((double)tileset.Tiles.Count / columns))
};
var maxHeight = this.TextureCount.Y * 64;
if (maxHeight >= scrollTextureView.Size.Height)
{
glSize = new Size(scrollTextureView.ClientSize.Width, maxHeight);
//GLSurface.GLSize = glSize;
GLSurface.Size = glSize;
}
else
{
this.TextureCount = new XYInt {
X = (int)(Math.Floor (GLSurface.Size.Width / 64.0D)),
Y = (int)(Math.Ceiling (GLSurface.Size.Height / 64.0D))
};
glSize = scrollTextureView.ClientSize;
//GLSurface.GLSize = glSize;
GLSurface.Size = glSize;
}
// send the resize event to the Graphics card.
GL.Viewport(0, 0, glSize.Width, glSize.Height);
GL.MatrixMode(MatrixMode.Projection);
GL.LoadIdentity();
GL.Ortho(-1.0, 1.0, -1.0, 1.0, 0.0, 4.0);
GL.MatrixMode (MatrixMode.Modelview);
GL.Disable (EnableCap.DepthTest);
GL.Clear(ClearBufferMask.ColorBufferBit);
var xyInt = new XYInt();
var unrotatedPos = new XYDouble();
var texCoord0 = new XYDouble();
var texCoord1 = new XYDouble();
var texCoord2 = new XYDouble();
var texCoord3 = new XYDouble();
GL.MatrixMode(MatrixMode.Projection);
GL.LoadIdentity();
GL.Ortho (0, glSize.Width, glSize.Height, 0, 0, 1);
GL.MatrixMode(MatrixMode.Modelview);
GL.LoadIdentity();
TileUtil.GetTileRotatedTexCoords(ToolOptions.Textures.TextureOrientation, ref texCoord0, ref texCoord1, ref texCoord2, ref texCoord3);
GL.Enable(EnableCap.Texture2D);
GL.Color4(0.0F, 0.0F, 0.0F, 1.0F);
for( var y = 0; y < TextureCount.Y; y++ )
{
for( var x = 0; x < TextureCount.X; x++ )
{
var num = y * TextureCount.X + x;
if( num >= tileset.Tiles.Count )
{
goto EndOfTextures1;
}
GL.BindTexture(TextureTarget.Texture2D, tileset.Tiles[num].GlTextureNum);
GL.TexEnv(TextureEnvTarget.TextureEnv, TextureEnvParameter.TextureEnvMode, (int)TextureEnvMode.Decal);
GL.Begin(BeginMode.Quads);
//Top-Right
GL.TexCoord2(texCoord0.X, texCoord0.Y);
GL.Vertex2(x * 64, y * 64);
//Top-Left
GL.TexCoord2(texCoord1.X, texCoord1.Y);
GL.Vertex2(x * 64 + 64, y * 64);
//Bottom-Left
GL.TexCoord2(texCoord3.X, texCoord3.Y);
GL.Vertex2(x * 64 + 64, y * 64 + 64);
//Bottom-Right
GL.TexCoord2(texCoord2.X, texCoord2.Y);
GL.Vertex2(x * 64, y * 64 + 64);
GL.End();
}
}
EndOfTextures1:
GL.Disable(EnableCap.Texture2D);
if( (bool)chkDisplayTileTypes.Checked )
{
GL.Begin(BeginMode.Quads);
for( var y = 0; y <= TextureCount.Y - 1; y++ )
{
for( var x = 0; x <= TextureCount.X - 1; x++ )
{
var num = y * TextureCount.X + x;
if( num >= tileset.Tiles.Count )
{
goto EndOfTextures2;
}
if(map != null)
{
num = map.TileTypeNum[num];
} else
{
num = tileset.Tiles[num].DefaultType;
}
GL.Color3(App.TileTypes[num].DisplayColour.Red, App.TileTypes[num].DisplayColour.Green, App.TileTypes[num].DisplayColour.Blue);
GL.Vertex2(x * 64 + 24, y * 64 + 24);
GL.Vertex2(x * 64 + 24, y * 64 + 40);
GL.Vertex2(x * 64 + 40, y * 64 + 40);
GL.Vertex2(x * 64 + 40, y * 64 + 24);
}
}
EndOfTextures2:
GL.End();
}
if( App.DisplayTileOrientation )
{
GL.Disable(EnableCap.CullFace);
unrotatedPos.X = 0.25F;
unrotatedPos.Y = 0.25F;
var vertex0 = TileUtil.GetTileRotatedPos_sng(App.TextureOrientation, unrotatedPos);
unrotatedPos.X = 0.5F;
unrotatedPos.Y = 0.25F;
var vertex1 = TileUtil.GetTileRotatedPos_sng(App.TextureOrientation, unrotatedPos);
unrotatedPos.X = 0.5F;
unrotatedPos.Y = 0.5F;
var vertex2 = TileUtil.GetTileRotatedPos_sng(App.TextureOrientation, unrotatedPos);
GL.Begin(BeginMode.Triangles);
GL.Color3(1.0F, 1.0F, 0.0F);
for( var y = 0; y <= TextureCount.Y - 1; y++ )
{
for( var x = 0; x <= TextureCount.X - 1; x++ )
{
var num = y * TextureCount.X + x;
if( num >= tileset.Tiles.Count )
{
goto EndOfTextures3;
}
GL.Vertex2(x * 64 + vertex0.X * 64, y * 64 + vertex0.Y * 64);
GL.Vertex2(x * 64 + vertex2.X * 64, y * 64 + vertex2.Y * 64);
GL.Vertex2(x * 64 + vertex1.X * 64, y * 64 + vertex1.Y * 64);
}
}
EndOfTextures3:
GL.End();
GL.Enable(EnableCap.CullFace);
}
if( (bool)chkDisplayTileNumbers.Checked && App.UnitLabelFont != null ) //TextureViewFont IsNot Nothing Then
{
GL.Enable(EnableCap.Texture2D);
for( var y = 0; y <= TextureCount.Y - 1; y++ )
{
for( var x = 0; x <= TextureCount.X - 1; x++ )
{
var num = y * TextureCount.X + x;
if( num >= tileset.Tiles.Count )
{
goto EndOfTextures4;
}
clsTextLabel textLabel = new clsTextLabel();
textLabel.Text = num.ToString();
textLabel.SizeY = 24.0F;
textLabel.Colour.Red = 1.0F;
textLabel.Colour.Green = 1.0F;
textLabel.Colour.Blue = 0.0F;
textLabel.Colour.Alpha = 1.0F;
textLabel.Pos.X = x * 64;
textLabel.Pos.Y = y * 64;
textLabel.TextFont = App.UnitLabelFont; //TextureViewFont
textLabel.Draw();
}
}
EndOfTextures4:
GL.Disable(EnableCap.Texture2D);
}
if( ToolOptions.Textures.SelectedTile >= 0 & TextureCount.X > 0 )
{
xyInt.X = ToolOptions.Textures.SelectedTile % TextureCount.X;
xyInt.Y = ToolOptions.Textures.SelectedTile / TextureCount.X;
GL.Begin(BeginMode.LineLoop);
GL.Color3(1.0F, 1.0F, 0.0F);
GL.Vertex2(xyInt.X * 64, xyInt.Y * 64);
GL.Vertex2(xyInt.X * 64, xyInt.Y * 64.0D + 64);
GL.Vertex2(xyInt.X * 64 + 64, xyInt.Y * 64 + 64);
GL.Vertex2(xyInt.X * 64 + 64, xyInt.Y * 64);
GL.End();
}
GL.Enable (EnableCap.DepthTest);
GL.Flush();
this.GLSurface.SwapBuffers();
}
private static DropDown TextureComboBox()
{
//var control = new ComboBox
// {
// AutoComplete = true,
// ReadOnly = true,
// };
var control = new DropDown();
if( App.Tilesets != null )
{
control.Items.AddRange(App.Tilesets);
}
return control;
}
private static ComboBox TileTypeComboBox()
{
var control = new ComboBox()
{
AutoComplete = true,
ReadOnly = true
};
if(App.TileTypes != null)
{
control.Items.AddRange(App.TileTypes);
}
return control;
}
private static ImageView MakeBtnRotateAntiClockwise()
{
var image = Resources.RotateAntiClockwise;
var control = new ImageView
{
Image = image,
Size = new Size(image.Width, image.Height)
};
control.MouseEnter += (sender, e) =>
{
((ImageView)sender).BackgroundColor = Eto.Drawing.Colors.Gray;
};
control.MouseLeave += (sender, e) =>
{
((ImageView)sender).BackgroundColor = Eto.Drawing.Colors.Transparent;
};
return control;
}
private static ImageView MakeBtnRotateClockwise()
{
var image = Resources.RotateClockwise;
var control = new ImageView
{
Image = image,
Size = new Size(image.Width, image.Height)
};
control.MouseEnter += (sender, e) =>
{
((ImageView)sender).BackgroundColor = Eto.Drawing.Colors.Gray;
};
control.MouseLeave += (sender, e) =>
{
((ImageView)sender).BackgroundColor = Eto.Drawing.Colors.Transparent;
};
return control;
}
private static ImageView MakeBtnFlipX()
{
var image = Resources.FlipX;
var control = new ImageView
{
Image = image,
Size = new Size(image.Width, image.Height)
};
control.MouseEnter += (sender, e) =>
{
((ImageView)sender).BackgroundColor = Eto.Drawing.Colors.Gray;
};
control.MouseLeave += (sender, e) =>
{
((ImageView)sender).BackgroundColor = Eto.Drawing.Colors.Transparent;
};
return control;
}
[EventPublication(EventTopics.OnOpenGLInitalized)]
public event EventHandler<EventArgs<GLSurface>> OnOpenGLInitalized = delegate { };
/// <summary>
/// Ons the GL control initialized.
/// </summary>
/// <param name="o">Not used.</param>
/// <param name="e">Not used.</param>
private void TextureView_OnGLControlInitialized(object o, EventArgs e)
{
this.GLSurface.MakeCurrent();
// Load tileset directories.
foreach( var path in Settings.TilesetDirectories )
{
if( !string.IsNullOrEmpty(path) )
{
SharpFlameApplication.InitializeResult.Add(App.LoadTilesets(path));
}
}
LoadSpecialTiles();
this.OnOpenGLInitalized(this, new EventArgs<GLSurface>(this.GLSurface));
}
private void LoadSpecialTiles()
{
Logger.Trace("Loading NoTile.");
var notileStream = Resources.GetStream("NoTile.png");
var notile = System.Drawing.Bitmap.FromStream(notileStream) as System.Drawing.Bitmap;
App.GLTexture_NoTile = BitmapUtil.CreateGLTexture(notile, 0);
var overflowStream = Resources.GetStream("Overflow.png");
var overflow = System.Drawing.Bitmap.FromStream(overflowStream) as System.Drawing.Bitmap;
App.GLTexture_OverflowTile = BitmapUtil.CreateGLTexture(overflow, 0);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.Security.Principal;
using Xunit;
namespace System.ServiceProcess.Tests
{
internal sealed class ServiceProvider
{
public readonly string TestMachineName;
public readonly TimeSpan ControlTimeout;
public readonly string TestServiceName;
public readonly string TestServiceDisplayName;
public readonly string DependentTestServiceNamePrefix;
public readonly string DependentTestServiceDisplayNamePrefix;
public readonly string TestServiceRegistryKey;
public ServiceProvider()
{
TestMachineName = ".";
ControlTimeout = TimeSpan.FromSeconds(120);
TestServiceName = Guid.NewGuid().ToString();
TestServiceDisplayName = "Test Service " + TestServiceName;
DependentTestServiceNamePrefix = TestServiceName + ".Dependent";
DependentTestServiceDisplayNamePrefix = TestServiceDisplayName + ".Dependent";
TestServiceRegistryKey = @"HKEY_USERS\.DEFAULT\dotnetTests\ServiceController\" + TestServiceName;
// Create the service
CreateTestServices();
}
private void CreateTestServices()
{
// Create the test service and its dependent services. Then, start the test service.
// All control tests assume that the test service is running when they are executed.
// So all tests should make sure to restart the service if they stop, pause, or shut
// it down.
RunServiceExecutable("create");
}
public void DeleteTestServices()
{
RunServiceExecutable("delete");
RegistryKey users = Registry.Users;
if (users.OpenSubKey(".DEFAULT\\dotnetTests") != null)
users.DeleteSubKeyTree(".DEFAULT\\dotnetTests");
}
private void RunServiceExecutable(string action)
{
const string serviceExecutable = "System.ServiceProcess.ServiceController.TestNativeService.exe";
var process = new Process();
process.StartInfo.FileName = serviceExecutable;
process.StartInfo.Arguments = string.Format("\"{0}\" \"{1}\" {2}", TestServiceName, TestServiceDisplayName, action);
process.Start();
process.WaitForExit();
if (process.ExitCode != 0)
{
throw new Exception("error: " + serviceExecutable + " failed with exit code " + process.ExitCode.ToString());
}
}
}
[OuterLoop(/* Modifies machine state */)]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Appx doesn't allow to access ServiceController")]
public class ServiceControllerTests : IDisposable
{
private const int ExpectedDependentServiceCount = 3;
private static readonly Lazy<bool> s_runningWithElevatedPrivileges = new Lazy<bool>(
() => new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator));
private readonly ServiceProvider _testService;
public ServiceControllerTests()
{
_testService = new ServiceProvider();
}
private static bool RunningWithElevatedPrivileges
{
get { return s_runningWithElevatedPrivileges.Value; }
}
private void AssertExpectedProperties(ServiceController testServiceController)
{
var comparer = PlatformDetection.IsFullFramework ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; // Full framework upper cases the name
Assert.Equal(_testService.TestServiceName, testServiceController.ServiceName, comparer);
Assert.Equal(_testService.TestServiceDisplayName, testServiceController.DisplayName);
Assert.Equal(_testService.TestMachineName, testServiceController.MachineName);
Assert.Equal(ServiceType.Win32OwnProcess, testServiceController.ServiceType);
}
[ConditionalFact(nameof(RunningWithElevatedPrivileges))]
public void ConstructWithServiceName()
{
var controller = new ServiceController(_testService.TestServiceName);
AssertExpectedProperties(controller);
}
[ConditionalFact(nameof(RunningWithElevatedPrivileges))]
public void ConstructWithServiceName_ToUpper()
{
var controller = new ServiceController(_testService.TestServiceName.ToUpperInvariant());
AssertExpectedProperties(controller);
}
[ConditionalFact(nameof(RunningWithElevatedPrivileges))]
public void ConstructWithDisplayName()
{
var controller = new ServiceController(_testService.TestServiceDisplayName);
AssertExpectedProperties(controller);
}
[ConditionalFact(nameof(RunningWithElevatedPrivileges))]
public void ConstructWithMachineName()
{
var controller = new ServiceController(_testService.TestServiceName, _testService.TestMachineName);
AssertExpectedProperties(controller);
AssertExtensions.Throws<ArgumentException>(null, () => { var c = new ServiceController(_testService.TestServiceName, ""); });
}
[ConditionalFact(nameof(RunningWithElevatedPrivileges))]
public void ControlCapabilities()
{
var controller = new ServiceController(_testService.TestServiceName);
controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout);
Assert.True(controller.CanStop);
Assert.True(controller.CanPauseAndContinue);
Assert.False(controller.CanShutdown);
}
[ConditionalFact(nameof(RunningWithElevatedPrivileges))]
public void StartWithArguments()
{
var controller = new ServiceController(_testService.TestServiceName);
controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout);
Assert.Equal(ServiceControllerStatus.Running, controller.Status);
controller.Stop();
controller.WaitForStatus(ServiceControllerStatus.Stopped, _testService.ControlTimeout);
Assert.Equal(ServiceControllerStatus.Stopped, controller.Status);
var args = new[] { "a", "b", "c", "d", "e" };
controller.Start(args);
controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout);
Assert.Equal(ServiceControllerStatus.Running, controller.Status);
// The test service writes the arguments that it was started with to the _testService.TestServiceRegistryKey.
// Read this key to verify that the arguments were properly passed to the service.
string argsString = Registry.GetValue(_testService.TestServiceRegistryKey, "ServiceArguments", null) as string;
Assert.Equal(string.Join(",", args), argsString);
}
[ConditionalFact(nameof(RunningWithElevatedPrivileges))]
public void Start_NullArg_ThrowsArgumentNullException()
{
var controller = new ServiceController(_testService.TestServiceName);
Assert.Throws<ArgumentNullException>(() => controller.Start(new string[] { null } ));
}
[ConditionalFact(nameof(RunningWithElevatedPrivileges))]
public void StopAndStart()
{
var controller = new ServiceController(_testService.TestServiceName);
controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout);
Assert.Equal(ServiceControllerStatus.Running, controller.Status);
for (int i = 0; i < 2; i++)
{
controller.Stop();
controller.WaitForStatus(ServiceControllerStatus.Stopped, _testService.ControlTimeout);
Assert.Equal(ServiceControllerStatus.Stopped, controller.Status);
controller.Start();
controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout);
Assert.Equal(ServiceControllerStatus.Running, controller.Status);
}
}
[ConditionalFact(nameof(RunningWithElevatedPrivileges))]
public void PauseAndContinue()
{
var controller = new ServiceController(_testService.TestServiceName);
controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout);
Assert.Equal(ServiceControllerStatus.Running, controller.Status);
for (int i = 0; i < 2; i++)
{
controller.Pause();
controller.WaitForStatus(ServiceControllerStatus.Paused, _testService.ControlTimeout);
Assert.Equal(ServiceControllerStatus.Paused, controller.Status);
controller.Continue();
controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout);
Assert.Equal(ServiceControllerStatus.Running, controller.Status);
}
}
[ConditionalFact(nameof(RunningWithElevatedPrivileges))]
public void GetServices_FindSelf()
{
bool foundTestService = false;
foreach (var service in ServiceController.GetServices())
{
if (service.ServiceName == _testService.TestServiceName)
{
foundTestService = true;
AssertExpectedProperties(service);
}
}
Assert.True(foundTestService, "Test service was not enumerated with all services");
}
[ConditionalFact(nameof(RunningWithElevatedPrivileges))]
public void Dependencies()
{
// The test service creates a number of dependent services, each of which is depended on
// by all the services created after it.
var controller = new ServiceController(_testService.TestServiceName);
Assert.Equal(ExpectedDependentServiceCount, controller.DependentServices.Length);
for (int i = 0; i < controller.DependentServices.Length; i++)
{
var dependent = AssertHasDependent(controller, _testService.DependentTestServiceNamePrefix + i, _testService.DependentTestServiceDisplayNamePrefix + i);
Assert.Equal(ServiceType.Win32OwnProcess, dependent.ServiceType);
// Assert that this dependent service is depended on by all the test services created after it
Assert.Equal(ExpectedDependentServiceCount - i - 1, dependent.DependentServices.Length);
for (int j = i + 1; j < ExpectedDependentServiceCount; j++)
{
AssertHasDependent(dependent, _testService.DependentTestServiceNamePrefix + j, _testService.DependentTestServiceDisplayNamePrefix + j);
}
// Assert that the dependent service depends on the main test service
AssertDependsOn(dependent, _testService.TestServiceName, _testService.TestServiceDisplayName);
// Assert that this dependent service depends on all the test services created before it
Assert.Equal(i + 1, dependent.ServicesDependedOn.Length);
for (int j = i - 1; j >= 0; j--)
{
AssertDependsOn(dependent, _testService.DependentTestServiceNamePrefix + j, _testService.DependentTestServiceDisplayNamePrefix + j);
}
}
}
[ConditionalFact(nameof(RunningWithElevatedPrivileges))]
public void ServicesStartMode()
{
var controller = new ServiceController(_testService.TestServiceName);
Assert.Equal(ServiceStartMode.Manual, controller.StartType);
// Check for the startType of the dependent services.
for (int i = 0; i < controller.DependentServices.Length; i++)
{
Assert.Equal(ServiceStartMode.Disabled, controller.DependentServices[i].StartType);
}
}
public void Dispose()
{
_testService.DeleteTestServices();
}
private static ServiceController AssertHasDependent(ServiceController controller, string serviceName, string displayName)
{
var dependent = FindService(controller.DependentServices, serviceName, displayName);
Assert.NotNull(dependent);
return dependent;
}
private static ServiceController AssertDependsOn(ServiceController controller, string serviceName, string displayName)
{
var dependency = FindService(controller.ServicesDependedOn, serviceName, displayName);
Assert.NotNull(dependency);
return dependency;
}
private static ServiceController FindService(ServiceController[] services, string serviceName, string displayName)
{
foreach (ServiceController service in services)
{
if (service.ServiceName == serviceName && service.DisplayName == displayName)
{
return service;
}
}
return null;
}
}
}
| |
//
// Copyright (C) 2012-2014 DataStax Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Cassandra.Collections;
using Cassandra.Tasks;
namespace Cassandra
{
/// <summary>
/// Represents a pool of connections to a host
/// </summary>
internal class HostConnectionPool : IDisposable
{
private const int ConnectionIndexOverflow = int.MaxValue - 100000;
private readonly static Logger Logger = new Logger(typeof(HostConnectionPool));
private readonly static Connection[] EmptyConnectionsArray = new Connection[0];
//Safe iteration of connections
private readonly CopyOnWriteList<Connection> _connections = new CopyOnWriteList<Connection>();
private readonly Host _host;
private readonly HostDistance _distance;
private readonly Configuration _config;
private readonly HashedWheelTimer _timer;
private int _connectionIndex;
private HashedWheelTimer.ITimeout _timeout;
private volatile bool _isShuttingDown;
private int _isIncreasingSize;
private TaskCompletionSource<Connection[]> _creationTcs;
private volatile bool _isDisposed;
/// <summary>
/// Gets a list of connections already opened to the host
/// </summary>
public IEnumerable<Connection> OpenConnections
{
get { return _connections; }
}
public byte ProtocolVersion { get; set; }
public HostConnectionPool(Host host, HostDistance distance, Configuration config)
{
_host = host;
_host.CheckedAsDown += OnHostCheckedAsDown;
_host.Down += OnHostDown;
_host.Up += OnHostUp;
_host.Remove += OnHostRemoved;
_distance = distance;
_config = config;
_timer = config.Timer;
}
/// <summary>
/// Gets an open connection from the host pool (creating if necessary).
/// It returns null if the load balancing policy didn't allow connections to this host.
/// </summary>
public Task<Connection> BorrowConnection()
{
return MaybeCreateFirstConnection().ContinueSync(poolConnections =>
{
if (poolConnections.Length == 0)
{
//The load balancing policy stated no connections for this host
return null;
}
var connection = MinInFlight(poolConnections, ref _connectionIndex);
MaybeIncreasePoolSize(connection.InFlight);
return connection;
});
}
/// <summary>
/// Gets the connection with the minimum number of InFlight requests.
/// Only checks for index + 1 and index, to avoid a loop of all connections.
/// </summary>
public static Connection MinInFlight(Connection[] connections, ref int connectionIndex)
{
if (connections.Length == 1)
{
return connections[0];
}
//It is very likely that the amount of InFlight requests per connection is the same
//Do round robin between connections, skipping connections that have more in flight requests
var index = Interlocked.Increment(ref connectionIndex);
if (index > ConnectionIndexOverflow)
{
//Overflow protection, not exactly thread-safe but we can live with it
Interlocked.Exchange(ref connectionIndex, 0);
}
var currentConnection = connections[index % connections.Length];
var previousConnection = connections[(index - 1)%connections.Length];
if (previousConnection.InFlight < currentConnection.InFlight)
{
return previousConnection;
}
return currentConnection;
}
/// <exception cref="System.Net.Sockets.SocketException">Throws a SocketException when the connection could not be established with the host</exception>
/// <exception cref="AuthenticationException" />
/// <exception cref="UnsupportedProtocolVersionException"></exception>
internal virtual Task<Connection> CreateConnection()
{
Logger.Info("Creating a new connection to the host " + _host.Address);
var c = new Connection(ProtocolVersion, _host.Address, _config);
return c.Open().ContinueWith(t =>
{
if (t.Status == TaskStatus.RanToCompletion)
{
if (_config.GetPoolingOptions(ProtocolVersion).GetHeartBeatInterval() > 0)
{
//Heartbeat is enabled, subscribe for possible exceptions
c.OnIdleRequestException += OnIdleRequestException;
}
return c;
}
Logger.Info("The connection to {0} could not be opened", _host.Address);
c.Dispose();
if (t.Exception != null)
{
t.Exception.Handle(_ => true);
Logger.Error(t.Exception.InnerException);
throw t.Exception.InnerException;
}
throw new TaskCanceledException("The connection creation task was cancelled");
}, TaskContinuationOptions.ExecuteSynchronously);
}
/// <summary>
/// Handler that gets invoked when if there is a socket exception when making a heartbeat/idle request
/// </summary>
private void OnIdleRequestException(Exception ex)
{
_host.SetDown();
}
internal void OnHostCheckedAsDown(Host h, long delay)
{
if (!_host.SetAttemptingReconnection())
{
//Another pool is attempting reconnection
//Eventually Host.Up event is going to be fired.
return;
}
//Schedule next reconnection attempt (without using the timer thread)
//Cancel the previous one
var nextTimeout = _timer.NewTimeout(_ => Task.Factory.StartNew(AttemptReconnection), null, delay);
SetReconnectionTimeout(nextTimeout);
}
/// <summary>
/// Handles the reconnection attempts.
/// If it succeeds, it marks the host as UP.
/// If not, it marks the host as DOWN
/// </summary>
internal void AttemptReconnection()
{
_isShuttingDown = false;
if (_isDisposed)
{
return;
}
var tcs = new TaskCompletionSource<Connection[]>();
//While there is a single thread here, there might be another thread
//Calling MaybeCreateFirstConnection()
//Guard for multiple creations
var creationTcs = Interlocked.CompareExchange(ref _creationTcs, tcs, null);
if (creationTcs != null || _connections.Count > 0)
{
//Already creating as host is back UP (possibly via events)
return;
}
Logger.Info("Attempting reconnection to host {0}", _host.Address);
//There is a single thread creating a connection
CreateConnection().ContinueWith(t =>
{
if (t.Status == TaskStatus.RanToCompletion)
{
if (_isShuttingDown)
{
t.Result.Dispose();
TransitionCreationTask(tcs, EmptyConnectionsArray);
return;
}
_connections.Add(t.Result);
Logger.Info("Reconnection attempt to host {0} succeeded", _host.Address);
_host.BringUpIfDown();
TransitionCreationTask(tcs, new [] { t.Result });
return;
}
Logger.Info("Reconnection attempt to host {0} failed", _host.Address);
Exception ex = null;
if (t.Exception != null)
{
t.Exception.Handle(e => true);
ex = t.Exception.InnerException;
}
TransitionCreationTask(tcs, EmptyConnectionsArray, ex);
_host.SetDown(failedReconnection: true);
}, TaskContinuationOptions.ExecuteSynchronously);
}
private void OnHostUp(Host host)
{
_isShuttingDown = false;
SetReconnectionTimeout(null);
//The host is back up, we can start creating the pool (if applies)
MaybeCreateFirstConnection();
}
private void OnHostDown(Host h, long delay)
{
Shutdown();
}
/// <summary>
/// Cancels the previous and set the next reconnection timeout, as an atomic operation.
/// </summary>
private void SetReconnectionTimeout(HashedWheelTimer.ITimeout nextTimeout)
{
var timeout = Interlocked.Exchange(ref _timeout, nextTimeout);
if (timeout != null)
{
timeout.Cancel();
}
}
/// <summary>
/// Create the min amount of connections, if the pool is empty.
/// It may return an empty array if its being closed.
/// It may return an array of connections being closed.
/// </summary>
internal Task<Connection[]> MaybeCreateFirstConnection()
{
var tcs = new TaskCompletionSource<Connection[]>();
var connections = _connections.GetSnapshot();
if (connections.Length > 0)
{
tcs.SetResult(connections);
return tcs.Task;
}
var creationTcs = Interlocked.CompareExchange(ref _creationTcs, tcs, null);
if (creationTcs != null)
{
return creationTcs.Task;
}
//Could have transitioned
connections = _connections.GetSnapshot();
if (connections.Length > 0)
{
TransitionCreationTask(tcs, connections);
return tcs.Task;
}
if (_isShuttingDown)
{
//It transitioned to DOWN, avoid try to create new Connections
TransitionCreationTask(tcs, EmptyConnectionsArray);
return tcs.Task;
}
Logger.Info("Initializing pool to {0}", _host.Address);
//There is a single thread creating a single connection
CreateConnection().ContinueWith(t =>
{
if (t.Status == TaskStatus.RanToCompletion)
{
if (_isShuttingDown)
{
//Is shutting down
t.Result.Dispose();
TransitionCreationTask(tcs, EmptyConnectionsArray);
return;
}
_connections.Add(t.Result);
_host.BringUpIfDown();
TransitionCreationTask(tcs, new[] { t.Result });
return;
}
if (t.Exception != null)
{
TransitionCreationTask(tcs, null, t.Exception.InnerException);
return;
}
TransitionCreationTask(tcs, EmptyConnectionsArray);
}, TaskContinuationOptions.ExecuteSynchronously);
return tcs.Task;
}
private void TransitionCreationTask(TaskCompletionSource<Connection[]> tcs, Connection[] result, Exception ex = null)
{
if (ex != null)
{
tcs.TrySetException(ex);
}
else if (result != null)
{
tcs.TrySetResult(result);
}
else
{
tcs.TrySetException(new DriverInternalError("Creation task must transition from a result or an exception"));
}
Interlocked.Exchange(ref _creationTcs, null);
}
/// <summary>
/// Increases the size of the pool from 1 to core and from core to max
/// </summary>
/// <returns>True if it is creating a new connection</returns>
internal bool MaybeIncreasePoolSize(int inFlight)
{
var coreConnections = _config.GetPoolingOptions(ProtocolVersion).GetCoreConnectionsPerHost(_distance);
var connections = _connections.GetSnapshot();
if (connections.Length == 0)
{
return false;
}
if (connections.Length >= coreConnections)
{
var maxInFlight = _config.GetPoolingOptions(ProtocolVersion).GetMaxSimultaneousRequestsPerConnectionTreshold(_distance);
var maxConnections = _config.GetPoolingOptions(ProtocolVersion).GetMaxConnectionPerHost(_distance);
if (inFlight < maxInFlight)
{
return false;
}
if (_connections.Count >= maxConnections)
{
return false;
}
}
var isAlreadyIncreasing = Interlocked.CompareExchange(ref _isIncreasingSize, 1, 0) == 1;
if (isAlreadyIncreasing)
{
return true;
}
if (_isShuttingDown || _connections.Count == 0)
{
Interlocked.Exchange(ref _isIncreasingSize, 0);
return false;
}
CreateConnection().ContinueWith(t =>
{
if (t.Status == TaskStatus.RanToCompletion)
{
if (_isShuttingDown)
{
//Is shutting down
t.Result.Dispose();
}
else
{
_connections.Add(t.Result);
}
}
if (t.Exception != null)
{
Logger.Error("Error while increasing pool size", t.Exception.InnerException);
}
Interlocked.Exchange(ref _isIncreasingSize, 0);
}, TaskContinuationOptions.ExecuteSynchronously);
return true;
}
public void CheckHealth(Connection c)
{
if (c.TimedOutOperations < _config.SocketOptions.DefunctReadTimeoutThreshold)
{
return;
}
//We are in the default thread-pool (non-io thread)
//Defunct: close it and remove it from the pool
_connections.Remove(c);
c.Dispose();
}
public void Shutdown()
{
_isShuttingDown = true;
var connections = _connections.ClearAndGet();
if (connections.Length == 0)
{
return;
}
Logger.Info(string.Format("Shutting down pool to {0}, closing {1} connection(s).", _host.Address, connections.Length));
foreach (var c in connections)
{
c.Dispose();
}
}
private void OnHostRemoved()
{
Dispose();
}
/// <summary>
/// Releases the resources associated with the pool.
/// </summary>
public void Dispose()
{
_isDisposed = true;
SetReconnectionTimeout(null);
Shutdown();
_host.CheckedAsDown -= OnHostCheckedAsDown;
_host.Up -= OnHostUp;
_host.Down -= OnHostDown;
_host.Remove -= OnHostRemoved;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using NuGet.Resources;
namespace NuGet
{
public class InstallWalker : PackageWalker, IPackageOperationResolver
{
private readonly bool _ignoreDependencies;
private readonly bool _allowPrereleaseVersions;
private readonly OperationLookup _operations;
public InstallWalker(IPackageRepository localRepository,
IPackageRepository sourceRepository,
ILogger logger,
bool ignoreDependencies,
bool allowPrereleaseVersions) :
this(localRepository,
sourceRepository,
constraintProvider: NullConstraintProvider.Instance,
logger: logger,
ignoreDependencies: ignoreDependencies,
allowPrereleaseVersions: allowPrereleaseVersions)
{
}
public InstallWalker(IPackageRepository localRepository,
IPackageRepository sourceRepository,
IPackageConstraintProvider constraintProvider,
ILogger logger,
bool ignoreDependencies,
bool allowPrereleaseVersions)
{
if (sourceRepository == null)
{
throw new ArgumentNullException("sourceRepository");
}
if (localRepository == null)
{
throw new ArgumentNullException("localRepository");
}
if (logger == null)
{
throw new ArgumentNullException("logger");
}
Repository = localRepository;
Logger = logger;
SourceRepository = sourceRepository;
_ignoreDependencies = ignoreDependencies;
ConstraintProvider = constraintProvider;
_operations = new OperationLookup();
_allowPrereleaseVersions = allowPrereleaseVersions;
}
protected ILogger Logger
{
get;
private set;
}
protected IPackageRepository Repository
{
get;
private set;
}
protected override bool IgnoreDependencies
{
get
{
return _ignoreDependencies;
}
}
protected override bool AllowPrereleaseVersions
{
get
{
return _allowPrereleaseVersions;
}
}
protected IPackageRepository SourceRepository
{
get;
private set;
}
private IPackageConstraintProvider ConstraintProvider { get; set; }
protected IList<PackageOperation> Operations
{
get
{
return _operations.ToList();
}
}
protected virtual ConflictResult GetConflict(IPackage package)
{
var conflictingPackage = Marker.FindPackage(package.Id);
if (conflictingPackage != null)
{
return new ConflictResult(conflictingPackage, Marker, Marker);
}
return null;
}
protected override void OnBeforePackageWalk(IPackage package)
{
ConflictResult conflictResult = GetConflict(package);
if (conflictResult == null)
{
return;
}
// If the conflicting package is the same as the package being installed
// then no-op
if (PackageEqualityComparer.IdAndVersion.Equals(package, conflictResult.Package))
{
return;
}
// First we get a list of dependents for the installed package.
// Then we find the dependency in the foreach dependent that this installed package used to satisfy.
// We then check if the resolved package also meets that dependency and if it doesn't it's added to the list
// i.e. A1 -> C >= 1
// B1 -> C >= 1
// C2 -> []
// Given the above graph, if we upgrade from C1 to C2, we need to see if A and B can work with the new C
var incompatiblePackages = from dependentPackage in GetDependents(conflictResult)
let dependency = dependentPackage.FindDependency(package.Id)
where dependency != null && !dependency.VersionSpec.Satisfies(package.Version)
select dependentPackage;
// If there were incompatible packages that we failed to update then we throw an exception
if (incompatiblePackages.Any() && !TryUpdate(incompatiblePackages, conflictResult, package, out incompatiblePackages))
{
throw CreatePackageConflictException(package, conflictResult.Package, incompatiblePackages);
}
else if (package.Version < conflictResult.Package.Version)
{
// REVIEW: Should we have a flag to allow downgrading?
throw new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
NuGetResources.NewerVersionAlreadyReferenced, package.Id));
}
else if (package.Version > conflictResult.Package.Version)
{
Uninstall(conflictResult.Package, conflictResult.DependentsResolver, conflictResult.Repository);
}
}
private void Uninstall(IPackage package, IDependentsResolver dependentsResolver, IPackageRepository repository)
{
// If this package isn't part of the current graph (i.e. hasn't been visited yet) and
// is marked for removal, then do nothing. This is so we don't get unnecessary duplicates.
if (!Marker.Contains(package) && _operations.Contains(package, PackageAction.Uninstall))
{
return;
}
// Uninstall the conflicting package. We set throw on conflicts to false since we've
// already decided that there were no conflicts based on the above code.
var resolver = new UninstallWalker(repository,
dependentsResolver,
NullLogger.Instance,
removeDependencies: !IgnoreDependencies,
forceRemove: false) { ThrowOnConflicts = false };
foreach (var operation in resolver.ResolveOperations(package))
{
_operations.AddOperation(operation);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We re-throw a more specific exception later on")]
private bool TryUpdate(IEnumerable<IPackage> dependents, ConflictResult conflictResult, IPackage package, out IEnumerable<IPackage> incompatiblePackages)
{
// Key dependents by id so we can look up the old package later
var dependentsLookup = dependents.ToDictionary(d => d.Id, StringComparer.OrdinalIgnoreCase);
var compatiblePackages = new Dictionary<IPackage, IPackage>();
// Initialize each compatible package to null
foreach (var dependent in dependents)
{
compatiblePackages[dependent] = null;
}
// Get compatible packages in one batch so we don't have to make requests for each one
var packages = from p in SourceRepository.FindCompatiblePackages(ConstraintProvider, dependentsLookup.Keys, package, AllowPrereleaseVersions)
group p by p.Id into g
let oldPackage = dependentsLookup[g.Key]
select new
{
OldPackage = oldPackage,
NewPackage = g.Where(p => p.Version > oldPackage.Version)
.OrderBy(p => p.Version)
.ResolveSafeVersion()
};
foreach (var p in packages)
{
compatiblePackages[p.OldPackage] = p.NewPackage;
}
// Get all packages that have an incompatibility with the specified package i.e.
// We couldn't find a version in the repository that works with the specified package.
incompatiblePackages = compatiblePackages.Where(p => p.Value == null)
.Select(p => p.Key);
if (incompatiblePackages.Any())
{
return false;
}
IPackageConstraintProvider currentConstraintProvider = ConstraintProvider;
try
{
// Add a constraint for the incoming package so we don't try to update it by mistake.
// Scenario:
// A 1.0 -> B [1.0]
// B 1.0.1, B 1.5, B 2.0
// A 2.0 -> B (any version)
// We have A 1.0 and B 1.0 installed. When trying to update to B 1.0.1, we'll end up trying
// to find a version of A that works with B 1.0.1. The version in the above case is A 2.0.
// When we go to install A 2.0 we need to make sure that when we resolve it's dependencies that we stay within bounds
// i.e. when we resolve B for A 2.0 we want to keep the B 1.0.1 we've already chosen instead of trying to grab
// B 1.5 or B 2.0. In order to achieve this, we add a constraint for version of B 1.0.1 so we stay within those bounds for B.
// Respect all existing constraints plus an additional one that we specify based on the incoming package
var constraintProvider = new DefaultConstraintProvider();
constraintProvider.AddConstraint(package.Id, new VersionSpec(package.Version));
ConstraintProvider = new AggregateConstraintProvider(ConstraintProvider, constraintProvider);
// Mark the incoming package as visited so that we don't try walking the graph again
Marker.MarkVisited(package);
var failedPackages = new List<IPackage>();
// Update each of the existing packages to more compatible one
foreach (var pair in compatiblePackages)
{
try
{
// Remove the old package
Uninstall(pair.Key, conflictResult.DependentsResolver, conflictResult.Repository);
// Install the new package
Walk(pair.Value);
}
catch
{
// If we failed to update this package (most likely because of a conflict further up the dependency chain)
// we keep track of it so we can report an error about the top level package.
failedPackages.Add(pair.Key);
}
}
incompatiblePackages = failedPackages;
return !incompatiblePackages.Any();
}
finally
{
// Restore the current constraint provider
ConstraintProvider = currentConstraintProvider;
// Mark the package as processing again
Marker.MarkProcessing(package);
}
}
protected override void OnAfterPackageWalk(IPackage package)
{
if (!Repository.Exists(package))
{
// Don't add the package for installation if it already exists in the repository
_operations.AddOperation(new PackageOperation(package, PackageAction.Install));
}
else
{
// If we already added an entry for removing this package then remove it
// (it's equivalent for doing +P since we're removing a -P from the list)
_operations.RemoveOperation(package, PackageAction.Uninstall);
}
}
protected override IPackage ResolveDependency(PackageDependency dependency)
{
Logger.Log(MessageLevel.Info, NuGetResources.Log_AttemptingToRetrievePackageFromSource, dependency);
// First try to get a local copy of the package
// Bug1638: Include prereleases when resolving locally installed dependencies.
IPackage package = Repository.ResolveDependency(dependency, ConstraintProvider, allowPrereleaseVersions: true, preferListedPackages: false);
// Next, query the source repo for the same dependency
IPackage sourcePackage = SourceRepository.ResolveDependency(dependency, ConstraintProvider, AllowPrereleaseVersions, preferListedPackages: true);
// We didn't find a copy in the local repository
if (package == null)
{
return sourcePackage;
}
// Only use the package from the source repository if it's a newer version (it'll only be newer in bug fixes)
if (sourcePackage != null && package.Version < sourcePackage.Version)
{
return sourcePackage;
}
return package;
}
protected override void OnDependencyResolveError(PackageDependency dependency)
{
IVersionSpec spec = ConstraintProvider.GetConstraint(dependency.Id);
string message = String.Empty;
if (spec != null)
{
message = String.Format(CultureInfo.CurrentCulture, NuGetResources.AdditonalConstraintsDefined, dependency.Id, VersionUtility.PrettyPrint(spec), ConstraintProvider.Source);
}
throw new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
NuGetResources.UnableToResolveDependency + message, dependency));
}
public IEnumerable<PackageOperation> ResolveOperations(IPackage package)
{
_operations.Clear();
Marker.Clear();
Walk(package);
return Operations.Reduce();
}
private IEnumerable<IPackage> GetDependents(ConflictResult conflict)
{
// Skip all dependents that are marked for uninstall
IEnumerable<IPackage> packages = _operations.GetPackages(PackageAction.Uninstall);
return conflict.DependentsResolver.GetDependents(conflict.Package, true)
.Except(packages, PackageEqualityComparer.IdAndVersion);
}
private static InvalidOperationException CreatePackageConflictException(IPackage resolvedPackage, IPackage package, IEnumerable<IPackage> dependents)
{
if (dependents.Count() == 1)
{
return new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,
NuGetResources.ConflictErrorWithDependent, package.GetFullName(), resolvedPackage.GetFullName(), dependents.Single().Id));
}
return new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,
NuGetResources.ConflictErrorWithDependents, package.GetFullName(), resolvedPackage.GetFullName(), String.Join(", ",
dependents.Select(d => d.Id))));
}
/// <summary>
/// Operation lookup encapsulates an operation list and another efficient data structure for finding package operations
/// by package id, version and PackageAction.
/// </summary>
private class OperationLookup
{
private readonly List<PackageOperation> _operations = new List<PackageOperation>();
private readonly Dictionary<PackageAction, Dictionary<IPackage, PackageOperation>> _operationLookup = new Dictionary<PackageAction, Dictionary<IPackage, PackageOperation>>();
internal void Clear()
{
_operations.Clear();
_operationLookup.Clear();
}
internal IList<PackageOperation> ToList()
{
return _operations;
}
internal IEnumerable<IPackage> GetPackages(PackageAction action)
{
Dictionary<IPackage, PackageOperation> dictionary = GetPackageLookup(action);
if (dictionary != null)
{
return dictionary.Keys;
}
return Enumerable.Empty<IPackage>();
}
internal void AddOperation(PackageOperation operation)
{
Dictionary<IPackage, PackageOperation> dictionary = GetPackageLookup(operation.Action, createIfNotExists: true);
if (!dictionary.ContainsKey(operation.Package))
{
dictionary.Add(operation.Package, operation);
_operations.Add(operation);
}
}
internal void RemoveOperation(IPackage package, PackageAction action)
{
Dictionary<IPackage, PackageOperation> dictionary = GetPackageLookup(action);
PackageOperation operation;
if (dictionary != null && dictionary.TryGetValue(package, out operation))
{
dictionary.Remove(package);
_operations.Remove(operation);
}
}
internal bool Contains(IPackage package, PackageAction action)
{
Dictionary<IPackage, PackageOperation> dictionary = GetPackageLookup(action);
return dictionary != null && dictionary.ContainsKey(package);
}
private Dictionary<IPackage, PackageOperation> GetPackageLookup(PackageAction action, bool createIfNotExists = false)
{
Dictionary<IPackage, PackageOperation> packages;
if (!_operationLookup.TryGetValue(action, out packages) && createIfNotExists)
{
packages = new Dictionary<IPackage, PackageOperation>(PackageEqualityComparer.IdAndVersion);
_operationLookup.Add(action, packages);
}
return packages;
}
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Collections.Generic;
#if OPENGL
#if MONOMAC
using MonoMac.OpenGL;
#elif WINDOWS || LINUX
using OpenTK.Graphics.OpenGL;
#else
using OpenTK.Graphics.ES20;
#endif
#elif PSM
using Sce.PlayStation.Core.Graphics;
#elif DIRECTX
using System.Reflection;
#endif
namespace Microsoft.Xna.Framework.Graphics
{
public class VertexDeclaration : GraphicsResource
{
#if PSM
private VertexFormat[] _vertexFormat;
#endif
private VertexElement[] _elements;
private int _vertexStride;
#if OPENGL
Dictionary<int, VertexDeclarationAttributeInfo> shaderAttributeInfo = new Dictionary<int, VertexDeclarationAttributeInfo>();
#endif
/// <summary>
/// A hash value which can be used to compare declarations.
/// </summary>
internal int HashKey { get; private set; }
public VertexDeclaration(params VertexElement[] elements)
: this( GetVertexStride(elements), elements)
{
}
public VertexDeclaration(int vertexStride, params VertexElement[] elements)
{
if ((elements == null) || (elements.Length == 0))
throw new ArgumentNullException("elements", "Elements cannot be empty");
var elementArray = (VertexElement[])elements.Clone();
_elements = elementArray;
_vertexStride = vertexStride;
// TODO: Is there a faster/better way to generate a
// unique hashkey for the same vertex layouts?
{
var signature = string.Empty;
foreach (var element in _elements)
signature += element;
var bytes = System.Text.Encoding.UTF8.GetBytes(signature);
HashKey = MonoGame.Utilities.Hash.ComputeHash(bytes);
}
}
private static int GetVertexStride(VertexElement[] elements)
{
int max = 0;
for (var i = 0; i < elements.Length; i++)
{
var start = elements[i].Offset + elements[i].VertexElementFormat.GetTypeSize();
if (max < start)
max = start;
}
return max;
}
/// <summary>
/// Returns the VertexDeclaration for Type.
/// </summary>
/// <param name="vertexType">A value type which implements the IVertexType interface.</param>
/// <returns>The VertexDeclaration.</returns>
/// <remarks>
/// Prefer to use VertexDeclarationCache when the declaration lookup
/// can be performed with a templated type.
/// </remarks>
internal static VertexDeclaration FromType(Type vertexType)
{
if (vertexType == null)
throw new ArgumentNullException("vertexType", "Cannot be null");
#if WINRT
if (!vertexType.GetTypeInfo().IsValueType)
#else
if (!vertexType.IsValueType)
#endif
{
var args = new object[] { vertexType };
throw new ArgumentException("vertexType", "Must be value type");
}
var type = Activator.CreateInstance(vertexType) as IVertexType;
if (type == null)
{
var objArray3 = new object[] { vertexType };
throw new ArgumentException("vertexData does not inherit IVertexType");
}
var vertexDeclaration = type.VertexDeclaration;
if (vertexDeclaration == null)
{
var objArray2 = new object[] { vertexType };
throw new Exception("VertexDeclaration cannot be null");
}
return vertexDeclaration;
}
public VertexElement[] GetVertexElements()
{
return (VertexElement[])_elements.Clone();
}
public int VertexStride
{
get
{
return _vertexStride;
}
}
#if OPENGL
internal void Apply(Shader shader, IntPtr offset)
{
VertexDeclarationAttributeInfo attrInfo;
int shaderHash = shader.GetHashCode();
if (!shaderAttributeInfo.TryGetValue(shaderHash, out attrInfo))
{
// Get the vertex attribute info and cache it
attrInfo = new VertexDeclarationAttributeInfo(GraphicsDevice.MaxVertexAttributes);
foreach (var ve in _elements)
{
var attributeLocation = shader.GetAttribLocation(ve.VertexElementUsage, ve.UsageIndex);
// XNA appears to ignore usages it can't find a match for, so we will do the same
if (attributeLocation >= 0)
{
attrInfo.Elements.Add(new VertexDeclarationAttributeInfo.Element()
{
Offset = ve.Offset,
AttributeLocation = attributeLocation,
NumberOfElements = ve.VertexElementFormat.OpenGLNumberOfElements(),
VertexAttribPointerType = ve.VertexElementFormat.OpenGLVertexAttribPointerType(),
Normalized = ve.OpenGLVertexAttribNormalized(),
});
attrInfo.EnabledAttributes[attributeLocation] = true;
}
}
shaderAttributeInfo.Add(shaderHash, attrInfo);
}
// Apply the vertex attribute info
foreach (var element in attrInfo.Elements)
{
GL.VertexAttribPointer(element.AttributeLocation,
element.NumberOfElements,
element.VertexAttribPointerType,
element.Normalized,
this.VertexStride,
(IntPtr)(offset.ToInt64() + element.Offset));
GraphicsExtensions.CheckGLError();
}
GraphicsDevice.SetVertexAttributeArray(attrInfo.EnabledAttributes);
}
#endif // OPENGL
#if DIRECTX
internal SharpDX.Direct3D11.InputElement[] GetInputLayout()
{
var inputs = new SharpDX.Direct3D11.InputElement[_elements.Length];
for (var i = 0; i < _elements.Length; i++)
inputs[i] = _elements[i].GetInputElement();
return inputs;
}
#endif
#if PSM
internal VertexFormat[] GetVertexFormat()
{
if (_vertexFormat == null)
{
_vertexFormat = new VertexFormat[_elements.Length];
for (int i = 0; i < _vertexFormat.Length; i++)
_vertexFormat[i] = PSSHelper.ToVertexFormat(_elements[i].VertexElementFormat);
}
return _vertexFormat;
}
#endif
#if OPENGL
/// <summary>
/// Vertex attribute information for a particular shader/vertex declaration combination.
/// </summary>
class VertexDeclarationAttributeInfo
{
internal bool[] EnabledAttributes;
internal class Element
{
public int Offset;
public int AttributeLocation;
public int NumberOfElements;
#if GLES
public All VertexAttribPointerType;
#elif OPENGL
public VertexAttribPointerType VertexAttribPointerType;
#endif
public bool Normalized;
}
internal List<Element> Elements;
internal VertexDeclarationAttributeInfo(int maxVertexAttributes)
{
EnabledAttributes = new bool[maxVertexAttributes];
Elements = new List<Element>();
}
}
#endif
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Lifetime;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using log4net;
using Nini.Config;
using OpenSim.Framework;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using Aurora.Framework;
using Aurora.Simulation.Base;
using Aurora.ScriptEngine.AuroraDotNetEngine.Plugins;
using Aurora.ScriptEngine.AuroraDotNetEngine.CompilerTools;
using Aurora.ScriptEngine.AuroraDotNetEngine.APIs.Interfaces;
using Aurora.ScriptEngine.AuroraDotNetEngine.APIs;
using Aurora.ScriptEngine.AuroraDotNetEngine.Runtime;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Scenes.Components;
namespace Aurora.ScriptEngine.AuroraDotNetEngine
{
public class ScriptStateSave
{
private ScriptEngine m_module;
private IComponentManager m_manager;
private string m_componentName = "ScriptState";
public void Initialize (ScriptEngine module)
{
m_module = module;
m_manager = module.Worlds[0].RequestModuleInterface<IComponentManager> ();
DefaultComponents com = new DefaultComponents (m_componentName);
m_manager.RegisterComponent (com);
}
public void AddScene (Scene scene)
{
scene.AuroraEventManager.OnGenericEvent += AuroraEventManager_OnGenericEvent;
}
public void Close ()
{
}
object AuroraEventManager_OnGenericEvent (string FunctionName, object parameters)
{
if (FunctionName == "DeleteToInventory")
{
//Resave all the state saves for this object
ISceneEntity entity = (ISceneEntity)parameters;
foreach(ISceneChildEntity child in entity.ChildrenEntities())
{
m_module.SaveStateSaves (child.UUID);
}
}
return null;
}
public void SaveStateTo(ScriptData script)
{
StateSave stateSave = new StateSave();
stateSave.State = script.State;
stateSave.ItemID = script.ItemID;
stateSave.Running = script.Running;
stateSave.MinEventDelay = script.EventDelayTicks;
stateSave.Disabled = script.Disabled;
stateSave.UserInventoryID = script.UserInventoryItemID;
//Allow for the full path to be put down, not just the assembly name itself
stateSave.AssemblyName = script.AssemblyName;
stateSave.Source = script.Source;
if (script.InventoryItem != null)
{
stateSave.PermsGranter = script.InventoryItem.PermsGranter;
stateSave.PermsMask = script.InventoryItem.PermsMask;
}
else
{
stateSave.PermsGranter = UUID.Zero;
stateSave.PermsMask = 0;
}
stateSave.TargetOmegaWasSet = script.TargetOmegaWasSet;
//Vars
Dictionary<string, Object> vars = new Dictionary<string, object>();
if (script.Script != null)
vars = script.Script.GetStoreVars();
stateSave.Variables = WebUtils.BuildXmlResponse(vars);
//Plugins
stateSave.Plugins = m_module.GetSerializationData(script.ItemID, script.Part.UUID);
CreateOSDMapForState(script, stateSave);
}
public void Deserialize (ScriptData instance, StateSave save)
{
instance.State = save.State;
instance.Running = save.Running;
instance.EventDelayTicks = (long)save.MinEventDelay;
instance.AssemblyName = save.AssemblyName;
instance.Disabled = save.Disabled;
instance.UserInventoryItemID = save.UserInventoryID;
instance.PluginData = save.Plugins;
instance.Source = save.Source;
instance.InventoryItem.PermsGranter = save.PermsGranter;
instance.InventoryItem.PermsMask = save.PermsMask;
instance.TargetOmegaWasSet = save.TargetOmegaWasSet;
Dictionary<string, object> vars = WebUtils.ParseXmlResponse (save.Variables);
if (vars != null && vars.Count != 0 || instance.Script != null)
instance.Script.SetStoreVars (vars);
}
public StateSave FindScriptStateSave (ScriptData script)
{
OSDMap component = m_manager.GetComponentState (script.Part, m_componentName) as OSDMap;
//Attempt to find the state saves we have
if (component != null)
{
OSD o;
//If we have one for this item, deserialize it
if (!component.TryGetValue (script.ItemID.ToString (), out o))
{
if (!component.TryGetValue (script.InventoryItem.OldItemID.ToString (), out o))
{
return null;
}
}
StateSave save = new StateSave ();
save.FromOSD ((OSDMap)o);
return save;
}
return null;
}
public Task DeleteFrom (ScriptData script)
{
return TaskEx.Run(() =>
{
OSDMap component = (OSDMap)m_manager.GetComponentState(script.Part, m_componentName);
//Attempt to find the state saves we have
if (component != null)
{
//if we did remove something, resave it
if (component.Remove(script.ItemID.ToString()))
{
m_manager.SetComponentState(script.Part, m_componentName, component);
}
}
});
}
private void CreateOSDMapForState (ScriptData script, StateSave save)
{
//Get any previous state saves from the component manager
OSDMap component = m_manager.GetComponentState (script.Part, m_componentName) as OSDMap;
if (component == null)
component = new OSDMap ();
//Add our state to the list of all scripts in this object
component[script.ItemID.ToString ()] = save.ToOSD ();
script.Part.ParentEntity.HasGroupChanged = true;
//Now resave it
m_manager.SetComponentState (script.Part, m_componentName, component);
}
}
}
| |
// 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.ComponentModel.Design;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Task = System.Threading.Tasks.Task;
namespace Microsoft.VisualStudioTools
{
internal class UIThread : UIThreadBase
{
private readonly TaskScheduler _scheduler;
private readonly TaskFactory _factory;
private readonly Thread _uiThread;
private UIThread()
{
if (SynchronizationContext.Current == null)
{
SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
}
this._scheduler = TaskScheduler.FromCurrentSynchronizationContext();
this._factory = new TaskFactory(this._scheduler);
this._uiThread = Thread.CurrentThread;
}
public static void EnsureService(IServiceContainer container)
{
if (container.GetService(typeof(UIThreadBase)) == null)
{
container.AddService(typeof(UIThreadBase), new UIThread(), true);
}
}
public override bool InvokeRequired => Thread.CurrentThread != this._uiThread;
public override void MustBeCalledFromUIThreadOrThrow()
{
if (this.InvokeRequired)
{
const int RPC_E_WRONG_THREAD = unchecked((int)0x8001010E);
throw new COMException("Invalid cross-thread call", RPC_E_WRONG_THREAD);
}
}
/// <summary>
/// Executes the specified action on the UI thread. Returns once the
/// action has been completed.
/// </summary>
/// <remarks>
/// If called from the UI thread, the action is executed synchronously.
/// </remarks>
public override void Invoke(Action action)
{
if (this.InvokeRequired)
{
this._factory.StartNew(action).GetAwaiter().GetResult();
}
else
{
action();
}
}
/// <summary>
/// Evaluates the specified function on the UI thread. Returns once the
/// function has completed.
/// </summary>
/// <remarks>
/// If called from the UI thread, the function is evaluated
/// synchronously.
/// </remarks>
public override T Invoke<T>(Func<T> func)
{
if (this.InvokeRequired)
{
return this._factory.StartNew(func).GetAwaiter().GetResult();
}
else
{
return func();
}
}
/// <summary>
/// Executes the specified action on the UI thread. The task is
/// completed once the action completes.
/// </summary>
/// <remarks>
/// If called from the UI thread, the action is executed synchronously.
/// </remarks>
public override Task InvokeAsync(Action action)
{
var tcs = new TaskCompletionSource<object>();
if (this.InvokeRequired)
{
return this._factory.StartNew(action);
}
else
{
// Action is run synchronously, but we still return the task.
InvokeAsyncHelper(action, tcs);
}
return tcs.Task;
}
/// <summary>
/// Evaluates the specified function on the UI thread. The task is
/// completed once the result is available.
/// </summary>
/// <remarks>
/// If called from the UI thread, the function is evaluated
/// synchronously.
/// </remarks>
public override Task<T> InvokeAsync<T>(Func<T> func)
{
var tcs = new TaskCompletionSource<T>();
if (this.InvokeRequired)
{
return this._factory.StartNew(func);
}
else
{
// Function is run synchronously, but we still return the task.
InvokeAsyncHelper(func, tcs);
}
return tcs.Task;
}
/// <summary>
/// Awaits the provided task on the UI thread. The function will be
/// invoked on the UI thread to ensure the correct context is captured
/// for any await statements within the task.
/// </summary>
/// <remarks>
/// If called from the UI thread, the function is evaluated
/// synchronously.
/// </remarks>
public override Task InvokeTask(Func<Task> func)
{
var tcs = new TaskCompletionSource<object>();
if (this.InvokeRequired)
{
InvokeAsync(() => InvokeTaskHelper(func, tcs));
}
else
{
// Function is run synchronously, but we still return the task.
InvokeTaskHelper(func, tcs);
}
return tcs.Task;
}
/// <summary>
/// Awaits the provided task on the UI thread. The function will be
/// invoked on the UI thread to ensure the correct context is captured
/// for any await statements within the task.
/// </summary>
/// <remarks>
/// If called from the UI thread, the function is evaluated
/// synchronously.
/// </remarks>
public override Task<T> InvokeTask<T>(Func<Task<T>> func)
{
var tcs = new TaskCompletionSource<T>();
if (this.InvokeRequired)
{
InvokeAsync(() => InvokeTaskHelper(func, tcs));
}
else
{
// Function is run synchronously, but we still return the task.
InvokeTaskHelper(func, tcs);
}
return tcs.Task;
}
#region Helper Functions
internal static void InvokeAsyncHelper(Action action, TaskCompletionSource<object> tcs)
{
try
{
action();
tcs.TrySetResult(null);
}
catch (OperationCanceledException)
{
tcs.TrySetCanceled();
}
catch (Exception ex)
{
if (ex.IsCriticalException())
{
throw;
}
tcs.TrySetException(ex);
}
}
internal static void InvokeAsyncHelper<T>(Func<T> func, TaskCompletionSource<T> tcs)
{
try
{
tcs.TrySetResult(func());
}
catch (OperationCanceledException)
{
tcs.TrySetCanceled();
}
catch (Exception ex)
{
if (ex.IsCriticalException())
{
throw;
}
tcs.TrySetException(ex);
}
}
internal static async void InvokeTaskHelper(Func<Task> func, TaskCompletionSource<object> tcs)
{
try
{
await func();
tcs.TrySetResult(null);
}
catch (OperationCanceledException)
{
tcs.TrySetCanceled();
}
catch (Exception ex)
{
if (ex.IsCriticalException())
{
throw;
}
tcs.TrySetException(ex);
}
}
internal static async void InvokeTaskHelper<T>(Func<Task<T>> func, TaskCompletionSource<T> tcs)
{
try
{
tcs.TrySetResult(await func());
}
catch (OperationCanceledException)
{
tcs.TrySetCanceled();
}
catch (Exception ex)
{
if (ex.IsCriticalException())
{
throw;
}
tcs.TrySetException(ex);
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Localization;
using Microsoft.Extensions.Localization;
using OrchardCore.ContentManagement.Metadata;
using OrchardCore.ContentManagement.Metadata.Models;
using OrchardCore.ContentManagement.Metadata.Settings;
using OrchardCore.ContentTypes.Editors;
using OrchardCore.ContentTypes.Services;
using OrchardCore.ContentTypes.ViewModels;
using OrchardCore.DisplayManagement.ModelBinding;
using OrchardCore.DisplayManagement.Notify;
using OrchardCore.Mvc.Utilities;
using OrchardCore.Routing;
using YesSql;
namespace OrchardCore.ContentTypes.Controllers
{
public class AdminController : Controller
{
private readonly IContentDefinitionService _contentDefinitionService;
private readonly IContentDefinitionManager _contentDefinitionManager;
private readonly IAuthorizationService _authorizationService;
private readonly ISession _session;
private readonly IContentDefinitionDisplayManager _contentDefinitionDisplayManager;
private readonly IHtmlLocalizer H;
private readonly IStringLocalizer S;
private readonly INotifier _notifier;
private readonly IUpdateModelAccessor _updateModelAccessor;
public AdminController(
IContentDefinitionDisplayManager contentDefinitionDisplayManager,
IContentDefinitionService contentDefinitionService,
IContentDefinitionManager contentDefinitionManager,
IAuthorizationService authorizationService,
ISession session,
IHtmlLocalizer<AdminController> htmlLocalizer,
IStringLocalizer<AdminController> stringLocalizer,
INotifier notifier,
IUpdateModelAccessor updateModelAccessor)
{
_notifier = notifier;
_contentDefinitionDisplayManager = contentDefinitionDisplayManager;
_session = session;
_authorizationService = authorizationService;
_contentDefinitionService = contentDefinitionService;
_contentDefinitionManager = contentDefinitionManager;
_updateModelAccessor = updateModelAccessor;
H = htmlLocalizer;
S = stringLocalizer;
}
public Task<ActionResult> Index()
{
return List();
}
#region Types
public async Task<ActionResult> List()
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ViewContentTypes))
{
return Forbid();
}
return View("List", new ListContentTypesViewModel
{
Types = _contentDefinitionService.GetTypes()
});
}
public async Task<ActionResult> Create(string suggestion)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContentTypes))
{
return Forbid();
}
return View(new CreateTypeViewModel { DisplayName = suggestion, Name = suggestion.ToSafeName() });
}
[HttpPost, ActionName("Create")]
public async Task<ActionResult> CreatePOST(CreateTypeViewModel viewModel)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContentTypes))
{
return Forbid();
}
viewModel.DisplayName = viewModel.DisplayName?.Trim() ?? String.Empty;
viewModel.Name = viewModel.Name ?? String.Empty;
if (String.IsNullOrWhiteSpace(viewModel.DisplayName))
{
ModelState.AddModelError("DisplayName", S["The Display Name can't be empty."]);
}
if (_contentDefinitionService.LoadTypes().Any(t => String.Equals(t.DisplayName.Trim(), viewModel.DisplayName.Trim(), StringComparison.OrdinalIgnoreCase)))
{
ModelState.AddModelError("DisplayName", S["A type with the same Display Name already exists."]);
}
if (String.IsNullOrWhiteSpace(viewModel.Name))
{
ModelState.AddModelError("Name", S["The Technical Name can't be empty."]);
}
if (!String.IsNullOrWhiteSpace(viewModel.Name) && !viewModel.Name[0].IsLetter())
{
ModelState.AddModelError("Name", S["The Technical Name must start with a letter."]);
}
if (!String.Equals(viewModel.Name, viewModel.Name.ToSafeName(), StringComparison.OrdinalIgnoreCase))
{
ModelState.AddModelError("Name", S["The Technical Name contains invalid characters."]);
}
if (_contentDefinitionService.LoadTypes().Any(t => String.Equals(t.Name.Trim(), viewModel.Name.Trim(), StringComparison.OrdinalIgnoreCase)))
{
ModelState.AddModelError("Name", S["A type with the same Technical Name already exists."]);
}
if (!ModelState.IsValid)
{
_session.Cancel();
return View(viewModel);
}
var contentTypeDefinition = _contentDefinitionService.AddType(viewModel.Name, viewModel.DisplayName);
var typeViewModel = new EditTypeViewModel(contentTypeDefinition);
_notifier.Success(H["The \"{0}\" content type has been created.", typeViewModel.DisplayName]);
return RedirectToAction("AddPartsTo", new { id = typeViewModel.Name });
}
public async Task<ActionResult> Edit(string id)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContentTypes))
{
return Forbid();
}
var typeViewModel = _contentDefinitionService.GetType(id);
if (typeViewModel == null)
{
return NotFound();
}
typeViewModel.Editor = await _contentDefinitionDisplayManager.BuildTypeEditorAsync(typeViewModel.TypeDefinition, _updateModelAccessor.ModelUpdater);
return View(typeViewModel);
}
[HttpPost, ActionName("Edit")]
[FormValueRequired("submit.Save")]
public async Task<ActionResult> EditPOST(string id, EditTypeViewModel viewModel)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContentTypes))
{
return Forbid();
}
var contentTypeDefinition = _contentDefinitionManager.LoadTypeDefinition(id);
if (contentTypeDefinition == null)
{
return NotFound();
}
viewModel.Settings = contentTypeDefinition.Settings;
viewModel.TypeDefinition = contentTypeDefinition;
viewModel.DisplayName = contentTypeDefinition.DisplayName;
viewModel.Editor = await _contentDefinitionDisplayManager.UpdateTypeEditorAsync(contentTypeDefinition, _updateModelAccessor.ModelUpdater);
if (!ModelState.IsValid)
{
_session.Cancel();
return View(viewModel);
}
else
{
var ownedPartDefinition = _contentDefinitionManager.LoadPartDefinition(contentTypeDefinition.Name);
if (ownedPartDefinition != null && viewModel.OrderedFieldNames != null)
{
_contentDefinitionService.AlterPartFieldsOrder(ownedPartDefinition, viewModel.OrderedFieldNames);
}
_contentDefinitionService.AlterTypePartsOrder(contentTypeDefinition, viewModel.OrderedPartNames);
_notifier.Success(H["\"{0}\" settings have been saved.", contentTypeDefinition.Name]);
}
return RedirectToAction("Edit", new { id });
}
[HttpPost, ActionName("Edit")]
[FormValueRequired("submit.Delete")]
public async Task<ActionResult> Delete(string id)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContentTypes))
{
return Forbid();
}
var typeViewModel = _contentDefinitionService.LoadType(id);
if (typeViewModel == null)
{
return NotFound();
}
_contentDefinitionService.RemoveType(id, true);
_notifier.Success(H["\"{0}\" has been removed.", typeViewModel.DisplayName]);
return RedirectToAction("List");
}
public async Task<ActionResult> AddPartsTo(string id)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContentTypes))
{
return Forbid();
}
var typeViewModel = _contentDefinitionService.GetType(id);
if (typeViewModel == null)
{
return NotFound();
}
var typePartNames = new HashSet<string>(typeViewModel.TypeDefinition.Parts.Select(p => p.PartDefinition.Name));
var viewModel = new AddPartsViewModel
{
Type = typeViewModel,
PartSelections = _contentDefinitionService.GetParts(metadataPartsOnly: false)
.Where(cpd => !typePartNames.Contains(cpd.Name) && cpd.PartDefinition != null ? cpd.PartDefinition.GetSettings<ContentPartSettings>().Attachable : false)
.Select(cpd => new PartSelectionViewModel { PartName = cpd.Name, PartDisplayName = cpd.DisplayName, PartDescription = cpd.Description })
.ToList()
};
return View(viewModel);
}
public async Task<ActionResult> AddReusablePartTo(string id)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContentTypes))
{
return Forbid();
}
var typeViewModel = _contentDefinitionService.GetType(id);
if (typeViewModel == null)
{
return NotFound();
}
var reusableParts = _contentDefinitionService.GetParts(metadataPartsOnly: false)
.Where(cpd => cpd.PartDefinition != null ?
(cpd.PartDefinition.GetSettings<ContentPartSettings>().Attachable &&
cpd.PartDefinition.GetSettings<ContentPartSettings>().Reusable) : false);
var viewModel = new AddReusablePartViewModel
{
Type = typeViewModel,
PartSelections = reusableParts
.Select(cpd => new PartSelectionViewModel { PartName = cpd.Name, PartDisplayName = cpd.DisplayName, PartDescription = cpd.Description })
.ToList(),
SelectedPartName = reusableParts.FirstOrDefault()?.Name
};
return View(viewModel);
}
[HttpPost, ActionName("AddPartsTo")]
public async Task<ActionResult> AddPartsToPOST(string id)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContentTypes))
{
return Forbid();
}
var typeViewModel = _contentDefinitionService.LoadType(id);
if (typeViewModel == null)
{
return NotFound();
}
var viewModel = new AddPartsViewModel();
if (!await TryUpdateModelAsync(viewModel))
{
return await AddPartsTo(id);
}
var partsToAdd = viewModel.PartSelections.Where(ps => ps.IsSelected).Select(ps => ps.PartName);
foreach (var partToAdd in partsToAdd)
{
_contentDefinitionService.AddPartToType(partToAdd, typeViewModel.Name);
_notifier.Success(H["The \"{0}\" part has been added.", partToAdd]);
}
if (!ModelState.IsValid)
{
_session.Cancel();
return await AddPartsTo(id);
}
return RedirectToAction("Edit", new { id });
}
[HttpPost, ActionName("AddReusablePartTo")]
public async Task<ActionResult> AddReusablePartToPOST(string id)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContentTypes))
{
return Forbid();
}
var typeViewModel = _contentDefinitionService.LoadType(id);
if (typeViewModel == null)
{
return NotFound();
}
var viewModel = new AddReusablePartViewModel();
if (!await TryUpdateModelAsync(viewModel))
{
return await AddReusablePartTo(id);
}
viewModel.DisplayName = viewModel.DisplayName?.Trim() ?? String.Empty;
viewModel.Name = viewModel.Name ?? String.Empty;
if (String.IsNullOrWhiteSpace(viewModel.DisplayName))
{
ModelState.AddModelError("DisplayName", S["The Display Name can't be empty."]);
}
if (typeViewModel.TypeDefinition.Parts.Any(f => String.Equals(f.DisplayName().Trim(), viewModel.DisplayName.Trim(), StringComparison.OrdinalIgnoreCase)))
{
ModelState.AddModelError("DisplayName", S["A part with the same Display Name already exists."]);
}
if (!String.IsNullOrWhiteSpace(viewModel.Name) && !viewModel.Name[0].IsLetter())
{
ModelState.AddModelError("Name", S["The Technical Name must start with a letter."]);
}
if (!String.Equals(viewModel.Name, viewModel.Name.ToSafeName(), StringComparison.OrdinalIgnoreCase))
{
ModelState.AddModelError("Name", S["The Technical Name contains invalid characters."]);
}
if (String.IsNullOrWhiteSpace(viewModel.Name))
{
ModelState.AddModelError("Name", S["The Technical Name can't be empty."]);
}
if (typeViewModel.TypeDefinition.Parts.Any(f => String.Equals(f.Name.Trim(), viewModel.Name.Trim(), StringComparison.OrdinalIgnoreCase)))
{
ModelState.AddModelError("Name", S["A part with the same Technical Name already exists."]);
}
if (!ModelState.IsValid)
{
_session.Cancel();
return await AddReusablePartTo(id);
}
var partToAdd = viewModel.SelectedPartName;
_contentDefinitionService.AddReusablePartToType(viewModel.Name, viewModel.DisplayName, viewModel.Description, partToAdd, typeViewModel.Name);
_notifier.Success(H["The \"{0}\" part has been added.", partToAdd]);
return RedirectToAction("Edit", new { id });
}
[HttpPost, ActionName("RemovePart")]
public async Task<ActionResult> RemovePart(string id, string name)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContentTypes))
{
return Forbid();
}
var typeViewModel = _contentDefinitionService.LoadType(id);
if (typeViewModel == null || !typeViewModel.TypeDefinition.Parts.Any(p => p.Name == name))
{
return NotFound();
}
_contentDefinitionService.RemovePartFromType(name, id);
_notifier.Success(H["The \"{0}\" part has been removed.", name]);
return RedirectToAction("Edit", new { id });
}
#endregion Types
#region Parts
public async Task<ActionResult> ListParts()
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ViewContentTypes))
{
return Forbid();
}
return View(new ListContentPartsViewModel
{
// only user-defined parts (not code as they are not configurable)
Parts = _contentDefinitionService.GetParts(true/*metadataPartsOnly*/)
});
}
public async Task<ActionResult> CreatePart(string suggestion)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContentTypes))
{
return Forbid();
}
return View(new CreatePartViewModel { Name = suggestion.ToSafeName() });
}
[HttpPost, ActionName("CreatePart")]
public async Task<ActionResult> CreatePartPOST(CreatePartViewModel viewModel)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContentTypes))
{
return Forbid();
}
viewModel.Name = viewModel.Name ?? String.Empty;
if (String.IsNullOrWhiteSpace(viewModel.Name))
{
ModelState.AddModelError("Name", S["The Technical Name can't be empty."]);
}
if (_contentDefinitionService.LoadParts(false).Any(p => String.Equals(p.Name.Trim(), viewModel.Name.Trim(), StringComparison.OrdinalIgnoreCase)))
{
ModelState.AddModelError("Name", S["A part with the same Technical Name already exists."]);
}
if (!String.IsNullOrWhiteSpace(viewModel.Name) && !viewModel.Name[0].IsLetter())
{
ModelState.AddModelError("Name", S["The Technical Name must start with a letter."]);
}
if (!String.Equals(viewModel.Name, viewModel.Name.ToSafeName(), StringComparison.OrdinalIgnoreCase))
{
ModelState.AddModelError("Name", S["The Technical Name contains invalid characters."]);
}
if (!ModelState.IsValid)
{
return View(viewModel);
}
var partViewModel = _contentDefinitionService.AddPart(viewModel);
if (partViewModel == null)
{
_notifier.Information(H["The content part could not be created."]);
return View(viewModel);
}
_notifier.Success(H["The \"{0}\" content part has been created.", partViewModel.Name]);
return RedirectToAction("EditPart", new { id = partViewModel.Name });
}
public async Task<ActionResult> EditPart(string id)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContentTypes))
{
return Forbid();
}
var contentPartDefinition = _contentDefinitionManager.GetPartDefinition(id);
if (contentPartDefinition == null)
{
return NotFound();
}
var viewModel = new EditPartViewModel(contentPartDefinition);
viewModel.Editor = await _contentDefinitionDisplayManager.BuildPartEditorAsync(contentPartDefinition, _updateModelAccessor.ModelUpdater);
return View(viewModel);
}
[HttpPost, ActionName("EditPart")]
[FormValueRequired("submit.Save")]
public async Task<ActionResult> EditPartPOST(string id, string[] orderedFieldNames)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContentTypes))
{
return Forbid();
}
var contentPartDefinition = _contentDefinitionManager.LoadPartDefinition(id);
if (contentPartDefinition == null)
{
return NotFound();
}
var viewModel = new EditPartViewModel(contentPartDefinition);
viewModel.Editor = await _contentDefinitionDisplayManager.UpdatePartEditorAsync(contentPartDefinition, _updateModelAccessor.ModelUpdater);
if (!ModelState.IsValid)
{
_session.Cancel();
return View(viewModel);
}
else
{
_contentDefinitionService.AlterPartFieldsOrder(contentPartDefinition, orderedFieldNames);
_notifier.Success(H["The settings of \"{0}\" have been saved.", contentPartDefinition.Name]);
}
return RedirectToAction("EditPart", new { id });
}
[HttpPost, ActionName("EditPart")]
[FormValueRequired("submit.Delete")]
public async Task<ActionResult> DeletePart(string id)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContentTypes))
{
return Forbid();
}
var partViewModel = _contentDefinitionService.LoadPart(id);
if (partViewModel == null)
{
return NotFound();
}
_contentDefinitionService.RemovePart(id);
_notifier.Information(H["\"{0}\" has been removed.", partViewModel.DisplayName]);
return RedirectToAction("ListParts");
}
public async Task<ActionResult> AddFieldTo(string id, string returnUrl = null)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContentTypes))
{
return Forbid();
}
var partViewModel = _contentDefinitionService.LoadPart(id);
if (partViewModel == null)
{
return NotFound();
}
var viewModel = new AddFieldViewModel
{
Part = partViewModel.PartDefinition,
Fields = _contentDefinitionService.GetFields().Select(x => x.Name).OrderBy(x => x).ToList()
};
ViewData["ReturnUrl"] = returnUrl;
return View(viewModel);
}
[HttpPost, ActionName("AddFieldTo")]
public async Task<ActionResult> AddFieldToPOST(AddFieldViewModel viewModel, string id, string returnUrl = null)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContentTypes))
{
return Forbid();
}
var partViewModel = _contentDefinitionService.LoadPart(id);
if (partViewModel == null)
{
return NotFound();
}
var partDefinition = partViewModel.PartDefinition;
viewModel.DisplayName = viewModel.DisplayName?.Trim() ?? String.Empty;
viewModel.Name = viewModel.Name ?? String.Empty;
if (String.IsNullOrWhiteSpace(viewModel.DisplayName))
{
ModelState.AddModelError("DisplayName", S["The Display Name can't be empty."]);
}
if (partDefinition.Fields.Any(f => String.Equals(f.DisplayName().Trim(), viewModel.DisplayName.Trim(), StringComparison.OrdinalIgnoreCase)))
{
ModelState.AddModelError("DisplayName", S["A field with the same Display Name already exists."]);
}
if (String.IsNullOrWhiteSpace(viewModel.Name))
{
ModelState.AddModelError("Name", S["The Technical Name can't be empty."]);
}
if (partDefinition.Fields.Any(f => String.Equals(f.Name.Trim(), viewModel.Name.Trim(), StringComparison.OrdinalIgnoreCase)))
{
ModelState.AddModelError("Name", S["A field with the same Technical Name already exists."]);
}
if (!String.IsNullOrWhiteSpace(viewModel.Name) && !viewModel.Name[0].IsLetter())
{
ModelState.AddModelError("Name", S["The Technical Name must start with a letter."]);
}
if (!String.Equals(viewModel.Name, viewModel.Name.ToSafeName(), StringComparison.OrdinalIgnoreCase))
{
ModelState.AddModelError("Name", S["The Technical Name contains invalid characters."]);
}
if (!ModelState.IsValid)
{
viewModel.Part = partDefinition;
viewModel.Fields = _contentDefinitionService.GetFields().Select(x => x.Name).OrderBy(x => x).ToList();
_session.Cancel();
ViewData["ReturnUrl"] = returnUrl;
return View(viewModel);
}
_contentDefinitionService.AddFieldToPart(viewModel.Name, viewModel.DisplayName, viewModel.FieldTypeName, partDefinition.Name);
_notifier.Success(H["The field \"{0}\" has been added.", viewModel.DisplayName]);
if (!String.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("EditField", new { id, viewModel.Name });
}
}
public async Task<ActionResult> EditField(string id, string name, string returnUrl = null)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContentTypes))
{
return Forbid();
}
var partViewModel = _contentDefinitionService.GetPart(id);
if (partViewModel == null)
{
return NotFound();
}
var partFieldDefinition = partViewModel.PartDefinition.Fields.FirstOrDefault(x => x.Name == name);
if (partFieldDefinition == null)
{
return NotFound();
}
var viewModel = new EditFieldViewModel
{
Name = partFieldDefinition.Name,
Editor = partFieldDefinition.Editor(),
DisplayMode = partFieldDefinition.DisplayMode(),
DisplayName = partFieldDefinition.DisplayName(),
PartFieldDefinition = partFieldDefinition,
Shape = await _contentDefinitionDisplayManager.BuildPartFieldEditorAsync(partFieldDefinition, _updateModelAccessor.ModelUpdater)
};
ViewData["ReturnUrl"] = returnUrl;
return View(viewModel);
}
[HttpPost, ActionName("EditField")]
[FormValueRequired("submit.Save")]
public async Task<ActionResult> EditFieldPOST(string id, EditFieldViewModel viewModel, string returnUrl = null)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContentTypes))
{
return Forbid();
}
if (viewModel == null)
{
return NotFound();
}
var partViewModel = _contentDefinitionService.LoadPart(id);
if (partViewModel == null)
{
return NotFound();
}
var field = _contentDefinitionManager.LoadPartDefinition(id).Fields.FirstOrDefault(x => x.Name == viewModel.Name);
if (field == null)
{
return NotFound();
}
viewModel.PartFieldDefinition = field;
if (field.DisplayName() != viewModel.DisplayName)
{
// prevent null reference exception in validation
viewModel.DisplayName = viewModel.DisplayName?.Trim() ?? String.Empty;
if (String.IsNullOrWhiteSpace(viewModel.DisplayName))
{
ModelState.AddModelError("DisplayName", S["The Display Name can't be empty."]);
}
if (_contentDefinitionService.LoadPart(partViewModel.Name).PartDefinition.Fields.Any(t => t.Name != viewModel.Name && String.Equals(t.DisplayName().Trim(), viewModel.DisplayName.Trim(), StringComparison.OrdinalIgnoreCase)))
{
ModelState.AddModelError("DisplayName", S["A field with the same Display Name already exists."]);
}
if (!ModelState.IsValid)
{
// Calls update to build editor shape with the display name validation failures, and other validation errors.
viewModel.Shape = await _contentDefinitionDisplayManager.UpdatePartFieldEditorAsync(field, _updateModelAccessor.ModelUpdater);
_session.Cancel();
ViewData["ReturnUrl"] = returnUrl;
return View(viewModel);
}
_notifier.Information(H["Display name changed to {0}.", viewModel.DisplayName]);
}
_contentDefinitionService.AlterField(partViewModel, viewModel);
// Refresh the local field variable in case it has been altered
field = _contentDefinitionManager.LoadPartDefinition(id).Fields.FirstOrDefault(x => x.Name == viewModel.Name);
viewModel.Shape = await _contentDefinitionDisplayManager.UpdatePartFieldEditorAsync(field, _updateModelAccessor.ModelUpdater);
if (!ModelState.IsValid)
{
_session.Cancel();
ViewData["ReturnUrl"] = returnUrl;
return View(viewModel);
}
else
{
_notifier.Success(H["The \"{0}\" field settings have been saved.", field.DisplayName()]);
}
if (!String.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
// Redirect to the type editor if a type exists with this name
var typeViewModel = _contentDefinitionService.LoadType(id);
if (typeViewModel != null)
{
return RedirectToAction("Edit", new { id });
}
return RedirectToAction("EditPart", new { id });
}
}
[HttpPost, ActionName("RemoveFieldFrom")]
public async Task<ActionResult> RemoveFieldFromPOST(string id, string name)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContentTypes))
{
return Forbid();
}
var partViewModel = _contentDefinitionService.LoadPart(id);
if (partViewModel == null)
{
return NotFound();
}
var field = partViewModel.PartDefinition.Fields.FirstOrDefault(x => x.Name == name);
if (field == null)
{
return NotFound();
}
_contentDefinitionService.RemoveFieldFromPart(name, partViewModel.Name);
_notifier.Success(H["The \"{0}\" field has been removed.", field.DisplayName()]);
if (_contentDefinitionService.LoadType(id) != null)
{
return RedirectToAction("Edit", new { id });
}
return RedirectToAction("EditPart", new { id });
}
#endregion Parts
#region Type Parts
public async Task<ActionResult> EditTypePart(string id, string name)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContentTypes))
{
return Forbid();
}
var typeDefinition = _contentDefinitionManager.GetTypeDefinition(id);
if (typeDefinition == null)
{
return NotFound();
}
var typePartDefinition = typeDefinition.Parts.FirstOrDefault(x => x.Name == name);
if (typePartDefinition == null)
{
return NotFound();
}
var typePartViewModel = new EditTypePartViewModel
{
Name = typePartDefinition.Name,
Editor = typePartDefinition.Editor(),
DisplayMode = typePartDefinition.DisplayMode(),
DisplayName = typePartDefinition.DisplayName(),
Description = typePartDefinition.Description(),
TypePartDefinition = typePartDefinition,
Shape = await _contentDefinitionDisplayManager.BuildTypePartEditorAsync(typePartDefinition, _updateModelAccessor.ModelUpdater)
};
return View(typePartViewModel);
}
[HttpPost, ActionName("EditTypePart")]
[FormValueRequired("submit.Save")]
public async Task<ActionResult> EditTypePartPOST(string id, EditTypePartViewModel viewModel)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContentTypes))
{
return Forbid();
}
if (viewModel == null)
{
return NotFound();
}
var typeDefinition = _contentDefinitionManager.LoadTypeDefinition(id);
if (typeDefinition == null)
{
return NotFound();
}
var part = typeDefinition.Parts.FirstOrDefault(x => x.Name == viewModel.Name);
if (part == null)
{
return NotFound();
}
viewModel.TypePartDefinition = part;
if (part.PartDefinition.IsReusable())
{
if (part.DisplayName() != viewModel.DisplayName)
{
// Prevent null reference exception in validation
viewModel.DisplayName = viewModel.DisplayName?.Trim() ?? String.Empty;
if (String.IsNullOrWhiteSpace(viewModel.DisplayName))
{
ModelState.AddModelError("DisplayName", S["The Display Name can't be empty."]);
}
if (typeDefinition.Parts.Any(t => t.Name != viewModel.Name && String.Equals(t.DisplayName()?.Trim(), viewModel.DisplayName.Trim(), StringComparison.OrdinalIgnoreCase)))
{
ModelState.AddModelError("DisplayName", S["A part with the same Display Name already exists."]);
}
if (!ModelState.IsValid)
{
viewModel.Shape = await _contentDefinitionDisplayManager.UpdateTypePartEditorAsync(part, _updateModelAccessor.ModelUpdater);
_session.Cancel();
return View(viewModel);
}
}
}
_contentDefinitionService.AlterTypePart(viewModel);
// Refresh the local part variable in case it has been altered
part = _contentDefinitionManager.LoadTypeDefinition(id).Parts.FirstOrDefault(x => x.Name == viewModel.Name);
viewModel.Shape = await _contentDefinitionDisplayManager.UpdateTypePartEditorAsync(part, _updateModelAccessor.ModelUpdater);
if (!ModelState.IsValid)
{
_session.Cancel();
return View(viewModel);
}
else
{
_notifier.Success(H["The \"{0}\" part settings have been saved.", part.DisplayName()]);
}
return RedirectToAction("Edit", new { id });
}
#endregion Type Parts
}
}
| |
// ****************************************************************
// This is free software licensed under the NUnit license. You
// may obtain a copy of the license as well as information regarding
// copyright ownership at http://nunit.org.
// ****************************************************************
namespace NUnit.Core
{
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Threading;
using System.Reflection;
/// <summary>
/// Test Class.
/// </summary>
public abstract class Test : ITest, IComparable
{
#region Constants
//private static readonly string SETCULTURE = "_SETCULTURE";
private static readonly string DESCRIPTION = "_DESCRIPTION";
private static readonly string IGNOREREASON = "_IGNOREREASON";
private static readonly string CATEGORIES = "_CATEGORIES";
#endregion
#region Fields
/// <summary>
/// TestName that identifies this test
/// </summary>
private TestName testName;
/// <summary>
/// Indicates whether the test should be executed
/// </summary>
private RunState runState;
/// <summary>
/// Test suite containing this test, or null
/// </summary>
private Test parent;
/// <summary>
/// A dictionary of properties, used to add information
/// to tests without requiring the class to change.
/// </summary>
private IDictionary properties;
#endregion
#region Properties
/// <summary>
/// Return true if the test requires a thread
/// </summary>
public bool RequiresThread
{
get { return Properties.Contains("RequiresThread") && (bool)Properties["RequiresThread"]; }
}
/// <summary>
/// Get the desired apartment state for running the test
/// </summary>
public ApartmentState ApartmentState
{
get
{
return Properties.Contains("APARTMENT_STATE")
? (ApartmentState)Properties["APARTMENT_STATE"]
: GetCurrentApartment();
}
}
/// <summary>
/// Get the current apartment state of the test
/// </summary>
protected ApartmentState GetCurrentApartment()
{
#if NET_2_0
return Thread.CurrentThread.GetApartmentState();
#else
return Thread.CurrentThread.ApartmentState;
#endif
}
/// <summary>
/// Gets a boolean value indicating whether this
/// test should run on it's own thread.
/// </summary>
protected virtual bool ShouldRunOnOwnThread
{
get
{
return RequiresThread
|| ApartmentState != ApartmentState.Unknown
&& ApartmentState != GetCurrentApartment();
}
}
#endregion
#region Construction
/// <summary>
/// Constructs a test given its name
/// </summary>
/// <param name="name">The name of the test</param>
protected Test( string name )
{
this.testName = new TestName();
this.testName.FullName = name;
this.testName.Name = name;
this.testName.TestID = new TestID();
this.runState = RunState.Runnable;
}
/// <summary>
/// Constructs a test given the path through the
/// test hierarchy to its parent and a name.
/// </summary>
/// <param name="pathName">The parent tests full name</param>
/// <param name="name">The name of the test</param>
protected Test( string pathName, string name )
{
this.testName = new TestName();
this.testName.FullName = pathName == null || pathName == string.Empty
? name : pathName + "." + name;
this.testName.Name = name;
this.testName.TestID = new TestID();
this.runState = RunState.Runnable;
}
/// <summary>
/// Constructs a test given a TestName object
/// </summary>
/// <param name="testName">The TestName for this test</param>
protected Test( TestName testName )
{
this.testName = testName;
this.runState = RunState.Runnable;
}
/// <summary>
/// Sets the runner id of a test and optionally its children
/// </summary>
/// <param name="runnerID">The runner id to be used</param>
/// <param name="recursive">True if all children should get the same id</param>
public void SetRunnerID( int runnerID, bool recursive )
{
this.testName.RunnerID = runnerID;
if ( recursive && this.Tests != null )
foreach( Test child in this.Tests )
child.SetRunnerID( runnerID, true );
}
#endregion
#region ITest Members
#region Properties
/// <summary>
/// Gets the TestName of the test
/// </summary>
public TestName TestName
{
get { return testName; }
}
/// <summary>
/// Gets a string representing the kind of test
/// that this object represents, for use in display.
/// </summary>
public abstract string TestType
{
get;
}
/// <summary>
/// Whether or not the test should be run
/// </summary>
public RunState RunState
{
get { return runState; }
set { runState = value; }
}
/// <summary>
/// Reason for not running the test, if applicable
/// </summary>
public string IgnoreReason
{
get { return (string)Properties[IGNOREREASON]; }
set
{
if (value == null)
Properties.Remove(IGNOREREASON);
else
Properties[IGNOREREASON] = value;
}
}
/// <summary>
/// Gets a count of test cases represented by
/// or contained under this test.
/// </summary>
public virtual int TestCount
{
get { return 1; }
}
/// <summary>
/// Gets a list of categories associated with this test.
/// </summary>
public IList Categories
{
get
{
if (Properties[CATEGORIES] == null)
Properties[CATEGORIES] = new ArrayList();
return (IList)Properties[CATEGORIES];
}
set
{
Properties[CATEGORIES] = value;
}
}
/// <summary>
/// Gets a description associated with this test.
/// </summary>
public String Description
{
get { return (string)Properties[DESCRIPTION]; }
set
{
if (value == null)
Properties.Remove(DESCRIPTION);
else
Properties[DESCRIPTION] = value;
}
}
/// <summary>
/// Gets the property dictionary for this test
/// </summary>
public IDictionary Properties
{
get
{
if ( properties == null )
properties = new ListDictionary();
return properties;
}
set
{
properties = value;
}
}
/// <summary>
/// Indicates whether this test is a suite
/// </summary>
public virtual bool IsSuite
{
get { return false; }
}
/// <summary>
/// Gets the parent test of this test
/// </summary>
ITest ITest.Parent
{
get { return parent; }
}
/// <summary>
/// Gets the parent as a Test object.
/// Used by the core to set the parent.
/// </summary>
public Test Parent
{
get { return parent; }
set { parent = value; }
}
/// <summary>
/// Gets this test's child tests
/// </summary>
public virtual IList Tests
{
get { return null; }
}
/// <summary>
/// Gets the Type of the fixture used in running this test
/// </summary>
public virtual Type FixtureType
{
get { return null; }
}
/// <summary>
/// Gets or sets a fixture object for running this test
/// </summary>
public abstract object Fixture
{
get; set;
}
#endregion
#region Methods
/// <summary>
/// Gets a count of test cases that would be run using
/// the specified filter.
/// </summary>
/// <param name="filter"></param>
/// <returns></returns>
public virtual int CountTestCases(ITestFilter filter)
{
if (filter.Pass(this))
return 1;
return 0;
}
/// <summary>
/// Runs the test under a particular filter, sending
/// notifications to a listener.
/// </summary>
/// <param name="listener">An event listener to receive notifications</param>
/// <param name="filter">A filter used in running the test</param>
/// <returns></returns>
public abstract TestResult Run(EventListener listener, ITestFilter filter);
#endregion
#endregion
#region IComparable Members
/// <summary>
/// Compares this test to another test for sorting purposes
/// </summary>
/// <param name="obj">The other test</param>
/// <returns>Value of -1, 0 or +1 depending on whether the current test is less than, equal to or greater than the other test</returns>
public int CompareTo(object obj)
{
Test other = obj as Test;
if ( other == null )
return -1;
return this.TestName.FullName.CompareTo( other.TestName.FullName );
}
#endregion
}
}
| |
/******************************************************************************
* Copyright (C) Leap Motion, Inc. 2011-2017. *
* Leap Motion proprietary and confidential. *
* *
* Use subject to the terms of the Leap Motion SDK Agreement available at *
* https://developer.leapmotion.com/sdk_agreement, or another agreement *
* between Leap Motion and you, your company or other organization. *
******************************************************************************/
using System;
using UnityEngine;
namespace Leap.Unity {
public class Deque<T> {
private T[] _array;
private uint _front, _count;
private uint _indexMask;
public Deque(int minCapacity = 8) {
if (minCapacity <= 0) {
throw new ArgumentException("Capacity must be positive and nonzero.");
}
//Find next highest power of two
int capacity = Mathf.ClosestPowerOfTwo(minCapacity);
if (capacity < minCapacity) {
capacity *= 2;
}
_array = new T[capacity];
recalculateIndexMask();
_front = 0;
_count = 0;
}
public int Count {
get {
return (int)_count;
}
}
public void Clear() {
if (_count != 0) {
Array.Clear(_array, 0, _array.Length);
_front = 0;
_count = 0;
}
}
public void PushBack(T t) {
doubleCapacityIfFull();
++_count;
_array[getBackIndex()] = t;
}
public void PushFront(T t) {
doubleCapacityIfFull();
++_count;
_front = (_front - 1) & _indexMask;
_array[_front] = t;
}
public void PopBack() {
checkForEmpty("pop back");
_array[getBackIndex()] = default(T);
--_count;
}
public void PopFront() {
checkForEmpty("pop front");
_array[_front] = default(T);
--_count;
_front = (_front + 1) & _indexMask;
}
public void PopBack(out T back) {
checkForEmpty("pop back");
uint backIndex = getBackIndex();
back = _array[backIndex];
_array[backIndex] = default(T);
--_count;
}
public void PopFront(out T front) {
checkForEmpty("pop front");
front = _array[_front];
_array[_front] = default(T);
_front = (_front + 1) & _indexMask;
--_count;
}
public T Front {
get {
checkForEmpty("get front");
return _array[_front];
}
set {
checkForEmpty("set front");
_array[_front] = value;
}
}
public T Back {
get {
checkForEmpty("get back");
return _array[getBackIndex()];
}
set {
checkForEmpty("set back");
_array[getBackIndex()] = value;
}
}
public T this[int index] {
get {
uint uindex = (uint)index;
checkForValidIndex(uindex);
return _array[getIndex(uindex)];
}
set {
uint uindex = (uint)index;
checkForValidIndex(uindex);
_array[getIndex(uindex)] = value;
}
}
public string ToDebugString() {
string debug = "[";
uint back = getBackIndex();
for (uint i = 0; i < _array.Length; i++) {
bool isEmpty;
if (_count == 0) {
isEmpty = true;
} else if (_count == 1) {
isEmpty = i != _front;
} else if (_front < back) {
isEmpty = (i < _front) || (i > back);
} else {
isEmpty = (i < _front) && (i > back);
}
string element = "";
if (i == _front) {
element = "{";
} else {
element = " ";
}
if (isEmpty) {
element += ".";
} else {
element += _array[i].ToString();
}
if (i == back) {
element += "}";
} else {
element += " ";
}
debug += element;
}
debug += "]";
return debug;
}
private uint getBackIndex() {
return (_front + _count - 1) & _indexMask;
}
private uint getIndex(uint index) {
return (_front + index) & _indexMask;
}
private void doubleCapacityIfFull() {
if (_count >= _array.Length) {
T[] newArray = new T[_array.Length * 2];
uint front = getBackIndex();
if (_front <= front) {
//values do not wrap around, we can use a simple copy
Array.Copy(_array, _front, newArray, 0, _count);
} else {
//values do wrap around, we need to use 2 copies
uint backOffset = (uint)_array.Length - _front;
Array.Copy(_array, _front, newArray, 0, backOffset);
Array.Copy(_array, 0, newArray, backOffset, _count - backOffset);
}
_front = 0;
_array = newArray;
recalculateIndexMask();
}
}
private void recalculateIndexMask() {
//array length is always power of 2, so length-1 is the bitmask we need
//8 = 1000
//7 = 0111 = mask for values 0-7
_indexMask = (uint)_array.Length - 1;
}
private void checkForValidIndex(uint index) {
if (index >= _count) {
throw new IndexOutOfRangeException("The index " + index + " was out of range for the RingBuffer with size " + _count + ".");
}
}
private void checkForEmpty(string actionName) {
if (_count == 0) {
throw new InvalidOperationException("Cannot " + actionName + " because the RingBuffer is empty.");
}
}
}
}
| |
/*
* Copyright 2012-2015 Aerospike, Inc.
*
* Portions may be licensed to Aerospike, Inc. under one or more contributor
* license agreements.
*
* 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.Text;
using System.Net;
using System.Net.Sockets;
using System.Collections.Generic;
namespace Aerospike.Client
{
/// <summary>
/// Access server's info monitoring protocol.
/// <para>
/// The info protocol is a name/value pair based system, where an individual
/// database server node is queried to determine its configuration and status.
/// The list of supported names can be found at:
/// </para>
/// <para>
/// <a href="https://docs.aerospike.com/display/AS2/Config+Parameters+Reference">https://docs.aerospike.com/display/AS2/Config+Parameters+Reference</a>
/// </para>
/// </summary>
public sealed class Info
{
//-------------------------------------------------------
// Static variables.
//-------------------------------------------------------
private const int DEFAULT_TIMEOUT = 1000;
//-------------------------------------------------------
// Member variables.
//-------------------------------------------------------
private byte[] buffer;
private int length;
private int offset;
//-------------------------------------------------------
// Constructor
//-------------------------------------------------------
/// <summary>
/// Send single command to server and store results.
/// This constructor is used internally.
/// The static request methods should be used instead.
/// </summary>
/// <param name="conn">connection to server node</param>
/// <param name="command">command sent to server</param>
public Info(Connection conn, string command)
{
buffer = ThreadLocalData.GetBuffer();
// If conservative estimate may be exceeded, get exact estimate
// to preserve memory and resize buffer.
if ((command.Length * 2 + 9) > buffer.Length)
{
offset = ByteUtil.EstimateSizeUtf8(command) + 9;
ResizeBuffer(offset);
}
offset = 8; // Skip size field.
// The command format is: <name1>\n<name2>\n...
offset += ByteUtil.StringToUtf8(command, buffer, offset);
buffer[offset++] = (byte)'\n';
SendCommand(conn);
}
/// <summary>
/// Send multiple commands to server and store results.
/// This constructor is used internally.
/// The static request methods should be used instead.
/// </summary>
/// <param name="conn">connection to server node</param>
/// <param name="commands">commands sent to server</param>
public Info(Connection conn, params string[] commands)
{
buffer = ThreadLocalData.GetBuffer();
// First, do quick conservative buffer size estimate.
offset = 8;
foreach (string command in commands)
{
offset += command.Length * 2 + 1;
}
// If conservative estimate may be exceeded, get exact estimate
// to preserve memory and resize buffer.
if (offset > buffer.Length)
{
offset = 8;
foreach (string command in commands)
{
offset += ByteUtil.EstimateSizeUtf8(command) + 1;
}
ResizeBuffer(offset);
}
offset = 8; // Skip size field.
// The command format is: <name1>\n<name2>\n...
foreach (string command in commands)
{
offset += ByteUtil.StringToUtf8(command, buffer, offset);
buffer[offset++] = (byte)'\n';
}
SendCommand(conn);
}
/// <summary>
/// Send default empty command to server and store results.
/// This constructor is used internally.
/// The static request methods should be used instead.
/// </summary>
/// <param name="conn">connection to server node</param>
public Info(Connection conn)
{
buffer = ThreadLocalData.GetBuffer();
offset = 8; // Skip size field.
SendCommand(conn);
}
/// <summary>
/// Parse response in name/value pair format:
/// <para>
/// <command>\t<name1>=<value1>;<name2>=<value2>;...\n
/// </para>
/// </summary>
public NameValueParser GetNameValueParser()
{
SkipToValue();
return new NameValueParser(this);
}
/// <summary>
/// Return single value from response buffer.
/// </summary>
public string GetValue()
{
SkipToValue();
return ByteUtil.Utf8ToString(buffer, offset, length - offset - 1);
}
private void SkipToValue()
{
// Skip past command.
while (offset < length)
{
byte b = buffer[offset];
if (b == '\t')
{
offset++;
break;
}
if (b == '\n')
{
break;
}
offset++;
}
}
//-------------------------------------------------------
// Get Info via Node
//-------------------------------------------------------
/// <summary>
/// Get one info value by name from the specified database server node.
/// This method supports user authentication.
/// </summary>
/// <param name="node">server node</param>
/// <param name="name">name of variable to retrieve</param>
public static string Request(Node node, string name)
{
Connection conn = node.GetConnection(DEFAULT_TIMEOUT);
try
{
string response = Info.Request(conn, name);
node.PutConnection(conn);
return response;
}
catch (Exception)
{
conn.Close();
throw;
}
}
/// <summary>
/// Get one info value by name from the specified database server node.
/// This method supports user authentication.
/// </summary>
/// <param name="policy">info command configuration parameters, pass in null for defaults</param>
/// <param name="node">server node</param>
/// <param name="name">name of variable to retrieve</param>
public static string Request(InfoPolicy policy, Node node, string name)
{
int timeout = (policy == null) ? DEFAULT_TIMEOUT : policy.timeout;
Connection conn = node.GetConnection(timeout);
try
{
string result = Request(conn, name);
node.PutConnection(conn);
return result;
}
catch (Exception)
{
// Garbage may be in socket. Do not put back into pool.
conn.Close();
throw;
}
}
/// <summary>
/// Get many info values by name from the specified database server node.
/// This method supports user authentication.
/// </summary>
/// <param name="policy">info command configuration parameters, pass in null for defaults</param>
/// <param name="node">server node</param>
/// <param name="names">names of variables to retrieve</param>
public static Dictionary<string, string> Request(InfoPolicy policy, Node node, params string[] names)
{
int timeout = (policy == null) ? DEFAULT_TIMEOUT : policy.timeout;
Connection conn = node.GetConnection(timeout);
try
{
Dictionary<string, string> result = Request(conn, names);
node.PutConnection(conn);
return result;
}
catch (Exception)
{
// Garbage may be in socket. Do not put back into pool.
conn.Close();
throw;
}
}
/// <summary>
/// Get default info values from the specified database server node.
/// This method supports user authentication.
/// </summary>
/// <param name="policy">info command configuration parameters, pass in null for defaults</param>
/// <param name="node">server node</param>
public static Dictionary<string, string> Request(InfoPolicy policy, Node node)
{
int timeout = (policy == null) ? DEFAULT_TIMEOUT : policy.timeout;
Connection conn = node.GetConnection(timeout);
try
{
Dictionary<string, string> result = Request(conn);
node.PutConnection(conn);
return result;
}
catch (Exception)
{
// Garbage may be in socket. Do not put back into pool.
conn.Close();
throw;
}
}
//-------------------------------------------------------
// Get Info via Host Name and Port
//-------------------------------------------------------
/// <summary>
/// Get one info value by name from the specified database server node, using
/// host name and port.
/// This method does not support user authentication.
/// </summary>
/// <param name="hostname">host name</param>
/// <param name="port">host port</param>
/// <param name="name">name of value to retrieve</param>
public static string Request(string hostname, int port, string name)
{
IPAddress[] addresses = Connection.GetHostAddresses(hostname, DEFAULT_TIMEOUT);
IPEndPoint ipe = new IPEndPoint(addresses[0], port);
return Request(ipe, name);
}
/// <summary>
/// Get many info values by name from the specified database server node,
/// using host name and port.
/// This method does not support user authentication.
/// </summary>
/// <param name="hostname">host name</param>
/// <param name="port">host port</param>
/// <param name="names">names of values to retrieve</param>
public static Dictionary<string,string> Request(string hostname, int port, params string[] names)
{
IPAddress[] addresses = Connection.GetHostAddresses(hostname, DEFAULT_TIMEOUT);
IPEndPoint ipe = new IPEndPoint(addresses[0], port);
return Request(ipe, names);
}
/// <summary>
/// Get default info from the specified database server node, using host name and port.
/// This method does not support user authentication.
/// </summary>
/// <param name="hostname">host name</param>
/// <param name="port">host port</param>
public static Dictionary<string, string> Request(string hostname, int port)
{
IPAddress[] addresses = Connection.GetHostAddresses(hostname, DEFAULT_TIMEOUT);
IPEndPoint ipe = new IPEndPoint(addresses[0], port);
return Request(ipe);
}
//-------------------------------------------------------
// Get Info via Socket Address
//-------------------------------------------------------
/// <summary>
/// Get one info value by name from the specified database server node.
/// This method does not support user authentication.
/// </summary>
/// <param name="socketAddress">InetSocketAddress of server node</param>
/// <param name="name">name of value to retrieve</param>
public static string Request(IPEndPoint socketAddress, string name)
{
Connection conn = new Connection(socketAddress, DEFAULT_TIMEOUT);
try
{
return Request(conn, name);
}
finally
{
conn.Close();
}
}
/// <summary>
/// Get many info values by name from the specified database server node.
/// This method does not support user authentication.
/// </summary>
/// <param name="socketAddress">InetSocketAddress of server node</param>
/// <param name="names">names of values to retrieve</param>
public static Dictionary<string, string> Request(IPEndPoint socketAddress, params string[] names)
{
Connection conn = new Connection(socketAddress, DEFAULT_TIMEOUT);
try
{
return Request(conn, names);
}
finally
{
conn.Close();
}
}
/// <summary>
/// Get all the default info from the specified database server node.
/// This method does not support user authentication.
/// </summary>
/// <param name="socketAddress">InetSocketAddress of server node</param>
public static Dictionary<string, string> Request(IPEndPoint socketAddress)
{
Connection conn = new Connection(socketAddress, DEFAULT_TIMEOUT);
try
{
return Request(conn);
}
finally
{
conn.Close();
}
}
//-------------------------------------------------------
// Get Info via Connection
//-------------------------------------------------------
/// <summary>
/// Get one info value by name from the specified database server node.
/// </summary>
/// <param name="conn">socket connection to server node</param>
/// <param name="name">name of value to retrieve</param>
public static string Request(Connection conn, string name)
{
Info info = new Info(conn, name);
return info.ParseSingleResponse(name);
}
/// <summary>
/// Get many info values by name from the specified database server node.
/// </summary>
/// <param name="conn">socket connection to server node</param>
/// <param name="names">names of values to retrieve</param>
public static Dictionary<string,string> Request(Connection conn, params string[] names)
{
Info info = new Info(conn, names);
return info.ParseMultiResponse();
}
/// <summary>
/// Get all the default info from the specified database server node.
/// </summary>
/// <param name="conn">socket connection to server node</param>
public static Dictionary<string,string> Request(Connection conn)
{
Info info = new Info(conn);
return info.ParseMultiResponse();
}
/// <summary>
/// Get response buffer. For internal use only.
/// </summary>
public byte[] GetBuffer()
{
return buffer;
}
/// <summary>
/// Get response length. For internal use only.
/// </summary>
public int GetLength()
{
return length;
}
//-------------------------------------------------------
// Private methods.
//-------------------------------------------------------
/// <summary>
/// Issue request and set results buffer. This method is used internally.
/// The static request methods should be used instead.
/// </summary>
/// <param name="conn">socket connection to server node</param>
/// <exception cref="AerospikeException">if socket send or receive fails</exception>
private void SendCommand(Connection conn)
{
try
{
// Write size field.
ulong size = ((ulong)offset - 8L) | (2L << 56) | (1L << 48);
ByteUtil.LongToBytes(size, buffer, 0);
// Write.
conn.Write(buffer, offset);
// Read - reuse input buffer.
conn.ReadFully(buffer, 8);
size = (ulong)ByteUtil.BytesToLong(buffer, 0);
length = (int)(size & 0xFFFFFFFFFFFFL);
ResizeBuffer(length);
conn.ReadFully(buffer, length);
offset = 0;
}
catch (SocketException se)
{
throw new AerospikeException(se);
}
}
private void ResizeBuffer(int size)
{
if (size > buffer.Length)
{
buffer = ThreadLocalData.ResizeBuffer(size);
}
}
private string ParseSingleResponse(string name)
{
// Convert the UTF8 byte array into a string.
string response = ByteUtil.Utf8ToString(buffer, 0, length);
if (response.StartsWith(name))
{
if (response.Length > name.Length + 1)
{
// Remove field name, tab and trailing newline from response.
// This is faster than calling parseMultiResponse()
return response.Substring(name.Length + 1, response.Length - 1 - (name.Length + 1));
}
else
{
return null;
}
}
else
{
throw new AerospikeException.Parse("Info response does not include: " + name);
}
}
private Dictionary<string, string> ParseMultiResponse()
{
Dictionary<string, string> responses = new Dictionary<string, string>();
int offset = 0;
int begin = 0;
while (offset < length)
{
byte b = buffer[offset];
if (b == '\t')
{
string name = ByteUtil.Utf8ToString(buffer, begin, offset - begin);
CheckError(name);
begin = ++offset;
// Parse field value.
while (offset < length)
{
if (buffer[offset] == '\n')
{
break;
}
offset++;
}
if (offset > begin)
{
string value = ByteUtil.Utf8ToString(buffer, begin, offset - begin);
responses[name] = value;
}
else
{
responses[name] = null;
}
begin = ++offset;
}
else if (b == '\n')
{
if (offset > begin)
{
string name = ByteUtil.Utf8ToString(buffer, begin, offset - begin);
CheckError(name);
responses[name] = null;
}
begin = ++offset;
}
else
{
offset++;
}
}
if (offset > begin)
{
string name = ByteUtil.Utf8ToString(buffer, begin, offset - begin);
CheckError(name);
responses[name] = null;
}
return responses;
}
private void CheckError(string str)
{
if (str.StartsWith("ERROR:"))
{
int begin = 6;
int end = str.IndexOf(':', begin);
int code = -1;
string message = "";
if (end >= 0)
{
code = int.Parse(str.Substring(begin, end - begin));
if (str[str.Length-1] == '\n')
{
message = str.Substring(end + 1, str.Length - 2);
}
else
{
message = str.Substring(end + 1);
}
}
throw new AerospikeException(code, message);
}
}
/// <summary>
/// Parser for responses in name/value pair format:
/// <para>
/// <command>\t<name1>=<value1>;<name2>=<value2>;...\n
/// </para>
/// </summary>
public sealed class NameValueParser
{
private readonly Info parent;
public NameValueParser(Info parent)
{
this.parent = parent;
}
internal int nameBegin;
internal int nameEnd;
internal int valueBegin;
internal int valueEnd;
/// <summary>
/// Set pointers to next name/value pair.
/// Return true if next name/value pair exists.
/// Return false if at end.
/// </summary>
public bool Next()
{
nameBegin = parent.offset;
while (parent.offset < parent.length)
{
byte b = parent.buffer[parent.offset];
if (b == '=')
{
if (parent.offset <= nameBegin)
{
return false;
}
nameEnd = parent.offset;
ParseValue();
return true;
}
if (b == '\n')
{
break;
}
parent.offset++;
}
nameEnd = parent.offset;
valueBegin = parent.offset;
valueEnd = parent.offset;
return parent.offset > nameBegin;
}
internal void ParseValue()
{
valueBegin = ++parent.offset;
while (parent.offset < parent.length)
{
byte b = parent.buffer[parent.offset];
if (b == ';')
{
valueEnd = parent.offset++;
return;
}
if (b == '\n')
{
break;
}
parent.offset++;
}
valueEnd = parent.offset;
}
/// <summary>
/// Get name.
/// </summary>
public string GetName()
{
int len = nameEnd - nameBegin;
return ByteUtil.Utf8ToString(parent.buffer, nameBegin, len);
}
/// <summary>
/// Get value.
/// </summary>
public string GetValue()
{
int len = valueEnd - valueBegin;
if (len <= 0)
{
return null;
}
return ByteUtil.Utf8ToString(parent.buffer, valueBegin, len);
}
/// <summary>
/// Get Base64 string value.
/// </summary>
public string GetStringBase64()
{
int len = valueEnd - valueBegin;
if (len <= 0)
{
return null;
}
char[] chars = Encoding.ASCII.GetChars(parent.buffer, valueBegin, len);
byte[] bytes = Convert.FromBase64CharArray(chars, 0, chars.Length);
return ByteUtil.Utf8ToString(bytes, 0, bytes.Length);
}
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
namespace OAuthTest
{
// Reference: http://tools.ietf.org/search/draft-jones-json-web-token-00
//
// JWT is made up of 3 parts: Envelope, Claims, Signature.
// - Envelope - specifies the token type and signature algorithm used to produce
// signature segment. This is in JSON format
// - Claims - specifies claims made by the token. This is in JSON format
// - Signature - Cryptographic signature use to maintain data integrity.
//
// To produce a JWT token:
// 1. Create Envelope segment in JSON format
// 2. Create Claims segment in JSON format
// 3. Create signature
// 4. Base64url encode each part and append together separated by "."
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.IO;
public class JsonWebToken
{
#region Helper Classes
[DataContract]
public class JsonWebTokenClaims
{
[DataMember(Name = "exp")]
private int expUnixTime
{
get;
set;
}
private DateTime? expiration = null;
public DateTime Expiration
{
get
{
if (this.expiration == null)
{
this.expiration = new DateTime(1970, 1, 1, 0, 0, 0).AddSeconds(expUnixTime);
}
return (DateTime)this.expiration;
}
}
[DataMember(Name = "iss")]
public string Issuer
{
get;
private set;
}
[DataMember(Name = "aud")]
public string Audience
{
get;
private set;
}
[DataMember(Name = "uid")]
public string UserId
{
get;
private set;
}
[DataMember(Name = "ver")]
public int Version
{
get;
private set;
}
[DataMember(Name = "urn:microsoft:appuri")]
public string ClientIdentifier
{
get;
private set;
}
[DataMember(Name = "urn:microsoft:appid")]
public string AppId
{
get;
private set;
}
}
[DataContract]
public class JsonWebTokenEnvelope
{
[DataMember(Name = "typ")]
public string Type
{
get;
private set;
}
[DataMember(Name = "alg")]
public string Algorithm
{
get;
private set;
}
[DataMember(Name = "kid")]
public int KeyId
{
get;
private set;
}
}
#endregion
#region Properties
private static readonly DataContractJsonSerializer ClaimsJsonSerializer = new DataContractJsonSerializer(typeof(JsonWebTokenClaims));
private static readonly DataContractJsonSerializer EnvelopeJsonSerializer = new DataContractJsonSerializer(typeof(JsonWebTokenEnvelope));
private static readonly UTF8Encoding UTF8Encoder = new UTF8Encoding(true, true);
private static readonly SHA256Managed SHA256Provider = new SHA256Managed();
private string claimsTokenSegment;
public JsonWebTokenClaims Claims
{
get;
private set;
}
private string envelopeTokenSegment;
public JsonWebTokenEnvelope Envelope
{
get;
private set;
}
public string Signature
{
get;
private set;
}
public bool IsExpired
{
get
{
return this.Claims.Expiration < DateTime.Now;
}
}
#endregion
#region Constructors
public JsonWebToken(string token, Dictionary<int, string> keyIdsKeys)
{
// Get the token segments & perform validation
string[] tokenSegments = this.SplitToken(token);
// Decode and deserialize the claims
this.claimsTokenSegment = tokenSegments[1];
this.Claims = this.GetClaimsFromTokenSegment(this.claimsTokenSegment);
// Decode and deserialize the envelope
this.envelopeTokenSegment = tokenSegments[0];
this.Envelope = this.GetEnvelopeFromTokenSegment(this.envelopeTokenSegment);
// Get the signature
this.Signature = tokenSegments[2];
// Ensure that the tokens KeyId exists in the secret keys list
if (!keyIdsKeys.ContainsKey(this.Envelope.KeyId))
{
throw new Exception(string.Format("Could not find key with id {0}", this.Envelope.KeyId));
}
// Validation
this.ValidateEnvelope(this.Envelope);
this.ValidateSignature(keyIdsKeys[this.Envelope.KeyId]);
}
private JsonWebToken()
{
}
#endregion
#region Parsing Methods
private JsonWebTokenClaims GetClaimsFromTokenSegment(string claimsTokenSegment)
{
byte[] claimsData = this.Base64UrlDecode(claimsTokenSegment);
using (MemoryStream memoryStream = new MemoryStream(claimsData))
{
return ClaimsJsonSerializer.ReadObject(memoryStream) as JsonWebTokenClaims;
}
}
private JsonWebTokenEnvelope GetEnvelopeFromTokenSegment(string envelopeTokenSegment)
{
byte[] envelopeData = this.Base64UrlDecode(envelopeTokenSegment);
using (MemoryStream memoryStream = new MemoryStream(envelopeData))
{
return EnvelopeJsonSerializer.ReadObject(memoryStream) as JsonWebTokenEnvelope;
}
}
private string[] SplitToken(string token)
{
// Expected token format: Envelope.Claims.Signature
if (string.IsNullOrEmpty(token))
{
throw new Exception("Token is empty or null.");
}
string[] segments = token.Split('.');
if (segments.Length != 3)
{
throw new Exception("Invalid token format. Expected Envelope.Claims.Signature");
}
if (string.IsNullOrEmpty(segments[0]))
{
throw new Exception("Invalid token format. Envelope must not be empty");
}
if (string.IsNullOrEmpty(segments[1]))
{
throw new Exception("Invalid token format. Claims must not be empty");
}
if (string.IsNullOrEmpty(segments[2]))
{
throw new Exception("Invalid token format. Signature must not be empty");
}
return segments;
}
#endregion
#region Validation Methods
private void ValidateEnvelope(JsonWebTokenEnvelope envelope)
{
if (envelope.Type != "JWT")
{
throw new Exception("Unsupported token type");
}
if (envelope.Algorithm != "HS256")
{
throw new Exception("Unsupported crypto algorithm");
}
}
private void ValidateSignature(string key)
{
// Derive signing key, Signing key = SHA256(secret + "JWTSig")
byte[] bytes = UTF8Encoder.GetBytes(key + "JWTSig");
byte[] signingKey = SHA256Provider.ComputeHash(bytes);
// To Validate:
//
// 1. Take the bytes of the UTF-8 representation of the JWT Claim
// Segment and calculate an HMAC SHA-256 MAC on them using the
// shared key.
//
// 2. Base64url encode the previously generated HMAC as defined in this
// document.
//
// 3. If the JWT Crypto Segment and the previously calculated value
// exactly match in a character by character, case sensitive
// comparison, then one has confirmation that the key was used to
// generate the HMAC on the JWT and that the contents of the JWT
// Claim Segment have not be tampered with.
//
// 4. If the validation fails, the token MUST be rejected.
// UFT-8 representation of the JWT envelope.claim segment
byte[] input = UTF8Encoder.GetBytes(this.envelopeTokenSegment + "." + this.claimsTokenSegment);
// calculate an HMAC SHA-256 MAC
using (HMACSHA256 hashProvider = new HMACSHA256(signingKey))
{
byte[] myHashValue = hashProvider.ComputeHash(input);
// Base64 url encode the hash
string base64urlEncodedHash = this.Base64UrlEncode(myHashValue);
// Now compare the two has values
if (base64urlEncodedHash != this.Signature)
{
throw new Exception("Signature does not match.");
}
}
}
#endregion
#region Base64 Encode / Decode Functions
// Reference: http://tools.ietf.org/search/draft-jones-json-web-token-00
public byte[] Base64UrlDecode(string encodedSegment)
{
string s = encodedSegment;
s = s.Replace('-', '+'); // 62nd char of encoding
s = s.Replace('_', '/'); // 63rd char of encoding
switch (s.Length % 4) // Pad with trailing '='s
{
case 0: break; // No pad chars in this case
case 2: s += "=="; break; // Two pad chars
case 3: s += "="; break; // One pad char
default: throw new System.Exception("Illegal base64url string");
}
return Convert.FromBase64String(s); // Standard base64 decoder
}
public string Base64UrlEncode(byte[] arg)
{
string s = Convert.ToBase64String(arg); // Standard base64 encoder
s = s.Split('=')[0]; // Remove any trailing '='s
s = s.Replace('+', '-'); // 62nd char of encoding
s = s.Replace('/', '_'); // 63rd char of encoding
return s;
}
#endregion
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
namespace System.Globalization
{
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
//
//
// List of calendar data
// Note the we cache overrides.
// Note that localized names (resource names) aren't available from here.
//
// NOTE: Calendars depend on the locale name that creates it. Only a few
// properties are available without locales using CalendarData.GetCalendar(int)
// StructLayout is needed here otherwise compiler can re-arrange the fields.
// We have to keep this in-[....] with the definition in calendardata.h
//
// WARNING WARNING WARNING
//
// WARNING: Anything changed here also needs to be updated on the native side (object.h see type CalendarDataBaseObject)
// WARNING: The type loader will rearrange class member offsets so the mscorwks!CalendarDataBaseObject
// WARNING: must be manually structured to match the true loaded class layout
//
internal partial class CalendarData
{
// Max calendars
internal const int MAX_CALENDARS = 23;
// Identity
internal String sNativeName ; // Calendar Name for the locale
// Formats
internal String[] saShortDates ; // Short Data format, default first
internal String[] saYearMonths ; // Year/Month Data format, default first
internal String[] saLongDates ; // Long Data format, default first
internal String sMonthDay ; // Month/Day format
// Calendar Parts Names
internal String[] saEraNames ; // Names of Eras
internal String[] saAbbrevEraNames ; // Abbreviated Era Names
internal String[] saAbbrevEnglishEraNames ; // Abbreviated Era Names in English
internal String[] saDayNames ; // Day Names, null to use locale data, starts on Sunday
internal String[] saAbbrevDayNames ; // Abbrev Day Names, null to use locale data, starts on Sunday
internal String[] saSuperShortDayNames ; // Super short Day of week names
internal String[] saMonthNames ; // Month Names (13)
internal String[] saAbbrevMonthNames ; // Abbrev Month Names (13)
internal String[] saMonthGenitiveNames ; // Genitive Month Names (13)
internal String[] saAbbrevMonthGenitiveNames; // Genitive Abbrev Month Names (13)
internal String[] saLeapYearMonthNames ; // Multiple strings for the month names in a leap year.
// Integers at end to make marshaller happier
internal int iTwoDigitYearMax=2029 ; // Max 2 digit year (for Y2K bug data entry)
internal int iCurrentEra=0 ; // current era # (usually 1)
// Use overrides?
internal bool bUseUserOverrides ; // True if we want user overrides.
// Static invariant for the invariant locale
internal static CalendarData Invariant;
// Private constructor
private CalendarData() {}
// Invariant constructor
static CalendarData()
{
// Set our default/gregorian US calendar data
// Calendar IDs are 1-based, arrays are 0 based.
CalendarData invariant = new CalendarData();
// Set default data for calendar
// Note that we don't load resources since this IS NOT supposed to change (by definition)
invariant.sNativeName = "Gregorian Calendar"; // Calendar Name
// Year
invariant.iTwoDigitYearMax = 2029; // Max 2 digit year (for Y2K bug data entry)
invariant.iCurrentEra = 1; // Current era #
// Formats
invariant.saShortDates = new String[] { "MM/dd/yyyy", "yyyy-MM-dd" }; // short date format
invariant.saLongDates = new String[] { "dddd, dd MMMM yyyy"}; // long date format
invariant.saYearMonths = new String[] { "yyyy MMMM" }; // year month format
invariant.sMonthDay = "MMMM dd"; // Month day pattern
// Calendar Parts Names
invariant.saEraNames = new String[] { "A.D." }; // Era names
invariant.saAbbrevEraNames = new String[] { "AD" }; // Abbreviated Era names
invariant.saAbbrevEnglishEraNames=new String[] { "AD" }; // Abbreviated era names in English
invariant.saDayNames = new String[] { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };// day names
invariant.saAbbrevDayNames = new String[] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; // abbreviated day names
invariant.saSuperShortDayNames = new String[] { "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" }; // The super short day names
invariant.saMonthNames = new String[] { "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December", String.Empty}; // month names
invariant.saAbbrevMonthNames = new String[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec", String.Empty}; // abbreviated month names
invariant.saMonthGenitiveNames = invariant.saMonthNames; // Genitive month names (same as month names for invariant)
invariant.saAbbrevMonthGenitiveNames=invariant.saAbbrevMonthNames; // Abbreviated genitive month names (same as abbrev month names for invariant)
invariant.saLeapYearMonthNames = invariant.saMonthNames; // leap year month names are unused in Gregorian English (invariant)
invariant.bUseUserOverrides = false;
// Calendar was built, go ahead and assign it...
Invariant = invariant;
}
//
// Get a bunch of data for a calendar
//
internal CalendarData(String localeName, int calendarId, bool bUseUserOverrides)
{
// Call nativeGetCalendarData to populate the data
this.bUseUserOverrides = bUseUserOverrides;
if (!nativeGetCalendarData(this, localeName, calendarId))
{
Contract.Assert(false, "[CalendarData] nativeGetCalendarData call isn't expected to fail for calendar " + calendarId + " locale " +localeName);
// Something failed, try invariant for missing parts
// This is really not good, but we don't want the callers to crash.
if (this.sNativeName == null) this.sNativeName = String.Empty; // Calendar Name for the locale.
// Formats
if (this.saShortDates == null) this.saShortDates = Invariant.saShortDates; // Short Data format, default first
if (this.saYearMonths == null) this.saYearMonths = Invariant.saYearMonths; // Year/Month Data format, default first
if (this.saLongDates == null) this.saLongDates = Invariant.saLongDates; // Long Data format, default first
if (this.sMonthDay == null) this.sMonthDay = Invariant.sMonthDay; // Month/Day format
// Calendar Parts Names
if (this.saEraNames == null) this.saEraNames = Invariant.saEraNames; // Names of Eras
if (this.saAbbrevEraNames == null) this.saAbbrevEraNames = Invariant.saAbbrevEraNames; // Abbreviated Era Names
if (this.saAbbrevEnglishEraNames == null) this.saAbbrevEnglishEraNames = Invariant.saAbbrevEnglishEraNames; // Abbreviated Era Names in English
if (this.saDayNames == null) this.saDayNames = Invariant.saDayNames; // Day Names, null to use locale data, starts on Sunday
if (this.saAbbrevDayNames == null) this.saAbbrevDayNames = Invariant.saAbbrevDayNames; // Abbrev Day Names, null to use locale data, starts on Sunday
if (this.saSuperShortDayNames == null) this.saSuperShortDayNames = Invariant.saSuperShortDayNames; // Super short Day of week names
if (this.saMonthNames == null) this.saMonthNames = Invariant.saMonthNames; // Month Names (13)
if (this.saAbbrevMonthNames == null) this.saAbbrevMonthNames = Invariant.saAbbrevMonthNames; // Abbrev Month Names (13)
// Genitive and Leap names can follow the fallback below
}
// Clean up the escaping of the formats
this.saShortDates = CultureData.ReescapeWin32Strings(this.saShortDates);
this.saLongDates = CultureData.ReescapeWin32Strings(this.saLongDates);
this.saYearMonths = CultureData.ReescapeWin32Strings(this.saYearMonths);
this.sMonthDay = CultureData.ReescapeWin32String(this.sMonthDay);
if ((CalendarId)calendarId == CalendarId.TAIWAN)
{
// for Geo----al reasons, the ----ese native name should only be returned when
// for ----ese SKU
if (CultureInfo.IsTaiwanSku)
{
// We got the month/day names from the OS (same as gregorian), but the native name is wrong
this.sNativeName = "\x4e2d\x83ef\x6c11\x570b\x66c6";
}
else
{
this.sNativeName = String.Empty;
}
}
// Check for null genitive names (in case unmanaged side skips it for non-gregorian calendars, etc)
if (this.saMonthGenitiveNames == null || String.IsNullOrEmpty(this.saMonthGenitiveNames[0]))
this.saMonthGenitiveNames = this.saMonthNames; // Genitive month names (same as month names for invariant)
if (this.saAbbrevMonthGenitiveNames == null || String.IsNullOrEmpty(this.saAbbrevMonthGenitiveNames[0]))
this.saAbbrevMonthGenitiveNames = this.saAbbrevMonthNames; // Abbreviated genitive month names (same as abbrev month names for invariant)
if (this.saLeapYearMonthNames == null || String.IsNullOrEmpty(this.saLeapYearMonthNames[0]))
this.saLeapYearMonthNames = this.saMonthNames;
InitializeEraNames(localeName, calendarId);
InitializeAbbreviatedEraNames(localeName, calendarId);
// Abbreviated English Era Names are only used for the Japanese calendar.
if (calendarId == (int)CalendarId.JAPAN)
{
this.saAbbrevEnglishEraNames = JapaneseCalendar.EnglishEraNames();
}
else
{
// For all others just use the an empty string (doesn't matter we'll never ask for it for other calendars)
this.saAbbrevEnglishEraNames = new String[] { "" };
}
// Japanese is the only thing with > 1 era. Its current era # is how many ever
// eras are in the array. (And the others all have 1 string in the array)
this.iCurrentEra = this.saEraNames.Length;
}
private void InitializeEraNames(string localeName, int calendarId)
{
// Note that the saEraNames only include "A.D." We don't have localized names for other calendars available from windows
switch ((CalendarId)calendarId)
{
// For Localized Gregorian we really expect the data from the OS.
case CalendarId.GREGORIAN:
// Fallback for CoreCLR < Win7 or culture.dll missing
if (this.saEraNames == null || this.saEraNames.Length == 0 || String.IsNullOrEmpty(this.saEraNames[0]))
{
this.saEraNames = new String[] { "A.D." };
}
break;
// The rest of the calendars have constant data, so we'll just use that
case CalendarId.GREGORIAN_US:
case CalendarId.JULIAN:
this.saEraNames = new String[] { "A.D." };
break;
case CalendarId.HEBREW:
this.saEraNames = new String[] { "C.E." };
break;
case CalendarId.HIJRI:
case CalendarId.UMALQURA:
if (localeName == "dv-MV")
{
// Special case for Divehi
this.saEraNames = new String[] { "\x0780\x07a8\x0796\x07b0\x0783\x07a9" };
}
else
{
this.saEraNames = new String[] { "\x0628\x0639\x062F \x0627\x0644\x0647\x062C\x0631\x0629" };
}
break;
case CalendarId.GREGORIAN_ARABIC:
case CalendarId.GREGORIAN_XLIT_ENGLISH:
case CalendarId.GREGORIAN_XLIT_FRENCH:
// These are all the same:
this.saEraNames = new String[] { "\x0645" };
break;
case CalendarId.GREGORIAN_ME_FRENCH:
this.saEraNames = new String[] { "ap. J.-C." };
break;
case CalendarId.TAIWAN:
// for Geo----al reasons, the ----ese native name should only be returned when
// for ----ese SKU
if (CultureInfo.IsTaiwanSku)
{
//
this.saEraNames = new String[] { "\x4e2d\x83ef\x6c11\x570b" };
}
else
{
this.saEraNames = new String[] { String.Empty };
}
break;
case CalendarId.KOREA:
this.saEraNames = new String[] { "\xb2e8\xae30" };
break;
case CalendarId.THAI:
this.saEraNames = new String[] { "\x0e1e\x002e\x0e28\x002e" };
break;
case CalendarId.JAPAN:
case CalendarId.JAPANESELUNISOLAR:
this.saEraNames = JapaneseCalendar.EraNames();
break;
default:
// Most calendars are just "A.D."
this.saEraNames = Invariant.saEraNames;
break;
}
}
private void InitializeAbbreviatedEraNames(string localeName, int calendarId)
{
// Note that the saAbbrevEraNames only include "AD" We don't have localized names for other calendars available from windows
switch ((CalendarId)calendarId)
{
// For Localized Gregorian we really expect the data from the OS.
case CalendarId.GREGORIAN:
// Fallback for CoreCLR < Win7 or culture.dll missing
if (this.saAbbrevEraNames == null || this.saAbbrevEraNames.Length == 0 || String.IsNullOrEmpty(this.saAbbrevEraNames[0]))
{
this.saAbbrevEraNames = new String[] { "AD" };
}
break;
// The rest of the calendars have constant data, so we'll just use that
case CalendarId.GREGORIAN_US:
case CalendarId.JULIAN:
this.saAbbrevEraNames = new String[] { "AD" };
break;
case CalendarId.JAPAN:
case CalendarId.JAPANESELUNISOLAR:
this.saAbbrevEraNames = JapaneseCalendar.AbbrevEraNames();
break;
case CalendarId.HIJRI:
case CalendarId.UMALQURA:
if (localeName == "dv-MV")
{
// Special case for Divehi
this.saAbbrevEraNames = new String[] { "\x0780\x002e" };
}
else
{
this.saAbbrevEraNames = new String[] { "\x0647\x0640" };
}
break;
case CalendarId.TAIWAN:
// Get era name and abbreviate it
this.saAbbrevEraNames = new String[1];
if (this.saEraNames[0].Length == 4)
{
this.saAbbrevEraNames[0] = this.saEraNames[0].Substring(2,2);
}
else
{
this.saAbbrevEraNames[0] = this.saEraNames[0];
}
break;
default:
// Most calendars just use the full name
this.saAbbrevEraNames = this.saEraNames;
break;
}
}
internal static CalendarData GetCalendarData(int calendarId)
{
//
// Get a calendar.
// Unfortunately we depend on the locale in the OS, so we need a locale
// no matter what. So just get the appropriate calendar from the
// appropriate locale here
//
// Get a culture name
//
String culture = CalendarIdToCultureName(calendarId);
// Return our calendar
return CultureInfo.GetCultureInfo(culture).m_cultureData.GetCalendar(calendarId);
}
//
// Helper methods
//
private static String CalendarIdToCultureName(int calendarId)
{
switch (calendarId)
{
case Calendar.CAL_GREGORIAN_US:
return "fa-IR"; // "fa-IR" Iran
case Calendar.CAL_JAPAN:
return "ja-JP"; // "ja-JP" Japan
case Calendar.CAL_TAIWAN:
return "zh-TW"; // zh-TW Taiwan
case Calendar.CAL_KOREA:
return "ko-KR"; // "ko-KR" Korea
case Calendar.CAL_HIJRI:
case Calendar.CAL_GREGORIAN_ARABIC:
case Calendar.CAL_UMALQURA:
return "ar-SA"; // "ar-SA" Saudi Arabia
case Calendar.CAL_THAI:
return "th-TH"; // "th-TH" Thailand
case Calendar.CAL_HEBREW:
return "he-IL"; // "he-IL" Israel
case Calendar.CAL_GREGORIAN_ME_FRENCH:
return "ar-DZ"; // "ar-DZ" Algeria
case Calendar.CAL_GREGORIAN_XLIT_ENGLISH:
case Calendar.CAL_GREGORIAN_XLIT_FRENCH:
return "ar-IQ"; // "ar-IQ"; Iraq
default:
// Default to gregorian en-US
break;
}
return "en-US";
}
#if !MONO_CULTURE_DATA
internal void FixupWin7MonthDaySemicolonBug()
{
int unescapedCharacterIndex = FindUnescapedCharacter(sMonthDay, ';');
if (unescapedCharacterIndex > 0)
{
sMonthDay = sMonthDay.Substring(0, unescapedCharacterIndex);
}
}
private static int FindUnescapedCharacter(string s, char charToFind)
{
bool inComment = false;
int length = s.Length;
for (int i = 0; i < length; i++)
{
char c = s[i];
switch (c)
{
case '\'':
inComment = !inComment;
break;
case '\\':
i++; // escape sequence -- skip next character
break;
default:
if (!inComment && charToFind == c)
{
return i;
}
break;
}
}
return -1;
}
// Get native two digit year max
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int nativeGetTwoDigitYearMax(int calID);
// Call native side to load our calendar data
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool nativeGetCalendarData(CalendarData data, String localeName, int calendar);
// Call native side to figure out which calendars are allowed
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int nativeGetCalendars(String localeName, bool useUserOverride, [In, Out] int[] calendars);
#endif
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEditor.Graphing;
namespace UnityEditor.ShaderGraph
{
[Title("Utility", "Sub-graph")]
class SubGraphNode : AbstractMaterialNode
, IGeneratesBodyCode
, IOnAssetEnabled
, IGeneratesFunction
, IMayRequireNormal
, IMayRequireTangent
, IMayRequireBitangent
, IMayRequireMeshUV
, IMayRequireScreenPosition
, IMayRequireViewDirection
, IMayRequirePosition
, IMayRequireVertexColor
, IMayRequireTime
, IMayRequireFaceSign
, IMayRequireCameraOpaqueTexture
, IMayRequireDepthTexture
{
[SerializeField]
private string m_SerializedSubGraph = string.Empty;
[NonSerialized]
SubGraphAsset m_SubGraph;
[NonSerialized]
SubGraphData m_SubGraphData = default;
[SerializeField]
List<string> m_PropertyGuids = new List<string>();
[SerializeField]
List<int> m_PropertyIds = new List<int>();
[Serializable]
private class SubGraphHelper
{
public SubGraphAsset subGraph;
}
[Serializable]
class SubGraphAssetReference
{
public AssetReference subGraph = default;
public override string ToString()
{
return $"subGraph={subGraph}";
}
}
[Serializable]
class AssetReference
{
public long fileID = default;
public string guid = default;
public int type = default;
public override string ToString()
{
return $"fileID={fileID}, guid={guid}, type={type}";
}
}
public string subGraphGuid
{
get
{
var assetReference = JsonUtility.FromJson<SubGraphAssetReference>(m_SerializedSubGraph);
return assetReference?.subGraph?.guid;
}
}
void LoadSubGraph()
{
if (m_SubGraph == null)
{
m_SubGraphData = null;
if (string.IsNullOrEmpty(m_SerializedSubGraph))
{
return;
}
var graphGuid = subGraphGuid;
var assetPath = AssetDatabase.GUIDToAssetPath(graphGuid);
m_SubGraph = AssetDatabase.LoadAssetAtPath<SubGraphAsset>(assetPath);
if (m_SubGraph == null)
{
return;
}
name = m_SubGraph.name;
var index = SubGraphDatabase.instance.subGraphGuids.BinarySearch(graphGuid);
m_SubGraphData = index < 0 ? null : SubGraphDatabase.instance.subGraphs[index];
}
}
public SubGraphData subGraphData
{
get
{
LoadSubGraph();
return m_SubGraphData;
}
}
public SubGraphAsset subGraphAsset
{
get
{
LoadSubGraph();
return m_SubGraph;
}
set
{
if (subGraphAsset == value)
return;
var helper = new SubGraphHelper();
helper.subGraph = value;
m_SerializedSubGraph = EditorJsonUtility.ToJson(helper, true);
m_SubGraph = null;
m_SubGraphData = null;
UpdateSlots();
Dirty(ModificationScope.Topological);
}
}
public override bool hasPreview
{
get { return subGraphData != null; }
}
public override PreviewMode previewMode
{
get
{
if (subGraphData == null)
return PreviewMode.Preview2D;
return PreviewMode.Preview3D;
}
}
public SubGraphNode()
{
name = "Sub Graph";
}
public override bool allowedInSubGraph
{
get { return true; }
}
public void GenerateNodeCode(ShaderGenerator visitor, GraphContext graphContext, GenerationMode generationMode)
{
var sb = new ShaderStringBuilder();
if (subGraphData == null || hasError)
{
var outputSlots = new List<MaterialSlot>();
GetOutputSlots(outputSlots);
foreach (var slot in outputSlots)
{
visitor.AddShaderChunk($"{NodeUtils.ConvertConcreteSlotValueTypeToString(precision, slot.concreteValueType)} {GetVariableNameForSlot(slot.id)} = {slot.GetDefaultValue(GenerationMode.ForReals)};");
}
return;
}
var inputVariableName = $"_{GetVariableNameForNode()}";
GraphUtil.GenerateSurfaceInputTransferCode(sb, subGraphData.requirements, subGraphData.inputStructName, inputVariableName);
visitor.AddShaderChunk(sb.ToString());
foreach (var outSlot in subGraphData.outputs)
visitor.AddShaderChunk(string.Format("{0} {1};", NodeUtils.ConvertConcreteSlotValueTypeToString(precision, outSlot.concreteValueType), GetVariableNameForSlot(outSlot.id)));
var arguments = new List<string>();
foreach (var prop in subGraphData.inputs)
{
var inSlotId = m_PropertyIds[m_PropertyGuids.IndexOf(prop.guid.ToString())];
if (prop is TextureShaderProperty)
arguments.Add(string.Format("TEXTURE2D_ARGS({0}, sampler{0})", GetSlotValue(inSlotId, generationMode)));
else if (prop is Texture2DArrayShaderProperty)
arguments.Add(string.Format("TEXTURE2D_ARRAY_ARGS({0}, sampler{0})", GetSlotValue(inSlotId, generationMode)));
else if (prop is Texture3DShaderProperty)
arguments.Add(string.Format("TEXTURE3D_ARGS({0}, sampler{0})", GetSlotValue(inSlotId, generationMode)));
else if (prop is CubemapShaderProperty)
arguments.Add(string.Format("TEXTURECUBE_ARGS({0}, sampler{0})", GetSlotValue(inSlotId, generationMode)));
else
arguments.Add(GetSlotValue(inSlotId, generationMode));
}
// pass surface inputs through
arguments.Add(inputVariableName);
foreach (var outSlot in subGraphData.outputs)
arguments.Add(GetVariableNameForSlot(outSlot.id));
visitor.AddShaderChunk(
string.Format("{0}({1});"
, subGraphData.functionName
, arguments.Aggregate((current, next) => string.Format("{0}, {1}", current, next))));
}
public void OnEnable()
{
UpdateSlots();
}
public virtual void UpdateSlots()
{
var validNames = new List<int>();
if (subGraphData == null)
{
return;
}
var props = subGraphData.inputs;
foreach (var prop in props)
{
var propType = prop.propertyType;
SlotValueType slotType;
switch (propType)
{
case PropertyType.Color:
slotType = SlotValueType.Vector4;
break;
case PropertyType.Texture2D:
slotType = SlotValueType.Texture2D;
break;
case PropertyType.Texture2DArray:
slotType = SlotValueType.Texture2DArray;
break;
case PropertyType.Texture3D:
slotType = SlotValueType.Texture3D;
break;
case PropertyType.Cubemap:
slotType = SlotValueType.Cubemap;
break;
case PropertyType.Gradient:
slotType = SlotValueType.Gradient;
break;
case PropertyType.Vector1:
slotType = SlotValueType.Vector1;
break;
case PropertyType.Vector2:
slotType = SlotValueType.Vector2;
break;
case PropertyType.Vector3:
slotType = SlotValueType.Vector3;
break;
case PropertyType.Vector4:
slotType = SlotValueType.Vector4;
break;
case PropertyType.Boolean:
slotType = SlotValueType.Boolean;
break;
case PropertyType.Matrix2:
slotType = SlotValueType.Matrix2;
break;
case PropertyType.Matrix3:
slotType = SlotValueType.Matrix3;
break;
case PropertyType.Matrix4:
slotType = SlotValueType.Matrix4;
break;
case PropertyType.SamplerState:
slotType = SlotValueType.SamplerState;
break;
default:
throw new ArgumentOutOfRangeException();
}
var propertyString = prop.guid.ToString();
var propertyIndex = m_PropertyGuids.IndexOf(propertyString);
if (propertyIndex < 0)
{
propertyIndex = m_PropertyGuids.Count;
m_PropertyGuids.Add(propertyString);
m_PropertyIds.Add(prop.guid.GetHashCode());
}
var id = m_PropertyIds[propertyIndex];
MaterialSlot slot = MaterialSlot.CreateMaterialSlot(slotType, id, prop.displayName, prop.referenceName, SlotType.Input, prop.defaultValue, ShaderStageCapability.All);
// copy default for texture for niceness
if (slotType == SlotValueType.Texture2D && propType == PropertyType.Texture2D)
{
var tSlot = slot as Texture2DInputMaterialSlot;
var tProp = prop as TextureShaderProperty;
if (tSlot != null && tProp != null)
tSlot.texture = tProp.value.texture;
}
// copy default for texture array for niceness
else if (slotType == SlotValueType.Texture2DArray && propType == PropertyType.Texture2DArray)
{
var tSlot = slot as Texture2DArrayInputMaterialSlot;
var tProp = prop as Texture2DArrayShaderProperty;
if (tSlot != null && tProp != null)
tSlot.textureArray = tProp.value.textureArray;
}
// copy default for texture 3d for niceness
else if (slotType == SlotValueType.Texture3D && propType == PropertyType.Texture3D)
{
var tSlot = slot as Texture3DInputMaterialSlot;
var tProp = prop as Texture3DShaderProperty;
if (tSlot != null && tProp != null)
tSlot.texture = tProp.value.texture;
}
// copy default for cubemap for niceness
else if (slotType == SlotValueType.Cubemap && propType == PropertyType.Cubemap)
{
var tSlot = slot as CubemapInputMaterialSlot;
var tProp = prop as CubemapShaderProperty;
if (tSlot != null && tProp != null)
tSlot.cubemap = tProp.value.cubemap;
}
// copy default for gradient for niceness
else if (slotType == SlotValueType.Gradient && propType == PropertyType.Gradient)
{
var tSlot = slot as GradientInputMaterialSlot;
var tProp = prop as GradientShaderProperty;
if (tSlot != null && tProp != null)
tSlot.value = tProp.value;
}
AddSlot(slot);
validNames.Add(id);
}
var outputStage = subGraphData.effectiveShaderStage;
foreach (var slot in subGraphData.outputs)
{
AddSlot(MaterialSlot.CreateMaterialSlot(slot.valueType, slot.id, slot.RawDisplayName(),
slot.shaderOutputName, SlotType.Output, Vector4.zero, outputStage));
validNames.Add(slot.id);
}
RemoveSlotsNameNotMatching(validNames, true);
}
void ValidateShaderStage()
{
if (subGraphData != null)
{
List<MaterialSlot> slots = new List<MaterialSlot>();
GetInputSlots(slots);
GetOutputSlots(slots);
var outputStage = subGraphData.effectiveShaderStage;
foreach (MaterialSlot slot in slots)
slot.stageCapability = outputStage;
}
}
public override void ValidateNode()
{
base.ValidateNode();
if (subGraphData == null)
{
hasError = true;
var assetGuid = subGraphGuid;
var assetPath = string.IsNullOrEmpty(subGraphGuid) ? null : AssetDatabase.GUIDToAssetPath(assetGuid);
if (string.IsNullOrEmpty(assetPath))
{
owner.AddValidationError(tempId, $"Could not find Sub Graph asset with GUID {assetGuid}.");
}
else
{
owner.AddValidationError(tempId, $"Could not load Sub Graph asset at \"{assetPath}\" with GUID {assetGuid}.");
}
}
else if (subGraphData.isRecursive || owner.isSubGraph && (subGraphData.descendents.Contains(owner.assetGuid) || subGraphData.assetGuid == owner.assetGuid))
{
hasError = true;
owner.AddValidationError(tempId, $"Detected a recursion in Sub Graph asset at \"{AssetDatabase.GUIDToAssetPath(subGraphGuid)}\" with GUID {subGraphGuid}.");
}
else if (!subGraphData.isValid)
{
hasError = true;
owner.AddValidationError(tempId, $"Invalid Sub Graph asset at \"{AssetDatabase.GUIDToAssetPath(subGraphGuid)}\" with GUID {subGraphGuid}.");
}
ValidateShaderStage();
}
public override void CollectShaderProperties(PropertyCollector visitor, GenerationMode generationMode)
{
base.CollectShaderProperties(visitor, generationMode);
if (subGraphData == null)
return;
foreach (var property in subGraphData.nodeProperties)
{
visitor.AddShaderProperty(property);
}
}
public override void CollectPreviewMaterialProperties(List<PreviewProperty> properties)
{
base.CollectPreviewMaterialProperties(properties);
if (subGraphData == null)
return;
foreach (var property in subGraphData.nodeProperties)
{
properties.Add(property.GetPreviewMaterialProperty());
}
}
public virtual void GenerateNodeFunction(FunctionRegistry registry, GraphContext graphContext, GenerationMode generationMode)
{
if (subGraphData == null || hasError)
return;
var database = SubGraphDatabase.instance;
foreach (var functionName in subGraphData.functionNames)
{
registry.ProvideFunction(functionName, s =>
{
var functionSource = database.functionSources[database.functionNames.BinarySearch(functionName)];
s.AppendLines(functionSource);
});
}
}
public NeededCoordinateSpace RequiresNormal(ShaderStageCapability stageCapability)
{
if (subGraphData == null)
return NeededCoordinateSpace.None;
return subGraphData.requirements.requiresNormal;
}
public bool RequiresMeshUV(UVChannel channel, ShaderStageCapability stageCapability)
{
if (subGraphData == null)
return false;
return subGraphData.requirements.requiresMeshUVs.Contains(channel);
}
public bool RequiresScreenPosition(ShaderStageCapability stageCapability)
{
if (subGraphData == null)
return false;
return subGraphData.requirements.requiresScreenPosition;
}
public NeededCoordinateSpace RequiresViewDirection(ShaderStageCapability stageCapability)
{
if (subGraphData == null)
return NeededCoordinateSpace.None;
return subGraphData.requirements.requiresViewDir;
}
public NeededCoordinateSpace RequiresPosition(ShaderStageCapability stageCapability)
{
if (subGraphData == null)
return NeededCoordinateSpace.None;
return subGraphData.requirements.requiresPosition;
}
public NeededCoordinateSpace RequiresTangent(ShaderStageCapability stageCapability)
{
if (subGraphData == null)
return NeededCoordinateSpace.None;
return subGraphData.requirements.requiresTangent;
}
public bool RequiresTime()
{
if (subGraphData == null)
return false;
return subGraphData.requirements.requiresTime;
}
public bool RequiresFaceSign(ShaderStageCapability stageCapability)
{
if (subGraphData == null)
return false;
return subGraphData.requirements.requiresFaceSign;
}
public NeededCoordinateSpace RequiresBitangent(ShaderStageCapability stageCapability)
{
if (subGraphData == null)
return NeededCoordinateSpace.None;
return subGraphData.requirements.requiresBitangent;
}
public bool RequiresVertexColor(ShaderStageCapability stageCapability)
{
if (subGraphData == null)
return false;
return subGraphData.requirements.requiresVertexColor;
}
public bool RequiresCameraOpaqueTexture(ShaderStageCapability stageCapability)
{
if (subGraphData == null)
return false;
return subGraphData.requirements.requiresCameraOpaqueTexture;
}
public bool RequiresDepthTexture(ShaderStageCapability stageCapability)
{
if (subGraphData == null)
return false;
return subGraphData.requirements.requiresDepthTexture;
}
public override void GetSourceAssetDependencies(List<string> paths)
{
base.GetSourceAssetDependencies(paths);
if (subGraphData != null)
{
paths.Add(AssetDatabase.GetAssetPath(subGraphAsset));
foreach (var graphGuid in subGraphData.descendents)
{
paths.Add(AssetDatabase.GUIDToAssetPath(graphGuid));
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Reflection;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public static class CallFactoryTests
{
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(3)]
public static void CheckCallIsOptimizedInstance(int arity)
{
AssertCallIsOptimizedInstance(arity);
}
[Fact]
public static void CheckCallFactoryOptimisedInstanceNullArgumentList()
{
var instance = Expression.Constant(new MS());
var expr = Expression.Call(instance, typeof(MS).GetMethod(nameof(MS.I0)), default(Expression[]));
AssertInstanceMethodCall(0, expr);
}
[Fact]
public static void CheckCallFactoryOptimizationInstance2()
{
MethodCallExpression expr = Expression.Call(Expression.Parameter(typeof(MS)), typeof(MS).GetMethod("I2"), Expression.Constant(0), Expression.Constant(1));
AssertInstanceMethodCall(2, expr);
}
[Fact]
public static void CheckCallFactoryOptimizationInstance3()
{
MethodCallExpression expr = Expression.Call(Expression.Parameter(typeof(MS)), typeof(MS).GetMethod("I3"), Expression.Constant(0), Expression.Constant(1), Expression.Constant(2));
AssertInstanceMethodCall(3, expr);
}
[Fact]
public static void CheckCallFactoryInstanceN()
{
const int N = 4;
ParameterExpression obj = Expression.Parameter(typeof(MS));
ConstantExpression[] args = Enumerable.Range(0, N).Select(i => Expression.Constant(i)).ToArray();
MethodCallExpression expr = Expression.Call(obj, typeof(MS).GetMethod("I" + N), args);
if (!PlatformDetection.IsNetNative) // .Net Native blocks internal framework reflection.
{
Assert.Equal("InstanceMethodCallExpressionN", expr.GetType().Name);
}
Assert.Same(obj, expr.Object);
Assert.Equal(N, expr.ArgumentCount);
for (var i = 0; i < N; i++)
{
Assert.Same(args[i], expr.GetArgument(i));
}
Collections.ObjectModel.ReadOnlyCollection<Expression> arguments = expr.Arguments;
Assert.Same(arguments, expr.Arguments);
Assert.Equal(N, arguments.Count);
for (var i = 0; i < N; i++)
{
Assert.Same(args[i], arguments[i]);
}
MethodCallExpression updated = expr.Update(obj, arguments.ToList());
Assert.Same(expr, updated);
var visited = (MethodCallExpression)new NopVisitor().Visit(expr);
Assert.Same(expr, visited);
var visitedObj = (MethodCallExpression)new VisitorObj().Visit(expr);
Assert.NotSame(expr, visitedObj);
Assert.NotSame(obj, visitedObj.Object);
Assert.Same(arguments, visitedObj.Arguments);
var visitedArgs = (MethodCallExpression)new VisitorArgs().Visit(expr);
Assert.NotSame(expr, visitedArgs);
Assert.Same(obj, visitedArgs.Object);
Assert.NotSame(arguments, visitedArgs.Arguments);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(3)]
[InlineData(4)]
[InlineData(5)]
public static void CheckCallIsOptimizedStatic(int arity)
{
AssertCallIsOptimizedStatic(arity);
}
[Fact]
public static void CheckCallFactoryOptimisedStaticNullArgumentList() =>
AssertStaticMethodCall(0, Expression.Call(typeof(MS).GetMethod(nameof(MS.S0)), default(Expression[])));
[Fact]
public static void CheckCallFactoryOptimizationStatic1()
{
MethodCallExpression expr = Expression.Call(typeof(MS).GetMethod("S1"), Expression.Constant(0));
AssertStaticMethodCall(1, expr);
}
[Fact]
public static void CheckCallFactoryOptimizationStatic2()
{
MethodCallExpression expr1 = Expression.Call(typeof(MS).GetMethod("S2"), Expression.Constant(0), Expression.Constant(1));
MethodCallExpression expr2 = Expression.Call(null, typeof(MS).GetMethod("S2"), Expression.Constant(0), Expression.Constant(1));
AssertStaticMethodCall(2, expr1);
AssertStaticMethodCall(2, expr2);
}
[Fact]
public static void CheckCallFactoryOptimizationStatic3()
{
MethodCallExpression expr1 = Expression.Call(typeof(MS).GetMethod("S3"), Expression.Constant(0), Expression.Constant(1), Expression.Constant(2));
MethodCallExpression expr2 = Expression.Call(null, typeof(MS).GetMethod("S3"), Expression.Constant(0), Expression.Constant(1), Expression.Constant(2));
AssertStaticMethodCall(3, expr1);
AssertStaticMethodCall(3, expr2);
}
[Fact]
public static void CheckCallFactoryOptimizationStatic4()
{
MethodCallExpression expr = Expression.Call(typeof(MS).GetMethod("S4"), Expression.Constant(0), Expression.Constant(1), Expression.Constant(2), Expression.Constant(3));
AssertStaticMethodCall(4, expr);
}
[Fact]
public static void CheckCallFactoryOptimizationStatic5()
{
MethodCallExpression expr = Expression.Call(typeof(MS).GetMethod("S5"), Expression.Constant(0), Expression.Constant(1), Expression.Constant(2), Expression.Constant(3), Expression.Constant(4));
AssertStaticMethodCall(5, expr);
}
[Fact]
public static void CheckCallFactoryStaticN()
{
const int N = 6;
ConstantExpression[] args = Enumerable.Range(0, N).Select(i => Expression.Constant(i)).ToArray();
MethodCallExpression expr = Expression.Call(typeof(MS).GetMethod("S" + N), args);
if (!PlatformDetection.IsNetNative) // .Net Native blocks internal framework reflection.
{
Assert.Equal("MethodCallExpressionN", expr.GetType().Name);
}
Assert.Equal(N, expr.ArgumentCount);
for (var i = 0; i < N; i++)
{
Assert.Same(args[i], expr.GetArgument(i));
}
Collections.ObjectModel.ReadOnlyCollection<Expression> arguments = expr.Arguments;
Assert.Same(arguments, expr.Arguments);
Assert.Equal(N, arguments.Count);
for (var i = 0; i < N; i++)
{
Assert.Same(args[i], arguments[i]);
}
MethodCallExpression updated = expr.Update(null, arguments);
Assert.Same(expr, updated);
var visited = (MethodCallExpression)new NopVisitor().Visit(expr);
Assert.Same(expr, visited);
var visitedArgs = (MethodCallExpression)new VisitorArgs().Visit(expr);
Assert.NotSame(expr, visitedArgs);
Assert.Same(null, visitedArgs.Object);
Assert.NotSame(arguments, visitedArgs.Arguments);
}
[Fact]
public static void CheckArrayIndexOptimization1()
{
ParameterExpression instance = Expression.Parameter(typeof(int[]));
ConstantExpression[] args = new[] { Expression.Constant(0) };
MethodCallExpression expr = Expression.ArrayIndex(instance, args);
MethodInfo method = typeof(int[]).GetMethod("Get", BindingFlags.Public | BindingFlags.Instance);
AssertCallIsOptimized(expr, instance, method, args);
}
[Fact]
public static void CheckArrayIndexOptimization2()
{
ParameterExpression instance = Expression.Parameter(typeof(int[,]));
ConstantExpression[] args = new[] { Expression.Constant(0), Expression.Constant(0) };
MethodCallExpression expr = Expression.ArrayIndex(instance, args);
MethodInfo method = typeof(int[,]).GetMethod("Get", BindingFlags.Public | BindingFlags.Instance);
AssertCallIsOptimized(expr, instance, method, args);
}
private static void AssertCallIsOptimizedInstance(int n)
{
MethodInfo method = typeof(MS).GetMethod("I" + n);
AssertCallIsOptimized(method);
}
private static void AssertCallIsOptimizedStatic(int n)
{
MethodInfo method = typeof(MS).GetMethod("S" + n);
AssertCallIsOptimized(method);
}
private static void AssertCallIsOptimized(MethodInfo method)
{
ParameterExpression instance = method.IsStatic ? null : Expression.Parameter(method.DeclaringType);
int n = method.GetParameters().Length;
// Expression[] overload
{
ConstantExpression[] args = Enumerable.Range(0, n).Select(i => Expression.Constant(i)).ToArray();
MethodCallExpression expr = Expression.Call(instance, method, args);
AssertCallIsOptimized(expr, instance, method, args);
}
// IEnumerable<Expression> overload
{
List<ConstantExpression> args = Enumerable.Range(0, n).Select(i => Expression.Constant(i)).ToList();
MethodCallExpression expr = Expression.Call(instance, method, args);
AssertCallIsOptimized(expr, instance, method, args);
}
}
private static void AssertCallIsOptimized(MethodCallExpression expr, Expression instance, MethodInfo method, IReadOnlyList<Expression> args)
{
int n = method.GetParameters().Length;
MethodCallExpression updatedArgs = UpdateArgs(expr);
MethodCallExpression visitedArgs = VisitArgs(expr);
var updatedObj = default(MethodCallExpression);
var visitedObj = default(MethodCallExpression);
MethodCallExpression[] nodes;
if (instance == null)
{
nodes = new[] { expr, updatedArgs, visitedArgs };
}
else
{
updatedObj = UpdateObj(expr);
visitedObj = VisitObj(expr);
nodes = new[] { expr, updatedArgs, visitedArgs, updatedObj, visitedObj };
}
foreach (var node in nodes)
{
if (node != visitedObj && node != updatedObj)
{
Assert.Same(instance, node.Object);
}
Assert.Same(method, node.Method);
if (method.IsStatic)
{
AssertStaticMethodCall(n, node);
}
else
{
AssertInstanceMethodCall(n, node);
}
var argProvider = node as IArgumentProvider;
Assert.NotNull(argProvider);
Assert.Equal(n, argProvider.ArgumentCount);
Assert.Throws<ArgumentOutOfRangeException>(() => argProvider.GetArgument(-1));
Assert.Throws<ArgumentOutOfRangeException>(() => argProvider.GetArgument(n));
if (node != visitedArgs) // our visitor clones argument nodes
{
for (var i = 0; i < n; i++)
{
Assert.Same(args[i], argProvider.GetArgument(i));
Assert.Same(args[i], node.Arguments[i]);
}
}
}
}
private static void AssertStaticMethodCall(int n, object obj)
{
if (!PlatformDetection.IsNetNative) // .Net Native blocks internal framework reflection.
{
AssertTypeName("MethodCallExpression" + n, obj);
}
}
private static void AssertInstanceMethodCall(int n, object obj)
{
if (!PlatformDetection.IsNetNative) // .Net Native blocks internal framework reflection.
{
AssertTypeName("InstanceMethodCallExpression" + n, obj);
}
}
private static void AssertTypeName(string expected, object obj)
{
Assert.Equal(expected, obj.GetType().Name);
}
private static MethodCallExpression UpdateArgs(MethodCallExpression node)
{
// Tests the call of Update to Expression.Call factories.
MethodCallExpression res = node.Update(node.Object, node.Arguments.ToArray());
Assert.Same(node, res);
return res;
}
[Fact]
public static void UpdateStaticNull()
{
MethodCallExpression expr = Expression.Call(typeof(MS).GetMethod(nameof(MS.S0)));
Assert.Same(expr, expr.Update(null, null));
for (int argNum = 1; argNum != 7; ++argNum)
{
ConstantExpression[] args = Enumerable.Range(0, argNum).Select(i => Expression.Constant(i)).ToArray();
expr = Expression.Call(typeof(MS).GetMethod("S" + argNum), args);
// Should attempt to create new expression, and fail due to incorrect arguments.
AssertExtensions.Throws<ArgumentException>("method", () => expr.Update(null, null));
}
}
[Fact]
public static void UpdateInstanceNull()
{
ConstantExpression instance = Expression.Constant(new MS());
MethodCallExpression expr = Expression.Call(instance, typeof(MS).GetMethod(nameof(MS.I0)));
Assert.Same(expr, expr.Update(instance, null));
for (int argNum = 1; argNum != 6; ++argNum)
{
ConstantExpression[] args = Enumerable.Range(0, argNum).Select(i => Expression.Constant(i)).ToArray();
expr = Expression.Call(instance, typeof(MS).GetMethod("I" + argNum), args);
// Should attempt to create new expression, and fail due to incorrect arguments.
AssertExtensions.Throws<ArgumentException>("method", () => expr.Update(instance, null));
}
}
[Fact]
public static void UpdateStaticExtraArguments()
{
for (int argNum = 0; argNum != 7; ++argNum)
{
ConstantExpression[] args = Enumerable.Range(0, argNum).Select(i => Expression.Constant(i)).ToArray();
MethodCallExpression expr = Expression.Call(typeof(MS).GetMethod("S" + argNum), args);
// Should attempt to create new expression, and fail due to incorrect arguments.
AssertExtensions.Throws<ArgumentException>("method", () => expr.Update(null, args.Append(Expression.Constant(-1))));
}
}
[Fact]
public static void UpdateInstanceExtraArguments()
{
ConstantExpression instance = Expression.Constant(new MS());
for (int argNum = 0; argNum != 6; ++argNum)
{
ConstantExpression[] args = Enumerable.Range(0, argNum).Select(i => Expression.Constant(i)).ToArray();
MethodCallExpression expr = Expression.Call(instance, typeof(MS).GetMethod("I" + argNum), args);
// Should attempt to create new expression, and fail due to incorrect arguments.
AssertExtensions.Throws<ArgumentException>("method", () => expr.Update(instance, args.Append(Expression.Constant(-1))));
}
}
[Fact]
public static void UpdateStaticDifferentArguments()
{
for (int argNum = 1; argNum != 7; ++argNum)
{
ConstantExpression[] args = Enumerable.Range(0, argNum).Select(i => Expression.Constant(i)).ToArray();
MethodCallExpression expr = Expression.Call(typeof(MS).GetMethod("S" + argNum), args);
ConstantExpression[] newArgs = new ConstantExpression[argNum];
for (int i = 0; i != argNum; ++i)
{
args.CopyTo(newArgs, 0);
newArgs[i] = Expression.Constant(i);
Assert.NotSame(expr, expr.Update(null, newArgs));
}
}
}
[Fact]
public static void UpdateInstanceDifferentArguments()
{
ConstantExpression instance = Expression.Constant(new MS());
for (int argNum = 1; argNum != 6; ++argNum)
{
ConstantExpression[] args = Enumerable.Range(0, argNum).Select(i => Expression.Constant(i)).ToArray();
MethodCallExpression expr = Expression.Call(instance, typeof(MS).GetMethod("I" + argNum), args);
ConstantExpression[] newArgs = new ConstantExpression[argNum];
for (int i = 0; i != argNum; ++i)
{
args.CopyTo(newArgs, 0);
newArgs[i] = Expression.Constant(i);
Assert.NotSame(expr, expr.Update(instance, newArgs));
}
}
}
private static MethodCallExpression UpdateObj(MethodCallExpression node)
{
// Tests the call of Update to Expression.Call factories.
MethodCallExpression res = node.Update(new VisitorObj().Visit(node.Object), node.Arguments);
Assert.NotSame(node, res);
return res;
}
private static MethodCallExpression VisitArgs(MethodCallExpression node)
{
// Tests dispatch of ExpressionVisitor into Rewrite method which calls Expression.Call factories.
return (MethodCallExpression)new VisitorArgs().Visit(node);
}
private static MethodCallExpression VisitObj(MethodCallExpression node)
{
// Tests dispatch of ExpressionVisitor into Rewrite method which calls Expression.Call factories.
return (MethodCallExpression)new VisitorObj().Visit(node);
}
class NopVisitor : ExpressionVisitor
{
}
class VisitorArgs : ExpressionVisitor
{
protected override Expression VisitConstant(ConstantExpression node)
{
return Expression.Constant(node.Value, node.Type); // clones
}
}
class VisitorObj : ExpressionVisitor
{
protected override Expression VisitParameter(ParameterExpression node)
{
return Expression.Parameter(node.Type, node.Name); // clones
}
}
}
public class MS
{
public void I0() { }
public void I1(int a) { }
public void I2(int a, int b) { }
public void I3(int a, int b, int c) { }
public void I4(int a, int b, int c, int d) { }
public void I5(int a, int b, int c, int d, int e) { }
public static void S0() { }
public static void S1(int a) { }
public static void S2(int a, int b) { }
public static void S3(int a, int b, int c) { }
public static void S4(int a, int b, int c, int d) { }
public static void S5(int a, int b, int c, int d, int e) { }
public static void S6(int a, int b, int c, int d, int e, int f) { }
}
}
| |
using BefunGen.AST.CodeGen;
using BefunGen.AST.Exceptions;
using BefunGen.Properties;
using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
namespace BefunGen.AST
{
public class TextFungeParser
{
private GOLD.Parser parser;
public long ParseTime { get; private set; }
public long GenerateTime { get; private set; }
public TextFungeParser()
{
parser = new GOLD.Parser();
LoadTables(new BinaryReader(new MemoryStream(GetGrammar())));
}
public bool LoadTables(BinaryReader r)
{
return parser.LoadTables(r);
}
public bool LoadTables(string p)
{
return LoadTables(new BinaryReader(new FileStream(p, FileMode.Open)));
}
public string GenerateCode(string txt, string initialDisplay, bool debug)
{
Program p;
CodePiece c;
return GenerateCode(txt, initialDisplay, debug, out p, out c);
}
public string GenerateCode(string txt, string initialDisplay, bool debug, out Program p, out CodePiece cp)
{
p = GenerateAst(txt) as Program;
GenerateTime = Environment.TickCount;
cp = p.GenerateCode(initialDisplay);
GenerateTime = Environment.TickCount - GenerateTime;
string result;
if (debug)
result = cp.ToString();
else
result = cp.ToSimpleString();
return result;
}
public Program GenerateAst(string txt)
{
ParseTime = Environment.TickCount;
Program result = null;
result = (Program)Parse(txt);
if (result == null)
throw new Exception("Result == null");
result.Prepare();
ParseTime = Environment.TickCount - ParseTime;
return result;
}
public bool TryParse(string txt, string disp, out BefunGenException err, out Program prog)
{
ParseTime = Environment.TickCount;
Program result = null;
try
{
result = (Program)Parse(txt);
}
catch (BefunGenException e)
{
err = e;
prog = null;
return false;
}
catch (Exception e)
{
err = new NativeException(e);
prog = null;
return false;
}
if (result == null)
{
err = new WTFException();
prog = null;
return false;
}
try
{
result.Prepare();
}
catch (BefunGenException e)
{
err = e;
prog = null;
return false;
}
catch (Exception e)
{
err = new NativeException(e);
prog = null;
return false;
}
try
{
result.GenerateCode(disp);
}
catch (BefunGenException e)
{
err = e;
prog = null;
return false;
}
catch (Exception e)
{
err = new NativeException(e);
prog = null;
return false;
}
ParseTime = Environment.TickCount - ParseTime;
err = null;
prog = result;
return true;
}
private object Parse(string txt)
{
lock (this)
{
object result = null;
txt = txt.Replace("\r\n", "\n") + "\n";
parser.Open(ref txt);
parser.TrimReductions = false;
bool done = false;
while (!done)
{
GOLD.ParseMessage response = parser.Parse();
switch (response)
{
case GOLD.ParseMessage.LexicalError:
case GOLD.ParseMessage.SyntaxError:
case GOLD.ParseMessage.InternalError:
case GOLD.ParseMessage.NotLoadedError:
case GOLD.ParseMessage.GroupError:
Fail(response);
break;
case GOLD.ParseMessage.Reduction: // Reduction
parser.CurrentReduction = GrammarTableMap.CreateNewASTObject(parser.CurrentReduction as GOLD.Reduction, parser.CurrentPosition());
break;
case GOLD.ParseMessage.Accept: //Accepted!
result = parser.CurrentReduction;
done = true;
break;
case GOLD.ParseMessage.TokenRead: //You don't have to do anything here.
break;
}
}
return result;
}
}
private void Fail(GOLD.ParseMessage msg)
{
switch (msg)
{
case GOLD.ParseMessage.LexicalError: //Cannot recognize token
throw new LexicalErrorException(parser.CurrentToken().Data, new SourceCodePosition(parser));
case GOLD.ParseMessage.SyntaxError: //Expecting a different token
throw new SyntaxErrorException(parser.CurrentToken().Data, parser.ExpectedSymbols().Text(), new SourceCodePosition(parser));
case GOLD.ParseMessage.InternalError: //INTERNAL ERROR! Something is horribly wrong.
throw new InternalErrorException(new SourceCodePosition(parser));
case GOLD.ParseMessage.NotLoadedError: //This error occurs if the CGT was not loaded.
throw new NotLoadedErrorException(new SourceCodePosition(parser));
case GOLD.ParseMessage.GroupError: //GROUP ERROR! Unexpected end of file
throw new GroupErrorException(new SourceCodePosition(parser));
}
}
public static string ExtractDisplayFromTFFormat(string sourcecode)
{
string[] lines = Regex.Split(sourcecode, @"\r?\n");
var displayBuilder = new StringBuilder();
var inDisplayDefinition = false;
var first = true;
foreach (var rawline in lines)
{
var line = rawline.Trim();
if (line.StartsWith("///"))
{
string content = line.Substring(3);
if (inDisplayDefinition)
{
if (content.Trim() == "</DISPLAY>")
{
return displayBuilder.ToString();
}
else
{
if (first)
displayBuilder.Append(content);
else
displayBuilder.Append("\n" + content);
first = false;
}
}
else
{
if (content.Trim() == "<DISPLAY>")
{
inDisplayDefinition = true;
displayBuilder = new StringBuilder();
first = true;
}
}
}
else
{
inDisplayDefinition = false;
}
}
return string.Empty;
}
public static bool UpdateDisplayInTFFormat(ref string sourcecode, string displayvalue)
{
if (string.IsNullOrWhiteSpace(displayvalue)) return RemoveDisplayInTFFormat(ref sourcecode);
var inputLines = Regex.Split(sourcecode, @"\r?\n");
var displayLines = Regex.Split(displayvalue, @"\r?\n");
#region Patch existing <DISPLAY>
{
StringBuilder output = new StringBuilder();
bool replaced = false;
bool inDisplayDefinition = false;
string displayindent = "";
foreach (var rawline in inputLines)
{
var line = rawline.TrimStart();
if (line.StartsWith("///"))
{
string content = line.Substring(3);
if (inDisplayDefinition)
{
if (content.Trim() == "</DISPLAY>")
{
// skip
inDisplayDefinition = false;
output.AppendLine(rawline);
continue;
}
else
{
// skip
continue;
}
}
else
{
if (content.Trim() == "<DISPLAY>" && !replaced)
{
// add display
output.AppendLine(rawline);
displayindent = line.Substring(0, line.IndexOf("///"));
foreach (var dl in displayLines) output.AppendLine(displayindent + "///" + dl);
inDisplayDefinition = true;
replaced = true;
}
else
{
// output
output.AppendLine(rawline);
}
}
}
else
{
// output
inDisplayDefinition = false;
output.AppendLine(rawline);
}
}
if (replaced)
{
StringBuilderToStringWithoutDanglingNewline(output);
return true;
}
}
#endregion
#region Create new <DISPLAY>
{
StringBuilder output = new StringBuilder();
bool replaced = false;
string displayindent = "";
foreach (var rawline in inputLines)
{
var line = rawline.TrimStart();
if (line.Trim().ToLower().StartsWith("program ") && !replaced)
{
// add display
displayindent = rawline.Substring(0, rawline.IndexOf("program"));
output.AppendLine(displayindent + "///<DISPLAY>");
foreach (var dl in displayLines) output.AppendLine(displayindent + "///" + dl);
output.AppendLine(displayindent + "///</DISPLAY>");
replaced = true;
}
// output
output.AppendLine(rawline);
}
if (replaced)
{
StringBuilderToStringWithoutDanglingNewline(output);
return true;
}
}
#endregion
return false;
}
private static bool RemoveDisplayInTFFormat(ref string sourcecode)
{
var inputLines = Regex.Split(sourcecode, @"\r?\n");
StringBuilder output = new StringBuilder();
bool inDisplayDefinition = false;
foreach (var rawline in inputLines)
{
var line = rawline.TrimStart();
if (line.StartsWith("///"))
{
string content = line.Substring(3);
if (inDisplayDefinition)
{
if (content.Trim() == "</DISPLAY>")
{
// skip
inDisplayDefinition = false;
continue;
}
else
{
// skip
continue;
}
}
else
{
if (content.Trim() == "<DISPLAY>")
{
// skip
inDisplayDefinition = true;
}
else
{
// output
output.AppendLine(rawline);
}
}
}
else
{
// output
inDisplayDefinition = false;
output.AppendLine(rawline);
}
}
sourcecode = StringBuilderToStringWithoutDanglingNewline(output);
return true;
}
private static string StringBuilderToStringWithoutDanglingNewline(StringBuilder b)
{
var str = b.ToString();
if (str.EndsWith("\r\n")) return str.Substring(0, str.Length - 2);
if (str.EndsWith("\n")) return str.Substring(0, str.Length - 1);
return str;
}
public string GetGrammarDefinition()
{
return Resources.TextFunge_grm;
}
public byte[] GetGrammar()
{
return Resources.TextFunge_egt;
}
}
}
| |
// 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.ServerManagement
{
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// GatewayOperations operations.
/// </summary>
public partial interface IGatewayOperations
{
/// <summary>
/// Creates or updates a ManagementService gateway.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group
/// within the user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
/// <param name='location'>
/// location of the resource
/// </param>
/// <param name='tags'>
/// resource tags
/// </param>
/// <param name='upgradeMode'>
/// The upgradeMode property gives the flexibility to gateway to auto
/// upgrade itself. If properties value not specified, then we assume
/// upgradeMode = Automatic. Possible values include: 'Manual',
/// 'Automatic'
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="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<GatewayResource>> CreateWithHttpMessagesAsync(string resourceGroupName, string gatewayName, string location = default(string), object tags = default(object), UpgradeMode? upgradeMode = default(UpgradeMode?), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Creates or updates a ManagementService gateway.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group
/// within the user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
/// <param name='location'>
/// location of the resource
/// </param>
/// <param name='tags'>
/// resource tags
/// </param>
/// <param name='upgradeMode'>
/// The upgradeMode property gives the flexibility to gateway to auto
/// upgrade itself. If properties value not specified, then we assume
/// upgradeMode = Automatic. Possible values include: 'Manual',
/// 'Automatic'
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="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<GatewayResource>> BeginCreateWithHttpMessagesAsync(string resourceGroupName, string gatewayName, string location = default(string), object tags = default(object), UpgradeMode? upgradeMode = default(UpgradeMode?), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Updates a gateway belonging to a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group
/// within the user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
/// <param name='location'>
/// location of the resource
/// </param>
/// <param name='tags'>
/// resource tags
/// </param>
/// <param name='upgradeMode'>
/// The upgradeMode property gives the flexibility to gateway to auto
/// upgrade itself. If properties value not specified, then we assume
/// upgradeMode = Automatic. Possible values include: 'Manual',
/// 'Automatic'
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="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<GatewayResource>> UpdateWithHttpMessagesAsync(string resourceGroupName, string gatewayName, string location = default(string), object tags = default(object), UpgradeMode? upgradeMode = default(UpgradeMode?), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Updates a gateway belonging to a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group
/// within the user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
/// <param name='location'>
/// location of the resource
/// </param>
/// <param name='tags'>
/// resource tags
/// </param>
/// <param name='upgradeMode'>
/// The upgradeMode property gives the flexibility to gateway to auto
/// upgrade itself. If properties value not specified, then we assume
/// upgradeMode = Automatic. Possible values include: 'Manual',
/// 'Automatic'
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="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<GatewayResource>> BeginUpdateWithHttpMessagesAsync(string resourceGroupName, string gatewayName, string location = default(string), object tags = default(object), UpgradeMode? upgradeMode = default(UpgradeMode?), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Deletes a gateway from a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group
/// within the user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string gatewayName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Returns a gateway
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group
/// within the user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum)
/// </param>
/// <param name='expand'>
/// Gets subscription credentials which uniquely identify Microsoft
/// Azure subscription. The subscription ID forms part of the URI for
/// every service call. Possible values include: 'status'
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="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<GatewayResource>> GetWithHttpMessagesAsync(string resourceGroupName, string gatewayName, GatewayExpandOption? expand = default(GatewayExpandOption?), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Returns gateways in a subscription
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// 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<Microsoft.Rest.Azure.IPage<GatewayResource>>> ListWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Returns gateways in a resource group
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group
/// within the user subscriptionId.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="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<Microsoft.Rest.Azure.IPage<GatewayResource>>> ListForResourceGroupWithHttpMessagesAsync(string resourceGroupName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Upgrade a gateway
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group
/// within the user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> UpgradeWithHttpMessagesAsync(string resourceGroupName, string gatewayName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Upgrade a gateway
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group
/// within the user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> BeginUpgradeWithHttpMessagesAsync(string resourceGroupName, string gatewayName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Regenerate a gateway's profile
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group
/// within the user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> RegenerateProfileWithHttpMessagesAsync(string resourceGroupName, string gatewayName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Regenerate a gateway's profile
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group
/// within the user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> BeginRegenerateProfileWithHttpMessagesAsync(string resourceGroupName, string gatewayName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Gets a gateway profile
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group
/// within the user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="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<GatewayProfile>> GetProfileWithHttpMessagesAsync(string resourceGroupName, string gatewayName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Gets a gateway profile
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group
/// within the user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="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<GatewayProfile>> BeginGetProfileWithHttpMessagesAsync(string resourceGroupName, string gatewayName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Returns gateways in a subscription
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// 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<Microsoft.Rest.Azure.IPage<GatewayResource>>> ListNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Returns gateways in a resource group
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// 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<Microsoft.Rest.Azure.IPage<GatewayResource>>> ListForResourceGroupNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
}
}
| |
#region License
/*---------------------------------------------------------------------------------*\
Distributed under the terms of an MIT-style license:
The MIT License
Copyright (c) 2006-2009 Stephen M. McKamey
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 License
using System;
using System.IO;
using System.Collections.Generic;
namespace Pathfinding.Serialization.JsonFx
{
/// <summary>
/// Represents a proxy method for serialization of types which do not implement IJsonSerializable
/// </summary>
/// <typeparam name="T">the type for this proxy</typeparam>
/// <param name="writer">the JsonWriter to serialize to</param>
/// <param name="value">the value to serialize</param>
public delegate void WriteDelegate<T>(JsonWriter writer, T value);
/// <summary>
/// Controls the serialization settings for JsonWriter
/// </summary>
public class JsonWriterSettings
{
#region Fields
private WriteDelegate<DateTime> dateTimeSerializer;
private int maxDepth = 25;
private string newLine = Environment.NewLine;
private bool prettyPrint;
private string tab = "\t";
private string typeHintName;
private bool useXmlSerializationAttributes;
#endregion Fields
#region Properties
/// <summary>
/// Gets or sets a value indicating whether this to handle cyclic references.
/// </summary>
/// <remarks>
/// Handling cyclic references is slightly more expensive and needs to keep a list
/// of all deserialized objects, but it will not crash or go into infinite loops
/// when trying to serialize an object graph with cyclic references and after
/// deserialization all references will point to the correct objects even if
/// it was used in different places (this can be good even if you do not have
/// cyclic references in your data).
///
/// More specifically, if your object graph (where one reference is a directed edge)
/// is a tree, this should be false, otherwise it should be true.
///
/// Note also that the deserialization methods which take a start position
/// will not work with this setting enabled.
///
/// When an object is first encountered, it will be serialized, just as usual,
/// but when it is encountered again, it will be replaced with an object only
/// containing a "@ref" field specifying that this is identical to object number
/// [value] that was serialized. This number is zero indexed.
///
/// Arrays can unfortunately not be deserialized to the same object if they are
/// referenced in multiple places since the contents of the array needs to be deserialized
/// before the actual array is created.
///
/// Make sure you also enable cyclic reference handling in the reader settings.
/// </remarks>
/// <value>
/// <c>true</c> if handle cyclic references; otherwise, <c>false</c>.
/// </value>
public bool HandleCyclicReferences {get; set;}
/// <summary>
/// Gets and sets the property name used for type hinting.
/// </summary>
public virtual string TypeHintName
{
get { return this.typeHintName; }
set { this.typeHintName = value; }
}
/// <summary>
/// Gets and sets if JSON will be formatted for human reading.
/// </summary>
public virtual bool PrettyPrint
{
get { return this.prettyPrint; }
set { this.prettyPrint = value; }
}
/// <summary>
/// Gets and sets the string to use for indentation
/// </summary>
public virtual string Tab
{
get { return this.tab; }
set { this.tab = value; }
}
/// <summary>
/// Gets and sets the line terminator string
/// </summary>
public virtual string NewLine
{
get { return this.newLine; }
set { this.newLine = value; }
}
/// <summary>
/// Gets and sets the maximum depth to be serialized.
/// </summary>
public virtual int MaxDepth
{
get { return this.maxDepth; }
set
{
if (value < 1)
{
throw new ArgumentOutOfRangeException("MaxDepth must be a positive integer as it controls the maximum nesting level of serialized objects.");
}
this.maxDepth = value;
}
}
/// <summary>
/// Gets and sets if should use XmlSerialization Attributes.
/// </summary>
/// <remarks>
/// Respects XmlIgnoreAttribute, ...
/// </remarks>
public virtual bool UseXmlSerializationAttributes
{
get { return this.useXmlSerializationAttributes; }
set { this.useXmlSerializationAttributes = value; }
}
/// <summary>
/// Gets and sets a proxy formatter to use for DateTime serialization
/// </summary>
public virtual WriteDelegate<DateTime> DateTimeSerializer
{
get { return this.dateTimeSerializer; }
set { this.dateTimeSerializer = value; }
}
/** Enables more debugging messages.
* E.g about why some members are not serialized.
* The number of debugging messages are in no way exhaustive
*/
public virtual bool DebugMode { get; set; }
protected List<JsonConverter> converters = new List<JsonConverter>();
/** Returns the converter for the specified type */
public virtual JsonConverter GetConverter (Type type) {
for (int i=0;i<converters.Count;i++)
if (converters[i].CanConvert (type))
return converters[i];
return null;
}
/** Adds a converter to use to serialize otherwise non-serializable types.
* Good if you do not have the source and it throws error when trying to serialize it.
* For example the Unity3D Vector3 can be serialized using a special converter
*/
public virtual void AddTypeConverter (JsonConverter converter) {
converters.Add (converter);
}
#endregion Properties
}
public abstract class JsonConverter {
/** Test if this converter can convert the specified type */
public abstract bool CanConvert (Type t);
public void Write (JsonWriter writer, Type type, object value) {
Dictionary<string,object> dict = WriteJson (type,value);
writer.Write (dict);
}
public object Read (JsonReader reader, Type type, Dictionary<string,object> value) {
return ReadJson (type, value);
}
public float CastFloat (object o) {
if (o==null)return 0.0F;
try {
return System.Convert.ToSingle(o);
} catch(System.Exception e) {
throw new JsonDeserializationException ("Cannot cast object to float. Expected float, got "+o.GetType(),e,0);
}
}
public double CastDouble (object o) {
if (o==null)return 0.0;
try {
return System.Convert.ToDouble(o);
} catch(System.Exception e) {
throw new JsonDeserializationException ("Cannot cast object to double. Expected double, got "+o.GetType(),e,0);
}
}
public abstract Dictionary<string,object> WriteJson (Type type, object value);
public abstract object ReadJson (Type type, Dictionary<string,object> value);
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Speech.Recognition;
using ClownCrew.GitBitch.Client.Interfaces;
using ClownCrew.GitBitch.Client.Model;
using ClownCrew.GitBitch.Client.Model.EventArgs;
namespace ClownCrew.GitBitch.Client.Agents
{
public class CommandAgent : ICommandAgent
{
private static readonly object SyncRoot = new object();
private readonly IEventHub _eventHub;
private readonly List<IGitBitchCommand> _commands;
private readonly SpeechRecognitionEngine _speechRecognitionEngine;
private bool _initiated;
private int _interruptCounter;
private bool _listenerActice;
private bool _voiceListenerWorking;
public event EventHandler<CommandRegisteredEventArgs> CommandRegisteredEvent;
public CommandAgent(IEventHub eventHub, ISettingAgent settingAgent)
{
_eventHub = eventHub;
_commands = new List<IGitBitchCommand>();
_eventHub.StartTalkingEvent += EventHub_StartTalkingEvent;
_eventHub.DoneTalkingEvent += EventHub_DoneTalkingEvent;
_eventHub.StartListeningEvent += EventHub_StartListeningEvent;
_eventHub.DoneListeningEvent += EventHub_DoneListeningEvent;
_eventHub.StartWorkingEvent += EventHub_StartWorkingEvent;
_eventHub.DoneWorkingEvent += EventHub_DoneWorkingEvent;
_speechRecognitionEngine = new SpeechRecognitionEngine();
_speechRecognitionEngine.SpeechRecognized += SpeechRecognized;
_speechRecognitionEngine.SpeechDetected += SpeechDetected;
_speechRecognitionEngine.SpeechRecognitionRejected += SpeechRecognitionRejected;
_speechRecognitionEngine.SpeechHypothesized += SpeechHypothesized;
_speechRecognitionEngine.AudioStateChanged += AudioStateChanged;
_speechRecognitionEngine.EmulateRecognizeCompleted += EmulateRecognizeCompleted;
_speechRecognitionEngine.LoadGrammarCompleted += LoadGrammarCompleted;
_speechRecognitionEngine.RecognizeCompleted += RecognizeCompleted;
_speechRecognitionEngine.RecognizerUpdateReached += RecognizerUpdateReached;
_speechRecognitionEngine.AudioLevelUpdated += AudioLevelUpdated;
_speechRecognitionEngine.AudioSignalProblemOccurred += AudioSignalProblemOccurred;
_eventHub.InvokeAudioInputStateChangedEvent(Source.CommandAgent, _voiceListenerWorking ? ListeningAudioState.NotListening : ListeningAudioState.MicrophoneMuted);
}
private void EventHub_DoneWorkingEvent(object sender, DoneWorkingEventArgs e)
{
ResumeListening();
}
private void EventHub_StartWorkingEvent(object sender, StartWorkingEventArgs e)
{
PauseListening();
}
private void EventHub_DoneListeningEvent(object sender, DoneListeningEventArgs e)
{
ResumeListening();
}
private void EventHub_StartListeningEvent(object sender, StartListeningEventArgs e)
{
PauseListening();
}
private void EventHub_DoneTalkingEvent(object sender, DoneTalkingEventArgs e)
{
ResumeListening();
}
private void EventHub_StartTalkingEvent(object sender, StartTalkingEventArgs e)
{
PauseListening();
}
private void ResumeListening()
{
lock (SyncRoot)
{
_interruptCounter--;
if (_interruptCounter == 0)
{
StartListening();
}
}
}
private void PauseListening()
{
lock (SyncRoot)
{
if (_interruptCounter == 0)
{
StopListening();
}
_interruptCounter++;
}
}
private void StartListening()
{
if (_listenerActice) return;
_listenerActice = true;
_eventHub.InvokeAudioInputStateChangedEvent(Source.ListenerAgent, _voiceListenerWorking ? ListeningAudioState.Listening : ListeningAudioState.MicrophoneMuted);
}
private void StopListening()
{
if (!_listenerActice) return;
_listenerActice = false;
_eventHub.InvokeAudioInputStateChangedEvent(Source.ListenerAgent, _voiceListenerWorking ? ListeningAudioState.NotListening : ListeningAudioState.MicrophoneMuted);
}
private void SpeechDetected(object sender, SpeechDetectedEventArgs e)
{
Debug.WriteLine("Speech detected: " + e.AudioPosition + ".");
}
private void SpeechRecognitionRejected(object sender, SpeechRecognitionRejectedEventArgs e)
{
Debug.WriteLine("Speech recognition rejected '" + e.Result.Text + "'.");
}
private void SpeechHypothesized(object sender, SpeechHypothesizedEventArgs e)
{
Debug.WriteLine("Speech hypothesized '" + e.Result.Text + "'.");
}
private void EmulateRecognizeCompleted(object sender, EmulateRecognizeCompletedEventArgs e)
{
Debug.WriteLine("Emulate recognize completed '" + e.Result.Text + "'.");
}
private void RecognizeCompleted(object sender, RecognizeCompletedEventArgs e)
{
if (e.Result != null) Debug.WriteLine("Recognize completed '" + e.Result.Text + "'.");
}
private void LoadGrammarCompleted(object sender, LoadGrammarCompletedEventArgs e)
{
//Debug.WriteLine("Load grammar completed: " + e.Grammar.Name);
}
private void AudioSignalProblemOccurred(object sender, AudioSignalProblemOccurredEventArgs e)
{
Debug.WriteLine("Audio signal problem occurred: " + e.AudioSignalProblem);
}
private void RecognizerUpdateReached(object sender, RecognizerUpdateReachedEventArgs e)
{
Debug.WriteLine("Recognizer update reached: " + e.AudioPosition + " " + e.UserToken);
}
private void AudioLevelUpdated(object sender, AudioLevelUpdatedEventArgs e)
{
_eventHub.InvokeAudioInputLevelChangedEvent(Source.CommandAgent, e.AudioLevel);
}
private void AudioStateChanged(object sender, AudioStateChangedEventArgs e)
{
Debug.WriteLine("Audio state changed: " + e.AudioState);
}
public IEnumerable<IGitBitchCommand> Commands { get { return _commands; } }
private async void SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
if (!_listenerActice) return;
var command = FindCommand(e);
if (command != null)
{
_eventHub.InvokeHeardSomethingEvent(Source.CommandAgent, e.Result.Text);
await command.ExecuteAsync(command.GetKey(e.Result.Text), e.Result.Text);
}
}
private IGitBitchCommand FindCommand(SpeechRecognizedEventArgs e)
{
return _commands.FirstOrDefault(command => command.Phrases.Any(phrase => string.Compare(phrase, e.Result.Text, StringComparison.InvariantCultureIgnoreCase) == 0));
}
public void ClearCommands()
{
_commands.Clear();
_speechRecognitionEngine.UnloadAllGrammars();
}
public void RegisterCommands(IGitBitchCommands gitBitchCommands)
{
foreach (var command in gitBitchCommands.Items)
{
if (command.Phrases.Any())
{
AddPhrases(command.Phrases.ToArray());
}
command.RegisterPhraseEvent += Command_RegisterPhraseEvent;
_commands.Add(command);
InvokeCommandRegisteredEvent(gitBitchCommands.Name, command);
}
}
private void AddPhrases(IEnumerable<string> phrases)
{
var choices = new Choices();
choices.Add(phrases.ToArray());
_speechRecognitionEngine.LoadGrammarAsync(new Grammar(choices));
if (_initiated) return;
lock (SyncRoot)
{
if (!_initiated)
{
_initiated = true;
if (_voiceListenerWorking)
{
_speechRecognitionEngine.SetInputToDefaultAudioDevice();
_speechRecognitionEngine.RecognizeAsync(RecognizeMode.Multiple);
}
}
}
}
private void Command_RegisterPhraseEvent(object sender, RegisterPhraseEventArgs e)
{
AddPhrases(e.Phrases);
}
protected virtual void InvokeCommandRegisteredEvent(string sectionName, IGitBitchCommand command)
{
var handler = CommandRegisteredEvent;
if (handler != null) handler(this, new CommandRegisteredEventArgs(sectionName, command));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
namespace ClosedXML.Excel
{
internal class XLCellsCollection
{
private readonly Dictionary<int, Dictionary<int, XLCell>> rowsCollection = new Dictionary<int, Dictionary<int, XLCell>>();
public readonly Dictionary<Int32, Int32> ColumnsUsed = new Dictionary<int, int>();
public readonly Dictionary<Int32, HashSet<Int32>> deleted = new Dictionary<int, HashSet<int>>();
internal Dictionary<int, Dictionary<int, XLCell>> RowsCollection
{
get { return rowsCollection; }
}
public Int32 MaxColumnUsed;
public Int32 MaxRowUsed;
public Dictionary<Int32, Int32> RowsUsed = new Dictionary<int, int>();
public XLCellsCollection()
{
Clear();
}
public Int32 Count { get; private set; }
public void Add(XLSheetPoint sheetPoint, XLCell cell)
{
Add(sheetPoint.Row, sheetPoint.Column, cell);
}
public void Add(Int32 row, Int32 column, XLCell cell)
{
Count++;
IncrementUsage(RowsUsed, row);
IncrementUsage(ColumnsUsed, column);
Dictionary<int, XLCell> columnsCollection;
if (!rowsCollection.TryGetValue(row, out columnsCollection))
{
columnsCollection = new Dictionary<int, XLCell>();
rowsCollection.Add(row, columnsCollection);
}
columnsCollection.Add(column, cell);
if (row > MaxRowUsed) MaxRowUsed = row;
if (column > MaxColumnUsed) MaxColumnUsed = column;
HashSet<Int32> delHash;
if (deleted.TryGetValue(row, out delHash))
delHash.Remove(column);
}
private static void IncrementUsage(Dictionary<int, int> dictionary, Int32 key)
{
if (dictionary.ContainsKey(key))
dictionary[key]++;
else
dictionary.Add(key, 1);
}
private static void DecrementUsage(Dictionary<int, int> dictionary, Int32 key)
{
Int32 count;
if (!dictionary.TryGetValue(key, out count)) return;
if (count > 0)
dictionary[key]--;
else
dictionary.Remove(key);
}
public void Clear()
{
Count = 0;
RowsUsed.Clear();
ColumnsUsed.Clear();
rowsCollection.Clear();
MaxRowUsed = 0;
MaxColumnUsed = 0;
}
public void Remove(XLSheetPoint sheetPoint)
{
Remove(sheetPoint.Row, sheetPoint.Column);
}
public void Remove(Int32 row, Int32 column)
{
Count--;
DecrementUsage(RowsUsed, row);
DecrementUsage(ColumnsUsed, row);
HashSet<Int32> delHash;
if (deleted.TryGetValue(row, out delHash))
{
if (!delHash.Contains(column))
delHash.Add(column);
}
else
{
delHash = new HashSet<int>();
delHash.Add(column);
deleted.Add(row, delHash);
}
Dictionary<int, XLCell> columnsCollection;
if (rowsCollection.TryGetValue(row, out columnsCollection))
{
columnsCollection.Remove(column);
if (columnsCollection.Count == 0)
{
rowsCollection.Remove(row);
}
}
}
internal IEnumerable<XLCell> GetCells(Int32 rowStart, Int32 columnStart,
Int32 rowEnd, Int32 columnEnd,
Func<IXLCell, Boolean> predicate = null)
{
int finalRow = rowEnd > MaxRowUsed ? MaxRowUsed : rowEnd;
int finalColumn = columnEnd > MaxColumnUsed ? MaxColumnUsed : columnEnd;
for (int ro = rowStart; ro <= finalRow; ro++)
{
Dictionary<int, XLCell> columnsCollection;
if (rowsCollection.TryGetValue(ro, out columnsCollection))
{
for (int co = columnStart; co <= finalColumn; co++)
{
XLCell cell;
if (columnsCollection.TryGetValue(co, out cell)
&& (predicate == null || predicate(cell)))
yield return cell;
}
}
}
}
internal HashSet<Int32> GetStyleIds(Int32 initial)
{
HashSet<Int32> ids = new HashSet<int>();
ids.Add(initial);
foreach (var row in rowsCollection)
{
foreach (var column in row.Value)
{
var id = column.Value.GetStyleId();
if (!ids.Contains(id))
{
ids.Add(id);
}
}
}
return ids;
}
internal IEnumerable<XLCell> GetCellsUsed(Int32 rowStart, Int32 columnStart,
Int32 rowEnd, Int32 columnEnd,
Boolean includeFormats, Func<IXLCell, Boolean> predicate = null)
{
int finalRow = rowEnd > MaxRowUsed ? MaxRowUsed : rowEnd;
int finalColumn = columnEnd > MaxColumnUsed ? MaxColumnUsed : columnEnd;
for (int ro = rowStart; ro <= finalRow; ro++)
{
Dictionary<int, XLCell> columnsCollection;
if (rowsCollection.TryGetValue(ro, out columnsCollection))
{
for (int co = columnStart; co <= finalColumn; co++)
{
XLCell cell;
if (columnsCollection.TryGetValue(co, out cell)
&& !cell.IsEmpty(includeFormats)
&& (predicate == null || predicate(cell)))
yield return cell;
}
}
}
}
public XLSheetPoint FirstPointUsed(Int32 rowStart, Int32 columnStart,
Int32 rowEnd, Int32 columnEnd, Boolean includeFormats = false, Func<IXLCell, Boolean> predicate = null)
{
int finalRow = rowEnd > MaxRowUsed ? MaxRowUsed : rowEnd;
int finalColumn = columnEnd > MaxColumnUsed ? MaxColumnUsed : columnEnd;
var firstRow = FirstRowUsed(rowStart, columnStart, finalRow, finalColumn, includeFormats, predicate);
if (firstRow == 0) return new XLSheetPoint(0, 0);
var firstColumn = FirstColumnUsed(rowStart, columnStart, finalRow, finalColumn, includeFormats, predicate);
if (firstColumn == 0) return new XLSheetPoint(0, 0);
return new XLSheetPoint(firstRow, firstColumn);
}
public XLSheetPoint LastPointUsed(Int32 rowStart, Int32 columnStart,
Int32 rowEnd, Int32 columnEnd, Boolean includeFormats = false, Func<IXLCell, Boolean> predicate = null)
{
int finalRow = rowEnd > MaxRowUsed ? MaxRowUsed : rowEnd;
int finalColumn = columnEnd > MaxColumnUsed ? MaxColumnUsed : columnEnd;
var firstRow = LastRowUsed(rowStart, columnStart, finalRow, finalColumn, includeFormats, predicate);
if (firstRow == 0) return new XLSheetPoint(0, 0);
var firstColumn = LastColumnUsed(rowStart, columnStart, finalRow, finalColumn, includeFormats, predicate);
if (firstColumn == 0) return new XLSheetPoint(0, 0);
return new XLSheetPoint(firstRow, firstColumn);
}
public int FirstRowUsed(int rowStart, int columnStart, int rowEnd, int columnEnd, Boolean includeFormats,
Func<IXLCell, Boolean> predicate = null)
{
int finalRow = rowEnd > MaxRowUsed ? MaxRowUsed : rowEnd;
int finalColumn = columnEnd > MaxColumnUsed ? MaxColumnUsed : columnEnd;
for (int ro = rowStart; ro <= finalRow; ro++)
{
Dictionary<int, XLCell> columnsCollection;
if (rowsCollection.TryGetValue(ro, out columnsCollection))
{
for (int co = columnStart; co <= finalColumn; co++)
{
XLCell cell;
if (columnsCollection.TryGetValue(co, out cell)
&& !cell.IsEmpty(includeFormats)
&& (predicate == null || predicate(cell)))
return ro;
}
}
}
return 0;
}
public int FirstColumnUsed(int rowStart, int columnStart, int rowEnd, int columnEnd, Boolean includeFormats, Func<IXLCell, Boolean> predicate = null)
{
int finalRow = rowEnd > MaxRowUsed ? MaxRowUsed : rowEnd;
int finalColumn = columnEnd > MaxColumnUsed ? MaxColumnUsed : columnEnd;
for (int ro = rowStart; ro <= finalRow; ro++)
{
Dictionary<int, XLCell> columnsCollection;
if (rowsCollection.TryGetValue(ro, out columnsCollection))
{
for (int co = columnStart; co <= finalColumn; co++)
{
XLCell cell;
if (columnsCollection.TryGetValue(co, out cell)
&& !cell.IsEmpty(includeFormats)
&& (predicate == null || predicate(cell)))
return co;
}
}
}
return 0;
}
public int LastRowUsed(int rowStart, int columnStart, int rowEnd, int columnEnd, Boolean includeFormats, Func<IXLCell, Boolean> predicate = null)
{
int finalRow = rowEnd > MaxRowUsed ? MaxRowUsed : rowEnd;
int finalColumn = columnEnd > MaxColumnUsed ? MaxColumnUsed : columnEnd;
for (int ro = finalRow; ro >= rowStart; ro--)
{
Dictionary<int, XLCell> columnsCollection;
if (rowsCollection.TryGetValue(ro, out columnsCollection))
{
for (int co = finalColumn; co >= columnStart; co--)
{
XLCell cell;
if (columnsCollection.TryGetValue(co, out cell)
&& !cell.IsEmpty(includeFormats)
&& (predicate == null || predicate(cell)))
return ro;
}
}
}
return 0;
}
public int LastColumnUsed(int rowStart, int columnStart, int rowEnd, int columnEnd, Boolean includeFormats, Func<IXLCell, Boolean> predicate = null)
{
int maxCo = 0;
int finalRow = rowEnd > MaxRowUsed ? MaxRowUsed : rowEnd;
int finalColumn = columnEnd > MaxColumnUsed ? MaxColumnUsed : columnEnd;
for (int ro = finalRow; ro >= rowStart; ro--)
{
Dictionary<int, XLCell> columnsCollection;
if (rowsCollection.TryGetValue(ro, out columnsCollection))
{
for (int co = finalColumn; co >= columnStart && co > maxCo; co--)
{
XLCell cell;
if (columnsCollection.TryGetValue(co, out cell)
&& !cell.IsEmpty(includeFormats)
&& (predicate == null || predicate(cell)))
maxCo = co;
}
}
}
return maxCo;
}
public void RemoveAll(Int32 rowStart, Int32 columnStart,
Int32 rowEnd, Int32 columnEnd)
{
int finalRow = rowEnd > MaxRowUsed ? MaxRowUsed : rowEnd;
int finalColumn = columnEnd > MaxColumnUsed ? MaxColumnUsed : columnEnd;
for (int ro = rowStart; ro <= finalRow; ro++)
{
Dictionary<int, XLCell> columnsCollection;
if (rowsCollection.TryGetValue(ro, out columnsCollection))
{
for (int co = columnStart; co <= finalColumn; co++)
{
if (columnsCollection.ContainsKey(co))
Remove(ro, co);
}
}
}
}
public IEnumerable<XLSheetPoint> GetSheetPoints(Int32 rowStart, Int32 columnStart,
Int32 rowEnd, Int32 columnEnd)
{
int finalRow = rowEnd > MaxRowUsed ? MaxRowUsed : rowEnd;
int finalColumn = columnEnd > MaxColumnUsed ? MaxColumnUsed : columnEnd;
for (int ro = rowStart; ro <= finalRow; ro++)
{
Dictionary<int, XLCell> columnsCollection;
if (rowsCollection.TryGetValue(ro, out columnsCollection))
{
for (int co = columnStart; co <= finalColumn; co++)
{
if (columnsCollection.ContainsKey(co))
yield return new XLSheetPoint(ro, co);
}
}
}
}
public XLCell GetCell(Int32 row, Int32 column)
{
if (row > MaxRowUsed || column > MaxColumnUsed)
return null;
Dictionary<int, XLCell> columnsCollection;
if (rowsCollection.TryGetValue(row, out columnsCollection))
{
XLCell cell;
return columnsCollection.TryGetValue(column, out cell) ? cell : null;
}
return null;
}
public XLCell GetCell(XLSheetPoint sp)
{
return GetCell(sp.Row, sp.Column);
}
internal void SwapRanges(XLSheetRange sheetRange1, XLSheetRange sheetRange2, XLWorksheet worksheet)
{
Int32 rowCount = sheetRange1.LastPoint.Row - sheetRange1.FirstPoint.Row + 1;
Int32 columnCount = sheetRange1.LastPoint.Column - sheetRange1.FirstPoint.Column + 1;
for (int row = 0; row < rowCount; row++)
{
for (int column = 0; column < columnCount; column++)
{
var sp1 = new XLSheetPoint(sheetRange1.FirstPoint.Row + row, sheetRange1.FirstPoint.Column + column);
var sp2 = new XLSheetPoint(sheetRange2.FirstPoint.Row + row, sheetRange2.FirstPoint.Column + column);
var cell1 = GetCell(sp1);
var cell2 = GetCell(sp2);
if (cell1 == null) cell1 = worksheet.Cell(sp1.Row, sp1.Column);
if (cell2 == null) cell2 = worksheet.Cell(sp2.Row, sp2.Column);
//if (cell1 != null)
//{
cell1.Address = new XLAddress(cell1.Worksheet, sp2.Row, sp2.Column, false, false);
Remove(sp1);
//if (cell2 != null)
Add(sp1, cell2);
//}
//if (cell2 == null) continue;
cell2.Address = new XLAddress(cell2.Worksheet, sp1.Row, sp1.Column, false, false);
Remove(sp2);
//if (cell1 != null)
Add(sp2, cell1);
}
}
}
internal IEnumerable<XLCell> GetCells()
{
return GetCells(1, 1, MaxRowUsed, MaxColumnUsed);
}
internal IEnumerable<XLCell> GetCells(Func<IXLCell, Boolean> predicate)
{
for (int ro = 1; ro <= MaxRowUsed; ro++)
{
Dictionary<int, XLCell> columnsCollection;
if (rowsCollection.TryGetValue(ro, out columnsCollection))
{
for (int co = 1; co <= MaxColumnUsed; co++)
{
XLCell cell;
if (columnsCollection.TryGetValue(co, out cell)
&& (predicate == null || predicate(cell)))
yield return cell;
}
}
}
}
public Boolean Contains(Int32 row, Int32 column)
{
Dictionary<int, XLCell> columnsCollection;
return rowsCollection.TryGetValue(row, out columnsCollection) && columnsCollection.ContainsKey(column);
}
public Int32 MinRowInColumn(Int32 column)
{
for (int row = 1; row <= MaxRowUsed; row++)
{
Dictionary<int, XLCell> columnsCollection;
if (rowsCollection.TryGetValue(row, out columnsCollection))
{
if (columnsCollection.ContainsKey(column))
return row;
}
}
return 0;
}
public Int32 MaxRowInColumn(Int32 column)
{
for (int row = MaxRowUsed; row >= 1; row--)
{
Dictionary<int, XLCell> columnsCollection;
if (rowsCollection.TryGetValue(row, out columnsCollection))
{
if (columnsCollection.ContainsKey(column))
return row;
}
}
return 0;
}
public Int32 MinColumnInRow(Int32 row)
{
Dictionary<int, XLCell> columnsCollection;
if (rowsCollection.TryGetValue(row, out columnsCollection))
{
if (columnsCollection.Count > 0)
return columnsCollection.Keys.Min();
}
return 0;
}
public Int32 MaxColumnInRow(Int32 row)
{
Dictionary<int, XLCell> columnsCollection;
if (rowsCollection.TryGetValue(row, out columnsCollection))
{
if (columnsCollection.Count > 0)
return columnsCollection.Keys.Max();
}
return 0;
}
public IEnumerable<XLCell> GetCellsInColumn(Int32 column)
{
return GetCells(1, column, MaxRowUsed, column);
}
public IEnumerable<XLCell> GetCellsInRow(Int32 row)
{
return GetCells(row, 1, row, MaxColumnUsed);
}
}
}
| |
// 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.
// Summary:
// Implements the exhaustive task cancel and wait scenarios.
using Xunit;
using System;
using System.Collections.Generic;
using System.Diagnostics; // for StopWatch
using System.Threading;
using System.Threading.Tasks;
using System.Linq;
namespace System.Threading.Tasks.Tests.CancelWait
{
/// <summary>
/// Test class
/// </summary>
public sealed class TaskCancelWaitTest
{
#region Private Fields
private API _api; // the API_CancelWait to be tested
private WaitBy _waitBy; // the format of Wait
private int _waitTimeout; // the timeout in ms to be waited
private TaskInfo _taskTree; // the _taskTree to track child task cancellation option
private static readonly int s_deltaTimeOut = 10;
private bool _taskCompleted; // result to record the Wait(timeout) return value
private AggregateException _caughtException; // exception thrown during wait
private CountdownEvent _countdownEvent; // event to signal the main thread that the whole task tree has been created
#endregion
/// <summary>
/// .ctor
/// </summary>
public TaskCancelWaitTest(TestParameters parameters)
{
_api = parameters.API_CancelWait;
_waitBy = parameters.WaitBy_CancelWait;
_waitTimeout = parameters.WaitTime;
_taskTree = parameters.RootNode;
_countdownEvent = new CountdownEvent(CaluateLeafNodes(_taskTree));
}
#region Helper Methods
/// <summary>
/// The method that performs the tests
/// Depending on the inputs different test code paths will be exercised
/// </summary>
internal void RealRun()
{
TaskScheduler tm = TaskScheduler.Default;
CreateTask(tm, _taskTree);
// wait the whole task tree to be created
_countdownEvent.Wait();
Stopwatch sw = Stopwatch.StartNew();
try
{
switch (_api)
{
case API.Cancel:
_taskTree.CancellationTokenSource.Cancel();
break;
case API.Wait:
switch (_waitBy)
{
case WaitBy.None:
_taskTree.Task.Wait();
_taskCompleted = true;
break;
case WaitBy.Millisecond:
_taskCompleted = _taskTree.Task.Wait(_waitTimeout);
break;
case WaitBy.TimeSpan:
_taskCompleted = _taskTree.Task.Wait(new TimeSpan(0, 0, 0, 0, _waitTimeout));
break;
}
break;
}
}
catch (AggregateException exp)
{
_caughtException = exp.Flatten();
}
finally
{
sw.Stop();
}
if (_waitTimeout != -1)
{
long delta = sw.ElapsedMilliseconds - ((long)_waitTimeout + s_deltaTimeOut);
if (delta > 0)
{
Debug.WriteLine("ElapsedMilliseconds way more than requested Timeout.");
Debug.WriteLine("WaitTime= {0} ms, ElapsedTime= {1} ms, Allowed Descrepancy = {2} ms", _waitTimeout, sw.ElapsedMilliseconds, s_deltaTimeOut);
Debug.WriteLine("Delta= {0} ms", delta);
}
else
{
var delaytask = Task.Delay((int)Math.Abs(delta)); // give delay to allow Context being collected before verification
delaytask.Wait();
}
}
Verify();
_countdownEvent.Dispose();
}
/// <summary>
/// recursively walk the tree and attach the tasks to the nodes
/// </summary>
private void CreateTask(TaskScheduler tm, TaskInfo treeNode)
{
treeNode.Task = Task.Factory.StartNew(
delegate (object o)
{
TaskInfo current = (TaskInfo)o;
if (current.IsLeaf)
{
if (!_countdownEvent.IsSet)
_countdownEvent.Signal();
}
else
{
// create children tasks
foreach (TaskInfo child in current.Children)
{
if (child.IsRespectParentCancellation)
{
//
// if child to respect parent cancellation we need to wire a linked token
//
child.CancellationToken =
CancellationTokenSource.CreateLinkedTokenSource(treeNode.CancellationToken, child.CancellationToken).Token;
}
CreateTask(tm, child);
}
}
if (current.CancelChildren)
{
try
{
foreach (TaskInfo child in current.Children)
{
child.CancellationTokenSource.Cancel();
}
}
finally
{
// stop the tree creation and let the main thread proceed
if (!_countdownEvent.IsSet)
{
_countdownEvent.Signal(_countdownEvent.CurrentCount);
}
}
}
// run the workload
current.RunWorkload();
}, treeNode, treeNode.CancellationToken, treeNode.Option, tm);
}
/// <summary>
/// Walk the tree and calculates the tree nodes count
/// </summary>
/// <param name="tree"></param>
private int CaluateLeafNodes(TaskInfo tree)
{
if (tree.IsLeaf)
return 1;
int sum = 0;
foreach (TaskInfo child in tree.Children)
sum += CaluateLeafNodes(child);
return sum;
}
/// <summary>
/// Verification method
/// </summary>
private void Verify()
{
switch (_api)
{
//root task had the token source cancelled
case API.Cancel:
_taskTree.Traversal(current =>
{
if (current.Task == null)
return;
VerifyCancel(current);
VerifyResult(current);
});
break;
//root task was calling wait
case API.Wait:
//will be true if the root cancelled itself - through its workload
if (_taskTree.CancellationToken.IsCancellationRequested)
{
_taskTree.Traversal(current =>
{
if (current.Task == null)
return;
VerifyTaskCanceledException(current);
});
}
else
{
_taskTree.Traversal(current =>
{
if (current.Task == null)
return;
VerifyWait(current);
VerifyResult(current);
});
}
break;
default:
throw new ArgumentOutOfRangeException(string.Format("unknown API_CancelWait of", _api));
}
}
/// <summary>
/// Cancel Verification
/// </summary>
private void VerifyCancel(TaskInfo current)
{
TaskInfo ti = current;
if (current.Parent == null)
{
if (!ti.CancellationToken.IsCancellationRequested)
Assert.True(false, string.Format("Root task must be cancel-requested"));
else if (_countdownEvent.IsSet && ti.Task.IsCanceled)
Assert.True(false, string.Format("Root task should not be cancelled when the whole tree has been created"));
}
else if (current.Parent.CancelChildren)
{
// need to make sure the parent task at least called .Cancel() on the child
if (!ti.CancellationToken.IsCancellationRequested)
Assert.True(false, string.Format("Task which has been explictly cancel-requested either by parent must have CancellationRequested set as true"));
}
else if (ti.IsRespectParentCancellation)
{
if (ti.CancellationToken.IsCancellationRequested != current.Parent.CancellationToken.IsCancellationRequested)
Assert.True(false, string.Format("Task with RespectParentCancellationcontract is broken"));
}
else
{
if (ti.CancellationToken.IsCancellationRequested || ti.Task.IsCanceled)
Assert.True(false, string.Format("Inner non-directly canceled task which opts out RespectParentCancellationshould not be cancelled"));
}
// verify IsCanceled indicate successfully dequeued based on the observing that
// - Thread is recorded the first thing in the RunWorkload from user delegate
//if (ti.Task.IsCompleted && (ti.Thread == null) != ti.Task.IsCanceled)
// Assert.Fail("IsCanceled contract is broken -- completed task which has the delegate executed can't have IsCanceled return true")
}
/// <summary>
/// Verify the Wait code path
/// </summary>
private void VerifyWait(TaskInfo current)
{
TaskInfo ti = current;
TaskInfo parent = current.Parent;
if (_taskCompleted)
{
if (parent == null)
{
Assert.True(ti.Task.IsCompleted, "Root task must complete");
}
else if (parent != null && parent.Task.IsCompleted)
{
if ((ti.Option & TaskCreationOptions.AttachedToParent) != 0
&& !ti.Task.IsCompleted)
{
Assert.True(false, string.Format("Inner attached task must complete"));
}
}
}
}
private void VerifyTaskCanceledException(TaskInfo current)
{
bool expCaught;
TaskInfo ti = current;
//a task will get into cancelled state only if:
//1.Its token was cancelled before as its action to get invoked
//2.The token was cancelled before the task's action to finish, task observed the cancelled token and threw OCE(token)
if (ti.Task.Status == TaskStatus.Canceled)
{
expCaught = FindException((ex) =>
{
TaskCanceledException expectedExp = ex as TaskCanceledException;
return expectedExp != null && expectedExp.Task == ti.Task;
});
Assert.True(expCaught, "expected TaskCanceledException in Task.Name = Task " + current.Name + " NOT caught");
}
else
{
expCaught = FindException((ex) =>
{
TaskCanceledException expectedExp = ex as TaskCanceledException;
return expectedExp != null && expectedExp.Task == ti.Task;
});
Assert.False(expCaught, "NON-expected TaskCanceledException in Task.Name = Task " + current.Name + " caught");
}
}
private void VerifyResult(TaskInfo current)
{
TaskInfo ti = current;
WorkloadType workType = ti.WorkType;
if (workType == WorkloadType.Exceptional && _api != API.Cancel)
{
bool expCaught = FindException((ex) =>
{
TPLTestException expectedExp = ex as TPLTestException;
return expectedExp != null && expectedExp.FromTaskId == ti.Task.Id;
});
if (!expCaught)
Assert.True(false, string.Format("expected TPLTestException in Task.Name = Task{0} NOT caught", current.Name));
}
else
{
if (ti.Task.Exception != null && _api == API.Wait)
Assert.True(false, string.Format("UNEXPECTED exception in Task.Name = Task{0} caught. Exception: {1}", current.Name, ti.Task.Exception));
if (ti.Task.IsCanceled && ti.Result != -42)
{
//this means that the task was not scheduled - it was cancelled or it is still in the queue
//-42 = UNINITIALED_RESULT
Assert.True(false, string.Format("Result must remain uninitialized for unstarted task"));
}
else if (ti.Task.IsCompleted)
{
//Function point comparison cant be done by rounding off to nearest decimal points since
//1.64 could be represented as 1.63999999 or as 1.6499999999. To perform floating point comparisons,
//a range has to be defined and check to ensure that the result obtained is within the specified range
double minLimit = 1.63;
double maxLimit = 1.65;
if (ti.Result < minLimit || ti.Result > maxLimit)
Assert.True(ti.Task.IsCanceled || ti.Task.IsFaulted,
string.Format(
"Expected Result to lie between {0} and {1} for completed task. Actual Result {2}. Using n={3} IsCanceled={4}",
minLimit,
maxLimit,
ti.Result,
workType,
ti.Task.IsCanceled));
}
}
}
/// <summary>
/// Verify the _caughtException against a custom predicate
/// </summary>
private bool FindException(Predicate<Exception> exceptionPred)
{
if (_caughtException == null)
return false; // not caught any exceptions
foreach (Exception ex in _caughtException.InnerExceptions)
{
if (exceptionPred(ex))
return true;
}
return false;
}
#endregion
}
#region Helper Classes / Enums
public class TestParameters
{
public readonly int WaitTime;
public readonly WaitBy WaitBy_CancelWait;
public readonly TaskInfo RootNode;
public readonly API API_CancelWait;
public TestParameters(TaskInfo rootNode, API api_CancelWait, WaitBy waitBy_CancelWait, int waitTime)
{
WaitBy_CancelWait = waitBy_CancelWait;
WaitTime = waitTime;
RootNode = rootNode;
API_CancelWait = api_CancelWait;
}
}
/// <summary>
/// The Tree node Data type
///
/// While the tree is not restricted to this data type
/// the implemented tests are using the TaskInfo_CancelWait data type for their scenarios
/// </summary>
public class TaskInfo
{
private static TaskCreationOptions s_DEFAULT_OPTION = TaskCreationOptions.AttachedToParent;
private static double s_UNINITIALED_RESULT = -42;
public TaskInfo(TaskInfo parent, string TaskInfo_CancelWaitName, WorkloadType workType, string optionsString)
{
Children = new LinkedList<TaskInfo>();
Result = s_UNINITIALED_RESULT;
Option = s_DEFAULT_OPTION;
Name = TaskInfo_CancelWaitName;
WorkType = workType;
Parent = parent;
CancelChildren = false;
CancellationTokenSource = new CancellationTokenSource();
CancellationToken = CancellationTokenSource.Token;
if (string.IsNullOrEmpty(optionsString))
return;
//
// Parse Task CreationOptions, if RespectParentCancellation we would want to acknowledge that
// and passed the remaining options for creation
//
string[] options = optionsString.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
int index = -1;
for (int i = 0; i < options.Length; i++)
{
string o = options[i].Trim(); // remove any white spaces.
options[i] = o;
if (o.Equals("RespectParentCancellation", StringComparison.OrdinalIgnoreCase))
{
IsRespectParentCancellation = true;
index = i;
}
}
if (index != -1)
{
string[] temp = new string[options.Length - 1];
int excludeIndex = index + 1;
Array.Copy(options, 0, temp, 0, index);
int leftToCopy = options.Length - excludeIndex;
Array.Copy(options, excludeIndex, temp, index, leftToCopy);
options = temp;
}
if (options.Length > 0)
{
TaskCreationOptions parsedOptions;
string joinedOptions = string.Join(",", options);
bool parsed = Enum.TryParse<TaskCreationOptions>(joinedOptions, out parsedOptions);
if (!parsed)
throw new NotSupportedException("could not parse the options string: " + joinedOptions);
Option = parsedOptions;
}
}
public TaskInfo(TaskInfo parent, string TaskInfo_CancelWaitName, WorkloadType workType, string optionsString, bool cancelChildren)
: this(parent, TaskInfo_CancelWaitName, workType, optionsString)
{
CancelChildren = cancelChildren;
}
#region Properties
/// <summary>
/// The task associated with the current node
/// </summary>
public Task Task { get; set; }
/// <summary>
/// LinkedList representing the children of the current node
/// </summary>
public LinkedList<TaskInfo> Children { get; set; }
/// <summary>
/// Bool flag indicating is the current node is a leaf
/// </summary>
public bool IsLeaf
{
get { return Children.Count == 0; }
}
/// <summary>
/// Current node Parent
/// </summary>
public TaskInfo Parent { get; set; }
/// <summary>
/// Current node Name
/// </summary>
public string Name { get; set; }
/// <summary>
/// TaskCreation option of task associated with the current node
/// </summary>
public TaskCreationOptions Option { get; private set; }
/// <summary>
/// WorkloadType_CancelWait of task associated with the current node
/// </summary>
public WorkloadType WorkType { get; private set; }
/// <summary>
/// bool for indicating if the current tasks should initiate its children cancellation
/// </summary>
public bool CancelChildren { get; private set; }
/// <summary>
/// While a tasks is correct execute a result is produced
/// this is the result
/// </summary>
public double Result { get; private set; }
/// <summary>
/// The token associated with the current node's task
/// </summary>
public CancellationToken CancellationToken { get; set; }
/// <summary>
/// Every node has a cancellation source - its token participate in the task creation
/// </summary>
public CancellationTokenSource CancellationTokenSource { get; set; }
/// <summary>
/// bool indicating if the children respect parent cancellation
/// If true - the children cancellation token will be linkewd with the parent cancellation
/// so is the parent will get cancelled the children will get as well
/// </summary>
public bool IsRespectParentCancellation { get; private set; }
#endregion
#region Helper Methods
/// <summary>
/// Recursively traverse the tree and compare the current node usign the predicate
/// </summary>
/// <param name="predicate">the predicate</param>
/// <param name="report"></param>
/// <returns></returns>
public void Traversal(Action<TaskInfo> predicate)
{
// check current data. If it fails check, an exception is thrown and it stops checking.
// check children
foreach (TaskInfo child in Children)
{
predicate(child);
child.Traversal(predicate);
}
}
/// <summary>
/// The Task workload execution
/// </summary>
public void RunWorkload()
{
//Thread = Thread.CurrentThread;
if (WorkType == WorkloadType.Exceptional)
{
ThrowException();
}
else if (WorkType == WorkloadType.Cancelled)
{
CancelSelf(this.CancellationTokenSource, this.CancellationToken);
}
else
{
// run the workload
if (Result == s_UNINITIALED_RESULT)
{
Result = ZetaSequence((int)WorkType);
}
else // task re-entry, mark it failed
{
Result = s_UNINITIALED_RESULT;
}
}
}
public static double ZetaSequence(int n)
{
double result = 0;
for (int i = 1; i < n; i++)
{
result += 1.0 / ((double)i * (double)i);
}
return result;
}
/// <summary>
/// Cancel self workload. The CancellationToken has been wired such that the source passed to this method
/// is a source that can actually causes the Task CancellationToken to be canceled. The source could be the
/// Token's original source, or one of the sources in case of Linked Tokens
/// </summary>
/// <param name="cts"></param>
public static void CancelSelf(CancellationTokenSource cts, CancellationToken ct)
{
cts.Cancel();
throw new OperationCanceledException(ct);
}
public static void ThrowException()
{
throw new TPLTestException();
}
internal void AddChildren(TaskInfo[] children)
{
foreach (var child in children)
Children.AddLast(child);
}
#endregion
}
public enum API
{
Cancel,
Wait,
}
/// <summary>
/// Waiting type
/// </summary>
public enum WaitBy
{
None,
TimeSpan,
Millisecond,
}
/// <summary>
/// Every task has an workload associated
/// These are the workload types used in the task tree
/// The workload is not common for the whole tree - Every node can have its own workload
/// </summary>
public enum WorkloadType
{
Exceptional = -2,
Cancelled = -1,
VeryLight = 100, // the number is the N input to the ZetaSequence workload
Light = 200,
Medium = 400,
Heavy = 800,
VeryHeavy = 1600,
}
#endregion
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Xunit;
namespace Microsoft.AspNetCore.Identity.Test
{
public class IdentityBuilderTest
{
[Fact]
public void AddRolesServicesAdded()
{
var services = new ServiceCollection();
services.AddIdentityCore<PocoUser>(o => { })
.AddRoles<PocoRole>()
.AddUserStore<NoopUserStore>()
.AddRoleStore<NoopRoleStore>();
var sp = services.BuildServiceProvider();
Assert.NotNull(sp.GetRequiredService<IRoleValidator<PocoRole>>());
Assert.IsType<NoopRoleStore>(sp.GetRequiredService<IRoleStore<PocoRole>>());
Assert.IsType<RoleManager<PocoRole>>(sp.GetRequiredService<RoleManager<PocoRole>>());
Assert.NotNull(sp.GetRequiredService<RoleManager<PocoRole>>());
Assert.IsType<UserClaimsPrincipalFactory<PocoUser, PocoRole>>(sp.GetRequiredService<IUserClaimsPrincipalFactory<PocoUser>>());
}
[Fact]
public void AddRolesWithoutStoreWillError()
{
var services = new ServiceCollection();
services.AddIdentityCore<PocoUser>(o => { })
.AddRoles<PocoRole>();
var sp = services.BuildServiceProvider();
Assert.NotNull(sp.GetRequiredService<IRoleValidator<PocoRole>>());
Assert.Null(sp.GetService<IRoleStore<PocoRole>>());
Assert.Throws<InvalidOperationException>(() => sp.GetService<RoleManager<PocoRole>>());
}
[Fact]
public void CanOverrideUserStore()
{
var services = new ServiceCollection()
.AddSingleton<IConfiguration>(new ConfigurationBuilder().Build());
services.AddIdentity<PocoUser,PocoRole>().AddUserStore<MyUberThingy>();
var thingy = services.BuildServiceProvider().GetRequiredService<IUserStore<PocoUser>>() as MyUberThingy;
Assert.NotNull(thingy);
}
[Fact]
public void CanOverrideRoleStore()
{
var services = new ServiceCollection()
.AddSingleton<IConfiguration>(new ConfigurationBuilder().Build());
services.AddIdentity<PocoUser,PocoRole>().AddRoleStore<MyUberThingy>();
var thingy = services.BuildServiceProvider().GetRequiredService<IRoleStore<PocoRole>>() as MyUberThingy;
Assert.NotNull(thingy);
}
[Fact]
public void CanOverridePrincipalFactory()
{
var services = new ServiceCollection()
.AddLogging()
.AddSingleton<IConfiguration>(new ConfigurationBuilder().Build());
services.AddIdentity<PocoUser, PocoRole>()
.AddClaimsPrincipalFactory<MyClaimsPrincipalFactory>()
.AddUserManager<MyUserManager>()
.AddUserStore<NoopUserStore>()
.AddRoleStore<NoopRoleStore>();
var thingy = services.BuildServiceProvider().GetRequiredService<IUserClaimsPrincipalFactory<PocoUser>>() as MyClaimsPrincipalFactory;
Assert.NotNull(thingy);
}
[Fact]
public void CanOverrideUserConfirmation()
{
var services = new ServiceCollection()
.AddLogging()
.AddSingleton<IConfiguration>(new ConfigurationBuilder().Build());
services.AddIdentity<PocoUser, PocoRole>()
.AddClaimsPrincipalFactory<MyClaimsPrincipalFactory>()
.AddUserConfirmation<MyUserConfirmation>()
.AddUserManager<MyUserManager>()
.AddUserStore<NoopUserStore>()
.AddRoleStore<NoopRoleStore>();
var thingy = services.BuildServiceProvider().GetRequiredService<IUserConfirmation<PocoUser>>() as MyUserConfirmation;
Assert.NotNull(thingy);
}
[Fact]
public void CanOverrideRoleValidator()
{
var services = new ServiceCollection()
.AddSingleton<IConfiguration>(new ConfigurationBuilder().Build());
services.AddIdentity<PocoUser,PocoRole>().AddRoleValidator<MyUberThingy>();
var thingy = services.BuildServiceProvider().GetRequiredService<IRoleValidator<PocoRole>>() as MyUberThingy;
Assert.NotNull(thingy);
}
[Fact]
public void CanOverrideUserValidator()
{
var services = new ServiceCollection()
.AddSingleton<IConfiguration>(new ConfigurationBuilder().Build());
services.AddIdentity<PocoUser,PocoRole>().AddUserValidator<MyUberThingy>();
var thingy = services.BuildServiceProvider().GetRequiredService<IUserValidator<PocoUser>>() as MyUberThingy;
Assert.NotNull(thingy);
}
[Fact]
public void CanOverridePasswordValidator()
{
var services = new ServiceCollection()
.AddSingleton<IConfiguration>(new ConfigurationBuilder().Build());
services.AddIdentity<PocoUser,PocoRole>().AddPasswordValidator<MyUberThingy>();
var thingy = services.BuildServiceProvider().GetRequiredService<IPasswordValidator<PocoUser>>() as MyUberThingy;
Assert.NotNull(thingy);
}
[Fact]
public void CanOverrideUserManager()
{
var services = new ServiceCollection()
.AddSingleton<IConfiguration>(new ConfigurationBuilder().Build());
services.AddIdentity<PocoUser, PocoRole>()
.AddUserStore<NoopUserStore>()
.AddUserManager<MyUserManager>();
var myUserManager = services.BuildServiceProvider().GetRequiredService(typeof(UserManager<PocoUser>)) as MyUserManager;
Assert.NotNull(myUserManager);
}
[Fact]
public void CanOverrideRoleManager()
{
var services = new ServiceCollection()
.AddSingleton<IConfiguration>(new ConfigurationBuilder().Build());
services.AddIdentity<PocoUser, PocoRole>()
.AddRoleStore<NoopRoleStore>()
.AddRoleManager<MyRoleManager>();
var myRoleManager = services.BuildServiceProvider().GetRequiredService<RoleManager<PocoRole>>() as MyRoleManager;
Assert.NotNull(myRoleManager);
}
[Fact]
public void CanOverrideSignInManager()
{
var services = new ServiceCollection()
.AddSingleton<IConfiguration>(new ConfigurationBuilder().Build())
.AddHttpContextAccessor()
.AddLogging();
services.AddIdentity<PocoUser, PocoRole>()
.AddUserStore<NoopUserStore>()
.AddRoleStore<NoopRoleStore>()
.AddUserManager<MyUserManager>()
.AddClaimsPrincipalFactory<MyClaimsPrincipalFactory>()
.AddSignInManager<MySignInManager>();
var myUserManager = services.BuildServiceProvider().GetRequiredService(typeof(SignInManager<PocoUser>)) as MySignInManager;
Assert.NotNull(myUserManager);
}
[Fact]
public void EnsureDefaultServices()
{
var services = new ServiceCollection()
.AddSingleton<IConfiguration>(new ConfigurationBuilder().Build());
services.AddLogging()
.AddIdentity<PocoUser,PocoRole>()
.AddUserStore<NoopUserStore>()
.AddRoleStore<NoopRoleStore>();
var provider = services.BuildServiceProvider();
var userValidator = provider.GetRequiredService<IUserValidator<PocoUser>>() as UserValidator<PocoUser>;
Assert.NotNull(userValidator);
var pwdValidator = provider.GetRequiredService<IPasswordValidator<PocoUser>>() as PasswordValidator<PocoUser>;
Assert.NotNull(pwdValidator);
var hasher = provider.GetRequiredService<IPasswordHasher<PocoUser>>() as PasswordHasher<PocoUser>;
Assert.NotNull(hasher);
Assert.IsType<RoleManager<PocoRole>>(provider.GetRequiredService<RoleManager<PocoRole>>());
Assert.IsType<UserManager<PocoUser>>(provider.GetRequiredService<UserManager<PocoUser>>());
}
[Fact]
public void EnsureDefaultTokenProviders()
{
var services = new ServiceCollection()
.AddSingleton<IConfiguration>(new ConfigurationBuilder().Build());
services.AddIdentity<PocoUser,PocoRole>().AddDefaultTokenProviders();
var provider = services.BuildServiceProvider();
var tokenProviders = provider.GetRequiredService<IOptions<IdentityOptions>>().Value.Tokens.ProviderMap.Values;
Assert.Equal(4, tokenProviders.Count());
}
[Fact]
public void AddManagerWithWrongTypesThrows()
{
var services = new ServiceCollection()
.AddSingleton<IConfiguration>(new ConfigurationBuilder().Build());
var builder = services.AddIdentity<PocoUser, PocoRole>();
Assert.Throws<InvalidOperationException>(() => builder.AddUserManager<object>());
Assert.Throws<InvalidOperationException>(() => builder.AddRoleManager<object>());
Assert.Throws<InvalidOperationException>(() => builder.AddSignInManager<object>());
}
[Fact]
public void AddTokenProviderWithWrongTypesThrows()
{
var services = new ServiceCollection()
.AddSingleton<IConfiguration>(new ConfigurationBuilder().Build());
var builder = services.AddIdentity<PocoUser, PocoRole>();
Assert.Throws<InvalidOperationException>(() => builder.AddTokenProvider<object>("whatevs"));
Assert.Throws<InvalidOperationException>(() => builder.AddTokenProvider("whatevs", typeof(object)));
}
private class MyUberThingy : IUserValidator<PocoUser>, IPasswordValidator<PocoUser>, IRoleValidator<PocoRole>, IUserStore<PocoUser>, IRoleStore<PocoRole>
{
public Task<IdentityResult> CreateAsync(PocoRole role, CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotImplementedException();
}
public Task<IdentityResult> CreateAsync(PocoUser user, CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotImplementedException();
}
public Task<IdentityResult> DeleteAsync(PocoRole role, CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotImplementedException();
}
public Task<IdentityResult> DeleteAsync(PocoUser user, CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotImplementedException();
}
public void Dispose()
{
throw new NotImplementedException();
}
public Task<PocoUser> FindByIdAsync(string userId, CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotImplementedException();
}
public Task<PocoUser> FindByNameAsync(string normalizedUserName, CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotImplementedException();
}
public Task<string> GetNormalizedRoleNameAsync(PocoRole role, CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotImplementedException();
}
public Task<string> GetNormalizedUserNameAsync(PocoUser user, CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotImplementedException();
}
public Task<string> GetRoleIdAsync(PocoRole role, CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotImplementedException();
}
public Task<string> GetRoleNameAsync(PocoRole role, CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotImplementedException();
}
public Task<string> GetUserIdAsync(PocoUser user, CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotImplementedException();
}
public Task<string> GetUserNameAsync(PocoUser user, CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotImplementedException();
}
public Task SetNormalizedRoleNameAsync(PocoRole role, string normalizedName, CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotImplementedException();
}
public Task SetNormalizedUserNameAsync(PocoUser user, string normalizedName, CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotImplementedException();
}
public Task SetRoleNameAsync(PocoRole role, string roleName, CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotImplementedException();
}
public Task SetUserNameAsync(PocoUser user, string userName, CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotImplementedException();
}
public Task<IdentityResult> UpdateAsync(PocoRole role, CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotImplementedException();
}
public Task<IdentityResult> UpdateAsync(PocoUser user, CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotImplementedException();
}
public Task<IdentityResult> ValidateAsync(RoleManager<PocoRole> manager, PocoRole role)
{
throw new NotImplementedException();
}
public Task<IdentityResult> ValidateAsync(UserManager<PocoUser> manager, PocoUser user)
{
throw new NotImplementedException();
}
public Task<IdentityResult> ValidateAsync(UserManager<PocoUser> manager, PocoUser user, string password)
{
throw new NotImplementedException();
}
Task<PocoRole> IRoleStore<PocoRole>.FindByIdAsync(string roleId, CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
Task<PocoRole> IRoleStore<PocoRole>.FindByNameAsync(string roleName, CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
}
private class MySignInManager : SignInManager<PocoUser>
{
public MySignInManager(UserManager<PocoUser> manager, IHttpContextAccessor context, IUserClaimsPrincipalFactory<PocoUser> claimsFactory) : base(manager, context, claimsFactory, null, null, null, null) { }
}
private class MyUserManager : UserManager<PocoUser>
{
public MyUserManager(IUserStore<PocoUser> store) : base(store, null, null, null, null, null, null, null, null) { }
}
private class MyClaimsPrincipalFactory : UserClaimsPrincipalFactory<PocoUser, PocoRole>
{
public MyClaimsPrincipalFactory(UserManager<PocoUser> userManager, RoleManager<PocoRole> roleManager, IOptions<IdentityOptions> optionsAccessor) : base(userManager, roleManager, optionsAccessor)
{
}
}
private class MyRoleManager : RoleManager<PocoRole>
{
public MyRoleManager(IRoleStore<PocoRole> store,
IEnumerable<IRoleValidator<PocoRole>> roleValidators) : base(store, null, null, null, null)
{
}
}
private class MyUserConfirmation : DefaultUserConfirmation<PocoUser>
{
}
}
}
| |
// 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.Diagnostics;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using Microsoft.Win32.SafeHandles;
namespace Internal.Cryptography.Pal
{
internal class OpenSslX509Encoder : IX509Pal
{
public AsymmetricAlgorithm DecodePublicKey(Oid oid, byte[] encodedKeyValue, byte[] encodedParameters, ICertificatePal certificatePal)
{
switch (oid.Value)
{
case Oids.RsaRsa:
return BuildRsaPublicKey(encodedKeyValue);
}
// NotSupportedException is what desktop and CoreFx-Windows throw in this situation.
throw new NotSupportedException(SR.NotSupported_KeyAlgorithm);
}
public string X500DistinguishedNameDecode(byte[] encodedDistinguishedName, X500DistinguishedNameFlags flags)
{
OpenSslX09NameFormatFlags nativeFlags = ConvertFormatFlags(flags);
return X500DistinguishedNameDecode(encodedDistinguishedName, nativeFlags);
}
internal static unsafe string X500DistinguishedNameDecode(byte[] encodedDistinguishedName, OpenSslX09NameFormatFlags nativeFlags)
{
using (SafeX509NameHandle x509Name = Interop.libcrypto.OpenSslD2I(Interop.libcrypto.d2i_X509_NAME, encodedDistinguishedName))
{
Interop.libcrypto.CheckValidOpenSslHandle(x509Name);
using (SafeBioHandle bioHandle = Interop.libcrypto.BIO_new(Interop.libcrypto.BIO_s_mem()))
{
Interop.libcrypto.CheckValidOpenSslHandle(bioHandle);
int written = Interop.libcrypto.X509_NAME_print_ex(
bioHandle,
x509Name,
0,
new UIntPtr((uint)nativeFlags));
// X509_NAME_print_ex returns how many bytes were written into the buffer.
// BIO_gets wants to ensure that the response is NULL-terminated.
// So add one to leave space for the NULL.
StringBuilder builder = new StringBuilder(written + 1);
int read = Interop.libcrypto.BIO_gets(bioHandle, builder, builder.Capacity);
if (read < 0)
{
throw Interop.libcrypto.CreateOpenSslCryptographicException();
}
return builder.ToString();
}
}
}
public byte[] X500DistinguishedNameEncode(string distinguishedName, X500DistinguishedNameFlags flag)
{
throw new NotImplementedException();
}
public string X500DistinguishedNameFormat(byte[] encodedDistinguishedName, bool multiLine)
{
throw new NotImplementedException();
}
public X509ContentType GetCertContentType(byte[] rawData)
{
throw new NotImplementedException();
}
public X509ContentType GetCertContentType(string fileName)
{
throw new NotImplementedException();
}
public byte[] EncodeX509KeyUsageExtension(X509KeyUsageFlags keyUsages)
{
throw new NotImplementedException();
}
public unsafe void DecodeX509KeyUsageExtension(byte[] encoded, out X509KeyUsageFlags keyUsages)
{
using (SafeAsn1BitStringHandle bitString = Interop.libcrypto.OpenSslD2I(Interop.libcrypto.d2i_ASN1_BIT_STRING, encoded))
{
Interop.libcrypto.CheckValidOpenSslHandle(bitString);
byte[] decoded = Interop.Crypto.GetAsn1StringBytes(bitString.DangerousGetHandle());
// Only 9 bits are defined.
if (decoded.Length > 2)
{
throw new CryptographicException();
}
// DER encodings of BIT_STRING values number the bits as
// 01234567 89 (big endian), plus a number saying how many bits of the last byte were padding.
//
// So digitalSignature (0) doesn't mean 2^0 (0x01), it means the most significant bit
// is set in this byte stream.
//
// BIT_STRING values are compact. So a value of cRLSign (6) | keyEncipherment (2), which
// is 0b0010001 => 0b0010 0010 (1 bit padding) => 0x22 encoded is therefore
// 0x02 (length remaining) 0x01 (1 bit padding) 0x22.
//
// OpenSSL's d2i_ASN1_BIT_STRING is going to take that, and return 0x22. 0x22 lines up
// exactly with X509KeyUsageFlags.CrlSign (0x20) | X509KeyUsageFlags.KeyEncipherment (0x02)
//
// Once the decipherOnly (8) bit is added to the mix, the values become:
// 0b001000101 => 0b0010 0010 1000 0000 (7 bits padding)
// { 0x03 0x07 0x22 0x80 }
// And OpenSSL returns new byte[] { 0x22 0x80 }
//
// The value of X509KeyUsageFlags.DecipherOnly is 0x8000. 0x8000 in a little endian
// representation is { 0x00 0x80 }. This means that the DER storage mechanism has effectively
// ended up being little-endian for BIT_STRING values. Untwist the bytes, and now the bits all
// line up with the existing X509KeyUsageFlags.
int value = 0;
if (decoded.Length > 0)
{
value = decoded[0];
}
if (decoded.Length > 1)
{
value |= decoded[1] << 8;
}
keyUsages = (X509KeyUsageFlags)value;
}
}
public byte[] EncodeX509BasicConstraints2Extension(
bool certificateAuthority,
bool hasPathLengthConstraint,
int pathLengthConstraint)
{
throw new NotImplementedException();
}
public void DecodeX509BasicConstraintsExtension(
byte[] encoded,
out bool certificateAuthority,
out bool hasPathLengthConstraint,
out int pathLengthConstraint)
{
throw new NotImplementedException();
}
public unsafe void DecodeX509BasicConstraints2Extension(
byte[] encoded,
out bool certificateAuthority,
out bool hasPathLengthConstraint,
out int pathLengthConstraint)
{
using (SafeBasicConstraintsHandle constraints = Interop.libcrypto.OpenSslD2I(Interop.libcrypto.d2i_BASIC_CONSTRAINTS, encoded))
{
Interop.libcrypto.CheckValidOpenSslHandle(constraints);
Interop.libcrypto.BASIC_CONSTRAINTS* data = (Interop.libcrypto.BASIC_CONSTRAINTS*)constraints.DangerousGetHandle();
certificateAuthority = data->CA != 0;
if (data->pathlen != IntPtr.Zero)
{
hasPathLengthConstraint = true;
pathLengthConstraint = Interop.libcrypto.ASN1_INTEGER_get(data->pathlen).ToInt32();
}
else
{
hasPathLengthConstraint = false;
pathLengthConstraint = 0;
}
}
}
public byte[] EncodeX509EnhancedKeyUsageExtension(OidCollection usages)
{
throw new NotImplementedException();
}
public unsafe void DecodeX509EnhancedKeyUsageExtension(byte[] encoded, out OidCollection usages)
{
OidCollection oids = new OidCollection();
using (SafeEkuExtensionHandle eku = Interop.libcrypto.OpenSslD2I(Interop.libcrypto.d2i_EXTENDED_KEY_USAGE, encoded))
{
Interop.libcrypto.CheckValidOpenSslHandle(eku);
int count = Interop.Crypto.GetX509EkuFieldCount(eku);
for (int i = 0; i < count; i++)
{
IntPtr oidPtr = Interop.Crypto.GetX509EkuField(eku, i);
if (oidPtr == IntPtr.Zero)
{
throw Interop.libcrypto.CreateOpenSslCryptographicException();
}
string oidValue = Interop.libcrypto.OBJ_obj2txt_helper(oidPtr);
oids.Add(new Oid(oidValue));
}
}
usages = oids;
}
public byte[] EncodeX509SubjectKeyIdentifierExtension(byte[] subjectKeyIdentifier)
{
throw new NotImplementedException();
}
public void DecodeX509SubjectKeyIdentifierExtension(byte[] encoded, out byte[] subjectKeyIdentifier)
{
subjectKeyIdentifier = DecodeX509SubjectKeyIdentifierExtension(encoded);
}
internal static unsafe byte[] DecodeX509SubjectKeyIdentifierExtension(byte[] encoded)
{
using (SafeAsn1OctetStringHandle octetString = Interop.libcrypto.OpenSslD2I(Interop.libcrypto.d2i_ASN1_OCTET_STRING, encoded))
{
Interop.libcrypto.CheckValidOpenSslHandle(octetString);
return Interop.Crypto.GetAsn1StringBytes(octetString.DangerousGetHandle());
}
}
public byte[] ComputeCapiSha1OfPublicKey(PublicKey key)
{
throw new NotImplementedException();
}
private static OpenSslX09NameFormatFlags ConvertFormatFlags(X500DistinguishedNameFlags inFlags)
{
OpenSslX09NameFormatFlags outFlags = 0;
if (inFlags.HasFlag(X500DistinguishedNameFlags.Reversed))
{
outFlags |= OpenSslX09NameFormatFlags.XN_FLAG_DN_REV;
}
if (inFlags.HasFlag(X500DistinguishedNameFlags.UseSemicolons))
{
outFlags |= OpenSslX09NameFormatFlags.XN_FLAG_SEP_SPLUS_SPC;
}
else if (inFlags.HasFlag(X500DistinguishedNameFlags.UseNewLines))
{
outFlags |= OpenSslX09NameFormatFlags.XN_FLAG_SEP_MULTILINE;
}
else
{
outFlags |= OpenSslX09NameFormatFlags.XN_FLAG_SEP_CPLUS_SPC;
}
if (inFlags.HasFlag(X500DistinguishedNameFlags.DoNotUseQuotes))
{
// TODO: Handle this.
}
if (inFlags.HasFlag(X500DistinguishedNameFlags.ForceUTF8Encoding))
{
// TODO: Handle this.
}
if (inFlags.HasFlag(X500DistinguishedNameFlags.UseUTF8Encoding))
{
// TODO: Handle this.
}
else if (inFlags.HasFlag(X500DistinguishedNameFlags.UseT61Encoding))
{
// TODO: Handle this.
}
return outFlags;
}
private static unsafe RSA BuildRsaPublicKey(byte[] encodedData)
{
using (SafeRsaHandle rsaHandle = Interop.libcrypto.OpenSslD2I(Interop.libcrypto.d2i_RSAPublicKey, encodedData))
{
Interop.libcrypto.CheckValidOpenSslHandle(rsaHandle);
RSAParameters rsaParameters = Interop.libcrypto.ExportRsaParameters(rsaHandle, false);
RSA rsa = new RSAOpenSsl();
rsa.ImportParameters(rsaParameters);
return rsa;
}
}
[Flags]
internal enum OpenSslX09NameFormatFlags : uint
{
XN_FLAG_SEP_MASK = (0xf << 16),
// O=Apache HTTP Server, OU=Test Certificate, CN=localhost
// Note that this is the only not-reversed value, since XN_FLAG_COMPAT | XN_FLAG_DN_REV produces nothing.
XN_FLAG_COMPAT = 0,
// CN=localhost,OU=Test Certificate,O=Apache HTTP Server
XN_FLAG_SEP_COMMA_PLUS = (1 << 16),
// CN=localhost, OU=Test Certificate, O=Apache HTTP Server
XN_FLAG_SEP_CPLUS_SPC = (2 << 16),
// CN=localhost; OU=Test Certificate; O=Apache HTTP Server
XN_FLAG_SEP_SPLUS_SPC = (3 << 16),
// CN=localhost
// OU=Test Certificate
// O=Apache HTTP Server
XN_FLAG_SEP_MULTILINE = (4 << 16),
XN_FLAG_DN_REV = (1 << 20),
XN_FLAG_FN_MASK = (0x3 << 21),
// CN=localhost, OU=Test Certificate, O=Apache HTTP Server
XN_FLAG_FN_SN = 0,
// commonName=localhost, organizationalUnitName=Test Certificate, organizationName=Apache HTTP Server
XN_FLAG_FN_LN = (1 << 21),
// 2.5.4.3=localhost, 2.5.4.11=Test Certificate, 2.5.4.10=Apache HTTP Server
XN_FLAG_FN_OID = (2 << 21),
// localhost, Test Certificate, Apache HTTP Server
XN_FLAG_FN_NONE = (3 << 21),
// CN = localhost, OU = Test Certificate, O = Apache HTTP Server
XN_FLAG_SPC_EQ = (1 << 23),
XN_FLAG_DUMP_UNKNOWN_FIELDS = (1 << 24),
XN_FLAG_FN_ALIGN = (1 << 25),
}
}
}
| |
// 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.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Linq;
namespace System.Collections.Immutable
{
/// <summary>
/// A set of initialization methods for instances of <see cref="ImmutableDictionary{TKey, TValue}"/>.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
public static class ImmutableDictionary
{
/// <summary>
/// Returns an empty collection.
/// </summary>
/// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam>
/// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam>
/// <returns>The immutable collection.</returns>
[Pure]
public static ImmutableDictionary<TKey, TValue> Create<TKey, TValue>()
{
return ImmutableDictionary<TKey, TValue>.Empty;
}
/// <summary>
/// Returns an empty collection with the specified key comparer.
/// </summary>
/// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam>
/// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam>
/// <param name="keyComparer">The key comparer.</param>
/// <returns>
/// The immutable collection.
/// </returns>
[Pure]
public static ImmutableDictionary<TKey, TValue> Create<TKey, TValue>(IEqualityComparer<TKey> keyComparer)
{
return ImmutableDictionary<TKey, TValue>.Empty.WithComparers(keyComparer);
}
/// <summary>
/// Returns an empty collection with the specified comparers.
/// </summary>
/// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam>
/// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam>
/// <param name="keyComparer">The key comparer.</param>
/// <param name="valueComparer">The value comparer.</param>
/// <returns>
/// The immutable collection.
/// </returns>
[Pure]
public static ImmutableDictionary<TKey, TValue> Create<TKey, TValue>(IEqualityComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer)
{
return ImmutableDictionary<TKey, TValue>.Empty.WithComparers(keyComparer, valueComparer);
}
/// <summary>
/// Creates a new immutable collection prefilled with the specified items.
/// </summary>
/// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam>
/// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam>
/// <param name="items">The items to prepopulate.</param>
/// <returns>The new immutable collection.</returns>
[Pure]
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
public static ImmutableDictionary<TKey, TValue> CreateRange<TKey, TValue>(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
return ImmutableDictionary<TKey, TValue>.Empty.AddRange(items);
}
/// <summary>
/// Creates a new immutable collection prefilled with the specified items.
/// </summary>
/// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam>
/// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam>
/// <param name="keyComparer">The key comparer.</param>
/// <param name="items">The items to prepopulate.</param>
/// <returns>The new immutable collection.</returns>
[Pure]
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
public static ImmutableDictionary<TKey, TValue> CreateRange<TKey, TValue>(IEqualityComparer<TKey> keyComparer, IEnumerable<KeyValuePair<TKey, TValue>> items)
{
return ImmutableDictionary<TKey, TValue>.Empty.WithComparers(keyComparer).AddRange(items);
}
/// <summary>
/// Creates a new immutable collection prefilled with the specified items.
/// </summary>
/// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam>
/// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam>
/// <param name="keyComparer">The key comparer.</param>
/// <param name="valueComparer">The value comparer.</param>
/// <param name="items">The items to prepopulate.</param>
/// <returns>The new immutable collection.</returns>
[Pure]
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
public static ImmutableDictionary<TKey, TValue> CreateRange<TKey, TValue>(IEqualityComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer, IEnumerable<KeyValuePair<TKey, TValue>> items)
{
return ImmutableDictionary<TKey, TValue>.Empty.WithComparers(keyComparer, valueComparer).AddRange(items);
}
/// <summary>
/// Creates a new immutable dictionary builder.
/// </summary>
/// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam>
/// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam>
/// <returns>The new builder.</returns>
[Pure]
public static ImmutableDictionary<TKey, TValue>.Builder CreateBuilder<TKey, TValue>()
{
return Create<TKey, TValue>().ToBuilder();
}
/// <summary>
/// Creates a new immutable dictionary builder.
/// </summary>
/// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam>
/// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam>
/// <param name="keyComparer">The key comparer.</param>
/// <returns>The new builder.</returns>
[Pure]
public static ImmutableDictionary<TKey, TValue>.Builder CreateBuilder<TKey, TValue>(IEqualityComparer<TKey> keyComparer)
{
return Create<TKey, TValue>(keyComparer).ToBuilder();
}
/// <summary>
/// Creates a new immutable dictionary builder.
/// </summary>
/// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam>
/// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam>
/// <param name="keyComparer">The key comparer.</param>
/// <param name="valueComparer">The value comparer.</param>
/// <returns>The new builder.</returns>
[Pure]
public static ImmutableDictionary<TKey, TValue>.Builder CreateBuilder<TKey, TValue>(IEqualityComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer)
{
return Create<TKey, TValue>(keyComparer, valueComparer).ToBuilder();
}
/// <summary>
/// Constructs an immutable dictionary based on some transformation of a sequence.
/// </summary>
/// <typeparam name="TSource">The type of element in the sequence.</typeparam>
/// <typeparam name="TKey">The type of key in the resulting map.</typeparam>
/// <typeparam name="TValue">The type of value in the resulting map.</typeparam>
/// <param name="source">The sequence to enumerate to generate the map.</param>
/// <param name="keySelector">The function that will produce the key for the map from each sequence element.</param>
/// <param name="elementSelector">The function that will produce the value for the map from each sequence element.</param>
/// <param name="keyComparer">The key comparer to use for the map.</param>
/// <param name="valueComparer">The value comparer to use for the map.</param>
/// <returns>The immutable map.</returns>
[Pure]
public static ImmutableDictionary<TKey, TValue> ToImmutableDictionary<TSource, TKey, TValue>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TValue> elementSelector, IEqualityComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer)
{
Requires.NotNull(source, "source");
Requires.NotNull(keySelector, "keySelector");
Requires.NotNull(elementSelector, "elementSelector");
Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null);
return ImmutableDictionary<TKey, TValue>.Empty.WithComparers(keyComparer, valueComparer)
.AddRange(source.Select(element => new KeyValuePair<TKey, TValue>(keySelector(element), elementSelector(element))));
}
/// <summary>
/// Constructs an immutable dictionary based on some transformation of a sequence.
/// </summary>
/// <typeparam name="TSource">The type of element in the sequence.</typeparam>
/// <typeparam name="TKey">The type of key in the resulting map.</typeparam>
/// <typeparam name="TValue">The type of value in the resulting map.</typeparam>
/// <param name="source">The sequence to enumerate to generate the map.</param>
/// <param name="keySelector">The function that will produce the key for the map from each sequence element.</param>
/// <param name="elementSelector">The function that will produce the value for the map from each sequence element.</param>
/// <param name="keyComparer">The key comparer to use for the map.</param>
/// <returns>The immutable map.</returns>
[Pure]
public static ImmutableDictionary<TKey, TValue> ToImmutableDictionary<TSource, TKey, TValue>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TValue> elementSelector, IEqualityComparer<TKey> keyComparer)
{
return ToImmutableDictionary(source, keySelector, elementSelector, keyComparer, null);
}
/// <summary>
/// Constructs an immutable dictionary based on some transformation of a sequence.
/// </summary>
/// <typeparam name="TSource">The type of element in the sequence.</typeparam>
/// <typeparam name="TKey">The type of key in the resulting map.</typeparam>
/// <param name="source">The sequence to enumerate to generate the map.</param>
/// <param name="keySelector">The function that will produce the key for the map from each sequence element.</param>
/// <returns>The immutable map.</returns>
[Pure]
public static ImmutableDictionary<TKey, TSource> ToImmutableDictionary<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
return ToImmutableDictionary(source, keySelector, v => v, null, null);
}
/// <summary>
/// Constructs an immutable dictionary based on some transformation of a sequence.
/// </summary>
/// <typeparam name="TSource">The type of element in the sequence.</typeparam>
/// <typeparam name="TKey">The type of key in the resulting map.</typeparam>
/// <param name="source">The sequence to enumerate to generate the map.</param>
/// <param name="keySelector">The function that will produce the key for the map from each sequence element.</param>
/// <param name="keyComparer">The key comparer to use for the map.</param>
/// <returns>The immutable map.</returns>
[Pure]
public static ImmutableDictionary<TKey, TSource> ToImmutableDictionary<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> keyComparer)
{
return ToImmutableDictionary(source, keySelector, v => v, keyComparer, null);
}
/// <summary>
/// Constructs an immutable dictionary based on some transformation of a sequence.
/// </summary>
/// <typeparam name="TSource">The type of element in the sequence.</typeparam>
/// <typeparam name="TKey">The type of key in the resulting map.</typeparam>
/// <typeparam name="TValue">The type of value in the resulting map.</typeparam>
/// <param name="source">The sequence to enumerate to generate the map.</param>
/// <param name="keySelector">The function that will produce the key for the map from each sequence element.</param>
/// <param name="elementSelector">The function that will produce the value for the map from each sequence element.</param>
/// <returns>The immutable map.</returns>
[Pure]
public static ImmutableDictionary<TKey, TValue> ToImmutableDictionary<TSource, TKey, TValue>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TValue> elementSelector)
{
return ToImmutableDictionary(source, keySelector, elementSelector, null, null);
}
/// <summary>
/// Creates an immutable dictionary given a sequence of key=value pairs.
/// </summary>
/// <typeparam name="TKey">The type of key in the map.</typeparam>
/// <typeparam name="TValue">The type of value in the map.</typeparam>
/// <param name="source">The sequence of key=value pairs.</param>
/// <param name="keyComparer">The key comparer to use when building the immutable map.</param>
/// <param name="valueComparer">The value comparer to use for the immutable map.</param>
/// <returns>An immutable map.</returns>
[Pure]
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
public static ImmutableDictionary<TKey, TValue> ToImmutableDictionary<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> source, IEqualityComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer)
{
Requires.NotNull(source, "source");
Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null);
var existingDictionary = source as ImmutableDictionary<TKey, TValue>;
if (existingDictionary != null)
{
return existingDictionary.WithComparers(keyComparer, valueComparer);
}
return ImmutableDictionary<TKey, TValue>.Empty.WithComparers(keyComparer, valueComparer).AddRange(source);
}
/// <summary>
/// Creates an immutable dictionary given a sequence of key=value pairs.
/// </summary>
/// <typeparam name="TKey">The type of key in the map.</typeparam>
/// <typeparam name="TValue">The type of value in the map.</typeparam>
/// <param name="source">The sequence of key=value pairs.</param>
/// <param name="keyComparer">The key comparer to use when building the immutable map.</param>
/// <returns>An immutable map.</returns>
[Pure]
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
public static ImmutableDictionary<TKey, TValue> ToImmutableDictionary<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> source, IEqualityComparer<TKey> keyComparer)
{
return ToImmutableDictionary(source, keyComparer, null);
}
/// <summary>
/// Creates an immutable dictionary given a sequence of key=value pairs.
/// </summary>
/// <typeparam name="TKey">The type of key in the map.</typeparam>
/// <typeparam name="TValue">The type of value in the map.</typeparam>
/// <param name="source">The sequence of key=value pairs.</param>
/// <returns>An immutable map.</returns>
[Pure]
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
public static ImmutableDictionary<TKey, TValue> ToImmutableDictionary<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> source)
{
return ToImmutableDictionary(source, null, null);
}
/// <summary>
/// Determines whether this map contains the specified key-value pair.
/// </summary>
/// <typeparam name="TKey">The type of key in the map.</typeparam>
/// <typeparam name="TValue">The type of value in the map.</typeparam>
/// <param name="map">The map to search.</param>
/// <param name="key">The key to check for.</param>
/// <param name="value">The value to check for on a matching key, if found.</param>
/// <returns>
/// <c>true</c> if this map contains the key-value pair; otherwise, <c>false</c>.
/// </returns>
[Pure]
public static bool Contains<TKey, TValue>(this IImmutableDictionary<TKey, TValue> map, TKey key, TValue value)
{
Requires.NotNull(map, "map");
Requires.NotNullAllowStructs(key, "key");
return map.Contains(new KeyValuePair<TKey, TValue>(key, value));
}
/// <summary>
/// Gets the value for a given key if a matching key exists in the dictionary.
/// </summary>
/// <param name="dictionary">The dictionary to retrieve the value from.</param>
/// <param name="key">The key to search for.</param>
/// <returns>The value for the key, or the default value of type <typeparamref name="TValue"/> if no matching key was found.</returns>
[Pure]
public static TValue GetValueOrDefault<TKey, TValue>(this IImmutableDictionary<TKey, TValue> dictionary, TKey key)
{
return GetValueOrDefault(dictionary, key, default(TValue));
}
/// <summary>
/// Gets the value for a given key if a matching key exists in the dictionary.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="TValue">The type of the value.</typeparam>
/// <param name="dictionary">The dictionary to retrieve the value from.</param>
/// <param name="key">The key to search for.</param>
/// <param name="defaultValue">The default value to return if no matching key is found in the dictionary.</param>
/// <returns>
/// The value for the key, or <paramref name="defaultValue"/> if no matching key was found.
/// </returns>
[Pure]
public static TValue GetValueOrDefault<TKey, TValue>(this IImmutableDictionary<TKey, TValue> dictionary, TKey key, TValue defaultValue)
{
Requires.NotNull(dictionary, "dictionary");
Requires.NotNullAllowStructs(key, "key");
TValue value;
if (dictionary.TryGetValue(key, out value))
{
return value;
}
return defaultValue;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Transactions;
using Abp.Application.Features;
using Abp.Auditing;
using Abp.Authorization.Roles;
using Abp.Configuration;
using Abp.Configuration.Startup;
using Abp.Dependency;
using Abp.Domain.Repositories;
using Abp.Domain.Services;
using Abp.Domain.Uow;
using Abp.Extensions;
using Abp.IdentityFramework;
using Abp.Localization;
using Abp.MultiTenancy;
using Abp.Organizations;
using Abp.Runtime.Caching;
using Abp.Runtime.Security;
using Abp.Runtime.Session;
using Abp.Timing;
using Abp.Zero;
using Abp.Zero.Configuration;
using Microsoft.AspNet.Identity;
namespace Abp.Authorization.Users
{
/// <summary>
/// Extends <see cref="UserManager{TUser,TKey}"/> of ASP.NET Identity Framework.
/// </summary>
public abstract class AbpUserManager<TTenant, TRole, TUser>
: UserManager<TUser, long>,
IDomainService
where TTenant : AbpTenant<TTenant, TUser>
where TRole : AbpRole<TTenant, TUser>, new()
where TUser : AbpUser<TTenant, TUser>
{
private IUserPermissionStore<TTenant, TUser> UserPermissionStore
{
get
{
if (!(Store is IUserPermissionStore<TTenant, TUser>))
{
throw new AbpException("Store is not IUserPermissionStore");
}
return Store as IUserPermissionStore<TTenant, TUser>;
}
}
public ILocalizationManager LocalizationManager { get; set; }
public IAbpSession AbpSession { get; set; }
public IAuditInfoProvider AuditInfoProvider { get; set; }
public FeatureDependencyContext FeatureDependencyContext { get; set; }
protected AbpRoleManager<TTenant, TRole, TUser> RoleManager { get; private set; }
protected ISettingManager SettingManager { get; private set; }
protected AbpUserStore<TTenant, TRole, TUser> AbpStore { get; private set; }
private readonly IPermissionManager _permissionManager;
private readonly IUnitOfWorkManager _unitOfWorkManager;
private readonly IUserManagementConfig _userManagementConfig;
private readonly IIocResolver _iocResolver;
private readonly IRepository<TTenant> _tenantRepository;
private readonly IMultiTenancyConfig _multiTenancyConfig;
private readonly ICacheManager _cacheManager;
private readonly IRepository<OrganizationUnit, long> _organizationUnitRepository;
private readonly IRepository<UserOrganizationUnit, long> _userOrganizationUnitRepository;
private readonly IOrganizationUnitSettings _organizationUnitSettings;
private readonly IRepository<UserLoginAttempt, long> _userLoginAttemptRepository;
protected AbpUserManager(
AbpUserStore<TTenant, TRole, TUser> userStore,
AbpRoleManager<TTenant, TRole, TUser> roleManager,
IRepository<TTenant> tenantRepository,
IMultiTenancyConfig multiTenancyConfig,
IPermissionManager permissionManager,
IUnitOfWorkManager unitOfWorkManager,
ISettingManager settingManager,
IUserManagementConfig userManagementConfig,
IIocResolver iocResolver,
ICacheManager cacheManager,
IRepository<OrganizationUnit, long> organizationUnitRepository,
IRepository<UserOrganizationUnit, long> userOrganizationUnitRepository,
IOrganizationUnitSettings organizationUnitSettings,
IRepository<UserLoginAttempt, long> userLoginAttemptRepository)
: base(userStore)
{
AbpStore = userStore;
RoleManager = roleManager;
SettingManager = settingManager;
_tenantRepository = tenantRepository;
_multiTenancyConfig = multiTenancyConfig;
_permissionManager = permissionManager;
_unitOfWorkManager = unitOfWorkManager;
_userManagementConfig = userManagementConfig;
_iocResolver = iocResolver;
_cacheManager = cacheManager;
_organizationUnitRepository = organizationUnitRepository;
_userOrganizationUnitRepository = userOrganizationUnitRepository;
_organizationUnitSettings = organizationUnitSettings;
_userLoginAttemptRepository = userLoginAttemptRepository;
LocalizationManager = NullLocalizationManager.Instance;
AbpSession = NullAbpSession.Instance;
}
public override async Task<IdentityResult> CreateAsync(TUser user)
{
var result = await CheckDuplicateUsernameOrEmailAddressAsync(user.Id, user.UserName, user.EmailAddress);
if (!result.Succeeded)
{
return result;
}
if (AbpSession.TenantId.HasValue)
{
user.TenantId = AbpSession.TenantId.Value;
}
return await base.CreateAsync(user);
}
/// <summary>
/// Check whether a user is granted for a permission.
/// </summary>
/// <param name="userId">User id</param>
/// <param name="permissionName">Permission name</param>
public virtual async Task<bool> IsGrantedAsync(long userId, string permissionName)
{
return await IsGrantedAsync(
userId,
_permissionManager.GetPermission(permissionName)
);
}
/// <summary>
/// Check whether a user is granted for a permission.
/// </summary>
/// <param name="user">User</param>
/// <param name="permission">Permission</param>
public virtual Task<bool> IsGrantedAsync(TUser user, Permission permission)
{
return IsGrantedAsync(user.Id, permission);
}
/// <summary>
/// Check whether a user is granted for a permission.
/// </summary>
/// <param name="userId">User id</param>
/// <param name="permission">Permission</param>
public virtual async Task<bool> IsGrantedAsync(long userId, Permission permission)
{
//Check for multi-tenancy side
if (!permission.MultiTenancySides.HasFlag(AbpSession.MultiTenancySide))
{
return false;
}
//Check for depended features
if (permission.FeatureDependency != null && AbpSession.MultiTenancySide == MultiTenancySides.Tenant)
{
if (!await permission.FeatureDependency.IsSatisfiedAsync(FeatureDependencyContext))
{
return false;
}
}
//Get cached user permissions
var cacheItem = await GetUserPermissionCacheItemAsync(userId);
//Check for user-specific value
if (cacheItem.GrantedPermissions.Contains(permission.Name))
{
return true;
}
if (cacheItem.ProhibitedPermissions.Contains(permission.Name))
{
return false;
}
//Check for roles
foreach (var roleId in cacheItem.RoleIds)
{
if (await RoleManager.IsGrantedAsync(roleId, permission))
{
return true;
}
}
return false;
}
/// <summary>
/// Gets granted permissions for a user.
/// </summary>
/// <param name="user">Role</param>
/// <returns>List of granted permissions</returns>
public virtual async Task<IReadOnlyList<Permission>> GetGrantedPermissionsAsync(TUser user)
{
var permissionList = new List<Permission>();
foreach (var permission in _permissionManager.GetAllPermissions())
{
if (await IsGrantedAsync(user.Id, permission))
{
permissionList.Add(permission);
}
}
return permissionList;
}
/// <summary>
/// Sets all granted permissions of a user at once.
/// Prohibits all other permissions.
/// </summary>
/// <param name="user">The user</param>
/// <param name="permissions">Permissions</param>
public virtual async Task SetGrantedPermissionsAsync(TUser user, IEnumerable<Permission> permissions)
{
var oldPermissions = await GetGrantedPermissionsAsync(user);
var newPermissions = permissions.ToArray();
foreach (var permission in oldPermissions.Where(p => !newPermissions.Contains(p)))
{
await ProhibitPermissionAsync(user, permission);
}
foreach (var permission in newPermissions.Where(p => !oldPermissions.Contains(p)))
{
await GrantPermissionAsync(user, permission);
}
}
/// <summary>
/// Prohibits all permissions for a user.
/// </summary>
/// <param name="user">User</param>
public async Task ProhibitAllPermissionsAsync(TUser user)
{
foreach (var permission in _permissionManager.GetAllPermissions())
{
await ProhibitPermissionAsync(user, permission);
}
}
/// <summary>
/// Resets all permission settings for a user.
/// It removes all permission settings for the user.
/// User will have permissions according to his roles.
/// This method does not prohibit all permissions.
/// For that, use <see cref="ProhibitAllPermissionsAsync"/>.
/// </summary>
/// <param name="user">User</param>
public async Task ResetAllPermissionsAsync(TUser user)
{
await UserPermissionStore.RemoveAllPermissionSettingsAsync(user);
}
/// <summary>
/// Grants a permission for a user if not already granted.
/// </summary>
/// <param name="user">User</param>
/// <param name="permission">Permission</param>
public virtual async Task GrantPermissionAsync(TUser user, Permission permission)
{
await UserPermissionStore.RemovePermissionAsync(user, new PermissionGrantInfo(permission.Name, false));
if (await IsGrantedAsync(user.Id, permission))
{
return;
}
await UserPermissionStore.AddPermissionAsync(user, new PermissionGrantInfo(permission.Name, true));
}
/// <summary>
/// Prohibits a permission for a user if it's granted.
/// </summary>
/// <param name="user">User</param>
/// <param name="permission">Permission</param>
public virtual async Task ProhibitPermissionAsync(TUser user, Permission permission)
{
await UserPermissionStore.RemovePermissionAsync(user, new PermissionGrantInfo(permission.Name, true));
if (!await IsGrantedAsync(user.Id, permission))
{
return;
}
await UserPermissionStore.AddPermissionAsync(user, new PermissionGrantInfo(permission.Name, false));
}
public virtual async Task<TUser> FindByNameOrEmailAsync(string userNameOrEmailAddress)
{
return await AbpStore.FindByNameOrEmailAsync(userNameOrEmailAddress);
}
public virtual Task<List<TUser>> FindAllAsync(UserLoginInfo login)
{
return AbpStore.FindAllAsync(login);
}
[UnitOfWork]
public virtual async Task<AbpLoginResult> LoginAsync(UserLoginInfo login, string tenancyName = null)
{
var result = await LoginAsyncInternal(login, tenancyName);
await SaveLoginAttempt(result, tenancyName, login.ProviderKey + "@" + login.LoginProvider);
return result;
}
private async Task<AbpLoginResult> LoginAsyncInternal(UserLoginInfo login, string tenancyName)
{
if (login == null || login.LoginProvider.IsNullOrEmpty() || login.ProviderKey.IsNullOrEmpty())
{
throw new ArgumentException("login");
}
//Get and check tenant
TTenant tenant = null;
if (!_multiTenancyConfig.IsEnabled)
{
tenant = await GetDefaultTenantAsync();
}
else if (!string.IsNullOrWhiteSpace(tenancyName))
{
tenant = await _tenantRepository.FirstOrDefaultAsync(t => t.TenancyName == tenancyName);
if (tenant == null)
{
return new AbpLoginResult(AbpLoginResultType.InvalidTenancyName);
}
if (!tenant.IsActive)
{
return new AbpLoginResult(AbpLoginResultType.TenantIsNotActive, tenant);
}
}
using (_unitOfWorkManager.Current.DisableFilter(AbpDataFilters.MayHaveTenant))
{
var user = await AbpStore.FindAsync(tenant == null ? (int?)null : tenant.Id, login);
if (user == null)
{
return new AbpLoginResult(AbpLoginResultType.UnknownExternalLogin, tenant);
}
return await CreateLoginResultAsync(user, tenant);
}
}
[UnitOfWork]
public virtual async Task<AbpLoginResult> LoginAsync(string userNameOrEmailAddress, string plainPassword, string tenancyName = null)
{
var result = await LoginAsyncInternal(userNameOrEmailAddress, plainPassword, tenancyName);
await SaveLoginAttempt(result, tenancyName, userNameOrEmailAddress);
return result;
}
private async Task<AbpLoginResult> LoginAsyncInternal(string userNameOrEmailAddress, string plainPassword, string tenancyName = null)
{
if (userNameOrEmailAddress.IsNullOrEmpty())
{
throw new ArgumentNullException("userNameOrEmailAddress");
}
if (plainPassword.IsNullOrEmpty())
{
throw new ArgumentNullException("plainPassword");
}
//Get and check tenant
TTenant tenant = null;
if (!_multiTenancyConfig.IsEnabled)
{
tenant = await GetDefaultTenantAsync();
}
else if (!string.IsNullOrWhiteSpace(tenancyName))
{
tenant = await _tenantRepository.FirstOrDefaultAsync(t => t.TenancyName == tenancyName);
if (tenant == null)
{
return new AbpLoginResult(AbpLoginResultType.InvalidTenancyName);
}
if (!tenant.IsActive)
{
return new AbpLoginResult(AbpLoginResultType.TenantIsNotActive, tenant);
}
}
using (_unitOfWorkManager.Current.DisableFilter(AbpDataFilters.MayHaveTenant))
{
var loggedInFromExternalSource = await TryLoginFromExternalAuthenticationSources(userNameOrEmailAddress, plainPassword, tenant);
var user = await AbpStore.FindByNameOrEmailAsync(tenant == null ? (int?)null : tenant.Id, userNameOrEmailAddress);
if (user == null)
{
return new AbpLoginResult(AbpLoginResultType.InvalidUserNameOrEmailAddress, tenant);
}
if (!loggedInFromExternalSource)
{
var verificationResult = new PasswordHasher().VerifyHashedPassword(user.Password, plainPassword);
if (verificationResult != PasswordVerificationResult.Success)
{
return new AbpLoginResult(AbpLoginResultType.InvalidPassword, tenant, user);
}
}
return await CreateLoginResultAsync(user, tenant);
}
}
private async Task<AbpLoginResult> CreateLoginResultAsync(TUser user, TTenant tenant = null)
{
if (!user.IsActive)
{
return new AbpLoginResult(AbpLoginResultType.UserIsNotActive);
}
if (await IsEmailConfirmationRequiredForLoginAsync(user.TenantId) && !user.IsEmailConfirmed)
{
return new AbpLoginResult(AbpLoginResultType.UserEmailIsNotConfirmed);
}
user.LastLoginTime = Clock.Now;
await Store.UpdateAsync(user);
await _unitOfWorkManager.Current.SaveChangesAsync();
return new AbpLoginResult(tenant, user, await CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie));
}
private async Task SaveLoginAttempt(AbpLoginResult loginResult, string tenancyName, string userNameOrEmailAddress)
{
using (var uow = _unitOfWorkManager.Begin(TransactionScopeOption.Suppress))
{
var loginAttempt = new UserLoginAttempt
{
TenantId = loginResult.Tenant != null ? loginResult.Tenant.Id : (int?)null,
TenancyName = tenancyName,
UserId = loginResult.User != null ? loginResult.User.Id : (long?)null,
UserNameOrEmailAddress = userNameOrEmailAddress,
Result = loginResult.Result,
};
//TODO: We should replace this workaround with IClientInfoProvider when it's implemented in ABP (https://github.com/aspnetboilerplate/aspnetboilerplate/issues/926)
if (AuditInfoProvider != null)
{
var auditInfo = new AuditInfo();
AuditInfoProvider.Fill(auditInfo);
loginAttempt.BrowserInfo = auditInfo.BrowserInfo;
loginAttempt.ClientIpAddress = auditInfo.ClientIpAddress;
loginAttempt.ClientName = auditInfo.ClientName;
}
await _userLoginAttemptRepository.InsertAsync(loginAttempt);
await _unitOfWorkManager.Current.SaveChangesAsync();
await uow.CompleteAsync();
}
}
private async Task<bool> TryLoginFromExternalAuthenticationSources(string userNameOrEmailAddress, string plainPassword, TTenant tenant)
{
if (!_userManagementConfig.ExternalAuthenticationSources.Any())
{
return false;
}
foreach (var sourceType in _userManagementConfig.ExternalAuthenticationSources)
{
using (var source = _iocResolver.ResolveAsDisposable<IExternalAuthenticationSource<TTenant, TUser>>(sourceType))
{
if (await source.Object.TryAuthenticateAsync(userNameOrEmailAddress, plainPassword, tenant))
{
var tenantId = tenant == null ? (int?)null : tenant.Id;
var user = await AbpStore.FindByNameOrEmailAsync(tenantId, userNameOrEmailAddress);
if (user == null)
{
user = await source.Object.CreateUserAsync(userNameOrEmailAddress, tenant);
user.Tenant = tenant;
user.AuthenticationSource = source.Object.Name;
user.Password = new PasswordHasher().HashPassword(Guid.NewGuid().ToString("N").Left(16)); //Setting a random password since it will not be used
user.Roles = new List<UserRole>();
foreach (var defaultRole in RoleManager.Roles.Where(r => r.TenantId == tenantId && r.IsDefault).ToList())
{
user.Roles.Add(new UserRole { RoleId = defaultRole.Id });
}
await Store.CreateAsync(user);
}
else
{
await source.Object.UpdateUserAsync(user, tenant);
user.AuthenticationSource = source.Object.Name;
await Store.UpdateAsync(user);
}
await _unitOfWorkManager.Current.SaveChangesAsync();
return true;
}
}
}
return false;
}
/// <summary>
/// Gets a user by given id.
/// Throws exception if no user found with given id.
/// </summary>
/// <param name="userId">User id</param>
/// <returns>User</returns>
/// <exception cref="AbpException">Throws exception if no user found with given id</exception>
public virtual async Task<TUser> GetUserByIdAsync(long userId)
{
var user = await FindByIdAsync(userId);
if (user == null)
{
throw new AbpException("There is no user with id: " + userId);
}
return user;
}
public async override Task<ClaimsIdentity> CreateIdentityAsync(TUser user, string authenticationType)
{
var identity = await base.CreateIdentityAsync(user, authenticationType);
if (user.TenantId.HasValue)
{
identity.AddClaim(new Claim(AbpClaimTypes.TenantId, user.TenantId.Value.ToString(CultureInfo.InvariantCulture)));
}
return identity;
}
public async override Task<IdentityResult> UpdateAsync(TUser user)
{
var result = await CheckDuplicateUsernameOrEmailAddressAsync(user.Id, user.UserName, user.EmailAddress);
if (!result.Succeeded)
{
return result;
}
var oldUserName = (await GetUserByIdAsync(user.Id)).UserName;
if (oldUserName == AbpUser<TTenant, TUser>.AdminUserName && user.UserName != AbpUser<TTenant, TUser>.AdminUserName)
{
return AbpIdentityResult.Failed(string.Format(L("CanNotRenameAdminUser"), AbpUser<TTenant, TUser>.AdminUserName));
}
return await base.UpdateAsync(user);
}
public async override Task<IdentityResult> DeleteAsync(TUser user)
{
if (user.UserName == AbpUser<TTenant, TUser>.AdminUserName)
{
return AbpIdentityResult.Failed(string.Format(L("CanNotDeleteAdminUser"), AbpUser<TTenant, TUser>.AdminUserName));
}
return await base.DeleteAsync(user);
}
public virtual async Task<IdentityResult> ChangePasswordAsync(TUser user, string newPassword)
{
var result = await PasswordValidator.ValidateAsync(newPassword);
if (!result.Succeeded)
{
return result;
}
await AbpStore.SetPasswordHashAsync(user, PasswordHasher.HashPassword(newPassword));
return IdentityResult.Success;
}
public virtual async Task<IdentityResult> CheckDuplicateUsernameOrEmailAddressAsync(long? expectedUserId, string userName, string emailAddress)
{
var user = (await FindByNameAsync(userName));
if (user != null && user.Id != expectedUserId)
{
return AbpIdentityResult.Failed(string.Format(L("Identity.DuplicateName"), userName));
}
user = (await FindByEmailAsync(emailAddress));
if (user != null && user.Id != expectedUserId)
{
return AbpIdentityResult.Failed(string.Format(L("Identity.DuplicateEmail"), emailAddress));
}
return IdentityResult.Success;
}
public virtual async Task<IdentityResult> SetRoles(TUser user, string[] roleNames)
{
//Remove from removed roles
foreach (var userRole in user.Roles.ToList())
{
var role = await RoleManager.FindByIdAsync(userRole.RoleId);
if (roleNames.All(roleName => role.Name != roleName))
{
var result = await RemoveFromRoleAsync(user.Id, role.Name);
if (!result.Succeeded)
{
return result;
}
}
}
//Add to added roles
foreach (var roleName in roleNames)
{
var role = await RoleManager.GetRoleByNameAsync(roleName);
if (user.Roles.All(ur => ur.RoleId != role.Id))
{
var result = await AddToRoleAsync(user.Id, roleName);
if (!result.Succeeded)
{
return result;
}
}
}
return IdentityResult.Success;
}
public virtual async Task<bool> IsInOrganizationUnitAsync(long userId, long ouId)
{
return await IsInOrganizationUnitAsync(
await GetUserByIdAsync(userId),
await _organizationUnitRepository.GetAsync(ouId)
);
}
public virtual async Task<bool> IsInOrganizationUnitAsync(TUser user, OrganizationUnit ou)
{
return await _userOrganizationUnitRepository.CountAsync(uou =>
uou.UserId == user.Id && uou.OrganizationUnitId == ou.Id
) > 0;
}
public virtual async Task AddToOrganizationUnitAsync(long userId, long ouId)
{
await AddToOrganizationUnitAsync(
await GetUserByIdAsync(userId),
await _organizationUnitRepository.GetAsync(ouId)
);
}
public virtual async Task AddToOrganizationUnitAsync(TUser user, OrganizationUnit ou)
{
var currentOus = await GetOrganizationUnitsAsync(user);
if (currentOus.Any(cou => cou.Id == ou.Id))
{
return;
}
await CheckMaxUserOrganizationUnitMembershipCountAsync(user.TenantId, currentOus.Count + 1);
await _userOrganizationUnitRepository.InsertAsync(new UserOrganizationUnit(user.TenantId, user.Id, ou.Id));
}
public virtual async Task RemoveFromOrganizationUnitAsync(long userId, long ouId)
{
await RemoveFromOrganizationUnitAsync(
await GetUserByIdAsync(userId),
await _organizationUnitRepository.GetAsync(ouId)
);
}
public virtual async Task RemoveFromOrganizationUnitAsync(TUser user, OrganizationUnit ou)
{
await _userOrganizationUnitRepository.DeleteAsync(uou => uou.UserId == user.Id && uou.OrganizationUnitId == ou.Id);
}
public virtual async Task SetOrganizationUnitsAsync(long userId, params long[] organizationUnitIds)
{
await SetOrganizationUnitsAsync(
await GetUserByIdAsync(userId),
organizationUnitIds
);
}
private async Task CheckMaxUserOrganizationUnitMembershipCountAsync(int? tenantId, int requestedCount)
{
var maxCount = await _organizationUnitSettings.GetMaxUserMembershipCountAsync(tenantId);
if (requestedCount > maxCount)
{
throw new AbpException(string.Format("Can not set more than {0} organization unit for a user!", maxCount));
}
}
public virtual async Task SetOrganizationUnitsAsync(TUser user, params long[] organizationUnitIds)
{
if (organizationUnitIds == null)
{
organizationUnitIds = new long[0];
}
await CheckMaxUserOrganizationUnitMembershipCountAsync(user.TenantId, organizationUnitIds.Length);
var currentOus = await GetOrganizationUnitsAsync(user);
//Remove from removed OUs
foreach (var currentOu in currentOus)
{
if (!organizationUnitIds.Contains(currentOu.Id))
{
await RemoveFromOrganizationUnitAsync(user, currentOu);
}
}
//Add to added OUs
foreach (var organizationUnitId in organizationUnitIds)
{
if (currentOus.All(ou => ou.Id != organizationUnitId))
{
await AddToOrganizationUnitAsync(
user,
await _organizationUnitRepository.GetAsync(organizationUnitId)
);
}
}
}
[UnitOfWork]
public virtual Task<List<OrganizationUnit>> GetOrganizationUnitsAsync(TUser user)
{
var query = from uou in _userOrganizationUnitRepository.GetAll()
join ou in _organizationUnitRepository.GetAll() on uou.OrganizationUnitId equals ou.Id
where uou.UserId == user.Id
select ou;
return Task.FromResult(query.ToList());
}
[UnitOfWork]
public virtual Task<List<TUser>> GetUsersInOrganizationUnit(OrganizationUnit organizationUnit, bool includeChildren = false)
{
if (!includeChildren)
{
var query = from uou in _userOrganizationUnitRepository.GetAll()
join user in AbpStore.Users on uou.UserId equals user.Id
where uou.OrganizationUnitId == organizationUnit.Id
select user;
return Task.FromResult(query.ToList());
}
else
{
var query = from uou in _userOrganizationUnitRepository.GetAll()
join user in AbpStore.Users on uou.UserId equals user.Id
join ou in _organizationUnitRepository.GetAll() on uou.OrganizationUnitId equals ou.Id
where ou.Code.StartsWith(organizationUnit.Code)
select user;
return Task.FromResult(query.ToList());
}
}
private async Task<bool> IsEmailConfirmationRequiredForLoginAsync(int? tenantId)
{
if (tenantId.HasValue)
{
return await SettingManager.GetSettingValueForTenantAsync<bool>(AbpZeroSettingNames.UserManagement.IsEmailConfirmationRequiredForLogin, tenantId.Value);
}
return await SettingManager.GetSettingValueForApplicationAsync<bool>(AbpZeroSettingNames.UserManagement.IsEmailConfirmationRequiredForLogin);
}
private async Task<TTenant> GetDefaultTenantAsync()
{
var tenant = await _tenantRepository.FirstOrDefaultAsync(t => t.TenancyName == AbpTenant<TTenant, TUser>.DefaultTenantName);
if (tenant == null)
{
throw new AbpException("There should be a 'Default' tenant if multi-tenancy is disabled!");
}
return tenant;
}
private async Task<UserPermissionCacheItem> GetUserPermissionCacheItemAsync(long userId)
{
return await _cacheManager.GetUserPermissionCache().GetAsync(userId, async () =>
{
var newCacheItem = new UserPermissionCacheItem(userId);
foreach (var roleName in await GetRolesAsync(userId))
{
newCacheItem.RoleIds.Add((await RoleManager.GetRoleByNameAsync(roleName)).Id);
}
foreach (var permissionInfo in await UserPermissionStore.GetPermissionsAsync(userId))
{
if (permissionInfo.IsGranted)
{
newCacheItem.GrantedPermissions.Add(permissionInfo.Name);
}
else
{
newCacheItem.ProhibitedPermissions.Add(permissionInfo.Name);
}
}
return newCacheItem;
});
}
private string L(string name)
{
return LocalizationManager.GetString(AbpZeroConsts.LocalizationSourceName, name);
}
public class AbpLoginResult
{
public AbpLoginResultType Result { get; private set; }
public TTenant Tenant { get; private set; }
public TUser User { get; private set; }
public ClaimsIdentity Identity { get; private set; }
public AbpLoginResult(AbpLoginResultType result, TTenant tenant = null, TUser user = null)
{
Result = result;
Tenant = tenant;
User = user;
}
public AbpLoginResult(TTenant tenant, TUser user, ClaimsIdentity identity)
: this(AbpLoginResultType.Success, tenant)
{
User = user;
Identity = identity;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data.Services.Client;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Runtime.Versioning;
namespace NuGet
{
public class DataServicePackageRepository : PackageRepositoryBase, IHttpClientEvents, IServiceBasedRepository, ICloneableRepository, ICultureAwareRepository
{
private IDataServiceContext _context;
private readonly IHttpClient _httpClient;
private readonly PackageDownloader _packageDownloader;
private CultureInfo _culture;
private const string FindPackagesByIdSvcMethod = "FindPackagesById";
private const string SearchSvcMethod = "Search";
private const string GetUpdatesSvcMethod = "GetUpdates";
// Just forward calls to the package downloader
public event EventHandler<ProgressEventArgs> ProgressAvailable
{
add
{
_packageDownloader.ProgressAvailable += value;
}
remove
{
_packageDownloader.ProgressAvailable -= value;
}
}
public event EventHandler<WebRequestEventArgs> SendingRequest
{
add
{
_packageDownloader.SendingRequest += value;
_httpClient.SendingRequest += value;
}
remove
{
_packageDownloader.SendingRequest -= value;
_httpClient.SendingRequest -= value;
}
}
public PackageDownloader PackageDownloader
{
get { return _packageDownloader; }
}
public DataServicePackageRepository(Uri serviceRoot)
: this(new HttpClient(serviceRoot))
{
}
public DataServicePackageRepository(IHttpClient client)
: this(client, new PackageDownloader())
{
}
public DataServicePackageRepository(IHttpClient client, PackageDownloader packageDownloader)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
if (packageDownloader == null)
{
throw new ArgumentNullException("packageDownloader");
}
_httpClient = client;
_httpClient.AcceptCompression = true;
_packageDownloader = packageDownloader;
}
public CultureInfo Culture
{
get
{
if (_culture == null)
{
// TODO: Technically, if this is a remote server, we have to return the culture of the server
// instead of invariant culture. However, there is no trivial way to retrieve the server's culture,
// So temporarily use Invariant culture here.
_culture = _httpClient.Uri.IsLoopback ? CultureInfo.CurrentCulture : CultureInfo.InvariantCulture;
}
return _culture;
}
}
public override string Source
{
get
{
return _httpClient.Uri.OriginalString;
}
}
public override bool SupportsPrereleasePackages
{
get
{
return Context.SupportsProperty("IsAbsoluteLatestVersion");
}
}
// Don't initialize the Context at the constructor time so that
// we don't make a web request if we are not going to actually use it
// since getting the Uri property of the RedirectedHttpClient will
// trigger that functionality.
internal IDataServiceContext Context
{
private get
{
if (_context == null)
{
_context = new DataServiceContextWrapper(_httpClient.Uri);
_context.SendingRequest += OnSendingRequest;
_context.ReadingEntity += OnReadingEntity;
_context.IgnoreMissingProperties = true;
}
return _context;
}
set
{
_context = value;
}
}
private void OnReadingEntity(object sender, ReadingWritingEntityEventArgs e)
{
var package = (DataServicePackage)e.Entity;
// REVIEW: This is the only way (I know) to download the package on demand
// GetReadStreamUri cannot be evaluated inside of OnReadingEntity. Lazily evaluate it inside DownloadPackage
package.Context = Context;
package.Downloader = _packageDownloader;
}
private void OnSendingRequest(object sender, SendingRequestEventArgs e)
{
// Initialize the request
_httpClient.InitializeRequest(e.Request);
}
public override IQueryable<IPackage> GetPackages()
{
// REVIEW: Is it ok to assume that the package entity set is called packages?
return new SmartDataServiceQuery<DataServicePackage>(Context, Constants.PackageServiceEntitySetName);
}
public IQueryable<IPackage> Search(string searchTerm, IEnumerable<string> targetFrameworks, bool allowPrereleaseVersions)
{
if (!Context.SupportsServiceMethod(SearchSvcMethod))
{
// If there's no search method then we can't filter by target framework
return GetPackages().Find(searchTerm)
.FilterByPrerelease(allowPrereleaseVersions)
.AsQueryable();
}
// Convert the list of framework names into short names
var shortFrameworkNames = targetFrameworks.Select(name => new FrameworkName(name))
.Select(VersionUtility.GetShortFrameworkName);
// Create a '|' separated string of framework names
string targetFrameworkString = String.Join("|", shortFrameworkNames);
var searchParameters = new Dictionary<string, object> {
{ "searchTerm", "'" + Escape(searchTerm) + "'" },
{ "targetFramework", "'" + Escape(targetFrameworkString) + "'" },
};
if (SupportsPrereleasePackages)
{
searchParameters.Add("includePrerelease", ToString(allowPrereleaseVersions));
}
// Create a query for the search service method
var query = Context.CreateQuery<DataServicePackage>(SearchSvcMethod, searchParameters);
return new SmartDataServiceQuery<DataServicePackage>(Context, query);
}
public IEnumerable<IPackage> FindPackagesById(string packageId)
{
if (!Context.SupportsServiceMethod(FindPackagesByIdSvcMethod))
{
// If there's no search method then we can't filter by target framework
return PackageRepositoryExtensions.FindPackagesByIdCore(this, packageId);
}
var serviceParameters = new Dictionary<string, object> {
{ "id", "'" + Escape(packageId) + "'" }
};
// Create a query for the search service method
var query = Context.CreateQuery<DataServicePackage>(FindPackagesByIdSvcMethod, serviceParameters);
return new SmartDataServiceQuery<DataServicePackage>(Context, query);
}
public IEnumerable<IPackage> GetUpdates(IEnumerable<IPackage> packages, bool includePrerelease, bool includeAllVersions, IEnumerable<FrameworkName> targetFramework)
{
if (!Context.SupportsServiceMethod(GetUpdatesSvcMethod))
{
// If there's no search method then we can't filter by target framework
return PackageRepositoryExtensions.GetUpdatesCore(this, packages, includePrerelease, includeAllVersions, targetFramework);
}
// Pipe all the things!
string ids = String.Join("|", packages.Select(p => p.Id));
string versions = String.Join("|", packages.Select(p => p.Version.ToString()));
string targetFrameworkValue = targetFramework.IsEmpty() ? "" : String.Join("|", targetFramework.Select(VersionUtility.GetShortFrameworkName));
var serviceParameters = new Dictionary<string, object> {
{ "packageIds", "'" + ids + "'" },
{ "versions", "'" + versions + "'" },
{ "includePrerelease", ToString(includePrerelease) },
{ "includeAllVersions", ToString(includeAllVersions) },
{ "targetFrameworks", "'" + Escape(targetFrameworkValue) + "'" },
};
var query = Context.CreateQuery<DataServicePackage>(GetUpdatesSvcMethod, serviceParameters);
return new SmartDataServiceQuery<DataServicePackage>(Context, query);
}
public IPackageRepository Clone()
{
return new DataServicePackageRepository(_httpClient, _packageDownloader);
}
/// <summary>
/// Escapes single quotes in the value by replacing them with two single quotes.
/// </summary>
private static string Escape(string value)
{
// REVIEW: Couldn't find another way to do this with odata
if (!String.IsNullOrEmpty(value))
{
return value.Replace("'", "''");
}
return value;
}
[SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Justification = "OData expects a lower case value.")]
private static string ToString(bool value)
{
return value.ToString().ToLowerInvariant();
}
}
}
| |
// -------------------------------------------------------------------------------------------------------------------
// Generated code, do not edit
// Command Line: DomGen "timeline.xsd" "..\Schema.cs" "timeline" "picoTimelineEditor"
// -------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using Sce.Atf.Dom;
namespace picoTimelineEditor
{
public static class Schema
{
public const string NS = "timeline";
public static void Initialize(XmlSchemaTypeCollection typeCollection)
{
Initialize((ns,name)=>typeCollection.GetNodeType(ns,name),
(ns,name)=>typeCollection.GetRootElement(ns,name));
}
public static void Initialize(IDictionary<string, XmlSchemaTypeCollection> typeCollections)
{
Initialize((ns,name)=>typeCollections[ns].GetNodeType(name),
(ns,name)=>typeCollections[ns].GetRootElement(name));
}
private static void Initialize(Func<string, string, DomNodeType> getNodeType, Func<string, string, ChildInfo> getRootElement)
{
timelineType.Type = getNodeType("timeline", "timelineType");
timelineType.nameAttribute = timelineType.Type.GetAttributeInfo("name");
timelineType.groupChild = timelineType.Type.GetChildInfo("group");
timelineType.markerChild = timelineType.Type.GetChildInfo("marker");
timelineType.timelineRefChild = timelineType.Type.GetChildInfo("timelineRef");
groupType.Type = getNodeType("timeline", "groupType");
groupType.nameAttribute = groupType.Type.GetAttributeInfo("name");
groupType.expandedAttribute = groupType.Type.GetAttributeInfo("expanded");
groupType.descriptionAttribute = groupType.Type.GetAttributeInfo("description");
groupType.trackChild = groupType.Type.GetChildInfo("track");
trackType.Type = getNodeType("timeline", "trackType");
trackType.nameAttribute = trackType.Type.GetAttributeInfo("name");
trackType.descriptionAttribute = trackType.Type.GetAttributeInfo("description");
trackType.intervalChild = trackType.Type.GetChildInfo("interval");
trackType.keyChild = trackType.Type.GetChildInfo("key");
intervalType.Type = getNodeType("timeline", "intervalType");
intervalType.startAttribute = intervalType.Type.GetAttributeInfo("start");
intervalType.descriptionAttribute = intervalType.Type.GetAttributeInfo("description");
intervalType.nameAttribute = intervalType.Type.GetAttributeInfo("name");
intervalType.lengthAttribute = intervalType.Type.GetAttributeInfo("length");
intervalType.colorAttribute = intervalType.Type.GetAttributeInfo("color");
eventType.Type = getNodeType("timeline", "eventType");
eventType.startAttribute = eventType.Type.GetAttributeInfo("start");
eventType.descriptionAttribute = eventType.Type.GetAttributeInfo("description");
eventType.nameAttribute = eventType.Type.GetAttributeInfo("name");
keyType.Type = getNodeType("timeline", "keyType");
keyType.startAttribute = keyType.Type.GetAttributeInfo("start");
keyType.descriptionAttribute = keyType.Type.GetAttributeInfo("description");
keyType.nameAttribute = keyType.Type.GetAttributeInfo("name");
markerType.Type = getNodeType("timeline", "markerType");
markerType.startAttribute = markerType.Type.GetAttributeInfo("start");
markerType.descriptionAttribute = markerType.Type.GetAttributeInfo("description");
markerType.nameAttribute = markerType.Type.GetAttributeInfo("name");
markerType.colorAttribute = markerType.Type.GetAttributeInfo("color");
timelineRefType.Type = getNodeType("timeline", "timelineRefType");
timelineRefType.nameAttribute = timelineRefType.Type.GetAttributeInfo("name");
timelineRefType.startAttribute = timelineRefType.Type.GetAttributeInfo("start");
timelineRefType.descriptionAttribute = timelineRefType.Type.GetAttributeInfo("description");
timelineRefType.colorAttribute = timelineRefType.Type.GetAttributeInfo("color");
timelineRefType.timelineFilenameAttribute = timelineRefType.Type.GetAttributeInfo("timelineFilename");
controlPointType.Type = getNodeType("timeline", "controlPointType");
controlPointType.xAttribute = controlPointType.Type.GetAttributeInfo("x");
controlPointType.yAttribute = controlPointType.Type.GetAttributeInfo("y");
controlPointType.tangentInAttribute = controlPointType.Type.GetAttributeInfo("tangentIn");
controlPointType.tangentInTypeAttribute = controlPointType.Type.GetAttributeInfo("tangentInType");
controlPointType.tangentOutAttribute = controlPointType.Type.GetAttributeInfo("tangentOut");
controlPointType.tangentOutTypeAttribute = controlPointType.Type.GetAttributeInfo("tangentOutType");
controlPointType.brokenTangentsAttribute = controlPointType.Type.GetAttributeInfo("brokenTangents");
curveType.Type = getNodeType("timeline", "curveType");
curveType.nameAttribute = curveType.Type.GetAttributeInfo("name");
curveType.displayNameAttribute = curveType.Type.GetAttributeInfo("displayName");
curveType.minXAttribute = curveType.Type.GetAttributeInfo("minX");
curveType.maxXAttribute = curveType.Type.GetAttributeInfo("maxX");
curveType.minYAttribute = curveType.Type.GetAttributeInfo("minY");
curveType.maxYAttribute = curveType.Type.GetAttributeInfo("maxY");
curveType.preInfinityAttribute = curveType.Type.GetAttributeInfo("preInfinity");
curveType.postInfinityAttribute = curveType.Type.GetAttributeInfo("postInfinity");
curveType.colorAttribute = curveType.Type.GetAttributeInfo("color");
curveType.xLabelAttribute = curveType.Type.GetAttributeInfo("xLabel");
curveType.yLabelAttribute = curveType.Type.GetAttributeInfo("yLabel");
curveType.controlPointChild = curveType.Type.GetChildInfo("controlPoint");
keyLuaScriptType.Type = getNodeType("timeline", "keyLuaScriptType");
keyLuaScriptType.startAttribute = keyLuaScriptType.Type.GetAttributeInfo("start");
keyLuaScriptType.descriptionAttribute = keyLuaScriptType.Type.GetAttributeInfo("description");
keyLuaScriptType.nameAttribute = keyLuaScriptType.Type.GetAttributeInfo("name");
keyLuaScriptType.sourceCodeAttribute = keyLuaScriptType.Type.GetAttributeInfo("sourceCode");
groupCameraType.Type = getNodeType("timeline", "groupCameraType");
groupCameraType.nameAttribute = groupCameraType.Type.GetAttributeInfo("name");
groupCameraType.expandedAttribute = groupCameraType.Type.GetAttributeInfo("expanded");
groupCameraType.descriptionAttribute = groupCameraType.Type.GetAttributeInfo("description");
groupCameraType.outputCameraAttribute = groupCameraType.Type.GetAttributeInfo("outputCamera");
groupCameraType.preCutsceneCameraAttribute = groupCameraType.Type.GetAttributeInfo("preCutsceneCamera");
groupCameraType.postCutsceneCameraAttribute = groupCameraType.Type.GetAttributeInfo("postCutsceneCamera");
groupCameraType.blendInDurationAttribute = groupCameraType.Type.GetAttributeInfo("blendInDuration");
groupCameraType.blendOutDurationAttribute = groupCameraType.Type.GetAttributeInfo("blendOutDuration");
groupCameraType.trackChild = groupCameraType.Type.GetChildInfo("track");
trackCameraAnimType.Type = getNodeType("timeline", "trackCameraAnimType");
trackCameraAnimType.nameAttribute = trackCameraAnimType.Type.GetAttributeInfo("name");
trackCameraAnimType.descriptionAttribute = trackCameraAnimType.Type.GetAttributeInfo("description");
trackCameraAnimType.intervalChild = trackCameraAnimType.Type.GetChildInfo("interval");
trackCameraAnimType.keyChild = trackCameraAnimType.Type.GetChildInfo("key");
trackCameraAnimType.intervalCameraAnimTypeChild = trackCameraAnimType.Type.GetChildInfo("intervalCameraAnimType");
intervalCameraAnimType.Type = getNodeType("timeline", "intervalCameraAnimType");
intervalCameraAnimType.startAttribute = intervalCameraAnimType.Type.GetAttributeInfo("start");
intervalCameraAnimType.descriptionAttribute = intervalCameraAnimType.Type.GetAttributeInfo("description");
intervalCameraAnimType.nameAttribute = intervalCameraAnimType.Type.GetAttributeInfo("name");
intervalCameraAnimType.lengthAttribute = intervalCameraAnimType.Type.GetAttributeInfo("length");
intervalCameraAnimType.colorAttribute = intervalCameraAnimType.Type.GetAttributeInfo("color");
intervalCameraAnimType.animOffsetAttribute = intervalCameraAnimType.Type.GetAttributeInfo("animOffset");
intervalCameraAnimType.animFileAttribute = intervalCameraAnimType.Type.GetAttributeInfo("animFile");
intervalCameraAnimType.cameraViewAttribute = intervalCameraAnimType.Type.GetAttributeInfo("cameraView");
intervalCameraAnimType.fovAttribute = intervalCameraAnimType.Type.GetAttributeInfo("fov");
intervalCameraAnimType.nearClipPlaneAttribute = intervalCameraAnimType.Type.GetAttributeInfo("nearClipPlane");
intervalCameraAnimType.farClipPlaneAttribute = intervalCameraAnimType.Type.GetAttributeInfo("farClipPlane");
groupAnimControllerType.Type = getNodeType("timeline", "groupAnimControllerType");
groupAnimControllerType.nameAttribute = groupAnimControllerType.Type.GetAttributeInfo("name");
groupAnimControllerType.expandedAttribute = groupAnimControllerType.Type.GetAttributeInfo("expanded");
groupAnimControllerType.descriptionAttribute = groupAnimControllerType.Type.GetAttributeInfo("description");
groupAnimControllerType.skelFileAttribute = groupAnimControllerType.Type.GetAttributeInfo("skelFile");
groupAnimControllerType.rootNodeAttribute = groupAnimControllerType.Type.GetAttributeInfo("rootNode");
groupAnimControllerType.trackChild = groupAnimControllerType.Type.GetChildInfo("track");
trackAnimControllerType.Type = getNodeType("timeline", "trackAnimControllerType");
trackAnimControllerType.nameAttribute = trackAnimControllerType.Type.GetAttributeInfo("name");
trackAnimControllerType.descriptionAttribute = trackAnimControllerType.Type.GetAttributeInfo("description");
trackAnimControllerType.intervalChild = trackAnimControllerType.Type.GetChildInfo("interval");
trackAnimControllerType.keyChild = trackAnimControllerType.Type.GetChildInfo("key");
trackAnimControllerType.intervalAnimControllerTypeChild = trackAnimControllerType.Type.GetChildInfo("intervalAnimControllerType");
intervalAnimControllerType.Type = getNodeType("timeline", "intervalAnimControllerType");
intervalAnimControllerType.startAttribute = intervalAnimControllerType.Type.GetAttributeInfo("start");
intervalAnimControllerType.descriptionAttribute = intervalAnimControllerType.Type.GetAttributeInfo("description");
intervalAnimControllerType.nameAttribute = intervalAnimControllerType.Type.GetAttributeInfo("name");
intervalAnimControllerType.lengthAttribute = intervalAnimControllerType.Type.GetAttributeInfo("length");
intervalAnimControllerType.colorAttribute = intervalAnimControllerType.Type.GetAttributeInfo("color");
intervalAnimControllerType.animOffsetAttribute = intervalAnimControllerType.Type.GetAttributeInfo("animOffset");
intervalAnimControllerType.animFileAttribute = intervalAnimControllerType.Type.GetAttributeInfo("animFile");
intervalCurveType.Type = getNodeType("timeline", "intervalCurveType");
intervalCurveType.startAttribute = intervalCurveType.Type.GetAttributeInfo("start");
intervalCurveType.descriptionAttribute = intervalCurveType.Type.GetAttributeInfo("description");
intervalCurveType.nameAttribute = intervalCurveType.Type.GetAttributeInfo("name");
intervalCurveType.lengthAttribute = intervalCurveType.Type.GetAttributeInfo("length");
intervalCurveType.colorAttribute = intervalCurveType.Type.GetAttributeInfo("color");
intervalCurveType.curveChild = intervalCurveType.Type.GetChildInfo("curve");
trackFaderType.Type = getNodeType("timeline", "trackFaderType");
trackFaderType.nameAttribute = trackFaderType.Type.GetAttributeInfo("name");
trackFaderType.descriptionAttribute = trackFaderType.Type.GetAttributeInfo("description");
trackFaderType.intervalChild = trackFaderType.Type.GetChildInfo("interval");
trackFaderType.keyChild = trackFaderType.Type.GetChildInfo("key");
intervalFaderType.Type = getNodeType("timeline", "intervalFaderType");
intervalFaderType.startAttribute = intervalFaderType.Type.GetAttributeInfo("start");
intervalFaderType.descriptionAttribute = intervalFaderType.Type.GetAttributeInfo("description");
intervalFaderType.nameAttribute = intervalFaderType.Type.GetAttributeInfo("name");
intervalFaderType.lengthAttribute = intervalFaderType.Type.GetAttributeInfo("length");
intervalFaderType.colorAttribute = intervalFaderType.Type.GetAttributeInfo("color");
intervalFaderType.curveChild = intervalFaderType.Type.GetChildInfo("curve");
intervalNodeAnimationType.Type = getNodeType("timeline", "intervalNodeAnimationType");
intervalNodeAnimationType.startAttribute = intervalNodeAnimationType.Type.GetAttributeInfo("start");
intervalNodeAnimationType.descriptionAttribute = intervalNodeAnimationType.Type.GetAttributeInfo("description");
intervalNodeAnimationType.nameAttribute = intervalNodeAnimationType.Type.GetAttributeInfo("name");
intervalNodeAnimationType.lengthAttribute = intervalNodeAnimationType.Type.GetAttributeInfo("length");
intervalNodeAnimationType.colorAttribute = intervalNodeAnimationType.Type.GetAttributeInfo("color");
intervalNodeAnimationType.nodeNameAttribute = intervalNodeAnimationType.Type.GetAttributeInfo("nodeName");
intervalNodeAnimationType.channelsAttribute = intervalNodeAnimationType.Type.GetAttributeInfo("channels");
intervalNodeAnimationType.curveChild = intervalNodeAnimationType.Type.GetChildInfo("curve");
groupCharacterControllerType.Type = getNodeType("timeline", "groupCharacterControllerType");
groupCharacterControllerType.nameAttribute = groupCharacterControllerType.Type.GetAttributeInfo("name");
groupCharacterControllerType.expandedAttribute = groupCharacterControllerType.Type.GetAttributeInfo("expanded");
groupCharacterControllerType.descriptionAttribute = groupCharacterControllerType.Type.GetAttributeInfo("description");
groupCharacterControllerType.nodeNameAttribute = groupCharacterControllerType.Type.GetAttributeInfo("nodeName");
groupCharacterControllerType.blendInDurationAttribute = groupCharacterControllerType.Type.GetAttributeInfo("blendInDuration");
groupCharacterControllerType.blendOutDurationAttribute = groupCharacterControllerType.Type.GetAttributeInfo("blendOutDuration");
groupCharacterControllerType.trackChild = groupCharacterControllerType.Type.GetChildInfo("track");
trackCharacterControllerAnimType.Type = getNodeType("timeline", "trackCharacterControllerAnimType");
trackCharacterControllerAnimType.nameAttribute = trackCharacterControllerAnimType.Type.GetAttributeInfo("name");
trackCharacterControllerAnimType.descriptionAttribute = trackCharacterControllerAnimType.Type.GetAttributeInfo("description");
trackCharacterControllerAnimType.intervalChild = trackCharacterControllerAnimType.Type.GetChildInfo("interval");
trackCharacterControllerAnimType.keyChild = trackCharacterControllerAnimType.Type.GetChildInfo("key");
intervalCharacterControllerAnimType.Type = getNodeType("timeline", "intervalCharacterControllerAnimType");
intervalCharacterControllerAnimType.startAttribute = intervalCharacterControllerAnimType.Type.GetAttributeInfo("start");
intervalCharacterControllerAnimType.descriptionAttribute = intervalCharacterControllerAnimType.Type.GetAttributeInfo("description");
intervalCharacterControllerAnimType.nameAttribute = intervalCharacterControllerAnimType.Type.GetAttributeInfo("name");
intervalCharacterControllerAnimType.lengthAttribute = intervalCharacterControllerAnimType.Type.GetAttributeInfo("length");
intervalCharacterControllerAnimType.colorAttribute = intervalCharacterControllerAnimType.Type.GetAttributeInfo("color");
intervalCharacterControllerAnimType.animFileAttribute = intervalCharacterControllerAnimType.Type.GetAttributeInfo("animFile");
intervalCharacterControllerAnimType.animOffsetAttribute = intervalCharacterControllerAnimType.Type.GetAttributeInfo("animOffset");
keySoundType.Type = getNodeType("timeline", "keySoundType");
keySoundType.startAttribute = keySoundType.Type.GetAttributeInfo("start");
keySoundType.descriptionAttribute = keySoundType.Type.GetAttributeInfo("description");
keySoundType.nameAttribute = keySoundType.Type.GetAttributeInfo("name");
keySoundType.soundBankAttribute = keySoundType.Type.GetAttributeInfo("soundBank");
keySoundType.soundAttribute = keySoundType.Type.GetAttributeInfo("sound");
keySoundType.positionalAttribute = keySoundType.Type.GetAttributeInfo("positional");
keySoundType.positionAttribute = keySoundType.Type.GetAttributeInfo("position");
intervalSoundType.Type = getNodeType("timeline", "intervalSoundType");
intervalSoundType.startAttribute = intervalSoundType.Type.GetAttributeInfo("start");
intervalSoundType.descriptionAttribute = intervalSoundType.Type.GetAttributeInfo("description");
intervalSoundType.nameAttribute = intervalSoundType.Type.GetAttributeInfo("name");
intervalSoundType.lengthAttribute = intervalSoundType.Type.GetAttributeInfo("length");
intervalSoundType.colorAttribute = intervalSoundType.Type.GetAttributeInfo("color");
intervalSoundType.soundBankAttribute = intervalSoundType.Type.GetAttributeInfo("soundBank");
intervalSoundType.soundAttribute = intervalSoundType.Type.GetAttributeInfo("sound");
intervalSoundType.positionalAttribute = intervalSoundType.Type.GetAttributeInfo("positional");
intervalSoundType.positionAttribute = intervalSoundType.Type.GetAttributeInfo("position");
refChangeLevelType.Type = getNodeType("timeline", "refChangeLevelType");
refChangeLevelType.nameAttribute = refChangeLevelType.Type.GetAttributeInfo("name");
refChangeLevelType.startAttribute = refChangeLevelType.Type.GetAttributeInfo("start");
refChangeLevelType.descriptionAttribute = refChangeLevelType.Type.GetAttributeInfo("description");
refChangeLevelType.colorAttribute = refChangeLevelType.Type.GetAttributeInfo("color");
refChangeLevelType.timelineFilenameAttribute = refChangeLevelType.Type.GetAttributeInfo("timelineFilename");
refChangeLevelType.levelNameAttribute = refChangeLevelType.Type.GetAttributeInfo("levelName");
refChangeLevelType.unloadCurrentlevelAttribute = refChangeLevelType.Type.GetAttributeInfo("unloadCurrentlevel");
refPlayTimelineType.Type = getNodeType("timeline", "refPlayTimelineType");
refPlayTimelineType.nameAttribute = refPlayTimelineType.Type.GetAttributeInfo("name");
refPlayTimelineType.startAttribute = refPlayTimelineType.Type.GetAttributeInfo("start");
refPlayTimelineType.descriptionAttribute = refPlayTimelineType.Type.GetAttributeInfo("description");
refPlayTimelineType.colorAttribute = refPlayTimelineType.Type.GetAttributeInfo("color");
refPlayTimelineType.timelineFilenameAttribute = refPlayTimelineType.Type.GetAttributeInfo("timelineFilename");
intervalTextType.Type = getNodeType("timeline", "intervalTextType");
intervalTextType.startAttribute = intervalTextType.Type.GetAttributeInfo("start");
intervalTextType.descriptionAttribute = intervalTextType.Type.GetAttributeInfo("description");
intervalTextType.nameAttribute = intervalTextType.Type.GetAttributeInfo("name");
intervalTextType.lengthAttribute = intervalTextType.Type.GetAttributeInfo("length");
intervalTextType.colorAttribute = intervalTextType.Type.GetAttributeInfo("color");
intervalTextType.textNodeNameAttribute = intervalTextType.Type.GetAttributeInfo("textNodeName");
intervalTextType.textTagAttribute = intervalTextType.Type.GetAttributeInfo("textTag");
trackBlendFactorType.Type = getNodeType("timeline", "trackBlendFactorType");
trackBlendFactorType.nameAttribute = trackBlendFactorType.Type.GetAttributeInfo("name");
trackBlendFactorType.descriptionAttribute = trackBlendFactorType.Type.GetAttributeInfo("description");
trackBlendFactorType.intervalChild = trackBlendFactorType.Type.GetChildInfo("interval");
trackBlendFactorType.keyChild = trackBlendFactorType.Type.GetChildInfo("key");
intervalBlendFactorType.Type = getNodeType("timeline", "intervalBlendFactorType");
intervalBlendFactorType.startAttribute = intervalBlendFactorType.Type.GetAttributeInfo("start");
intervalBlendFactorType.descriptionAttribute = intervalBlendFactorType.Type.GetAttributeInfo("description");
intervalBlendFactorType.nameAttribute = intervalBlendFactorType.Type.GetAttributeInfo("name");
intervalBlendFactorType.lengthAttribute = intervalBlendFactorType.Type.GetAttributeInfo("length");
intervalBlendFactorType.colorAttribute = intervalBlendFactorType.Type.GetAttributeInfo("color");
intervalBlendFactorType.curveChild = intervalBlendFactorType.Type.GetChildInfo("curve");
settingType.Type = getNodeType("timeline", "settingType");
cresLodSettingType.Type = getNodeType("timeline", "cresLodSettingType");
cresLodSettingType.nodeNameAttribute = cresLodSettingType.Type.GetAttributeInfo("nodeName");
cresLodSettingType.lod0DistanceAttribute = cresLodSettingType.Type.GetAttributeInfo("lod0Distance");
cresLodSettingType.lod1DistanceAttribute = cresLodSettingType.Type.GetAttributeInfo("lod1Distance");
cresLodSettingType.lod2DistanceAttribute = cresLodSettingType.Type.GetAttributeInfo("lod2Distance");
cresLodSettingType.cullDistanceAttribute = cresLodSettingType.Type.GetAttributeInfo("cullDistance");
cresLodSettingType.lod0DistanceShadowAttribute = cresLodSettingType.Type.GetAttributeInfo("lod0DistanceShadow");
cresLodSettingType.lod1DistanceShadowAttribute = cresLodSettingType.Type.GetAttributeInfo("lod1DistanceShadow");
cresLodSettingType.lod2DistanceShadowAttribute = cresLodSettingType.Type.GetAttributeInfo("lod2DistanceShadow");
intervalSettingType.Type = getNodeType("timeline", "intervalSettingType");
intervalSettingType.startAttribute = intervalSettingType.Type.GetAttributeInfo("start");
intervalSettingType.descriptionAttribute = intervalSettingType.Type.GetAttributeInfo("description");
intervalSettingType.nameAttribute = intervalSettingType.Type.GetAttributeInfo("name");
intervalSettingType.lengthAttribute = intervalSettingType.Type.GetAttributeInfo("length");
intervalSettingType.colorAttribute = intervalSettingType.Type.GetAttributeInfo("color");
intervalSettingType.settingChild = intervalSettingType.Type.GetChildInfo("setting");
timelineRootElement = getRootElement(NS, "timeline");
}
public static class timelineType
{
public static DomNodeType Type;
public static AttributeInfo nameAttribute;
public static ChildInfo groupChild;
public static ChildInfo markerChild;
public static ChildInfo timelineRefChild;
}
public static class groupType
{
public static DomNodeType Type;
public static AttributeInfo nameAttribute;
public static AttributeInfo expandedAttribute;
public static AttributeInfo descriptionAttribute;
public static ChildInfo trackChild;
}
public static class trackType
{
public static DomNodeType Type;
public static AttributeInfo nameAttribute;
public static AttributeInfo descriptionAttribute;
public static ChildInfo intervalChild;
public static ChildInfo keyChild;
}
public static class intervalType
{
public static DomNodeType Type;
public static AttributeInfo startAttribute;
public static AttributeInfo descriptionAttribute;
public static AttributeInfo nameAttribute;
public static AttributeInfo lengthAttribute;
public static AttributeInfo colorAttribute;
}
public static class eventType
{
public static DomNodeType Type;
public static AttributeInfo startAttribute;
public static AttributeInfo descriptionAttribute;
public static AttributeInfo nameAttribute;
}
public static class keyType
{
public static DomNodeType Type;
public static AttributeInfo startAttribute;
public static AttributeInfo descriptionAttribute;
public static AttributeInfo nameAttribute;
}
public static class markerType
{
public static DomNodeType Type;
public static AttributeInfo startAttribute;
public static AttributeInfo descriptionAttribute;
public static AttributeInfo nameAttribute;
public static AttributeInfo colorAttribute;
}
public static class timelineRefType
{
public static DomNodeType Type;
public static AttributeInfo nameAttribute;
public static AttributeInfo startAttribute;
public static AttributeInfo descriptionAttribute;
public static AttributeInfo colorAttribute;
public static AttributeInfo timelineFilenameAttribute;
}
public static class controlPointType
{
public static DomNodeType Type;
public static AttributeInfo xAttribute;
public static AttributeInfo yAttribute;
public static AttributeInfo tangentInAttribute;
public static AttributeInfo tangentInTypeAttribute;
public static AttributeInfo tangentOutAttribute;
public static AttributeInfo tangentOutTypeAttribute;
public static AttributeInfo brokenTangentsAttribute;
}
public static class curveType
{
public static DomNodeType Type;
public static AttributeInfo nameAttribute;
public static AttributeInfo displayNameAttribute;
public static AttributeInfo minXAttribute;
public static AttributeInfo maxXAttribute;
public static AttributeInfo minYAttribute;
public static AttributeInfo maxYAttribute;
public static AttributeInfo preInfinityAttribute;
public static AttributeInfo postInfinityAttribute;
public static AttributeInfo colorAttribute;
public static AttributeInfo xLabelAttribute;
public static AttributeInfo yLabelAttribute;
public static ChildInfo controlPointChild;
}
public static class keyLuaScriptType
{
public static DomNodeType Type;
public static AttributeInfo startAttribute;
public static AttributeInfo descriptionAttribute;
public static AttributeInfo nameAttribute;
public static AttributeInfo sourceCodeAttribute;
}
public static class groupCameraType
{
public static DomNodeType Type;
public static AttributeInfo nameAttribute;
public static AttributeInfo expandedAttribute;
public static AttributeInfo descriptionAttribute;
public static AttributeInfo outputCameraAttribute;
public static AttributeInfo preCutsceneCameraAttribute;
public static AttributeInfo postCutsceneCameraAttribute;
public static AttributeInfo blendInDurationAttribute;
public static AttributeInfo blendOutDurationAttribute;
public static ChildInfo trackChild;
}
public static class trackCameraAnimType
{
public static DomNodeType Type;
public static AttributeInfo nameAttribute;
public static AttributeInfo descriptionAttribute;
public static ChildInfo intervalChild;
public static ChildInfo keyChild;
public static ChildInfo intervalCameraAnimTypeChild;
}
public static class intervalCameraAnimType
{
public static DomNodeType Type;
public static AttributeInfo startAttribute;
public static AttributeInfo descriptionAttribute;
public static AttributeInfo nameAttribute;
public static AttributeInfo lengthAttribute;
public static AttributeInfo colorAttribute;
public static AttributeInfo animOffsetAttribute;
public static AttributeInfo animFileAttribute;
public static AttributeInfo cameraViewAttribute;
public static AttributeInfo fovAttribute;
public static AttributeInfo nearClipPlaneAttribute;
public static AttributeInfo farClipPlaneAttribute;
}
public static class groupAnimControllerType
{
public static DomNodeType Type;
public static AttributeInfo nameAttribute;
public static AttributeInfo expandedAttribute;
public static AttributeInfo descriptionAttribute;
public static AttributeInfo skelFileAttribute;
public static AttributeInfo rootNodeAttribute;
public static ChildInfo trackChild;
}
public static class trackAnimControllerType
{
public static DomNodeType Type;
public static AttributeInfo nameAttribute;
public static AttributeInfo descriptionAttribute;
public static ChildInfo intervalChild;
public static ChildInfo keyChild;
public static ChildInfo intervalAnimControllerTypeChild;
}
public static class intervalAnimControllerType
{
public static DomNodeType Type;
public static AttributeInfo startAttribute;
public static AttributeInfo descriptionAttribute;
public static AttributeInfo nameAttribute;
public static AttributeInfo lengthAttribute;
public static AttributeInfo colorAttribute;
public static AttributeInfo animOffsetAttribute;
public static AttributeInfo animFileAttribute;
}
public static class intervalCurveType
{
public static DomNodeType Type;
public static AttributeInfo startAttribute;
public static AttributeInfo descriptionAttribute;
public static AttributeInfo nameAttribute;
public static AttributeInfo lengthAttribute;
public static AttributeInfo colorAttribute;
public static ChildInfo curveChild;
}
public static class trackFaderType
{
public static DomNodeType Type;
public static AttributeInfo nameAttribute;
public static AttributeInfo descriptionAttribute;
public static ChildInfo intervalChild;
public static ChildInfo keyChild;
}
public static class intervalFaderType
{
public static DomNodeType Type;
public static AttributeInfo startAttribute;
public static AttributeInfo descriptionAttribute;
public static AttributeInfo nameAttribute;
public static AttributeInfo lengthAttribute;
public static AttributeInfo colorAttribute;
public static ChildInfo curveChild;
}
public static class intervalNodeAnimationType
{
public static DomNodeType Type;
public static AttributeInfo startAttribute;
public static AttributeInfo descriptionAttribute;
public static AttributeInfo nameAttribute;
public static AttributeInfo lengthAttribute;
public static AttributeInfo colorAttribute;
public static AttributeInfo nodeNameAttribute;
public static AttributeInfo channelsAttribute;
public static ChildInfo curveChild;
}
public static class groupCharacterControllerType
{
public static DomNodeType Type;
public static AttributeInfo nameAttribute;
public static AttributeInfo expandedAttribute;
public static AttributeInfo descriptionAttribute;
public static AttributeInfo nodeNameAttribute;
public static AttributeInfo blendInDurationAttribute;
public static AttributeInfo blendOutDurationAttribute;
public static ChildInfo trackChild;
}
public static class trackCharacterControllerAnimType
{
public static DomNodeType Type;
public static AttributeInfo nameAttribute;
public static AttributeInfo descriptionAttribute;
public static ChildInfo intervalChild;
public static ChildInfo keyChild;
}
public static class intervalCharacterControllerAnimType
{
public static DomNodeType Type;
public static AttributeInfo startAttribute;
public static AttributeInfo descriptionAttribute;
public static AttributeInfo nameAttribute;
public static AttributeInfo lengthAttribute;
public static AttributeInfo colorAttribute;
public static AttributeInfo animFileAttribute;
public static AttributeInfo animOffsetAttribute;
}
public static class keySoundType
{
public static DomNodeType Type;
public static AttributeInfo startAttribute;
public static AttributeInfo descriptionAttribute;
public static AttributeInfo nameAttribute;
public static AttributeInfo soundBankAttribute;
public static AttributeInfo soundAttribute;
public static AttributeInfo positionalAttribute;
public static AttributeInfo positionAttribute;
}
public static class intervalSoundType
{
public static DomNodeType Type;
public static AttributeInfo startAttribute;
public static AttributeInfo descriptionAttribute;
public static AttributeInfo nameAttribute;
public static AttributeInfo lengthAttribute;
public static AttributeInfo colorAttribute;
public static AttributeInfo soundBankAttribute;
public static AttributeInfo soundAttribute;
public static AttributeInfo positionalAttribute;
public static AttributeInfo positionAttribute;
}
public static class refChangeLevelType
{
public static DomNodeType Type;
public static AttributeInfo nameAttribute;
public static AttributeInfo startAttribute;
public static AttributeInfo descriptionAttribute;
public static AttributeInfo colorAttribute;
public static AttributeInfo timelineFilenameAttribute;
public static AttributeInfo levelNameAttribute;
public static AttributeInfo unloadCurrentlevelAttribute;
}
public static class refPlayTimelineType
{
public static DomNodeType Type;
public static AttributeInfo nameAttribute;
public static AttributeInfo startAttribute;
public static AttributeInfo descriptionAttribute;
public static AttributeInfo colorAttribute;
public static AttributeInfo timelineFilenameAttribute;
}
public static class intervalTextType
{
public static DomNodeType Type;
public static AttributeInfo startAttribute;
public static AttributeInfo descriptionAttribute;
public static AttributeInfo nameAttribute;
public static AttributeInfo lengthAttribute;
public static AttributeInfo colorAttribute;
public static AttributeInfo textNodeNameAttribute;
public static AttributeInfo textTagAttribute;
}
public static class trackBlendFactorType
{
public static DomNodeType Type;
public static AttributeInfo nameAttribute;
public static AttributeInfo descriptionAttribute;
public static ChildInfo intervalChild;
public static ChildInfo keyChild;
}
public static class intervalBlendFactorType
{
public static DomNodeType Type;
public static AttributeInfo startAttribute;
public static AttributeInfo descriptionAttribute;
public static AttributeInfo nameAttribute;
public static AttributeInfo lengthAttribute;
public static AttributeInfo colorAttribute;
public static ChildInfo curveChild;
}
public static class settingType
{
public static DomNodeType Type;
}
public static class cresLodSettingType
{
public static DomNodeType Type;
public static AttributeInfo nodeNameAttribute;
public static AttributeInfo lod0DistanceAttribute;
public static AttributeInfo lod1DistanceAttribute;
public static AttributeInfo lod2DistanceAttribute;
public static AttributeInfo cullDistanceAttribute;
public static AttributeInfo lod0DistanceShadowAttribute;
public static AttributeInfo lod1DistanceShadowAttribute;
public static AttributeInfo lod2DistanceShadowAttribute;
}
public static class intervalSettingType
{
public static DomNodeType Type;
public static AttributeInfo startAttribute;
public static AttributeInfo descriptionAttribute;
public static AttributeInfo nameAttribute;
public static AttributeInfo lengthAttribute;
public static AttributeInfo colorAttribute;
public static ChildInfo settingChild;
}
public static ChildInfo timelineRootElement;
}
}
| |
// Copyright 2010 Chris Patterson
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace Stact.Visitors
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Channels.Visitors;
using Magnum.Extensions;
using Magnum.Graphing;
public class GraphChannelVisitor :
ChannelVisitor
{
readonly List<Edge> _edges = new List<Edge>();
readonly Stack<Vertex> _stack = new Stack<Vertex>();
readonly Dictionary<int, Vertex> _vertices = new Dictionary<int, Vertex>();
Vertex _current;
public ChannelGraphData GetGraphData()
{
return new ChannelGraphData(_vertices.Values, _edges);
}
Vertex GetVertex(int key, Func<string> getTitle, Type nodeType, Type objectType)
{
return _vertices.Retrieve(key, () =>
{
var newSink = new Vertex(nodeType, objectType, getTitle());
return newSink;
});
}
Channel<T> WithVertex<T>(Func<Channel<T>> scopedAction)
{
_stack.Push(_current);
Channel<T> result = scopedAction();
_stack.Pop();
return result;
}
UntypedChannel WithVertex(Func<UntypedChannel> scopedAction)
{
_stack.Push(_current);
UntypedChannel result = scopedAction();
_stack.Pop();
return result;
}
ChannelProvider<T> WithVertex<T>(Func<ChannelProvider<T>> scopedAction)
{
_stack.Push(_current);
ChannelProvider<T> result = scopedAction();
_stack.Pop();
return result;
}
protected override Channel<T> Visitor<T>(ConsumerChannel<T> channel)
{
_current = GetVertex(channel.GetHashCode(), () => "Consumer", typeof(ConsumerChannel<T>), typeof(T));
if (_stack.Count > 0)
_edges.Add(new Edge(_stack.Peek(), _current, _current.TargetType.Name));
return WithVertex(() => base.Visitor(channel));
}
protected override Channel<T> Visitor<T>(FilterChannel<T> channel)
{
_current = GetVertex(channel.GetHashCode(), () => "Filter", typeof(FilterChannel<T>), typeof(T));
if (_stack.Count > 0)
_edges.Add(new Edge(_stack.Peek(), _current, _current.TargetType.Name));
return WithVertex(() => base.Visitor(channel));
}
protected override Channel<T> Visitor<T>(InstanceChannel<T> channel)
{
_current = GetVertex(channel.GetHashCode(), () => "Instance", typeof(InstanceChannel<T>), typeof(T));
if (_stack.Count > 0)
_edges.Add(new Edge(_stack.Peek(), _current, _current.TargetType.Name));
return WithVertex(() => base.Visitor(channel));
}
protected override Channel<T> Visitor<T>(IntervalChannel<T> channel)
{
_current = GetVertex(channel.GetHashCode(), () => "Interval", typeof(IntervalChannel<T>), typeof(ICollection<T>));
if (_stack.Count > 0)
_edges.Add(new Edge(_stack.Peek(), _current, _current.TargetType.Name));
return WithVertex(() => base.Visitor(channel));
}
protected override Channel<T> Visitor<T>(InterceptorChannel<T> channel)
{
Trace.WriteLine("InterceptorChannel<{0}>".FormatWith(typeof(T).Name));
return base.Visitor(channel);
}
protected override Channel<ICollection<T>> Visitor<T, TKey>(DistinctChannel<T, TKey> channel)
{
_current = GetVertex(channel.GetHashCode(), () => "Distinct", typeof(DistinctChannel<T, TKey>), typeof(T));
if (_stack.Count > 0)
_edges.Add(new Edge(_stack.Peek(), _current, _current.TargetType.Name));
return WithVertex(() => base.Visitor(channel));
}
protected override Channel<ICollection<T>> Visitor<T>(LastChannel<T> channel)
{
_current = GetVertex(channel.GetHashCode(), () => "Last", typeof(LastChannel<T>), typeof(T));
if (_stack.Count > 0)
_edges.Add(new Edge(_stack.Peek(), _current, _current.TargetType.Name));
return WithVertex(() => base.Visitor(channel));
}
protected override Channel<T> Visitor<T>(AsyncResultChannel<T> channel)
{
Trace.WriteLine("AsyncResultChannel<{0}>, {1}".FormatWith(typeof(T).Name,
channel.IsCompleted ? "Complete" : "Pending"));
return base.Visitor(channel);
}
protected override UntypedChannel Visitor(ShuntChannel channel)
{
_current = GetVertex(channel.GetHashCode(), () => "Shunt", typeof(ShuntChannel), typeof(object));
if (_stack.Count > 0)
_edges.Add(new Edge(_stack.Peek(), _current, _current.TargetType.Name));
return WithVertex(() => base.Visitor(channel));
}
protected override Channel<T> Visitor<T>(ShuntChannel<T> channel)
{
_current = GetVertex(channel.GetHashCode(), () => "Shunt", typeof(ShuntChannel<T>), typeof(T));
if (_stack.Count > 0)
_edges.Add(new Edge(_stack.Peek(), _current, _current.TargetType.Name));
return WithVertex(() => base.Visitor(channel));
}
protected override Channel<T> Visitor<T>(ChannelAdapter<T> channel)
{
_current = GetVertex(channel.GetHashCode(), () => "Adapter", typeof(ChannelAdapter<T>), typeof(T));
if (_stack.Count > 0)
_edges.Add(new Edge(_stack.Peek(), _current, _current.TargetType.Name));
return WithVertex(() => base.Visitor(channel));
}
protected override Channel<T> Visitor<T>(BroadcastChannel<T> channel)
{
_current = GetVertex(channel.GetHashCode(), () => "Router", typeof(BroadcastChannel<T>), typeof(T));
if (_stack.Count > 0)
_edges.Add(new Edge(_stack.Peek(), _current, _current.TargetType.Name));
return WithVertex(() => base.Visitor(channel));
}
protected override Channel<TInput> Visitor<TInput, TOutput>(ConvertChannel<TInput, TOutput> channel)
{
_current = GetVertex(channel.GetHashCode(), () => "Convert", typeof(ConvertChannel<TInput,TOutput>), typeof(TInput));
if (_stack.Count > 0)
_edges.Add(new Edge(_stack.Peek(), _current, _current.TargetType.Name));
return WithVertex(() => base.Visitor(channel));
}
protected override Channel<T> Visitor<T>(Channel<T> channel)
{
_current = GetVertex(channel.GetHashCode(), () => "Channel", typeof(Channel<T>), typeof(T));
if (_stack.Count > 0)
_edges.Add(new Edge(_stack.Peek(), _current, _current.TargetType.Name));
return WithVertex(() => base.Visitor(channel));
}
protected override UntypedChannel Visitor(UntypedChannel channel)
{
_current = GetVertex(channel.GetHashCode(), () => "UntypedChannel", typeof(UntypedChannel), typeof(object));
if (_stack.Count > 0)
_edges.Add(new Edge(_stack.Peek(), _current, _current.TargetType.Name));
return WithVertex(() => base.Visitor(channel));
}
protected override UntypedChannel Visitor<TFilter>(UntypedFilterChannel<TFilter> channel)
{
_current = GetVertex(channel.GetHashCode(), () => "UntypedFilterChannel", typeof(UntypedFilterChannel<TFilter>), typeof(TFilter));
if (_stack.Count > 0)
_edges.Add(new Edge(_stack.Peek(), _current, _current.TargetType.Name));
return WithVertex(() => base.Visitor(channel));
}
protected override UntypedChannel Visitor(ChannelAdapter channel)
{
_current = GetVertex(channel.GetHashCode(), () => "Adapter", typeof(ChannelAdapter), typeof(object));
if (_stack.Count > 0)
_edges.Add(new Edge(_stack.Peek(), _current, _current.TargetType.Name));
return WithVertex(() => base.Visitor(channel));
}
protected override UntypedChannel Visitor(BroadcastChannel channel)
{
_current = GetVertex(channel.GetHashCode(), () => "Router", typeof(BroadcastChannel), typeof(object));
if (_stack.Count > 0)
_edges.Add(new Edge(_stack.Peek(), _current, _current.TargetType.Name));
return WithVertex(() => base.Visitor(channel));
}
protected override UntypedChannel Visitor<T>(TypedChannelAdapter<T> channel)
{
_current = GetVertex(channel.GetHashCode(), () => "Cast", typeof(TypedChannelAdapter<T>), typeof(T));
if (_stack.Count > 0)
_edges.Add(new Edge(_stack.Peek(), _current, _current.TargetType.Name));
return WithVertex(() => base.Visitor(channel));
}
protected override ChannelProvider<T> Visitor<T>(ChannelProvider<T> provider)
{
Trace.WriteLine("ChannelProvider<{0}>".FormatWith(typeof(T).Name));
return base.Visitor(provider);
}
protected override ChannelProvider<T> Visitor<T>(DelegateChannelProvider<T> provider)
{
_current = GetVertex(provider.GetHashCode(), () => "Provider", typeof(DelegateChannelProvider<T>), typeof(T));
if (_stack.Count > 0)
_edges.Add(new Edge(_current, _stack.Peek(), _current.TargetType.Name));
return WithVertex(() => base.Visitor(provider));
}
protected override ChannelProvider<TChannel> Visitor<TConsumer, TChannel>(
InstanceChannelProvider<TConsumer, TChannel> provider)
{
_current = GetVertex(provider.GetHashCode(), () => "Provider", typeof(InstanceChannelProvider<TConsumer, TChannel>),
typeof(TConsumer));
if (_stack.Count > 0)
_edges.Add(new Edge(_current, _stack.Peek(), _current.TargetType.Name));
return WithVertex(() => base.Visitor(provider));
}
protected override ChannelProvider<T> Visitor<T, TKey>(KeyedChannelProvider<T, TKey> provider)
{
Trace.WriteLine("KeyedChannelProvider<{0}>, Key = {1}".FormatWith(typeof(T).Name, typeof(TKey).Name));
return base.Visitor(provider);
}
protected override ChannelProvider<T> Visitor<T>(ThreadStaticChannelProvider<T> provider)
{
Trace.WriteLine("ThreadStaticChannelProvider<{0}>".FormatWith(typeof(T).Name));
return base.Visitor(provider);
}
protected override InterceptorFactory<T> Visitor<T>(InterceptorFactory<T> factory)
{
Trace.WriteLine("InterceptorFactory<{0}>".FormatWith(typeof(T).Name));
return base.Visitor(factory);
}
}
//
// public class GraphChannkkelVisitor :
// ChannelVisitor
// {
//
// public new void Visit(Pipe pipe)
// {
// base.Visit(pipe);
// }
//
// protected override Pipe VisitInput(InputSegment input)
// {
// _lastNodeVertex = GetSink(input.GetHashCode(), () => "Input", typeof(InputSegment), input.MessageType);
//
// if (_stack.Count > 0)
// _edges.Add(new Edge(_stack.Peek(), _lastNodeVertex, _lastNodeVertex.TargetType.Name));
//
// return Recurse(() => base.VisitInput(input));
// }
//
// protected override Pipe VisitEnd(EndSegment end)
// {
// _lastNodeVertex = GetSink(end.GetHashCode(), () => "End", typeof(EndSegment), end.MessageType);
//
// if (_stack.Count > 0)
// _edges.Add(new Edge(_stack.Peek(), _lastNodeVertex, _lastNodeVertex.TargetType.Name));
//
// return base.VisitEnd(end);
// }
//
// protected override Pipe VisitFilter(FilterSegment filter)
// {
// _lastNodeVertex = GetSink(filter.GetHashCode(), () => "Filter", typeof(FilterSegment), filter.MessageType);
//
// if (_stack.Count > 0)
// _edges.Add(new Edge(_stack.Peek(), _lastNodeVertex, _lastNodeVertex.TargetType.Name));
//
// return Recurse(() => base.VisitFilter(filter));
// }
//
// protected override Pipe VisitInterceptor(InterceptorSegment interceptor)
// {
// _lastNodeVertex = GetSink(interceptor.GetHashCode(), () => "Interceptor", typeof(InterceptorSegment), interceptor.MessageType);
//
// if (_stack.Count > 0)
// _edges.Add(new Edge(_stack.Peek(), _lastNodeVertex, _lastNodeVertex.TargetType.Name));
//
// return Recurse(() => base.VisitInterceptor(interceptor));
// }
//
// protected override Pipe VisitMessageConsumer(MessageConsumerSegment messageConsumer)
// {
// _lastNodeVertex = GetSink(messageConsumer.GetHashCode(), () => "Consumer", typeof(MessageConsumerSegment), messageConsumer.MessageType);
//
// if (_stack.Count > 0)
// _edges.Add(new Edge(_stack.Peek(), _lastNodeVertex, _lastNodeVertex.TargetType.Name));
//
// return Recurse(() => base.VisitMessageConsumer(messageConsumer));
// }
//
// protected override Pipe VisitIntervalMessageConsumer(IntervalMessageConsumerSegment messageConsumer)
// {
// _lastNodeVertex = GetSink(messageConsumer.GetHashCode(), () => "Consumer", typeof(IntervalMessageConsumerSegment), messageConsumer.MessageType);
//
// if (_stack.Count > 0)
// _edges.Add(new Edge(_stack.Peek(), _lastNodeVertex, _lastNodeVertex.TargetType.Name));
//
// return Recurse(() => base.VisitIntervalMessageConsumer(messageConsumer));
// }
//
// protected override Pipe VisitAsyncMessageConsumer(AsyncMessageConsumerSegment messageConsumer)
// {
// _lastNodeVertex = GetSink(messageConsumer.GetHashCode(), () => "Consumer", typeof(AsyncMessageConsumerSegment), messageConsumer.MessageType);
//
// if (_stack.Count > 0)
// _edges.Add(new Edge(_stack.Peek(), _lastNodeVertex, _lastNodeVertex.TargetType.Name));
//
// return Recurse(() => base.VisitAsyncMessageConsumer(messageConsumer));
// }
//
// protected override Pipe VisitRecipientList(RecipientListSegment recipientList)
// {
// _lastNodeVertex = GetSink(recipientList.GetHashCode(), () => "List", typeof(RecipientListSegment), recipientList.MessageType);
//
// if (_stack.Count > 0)
// _edges.Add(new Edge(_stack.Peek(), _lastNodeVertex, _lastNodeVertex.TargetType.Name));
//
// return Recurse(() => base.VisitRecipientList(recipientList));
// }
//
// private Pipe Recurse(Func<Pipe> action)
// {
// _stack.Push(_lastNodeVertex);
//
// Pipe result = action();
//
// _stack.Pop();
//
// return result;
// }
//
// private Vertex GetSink(int key, Func<string> getTitle, Type nodeType, Type objectType)
// {
// return _vertices.Retrieve(key, () =>
// {
// var newSink = new Vertex(nodeType, objectType, getTitle());
//
// return newSink;
// });
// }
// }
// }
}
| |
/*
* MindTouch Dream - a distributed REST framework
* Copyright (C) 2006-2014 MindTouch, Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit mindtouch.com;
* please review the licensing section.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Specialized;
using System.IO;
using System.Net;
using MindTouch.Web;
using MindTouch.Xml;
using NUnit.Framework;
namespace MindTouch.Dream.Test {
[TestFixture]
public class DreamHeadersTests {
private MockServiceInfo _mockService;
private DreamHostInfo _hostInfo;
[TestFixtureTearDown]
public void GlobalTeardown() {
if(_mockService != null) {
_hostInfo.Dispose();
}
}
[Test]
public void Can_parse_bad_namevaluecollection_from_HttpContext() {
var collections = new NameValueCollection {
{ "Cookie", "__utma=134392366.2030730348.1275932450.1276553042.1276556836.19; __utmz=134392366.1276207881.9.3.utmcsr=developer.mindtouch.com|utmccn=(referral)|utmcmd=referral|utmcct=/User:arnec/bugs; _mkto_trk=id:954-WGP-507&token:_mch-mindtouch.com-1270756717014-83706; WRUID=0; __kti=1274382964652" },
{ "Cookie", "http%3A%2F%2Fwww.mindtouch.com%2F" },
{ "Cookie", "; __ktv=2f4-f02d-634b-51e2128b724d7c2; __qca=P0-2102347259-1274460371553; PHPSESSID=307e779182909ab37932b4dffe77c40a; __utmc=134392366; __kts=1274382964673,http%3A%2F%2Fwww.mindtouch.com%2F,; __ktt=631f-d0a2-648e-e0b128b724d7c2; authtoken=\"1_634121336269193470_4254e33b49bc1ee0a72c5716200e296b\"; __utmb=134392366.6.10.1276556836" }
};
Assert.AreEqual(3, collections.GetValues("Cookie").Length);
var headers = new DreamHeaders(collections);
var cookies = headers.Cookies;
Assert.AreEqual(13, cookies.Count);
Assert.AreEqual("__utma", cookies[0].Name);
Assert.AreEqual("134392366.2030730348.1275932450.1276553042.1276556836.19", cookies[0].Value);
Assert.AreEqual("__utmz", cookies[1].Name);
Assert.AreEqual("134392366.1276207881.9.3.utmcsr=developer.mindtouch.com|utmccn=(referral)|utmcmd=referral|utmcct=/User:arnec/bugs", cookies[1].Value);
Assert.AreEqual("_mkto_trk", cookies[2].Name);
Assert.AreEqual("id:954-WGP-507&token:_mch-mindtouch.com-1270756717014-83706", cookies[2].Value);
Assert.AreEqual("WRUID", cookies[3].Name);
Assert.AreEqual("0", cookies[3].Value);
Assert.AreEqual("__kti", cookies[4].Name);
Assert.AreEqual("1274382964652,http%3A%2F%2Fwww.mindtouch.com%2F,", cookies[4].Value);
Assert.AreEqual("__ktv", cookies[5].Name);
Assert.AreEqual("2f4-f02d-634b-51e2128b724d7c2", cookies[5].Value);
Assert.AreEqual("__qca", cookies[6].Name);
Assert.AreEqual("P0-2102347259-1274460371553", cookies[6].Value);
Assert.AreEqual("PHPSESSID", cookies[7].Name);
Assert.AreEqual("307e779182909ab37932b4dffe77c40a", cookies[7].Value);
Assert.AreEqual("__utmc", cookies[8].Name);
Assert.AreEqual("134392366", cookies[8].Value);
Assert.AreEqual("__kts", cookies[9].Name);
Assert.AreEqual("1274382964673,http%3A%2F%2Fwww.mindtouch.com%2F,", cookies[9].Value);
Assert.AreEqual("__ktt", cookies[10].Name);
Assert.AreEqual("631f-d0a2-648e-e0b128b724d7c2", cookies[10].Value);
Assert.AreEqual("authtoken", cookies[11].Name);
Assert.AreEqual("1_634121336269193470_4254e33b49bc1ee0a72c5716200e296b", cookies[11].Value);
Assert.AreEqual("__utmb", cookies[12].Name);
Assert.AreEqual("134392366.6.10.1276556836", cookies[12].Value);
}
[Test]
public void Preserve_order_of_hosts_in_forwarded_for_header() {
// X-Forwarded-For
var collections = new NameValueCollection();
collections.Add("X-Forwarded-For", "a, b, c");
collections.Add("X-Forwarded-For", "d, e");
collections.Add("X-Forwarded-For", "f, g, h");
var headers = new DreamHeaders(collections);
var values = headers.ForwardedFor;
Assert.AreEqual(new[] { "a", "b", "c", "d", "e", "f", "g", "h" }, values);
}
[Test]
public void Parsing_quoted_etag_removes_quotes() {
var etag = "dsfsdfsdfsdfsdf";
var rawHeaders = new NameValueCollection { { "etag", "\"" + etag + "\"" } };
var headers = new DreamHeaders(rawHeaders);
Assert.AreEqual(etag, headers.ETag);
}
[Test]
public void Parsing_single_quoted_etag_removes_quotes() {
var etag = "dsfsdfsdfsdfsdf";
var rawHeaders = new NameValueCollection { { "etag", "'" + etag + "'" } };
var headers = new DreamHeaders(rawHeaders);
Assert.AreEqual(etag, headers.ETag);
}
[Test]
public void Parsing_unquoted_etag_does_not_alter_etag() {
var etag = "dsfsdfsdfsdfsdf";
var rawHeaders = new NameValueCollection { { "etag", etag } };
var headers = new DreamHeaders(rawHeaders);
Assert.AreEqual(etag, headers.ETag);
}
[Test]
public void Parsing_quoted_IfNoneMatch_removes_quotes() {
var ifNoneMatch = "dsfsdfsdfsdfsdf";
var rawHeaders = new NameValueCollection { { DreamHeaders.IF_NONE_MATCH, "\"" + ifNoneMatch + "\"" } };
var headers = new DreamHeaders(rawHeaders);
Assert.AreEqual(ifNoneMatch, headers.IfNoneMatch);
}
[Test]
public void Parsing_single_quoted_IfNoneMatch_removes_quotes() {
var ifNoneMatch = "dsfsdfsdfsdfsdf";
var rawHeaders = new NameValueCollection { { DreamHeaders.IF_NONE_MATCH, "'" + ifNoneMatch + "'" } };
var headers = new DreamHeaders(rawHeaders);
Assert.AreEqual(ifNoneMatch, headers.IfNoneMatch);
}
[Test]
public void Parsing_unquoted_IfNoneMatch_does_not_alter_etag() {
var ifNoneMatch = "dsfsdfsdfsdfsdf";
var rawHeaders = new NameValueCollection { { DreamHeaders.IF_NONE_MATCH, ifNoneMatch } };
var headers = new DreamHeaders(rawHeaders);
Assert.AreEqual(ifNoneMatch, headers.IfNoneMatch);
}
[Test]
public void Rendering_etag_quotes_unquoted_value() {
var etag = "dsfsdfsdfsdfsdf";
var headers = new DreamHeaders { ETag = etag };
var httpRequest = (HttpWebRequest)WebRequest.Create("http://localhost");
HttpUtil.AddHeader(httpRequest, DreamHeaders.ETAG, headers.ETag);
Assert.AreEqual("\"" + etag + "\"", httpRequest.Headers[DreamHeaders.ETAG]);
}
[Test]
public void Rendering_etag_leaves_quotes_value_alone() {
var etag = "dsfsdfsdfsdfsdf";
var headers = new DreamHeaders { ETag = "\"" + etag + "\"" };
var httpRequest = (HttpWebRequest)WebRequest.Create("http://localhost");
HttpUtil.AddHeader(httpRequest, DreamHeaders.ETAG, headers.ETag);
Assert.AreEqual("\"" + etag + "\"", httpRequest.Headers[DreamHeaders.ETAG]);
}
[Test]
public void Rendering_etag_leaves_single_quoted_value_alone() {
var etag = "dsfsdfsdfsdfsdf";
var headers = new DreamHeaders { ETag = "'" + etag + "'" };
var httpRequest = (HttpWebRequest)WebRequest.Create("http://localhost");
HttpUtil.AddHeader(httpRequest, DreamHeaders.ETAG, headers.ETag);
Assert.AreEqual("'" + etag + "'", httpRequest.Headers[DreamHeaders.ETAG]);
}
[Test]
public void Incoming_IfNoneMatch_is_unquoted() {
var hostinfo = DreamTestHelper.CreateRandomPortHost(new XDoc("config"));
var mockService = MockService.CreateMockService(hostinfo);
mockService.Service.CatchAllCallback = (ctx, req, res) => res.Return(DreamMessage.Ok(MimeType.TEXT, req.Headers.IfNoneMatch));
var request = WebRequest.Create(mockService.AtLocalHost.ToString());
request.Headers[DreamHeaders.IF_NONE_MATCH] = "\"foo\"";
var response = request.GetResponse();
var reader = new StreamReader(response.GetResponseStream());
var content = reader.ReadToEnd();
Assert.AreEqual("foo", content);
}
[Test]
public void Outgoing_Etag_is_quoted() {
var mockService = GetMockService();
mockService.Service.CatchAllCallback = (ctx, req, res) => {
var msg = DreamMessage.Ok();
msg.Headers.ETag = "foo";
res.Return(msg);
};
var request = WebRequest.Create(mockService.AtLocalHost.ToString());
var response = request.GetResponse();
Assert.AreEqual("\"foo\"", response.Headers[DreamHeaders.ETAG]);
}
private MockServiceInfo GetMockService() {
if(_mockService == null) {
_hostInfo = DreamTestHelper.CreateRandomPortHost(new XDoc("config"));
_mockService = MockService.CreateMockService(_hostInfo);
}
return _mockService;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Management.Automation;
using Microsoft.Management.Infrastructure;
using Microsoft.Management.Infrastructure.Options;
using Microsoft.PowerShell.Cim;
using Dbg = System.Management.Automation.Diagnostics;
namespace Microsoft.PowerShell.Cmdletization.Cim
{
/// <summary>
/// Job wrapping invocation of an extrinsic CIM method.
/// </summary>
internal abstract class MethodInvocationJobBase<T> : CimChildJobBase<T>
{
internal MethodInvocationJobBase(CimJobContext jobContext, bool passThru, string methodSubject, MethodInvocationInfo methodInvocationInfo)
: base(jobContext)
{
Dbg.Assert(methodInvocationInfo != null, "Caller should verify methodInvocationInfo != null");
Dbg.Assert(methodSubject != null, "Caller should verify methodSubject != null");
_passThru = passThru;
MethodSubject = methodSubject;
_methodInvocationInfo = methodInvocationInfo;
}
private readonly bool _passThru;
private readonly MethodInvocationInfo _methodInvocationInfo;
internal string MethodName
{
get { return _methodInvocationInfo.MethodName; }
}
private const string CustomOperationOptionPrefix = "cim:operationOption:";
private IEnumerable<MethodParameter> GetMethodInputParametersCore(Func<MethodParameter, bool> filter)
{
IEnumerable<MethodParameter> inputParameters = _methodInvocationInfo.Parameters.Where(filter);
var result = new List<MethodParameter>();
foreach (MethodParameter inputParameter in inputParameters)
{
object cimValue = CimSensitiveValueConverter.ConvertFromDotNetToCim(inputParameter.Value);
Type cimType = CimSensitiveValueConverter.GetCimType(inputParameter.ParameterType);
CimValueConverter.AssertIntrinsicCimType(cimType);
result.Add(new MethodParameter
{
Name = inputParameter.Name,
ParameterType = cimType,
Bindings = inputParameter.Bindings,
Value = cimValue,
IsValuePresent = inputParameter.IsValuePresent
});
}
return result;
}
internal IEnumerable<MethodParameter> GetMethodInputParameters()
{
var allMethodParameters = this.GetMethodInputParametersCore(p => !p.Name.StartsWith(CustomOperationOptionPrefix, StringComparison.OrdinalIgnoreCase));
var methodParametersWithInputValue = allMethodParameters.Where(p => p.IsValuePresent);
return methodParametersWithInputValue;
}
internal IEnumerable<CimInstance> GetCimInstancesFromArguments()
{
return _methodInvocationInfo.GetArgumentsOfType<CimInstance>();
}
internal override CimCustomOptionsDictionary CalculateJobSpecificCustomOptions()
{
IDictionary<string, object> result = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
IEnumerable<MethodParameter> customOptions = this
.GetMethodInputParametersCore(p => p.Name.StartsWith(CustomOperationOptionPrefix, StringComparison.OrdinalIgnoreCase));
foreach (MethodParameter customOption in customOptions)
{
if (customOption.Value == null)
{
continue;
}
result.Add(customOption.Name.Substring(CustomOperationOptionPrefix.Length), customOption.Value);
}
return CimCustomOptionsDictionary.Create(result);
}
internal IEnumerable<MethodParameter> GetMethodOutputParameters()
{
IEnumerable<MethodParameter> allParameters_plus_returnValue = _methodInvocationInfo.Parameters;
if (_methodInvocationInfo.ReturnValue != null)
{
allParameters_plus_returnValue = allParameters_plus_returnValue.Append(_methodInvocationInfo.ReturnValue);
}
var outParameters = allParameters_plus_returnValue
.Where(p => (0 != (p.Bindings & (MethodParameterBindings.Out | MethodParameterBindings.Error))));
return outParameters;
}
internal string MethodSubject { get; }
internal bool ShouldProcess()
{
Dbg.Assert(this.MethodSubject != null, "MethodSubject property should be initialized before starting main job processing");
if (!this.JobContext.CmdletInvocationContext.CmdletDefinitionContext.ClientSideShouldProcess)
{
return true;
}
bool shouldProcess;
if (!this.JobContext.SupportsShouldProcess)
{
shouldProcess = true;
this.WriteVerboseStartOfCimOperation();
}
else
{
string target = this.MethodSubject;
string action = this.MethodName;
CimResponseType cimResponseType = this.ShouldProcess(target, action);
switch (cimResponseType)
{
case CimResponseType.Yes:
case CimResponseType.YesToAll:
shouldProcess = true;
break;
default:
shouldProcess = false;
break;
}
}
if (!shouldProcess)
{
this.SetCompletedJobState(JobState.Completed, null);
}
return shouldProcess;
}
#region PassThru functionality
internal abstract object PassThruObject { get; }
internal bool IsPassThruObjectNeeded()
{
return (_passThru) && (!this.DidUserSuppressTheOperation) && (!this.JobHadErrors);
}
public override void OnCompleted()
{
this.ExceptionSafeWrapper(
delegate
{
Dbg.Assert(this.MethodSubject != null, "MethodSubject property should be initialized before starting main job processing");
if (this.IsPassThruObjectNeeded())
{
object passThruObject = this.PassThruObject;
if (passThruObject != null)
{
this.WriteObject(passThruObject);
}
}
});
base.OnCompleted();
}
#endregion
#region Job descriptions
internal override string Description
{
get
{
return string.Format(
CultureInfo.InvariantCulture,
CmdletizationResources.CimJob_MethodDescription,
this.MethodSubject,
this.MethodName);
}
}
internal override string FailSafeDescription
{
get
{
return string.Format(
CultureInfo.InvariantCulture,
CmdletizationResources.CimJob_SafeMethodDescription,
this.JobContext.CmdletizationClassName,
this.JobContext.Session.ComputerName,
this.MethodName);
}
}
#endregion
}
}
| |
using System;
using System.Data;
using Csla;
using Csla.Data;
using SelfLoadSoftDelete.DataAccess;
using SelfLoadSoftDelete.DataAccess.ERLevel;
namespace SelfLoadSoftDelete.Business.ERLevel
{
/// <summary>
/// G02_Continent (editable root object).<br/>
/// This is a generated base class of <see cref="G02_Continent"/> business object.
/// </summary>
/// <remarks>
/// This class contains one child collection:<br/>
/// - <see cref="G03_SubContinentObjects"/> of type <see cref="G03_SubContinentColl"/> (1:M relation to <see cref="G04_SubContinent"/>)
/// </remarks>
[Serializable]
public partial class G02_Continent : BusinessBase<G02_Continent>
{
#region Static Fields
private static int _lastID;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Continent_ID"/> property.
/// </summary>
public static readonly PropertyInfo<int> Continent_IDProperty = RegisterProperty<int>(p => p.Continent_ID, "Continents ID");
/// <summary>
/// Gets the Continents ID.
/// </summary>
/// <value>The Continents ID.</value>
public int Continent_ID
{
get { return GetProperty(Continent_IDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="Continent_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Continent_NameProperty = RegisterProperty<string>(p => p.Continent_Name, "Continents Name");
/// <summary>
/// Gets or sets the Continents Name.
/// </summary>
/// <value>The Continents Name.</value>
public string Continent_Name
{
get { return GetProperty(Continent_NameProperty); }
set { SetProperty(Continent_NameProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="G03_Continent_SingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<G03_Continent_Child> G03_Continent_SingleObjectProperty = RegisterProperty<G03_Continent_Child>(p => p.G03_Continent_SingleObject, "G03 Continent Single Object", RelationshipTypes.Child);
/// <summary>
/// Gets the G03 Continent Single Object ("self load" child property).
/// </summary>
/// <value>The G03 Continent Single Object.</value>
public G03_Continent_Child G03_Continent_SingleObject
{
get { return GetProperty(G03_Continent_SingleObjectProperty); }
private set { LoadProperty(G03_Continent_SingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="G03_Continent_ASingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<G03_Continent_ReChild> G03_Continent_ASingleObjectProperty = RegisterProperty<G03_Continent_ReChild>(p => p.G03_Continent_ASingleObject, "G03 Continent ASingle Object", RelationshipTypes.Child);
/// <summary>
/// Gets the G03 Continent ASingle Object ("self load" child property).
/// </summary>
/// <value>The G03 Continent ASingle Object.</value>
public G03_Continent_ReChild G03_Continent_ASingleObject
{
get { return GetProperty(G03_Continent_ASingleObjectProperty); }
private set { LoadProperty(G03_Continent_ASingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="G03_SubContinentObjects"/> property.
/// </summary>
public static readonly PropertyInfo<G03_SubContinentColl> G03_SubContinentObjectsProperty = RegisterProperty<G03_SubContinentColl>(p => p.G03_SubContinentObjects, "G03 SubContinent Objects", RelationshipTypes.Child);
/// <summary>
/// Gets the G03 Sub Continent Objects ("self load" child property).
/// </summary>
/// <value>The G03 Sub Continent Objects.</value>
public G03_SubContinentColl G03_SubContinentObjects
{
get { return GetProperty(G03_SubContinentObjectsProperty); }
private set { LoadProperty(G03_SubContinentObjectsProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="G02_Continent"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="G02_Continent"/> object.</returns>
public static G02_Continent NewG02_Continent()
{
return DataPortal.Create<G02_Continent>();
}
/// <summary>
/// Factory method. Loads a <see cref="G02_Continent"/> object, based on given parameters.
/// </summary>
/// <param name="continent_ID">The Continent_ID parameter of the G02_Continent to fetch.</param>
/// <returns>A reference to the fetched <see cref="G02_Continent"/> object.</returns>
public static G02_Continent GetG02_Continent(int continent_ID)
{
return DataPortal.Fetch<G02_Continent>(continent_ID);
}
/// <summary>
/// Factory method. Deletes a <see cref="G02_Continent"/> object, based on given parameters.
/// </summary>
/// <param name="continent_ID">The Continent_ID of the G02_Continent to delete.</param>
public static void DeleteG02_Continent(int continent_ID)
{
DataPortal.Delete<G02_Continent>(continent_ID);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="G02_Continent"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public G02_Continent()
{
// Use factory methods and do not use direct creation.
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="G02_Continent"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void DataPortal_Create()
{
LoadProperty(Continent_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID));
LoadProperty(G03_Continent_SingleObjectProperty, DataPortal.CreateChild<G03_Continent_Child>());
LoadProperty(G03_Continent_ASingleObjectProperty, DataPortal.CreateChild<G03_Continent_ReChild>());
LoadProperty(G03_SubContinentObjectsProperty, DataPortal.CreateChild<G03_SubContinentColl>());
var args = new DataPortalHookArgs();
OnCreate(args);
base.DataPortal_Create();
}
/// <summary>
/// Loads a <see cref="G02_Continent"/> object from the database, based on given criteria.
/// </summary>
/// <param name="continent_ID">The Continent ID.</param>
protected void DataPortal_Fetch(int continent_ID)
{
var args = new DataPortalHookArgs(continent_ID);
OnFetchPre(args);
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var dal = dalManager.GetProvider<IG02_ContinentDal>();
var data = dal.Fetch(continent_ID);
Fetch(data);
}
OnFetchPost(args);
FetchChildren();
// check all object rules and property rules
BusinessRules.CheckRules();
}
private void Fetch(IDataReader data)
{
using (var dr = new SafeDataReader(data))
{
if (dr.Read())
{
Fetch(dr);
}
}
}
/// <summary>
/// Loads a <see cref="G02_Continent"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Continent_IDProperty, dr.GetInt32("Continent_ID"));
LoadProperty(Continent_NameProperty, dr.GetString("Continent_Name"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Loads child objects.
/// </summary>
private void FetchChildren()
{
LoadProperty(G03_Continent_SingleObjectProperty, G03_Continent_Child.GetG03_Continent_Child(Continent_ID));
LoadProperty(G03_Continent_ASingleObjectProperty, G03_Continent_ReChild.GetG03_Continent_ReChild(Continent_ID));
LoadProperty(G03_SubContinentObjectsProperty, G03_SubContinentColl.GetG03_SubContinentColl(Continent_ID));
}
/// <summary>
/// Inserts a new <see cref="G02_Continent"/> object in the database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Insert()
{
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
OnInsertPre(args);
var dal = dalManager.GetProvider<IG02_ContinentDal>();
using (BypassPropertyChecks)
{
int continent_ID = -1;
dal.Insert(
out continent_ID,
Continent_Name
);
LoadProperty(Continent_IDProperty, continent_ID);
}
OnInsertPost(args);
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="G02_Continent"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Update()
{
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
OnUpdatePre(args);
var dal = dalManager.GetProvider<IG02_ContinentDal>();
using (BypassPropertyChecks)
{
dal.Update(
Continent_ID,
Continent_Name
);
}
OnUpdatePost(args);
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Self deletes the <see cref="G02_Continent"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_DeleteSelf()
{
DataPortal_Delete(Continent_ID);
}
/// <summary>
/// Deletes the <see cref="G02_Continent"/> object from database.
/// </summary>
/// <param name="continent_ID">The Continent ID.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void DataPortal_Delete(int continent_ID)
{
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
// flushes all pending data operations
FieldManager.UpdateChildren(this);
OnDeletePre(args);
var dal = dalManager.GetProvider<IG02_ContinentDal>();
using (BypassPropertyChecks)
{
dal.Delete(continent_ID);
}
OnDeletePost(args);
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
//---------------------------------------------------------------------
// <copyright file="FunctionImportMappingComposable.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner willa
//---------------------------------------------------------------------
using System.Collections.Generic;
using System.Data.Common;
using System.Data.Common.CommandTrees;
using System.Data.Common.CommandTrees.ExpressionBuilder;
using System.Data.Common.Utils;
using System.Data.Mapping.ViewGeneration;
using System.Data.Metadata.Edm;
using System.Data.Query.InternalTrees;
using System.Data.Query.PlanCompiler;
using System.Diagnostics;
using System.Linq;
namespace System.Data.Mapping
{
/// <summary>
/// Represents a mapping from a model function import to a store composable function.
/// </summary>
internal class FunctionImportMappingComposable : FunctionImportMapping
{
#region Constructors
internal FunctionImportMappingComposable(
EdmFunction functionImport,
EdmFunction targetFunction,
List<Tuple<StructuralType, List<StorageConditionPropertyMapping>, List<StoragePropertyMapping>>> structuralTypeMappings,
EdmProperty[] targetFunctionKeys,
StorageMappingItemCollection mappingItemCollection,
string sourceLocation,
LineInfo lineInfo)
: base(functionImport, targetFunction)
{
EntityUtil.CheckArgumentNull(mappingItemCollection, "mappingItemCollection");
Debug.Assert(functionImport.IsComposableAttribute, "functionImport.IsComposableAttribute");
Debug.Assert(targetFunction.IsComposableAttribute, "targetFunction.IsComposableAttribute");
Debug.Assert(functionImport.EntitySet == null || structuralTypeMappings != null, "Function import returning entities must have structuralTypeMappings.");
Debug.Assert(structuralTypeMappings == null || structuralTypeMappings.Count > 0, "Non-null structuralTypeMappings must not be empty.");
EdmType resultType;
Debug.Assert(
structuralTypeMappings != null ||
MetadataHelper.TryGetFunctionImportReturnType<EdmType>(functionImport, 0, out resultType) && TypeSemantics.IsScalarType(resultType),
"Either type mappings should be specified or the function import should be Collection(Scalar).");
Debug.Assert(functionImport.EntitySet == null || targetFunctionKeys != null, "Keys must be inferred for a function import returning entities.");
Debug.Assert(targetFunctionKeys == null || targetFunctionKeys.Length > 0, "Keys must be null or non-empty.");
m_mappingItemCollection = mappingItemCollection;
// We will use these parameters to target s-space function calls in the generated command tree.
// Since enums don't exist in s-space we need to use the underlying type.
m_commandParameters = functionImport.Parameters.Select(p => TypeHelpers.GetPrimitiveTypeUsageForScalar(p.TypeUsage).Parameter(p.Name)).ToArray();
m_structuralTypeMappings = structuralTypeMappings;
m_targetFunctionKeys = targetFunctionKeys;
m_sourceLocation = sourceLocation;
m_lineInfo = lineInfo;
}
#endregion
#region Fields
private readonly StorageMappingItemCollection m_mappingItemCollection;
/// <summary>
/// Command parameter refs created from m_edmFunction parameters.
/// Used as arguments to target (s-space) function calls in the generated command tree.
/// </summary>
private readonly DbParameterReferenceExpression[] m_commandParameters;
/// <summary>
/// Result mapping as entity type hierarchy.
/// </summary>
private readonly List<Tuple<StructuralType, List<StorageConditionPropertyMapping>, List<StoragePropertyMapping>>> m_structuralTypeMappings;
/// <summary>
/// Keys inside the result set of the target function. Inferred based on the mapping (using c-space entity type keys).
/// </summary>
private readonly EdmProperty[] m_targetFunctionKeys;
/// <summary>
/// ITree template. Requires function argument substitution during function view expansion.
/// </summary>
private Node m_internalTreeNode;
private readonly string m_sourceLocation;
private readonly LineInfo m_lineInfo;
#endregion
#region Properties/Methods
internal EdmProperty[] TvfKeys
{
get { return m_targetFunctionKeys; }
}
#region GetInternalTree(...) implementation
internal Node GetInternalTree(Command targetIqtCommand, IList<Node> targetIqtArguments)
{
if (m_internalTreeNode == null)
{
var viewGenErrors = new List<EdmSchemaError>();
DiscriminatorMap discriminatorMap;
DbQueryCommandTree tree = GenerateFunctionView(viewGenErrors, out discriminatorMap);
if (viewGenErrors.Count > 0)
{
throw new MappingException(Helper.CombineErrorMessage(viewGenErrors));
}
Debug.Assert(tree != null, "tree != null");
// Convert this into an ITree first
Command itree = ITreeGenerator.Generate(tree, discriminatorMap);
var rootProject = itree.Root; // PhysicalProject(RelInput)
PlanCompiler.Assert(rootProject.Op.OpType == OpType.PhysicalProject, "Expected a physical projectOp at the root of the tree - found " + rootProject.Op.OpType);
var rootProjectOp = (PhysicalProjectOp)rootProject.Op;
Debug.Assert(rootProjectOp.Outputs.Count == 1, "rootProjectOp.Outputs.Count == 1");
var rootInput = rootProject.Child0; // the RelInput in PhysicalProject(RelInput)
// #554756: VarVec enumerators are not cached on the shared Command instance.
itree.DisableVarVecEnumCaching();
// Function import returns a collection, so convert it to a scalar by wrapping into CollectOp.
Node relNode = rootInput;
Var relVar = rootProjectOp.Outputs[0];
// ProjectOp does not implement Type property, so get the type from the column map.
TypeUsage functionViewType = rootProjectOp.ColumnMap.Type;
if (!Command.EqualTypes(functionViewType, this.FunctionImport.ReturnParameter.TypeUsage))
{
Debug.Assert(TypeSemantics.IsPromotableTo(functionViewType, this.FunctionImport.ReturnParameter.TypeUsage), "Mapping expression result type must be promotable to the c-space function return type.");
// Build "relNode = Project(relNode, SoftCast(relVar))"
CollectionType expectedCollectionType = (CollectionType)this.FunctionImport.ReturnParameter.TypeUsage.EdmType;
var expectedElementType = expectedCollectionType.TypeUsage;
Node varRefNode = itree.CreateNode(itree.CreateVarRefOp(relVar));
Node castNode = itree.CreateNode(itree.CreateSoftCastOp(expectedElementType), varRefNode);
Node varDefListNode = itree.CreateVarDefListNode(castNode, out relVar);
ProjectOp projectOp = itree.CreateProjectOp(relVar);
relNode = itree.CreateNode(projectOp, relNode, varDefListNode);
}
// Build "Collect(PhysicalProject(relNode))
m_internalTreeNode = itree.BuildCollect(relNode, relVar);
}
Debug.Assert(m_internalTreeNode != null, "m_internalTreeNode != null");
// Prepare argument replacement dictionary
Debug.Assert(m_commandParameters.Length == targetIqtArguments.Count, "m_commandParameters.Length == targetIqtArguments.Count");
Dictionary<string, Node> viewArguments = new Dictionary<string, Node>(m_commandParameters.Length);
for (int i = 0; i < m_commandParameters.Length; ++i)
{
var commandParam = (DbParameterReferenceExpression)m_commandParameters[i];
var argumentNode = targetIqtArguments[i];
// If function import parameter is of enum type, the argument value for it will be of enum type. We however have
// converted enum types to underlying types for m_commandParameters. So we now need to softcast the argument
// expression to the underlying type as well.
if (TypeSemantics.IsEnumerationType(argumentNode.Op.Type))
{
argumentNode = targetIqtCommand.CreateNode(
targetIqtCommand.CreateSoftCastOp(TypeHelpers.CreateEnumUnderlyingTypeUsage(argumentNode.Op.Type)),
argumentNode);
}
Debug.Assert(TypeSemantics.IsPromotableTo(argumentNode.Op.Type, commandParam.ResultType), "Argument type must be promotable to parameter type.");
viewArguments.Add(commandParam.ParameterName, argumentNode);
}
return FunctionViewOpCopier.Copy(targetIqtCommand, m_internalTreeNode, viewArguments);
}
private sealed class FunctionViewOpCopier : OpCopier
{
private Dictionary<string, Node> m_viewArguments;
private FunctionViewOpCopier(Command cmd, Dictionary<string, Node> viewArguments)
: base(cmd)
{
m_viewArguments = viewArguments;
}
internal static Node Copy(Command cmd, Node viewNode, Dictionary<string, Node> viewArguments)
{
return new FunctionViewOpCopier(cmd, viewArguments).CopyNode(viewNode);
}
#region Visitor Members
public override Node Visit(VarRefOp op, Node n)
{
// The original function view has store function calls with arguments represented as command parameter refs.
// We are now replacing command parameter refs with the real argument nodes from the calling tree.
// The replacement is performed in the function view subtree and we search for parameter refs with names
// matching the FunctionImportMapping.FunctionImport parameter names (this is how the command parameters
// have been created in the first place, see m_commandParameters and GetCommandTree(...) for more info).
// The search and replace is not performed on the argument nodes themselves. This is important because it guarantees
// that we are not replacing unrelated (possibly user-defined) parameter refs that accidentally have the matching names.
Node argNode;
if (op.Var.VarType == VarType.Parameter && m_viewArguments.TryGetValue(((ParameterVar)op.Var).ParameterName, out argNode))
{
// Just copy the argNode, do not reapply this visitor. We do not want search and replace inside the argNode. See comment above.
return OpCopier.Copy(m_destCmd, argNode);
}
else
{
return base.Visit(op, n);
}
}
#endregion
}
#endregion
#region GenerateFunctionView(...) implementation
#region GenerateFunctionView
internal DbQueryCommandTree GenerateFunctionView(IList<EdmSchemaError> errors, out DiscriminatorMap discriminatorMap)
{
Debug.Assert(errors != null, "errors != null");
discriminatorMap = null;
// Prepare the direct call of the store function as StoreFunction(@EdmFunc_p1, ..., @EdmFunc_pN).
// Note that function call arguments are command parameters created from the m_edmFunction parameters.
Debug.Assert(this.TargetFunction != null, "this.TargetFunction != null");
DbExpression storeFunctionInvoke = this.TargetFunction.Invoke(GetParametersForTargetFunctionCall());
// Generate the query expression producing c-space result from s-space function call(s).
DbExpression queryExpression;
if (m_structuralTypeMappings != null)
{
queryExpression = GenerateStructuralTypeResultMappingView(storeFunctionInvoke, errors, out discriminatorMap);
Debug.Assert(queryExpression == null ||
TypeSemantics.IsPromotableTo(queryExpression.ResultType, this.FunctionImport.ReturnParameter.TypeUsage),
"TypeSemantics.IsPromotableTo(queryExpression.ResultType, this.FunctionImport.ReturnParameter.TypeUsage)");
}
else
{
queryExpression = GenerateScalarResultMappingView(storeFunctionInvoke);
Debug.Assert(queryExpression == null ||
TypeSemantics.IsEqual(queryExpression.ResultType, this.FunctionImport.ReturnParameter.TypeUsage),
"TypeSemantics.IsEqual(queryExpression.ResultType, this.FunctionImport.ReturnParameter.TypeUsage)");
}
if (queryExpression == null)
{
// In case of errors during view generation, return.
return null;
}
// Generate parameterized command, where command parameters are semantically the c-space function parameters.
return DbQueryCommandTree.FromValidExpression(m_mappingItemCollection.Workspace, TargetPerspective.TargetPerspectiveDataSpace, queryExpression);
}
private IEnumerable<DbExpression> GetParametersForTargetFunctionCall()
{
Debug.Assert(this.FunctionImport.Parameters.Count == m_commandParameters.Length, "this.FunctionImport.Parameters.Count == m_commandParameters.Length");
Debug.Assert(this.TargetFunction.Parameters.Count == m_commandParameters.Length, "this.TargetFunction.Parameters.Count == m_commandParameters.Length");
foreach (var targetParameter in this.TargetFunction.Parameters)
{
Debug.Assert(this.FunctionImport.Parameters.Contains(targetParameter.Name), "this.FunctionImport.Parameters.Contains(targetParameter.Name)");
var functionImportParameter = this.FunctionImport.Parameters.Single(p => p.Name == targetParameter.Name);
yield return m_commandParameters[this.FunctionImport.Parameters.IndexOf(functionImportParameter)];
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] // referenced by System.Data.Entity.Design.dll
internal void ValidateFunctionView(IList<EdmSchemaError> errors)
{
DiscriminatorMap dm;
GenerateFunctionView(errors, out dm);
}
#endregion
#region GenerateStructuralTypeResultMappingView
private DbExpression GenerateStructuralTypeResultMappingView(DbExpression storeFunctionInvoke, IList<EdmSchemaError> errors, out DiscriminatorMap discriminatorMap)
{
Debug.Assert(m_structuralTypeMappings != null && m_structuralTypeMappings.Count > 0, "m_structuralTypeMappings != null && m_structuralTypeMappings.Count > 0");
discriminatorMap = null;
// Process explicit structural type mappings. The mapping is based on the direct call of the store function
// wrapped into a projection constructing the mapped structural types.
DbExpression queryExpression = storeFunctionInvoke;
if (m_structuralTypeMappings.Count == 1)
{
var mapping = m_structuralTypeMappings[0];
var type = mapping.Item1;
var conditions = mapping.Item2;
var propertyMappings = mapping.Item3;
if (conditions.Count > 0)
{
queryExpression = queryExpression.Where((row) => GenerateStructuralTypeConditionsPredicate(conditions, row));
}
var binding = queryExpression.BindAs("row");
var entityTypeMappingView = GenerateStructuralTypeMappingView(type, propertyMappings, binding.Variable, errors);
if (entityTypeMappingView == null)
{
return null;
}
queryExpression = binding.Project(entityTypeMappingView);
}
else
{
var binding = queryExpression.BindAs("row");
// Make sure type projection is performed over a closed set where each row is guaranteed to produce a known type.
// To do this, filter the store function output using the type conditions.
Debug.Assert(m_structuralTypeMappings.All(m => m.Item2.Count > 0), "In multi-type mapping each type must have conditions.");
List<DbExpression> structuralTypePredicates = m_structuralTypeMappings.Select(m => GenerateStructuralTypeConditionsPredicate(m.Item2, binding.Variable)).ToList();
queryExpression = binding.Filter(Helpers.BuildBalancedTreeInPlace(
structuralTypePredicates.ToArray(), // clone, otherwise BuildBalancedTreeInPlace will change it
(prev, next) => prev.Or(next)));
binding = queryExpression.BindAs("row");
List<DbExpression> structuralTypeMappingViews = new List<DbExpression>(m_structuralTypeMappings.Count);
foreach (var mapping in m_structuralTypeMappings)
{
var type = mapping.Item1;
var propertyMappings = mapping.Item3;
var structuralTypeMappingView = GenerateStructuralTypeMappingView(type, propertyMappings, binding.Variable, errors);
if (structuralTypeMappingView == null)
{
continue;
}
else
{
structuralTypeMappingViews.Add(structuralTypeMappingView);
}
}
Debug.Assert(structuralTypeMappingViews.Count == structuralTypePredicates.Count, "structuralTypeMappingViews.Count == structuralTypePredicates.Count");
if (structuralTypeMappingViews.Count != m_structuralTypeMappings.Count)
{
Debug.Assert(errors.Count > 0, "errors.Count > 0");
return null;
}
// Because we are projecting over the closed set, we can convert the last WHEN THEN into ELSE.
DbExpression typeConstructors = DbExpressionBuilder.Case(
structuralTypePredicates.Take(m_structuralTypeMappings.Count - 1),
structuralTypeMappingViews.Take(m_structuralTypeMappings.Count - 1),
structuralTypeMappingViews[m_structuralTypeMappings.Count - 1]);
queryExpression = binding.Project(typeConstructors);
if (DiscriminatorMap.TryCreateDiscriminatorMap(this.FunctionImport.EntitySet, queryExpression, out discriminatorMap))
{
Debug.Assert(discriminatorMap != null, "discriminatorMap == null after it has been created");
}
}
return queryExpression;
}
private DbExpression GenerateStructuralTypeMappingView(StructuralType structuralType, List<StoragePropertyMapping> propertyMappings, DbExpression row, IList<EdmSchemaError> errors)
{
// Generate property views.
var properties = TypeHelpers.GetAllStructuralMembers(structuralType);
Debug.Assert(properties.Count == propertyMappings.Count, "properties.Count == propertyMappings.Count");
var constructorArgs = new List<DbExpression>(properties.Count);
for (int i = 0; i < propertyMappings.Count; ++i)
{
var propertyMapping = propertyMappings[i];
Debug.Assert(properties[i].EdmEquals(propertyMapping.EdmProperty), "properties[i].EdmEquals(propertyMapping.EdmProperty)");
var propertyMappingView = GeneratePropertyMappingView(propertyMapping, row, new List<string>() { propertyMapping.EdmProperty.Name }, errors);
if (propertyMappingView != null)
{
constructorArgs.Add(propertyMappingView);
}
}
if (constructorArgs.Count != propertyMappings.Count)
{
Debug.Assert(errors.Count > 0, "errors.Count > 0");
return null;
}
else
{
// Return the structural type constructor.
return TypeUsage.Create(structuralType).New(constructorArgs);
}
}
private DbExpression GenerateStructuralTypeConditionsPredicate(List<StorageConditionPropertyMapping> conditions, DbExpression row)
{
Debug.Assert(conditions.Count > 0, "conditions.Count > 0");
DbExpression predicate = Helpers.BuildBalancedTreeInPlace(conditions.Select(c => GeneratePredicate(c, row)).ToArray(), (prev, next) => prev.And(next));
return predicate;
}
private DbExpression GeneratePredicate(StorageConditionPropertyMapping condition, DbExpression row)
{
Debug.Assert(condition.EdmProperty == null, "C-side conditions are not supported in function mappings.");
DbExpression columnRef = GenerateColumnRef(row, condition.ColumnProperty);
if (condition.IsNull.HasValue)
{
return condition.IsNull.Value ? (DbExpression)columnRef.IsNull() : (DbExpression)columnRef.IsNull().Not();
}
else
{
return columnRef.Equal(columnRef.ResultType.Constant(condition.Value));
}
}
private DbExpression GeneratePropertyMappingView(StoragePropertyMapping mapping, DbExpression row, List<string> context, IList<EdmSchemaError> errors)
{
Debug.Assert(mapping is StorageScalarPropertyMapping, "Complex property mapping is not supported in function imports.");
var scalarPropertyMapping = (StorageScalarPropertyMapping)mapping;
return GenerateScalarPropertyMappingView(scalarPropertyMapping.EdmProperty, scalarPropertyMapping.ColumnProperty, row);
}
private DbExpression GenerateScalarPropertyMappingView(EdmProperty edmProperty, EdmProperty columnProperty, DbExpression row)
{
DbExpression accessorExpr = GenerateColumnRef(row, columnProperty);
if (!TypeSemantics.IsEqual(accessorExpr.ResultType, edmProperty.TypeUsage))
{
accessorExpr = accessorExpr.CastTo(edmProperty.TypeUsage);
}
return accessorExpr;
}
private DbExpression GenerateColumnRef(DbExpression row, EdmProperty column)
{
Debug.Assert(row.ResultType.EdmType.BuiltInTypeKind == BuiltInTypeKind.RowType, "Input type is expected to be a row type.");
var rowType = (RowType)row.ResultType.EdmType;
Debug.Assert(rowType.Properties.Contains(column.Name), "Column name must be resolvable in the TVF result type.");
return row.Property(column.Name);
}
#endregion
#region GenerateScalarResultMappingView
private DbExpression GenerateScalarResultMappingView(DbExpression storeFunctionInvoke)
{
DbExpression queryExpression = storeFunctionInvoke;
CollectionType functionImportReturnType;
if (!MetadataHelper.TryGetFunctionImportReturnCollectionType(this.FunctionImport, 0, out functionImportReturnType))
{
Debug.Fail("Failed to get the result type of the function import.");
}
Debug.Assert(TypeSemantics.IsCollectionType(queryExpression.ResultType), "Store function must be TVF (collection expected).");
var collectionType = (CollectionType)queryExpression.ResultType.EdmType;
Debug.Assert(TypeSemantics.IsRowType(collectionType.TypeUsage), "Store function must be TVF (collection of rows expected).");
var rowType = (RowType)collectionType.TypeUsage.EdmType;
var column = rowType.Properties[0];
Func<DbExpression, DbExpression> scalarView = (DbExpression row) =>
{
var propertyAccess = row.Property(column);
if (TypeSemantics.IsEqual(functionImportReturnType.TypeUsage, column.TypeUsage))
{
return propertyAccess;
}
else
{
return propertyAccess.CastTo(functionImportReturnType.TypeUsage);
}
};
queryExpression = queryExpression.Select(row => scalarView(row));
return queryExpression;
}
#endregion
#endregion
#endregion
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="RotateTransform3D.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// This file was generated, please do not edit it directly.
//
// Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information.
//
//---------------------------------------------------------------------------
using MS.Internal;
using MS.Internal.Collections;
using MS.Internal.PresentationCore;
using MS.Utility;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Markup;
using System.Windows.Media.Media3D.Converters;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Composition;
using System.Security;
using System.Security.Permissions;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
using System.Windows.Media.Imaging;
// These types are aliased to match the unamanaged names used in interop
using BOOL = System.UInt32;
using WORD = System.UInt16;
using Float = System.Single;
namespace System.Windows.Media.Media3D
{
sealed partial class RotateTransform3D : AffineTransform3D
{
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
/// <summary>
/// Shadows inherited Clone() with a strongly typed
/// version for convenience.
/// </summary>
public new RotateTransform3D Clone()
{
return (RotateTransform3D)base.Clone();
}
/// <summary>
/// Shadows inherited CloneCurrentValue() with a strongly typed
/// version for convenience.
/// </summary>
public new RotateTransform3D CloneCurrentValue()
{
return (RotateTransform3D)base.CloneCurrentValue();
}
#endregion Public Methods
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
private static void CenterXPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
RotateTransform3D target = ((RotateTransform3D) d);
target._cachedCenterXValue = (double)e.NewValue;
target.PropertyChanged(CenterXProperty);
}
private static void CenterYPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
RotateTransform3D target = ((RotateTransform3D) d);
target._cachedCenterYValue = (double)e.NewValue;
target.PropertyChanged(CenterYProperty);
}
private static void CenterZPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
RotateTransform3D target = ((RotateTransform3D) d);
target._cachedCenterZValue = (double)e.NewValue;
target.PropertyChanged(CenterZProperty);
}
private static void RotationPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
// The first change to the default value of a mutable collection property (e.g. GeometryGroup.Children)
// will promote the property value from a default value to a local value. This is technically a sub-property
// change because the collection was changed and not a new collection set (GeometryGroup.Children.
// Add versus GeometryGroup.Children = myNewChildrenCollection). However, we never marshalled
// the default value to the compositor. If the property changes from a default value, the new local value
// needs to be marshalled to the compositor. We detect this scenario with the second condition
// e.OldValueSource != e.NewValueSource. Specifically in this scenario the OldValueSource will be
// Default and the NewValueSource will be Local.
if (e.IsASubPropertyChange &&
(e.OldValueSource == e.NewValueSource))
{
return;
}
RotateTransform3D target = ((RotateTransform3D) d);
target._cachedRotationValue = (Rotation3D)e.NewValue;
Rotation3D oldV = (Rotation3D) e.OldValue;
Rotation3D newV = (Rotation3D) e.NewValue;
System.Windows.Threading.Dispatcher dispatcher = target.Dispatcher;
if (dispatcher != null)
{
DUCE.IResource targetResource = (DUCE.IResource)target;
using (CompositionEngineLock.Acquire())
{
int channelCount = targetResource.GetChannelCount();
for (int channelIndex = 0; channelIndex < channelCount; channelIndex++)
{
DUCE.Channel channel = targetResource.GetChannel(channelIndex);
Debug.Assert(!channel.IsOutOfBandChannel);
Debug.Assert(!targetResource.GetHandle(channel).IsNull);
target.ReleaseResource(oldV,channel);
target.AddRefResource(newV,channel);
}
}
}
target.PropertyChanged(RotationProperty);
}
#region Public Properties
/// <summary>
/// CenterX - double. Default value is 0.0.
/// </summary>
public double CenterX
{
get
{
ReadPreamble();
return _cachedCenterXValue;
}
set
{
SetValueInternal(CenterXProperty, value);
}
}
/// <summary>
/// CenterY - double. Default value is 0.0.
/// </summary>
public double CenterY
{
get
{
ReadPreamble();
return _cachedCenterYValue;
}
set
{
SetValueInternal(CenterYProperty, value);
}
}
/// <summary>
/// CenterZ - double. Default value is 0.0.
/// </summary>
public double CenterZ
{
get
{
ReadPreamble();
return _cachedCenterZValue;
}
set
{
SetValueInternal(CenterZProperty, value);
}
}
/// <summary>
/// Rotation - Rotation3D. Default value is Rotation3D.Identity.
/// </summary>
public Rotation3D Rotation
{
get
{
ReadPreamble();
return _cachedRotationValue;
}
set
{
SetValueInternal(RotationProperty, value);
}
}
#endregion Public Properties
//------------------------------------------------------
//
// Protected Methods
//
//------------------------------------------------------
#region Protected Methods
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new RotateTransform3D();
}
#endregion ProtectedMethods
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
/// <SecurityNote>
/// Critical: This code calls into an unsafe code block
/// TreatAsSafe: This code does not return any critical data.It is ok to expose
/// Channels are safe to call into and do not go cross domain and cross process
/// </SecurityNote>
[SecurityCritical,SecurityTreatAsSafe]
internal override void UpdateResource(DUCE.Channel channel, bool skipOnChannelCheck)
{
// If we're told we can skip the channel check, then we must be on channel
Debug.Assert(!skipOnChannelCheck || _duceResource.IsOnChannel(channel));
if (skipOnChannelCheck || _duceResource.IsOnChannel(channel))
{
base.UpdateResource(channel, skipOnChannelCheck);
// Read values of properties into local variables
Rotation3D vRotation = Rotation;
// Obtain handles for properties that implement DUCE.IResource
DUCE.ResourceHandle hRotation = vRotation != null ? ((DUCE.IResource)vRotation).GetHandle(channel) : DUCE.ResourceHandle.Null;
// Obtain handles for animated properties
DUCE.ResourceHandle hCenterXAnimations = GetAnimationResourceHandle(CenterXProperty, channel);
DUCE.ResourceHandle hCenterYAnimations = GetAnimationResourceHandle(CenterYProperty, channel);
DUCE.ResourceHandle hCenterZAnimations = GetAnimationResourceHandle(CenterZProperty, channel);
// Pack & send command packet
DUCE.MILCMD_ROTATETRANSFORM3D data;
unsafe
{
data.Type = MILCMD.MilCmdRotateTransform3D;
data.Handle = _duceResource.GetHandle(channel);
if (hCenterXAnimations.IsNull)
{
data.centerX = CenterX;
}
data.hCenterXAnimations = hCenterXAnimations;
if (hCenterYAnimations.IsNull)
{
data.centerY = CenterY;
}
data.hCenterYAnimations = hCenterYAnimations;
if (hCenterZAnimations.IsNull)
{
data.centerZ = CenterZ;
}
data.hCenterZAnimations = hCenterZAnimations;
data.hrotation = hRotation;
// Send packed command structure
channel.SendCommand(
(byte*)&data,
sizeof(DUCE.MILCMD_ROTATETRANSFORM3D));
}
}
}
internal override DUCE.ResourceHandle AddRefOnChannelCore(DUCE.Channel channel)
{
if (_duceResource.CreateOrAddRefOnChannel(this, channel, System.Windows.Media.Composition.DUCE.ResourceType.TYPE_ROTATETRANSFORM3D))
{
Rotation3D vRotation = Rotation;
if (vRotation != null) ((DUCE.IResource)vRotation).AddRefOnChannel(channel);
AddRefOnChannelAnimations(channel);
UpdateResource(channel, true /* skip "on channel" check - we already know that we're on channel */ );
}
return _duceResource.GetHandle(channel);
}
internal override void ReleaseOnChannelCore(DUCE.Channel channel)
{
Debug.Assert(_duceResource.IsOnChannel(channel));
if (_duceResource.ReleaseOnChannel(channel))
{
Rotation3D vRotation = Rotation;
if (vRotation != null) ((DUCE.IResource)vRotation).ReleaseOnChannel(channel);
ReleaseOnChannelAnimations(channel);
}
}
internal override DUCE.ResourceHandle GetHandleCore(DUCE.Channel channel)
{
// Note that we are in a lock here already.
return _duceResource.GetHandle(channel);
}
internal override int GetChannelCountCore()
{
// must already be in composition lock here
return _duceResource.GetChannelCount();
}
internal override DUCE.Channel GetChannelCore(int index)
{
// Note that we are in a lock here already.
return _duceResource.GetChannel(index);
}
#endregion Internal Methods
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
#region Internal Properties
#endregion Internal Properties
//------------------------------------------------------
//
// Dependency Properties
//
//------------------------------------------------------
#region Dependency Properties
/// <summary>
/// The DependencyProperty for the RotateTransform3D.CenterX property.
/// </summary>
public static readonly DependencyProperty CenterXProperty;
/// <summary>
/// The DependencyProperty for the RotateTransform3D.CenterY property.
/// </summary>
public static readonly DependencyProperty CenterYProperty;
/// <summary>
/// The DependencyProperty for the RotateTransform3D.CenterZ property.
/// </summary>
public static readonly DependencyProperty CenterZProperty;
/// <summary>
/// The DependencyProperty for the RotateTransform3D.Rotation property.
/// </summary>
public static readonly DependencyProperty RotationProperty;
#endregion Dependency Properties
//------------------------------------------------------
//
// Internal Fields
//
//------------------------------------------------------
#region Internal Fields
private double _cachedCenterXValue = 0.0;
private double _cachedCenterYValue = 0.0;
private double _cachedCenterZValue = 0.0;
private Rotation3D _cachedRotationValue = Rotation3D.Identity;
internal System.Windows.Media.Composition.DUCE.MultiChannelResource _duceResource = new System.Windows.Media.Composition.DUCE.MultiChannelResource();
internal const double c_CenterX = 0.0;
internal const double c_CenterY = 0.0;
internal const double c_CenterZ = 0.0;
internal static Rotation3D s_Rotation = Rotation3D.Identity;
#endregion Internal Fields
#region Constructors
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
static RotateTransform3D()
{
// We check our static default fields which are of type Freezable
// to make sure that they are not mutable, otherwise we will throw
// if these get touched by more than one thread in the lifetime
// of your app. (Windows OS Bug #947272)
//
Debug.Assert(s_Rotation == null || s_Rotation.IsFrozen,
"Detected context bound default value RotateTransform3D.s_Rotation (See OS Bug #947272).");
// Initializations
Type typeofThis = typeof(RotateTransform3D);
CenterXProperty =
RegisterProperty("CenterX",
typeof(double),
typeofThis,
0.0,
new PropertyChangedCallback(CenterXPropertyChanged),
null,
/* isIndependentlyAnimated = */ true,
/* coerceValueCallback */ null);
CenterYProperty =
RegisterProperty("CenterY",
typeof(double),
typeofThis,
0.0,
new PropertyChangedCallback(CenterYPropertyChanged),
null,
/* isIndependentlyAnimated = */ true,
/* coerceValueCallback */ null);
CenterZProperty =
RegisterProperty("CenterZ",
typeof(double),
typeofThis,
0.0,
new PropertyChangedCallback(CenterZPropertyChanged),
null,
/* isIndependentlyAnimated = */ true,
/* coerceValueCallback */ null);
RotationProperty =
RegisterProperty("Rotation",
typeof(Rotation3D),
typeofThis,
Rotation3D.Identity,
new PropertyChangedCallback(RotationPropertyChanged),
null,
/* isIndependentlyAnimated = */ false,
/* coerceValueCallback */ null);
}
#endregion Constructors
}
}
| |
using System;
using System.Collections.Generic;
using UnityEngine;
namespace TinyBinaryXml
{
public class TbXmlNode
{
public ushort id;
public List<ushort> childrenIds;
public ushort templateId;
public List<int> attributeValues;
public TbXml tbXml;
public int text = -1;
public string GetText()
{
if (this.text == -1)
{
return string.Empty;
}
return this.tbXml.stringPool[this.text];
}
public string GetStringValue(string name)
{
object value = this.GetValue(ref name);
if (value == null)
{
return string.Empty;
}
if (value is double)
{
return value.ToString();
}
return value as string;
}
public double GetDoubleValue(string name)
{
object value = this.GetValue(ref name);
if (value is double)
{
return (double)value;
}
return 0.0;
}
public float GetFloatValue(string name, float defaultValue = 0f)
{
object obj = this.GetValue(ref name);
if (obj is double)
{
return (float)((double)obj);
}
string text = obj as string;
if (string.IsNullOrEmpty(text))
{
return defaultValue;
}
obj = text.Trim();
float result;
if (float.TryParse(text, out result))
{
return result;
}
return defaultValue;
}
public int GetIntValue(string name, int defaultValue = 0)
{
object obj = this.GetValue(ref name);
if (obj is double)
{
return (int)((double)obj);
}
string text = obj as string;
if (string.IsNullOrEmpty(text))
{
return defaultValue;
}
obj = text.Trim();
int result;
if (int.TryParse(text, out result))
{
return result;
}
return defaultValue;
}
public uint GetUIntValue(string name)
{
object value = this.GetValue(ref name);
if (value is double)
{
return (uint)((double)value);
}
return 0u;
}
public byte GetByteValue(string name)
{
object value = this.GetValue(ref name);
if (value is double)
{
return (byte)((double)value);
}
return 0;
}
public ushort GetUShortValue(string name)
{
object value = this.GetValue(ref name);
if (value is double)
{
return (ushort)((double)value);
}
return 0;
}
public short GetShortValue(string name)
{
object value = this.GetValue(ref name);
if (value is double)
{
return (short)((double)value);
}
return 0;
}
public bool GetBooleanValue(string name)
{
object value = this.GetValue(ref name);
if (value == null)
{
return false;
}
if (value is double)
{
return !Mathf.Approximately(0f, (float)((double)value));
}
return value.ToString() == "true";
}
public object GetValue(ref string name)
{
TbXmlNodeTemplate tbXmlNodeTemplate = this.tbXml.nodeTemplates[(int)this.templateId];
int index;
if (!tbXmlNodeTemplate.attributeNameIndexMapping.TryGetValue(name, out index))
{
return null;
}
if (tbXmlNodeTemplate.attributeTypes[index] == TB_XML_ATTRIBUTE_TYPE.DOUBLE)
{
return this.tbXml.valuePool[this.attributeValues[index]];
}
return this.tbXml.stringPool[this.attributeValues[index]];
}
public List<TbXmlNode> GetNodes(string path)
{
if (string.IsNullOrEmpty(path))
{
return null;
}
List<TbXmlNode> result = null;
int num = (this.childrenIds != null) ? this.childrenIds.Count : 0;
string[] array = path.Split(new char[]
{
'/'
});
for (int i = 0; i < num; i++)
{
TbXmlNode currentNode = this.tbXml.nodes[(int)this.childrenIds[i]];
this.GetNodesRecursive(array, 0, ref array[0], currentNode, ref result);
}
return result;
}
private void GetNodesRecursive(string[] pathBlocks, int pathBlockIndex, ref string pathBlock, TbXmlNode currentNode, ref List<TbXmlNode> resultNodes)
{
if (this.tbXml.nodeTemplates[(int)currentNode.templateId].name.Equals(pathBlock))
{
if (pathBlockIndex == pathBlocks.Length - 1)
{
if (resultNodes == null)
{
resultNodes = new List<TbXmlNode>();
}
resultNodes.Add(currentNode);
}
else
{
List<ushort> list = currentNode.childrenIds;
int num = (list != null) ? list.Count : 0;
for (int i = 0; i < num; i++)
{
this.GetNodesRecursive(pathBlocks, pathBlockIndex + 1, ref pathBlocks[pathBlockIndex + 1], this.tbXml.nodes[(int)list[i]], ref resultNodes);
}
}
}
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Positioning.Forms.dll
// Description: A library for managing GPS connections.
// ********************************************************************************************************
// 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 from http://gps3.codeplex.com/ version 3.0
//
// The Initial Developer of this original code is Jon Pearson. Submitted Oct. 21, 2010 by Ben Tombs (tidyup)
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
// -------------------------------------------------------------------------------------------------------
// | Developer | Date | Comments
// |--------------------------|------------|--------------------------------------------------------------
// | Tidyup (Ben Tombs) | 10/21/2010 | Original copy submitted from modified GPS.Net 3.0
// | Shade1974 (Ted Dunsford) | 10/22/2010 | Added file headers reviewed formatting with resharper.
// ********************************************************************************************************
using System;
using System.Drawing;
using System.Reflection;
#if !PocketPC || DesignTime
using System.ComponentModel;
#endif
namespace DotSpatial.Positioning.Forms
{
#if !PocketPC || DesignTime
#if Framework20
/// <summary>Calculates intermediate colors between two other colors.</summary>
/// <remarks>
/// <para>This class is used to create a smooth transition from one color to another.
/// After specifying a start color, end color, and number of intervals, the indexer
/// will return a calculated <strong>Color</strong>. Specifying a greater number of
/// intervals creates a smoother color gradient.</para>
/// <para>Instances of this class are guaranteed to be thread-safe because the class
/// uses thread synchronization.</para>
/// <para>On the .NET Compact Framework, the alpha channel is not supported.</para>
/// </remarks>
/// <example>
/// This example uses a <strong>ColorInterpolator</strong> to calculate ten colors
/// between (and including) <strong>Blue</strong> and <strong>Red</strong> .
/// <code lang="VB" title="[New Example]">
/// ' Create a New color interpolator
/// Dim Interpolator As New ColorInterpolator(Color.Blue, Color.Red, 10)
/// ' Output Each calculated color
/// Dim i As Integer
/// For i = 0 To 9
/// ' Get the Next color In the sequence
/// Dim NewColor As Color = Interpolator(i)
/// ' Output RGB values of this color
/// Debug.Write(NewColor.R.ToString() + ",")
/// Debug.Write(NewColor.G.ToString() + ",")
/// Debug.WriteLine(NewColor.B.ToString())
/// Next i
/// </code>
/// <code lang="CS" title="[New Example]">
/// // Create a new color interpolator
/// ColorInterpolator Interpolator = new ColorInterpolator(Color.Blue, Color.Red, 10);
/// // Output each calculated color
/// for (int i = 0; i < 10; i++)
/// {
/// // Get the next color in the sequence
/// Color NewColor = Interpolator[i];
/// // Output RGB values of this color
/// Console.Write(NewColor.R.ToString() + ",");
/// Console.Write(NewColor.G.ToString() + ",");
/// Console.WriteLine(NewColor.B.ToString());
/// }
/// </code>
/// </example>
[Obfuscation(Feature = "renaming", Exclude = false, ApplyToMembers = true)]
[Obfuscation(Feature = "controlflow", Exclude = true, ApplyToMembers = true)]
[Obfuscation(Feature = "stringencryption", Exclude = false, ApplyToMembers = true)]
#endif
[TypeConverter(typeof(ExpandableObjectConverter))]
[ImmutableObject(false)]
[Serializable]
#endif
public sealed class ColorInterpolator
{
#if !PocketPC
private readonly Interpolator _a = new Interpolator();
#endif
private readonly Interpolator _r = new Interpolator();
private readonly Interpolator _g = new Interpolator();
private readonly Interpolator _b = new Interpolator();
/// <summary>Creates a new instance.</summary>
/// <param name="startColor">A <strong>Color</strong> at the start of the sequence.</param>
/// <param name="endColor">A <strong>Color</strong> at the end of the sequence.</param>
/// <param name="count">
/// The total number of colors in the sequence, including the start and end
/// colors.
/// </param>
public ColorInterpolator(Color startColor, Color endColor, int count)
{
Count = count;
StartColor = startColor;
EndColor = endColor;
}
/// <summary>Returns a calculated color in the sequence.</summary>
/// <value>A <strong>Color</strong> value representing a calculated color.</value>
/// <example>
/// This example creates a new color interpolator between blue and red, then accesses
/// the sixth item in the sequence.
/// <code lang="VB" title="[New Example]">
/// ' Create a New color interpolator
/// Dim Interpolator As New ColorInterpolator(Color.Blue, Color.Red, 10)
/// ' Access the sixth item
/// Color CalculatedColor = Interpolator(5);
/// </code>
/// <code lang="CS" title="[New Example]">
/// // Create a New color interpolator
/// ColorInterpolator Interpolator = new ColorInterpolator(Color.Blue, Color.Red, 10);
/// // Access the sixth item
/// Color CalculatedColor = Interpolator[5];
/// </code>
/// </example>
/// <param name="index">
/// An <strong>Integer</strong> between 0 and <strong>Count</strong> minus
/// one.
/// </param>
public Color this[int index]
{
get
{
#if PocketPC
return Color.FromArgb((byte)R[index], (byte)G[index], (byte)B[index]);
#else
return Color.FromArgb((byte)_a[index], (byte)_r[index], (byte)_g[index], (byte)_b[index]);
#endif
}
}
/// <summary>
/// Controls the interpolation technique used to calculate intermediate
/// colors.
/// </summary>
/// <value>
/// An <strong>InterpolationMethod</strong> value indicating the interpolation
/// technique. Default is <strong>Linear</strong>.
/// </value>
/// <remarks>
/// This property controls the rate at which the start color transitions to the end
/// color. Values other than Linear can "accelerate" and/or "decelerate" towards the end
/// color.
/// </remarks>
public InterpolationMethod InterpolationMethod
{
get
{
return _r.InterpolationMethod;
}
set
{
#if !PocketPC
_a.InterpolationMethod = value;
#endif
_r.InterpolationMethod = value;
_g.InterpolationMethod = value;
_b.InterpolationMethod = value;
}
}
/// <summary>Controls the first color in the sequence.</summary>
/// <value>
/// A <strong>Color</strong> object representing the first color in the
/// sequence.
/// </value>
/// <remarks>Changing this property causes the entire sequence to be recalculated.</remarks>
/// <example>
/// This example changes the start color from Green to Orange.
/// </example>
public Color StartColor
{
get
{
#if PocketPC
return Color.FromArgb((byte)R.Minimum, (byte)G.Minimum, (byte)B.Minimum);
#else
return Color.FromArgb((byte)_a.Minimum, (byte)_r.Minimum, (byte)_g.Minimum, (byte)_b.Minimum);
#endif
}
set
{
#if !PocketPC
_a.Minimum = value.A;
#endif
_r.Minimum = value.R;
_g.Minimum = value.G;
_b.Minimum = value.B;
}
}
/// <value>
/// A <strong>Color</strong> object representing the last color in the
/// sequence.
/// </value>
/// <summary>Controls the last color in the sequence.</summary>
/// <remarks>Changing this property causes the entire sequence to be recalculated.</remarks>
public Color EndColor
{
get
{
#if PocketPC
return Color.FromArgb((byte)R.Maximum, (byte)G.Maximum, (byte)B.Maximum);
#else
return Color.FromArgb((byte)_a.Maximum, (byte)_r.Maximum, (byte)_g.Maximum, (byte)_b.Maximum);
#endif
}
set
{
#if !PocketPC
_a.Maximum = value.A;
#endif
_r.Maximum = value.R;
_g.Maximum = value.G;
_b.Maximum = value.B;
}
}
/// <summary>Controls the number of colors in the sequence.</summary>
/// <remarks>Changing this property causes the entire sequence to be recalculated.</remarks>
/// <value>
/// An <strong>Integer</strong> indicating the total number of colors, including the
/// start and end colors.
/// </value>
public int Count
{
get
{
return _r.Count;
}
set
{
#if !PocketPC
_a.Count = value;
#endif
_r.Count = value;
_g.Count = value;
_b.Count = value;
}
}
}
}
| |
// Copyright (c) 2007-2008, Gaudenz Alder
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
namespace com.mxgraph
{
/// <summary>
/// Represents the geometry of a cell. For vertices, the geometry consists
/// of the x- and y-location, as well as the width and height. For edges,
/// the edge either defines the source- and target-terminal, or the geometry
/// defines the respective terminal points.
/// </summary>
public class mxGeometry : mxRectangle
{
/// <summary>
/// Global switch to translate the points in translate. Default is true.
/// </summary>
public static bool TRANSLATE_CONTROL_POINTS = true;
/// <summary>
/// Stores alternate values for x, y, width and height in a rectangle.
/// Default is null.
/// </summary>
protected mxRectangle alternateBounds;
/// <summary>
/// Defines the source-point of the edge. This is used if the
/// corresponding edge does not have a source vertex. Otherwise it is
/// ignored. Default is null.
/// </summary>
protected mxPoint sourcePoint;
/// <summary>
/// Defines the target-point of the edge. This is used if the
/// corresponding edge does not have a source vertex. Otherwise it is
/// ignored. Default is null.
/// </summary>
protected mxPoint targetPoint;
/// <summary>
/// Holds the offset of the label for edges. This is the absolute vector
/// between the center of the edge and the top, left point of the label.
/// Default is null.
/// </summary>
protected mxPoint offset;
/// <summary>
/// List of mxPoints which specifies the control points along the edge.
/// These points are the intermediate points on the edge, for the endpoints
/// use targetPoint and sourcePoint or set the terminals of the edge to
/// a non-null value. Default is null.
/// </summary>
protected List<mxPoint> points;
/// <summary>
/// Specifies if the coordinates in the geometry are to be interpreted as
/// relative coordinates. Default is false. This is used to mark a geometry
/// with an x- and y-coordinate that is used to describe an edge label
/// position.
/// </summary>
protected bool relative = false;
/// <summary>
/// Constructs a new geometry at (0, 0) with the width and height set to 0.
/// </summary>
public mxGeometry() : this(0, 0, 0, 0) { }
/// <summary>
/// Constructs a geometry using the given parameters.
/// </summary>
/// <param name="x">X-coordinate of the new geometry.</param>
/// <param name="y">Y-coordinate of the new geometry.</param>
/// <param name="width">Width of the new geometry.</param>
/// <param name="height">Height of the new geometry.</param>
public mxGeometry(double x, double y, double width, double height) : base(x, y, width, height) { }
/// <summary>
/// Constructs a copy of the given geometry.
/// </summary>
/// <param name="geometry">Geometry to construct a copy of.</param>
public mxGeometry(mxGeometry geometry)
: base(geometry.X, geometry.Y, geometry.Width, geometry
.Height)
{
if (geometry.points != null)
{
points = new List<mxPoint>(geometry.points.Count);
foreach (mxPoint pt in geometry.points)
{
points.Add(pt.Clone());
}
}
if (geometry.sourcePoint != null)
{
sourcePoint = geometry.sourcePoint.Clone();
}
if (geometry.targetPoint != null)
{
targetPoint = geometry.targetPoint.Clone();
}
if (geometry.offset != null)
{
offset = geometry.offset.Clone();
}
if (geometry.alternateBounds != null)
{
alternateBounds = geometry.alternateBounds.Clone();
}
relative = geometry.relative;
}
/// <summary>
/// Sets or returns the alternate bounds.
/// </summary>
public mxRectangle AlternateBounds
{
get { return alternateBounds; }
set { alternateBounds = value; }
}
/// <summary>
/// Sets or returns the source point.
/// </summary>
public mxPoint SourcePoint
{
get { return sourcePoint; }
set { sourcePoint = value; }
}
/// <summary>
/// Sets or returns the target point.
/// </summary>
public mxPoint TargetPoint
{
get { return targetPoint; }
set { targetPoint = value; }
}
/// <summary>
/// Sets or returns the list of control points.
/// </summary>
public List<mxPoint> Points
{
get { return points; }
set { points = value; }
}
/// <summary>
/// Sets or returns the offset.
/// </summary>
public mxPoint Offset
{
get { return offset; }
set { offset = value; }
}
/// <summary>
/// Sets or returns if the geometry is relative.
/// </summary>
public bool Relative
{
get { return relative; }
set { relative = value; }
}
/// <summary>
/// Returns the point representing the source or target point of this edge.
/// This is only used if the edge has no source or target vertex.
/// </summary>
/// <param name="source">Boolean that specifies if the source or target point
/// should be returned.</param>
/// <returns>Returns the source or target point.</returns>
public mxPoint GetTerminalPoint(bool source)
{
return (source) ? sourcePoint : targetPoint;
}
/// <summary>
/// Sets the sourcePoint or targetPoint to the given point and returns the
/// new point.
/// </summary>
/// <param name="point">Point to be used as the new source or target point.</param>
/// <param name="source">Boolean that specifies if the source or target point
/// should be set.</param>
/// <returns>Returns the new point.</returns>
public mxPoint SetTerminalPoint(mxPoint point, bool source)
{
if (source)
{
sourcePoint = point;
}
else
{
targetPoint = point;
}
return point;
}
/// <summary>
/// Translates the geometry by the specified amount. That is, x and y of the
/// geometry, the sourcePoint, targetPoint and all elements of points are
/// translated by the given amount. X and y are only translated if the
/// geometry is not relative. If TRANSLATE_CONTROL_POINTS is false, then
/// are not modified by this function.
/// </summary>
/// <param name="dx">Integer that specifies the x-coordinate of the translation.</param>
/// <param name="dy">Integer that specifies the y-coordinate of the translation.</param>
public void Translate(double dx, double dy)
{
// Translates the geometry
if (!Relative)
{
x += dx;
y += dy;
}
// Translates the source point
if (sourcePoint != null)
{
sourcePoint.X += dx;
sourcePoint.Y += dy;
}
// Translates the target point
if (targetPoint != null)
{
targetPoint.X += dx;
targetPoint.Y += dy;
}
// Translate the control points
if (TRANSLATE_CONTROL_POINTS &&
points != null)
{
int count = points.Count;
for (int i = 0; i < count; i++)
{
mxPoint pt = points[i];
pt.X += dx;
pt.Y += dy;
}
}
}
/// <summary>
/// Returns a new instance of the same geometry.
/// </summary>
/// <returns>Returns a clone of the geometry.</returns>
public new mxGeometry Clone()
{
return new mxGeometry(this);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text;
using Rynchodon.Utility;
using Rynchodon.Utility.Network;
using Sandbox.ModAPI;
namespace Rynchodon.Settings
{
/// <summary>
/// Some of the settings will be made available to clients.
/// </summary>
public class ServerSettings
{
public enum SettingName : byte
{
bAirResistanceBeta, bAllowAutopilot, bAllowGuidedMissile, bAllowHacker, bAllowRadar, bAllowWeaponControl, bImmortalMiner, bUseRemoteControl,
fDefaultSpeed, fMaxSpeed, fMaxWeaponRange
}
private static ushort ModID { get { return MessageHandler.ModId; } }
private static ServerSettings value_Instance;
private static ServerSettings Instance
{
get
{
if (Globals.WorldClosed)
throw new Exception("World closed");
if (value_Instance == null)
value_Instance = new ServerSettings();
return value_Instance;
}
set { value_Instance = value; }
}
public static Version CurrentVersion { get { return Instance.m_currentVersion; } }
public static bool ServerSettingsLoaded { get { return Instance.m_settingsLoaded; } }
/// <exception cref="NullReferenceException">if setting does not exist or is of a different type</exception>
public static T GetSetting<T>(SettingName name) where T : struct
{
ServerSettings instance = Instance;
SettingSimple<T> set = instance.AllSettings[name] as SettingSimple<T>;
return set.Value;
}
private static void SetSetting<T>(SettingName name, T value) where T : struct
{
ServerSettings instance = Instance;
SettingSimple<T> set = instance.AllSettings[name] as SettingSimple<T>;
set.Value = value;
Logger.AlwaysLog("Setting " + name + " = " + value, Rynchodon.Logger.severity.INFO);
}
/// <exception cref="NullReferenceException">if setting does not exist or is of a different type</exception>
public static string GetSettingString(SettingName name)
{
ServerSettings instance = Instance;
SettingString set = instance.AllSettings[name] as SettingString;
return set.Value;
}
private const string modName = "ARMS";
private const string settings_file_name = "ServerSettings.txt";
private const string strVersion = "Version";
private Dictionary<SettingName, Setting> AllSettings = new Dictionary<SettingName, Setting>();
private System.IO.TextWriter settingsWriter;
private Version fileVersion;
private Version m_currentVersion, m_serverVersion;
private bool m_settingsLoaded;
[OnWorldClose]
private static void Unload()
{
Instance = null;
}
private ServerSettings()
{
m_currentVersion = new Version(FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location));
buildSettings();
m_settingsLoaded = false;
if (MyAPIGateway.Multiplayer.IsServer)
{
m_serverVersion = m_currentVersion;
m_settingsLoaded = true;
MessageHandler.SetHandler(MessageHandler.SubMod.ServerSettings, Server_ReceiveMessage);
fileVersion = readAll();
if (fileVersion.CompareTo(m_currentVersion) < 0)
Rynchodon.Logger.DebugNotify(modName + " has been updated to version " + m_currentVersion, 10000, Rynchodon.Logger.severity.INFO);
Logger.AlwaysLog("file version: " + fileVersion + ", latest version: " + m_currentVersion, Rynchodon.Logger.severity.INFO);
writeAll(); // writing immediately decreases user errors & whining
}
else
{
MessageHandler.SetHandler(MessageHandler.SubMod.ServerSettings, Client_ReceiveMessage);
RequestSettingsFromServer();
}
}
private void Server_ReceiveMessage(byte[] message, int pos)
{
try
{
if (message == null)
{
Logger.DebugLog("Message is null");
return;
}
if( message.Length < 8)
{
Logger.DebugLog("Message is too short: " + message.Length);
return;
}
ulong SteamUserId = ByteConverter.GetUlong(message, ref pos);
Logger.DebugLog("Received request from: " + SteamUserId);
List<byte> send = new List<byte>();
ByteConverter.AppendBytes(send, (byte)MessageHandler.SubMod.ServerSettings);
ByteConverter.AppendBytes(send, m_serverVersion.Major);
ByteConverter.AppendBytes(send, m_serverVersion.Minor);
ByteConverter.AppendBytes(send, m_serverVersion.Build);
ByteConverter.AppendBytes(send, m_serverVersion.Revision);
ByteConverter.AppendBytes(send, GetSetting<bool>(SettingName.bAirResistanceBeta));
ByteConverter.AppendBytes(send, GetSetting<bool>(SettingName.bAllowAutopilot));
ByteConverter.AppendBytes(send, GetSetting<bool>(SettingName.bAllowGuidedMissile));
ByteConverter.AppendBytes(send, GetSetting<bool>(SettingName.bAllowHacker));
ByteConverter.AppendBytes(send, GetSetting<bool>(SettingName.bAllowRadar));
ByteConverter.AppendBytes(send, GetSetting<bool>(SettingName.bAllowWeaponControl));
ByteConverter.AppendBytes(send, GetSetting<bool>(SettingName.bImmortalMiner));
ByteConverter.AppendBytes(send, GetSetting<bool>(SettingName.bUseRemoteControl));
ByteConverter.AppendBytes(send, GetSetting<float>(SettingName.fDefaultSpeed));
ByteConverter.AppendBytes(send, GetSetting<float>(SettingName.fMaxSpeed));
ByteConverter.AppendBytes(send, GetSetting<float>(SettingName.fMaxWeaponRange));
if (MyAPIGateway.Multiplayer.SendMessageTo(ModID, send.ToArray(), SteamUserId))
Logger.DebugLog("Sent settings to " + SteamUserId, Rynchodon.Logger.severity.INFO);
else
Logger.AlwaysLog("Failed to send settings to " + SteamUserId, Rynchodon.Logger.severity.ERROR);
}
catch (Exception ex)
{ Logger.AlwaysLog("Exception: " + ex, Rynchodon.Logger.severity.ERROR); }
}
private void Client_ReceiveMessage(byte[] message, int pos)
{
try
{
Logger.DebugLog("Received settings from server");
m_serverVersion.Major = ByteConverter.GetInt(message, ref pos);
m_serverVersion.Minor = ByteConverter.GetInt(message, ref pos);
m_serverVersion.Build = ByteConverter.GetInt(message, ref pos);
m_serverVersion.Revision = ByteConverter.GetInt(message, ref pos);
if (m_currentVersion.Major == m_serverVersion.Major && m_currentVersion.Minor == m_serverVersion.Minor && m_currentVersion.Build == m_serverVersion.Build)
{
if (m_currentVersion.Revision != m_serverVersion.Revision)
Logger.AlwaysLog("Server has different revision of ARMS. Server version: " + m_serverVersion + ", client version: " + m_currentVersion, Rynchodon.Logger.severity.WARNING);
}
else
{
Logger.AlwaysLog("Server has different version of ARMS. Server version: " + m_serverVersion + ", client version: " + m_currentVersion, Rynchodon.Logger.severity.FATAL);
return;
}
SetSetting<bool>(SettingName.bAirResistanceBeta, ByteConverter.GetBool(message, ref pos));
SetSetting<bool>(SettingName.bAllowAutopilot, ByteConverter.GetBool(message, ref pos));
SetSetting<bool>(SettingName.bAllowGuidedMissile, ByteConverter.GetBool(message, ref pos));
SetSetting<bool>(SettingName.bAllowHacker, ByteConverter.GetBool(message, ref pos));
SetSetting<bool>(SettingName.bAllowRadar, ByteConverter.GetBool(message, ref pos));
SetSetting<bool>(SettingName.bAllowWeaponControl, ByteConverter.GetBool(message, ref pos));
SetSetting<bool>(SettingName.bImmortalMiner, ByteConverter.GetBool(message, ref pos));
SetSetting<bool>(SettingName.bUseRemoteControl, ByteConverter.GetBool(message, ref pos));
SetSetting<float>(SettingName.fDefaultSpeed, ByteConverter.GetFloat(message, ref pos));
SetSetting<float>(SettingName.fMaxSpeed, ByteConverter.GetFloat(message, ref pos));
SetSetting<float>(SettingName.fMaxWeaponRange, ByteConverter.GetFloat(message, ref pos));
m_settingsLoaded = true;
}
catch (Exception ex)
{ Logger.AlwaysLog("Exception: " + ex, Rynchodon.Logger.severity.ERROR); }
}
private void RequestSettingsFromServer()
{
if (MyAPIGateway.Session.Player == null)
{
Logger.AlwaysLog("Could not get player, not requesting server settings.", Rynchodon.Logger.severity.WARNING);
m_settingsLoaded = true;
return;
}
List<byte> bytes = new List<byte>();
ByteConverter.AppendBytes(bytes, (byte)MessageHandler.SubMod.ServerSettings);
ByteConverter.AppendBytes(bytes, MyAPIGateway.Session.Player.SteamUserId);
if (MyAPIGateway.Multiplayer.SendMessageToServer(ModID, bytes.ToArray()))
Logger.DebugLog("Sent request to server", Rynchodon.Logger.severity.INFO);
else
Logger.AlwaysLog("Failed to send request to server", Rynchodon.Logger.severity.ERROR);
}
/// <summary>
/// put each setting into AllSettings with its default value
/// </summary>
private void buildSettings()
{
AllSettings.Add(SettingName.bAirResistanceBeta, new SettingSimple<bool>(false));
AllSettings.Add(SettingName.bAllowAutopilot, new SettingSimple<bool>(true));
AllSettings.Add(SettingName.bAllowGuidedMissile, new SettingSimple<bool>(true));
AllSettings.Add(SettingName.bAllowHacker, new SettingSimple<bool>(true));
AllSettings.Add(SettingName.bAllowRadar, new SettingSimple<bool>(true));
AllSettings.Add(SettingName.bAllowWeaponControl, new SettingSimple<bool>(true));
AllSettings.Add(SettingName.bImmortalMiner, new SettingSimple<bool>(false));
AllSettings.Add(SettingName.bUseRemoteControl, new SettingSimple<bool>(false));
AllSettings.Add(SettingName.fDefaultSpeed, new SettingMinMax<float>(1, float.MaxValue, 100));
AllSettings.Add(SettingName.fMaxSpeed, new SettingMinMax<float>(10, float.MaxValue, float.MaxValue));
AllSettings.Add(SettingName.fMaxWeaponRange, new SettingMinMax<float>(100, float.MaxValue, 800));
}
/// <summary>
/// Read all settings from file
/// </summary>
/// <returns>version of file</returns>
private Version readAll()
{
if (!MyAPIGateway.Utilities.FileExistsInLocalStorage(settings_file_name, typeof(ServerSettings)))
return new Version(-1); // no file
TextReader settingsReader = null;
try
{
settingsReader = MyAPIGateway.Utilities.ReadFileInLocalStorage(settings_file_name, typeof(ServerSettings));
string[] versionLine = settingsReader.ReadLine().Split('=');
if (versionLine.Length != 2 || !versionLine[0].Equals(strVersion))
return new Version(-2); // first line is not version
Version fileVersion = new Version(versionLine[1]);
// read settings
while (true)
{
string line = settingsReader.ReadLine();
if (line == null)
break;
parse(line);
}
return fileVersion;
}
catch (Exception ex)
{
Logger.AlwaysLog("Failed to read settings from " + settings_file_name + ": " + ex, Rynchodon.Logger.severity.WARNING);
return new Version(-4); // exception while reading
}
finally
{
if (settingsReader != null)
settingsReader.Close();
}
}
/// <summary>
/// Write all settings to file. Only server should call this!
/// </summary>
private void writeAll()
{
try
{
settingsWriter = MyAPIGateway.Utilities.WriteFileInLocalStorage(settings_file_name, typeof(ServerSettings));
write(strVersion, m_currentVersion.ToString()); // must be first line
// write settings
foreach (KeyValuePair<SettingName, Setting> pair in AllSettings)
write(pair.Key.ToString(), pair.Value.ValueAsString());
settingsWriter.Flush();
}
catch (Exception ex)
{ Logger.AlwaysLog("Failed to write settings to " + settings_file_name + ": " + ex, Rynchodon.Logger.severity.WARNING); }
finally
{
if (settingsWriter != null)
{
settingsWriter.Close();
settingsWriter = null;
}
}
}
/// <summary>
/// write a single setting to file, format is name=value
/// </summary>
/// <param name="name">name of setting</param>
/// <param name="value">value of setting</param>
private void write(string name, string value)
{
StringBuilder toWrite = new StringBuilder();
toWrite.Append(name);
toWrite.Append('=');
toWrite.Append(value);
settingsWriter.WriteLine(toWrite);
}
/// <summary>
/// convert a line of format name=value into a setting and apply it
/// </summary>
private void parse(string line)
{
string[] split = line.Split('=');
if (split.Length != 2)
{
Logger.AlwaysLog("split wrong length: " + split.Length + ", line: " + line, Rynchodon.Logger.severity.WARNING);
return;
}
SettingName name;
if (Enum.TryParse<SettingName>(split[0], out name))
try
{
if (AllSettings[name].ValueFromString(split[1]))
Logger.AlwaysLog("Setting " + name + " = " + split[1], Rynchodon.Logger.severity.INFO);
}
catch (Exception)
{ Logger.AlwaysLog("failed to parse: " + split[1] + " for " + name, Rynchodon.Logger.severity.WARNING); }
else
Logger.AlwaysLog("Setting does not exist: " + split[0], Rynchodon.Logger.severity.WARNING);
}
}
}
| |
namespace AgileObjects.AgileMapper.Members.Dictionaries
{
using System.Collections.Generic;
using System.Linq;
using Extensions.Internal;
using NetStandardPolyfills;
using ReadableExpressions.Extensions;
#if NET35
using Microsoft.Scripting.Ast;
#else
using System.Linq.Expressions;
#endif
internal static class DictionaryMemberMapperDataExtensions
{
public static Expression GetDictionaryKeyPartSeparator(this IMemberMapperData mapperData)
{
return mapperData
.MapperContext
.UserConfigurations
.Dictionaries
.GetSeparator(mapperData);
}
public static Expression GetDictionaryElementKeyPartMatcher(this IMemberMapperData mapperData)
{
return mapperData
.MapperContext
.UserConfigurations
.Dictionaries
.GetElementKeyPartMatcher(mapperData);
}
public static Expression GetTargetMemberDictionaryKey(this IMemberMapperData mapperData)
{
var configuredKey = mapperData.MapperContext
.UserConfigurations
.Dictionaries
.GetFullKeyOrNull(mapperData);
if (configuredKey != null)
{
return configuredKey;
}
var keyParts = GetTargetMemberDictionaryKeyParts(mapperData);
if (keyParts.Any() && (keyParts[0].NodeType == ExpressionType.Constant))
{
var firstKeyPart = (ConstantExpression)keyParts[0];
var firstKeyPartValue = (string)firstKeyPart.Value;
if (firstKeyPartValue.StartsWith('.'))
{
keyParts[0] = firstKeyPartValue.Substring(1).ToConstantExpression();
}
}
return keyParts.GetStringConcatCall();
}
public static IList<Expression> GetTargetMemberDictionaryKeyParts(this IMemberMapperData mapperData)
{
var joinedName = default(string);
var memberPartExpressions = new List<Expression>();
var joinedNameIsConstant = true;
var parentCounterInaccessible = false;
Expression parentContextAccess = null;
var targetQualifiedMember = mapperData.TargetMember;
var isTargetDictionary = targetQualifiedMember is DictionaryTargetMember;
foreach (var targetMember in targetQualifiedMember.MemberChain.Reverse())
{
if (IsRootDictionaryContext(targetMember, isTargetDictionary, mapperData))
{
break;
}
parentCounterInaccessible = parentCounterInaccessible || mapperData.IsEntryPoint;
if (targetMember.IsEnumerableElement())
{
var index = GetElementIndexAccess(parentContextAccess, mapperData);
AddEnumerableMemberNamePart(memberPartExpressions, mapperData, index);
joinedNameIsConstant = false;
}
else
{
if (parentCounterInaccessible && (parentContextAccess == null))
{
parentContextAccess = mapperData.MappingDataObject;
}
var namePart = AddMemberNamePart(memberPartExpressions, targetMember, mapperData);
joinedNameIsConstant = joinedNameIsConstant && namePart.NodeType == ExpressionType.Constant;
if (joinedNameIsConstant)
{
joinedName = (string)((ConstantExpression)namePart).Value + joinedName;
}
}
MoveToParentMapperContextIfNecessary(targetMember, isTargetDictionary, ref mapperData);
}
if (joinedNameIsConstant && (memberPartExpressions.Count > 1))
{
memberPartExpressions.Clear();
memberPartExpressions.Add(joinedName.ToConstantExpression());
}
return memberPartExpressions;
}
private static bool IsRootDictionaryContext(
Member targetMember,
bool isTargetDictionary,
IMemberMapperData mapperData)
{
if (targetMember.IsRoot || mapperData.Context.IsStandalone)
{
return true;
}
if (isTargetDictionary)
{
return targetMember.IsDictionary;
}
return mapperData.SourceType.IsDictionary() && !mapperData.Parent.SourceType.IsDictionary();
}
private static Expression GetElementIndexAccess(Expression parentContextAccess, IMemberMapperData mapperData)
{
if (parentContextAccess == null)
{
while (!mapperData.TargetMemberIsEnumerableElement())
{
mapperData = mapperData.Parent;
}
if (!mapperData.IsEntryPoint)
{
return mapperData.Parent.EnumerablePopulationBuilder.Counter;
}
parentContextAccess = mapperData.MappingDataObject;
}
var mappingDataType = typeof(IMappingData<,>)
.MakeGenericType(parentContextAccess.Type.GetGenericTypeArguments());
var elementIndexProperty = mappingDataType.GetPublicInstanceProperty("ElementIndex");
// ReSharper disable once AssignNullToNotNullAttribute
return Expression.Property(parentContextAccess, elementIndexProperty);
}
private static void AddEnumerableMemberNamePart(
List<Expression> memberPartExpressions,
IMemberMapperData mapperData,
Expression index)
{
var elementKeyParts = GetTargetMemberDictionaryElementKeyParts(mapperData, index);
memberPartExpressions.InsertRange(0, elementKeyParts);
}
public static IList<Expression> GetTargetMemberDictionaryElementKeyParts(
this IMemberMapperData mapperData,
Expression index)
{
var elementContext = mapperData.GetElementMemberContext();
return mapperData
.MapperContext
.UserConfigurations
.Dictionaries
.GetElementKeyParts(index, elementContext);
}
private static Expression AddMemberNamePart(
IList<Expression> memberPartExpressions,
Member targetMember,
IMemberMapperData mapperData)
{
var memberNamePart = mapperData.MapperContext
.UserConfigurations
.Dictionaries
.GetJoiningName(targetMember, mapperData);
memberPartExpressions.Insert(0, memberNamePart);
return memberNamePart;
}
private static void MoveToParentMapperContextIfNecessary(
Member targetMember,
bool isTargetDictionary,
ref IMemberMapperData mapperData)
{
if (mapperData.Parent.IsRoot)
{
return;
}
if (!isTargetDictionary)
{
mapperData = mapperData.Parent;
return;
}
if (!targetMember.IsEnumerableElement())
{
return;
}
while (!mapperData.TargetMember.IsEnumerable)
{
mapperData = mapperData.Parent;
}
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Management.ServiceBus;
using Microsoft.WindowsAzure.Management.ServiceBus.Models;
namespace Microsoft.WindowsAzure.Management.ServiceBus
{
/// <summary>
/// The Service Bus Management API is a REST API for managing Service Bus
/// queues, topics, rules and subscriptions. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/hh780776.aspx for
/// more information)
/// </summary>
public static partial class NamespaceOperationsExtensions
{
/// <summary>
/// Checks the availability of the given service namespace across all
/// Windows Azure subscriptions. This is useful because the domain
/// name is created based on the service namespace name. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj870968.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <returns>
/// The response to a query for the availability status of a namespace
/// name.
/// </returns>
public static CheckNamespaceAvailabilityResponse CheckAvailability(this INamespaceOperations operations, string namespaceName)
{
return Task.Factory.StartNew((object s) =>
{
return ((INamespaceOperations)s).CheckAvailabilityAsync(namespaceName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Checks the availability of the given service namespace across all
/// Windows Azure subscriptions. This is useful because the domain
/// name is created based on the service namespace name. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj870968.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <returns>
/// The response to a query for the availability status of a namespace
/// name.
/// </returns>
public static Task<CheckNamespaceAvailabilityResponse> CheckAvailabilityAsync(this INamespaceOperations operations, string namespaceName)
{
return operations.CheckAvailabilityAsync(namespaceName, CancellationToken.None);
}
/// <summary>
/// Creates a new service namespace. Once created, this namespace's
/// resource manifest is immutable. This operation is idempotent.
/// (see http://msdn.microsoft.com/en-us/library/windowsazure/jj856303.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <param name='region'>
/// Optional. The namespace region.
/// </param>
/// <returns>
/// The response to a request for a particular namespace.
/// </returns>
public static ServiceBusNamespaceResponse Create(this INamespaceOperations operations, string namespaceName, string region)
{
return Task.Factory.StartNew((object s) =>
{
return ((INamespaceOperations)s).CreateAsync(namespaceName, region);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates a new service namespace. Once created, this namespace's
/// resource manifest is immutable. This operation is idempotent.
/// (see http://msdn.microsoft.com/en-us/library/windowsazure/jj856303.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <param name='region'>
/// Optional. The namespace region.
/// </param>
/// <returns>
/// The response to a request for a particular namespace.
/// </returns>
public static Task<ServiceBusNamespaceResponse> CreateAsync(this INamespaceOperations operations, string namespaceName, string region)
{
return operations.CreateAsync(namespaceName, region, CancellationToken.None);
}
/// <summary>
/// The create namespace authorization rule operation creates an
/// authorization rule for a namespace
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <param name='rule'>
/// Required. The shared access authorization rule.
/// </param>
/// <returns>
/// A response to a request for a particular authorization rule.
/// </returns>
public static ServiceBusAuthorizationRuleResponse CreateAuthorizationRule(this INamespaceOperations operations, string namespaceName, ServiceBusSharedAccessAuthorizationRule rule)
{
return Task.Factory.StartNew((object s) =>
{
return ((INamespaceOperations)s).CreateAuthorizationRuleAsync(namespaceName, rule);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The create namespace authorization rule operation creates an
/// authorization rule for a namespace
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <param name='rule'>
/// Required. The shared access authorization rule.
/// </param>
/// <returns>
/// A response to a request for a particular authorization rule.
/// </returns>
public static Task<ServiceBusAuthorizationRuleResponse> CreateAuthorizationRuleAsync(this INamespaceOperations operations, string namespaceName, ServiceBusSharedAccessAuthorizationRule rule)
{
return operations.CreateAuthorizationRuleAsync(namespaceName, rule, CancellationToken.None);
}
/// <summary>
/// Creates a new service namespace. Once created, this namespace's
/// resource manifest is immutable. This operation is idempotent.
/// (see http://msdn.microsoft.com/en-us/library/windowsazure/jj856303.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <param name='namespaceEntity'>
/// Required. The service bus namespace.
/// </param>
/// <returns>
/// The response to a request for a particular namespace.
/// </returns>
public static ServiceBusNamespaceResponse CreateNamespace(this INamespaceOperations operations, string namespaceName, ServiceBusNamespaceCreateParameters namespaceEntity)
{
return Task.Factory.StartNew((object s) =>
{
return ((INamespaceOperations)s).CreateNamespaceAsync(namespaceName, namespaceEntity);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates a new service namespace. Once created, this namespace's
/// resource manifest is immutable. This operation is idempotent.
/// (see http://msdn.microsoft.com/en-us/library/windowsazure/jj856303.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <param name='namespaceEntity'>
/// Required. The service bus namespace.
/// </param>
/// <returns>
/// The response to a request for a particular namespace.
/// </returns>
public static Task<ServiceBusNamespaceResponse> CreateNamespaceAsync(this INamespaceOperations operations, string namespaceName, ServiceBusNamespaceCreateParameters namespaceEntity)
{
return operations.CreateNamespaceAsync(namespaceName, namespaceEntity, CancellationToken.None);
}
/// <summary>
/// Deletes an existing namespace. This operation also removes all
/// associated entities including queues, topics, relay points, and
/// messages stored under the namespace. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj856296.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Delete(this INamespaceOperations operations, string namespaceName)
{
return Task.Factory.StartNew((object s) =>
{
return ((INamespaceOperations)s).DeleteAsync(namespaceName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes an existing namespace. This operation also removes all
/// associated entities including queues, topics, relay points, and
/// messages stored under the namespace. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj856296.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> DeleteAsync(this INamespaceOperations operations, string namespaceName)
{
return operations.DeleteAsync(namespaceName, CancellationToken.None);
}
/// <summary>
/// The delete namespace authorization rule operation deletes an
/// authorization rule for a namespace
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <param name='ruleName'>
/// Required. The rule name.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse DeleteAuthorizationRule(this INamespaceOperations operations, string namespaceName, string ruleName)
{
return Task.Factory.StartNew((object s) =>
{
return ((INamespaceOperations)s).DeleteAuthorizationRuleAsync(namespaceName, ruleName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The delete namespace authorization rule operation deletes an
/// authorization rule for a namespace
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <param name='ruleName'>
/// Required. The rule name.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> DeleteAuthorizationRuleAsync(this INamespaceOperations operations, string namespaceName, string ruleName)
{
return operations.DeleteAuthorizationRuleAsync(namespaceName, ruleName, CancellationToken.None);
}
/// <summary>
/// Returns the description for the specified namespace. (see
/// http://msdn.microsoft.com/library/azure/dn140232.aspx for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <returns>
/// The response to a request for a particular namespace.
/// </returns>
public static ServiceBusNamespaceResponse Get(this INamespaceOperations operations, string namespaceName)
{
return Task.Factory.StartNew((object s) =>
{
return ((INamespaceOperations)s).GetAsync(namespaceName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns the description for the specified namespace. (see
/// http://msdn.microsoft.com/library/azure/dn140232.aspx for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <returns>
/// The response to a request for a particular namespace.
/// </returns>
public static Task<ServiceBusNamespaceResponse> GetAsync(this INamespaceOperations operations, string namespaceName)
{
return operations.GetAsync(namespaceName, CancellationToken.None);
}
/// <summary>
/// The get authorization rule operation gets an authorization rule for
/// a namespace by name.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace to get the authorization rule for.
/// </param>
/// <param name='entityName'>
/// Required. The entity name to get the authorization rule for.
/// </param>
/// <returns>
/// A response to a request for a particular authorization rule.
/// </returns>
public static ServiceBusAuthorizationRuleResponse GetAuthorizationRule(this INamespaceOperations operations, string namespaceName, string entityName)
{
return Task.Factory.StartNew((object s) =>
{
return ((INamespaceOperations)s).GetAuthorizationRuleAsync(namespaceName, entityName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The get authorization rule operation gets an authorization rule for
/// a namespace by name.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace to get the authorization rule for.
/// </param>
/// <param name='entityName'>
/// Required. The entity name to get the authorization rule for.
/// </param>
/// <returns>
/// A response to a request for a particular authorization rule.
/// </returns>
public static Task<ServiceBusAuthorizationRuleResponse> GetAuthorizationRuleAsync(this INamespaceOperations operations, string namespaceName, string entityName)
{
return operations.GetAuthorizationRuleAsync(namespaceName, entityName, CancellationToken.None);
}
/// <summary>
/// The namespace description is an XML AtomPub document that defines
/// the desired semantics for a service namespace. The namespace
/// description contains the following properties. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj873988.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <returns>
/// A response to a request for a list of namespaces.
/// </returns>
public static ServiceBusNamespaceDescriptionResponse GetNamespaceDescription(this INamespaceOperations operations, string namespaceName)
{
return Task.Factory.StartNew((object s) =>
{
return ((INamespaceOperations)s).GetNamespaceDescriptionAsync(namespaceName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The namespace description is an XML AtomPub document that defines
/// the desired semantics for a service namespace. The namespace
/// description contains the following properties. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj873988.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <returns>
/// A response to a request for a list of namespaces.
/// </returns>
public static Task<ServiceBusNamespaceDescriptionResponse> GetNamespaceDescriptionAsync(this INamespaceOperations operations, string namespaceName)
{
return operations.GetNamespaceDescriptionAsync(namespaceName, CancellationToken.None);
}
/// <summary>
/// Lists the available namespaces. (see
/// http://msdn.microsoft.com/en-us/library/azure/hh780759.aspx for
/// more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <returns>
/// The response to the request for a listing of namespaces.
/// </returns>
public static ServiceBusNamespacesResponse List(this INamespaceOperations operations)
{
return Task.Factory.StartNew((object s) =>
{
return ((INamespaceOperations)s).ListAsync();
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists the available namespaces. (see
/// http://msdn.microsoft.com/en-us/library/azure/hh780759.aspx for
/// more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <returns>
/// The response to the request for a listing of namespaces.
/// </returns>
public static Task<ServiceBusNamespacesResponse> ListAsync(this INamespaceOperations operations)
{
return operations.ListAsync(CancellationToken.None);
}
/// <summary>
/// The get authorization rules operation gets the authorization rules
/// for a namespace.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace to get the authorization rule for.
/// </param>
/// <returns>
/// A response to a request for a list of authorization rules.
/// </returns>
public static ServiceBusAuthorizationRulesResponse ListAuthorizationRules(this INamespaceOperations operations, string namespaceName)
{
return Task.Factory.StartNew((object s) =>
{
return ((INamespaceOperations)s).ListAuthorizationRulesAsync(namespaceName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The get authorization rules operation gets the authorization rules
/// for a namespace.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace to get the authorization rule for.
/// </param>
/// <returns>
/// A response to a request for a list of authorization rules.
/// </returns>
public static Task<ServiceBusAuthorizationRulesResponse> ListAuthorizationRulesAsync(this INamespaceOperations operations, string namespaceName)
{
return operations.ListAuthorizationRulesAsync(namespaceName, CancellationToken.None);
}
/// <summary>
/// The update authorization rule operation updates an authorization
/// rule for a namespace.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <param name='rule'>
/// Optional. Updated access authorization rule.
/// </param>
/// <returns>
/// A response to a request for a particular authorization rule.
/// </returns>
public static ServiceBusAuthorizationRuleResponse UpdateAuthorizationRule(this INamespaceOperations operations, string namespaceName, ServiceBusSharedAccessAuthorizationRule rule)
{
return Task.Factory.StartNew((object s) =>
{
return ((INamespaceOperations)s).UpdateAuthorizationRuleAsync(namespaceName, rule);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The update authorization rule operation updates an authorization
/// rule for a namespace.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <param name='rule'>
/// Optional. Updated access authorization rule.
/// </param>
/// <returns>
/// A response to a request for a particular authorization rule.
/// </returns>
public static Task<ServiceBusAuthorizationRuleResponse> UpdateAuthorizationRuleAsync(this INamespaceOperations operations, string namespaceName, ServiceBusSharedAccessAuthorizationRule rule)
{
return operations.UpdateAuthorizationRuleAsync(namespaceName, rule, CancellationToken.None);
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2008 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 NUnit.Framework.Internal;
namespace NUnit.Framework.Constraints
{
/// <summary>
/// ThrowsConstraint is used to test the exception thrown by
/// a delegate by applying a constraint to it.
/// </summary>
public class ThrowsConstraint : PrefixConstraint
{
private Exception caughtException;
/// <summary>
/// Initializes a new instance of the <see cref="ThrowsConstraint"/> class,
/// using a constraint to be applied to the exception.
/// </summary>
/// <param name="baseConstraint">A constraint to apply to the caught exception.</param>
public ThrowsConstraint(IConstraint baseConstraint)
: base(baseConstraint) { }
/// <summary>
/// Get the actual exception thrown - used by Assert.Throws.
/// </summary>
public Exception ActualException
{
get { return caughtException; }
}
#region Constraint Overrides
/// <summary>
/// Gets text describing a constraint
/// </summary>
public override string Description
{
get { return BaseConstraint.Description; }
}
/// <summary>
/// Executes the code of the delegate and captures any exception.
/// If a non-null base constraint was provided, it applies that
/// constraint to the exception.
/// </summary>
/// <param name="actual">A delegate representing the code to be tested</param>
/// <returns>True if an exception is thrown and the constraint succeeds, otherwise false</returns>
public override ConstraintResult ApplyTo<TActual>(TActual actual)
{
//TestDelegate code = actual as TestDelegate;
//if (code == null)
// throw new ArgumentException(
// string.Format("The actual value must be a TestDelegate but was {0}", actual.GetType().Name), "actual");
//caughtException = null;
//try
//{
// code();
//}
//catch (Exception ex)
//{
// caughtException = ex;
//}
caughtException = ExceptionInterceptor.Intercept(actual);
return new ThrowsConstraintResult(
this,
caughtException,
caughtException != null
? BaseConstraint.ApplyTo(caughtException)
: null);
}
/// <summary>
/// Converts an ActualValueDelegate to a TestDelegate
/// before calling the primary overload.
/// </summary>
/// <param name="del"></param>
/// <returns></returns>
public override ConstraintResult ApplyTo<TActual>(ActualValueDelegate<TActual> del)
{
//TestDelegate testDelegate = new TestDelegate(delegate { del(); });
//return ApplyTo((object)testDelegate);
return ApplyTo(new GenericInvocationDescriptor<TActual>(del));
}
#endregion
#region Nested Result Class
private class ThrowsConstraintResult : ConstraintResult
{
private readonly ConstraintResult baseResult;
public ThrowsConstraintResult(ThrowsConstraint constraint,
Exception caughtException,
ConstraintResult baseResult)
: base(constraint, caughtException)
{
if (caughtException != null && baseResult.IsSuccess)
Status = ConstraintStatus.Success;
else
Status = ConstraintStatus.Failure;
this.baseResult = baseResult;
}
/// <summary>
/// Write the actual value for a failing constraint test to a
/// MessageWriter. This override only handles the special message
/// used when an exception is expected but none is thrown.
/// </summary>
/// <param name="writer">The writer on which the actual value is displayed</param>
public override void WriteActualValueTo(MessageWriter writer)
{
if (ActualValue == null)
writer.Write("no exception thrown");
else
baseResult.WriteActualValueTo(writer);
}
}
#endregion
#region ExceptionInterceptor
internal class ExceptionInterceptor
{
private ExceptionInterceptor() { }
internal static Exception Intercept(object invocation)
{
var invocationDescriptor = GetInvocationDescriptor(invocation);
#if NET_4_0 || NET_4_5 || PORTABLE
if (AsyncInvocationRegion.IsAsyncOperation(invocationDescriptor.Delegate))
{
using (var region = AsyncInvocationRegion.Create(invocationDescriptor.Delegate))
{
try
{
object result = invocationDescriptor.Invoke();
region.WaitForPendingOperationsToComplete(result);
return null;
}
catch (Exception ex)
{
return ex;
}
}
}
else
#endif
{
try
{
invocationDescriptor.Invoke();
return null;
}
catch (Exception ex)
{
return ex;
}
}
}
private static IInvocationDescriptor GetInvocationDescriptor(object actual)
{
var invocationDescriptor = actual as IInvocationDescriptor;
if (invocationDescriptor == null)
{
var testDelegate = actual as TestDelegate;
if (testDelegate != null)
{
invocationDescriptor = new VoidInvocationDescriptor(testDelegate);
}
#if NET_4_0 || NET_4_5 || PORTABLE
else
{
var asyncTestDelegate = actual as AsyncTestDelegate;
if (asyncTestDelegate != null)
{
invocationDescriptor = new GenericInvocationDescriptor<System.Threading.Tasks.Task>(() => asyncTestDelegate());
}
}
#endif
}
if (invocationDescriptor == null)
throw new ArgumentException(
String.Format(
"The actual value must be a TestDelegate or AsyncTestDelegate but was {0}",
actual.GetType().Name),
"actual");
return invocationDescriptor;
}
}
#endregion
#region InvocationDescriptor
internal class GenericInvocationDescriptor<T> : IInvocationDescriptor
{
private readonly ActualValueDelegate<T> _del;
public GenericInvocationDescriptor(ActualValueDelegate<T> del)
{
_del = del;
}
public object Invoke()
{
return _del();
}
public Delegate Delegate
{
get { return _del; }
}
}
private interface IInvocationDescriptor
{
Delegate Delegate { get; }
object Invoke();
}
private class VoidInvocationDescriptor : IInvocationDescriptor
{
private readonly TestDelegate _del;
public VoidInvocationDescriptor(TestDelegate del)
{
_del = del;
}
public object Invoke()
{
_del();
return null;
}
public Delegate Delegate
{
get { return _del; }
}
}
#endregion
}
}
| |
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------
namespace System.Activities.Presentation
{
using System.Diagnostics;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Activities.Presentation.Hosting;
using System.Activities.Presentation.Model;
using System.Activities.Presentation.View;
using System.Windows.Threading;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Activities.Presentation.Internal.PropertyEditing;
using System.Runtime;
using System.Reflection;
using System.Activities.Presentation.Sqm;
using System.Collections.Generic;
using System.Windows.Controls;
using System.Linq;
using Microsoft.Activities.Presentation;
// This is a helper class for making dragdrop inside workflow designer easy. This abstracts out te encoding formats used in the
// DataObject that is passed on from Drag source to target.
public static class DragDropHelper
{
// Using a DependencyProperty as the backing store for MyProperty. This enables animation, styling, binding, etc...
public static readonly DependencyProperty DragSourceProperty =
DependencyProperty.RegisterAttached("DragSource", typeof(UIElement), typeof(DragDropHelper), new UIPropertyMetadata(null));
public static readonly string ModelItemDataFormat;
public static readonly string CompositeViewFormat;
public static readonly string CompletedEffectsFormat = "DragCompletedEffectsFormat";
public static readonly string WorkflowItemTypeNameFormat = "WorkflowItemTypeNameFormat";
public static readonly string DragAnchorPointFormat;
internal static readonly string ModelItemsDataFormat;
internal static readonly string MovedViewElementsFormat;
[SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline")]
static DragDropHelper()
{
string postfix = Guid.NewGuid().ToString();
//set per process unique data format names - this will disable possibility of trying to drag & drop operation
//between designers in two different VS instances (use Cut-Copy-Paste for that)
ModelItemDataFormat = string.Format(CultureInfo.InvariantCulture, "ModelItemFormat_{0}", postfix);
CompositeViewFormat = string.Format(CultureInfo.InvariantCulture, "CompositeViewFormat_{0}", postfix);
DragAnchorPointFormat = string.Format(CultureInfo.InvariantCulture, "DragAnchorFormat_{0}", postfix);
ModelItemsDataFormat = string.Format(CultureInfo.InvariantCulture, "ModelItemsFormat_{0}", postfix);
MovedViewElementsFormat = string.Format(CultureInfo.InvariantCulture, "MovedViewElementsFormat_{0}", postfix);
}
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
public static void SetCompositeView(WorkflowViewElement workflowViewElement, UIElement dragSource)
{
if (workflowViewElement == null)
{
throw FxTrace.Exception.ArgumentNull("workflowViewElement");
}
if (dragSource == null)
{
throw FxTrace.Exception.ArgumentNull("dragSource");
}
workflowViewElement.SetValue(DragDropHelper.DragSourceProperty, dragSource);
}
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
public static UIElement GetCompositeView(WorkflowViewElement workflowViewElement)
{
if (workflowViewElement == null)
{
throw FxTrace.Exception.ArgumentNull("workflowViewElement");
}
return (UIElement)workflowViewElement.GetValue(DragDropHelper.DragSourceProperty);
}
internal static DataObject DoDragMoveImpl(IEnumerable<WorkflowViewElement> draggedViewElements, Point referencePoint)
{
List<ModelItem> draggedModelItems = new List<ModelItem>();
bool first = true;
WorkflowViewElement viewElement = null;
foreach (WorkflowViewElement view in draggedViewElements)
{
if (view != null)
{
if (first)
{
viewElement = view;
first = false;
}
draggedModelItems.Add(view.ModelItem);
view.IsHitTestVisible = false;
}
}
DataObject dataObject = new DataObject(ModelItemsDataFormat, draggedModelItems);
// For compatiblity
if (viewElement != null)
{
dataObject.SetData(ModelItemDataFormat, viewElement.ModelItem);
dataObject.SetData(CompositeViewFormat, GetCompositeView(viewElement));
}
dataObject.SetData(DragAnchorPointFormat, referencePoint);
if (viewElement != null)
{
DesignerView designerView = viewElement.Context.Services.GetService<DesignerView>();
ViewElementDragShadow dragShadow = new ViewElementDragShadow(designerView.scrollableContent, draggedViewElements, referencePoint, designerView.ZoomFactor);
designerView.BeginDragShadowTracking(dragShadow);
//whenever drag drop fails - ensure getting rid of drag shadow
try
{
DragDrop.DoDragDrop(designerView, dataObject, DragDropEffects.Move | DragDropEffects.Copy | DragDropEffects.Scroll | DragDropEffects.Link);
}
catch
{
//let the caller handle exception
throw;
}
finally
{
designerView.EndDragShadowTracking(dragShadow);
foreach (WorkflowViewElement view in draggedViewElements)
{
if (view != null)
{
view.IsHitTestVisible = true;
}
}
}
}
return dataObject;
}
[Obsolete("This method does not support dragging multiple items. Use \"public static IEnumerable<WorkflowViewElement> DoDragMove(IEnumerable<WorkflowViewElement> draggedViewElements, Point referencePoint)\" instead.")]
public static DragDropEffects DoDragMove(WorkflowViewElement draggedViewElement, Point referencePoint)
{
if (draggedViewElement == null)
{
throw FxTrace.Exception.ArgumentNull("draggedViewElement");
}
if (referencePoint == null)
{
throw FxTrace.Exception.ArgumentNull("referencePoint");
}
ModelItem draggedActivityModelItem = draggedViewElement.ModelItem;
DataObject dataObject = new DataObject(ModelItemDataFormat, draggedActivityModelItem);
dataObject.SetData(CompositeViewFormat, GetCompositeView(draggedViewElement));
dataObject.SetData(DragAnchorPointFormat, referencePoint);
List<ModelItem> draggedModelItems = new List<ModelItem>();
draggedModelItems.Add(draggedActivityModelItem);
dataObject.SetData(ModelItemsDataFormat, draggedModelItems);
DesignerView view = draggedViewElement.Context.Services.GetService<DesignerView>();
ViewElementDragShadow dragShadow = new ViewElementDragShadow(view.scrollableContent, draggedViewElement, referencePoint, view.ZoomFactor);
draggedViewElement.IsHitTestVisible = false;
view.BeginDragShadowTracking(dragShadow);
//whenever drag drop fails - ensure getting rid of drag shadow
try
{
DragDrop.DoDragDrop(GetCompositeView(draggedViewElement), dataObject, DragDropEffects.Move | DragDropEffects.Copy | DragDropEffects.Scroll | DragDropEffects.Link);
}
catch
{
//let the caller handle exception
throw;
}
finally
{
view.EndDragShadowTracking(dragShadow);
draggedViewElement.IsHitTestVisible = true;
}
return GetDragDropCompletedEffects(dataObject);
}
public static bool AllowDrop(IDataObject draggedDataObject, EditingContext context, params Type[] allowedItemTypes)
{
if (draggedDataObject == null)
{
throw FxTrace.Exception.ArgumentNull("draggedDataObject");
}
if (context == null)
{
throw FxTrace.Exception.ArgumentNull("context");
}
if (allowedItemTypes == null)
{
throw FxTrace.Exception.ArgumentNull("allowedItemTypes");
}
ReadOnlyState readOnlyState = context.Items.GetValue<ReadOnlyState>();
if (readOnlyState != null && readOnlyState.IsReadOnly)
{
return false;
}
if (!AllowDrop(draggedDataObject, context))
{
return false;
}
List<Type> draggedTypes = GetDraggedTypes(draggedDataObject);
return draggedTypes != null
&& draggedTypes.Count != 0
&& draggedTypes.All<Type>((p) =>
{
for (int i = 0; i < allowedItemTypes.Length; ++i)
{
if (allowedItemTypes[i] == null)
{
throw FxTrace.Exception.ArgumentNull(string.Format(CultureInfo.InvariantCulture, "allowedItemTypes[{0}]", i));
}
if (AllowDrop(p, allowedItemTypes[i]))
{
return true;
}
}
return false;
});
}
static bool AllowDrop(IDataObject draggedDataObject, EditingContext context)
{
ModelItem droppedModelItem = draggedDataObject.GetData(ModelItemDataFormat) as ModelItem;
if (droppedModelItem == null)
{
return true;
}
return ((IModelTreeItem)droppedModelItem).ModelTreeManager.Context.Equals(context);
}
internal static bool AllowDrop(Type draggedType, Type allowedItemType)
{
if (draggedType == null)
{
// This is the case where some external stuff (e.g. Recycle bin) get dragged over.
return false;
}
// This is a special case in GetDroppedObject() and replicated here.
// Check whether dragged type is IActivityTemplateFactory, if true, use Factory's implement type instead.
Type factoryType;
if (draggedType.TryGetActivityTemplateFactory(out factoryType))
{
draggedType = factoryType;
}
if (allowedItemType.IsAssignableFrom(draggedType))
{
return true;
}
else if (allowedItemType.IsGenericTypeDefinition && draggedType.IsGenericType)
{
// We don't have inheritance relationship for GenericTypeDefinition, therefore the right check is equality
return allowedItemType.Equals(draggedType.GetGenericTypeDefinition());
}
else if (allowedItemType.IsGenericType && draggedType.IsGenericTypeDefinition)
{
// Allow GenericTypeDefinition to be dropped with GenericType constraint, if user select a correct argument type, drop should work.
return draggedType.Equals(allowedItemType.GetGenericTypeDefinition());
}
else if (allowedItemType.IsGenericType && draggedType.IsGenericType && draggedType.ContainsGenericParameters)
{
// If the draggedType is generic type but it contains generic parameters, which may happen to match the constraint.
return allowedItemType.GetGenericTypeDefinition() == draggedType.GetGenericTypeDefinition();
}
else
{
return false;
}
}
internal static List<Type> GetDraggedTypes(IDataObject draggedDataObject)
{
List<Type> types = new List<Type>();
if (draggedDataObject != null)
{
if (draggedDataObject.GetDataPresent(ModelItemsDataFormat))
{
IEnumerable<ModelItem> modelItems = draggedDataObject.GetData(ModelItemsDataFormat) as IEnumerable<ModelItem>;
foreach (ModelItem modelItem in modelItems)
{
if (modelItem != null)
{
types.Add(modelItem.ItemType);
}
}
}
else if (draggedDataObject.GetDataPresent(ModelItemDataFormat))
{
ModelItem modelItem = draggedDataObject.GetData(ModelItemDataFormat) as ModelItem;
if (modelItem != null)
{
types.Add(modelItem.ItemType);
}
}
// This is an object dragged from somewhere else other than from within the designer surface
if (draggedDataObject.GetDataPresent(WorkflowItemTypeNameFormat))
{
// This is the case where the object is dropped from the toolbox
string text = draggedDataObject.GetData(WorkflowItemTypeNameFormat) as string;
if (!string.IsNullOrEmpty(text))
{
types.Add(Type.GetType(text));
}
}
}
return types;
}
internal static bool IsDraggingFromToolbox(DragEventArgs e)
{
return e.Data.GetDataPresent(WorkflowItemTypeNameFormat);
}
public static IEnumerable<object> GetDroppedObjects(DependencyObject dropTarget, DragEventArgs e, EditingContext context)
{
List<object> droppedObjects = new List<object>();
if (e.Data.GetDataPresent(ModelItemsDataFormat))
{
IEnumerable<ModelItem> droppedModelItems = e.Data.GetData(ModelItemsDataFormat) as IEnumerable<ModelItem>;
foreach (ModelItem modelItem in droppedModelItems)
{
droppedObjects.Add(modelItem);
}
}
else
{
object droppedObject = e.Data.GetData(ModelItemDataFormat) as ModelItem;
// could have been dropped from toolbox.
if (droppedObject == null)
{
Type type = null;
if (e.Data.GetDataPresent(WorkflowItemTypeNameFormat))
{
string text = e.Data.GetData(WorkflowItemTypeNameFormat) as string;
if (!string.IsNullOrEmpty(text))
{
//try to use the text format to see if it holds a type name and try to create an object out of it.
type = Type.GetType(text);
}
}
droppedObject = GetDroppedObjectInstance(dropTarget, context, type, e.Data);
}
if (droppedObject != null)
{
droppedObjects.Add(droppedObject);
}
}
e.Handled = true;
context.Services.GetService<DesignerPerfEventProvider>().WorkflowDesignerDrop();
Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle,
new Action(() =>
{
context.Services.GetService<DesignerPerfEventProvider>().WorkflowDesignerIdleAfterDrop();
}));
return droppedObjects;
}
internal static void ValidateItemsAreOnView(IList<ModelItem> items, ICollection<ModelItem> modelItemsOnView)
{
Fx.Assert(items != null, "items");
Fx.Assert(modelItemsOnView != null, "modelItemsOnView");
for (int index = 0; index < items.Count; ++index)
{
if (!modelItemsOnView.Contains(items[index]))
{
throw FxTrace.Exception.AsError(
new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.Error_ItemNotOnView, index)));
}
}
}
[Obsolete("This method does not support dropping multiple items. Use \"public static IEnumerable<object> GetDroppedObjects(DependencyObject dropTarget, DragEventArgs e, EditingContext context)\" instead.")]
public static object GetDroppedObject(DependencyObject dropTarget, DragEventArgs e, EditingContext context)
{
IEnumerable<object> droppedObjects = GetDroppedObjects(dropTarget, e, context);
if (droppedObjects.Count() > 0)
{
return droppedObjects.First();
}
return null;
}
[SuppressMessage(FxCop.Category.Design, FxCop.Rule.DoNotCatchGeneralExceptionTypes,
Justification = "Any exception can be thrown from custom code. We don't want to crash VS.")]
[SuppressMessage("Reliability", "Reliability108",
Justification = "Any exception can be thrown from custom code. We don't want to crash VS.")]
internal static object GetDroppedObjectInstance(DependencyObject dropTarget, EditingContext context, Type type, IDataObject dataObject)
{
if (type != null)
{
//check if type is generic
if (type.IsGenericTypeDefinition)
{
type = ResolveGenericParameters(dropTarget, context, type);
}
}
object droppedObject = null;
if (null != type)
{
try
{
droppedObject = Activator.CreateInstance(type);
if (type.IsActivityTemplateFactory() && type.IsClass)
{
//find parent WorkflowViewElement - in case of mouse drop, current drop target most likely is ISourceContainer
if (!(dropTarget is WorkflowViewElement))
{
dropTarget = VisualTreeUtils.FindVisualAncestor<WorkflowViewElement>(dropTarget);
}
Type templateFactoryInterface2 = type.GetInterface(typeof(IActivityTemplateFactory<>).FullName);
if (templateFactoryInterface2 != null)
{
droppedObject = templateFactoryInterface2.InvokeMember("Create", BindingFlags.InvokeMethod, null, droppedObject, new object[] { dropTarget, dataObject }, CultureInfo.InvariantCulture);
}
else if (droppedObject is IActivityTemplateFactory)
{
droppedObject = ((IActivityTemplateFactory)droppedObject).Create(dropTarget);
}
}
// SQM: Log activity usage count
ActivityUsageCounter.ReportUsage(context.Services.GetService<IVSSqmService>(), type);
}
catch (Exception ex)
{
if (Fx.IsFatal(ex))
{
throw;
}
string details = ex.Message;
if (ex is TargetInvocationException && ex.InnerException != null)
{
details = ex.InnerException.Message;
}
ErrorReporting.ShowErrorMessage(string.Format(CultureInfo.CurrentUICulture, SR.CannotCreateInstance, TypeNameHelper.GetDisplayName(type, false)), details);
}
}
return droppedObject;
}
static Type ResolveGenericParameters(DependencyObject dropTarget, EditingContext context, Type type)
{
// look to see if there is a DefaultTypeArgumentAttribute on it
DefaultTypeArgumentAttribute typeArgumentAttribute = ExtensibilityAccessor.GetAttribute<DefaultTypeArgumentAttribute>(type);
if (typeArgumentAttribute != null && typeArgumentAttribute.Type != null)
{
type = type.MakeGenericType(typeArgumentAttribute.Type);
}
else //require user to resolve generic arguments
{
ActivityTypeResolver wnd = new ActivityTypeResolver();
if (null != context)
{
WindowHelperService service = context.Services.GetService<WindowHelperService>();
if (null != service)
{
service.TrySetWindowOwner(dropTarget, wnd);
}
}
TypeResolvingOptions dropTargetOptions = null;
TypeResolvingOptions activityTypeOptions = null;
//try to see if the container has any customization for type resolver
ICompositeView container = dropTarget as ICompositeView;
if (container != null)
{
dropTargetOptions = container.DroppingTypeResolvingOptions;
}
//try to see if the activity type in discourse has any customization for type resolver
TypeResolvingOptionsAttribute attr = WorkflowViewService.GetAttribute<TypeResolvingOptionsAttribute>(type);
if (attr != null)
{
activityTypeOptions = attr.TypeResolvingOptions;
}
//if both have type resolver, try to merge them
TypeResolvingOptions options = TypeResolvingOptions.Merge(dropTargetOptions, activityTypeOptions);
if (options != null)
{
wnd.Options = options;
}
wnd.Context = context;
wnd.EditedType = type;
wnd.Width = 340;
wnd.Height = 200;
type = (true == wnd.ShowDialog() ? wnd.ConcreteType : null);
}
return type;
}
[Obsolete("This method does not support dragging multiple items. Use \"public static IEnumerable<ModelItem> GetDraggedModelItems(DragEventArgs e)\" instead.")]
public static ModelItem GetDraggedModelItem(DragEventArgs e)
{
return GetDraggedModelItemInternal(e);
}
internal static ModelItem GetDraggedModelItemInternal(DragEventArgs e)
{
IEnumerable<ModelItem> draggedModelItems = GetDraggedModelItems(e);
if (draggedModelItems.Count() > 0)
{
return draggedModelItems.First();
}
return null;
}
public static IEnumerable<ModelItem> GetDraggedModelItems(DragEventArgs e)
{
IEnumerable<ModelItem> draggedModelItems = e.Data.GetData(ModelItemsDataFormat) as IEnumerable<ModelItem>;
if (draggedModelItems != null)
{
return draggedModelItems;
}
else
{
ModelItem draggedItem = e.Data.GetData(ModelItemDataFormat) as ModelItem;
if (draggedItem != null)
{
return new ModelItem[] { draggedItem };
}
}
return new ModelItem[] { };
}
internal static bool AreListsIdenticalExceptOrder<T>(IList<T> sourceList, IList<T> destinationList)
{
// User does not
// 1) introduce unseen object into the collection.
// 2) remove object from the collection.
// 3) introduce null in the collection.
// 4) return null
if (sourceList == null)
{
return destinationList == null;
}
if (destinationList == null)
{
return false;
}
if (sourceList.Count != destinationList.Count)
{
return false;
}
HashSet<T> checkingMap = new HashSet<T>();
// create set
foreach (T item in sourceList)
{
bool ret = checkingMap.Add(item);
// an internal error, the item in src should be identical.
Fx.Assert(ret, "item in source list is not identical?");
}
foreach (T item in destinationList)
{
if (!checkingMap.Remove(item))
{
return false;
}
}
return checkingMap.Count == 0;
}
// 1) obj with CompositeView2: sort by IMultipleDragEnabledCompositeView SortSelectedItems.
// 2) obj with CompoisteView: no sort.
// 3) obj without CompositeView: just put them at the end of the list as the order in selectedObjects.
internal static List<object> SortSelectedObjects(IEnumerable<object> selectedObjects)
{
//1) Separate objects
Dictionary<ICompositeView, List<ModelItem>> viewItemListDictionary = new Dictionary<ICompositeView, List<ModelItem>>();
List<object> nonCompositeView = new List<object>();
List<object> retList = new List<object>();
foreach (object obj in selectedObjects)
{
ModelItem modelItem = obj as ModelItem;
if (modelItem == null || modelItem.View == null)
{
nonCompositeView.Add(obj);
continue;
}
ICompositeView container = DragDropHelper
.GetCompositeView(modelItem.View as WorkflowViewElement) as ICompositeView;
if (container == null)
{
nonCompositeView.Add(obj);
continue;
}
// add to dictionary.
if (!viewItemListDictionary.ContainsKey(container))
{
viewItemListDictionary.Add(container, new List<ModelItem>());
}
viewItemListDictionary[container].Add(modelItem);
}
// 2) sort when possible
foreach (KeyValuePair<ICompositeView, List<ModelItem>> pair in viewItemListDictionary)
{
IMultipleDragEnabledCompositeView view2 = pair.Key as IMultipleDragEnabledCompositeView;
List<ModelItem> sortedList = view2 == null ?
pair.Value : view2.SortSelectedItems(new List<ModelItem>(pair.Value));
if (!AreListsIdenticalExceptOrder(pair.Value, sortedList))
{
// check consistens.
throw FxTrace.Exception.AsError(
new InvalidOperationException(SR.Error_BadOutputFromSortSelectedItems));
}
retList.AddRange(sortedList);
}
retList.AddRange(nonCompositeView);
return retList;
}
[Obsolete("This method does not support dragging multiple items. Use \"public static UIElement GetCompositeView(WorkflowViewElement workflowViewElement)\" instead.")]
public static ICompositeView GetCompositeView(DragEventArgs e)
{
return (ICompositeView)e.Data.GetData(CompositeViewFormat);
}
public static Point GetDragDropAnchorPoint(DragEventArgs e)
{
Point referencePoint;
if (e.Data.GetDataPresent(DragAnchorPointFormat))
{
referencePoint = (Point)e.Data.GetData(DragAnchorPointFormat);
}
else
{
referencePoint = new Point(-1, -1);
}
return referencePoint;
}
[Obsolete("This method does not support dragging multiple items. Consider using \"public static void SetDragDropMovedViewElements(DragEventArgs e, IEnumerable<WorkflowViewElement> movedViewElements)\" instead.")]
public static void SetDragDropCompletedEffects(DragEventArgs e, DragDropEffects completedEffects)
{
try
{
e.Data.SetData(CompletedEffectsFormat, completedEffects);
}
catch (InvalidOperationException exception)
{
Trace.WriteLine(exception.ToString());
}
}
[Obsolete("This method does not support dragging multiple items. Consider using \"public static IEnumerable<WorkflowViewElement> GetDragDropMovedViewElements(DataObject data)\" instead.")]
public static DragDropEffects GetDragDropCompletedEffects(DataObject data)
{
if (data == null)
{
throw FxTrace.Exception.ArgumentNull("data");
}
DragDropEffects completedEffects = DragDropEffects.None;
if (data.GetDataPresent(CompletedEffectsFormat))
{
completedEffects = (DragDropEffects)data.GetData(CompletedEffectsFormat);
}
return completedEffects;
}
internal static void SetDragDropMovedViewElements(DragEventArgs e, IEnumerable<WorkflowViewElement> movedViewElements)
{
if (e == null)
{
throw FxTrace.Exception.ArgumentNull("e");
}
if (movedViewElements == null)
{
throw FxTrace.Exception.ArgumentNull("movedViewElements");
}
try
{
e.Data.SetData(MovedViewElementsFormat, movedViewElements);
}
catch (InvalidOperationException exception)
{
Trace.WriteLine(exception.ToString());
}
}
internal static IEnumerable<WorkflowViewElement> GetDragDropMovedViewElements(DataObject data)
{
if (data == null)
{
throw FxTrace.Exception.ArgumentNull("data");
}
if (data.GetDataPresent(MovedViewElementsFormat))
{
return (IEnumerable<WorkflowViewElement>)data.GetData(MovedViewElementsFormat);
}
return null;
}
internal static int GetDraggedObjectCount(DragEventArgs e)
{
return GetDraggedTypes(e.Data).Count;
}
internal static Dictionary<WorkflowViewElement, Point> GetViewElementRelativeLocations(IEnumerable<WorkflowViewElement> viewElements)
{
DesignerView designerView = null;
Dictionary<WorkflowViewElement, Point> locations = new Dictionary<WorkflowViewElement, Point>();
Point topLeftPoint = new Point(double.PositiveInfinity, double.PositiveInfinity);
foreach (WorkflowViewElement viewElement in viewElements)
{
if (designerView == null)
{
designerView = viewElement.Context.Services.GetService<DesignerView>();
}
Point location = new Point(0, 0);
if (designerView.scrollableContent.IsAncestorOf(viewElement))
{
GeneralTransform transform = viewElement.TransformToAncestor(designerView.scrollableContent);
location = transform.Transform(new Point(0, 0));
}
if (location.X < topLeftPoint.X)
{
topLeftPoint.X = location.X;
}
if (location.Y < topLeftPoint.Y)
{
topLeftPoint.Y = location.Y;
}
locations.Add(viewElement, location);
}
foreach (WorkflowViewElement viewElement in viewElements)
{
locations[viewElement] = Vector.Add(new Vector(-topLeftPoint.X, -topLeftPoint.Y), locations[viewElement]);
}
return locations;
}
internal static Dictionary<WorkflowViewElement, Point> GetDraggedViewElementRelativeLocations(DragEventArgs e)
{
List<WorkflowViewElement> draggedViewElements = new List<WorkflowViewElement>();
if (e.Data.GetDataPresent(ModelItemsDataFormat))
{
IEnumerable<ModelItem> draggedModelItems = e.Data.GetData(ModelItemsDataFormat) as IEnumerable<ModelItem>;
if (draggedModelItems != null)
{
foreach (ModelItem draggedModelItem in draggedModelItems)
{
if (draggedModelItem != null && draggedModelItem.View != null)
{
draggedViewElements.Add((WorkflowViewElement)draggedModelItem.View);
}
}
}
}
else if (e.Data.GetDataPresent(ModelItemDataFormat))
{
ModelItem draggedModelItem = e.Data.GetData(ModelItemDataFormat) as ModelItem;
if (draggedModelItem != null && draggedModelItem.View != null)
{
draggedViewElements.Add((WorkflowViewElement)draggedModelItem.View);
}
}
return GetViewElementRelativeLocations(draggedViewElements);
}
// Get rid of descendant model items when both ancestor and descendant and ancestor model items are selected
internal static IEnumerable<ModelItem> GetModelItemsToDrag(IEnumerable<ModelItem> modelItems)
{
HashSet<ModelItem> modelItemsToDrag = new HashSet<ModelItem>();
foreach (ModelItem modelItem in modelItems)
{
HashSet<ModelItem> parentModelItems = CutCopyPasteHelper.GetSelectableParentModelItems(modelItem);
parentModelItems.IntersectWith(modelItems);
if (parentModelItems.Count == 0)
{
modelItemsToDrag.Add(modelItem);
}
}
return modelItemsToDrag;
}
internal sealed class ViewElementDragShadow : Adorner
{
Rectangle content;
double x;
double y;
double offsetX;
double offsetY;
double scaleFactor;
double width;
double height;
AdornerLayer layer;
public ViewElementDragShadow(UIElement owner, WorkflowViewElement viewElement, Point offset, double scaleFactor)
: base(owner)
{
Rect bounds = VisualTreeHelper.GetDescendantBounds(viewElement);
this.width = bounds.Width;
this.height = bounds.Height;
this.content = new Rectangle()
{
Width = this.width,
Height = this.height,
Fill = new VisualBrush(viewElement)
{
Opacity = 0.6
}
};
this.InitializeCommon(offset, scaleFactor);
}
public ViewElementDragShadow(UIElement owner, IEnumerable<WorkflowViewElement> viewElements, Point offset, double scaleFactor)
: base(owner)
{
Dictionary<WorkflowViewElement, Point> locations = DragDropHelper.GetViewElementRelativeLocations(viewElements);
Grid grid = new Grid();
foreach (WorkflowViewElement viewElement in viewElements)
{
Rect bounds = VisualTreeHelper.GetDescendantBounds(viewElement);
Rectangle rectangle = new Rectangle()
{
Width = bounds.Width,
Height = bounds.Height,
Fill = new VisualBrush(viewElement),
Margin = new Thickness(locations[viewElement].X, locations[viewElement].Y, 0, 0),
VerticalAlignment = VerticalAlignment.Top,
HorizontalAlignment = HorizontalAlignment.Left
};
grid.Children.Add(rectangle);
}
grid.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
this.width = grid.DesiredSize.Width;
this.height = grid.DesiredSize.Height;
this.content = new Rectangle()
{
Width = this.width,
Height = this.height,
Fill = new VisualBrush(grid)
{
Opacity = 0.6
}
};
this.InitializeCommon(offset, scaleFactor);
}
internal void UpdatePosition(double x, double y)
{
if (this.Visibility == Visibility.Hidden)
{
this.Visibility = Visibility.Visible;
}
double oldX = this.x;
double oldY = this.y;
this.x = x - this.offsetX;
this.y = y - this.offsetY;
if (oldX != this.x || oldY != this.y)
{
this.layer = this.Parent as AdornerLayer;
this.layer.Update(this.AdornedElement);
}
}
public override GeneralTransform GetDesiredTransform(GeneralTransform transform)
{
GeneralTransformGroup result = new GeneralTransformGroup();
result.Children.Add(new TranslateTransform(this.x, this.y));
result.Children.Add(new ScaleTransform(this.scaleFactor, this.scaleFactor, this.x, this.y));
return result;
}
protected override Visual GetVisualChild(int index)
{
return this.content;
}
protected override int VisualChildrenCount
{
get { return 1; }
}
protected override Size ArrangeOverride(Size finalSize)
{
this.content.Arrange(new Rect(this.content.DesiredSize));
System.Diagnostics.Debug.WriteLine("DragShadow.ArrangeOverride " + this.content.DesiredSize);
return this.content.DesiredSize;
}
protected override Size MeasureOverride(Size constraint)
{
this.content.Measure(constraint);
System.Diagnostics.Debug.WriteLine("DragShadow.MeasureOverride " + this.content.DesiredSize);
return this.content.DesiredSize;
}
private void InitializeCommon(Point offset, double scaleFactor)
{
this.offsetX = offset.X * scaleFactor;
this.offsetY = offset.Y * scaleFactor;
this.Visibility = Visibility.Hidden;
this.scaleFactor = scaleFactor;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Description;
using Service.Areas.HelpPage.Models;
namespace Service.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
model = GenerateApiModel(apiDescription, sampleGenerator);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator)
{
HelpPageApiModel apiModel = new HelpPageApiModel();
apiModel.ApiDescription = apiDescription;
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message));
}
return apiModel;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
#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;
using System.Globalization;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections.Generic;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json.Utilities
{
internal static class BufferUtils
{
public static char[] RentBuffer(IArrayPool<char> bufferPool, int minSize)
{
if (bufferPool == null)
{
return new char[minSize];
}
char[] buffer = bufferPool.Rent(minSize);
return buffer;
}
public static void ReturnBuffer(IArrayPool<char> bufferPool, char[] buffer)
{
if (bufferPool == null)
{
return;
}
bufferPool.Return(buffer);
}
public static char[] EnsureBufferSize(IArrayPool<char> bufferPool, int size, char[] buffer)
{
if (bufferPool == null)
{
return new char[size];
}
if (buffer != null)
{
bufferPool.Return(buffer);
}
return bufferPool.Rent(size);
}
}
internal static class JavaScriptUtils
{
internal static readonly bool[] SingleQuoteCharEscapeFlags = new bool[128];
internal static readonly bool[] DoubleQuoteCharEscapeFlags = new bool[128];
internal static readonly bool[] HtmlCharEscapeFlags = new bool[128];
private const int UnicodeTextLength = 6;
static JavaScriptUtils()
{
IList<char> escapeChars = new List<char>
{
'\n', '\r', '\t', '\\', '\f', '\b',
};
for (int i = 0; i < ' '; i++)
{
escapeChars.Add((char)i);
}
foreach (var escapeChar in escapeChars.Union(new[] { '\'' }))
{
SingleQuoteCharEscapeFlags[escapeChar] = true;
}
foreach (var escapeChar in escapeChars.Union(new[] { '"' }))
{
DoubleQuoteCharEscapeFlags[escapeChar] = true;
}
foreach (var escapeChar in escapeChars.Union(new[] { '"', '\'', '<', '>', '&' }))
{
HtmlCharEscapeFlags[escapeChar] = true;
}
}
private const string EscapedUnicodeText = "!";
public static bool[] GetCharEscapeFlags(StringEscapeHandling stringEscapeHandling, char quoteChar)
{
if (stringEscapeHandling == StringEscapeHandling.EscapeHtml)
{
return HtmlCharEscapeFlags;
}
if (quoteChar == '"')
{
return DoubleQuoteCharEscapeFlags;
}
return SingleQuoteCharEscapeFlags;
}
public static bool ShouldEscapeJavaScriptString(string s, bool[] charEscapeFlags)
{
if (s == null)
{
return false;
}
foreach (char c in s)
{
if (c >= charEscapeFlags.Length || charEscapeFlags[c])
{
return true;
}
}
return false;
}
public static void WriteEscapedJavaScriptString(TextWriter writer, string s, char delimiter, bool appendDelimiters,
bool[] charEscapeFlags, StringEscapeHandling stringEscapeHandling, IArrayPool<char> bufferPool, ref char[] writeBuffer)
{
// leading delimiter
if (appendDelimiters)
{
writer.Write(delimiter);
}
if (s != null)
{
int lastWritePosition = 0;
for (int i = 0; i < s.Length; i++)
{
var c = s[i];
if (c < charEscapeFlags.Length && !charEscapeFlags[c])
{
continue;
}
string escapedValue;
switch (c)
{
case '\t':
escapedValue = @"\t";
break;
case '\n':
escapedValue = @"\n";
break;
case '\r':
escapedValue = @"\r";
break;
case '\f':
escapedValue = @"\f";
break;
case '\b':
escapedValue = @"\b";
break;
case '\\':
escapedValue = @"\\";
break;
case '\u0085': // Next Line
escapedValue = @"\u0085";
break;
case '\u2028': // Line Separator
escapedValue = @"\u2028";
break;
case '\u2029': // Paragraph Separator
escapedValue = @"\u2029";
break;
default:
if (c < charEscapeFlags.Length || stringEscapeHandling == StringEscapeHandling.EscapeNonAscii)
{
if (c == '\'' && stringEscapeHandling != StringEscapeHandling.EscapeHtml)
{
escapedValue = @"\'";
}
else if (c == '"' && stringEscapeHandling != StringEscapeHandling.EscapeHtml)
{
escapedValue = @"\""";
}
else
{
if (writeBuffer == null || writeBuffer.Length < UnicodeTextLength)
{
writeBuffer = BufferUtils.EnsureBufferSize(bufferPool, UnicodeTextLength, writeBuffer);
}
StringUtils.ToCharAsUnicode(c, writeBuffer);
// slightly hacky but it saves multiple conditions in if test
escapedValue = EscapedUnicodeText;
}
}
else
{
escapedValue = null;
}
break;
}
if (escapedValue == null)
{
continue;
}
bool isEscapedUnicodeText = string.Equals(escapedValue, EscapedUnicodeText);
if (i > lastWritePosition)
{
int length = i - lastWritePosition + ((isEscapedUnicodeText) ? UnicodeTextLength : 0);
int start = (isEscapedUnicodeText) ? UnicodeTextLength : 0;
if (writeBuffer == null || writeBuffer.Length < length)
{
char[] newBuffer = BufferUtils.RentBuffer(bufferPool, length);
// the unicode text is already in the buffer
// copy it over when creating new buffer
if (isEscapedUnicodeText)
{
Array.Copy(writeBuffer, newBuffer, UnicodeTextLength);
}
BufferUtils.ReturnBuffer(bufferPool, writeBuffer);
writeBuffer = newBuffer;
}
s.CopyTo(lastWritePosition, writeBuffer, start, length - start);
// write unchanged chars before writing escaped text
writer.Write(writeBuffer, start, length - start);
}
lastWritePosition = i + 1;
if (!isEscapedUnicodeText)
{
writer.Write(escapedValue);
}
else
{
writer.Write(writeBuffer, 0, UnicodeTextLength);
}
}
if (lastWritePosition == 0)
{
// no escaped text, write entire string
writer.Write(s);
}
else
{
int length = s.Length - lastWritePosition;
if (writeBuffer == null || writeBuffer.Length < length)
{
writeBuffer = BufferUtils.EnsureBufferSize(bufferPool, length, writeBuffer);
}
s.CopyTo(lastWritePosition, writeBuffer, 0, length);
// write remaining text
writer.Write(writeBuffer, 0, length);
}
}
// trailing delimiter
if (appendDelimiters)
{
writer.Write(delimiter);
}
}
public static string ToEscapedJavaScriptString(string value, char delimiter, bool appendDelimiters, StringEscapeHandling stringEscapeHandling)
{
bool[] charEscapeFlags = GetCharEscapeFlags(stringEscapeHandling, delimiter);
using (StringWriter w = StringUtils.CreateStringWriter(StringUtils.GetLength(value) ?? 16))
{
char[] buffer = null;
WriteEscapedJavaScriptString(w, value, delimiter, appendDelimiters, charEscapeFlags, stringEscapeHandling, null, ref buffer);
return w.ToString();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net.Cache;
using System.Net.Http;
using System.Net.Security;
using System.Runtime.Serialization;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net
{
public delegate void HttpContinueDelegate(int StatusCode, WebHeaderCollection httpHeaders);
public class HttpWebRequest : WebRequest, ISerializable
{
private const int DefaultContinueTimeout = 350; // Current default value from .NET Desktop.
private const int DefaultReadWriteTimeout = 5 * 60 * 1000; // 5 minutes
private WebHeaderCollection _webHeaderCollection = new WebHeaderCollection();
private readonly Uri _requestUri;
private string _originVerb = HttpMethod.Get.Method;
// We allow getting and setting this (to preserve app-compat). But we don't do anything with it
// as the underlying System.Net.Http API doesn't support it.
private int _continueTimeout = DefaultContinueTimeout;
private bool _allowReadStreamBuffering = false;
private CookieContainer _cookieContainer = null;
private ICredentials _credentials = null;
private IWebProxy _proxy = WebRequest.DefaultWebProxy;
private Task<HttpResponseMessage> _sendRequestTask;
private static int _defaultMaxResponseHeadersLength = HttpHandlerDefaults.DefaultMaxResponseHeadersLength;
private int _beginGetRequestStreamCalled = 0;
private int _beginGetResponseCalled = 0;
private int _endGetRequestStreamCalled = 0;
private int _endGetResponseCalled = 0;
private int _maximumAllowedRedirections = HttpHandlerDefaults.DefaultMaxAutomaticRedirections;
private int _maximumResponseHeadersLen = _defaultMaxResponseHeadersLength;
private ServicePoint _servicePoint;
private int _timeout = WebRequest.DefaultTimeoutMilliseconds;
private int _readWriteTimeout = DefaultReadWriteTimeout;
private HttpContinueDelegate _continueDelegate;
// stores the user provided Host header as Uri. If the user specified a default port explicitly we'll lose
// that information when converting the host string to a Uri. _HostHasPort will store that information.
private bool _hostHasPort;
private Uri _hostUri;
private RequestStream _requestStream;
private TaskCompletionSource<Stream> _requestStreamOperation = null;
private TaskCompletionSource<WebResponse> _responseOperation = null;
private AsyncCallback _requestStreamCallback = null;
private AsyncCallback _responseCallback = null;
private int _abortCalled = 0;
private CancellationTokenSource _sendRequestCts;
private X509CertificateCollection _clientCertificates;
private Booleans _booleans = Booleans.Default;
private bool _pipelined = true;
private bool _preAuthenticate;
private DecompressionMethods _automaticDecompression = HttpHandlerDefaults.DefaultAutomaticDecompression;
private static readonly object s_syncRoot = new object();
private static volatile HttpClient s_cachedHttpClient;
private static HttpClientParameters s_cachedHttpClientParameters;
//these should be safe.
[Flags]
private enum Booleans : uint
{
AllowAutoRedirect = 0x00000001,
AllowWriteStreamBuffering = 0x00000002,
ExpectContinue = 0x00000004,
ProxySet = 0x00000010,
UnsafeAuthenticatedConnectionSharing = 0x00000040,
IsVersionHttp10 = 0x00000080,
SendChunked = 0x00000100,
EnableDecompression = 0x00000200,
IsTunnelRequest = 0x00000400,
IsWebSocketRequest = 0x00000800,
Default = AllowAutoRedirect | AllowWriteStreamBuffering | ExpectContinue
}
private class HttpClientParameters
{
public readonly DecompressionMethods AutomaticDecompression;
public readonly bool AllowAutoRedirect;
public readonly int MaximumAutomaticRedirections;
public readonly int MaximumResponseHeadersLength;
public readonly bool PreAuthenticate;
public readonly TimeSpan Timeout;
public readonly SecurityProtocolType SslProtocols;
public readonly bool CheckCertificateRevocationList;
public readonly ICredentials Credentials;
public readonly IWebProxy Proxy;
public readonly RemoteCertificateValidationCallback ServerCertificateValidationCallback;
public readonly X509CertificateCollection ClientCertificates;
public readonly CookieContainer CookieContainer;
public HttpClientParameters(HttpWebRequest webRequest)
{
AutomaticDecompression = webRequest.AutomaticDecompression;
AllowAutoRedirect = webRequest.AllowAutoRedirect;
MaximumAutomaticRedirections = webRequest.MaximumAutomaticRedirections;
MaximumResponseHeadersLength = webRequest.MaximumResponseHeadersLength;
PreAuthenticate = webRequest.PreAuthenticate;
Timeout = webRequest.Timeout == Threading.Timeout.Infinite
? Threading.Timeout.InfiniteTimeSpan
: TimeSpan.FromMilliseconds(webRequest.Timeout);
SslProtocols = ServicePointManager.SecurityProtocol;
CheckCertificateRevocationList = ServicePointManager.CheckCertificateRevocationList;
Credentials = webRequest._credentials;
Proxy = webRequest._proxy;
ServerCertificateValidationCallback = webRequest.ServerCertificateValidationCallback ?? ServicePointManager.ServerCertificateValidationCallback;
ClientCertificates = webRequest._clientCertificates;
CookieContainer = webRequest._cookieContainer;
}
public bool Matches(HttpClientParameters requestParameters)
{
return AutomaticDecompression == requestParameters.AutomaticDecompression
&& AllowAutoRedirect == requestParameters.AllowAutoRedirect
&& MaximumAutomaticRedirections == requestParameters.MaximumAutomaticRedirections
&& MaximumResponseHeadersLength == requestParameters.MaximumResponseHeadersLength
&& PreAuthenticate == requestParameters.PreAuthenticate
&& Timeout == requestParameters.Timeout
&& SslProtocols == requestParameters.SslProtocols
&& CheckCertificateRevocationList == requestParameters.CheckCertificateRevocationList
&& ReferenceEquals(Credentials, requestParameters.Credentials)
&& ReferenceEquals(Proxy, requestParameters.Proxy)
&& ReferenceEquals(ServerCertificateValidationCallback, requestParameters.ServerCertificateValidationCallback)
&& ReferenceEquals(ClientCertificates, requestParameters.ClientCertificates)
&& ReferenceEquals(CookieContainer, requestParameters.CookieContainer);
}
public bool AreParametersAcceptableForCaching()
{
return Credentials == null
&& ReferenceEquals(Proxy, DefaultWebProxy)
&& ServerCertificateValidationCallback == null
&& ClientCertificates == null
&& CookieContainer == null;
}
}
private const string ContinueHeader = "100-continue";
private const string ChunkedHeader = "chunked";
public HttpWebRequest()
{
}
[Obsolete("Serialization is obsoleted for this type. https://go.microsoft.com/fwlink/?linkid=14202")]
protected HttpWebRequest(SerializationInfo serializationInfo, StreamingContext streamingContext) : base(serializationInfo, streamingContext)
{
throw new PlatformNotSupportedException();
}
void ISerializable.GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
throw new PlatformNotSupportedException();
}
protected override void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
throw new PlatformNotSupportedException();
}
internal HttpWebRequest(Uri uri)
{
_requestUri = uri;
}
private void SetSpecialHeaders(string HeaderName, string value)
{
_webHeaderCollection.Remove(HeaderName);
if (!string.IsNullOrEmpty(value))
{
_webHeaderCollection[HeaderName] = value;
}
}
public string Accept
{
get
{
return _webHeaderCollection[HttpKnownHeaderNames.Accept];
}
set
{
SetSpecialHeaders(HttpKnownHeaderNames.Accept, value);
}
}
public virtual bool AllowReadStreamBuffering
{
get
{
return _allowReadStreamBuffering;
}
set
{
_allowReadStreamBuffering = value;
}
}
public int MaximumResponseHeadersLength
{
get => _maximumResponseHeadersLen;
set
{
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
if (value < 0 && value != System.Threading.Timeout.Infinite)
{
throw new ArgumentOutOfRangeException(nameof(value), SR.net_toosmall);
}
_maximumResponseHeadersLen = value;
}
}
public int MaximumAutomaticRedirections
{
get
{
return _maximumAllowedRedirections;
}
set
{
if (value <= 0)
{
throw new ArgumentException(SR.net_toosmall, nameof(value));
}
_maximumAllowedRedirections = value;
}
}
public override string ContentType
{
get
{
return _webHeaderCollection[HttpKnownHeaderNames.ContentType];
}
set
{
SetSpecialHeaders(HttpKnownHeaderNames.ContentType, value);
}
}
public int ContinueTimeout
{
get
{
return _continueTimeout;
}
set
{
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
if ((value < 0) && (value != System.Threading.Timeout.Infinite))
{
throw new ArgumentOutOfRangeException(nameof(value), SR.net_io_timeout_use_ge_zero);
}
_continueTimeout = value;
}
}
public override int Timeout
{
get
{
return _timeout;
}
set
{
if (value < 0 && value != System.Threading.Timeout.Infinite)
{
throw new ArgumentOutOfRangeException(nameof(value), SR.net_io_timeout_use_ge_zero);
}
_timeout = value;
}
}
public override long ContentLength
{
get
{
long value;
long.TryParse(_webHeaderCollection[HttpKnownHeaderNames.ContentLength], out value);
return value;
}
set
{
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_writestarted);
}
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value), SR.net_clsmall);
}
SetSpecialHeaders(HttpKnownHeaderNames.ContentLength, value.ToString());
}
}
public Uri Address
{
get
{
return _requestUri;
}
}
public string UserAgent
{
get
{
return _webHeaderCollection[HttpKnownHeaderNames.UserAgent];
}
set
{
SetSpecialHeaders(HttpKnownHeaderNames.UserAgent, value);
}
}
public string Host
{
get
{
Uri hostUri = _hostUri ?? Address;
return (_hostUri == null || !_hostHasPort) && Address.IsDefaultPort ?
hostUri.Host :
hostUri.Host + ":" + hostUri.Port;
}
set
{
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_writestarted);
}
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
Uri hostUri;
if ((value.Contains('/')) || (!TryGetHostUri(value, out hostUri)))
{
throw new ArgumentException(SR.net_invalid_host, nameof(value));
}
_hostUri = hostUri;
// Determine if the user provided string contains a port
if (!_hostUri.IsDefaultPort)
{
_hostHasPort = true;
}
else if (!value.Contains(':'))
{
_hostHasPort = false;
}
else
{
int endOfIPv6Address = value.IndexOf(']');
_hostHasPort = endOfIPv6Address == -1 || value.LastIndexOf(':') > endOfIPv6Address;
}
}
}
public bool Pipelined
{
get
{
return _pipelined;
}
set
{
_pipelined = value;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the value of the Referer header.
/// </para>
/// </devdoc>
public string Referer
{
get
{
return _webHeaderCollection[HttpKnownHeaderNames.Referer];
}
set
{
SetSpecialHeaders(HttpKnownHeaderNames.Referer, value);
}
}
/// <devdoc>
/// <para>Sets the media type header</para>
/// </devdoc>
public string MediaType
{
get;
set;
}
/// <devdoc>
/// <para>
/// Gets or sets the value of the Transfer-Encoding header. Setting null clears it out.
/// </para>
/// </devdoc>
public string TransferEncoding
{
get
{
return _webHeaderCollection[HttpKnownHeaderNames.TransferEncoding];
}
set
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
bool fChunked;
//
// on blank string, remove current header
//
if (string.IsNullOrWhiteSpace(value))
{
//
// if the value is blank, then remove the header
//
_webHeaderCollection.Remove(HttpKnownHeaderNames.TransferEncoding);
return;
}
//
// if not check if the user is trying to set chunked:
//
fChunked = (value.IndexOf(ChunkedHeader, StringComparison.OrdinalIgnoreCase) != -1);
//
// prevent them from adding chunked, or from adding an Encoding without
// turning on chunked, the reason is due to the HTTP Spec which prevents
// additional encoding types from being used without chunked
//
if (fChunked)
{
throw new ArgumentException(SR.net_nochunked, nameof(value));
}
else if (!SendChunked)
{
throw new InvalidOperationException(SR.net_needchunked);
}
else
{
string checkedValue = HttpValidationHelpers.CheckBadHeaderValueChars(value);
_webHeaderCollection[HttpKnownHeaderNames.TransferEncoding] = checkedValue;
}
#if DEBUG
}
#endif
}
}
public bool KeepAlive { get; set; } = true;
public bool UnsafeAuthenticatedConnectionSharing
{
get
{
return (_booleans & Booleans.UnsafeAuthenticatedConnectionSharing) != 0;
}
set
{
if (value)
{
_booleans |= Booleans.UnsafeAuthenticatedConnectionSharing;
}
else
{
_booleans &= ~Booleans.UnsafeAuthenticatedConnectionSharing;
}
}
}
public DecompressionMethods AutomaticDecompression
{
get
{
return _automaticDecompression;
}
set
{
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_writestarted);
}
_automaticDecompression = value;
}
}
public virtual bool AllowWriteStreamBuffering
{
get
{
return (_booleans & Booleans.AllowWriteStreamBuffering) != 0;
}
set
{
if (value)
{
_booleans |= Booleans.AllowWriteStreamBuffering;
}
else
{
_booleans &= ~Booleans.AllowWriteStreamBuffering;
}
}
}
/// <devdoc>
/// <para>
/// Enables or disables automatically following redirection responses.
/// </para>
/// </devdoc>
public virtual bool AllowAutoRedirect
{
get
{
return (_booleans & Booleans.AllowAutoRedirect) != 0;
}
set
{
if (value)
{
_booleans |= Booleans.AllowAutoRedirect;
}
else
{
_booleans &= ~Booleans.AllowAutoRedirect;
}
}
}
public override string ConnectionGroupName { get; set; }
public override bool PreAuthenticate
{
get
{
return _preAuthenticate;
}
set
{
_preAuthenticate = value;
}
}
public string Connection
{
get
{
return _webHeaderCollection[HttpKnownHeaderNames.Connection];
}
set
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
bool fKeepAlive;
bool fClose;
//
// on blank string, remove current header
//
if (string.IsNullOrWhiteSpace(value))
{
_webHeaderCollection.Remove(HttpKnownHeaderNames.Connection);
return;
}
fKeepAlive = (value.IndexOf("keep-alive", StringComparison.OrdinalIgnoreCase) != -1);
fClose = (value.IndexOf("close", StringComparison.OrdinalIgnoreCase) != -1);
//
// Prevent keep-alive and close from being added
//
if (fKeepAlive ||
fClose)
{
throw new ArgumentException(SR.net_connarg, nameof(value));
}
else
{
string checkedValue = HttpValidationHelpers.CheckBadHeaderValueChars(value);
_webHeaderCollection[HttpKnownHeaderNames.Connection] = checkedValue;
}
#if DEBUG
}
#endif
}
}
/*
Accessor: Expect
The property that controls the Expect header
Input:
string Expect, null clears the Expect except for 100-continue value
Returns: The value of the Expect on get.
*/
public string Expect
{
get
{
return _webHeaderCollection[HttpKnownHeaderNames.Expect];
}
set
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
// only remove everything other than 100-cont
bool fContinue100;
//
// on blank string, remove current header
//
if (string.IsNullOrWhiteSpace(value))
{
_webHeaderCollection.Remove(HttpKnownHeaderNames.Expect);
return;
}
//
// Prevent 100-continues from being added
//
fContinue100 = (value.IndexOf(ContinueHeader, StringComparison.OrdinalIgnoreCase) != -1);
if (fContinue100)
{
throw new ArgumentException(SR.net_no100, nameof(value));
}
else
{
string checkedValue = HttpValidationHelpers.CheckBadHeaderValueChars(value);
_webHeaderCollection[HttpKnownHeaderNames.Expect] = checkedValue;
}
#if DEBUG
}
#endif
}
}
/// <devdoc>
/// <para>
/// Gets or sets the default for the MaximumResponseHeadersLength property.
/// </para>
/// <remarks>
/// This value can be set in the config file, the default can be overridden using the MaximumResponseHeadersLength property.
/// </remarks>
/// </devdoc>
public static int DefaultMaximumResponseHeadersLength
{
get
{
return _defaultMaxResponseHeadersLength;
}
set
{
_defaultMaxResponseHeadersLength = value;
}
}
// NOP
public static int DefaultMaximumErrorResponseLength
{
get; set;
}
public static new RequestCachePolicy DefaultCachePolicy { get; set; } = new RequestCachePolicy(RequestCacheLevel.BypassCache);
public DateTime IfModifiedSince
{
get
{
return GetDateHeaderHelper(HttpKnownHeaderNames.IfModifiedSince);
}
set
{
SetDateHeaderHelper(HttpKnownHeaderNames.IfModifiedSince, value);
}
}
/// <devdoc>
/// <para>
/// Gets or sets the value of the Date header.
/// </para>
/// </devdoc>
public DateTime Date
{
get
{
return GetDateHeaderHelper(HttpKnownHeaderNames.Date);
}
set
{
SetDateHeaderHelper(HttpKnownHeaderNames.Date, value);
}
}
public bool SendChunked
{
get
{
return (_booleans & Booleans.SendChunked) != 0;
}
set
{
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_writestarted);
}
if (value)
{
_booleans |= Booleans.SendChunked;
}
else
{
_booleans &= ~Booleans.SendChunked;
}
}
}
public HttpContinueDelegate ContinueDelegate
{
// Nop since the underlying API do not expose 100 continue.
get
{
return _continueDelegate;
}
set
{
_continueDelegate = value;
}
}
public ServicePoint ServicePoint
{
get
{
if (_servicePoint == null)
{
_servicePoint = ServicePointManager.FindServicePoint(Address, Proxy);
}
return _servicePoint;
}
}
public RemoteCertificateValidationCallback ServerCertificateValidationCallback { get; set; }
//
// ClientCertificates - sets our certs for our reqest,
// uses a hash of the collection to create a private connection
// group, to prevent us from using the same Connection as
// non-Client Authenticated requests.
//
public X509CertificateCollection ClientCertificates
{
get
{
if (_clientCertificates == null)
_clientCertificates = new X509CertificateCollection();
return _clientCertificates;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
_clientCertificates = value;
}
}
// HTTP Version
/// <devdoc>
/// <para>
/// Gets and sets
/// the HTTP protocol version used in this request.
/// </para>
/// </devdoc>
public Version ProtocolVersion
{
get
{
return IsVersionHttp10 ? HttpVersion.Version10 : HttpVersion.Version11;
}
set
{
if (value.Equals(HttpVersion.Version11))
{
IsVersionHttp10 = false;
}
else if (value.Equals(HttpVersion.Version10))
{
IsVersionHttp10 = true;
}
else
{
throw new ArgumentException(SR.net_wrongversion, nameof(value));
}
}
}
public int ReadWriteTimeout
{
get
{
return _readWriteTimeout;
}
set
{
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
if (value <= 0 && value != System.Threading.Timeout.Infinite)
{
throw new ArgumentOutOfRangeException(nameof(value), SR.net_io_timeout_use_gt_zero);
}
_readWriteTimeout = value;
}
}
public virtual CookieContainer CookieContainer
{
get
{
return _cookieContainer;
}
set
{
_cookieContainer = value;
}
}
public override ICredentials Credentials
{
get
{
return _credentials;
}
set
{
_credentials = value;
}
}
public virtual bool HaveResponse
{
get
{
return (_sendRequestTask != null) && (_sendRequestTask.IsCompletedSuccessfully);
}
}
public override WebHeaderCollection Headers
{
get
{
return _webHeaderCollection;
}
set
{
// We can't change headers after they've already been sent.
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
WebHeaderCollection webHeaders = value;
WebHeaderCollection newWebHeaders = new WebHeaderCollection();
// Copy And Validate -
// Handle the case where their object tries to change
// name, value pairs after they call set, so therefore,
// we need to clone their headers.
foreach (string headerName in webHeaders.AllKeys)
{
newWebHeaders[headerName] = webHeaders[headerName];
}
_webHeaderCollection = newWebHeaders;
}
}
public override string Method
{
get
{
return _originVerb;
}
set
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentException(SR.net_badmethod, nameof(value));
}
if (HttpValidationHelpers.IsInvalidMethodOrHeaderString(value))
{
throw new ArgumentException(SR.net_badmethod, nameof(value));
}
_originVerb = value;
}
}
public override Uri RequestUri
{
get
{
return _requestUri;
}
}
public virtual bool SupportsCookieContainer
{
get
{
return true;
}
}
public override bool UseDefaultCredentials
{
get
{
return (_credentials == CredentialCache.DefaultCredentials);
}
set
{
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_writestarted);
}
// Match Desktop behavior. Changing this property will also
// change the .Credentials property as well.
_credentials = value ? CredentialCache.DefaultCredentials : null;
}
}
public override IWebProxy Proxy
{
get
{
return _proxy;
}
set
{
// We can't change the proxy while the request is already fired.
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
_proxy = value;
}
}
public override void Abort()
{
if (Interlocked.Exchange(ref _abortCalled, 1) != 0)
{
return;
}
// .NET Desktop behavior requires us to invoke outstanding callbacks
// before returning if used in either the BeginGetRequestStream or
// BeginGetResponse methods.
//
// If we can transition the task to the canceled state, then we invoke
// the callback. If we can't transition the task, it is because it is
// already in the terminal state and the callback has already been invoked
// via the async task continuation.
if (_responseOperation != null)
{
if (_responseOperation.TrySetCanceled() && _responseCallback != null)
{
_responseCallback(_responseOperation.Task);
}
// Cancel the underlying send operation.
Debug.Assert(_sendRequestCts != null);
_sendRequestCts.Cancel();
}
else if (_requestStreamOperation != null)
{
if (_requestStreamOperation.TrySetCanceled() && _requestStreamCallback != null)
{
_requestStreamCallback(_requestStreamOperation.Task);
}
}
}
// HTTP version of the request
private bool IsVersionHttp10
{
get
{
return (_booleans & Booleans.IsVersionHttp10) != 0;
}
set
{
if (value)
{
_booleans |= Booleans.IsVersionHttp10;
}
else
{
_booleans &= ~Booleans.IsVersionHttp10;
}
}
}
public override WebResponse GetResponse()
{
try
{
_sendRequestCts = new CancellationTokenSource();
return SendRequest().GetAwaiter().GetResult();
}
catch (Exception ex)
{
throw WebException.CreateCompatibleException(ex);
}
}
public override Stream GetRequestStream()
{
return InternalGetRequestStream().Result;
}
private Task<Stream> InternalGetRequestStream()
{
CheckAbort();
// Match Desktop behavior: prevent someone from getting a request stream
// if the protocol verb/method doesn't support it. Note that this is not
// entirely compliant RFC2616 for the aforementioned compatibility reasons.
if (string.Equals(HttpMethod.Get.Method, _originVerb, StringComparison.OrdinalIgnoreCase) ||
string.Equals(HttpMethod.Head.Method, _originVerb, StringComparison.OrdinalIgnoreCase) ||
string.Equals("CONNECT", _originVerb, StringComparison.OrdinalIgnoreCase))
{
throw new ProtocolViolationException(SR.net_nouploadonget);
}
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
_requestStream = new RequestStream();
return Task.FromResult((Stream)_requestStream);
}
public Stream EndGetRequestStream(IAsyncResult asyncResult, out TransportContext context)
{
context = null;
return EndGetRequestStream(asyncResult);
}
public Stream GetRequestStream(out TransportContext context)
{
context = null;
return GetRequestStream();
}
public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state)
{
CheckAbort();
if (Interlocked.Exchange(ref _beginGetRequestStreamCalled, 1) != 0)
{
throw new InvalidOperationException(SR.net_repcall);
}
_requestStreamCallback = callback;
_requestStreamOperation = InternalGetRequestStream().ToApm(callback, state);
return _requestStreamOperation.Task;
}
public override Stream EndGetRequestStream(IAsyncResult asyncResult)
{
CheckAbort();
if (asyncResult == null || !(asyncResult is Task<Stream>))
{
throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
}
if (Interlocked.Exchange(ref _endGetRequestStreamCalled, 1) != 0)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndGetRequestStream"));
}
Stream stream;
try
{
stream = ((Task<Stream>)asyncResult).GetAwaiter().GetResult();
}
catch (Exception ex)
{
throw WebException.CreateCompatibleException(ex);
}
return stream;
}
private async Task<WebResponse> SendRequest()
{
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
var request = new HttpRequestMessage(new HttpMethod(_originVerb), _requestUri);
bool disposeRequired = false;
HttpClient client = null;
try
{
client = GetCachedOrCreateHttpClient(out disposeRequired);
if (_requestStream != null)
{
ArraySegment<byte> bytes = _requestStream.GetBuffer();
request.Content = new ByteArrayContent(bytes.Array, bytes.Offset, bytes.Count);
}
if (_hostUri != null)
{
request.Headers.Host = Host;
}
// Copy the HttpWebRequest request headers from the WebHeaderCollection into HttpRequestMessage.Headers and
// HttpRequestMessage.Content.Headers.
foreach (string headerName in _webHeaderCollection)
{
// The System.Net.Http APIs require HttpRequestMessage headers to be properly divided between the request headers
// collection and the request content headers collection for all well-known header names. And custom headers
// are only allowed in the request headers collection and not in the request content headers collection.
if (IsWellKnownContentHeader(headerName))
{
if (request.Content == null)
{
// Create empty content so that we can send the entity-body header.
request.Content = new ByteArrayContent(Array.Empty<byte>());
}
request.Content.Headers.TryAddWithoutValidation(headerName, _webHeaderCollection[headerName]);
}
else
{
request.Headers.TryAddWithoutValidation(headerName, _webHeaderCollection[headerName]);
}
}
request.Headers.TransferEncodingChunked = SendChunked;
if (KeepAlive)
{
request.Headers.Connection.Add(HttpKnownHeaderNames.KeepAlive);
}
else
{
request.Headers.ConnectionClose = true;
}
request.Version = ProtocolVersion;
_sendRequestTask = client.SendAsync(
request,
_allowReadStreamBuffering ? HttpCompletionOption.ResponseContentRead : HttpCompletionOption.ResponseHeadersRead,
_sendRequestCts.Token);
HttpResponseMessage responseMessage = await _sendRequestTask.ConfigureAwait(false);
HttpWebResponse response = new HttpWebResponse(responseMessage, _requestUri, _cookieContainer);
if (!responseMessage.IsSuccessStatusCode)
{
throw new WebException(
SR.Format(SR.net_servererror, (int)response.StatusCode, response.StatusDescription),
null,
WebExceptionStatus.ProtocolError,
response);
}
return response;
}
finally
{
if (disposeRequired)
{
client?.Dispose();
}
}
}
public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state)
{
CheckAbort();
if (Interlocked.Exchange(ref _beginGetResponseCalled, 1) != 0)
{
throw new InvalidOperationException(SR.net_repcall);
}
_sendRequestCts = new CancellationTokenSource();
_responseCallback = callback;
_responseOperation = SendRequest().ToApm(callback, state);
return _responseOperation.Task;
}
public override WebResponse EndGetResponse(IAsyncResult asyncResult)
{
CheckAbort();
if (asyncResult == null || !(asyncResult is Task<WebResponse>))
{
throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
}
if (Interlocked.Exchange(ref _endGetResponseCalled, 1) != 0)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndGetResponse"));
}
WebResponse response;
try
{
response = ((Task<WebResponse>)asyncResult).GetAwaiter().GetResult();
}
catch (Exception ex)
{
throw WebException.CreateCompatibleException(ex);
}
return response;
}
/// <devdoc>
/// <para>
/// Adds a range header to the request for a specified range.
/// </para>
/// </devdoc>
public void AddRange(int from, int to)
{
AddRange("bytes", (long)from, (long)to);
}
/// <devdoc>
/// <para>
/// Adds a range header to the request for a specified range.
/// </para>
/// </devdoc>
public void AddRange(long from, long to)
{
AddRange("bytes", from, to);
}
/// <devdoc>
/// <para>
/// Adds a range header to a request for a specific
/// range from the beginning or end
/// of the requested data.
/// To add the range from the end pass negative value
/// To add the range from the some offset to the end pass positive value
/// </para>
/// </devdoc>
public void AddRange(int range)
{
AddRange("bytes", (long)range);
}
/// <devdoc>
/// <para>
/// Adds a range header to a request for a specific
/// range from the beginning or end
/// of the requested data.
/// To add the range from the end pass negative value
/// To add the range from the some offset to the end pass positive value
/// </para>
/// </devdoc>
public void AddRange(long range)
{
AddRange("bytes", range);
}
public void AddRange(string rangeSpecifier, int from, int to)
{
AddRange(rangeSpecifier, (long)from, (long)to);
}
public void AddRange(string rangeSpecifier, long from, long to)
{
//
// Do some range checking before assembling the header
//
if (rangeSpecifier == null)
{
throw new ArgumentNullException(nameof(rangeSpecifier));
}
if ((from < 0) || (to < 0))
{
throw new ArgumentOutOfRangeException(from < 0 ? nameof(from) : nameof(to), SR.net_rangetoosmall);
}
if (from > to)
{
throw new ArgumentOutOfRangeException(nameof(from), SR.net_fromto);
}
if (!HttpValidationHelpers.IsValidToken(rangeSpecifier))
{
throw new ArgumentException(SR.net_nottoken, nameof(rangeSpecifier));
}
if (!AddRange(rangeSpecifier, from.ToString(NumberFormatInfo.InvariantInfo), to.ToString(NumberFormatInfo.InvariantInfo)))
{
throw new InvalidOperationException(SR.net_rangetype);
}
}
public void AddRange(string rangeSpecifier, int range)
{
AddRange(rangeSpecifier, (long)range);
}
public void AddRange(string rangeSpecifier, long range)
{
if (rangeSpecifier == null)
{
throw new ArgumentNullException(nameof(rangeSpecifier));
}
if (!HttpValidationHelpers.IsValidToken(rangeSpecifier))
{
throw new ArgumentException(SR.net_nottoken, nameof(rangeSpecifier));
}
if (!AddRange(rangeSpecifier, range.ToString(NumberFormatInfo.InvariantInfo), (range >= 0) ? "" : null))
{
throw new InvalidOperationException(SR.net_rangetype);
}
}
private bool AddRange(string rangeSpecifier, string from, string to)
{
string curRange = _webHeaderCollection[HttpKnownHeaderNames.Range];
if ((curRange == null) || (curRange.Length == 0))
{
curRange = rangeSpecifier + "=";
}
else
{
if (!string.Equals(curRange.Substring(0, curRange.IndexOf('=')), rangeSpecifier, StringComparison.OrdinalIgnoreCase))
{
return false;
}
curRange = string.Empty;
}
curRange += from.ToString();
if (to != null)
{
curRange += "-" + to;
}
_webHeaderCollection[HttpKnownHeaderNames.Range] = curRange;
return true;
}
private bool RequestSubmitted
{
get
{
return _sendRequestTask != null;
}
}
private void CheckAbort()
{
if (Volatile.Read(ref _abortCalled) == 1)
{
throw new WebException(SR.net_reqaborted, WebExceptionStatus.RequestCanceled);
}
}
private static readonly string[] s_wellKnownContentHeaders = {
HttpKnownHeaderNames.ContentDisposition,
HttpKnownHeaderNames.ContentEncoding,
HttpKnownHeaderNames.ContentLanguage,
HttpKnownHeaderNames.ContentLength,
HttpKnownHeaderNames.ContentLocation,
HttpKnownHeaderNames.ContentMD5,
HttpKnownHeaderNames.ContentRange,
HttpKnownHeaderNames.ContentType,
HttpKnownHeaderNames.Expires,
HttpKnownHeaderNames.LastModified
};
private bool IsWellKnownContentHeader(string header)
{
foreach (string contentHeaderName in s_wellKnownContentHeaders)
{
if (string.Equals(header, contentHeaderName, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
private DateTime GetDateHeaderHelper(string headerName)
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
string headerValue = _webHeaderCollection[headerName];
if (headerValue == null)
{
return DateTime.MinValue; // MinValue means header is not present
}
if (HttpDateParser.TryStringToDate(headerValue, out DateTimeOffset dateTimeOffset))
{
return dateTimeOffset.LocalDateTime;
}
else
{
throw new ProtocolViolationException(SR.net_baddate);
}
#if DEBUG
}
#endif
}
private void SetDateHeaderHelper(string headerName, DateTime dateTime)
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
if (dateTime == DateTime.MinValue)
SetSpecialHeaders(headerName, null); // remove header
else
SetSpecialHeaders(headerName, HttpDateParser.DateToString(dateTime.ToUniversalTime()));
#if DEBUG
}
#endif
}
private bool TryGetHostUri(string hostName, out Uri hostUri)
{
string s = Address.Scheme + "://" + hostName + Address.PathAndQuery;
return Uri.TryCreate(s, UriKind.Absolute, out hostUri);
}
private HttpClient GetCachedOrCreateHttpClient(out bool disposeRequired)
{
var parameters = new HttpClientParameters(this);
if (parameters.AreParametersAcceptableForCaching())
{
disposeRequired = false;
if (s_cachedHttpClient == null)
{
lock (s_syncRoot)
{
if (s_cachedHttpClient == null)
{
s_cachedHttpClientParameters = parameters;
s_cachedHttpClient = CreateHttpClient(parameters, null);
return s_cachedHttpClient;
}
}
}
if (s_cachedHttpClientParameters.Matches(parameters))
{
return s_cachedHttpClient;
}
}
disposeRequired = true;
return CreateHttpClient(parameters, this);
}
private static HttpClient CreateHttpClient(HttpClientParameters parameters, HttpWebRequest request)
{
HttpClient client = null;
try
{
var handler = new HttpClientHandler();
client = new HttpClient(handler);
handler.AutomaticDecompression = parameters.AutomaticDecompression;
handler.Credentials = parameters.Credentials;
handler.AllowAutoRedirect = parameters.AllowAutoRedirect;
handler.MaxAutomaticRedirections = parameters.MaximumAutomaticRedirections;
handler.MaxResponseHeadersLength = parameters.MaximumResponseHeadersLength;
handler.PreAuthenticate = parameters.PreAuthenticate;
client.Timeout = parameters.Timeout;
if (parameters.CookieContainer != null)
{
handler.CookieContainer = parameters.CookieContainer;
Debug.Assert(handler.UseCookies); // Default of handler.UseCookies is true.
}
else
{
handler.UseCookies = false;
}
Debug.Assert(handler.UseProxy); // Default of handler.UseProxy is true.
Debug.Assert(handler.Proxy == null); // Default of handler.Proxy is null.
// HttpClientHandler default is to use a proxy which is the system proxy.
// This is indicated by the properties 'UseProxy == true' and 'Proxy == null'.
//
// However, HttpWebRequest doesn't have a separate 'UseProxy' property. Instead,
// the default of the 'Proxy' property is a non-null IWebProxy object which is the
// system default proxy object. If the 'Proxy' property were actually null, then
// that means don't use any proxy.
//
// So, we need to map the desired HttpWebRequest proxy settings to equivalent
// HttpClientHandler settings.
if (parameters.Proxy == null)
{
handler.UseProxy = false;
}
else if (!object.ReferenceEquals(parameters.Proxy, WebRequest.GetSystemWebProxy()))
{
handler.Proxy = parameters.Proxy;
}
else
{
// Since this HttpWebRequest is using the default system proxy, we need to
// pass any proxy credentials that the developer might have set via the
// WebRequest.DefaultWebProxy.Credentials property.
handler.DefaultProxyCredentials = parameters.Proxy.Credentials;
}
if (parameters.ClientCertificates != null)
{
handler.ClientCertificates.AddRange(parameters.ClientCertificates);
}
// Set relevant properties from ServicePointManager
handler.SslProtocols = (SslProtocols)parameters.SslProtocols;
handler.CheckCertificateRevocationList = parameters.CheckCertificateRevocationList;
RemoteCertificateValidationCallback rcvc = parameters.ServerCertificateValidationCallback;
if (rcvc != null)
{
RemoteCertificateValidationCallback localRcvc = rcvc;
HttpWebRequest localRequest = request;
handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => localRcvc(localRequest, cert, chain, errors);
}
return client;
}
catch
{
client?.Dispose();
throw;
}
}
}
}
| |
// 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 *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 Microsoft.WindowsAzure.Management.HDInsight.Framework.Core.Library;
namespace Microsoft.WindowsAzure.Management.HDInsight.ClusterProvisioning.PocoClient.PaasClusters
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Management.HDInsight.ClusterProvisioning.Data;
using Microsoft.WindowsAzure.Management.HDInsight.ClusterProvisioning.Data.Rdfe;
using Microsoft.WindowsAzure.Management.HDInsight.ClusterProvisioning.LocationFinder;
using Microsoft.WindowsAzure.Management.HDInsight.ClusterProvisioning.RestClient;
using Microsoft.WindowsAzure.Management.HDInsight.ClusterProvisioning.RestClient.ClustersResource;
using Microsoft.WindowsAzure.Management.HDInsight.Contracts;
using Microsoft.WindowsAzure.Management.HDInsight.Contracts.May2014;
using Microsoft.WindowsAzure.Management.HDInsight.Contracts.May2014.Components;
using Microsoft.WindowsAzure.Management.HDInsight.Framework.Core.Library.WebRequest;
using Microsoft.WindowsAzure.Management.HDInsight.Framework.Rest.CustomMessageHandlers;
using Microsoft.WindowsAzure.Management.HDInsight.Framework.ServiceLocation;
using Microsoft.WindowsAzure.Management.HDInsight.Logging;
internal class PaasClustersPocoClient : IHDInsightManagementPocoClient
{
private readonly IRdfeClustersResourceRestClient rdfeClustersRestClient;
private readonly IHDInsightSubscriptionCredentials credentials;
internal const string ClustersResourceType = "CLUSTERS";
private readonly bool ignoreSslErrors;
private const string ResourceAlreadyExists = "The condition specified by the ETag is not satisfied.";
internal const string ResizeCapabilityEnabled = "ResizeEnabled";
public const string ClusterConfigActionCapabilitityName = "CAPABILITY_FEATURE_POWERSHELL_SCRIPT_ACTION_SDK";
private const string ResizeRoleAction = "Resize";
private const string EnableRdpAction = "EnableRdp";
/// <inheritdoc />
public event EventHandler<ClusterProvisioningStatusEventArgs> ClusterProvisioning;
private List<string> capabilities;
public IAbstractionContext Context
{
get;
private set;
}
public void RaiseClusterProvisioningEvent(object sender, ClusterProvisioningStatusEventArgs e)
{
this.OnClusterProvisioning(e);
}
internal PaasClustersPocoClient(IHDInsightSubscriptionCredentials credentials, bool ignoreSslErrors, IAbstractionContext context, List<string> capabilities)
: this(credentials, ignoreSslErrors, context, capabilities, ServiceLocator.Instance.Locate<IRdfeClustersResourceRestClientFactory>().Create(credentials, context, ignoreSslErrors, SchemaVersionUtils.GetSchemaVersion(capabilities)))
{
}
internal PaasClustersPocoClient(
IHDInsightSubscriptionCredentials credentials,
bool ignoreSslErrors,
IAbstractionContext context,
List<string> capabilities,
IRdfeClustersResourceRestClient clustersResourceRestClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (context == null)
{
throw new ArgumentNullException("context");
}
if (capabilities == null)
{
throw new ArgumentNullException("capabilities");
}
if (clustersResourceRestClient == null)
{
throw new ArgumentNullException("clustersResourceRestClient");
}
this.credentials = credentials;
this.Context = context;
this.Logger = context.Logger;
this.ignoreSslErrors = ignoreSslErrors;
this.rdfeClustersRestClient = clustersResourceRestClient;
this.capabilities = capabilities;
}
protected virtual void OnClusterProvisioning(ClusterProvisioningStatusEventArgs e)
{
var handler = this.ClusterProvisioning;
if (handler != null)
{
handler(this, e);
}
}
private async Task RegisterSubscriptionIfExistsAsync()
{
try
{
await
this.rdfeClustersRestClient.RegisterSubscriptionIfNotExists(
this.credentials.SubscriptionId.ToString(), this.credentials.DeploymentNamespace + "." + ClustersResourceType.ToLowerInvariant(), this.Context.CancellationToken);
}
catch (InvalidExpectedStatusCodeException invalidExpectedStatusCodeException)
{
if (invalidExpectedStatusCodeException.ReceivedStatusCode == HttpStatusCode.Conflict)
{
return;
}
throw;
}
}
private async Task CreateCloudServiceAsyncIfNotExists(string regionName)
{
var resolvedCloudServiceName = ServiceLocator.Instance.Locate<ICloudServiceNameResolver>()
.GetCloudServiceName(
this.credentials.SubscriptionId,
this.credentials.DeploymentNamespace,
regionName);
try
{
var cloudServices = await
this.rdfeClustersRestClient.ListCloudServicesAsync(
this.credentials.SubscriptionId.ToString(),
this.Context.CancellationToken);
if (!cloudServices.Any(c => c.Name.Equals(resolvedCloudServiceName, StringComparison.OrdinalIgnoreCase)))
{
await
this.rdfeClustersRestClient.PutCloudServiceAsync(
this.credentials.SubscriptionId.ToString(),
resolvedCloudServiceName,
new CloudService
{
Description = "HDInsight cloud service for provisioning clusters.",
GeoRegion = regionName,
Label = "HdInsightCloudService",
Name = resolvedCloudServiceName,
},
this.Context.CancellationToken);
}
}
catch (InvalidExpectedStatusCodeException invalidExpectedStatusCodeException)
{
if (invalidExpectedStatusCodeException.ReceivedStatusCode == HttpStatusCode.Conflict)
{
return;
}
if (invalidExpectedStatusCodeException.ReceivedStatusCode == HttpStatusCode.BadRequest)
{
var str = invalidExpectedStatusCodeException.Response.Content != null
? invalidExpectedStatusCodeException.Response.Content.ReadAsStringAsync().Result : string.Empty;
if (str.IndexOf(ResourceAlreadyExists, StringComparison.OrdinalIgnoreCase) != -1)
{
return;
}
}
throw;
}
}
internal static bool HasClusterConfigActionCapability(IEnumerable<string> capabilities)
{
return capabilities.Contains(ClusterConfigActionCapabilitityName, StringComparer.OrdinalIgnoreCase);
}
internal static bool HasCorrectSchemaVersionForConfigAction(IEnumerable<string> capabilities)
{
string resizeCapability;
SchemaVersionUtils.SupportedSchemaVersions.TryGetValue(2, out resizeCapability);
if (resizeCapability == null)
{
return false;
}
return capabilities.Contains(resizeCapability, StringComparer.OrdinalIgnoreCase);
}
internal static bool HasCorrectSchemaVersionForNewVMSizes(IEnumerable<string> capabilities)
{
string vmSizesCapability;
SchemaVersionUtils.SupportedSchemaVersions.TryGetValue(3, out vmSizesCapability);
if (vmSizesCapability == null)
{
return false;
}
return capabilities.Contains(vmSizesCapability, StringComparer.OrdinalIgnoreCase);
}
/// <summary>
/// Creates the container.
/// </summary>
/// <param name="clusterCreateParameters">The cluster create parameters.</param>
/// <returns>A task.</returns>
public async Task CreateContainer(HDInsight.ClusterCreateParametersV2 clusterCreateParameters)
{
if (clusterCreateParameters == null)
{
throw new ArgumentNullException("clusterCreateParameters");
}
if (string.IsNullOrEmpty(clusterCreateParameters.Name))
{
throw new ArgumentException("ClusterCreateParameters.Name cannot be null or empty", "clusterCreateParameters");
}
if (string.IsNullOrEmpty(clusterCreateParameters.Location))
{
throw new ArgumentException("ClusterCreateParameters.Location cannot be null or empty", "clusterCreateParameters");
}
if (clusterCreateParameters.ClusterSizeInNodes < 1)
{
throw new ArgumentException("clusterCreateParameters.ClusterSizeInNodes must be > 0");
}
//allow zookeeper to be specified only for Hbase and Storm clusters
if (clusterCreateParameters.ZookeeperNodeSize != null)
{
if (clusterCreateParameters.ClusterType != ClusterType.HBase &&
clusterCreateParameters.ClusterType != ClusterType.Storm)
{
throw new ArgumentException(
string.Format("clusterCreateParameters.ZookeeperNodeSize must be null for {0} clusters.",
clusterCreateParameters.ClusterType));
}
}
try
{
//Validate
AsvValidationHelper.ValidateAndResolveAsvAccountsAndPrep(clusterCreateParameters);
// Validates config action component.
if (clusterCreateParameters.ConfigActions != null && clusterCreateParameters.ConfigActions.Count > 0)
{
this.LogMessage("Validating parameters for config actions.", Severity.Informational, Verbosity.Detailed);
if (!HasClusterConfigActionCapability(this.capabilities) ||
!HasCorrectSchemaVersionForConfigAction(this.capabilities))
{
throw new NotSupportedException("Your subscription does not support config actions.");
}
this.LogMessage("Validating URIs for config actions.", Severity.Informational, Verbosity.Detailed);
// Validates that the config actions' Uris are downloadable.
UriEndpointValidator.ValidateAndResolveConfigActionEndpointUris(clusterCreateParameters);
}
//Validate Rdp settings in case any of the RdpUsername or RdpPassword or RdpAccessExpiry is specified.
if (!string.IsNullOrEmpty(clusterCreateParameters.RdpUsername) ||
!string.IsNullOrEmpty(clusterCreateParameters.RdpPassword) ||
clusterCreateParameters.RdpAccessExpiry.IsNotNull())
{
if(string.IsNullOrEmpty(clusterCreateParameters.RdpUsername))
{
throw new ArgumentException(
"clusterCreateParameters.RdpUsername cannot be null or empty in case either RdpPassword or RdpAccessExpiry is specified",
"clusterCreateParameters");
}
if (string.IsNullOrEmpty(clusterCreateParameters.RdpPassword))
{
throw new ArgumentException(
"clusterCreateParameters.RdpPassword cannot be null or empty in case either RdpUsername or RdpAccessExpiry is specified",
"clusterCreateParameters");
}
if (clusterCreateParameters.RdpAccessExpiry.IsNull())
{
throw new ArgumentException(
"clusterCreateParameters.RdpAccessExpiry cannot be null or empty in case either RdpUsername or RdpPassword is specified",
"clusterCreateParameters");
}
if (clusterCreateParameters.RdpAccessExpiry < DateTime.UtcNow)
{
throw new ArgumentException(
"clusterCreateParameters.RdpAccessExpiry should be a time in future.",
"clusterCreateParameters");
}
}
//Validate if new vm sizes are used and if the schema is on.
if (CreateHasNewVMSizesSpecified(clusterCreateParameters) &&
!HasCorrectSchemaVersionForNewVMSizes(this.capabilities))
{
throw new NotSupportedException("Your subscription does not support new VM sizes.");
}
var rdfeCapabilitiesClient =
ServiceLocator.Instance.Locate<IRdfeServiceRestClientFactory>().Create(this.credentials, this.Context, this.ignoreSslErrors);
var capabilities = await rdfeCapabilitiesClient.GetResourceProviderProperties();
// Validates the region for the cluster creation
var locationClient = ServiceLocator.Instance.Locate<ILocationFinderClientFactory>().Create(this.credentials, this.Context, this.ignoreSslErrors);
var availableLocations = locationClient.ListAvailableLocations(capabilities);
if (!availableLocations.Contains(clusterCreateParameters.Location, StringComparer.OrdinalIgnoreCase))
{
throw new InvalidOperationException(string.Format(
"Cannot create a cluster in '{0}'. Available Locations for your subscription are: {1}",
clusterCreateParameters.Location,
string.Join(",", availableLocations)));
}
await this.RegisterSubscriptionIfExistsAsync();
await this.CreateCloudServiceAsyncIfNotExists(clusterCreateParameters.Location);
var wireCreateParameters = PayloadConverterClusters.CreateWireClusterCreateParametersFromUserType(clusterCreateParameters);
var rdfeResourceInputFromWireInput = PayloadConverterClusters.CreateRdfeResourceInputFromWireInput(wireCreateParameters, SchemaVersionUtils.GetSchemaVersion(this.capabilities));
var resp = await
this.rdfeClustersRestClient.CreateCluster(
this.credentials.SubscriptionId.ToString(),
this.GetCloudServiceName(clusterCreateParameters.Location),
this.credentials.DeploymentNamespace,
clusterCreateParameters.Name,
rdfeResourceInputFromWireInput,
this.Context.CancellationToken);
// Retrieve the request id (or operation id) from the PUT Response. The request id will be used to poll on operation status.
IEnumerable<String> requestIds;
if (resp.Headers.TryGetValues("x-ms-request-id", out requestIds))
{
Guid operationId;
if (!Guid.TryParse(requestIds.First(), out operationId))
{
throw new InvalidOperationException("Could not retrieve a valid operation id for the PUT (cluster create) operation.");
}
// Wait for the operation specified by the request id to complete (succeed or fail).
TimeSpan interval = TimeSpan.FromSeconds(1);
TimeSpan timeout = TimeSpan.FromMinutes(5);
await this.WaitForRdfeOperationToComplete(operationId, interval, timeout, Context.CancellationToken);
}
}
catch (InvalidExpectedStatusCodeException iEx)
{
string content = iEx.Response.Content != null ? iEx.Response.Content.ReadAsStringAsync().Result : string.Empty;
throw new HttpLayerException(iEx.ReceivedStatusCode, content);
}
}
private static bool CreateHasNewVMSizesSpecified(ClusterCreateParametersV2 clusterCreateParameters)
{
return new[]
{
clusterCreateParameters.HeadNodeSize,
clusterCreateParameters.DataNodeSize,
clusterCreateParameters.ZookeeperNodeSize
}
.Except(
new[]
{
"ExtraLarge",
"Large",
"Medium",
"Small",
"ExtraSmall"
}, StringComparer.OrdinalIgnoreCase).Any(ns => ns.IsNotNullOrEmpty());
}
/// <summary>
/// Lists the HDInsight containers for a subscription.
/// </summary>
/// <returns>
/// A task that can be used to retrieve a collection of HDInsight containers (clusters).
/// </returns>
public async Task<ICollection<ClusterDetails>> ListContainers()
{
try
{
var cloudServices =
await
this.rdfeClustersRestClient.ListCloudServicesAsync(
this.credentials.SubscriptionId.ToString(), this.Context.CancellationToken);
var listOfClusters = new List<GetClusterResult>();
foreach (CloudService service in cloudServices)
{
foreach (
var clusterResource in service.Resources.Where(r => r.Type.Equals(ClustersResourceType, StringComparison.OrdinalIgnoreCase)))
{
listOfClusters.Add(await this.GetClusterFromCloudServiceResource(service, clusterResource));
}
}
return listOfClusters.Select(r => r.ClusterDetails).ToList();
}
catch (InvalidExpectedStatusCodeException iEx)
{
string content = iEx.Response.Content != null ? iEx.Response.Content.ReadAsStringAsync().Result : string.Empty;
throw new HttpLayerException(iEx.ReceivedStatusCode, content);
}
}
/// <summary>
/// Deletes an HDInsight container (cluster). If there are multiple clusters with same
/// name in different regions then all of them will be deleted.
/// </summary>
/// <param name="dnsName">The name of the cluster to delete.</param>
/// <returns>
/// A task that can be used to wait for the delete request to complete.
/// </returns>
public async Task DeleteContainer(string dnsName)
{
if (string.IsNullOrEmpty(dnsName))
{
throw new ArgumentNullException("dnsName");
}
try
{
var cloudServices = await this.ListCloudServices();
var servicesHoldingTheService =
cloudServices.Where(
c =>
c.Resources.Any(
r =>
r.Type.Equals(ClustersResourceType, StringComparison.OrdinalIgnoreCase) &&
r.Name.Equals(dnsName, StringComparison.OrdinalIgnoreCase))).ToList();
if (servicesHoldingTheService == null || servicesHoldingTheService.Count == 0)
{
throw new HDInsightClusterDoesNotExistException(dnsName);
}
if (servicesHoldingTheService.Count > 1)
{
throw new InvalidOperationException(string.Format("Multiple clusters found with dnsname '{0}'. Please specify dnsname and location", dnsName));
}
foreach (var service in servicesHoldingTheService)
{
await
this.rdfeClustersRestClient.DeleteCluster(
this.credentials.SubscriptionId.ToString(),
this.GetCloudServiceName(service.GeoRegion),
this.credentials.DeploymentNamespace,
dnsName,
this.Context.CancellationToken);
}
}
catch (InvalidExpectedStatusCodeException iEx)
{
string content = iEx.Response.Content != null ? iEx.Response.Content.ReadAsStringAsync().Result : string.Empty;
throw new HttpLayerException(iEx.ReceivedStatusCode, content);
}
}
/// <summary>
/// Deletes an HDInsight container (cluster).
/// </summary>
/// <param name="dnsName">The name of the cluster to delete.</param>
/// <param name="location">The location of the cluster to delete.</param>
/// <returns>
/// A task that can be used to wait for the delete request to complete.
/// </returns>
public async Task DeleteContainer(string dnsName, string location)
{
if (string.IsNullOrEmpty(dnsName))
{
throw new ArgumentNullException("dnsName");
}
if (string.IsNullOrEmpty(location))
{
throw new ArgumentNullException("location");
}
try
{
await
this.rdfeClustersRestClient.DeleteCluster(
this.credentials.SubscriptionId.ToString(),
this.GetCloudServiceName(location),
this.credentials.DeploymentNamespace,
dnsName,
this.Context.CancellationToken);
}
catch (InvalidExpectedStatusCodeException iEx)
{
string content = iEx.Response.Content != null ? iEx.Response.Content.ReadAsStringAsync().Result : string.Empty;
throw new HttpLayerException(iEx.ReceivedStatusCode, content);
}
}
/// <inheritdoc />
public async Task<Guid> ChangeClusterSize(string dnsName, string location, int newSize)
{
if (string.IsNullOrEmpty(dnsName))
{
throw new ArgumentNullException("dnsName", "The dns name cannot be null or empty.");
}
if (newSize < 1)
{
throw new ArgumentOutOfRangeException("newSize", "The new node count must be at least 1.");
}
try
{
var clusterResult = string.IsNullOrEmpty(location) ? await this.GetCluster(dnsName) : await this.GetCluster(dnsName, location);
var cloudServiceName = this.GetCloudServiceName(clusterResult.ClusterDetails.Location);
var cluster = clusterResult.ResultOfGetClusterCall;
SchemaVersionUtils.EnsureSchemaVersionSupportsResize(this.capabilities);
if (cluster.ClusterCapabilities == null ||
!cluster.ClusterCapabilities.Contains(ResizeCapabilityEnabled, StringComparer.OrdinalIgnoreCase))
{
throw new NotSupportedException(
"This cluster does not support a change cluster size operation. Please drop and recreate the cluster to enable this operation.");
}
var clusterRoleCollection = cluster.ClusterRoleCollection;
var workerRole = clusterRoleCollection.SingleOrDefault(role => role.FriendlyName.Equals("WorkerNodeRole"));
if (workerRole == null)
{
throw new NullReferenceException("The cluster does not contain a worker node role.");
}
if (workerRole.InstanceCount == newSize)
{
return Guid.Empty;
}
workerRole.InstanceCount = newSize;
this.LogMessage("Sending passthrough request to RDFE", Severity.Informational, Verbosity.Detailed);
var resp = this.SafeGetDataFromPassthroughResponse<Contracts.May2014.Operation>(
await this.rdfeClustersRestClient.ChangeClusterSize(
this.credentials.SubscriptionId.ToString(),
cloudServiceName,
this.credentials.DeploymentNamespace,
dnsName,
ResizeRoleAction,
clusterRoleCollection,
this.Context.CancellationToken));
var operationId = Guid.Parse(resp.OperationId);
if (resp.Status.Equals(Contracts.May2014.OperationStatus.Failed))
{
var message = string.Format("ChangeClusterSize operation with operation ID {0} failed with the following response:\n{1}", operationId, resp.ErrorDetails.ErrorMessage);
this.LogMessage(message, Severity.Error, Verbosity.Detailed);
throw new InvalidOperationException(message);
}
return operationId;
}
catch (InvalidExpectedStatusCodeException iEx)
{
this.LogException(iEx);
string content = iEx.Response.Content != null ? iEx.Response.Content.ReadAsStringAsync().Result : string.Empty;
throw new HttpLayerException(iEx.ReceivedStatusCode, content);
}
}
public Task<Guid> EnableDisableProtocol(
UserChangeRequestUserType protocol,
UserChangeRequestOperationType operation,
string dnsName,
string location,
string userName,
string password,
DateTimeOffset expiration)
{
throw new NotImplementedException();
}
/// <summary>
/// Enables Http Connectivity on the HDInsight cluster.
/// </summary>
/// <param name="dnsName">The DNS name of the cluster.</param>
/// <param name="location">The location of the cluster.</param>
/// <param name="httpUserName">The user name to use when enabling Http Connectivity.</param>
/// <param name="httpPassword">The password to use when enabling Http Connectivity.</param>
/// <returns>
/// A task that can be used to wait for the request to complete.
/// </returns>
public Task<Guid> EnableHttp(string dnsName, string location, string httpUserName, string httpPassword)
{
return this.EnableDisableHttp(dnsName, httpUserName, httpPassword, true);
}
/// <summary>
/// Disables Http Connectivity on the HDInsight cluster.
/// </summary>
/// <param name="dnsName">The DNS name of the cluster.</param>
/// <param name="location">The location of the cluster.</param>
/// <returns>
/// A task that can be used to wait for the request to complete.
/// </returns>
public Task<Guid> DisableHttp(string dnsName, string location)
{
return this.EnableDisableHttp(dnsName, null, null, false);
}
/// <summary>
/// Enables Rdp user on the HDInsight cluster.
/// </summary>
/// <param name="dnsName">The DNS name of the cluster</param>
/// <param name="location">The location of the cluster</param>
/// <param name="rdpUserName">The username of the rdp user on the cluster</param>
/// <param name="rdpPassword">The password of the rdo user on the cluster</param>
/// <param name="expiry">The time when the rdp access will expire on the cluster</param>
/// <returns>A task that can be used to wait for the request to complete</returns>
public async Task<Guid> EnableRdp(string dnsName, string location, string rdpUserName, string rdpPassword, DateTime expiry)
{
try
{
var clusterResult = string.IsNullOrEmpty(location) ? await this.GetCluster(dnsName) : await this.GetCluster(dnsName, location);
var cloudServiceName = this.GetCloudServiceName(clusterResult.ClusterDetails.Location);
var cluster = clusterResult.ResultOfGetClusterCall;
var clusterRoleCollection = cluster.ClusterRoleCollection;
var remoteDesktopSettings = new RemoteDesktopSettings
{
AuthenticationCredential = new UsernamePasswordCredential
{
Username = rdpUserName,
Password = rdpPassword,
},
IsEnabled = true,
RemoteAccessExpiry = expiry,
};
foreach (var role in clusterRoleCollection)
{
role.RemoteDesktopSettings = remoteDesktopSettings;
}
this.LogMessage("Sending passthrough request to RDFE", Severity.Informational, Verbosity.Detailed);
var resp = this.SafeGetDataFromPassthroughResponse<Contracts.May2014.Operation>(
await this.rdfeClustersRestClient.EnableDisableRdp(
this.credentials.SubscriptionId.ToString(),
cloudServiceName,
credentials.DeploymentNamespace,
dnsName,
EnableRdpAction,
clusterRoleCollection, this.Context.CancellationToken));
var operationId = Guid.Parse(resp.OperationId);
if (resp.Status.Equals(Contracts.May2014.OperationStatus.Failed))
{
var message = string.Format("EnableRdp operation with operation ID {0} failed with the following response:\n{1}", operationId, resp.ErrorDetails.ErrorMessage);
this.LogMessage(message, Severity.Error, Verbosity.Detailed);
throw new InvalidOperationException(message);
}
return operationId;
}
catch (InvalidExpectedStatusCodeException iEx)
{
this.LogException(iEx);
string content = iEx.Response.Content != null ? iEx.Response.Content.ReadAsStringAsync().Result : string.Empty;
throw new HttpLayerException(iEx.ReceivedStatusCode, content);
}
}
/// <summary>
/// Disables the Rdp user on the HDInsight cluster.
/// </summary>
/// <param name="dnsName">The DNS name of the cluster</param>
/// <param name="location">The location of the cluster</param>
/// <returns>A task that can be used to wait for the request to complete</returns>
public async Task<Guid> DisableRdp(string dnsName, string location)
{
try
{
var clusterResult = string.IsNullOrEmpty(location) ? await this.GetCluster(dnsName) : await this.GetCluster(dnsName, location);
var cloudServiceName = this.GetCloudServiceName(clusterResult.ClusterDetails.Location);
var cluster = clusterResult.ResultOfGetClusterCall;
var clusterRoleCollection = cluster.ClusterRoleCollection;
var remoteDesktopSettings = new RemoteDesktopSettings
{
IsEnabled = false,
};
foreach (var role in clusterRoleCollection)
{
role.RemoteDesktopSettings = remoteDesktopSettings;
}
this.LogMessage("Sending passthrough request to RDFE", Severity.Informational, Verbosity.Detailed);
var resp = this.SafeGetDataFromPassthroughResponse<Contracts.May2014.Operation>(
await this.rdfeClustersRestClient.EnableDisableRdp(
this.credentials.SubscriptionId.ToString(),
cloudServiceName,
credentials.DeploymentNamespace,
dnsName,
EnableRdpAction,
clusterRoleCollection, this.Context.CancellationToken));
var operationId = Guid.Parse(resp.OperationId);
if (resp.Status.Equals(Contracts.May2014.OperationStatus.Failed))
{
var message = string.Format("EnableRdp operation with operation ID {0} failed with the following response:\n{1}", operationId, resp.ErrorDetails.ErrorMessage);
this.LogMessage(message, Severity.Error, Verbosity.Detailed);
throw new InvalidOperationException(message);
}
return operationId;
}
catch (InvalidExpectedStatusCodeException iEx)
{
this.LogException(iEx);
string content = iEx.Response.Content != null ? iEx.Response.Content.ReadAsStringAsync().Result : string.Empty;
throw new HttpLayerException(iEx.ReceivedStatusCode, content);
}
}
/// <summary>
/// Queries an operation status to check whether it is complete.
/// </summary>
/// <param name="dnsName">The DNS name of the cluster.</param>
/// <param name="location">The location of the cluster.</param>
/// <param name="operationId">The Id of the operation to wait for.</param>
/// <returns>
/// Returns true, if the the operation is complete.
/// </returns>
public async Task<bool> IsComplete(string dnsName, string location, Guid operationId)
{
if (string.IsNullOrEmpty(dnsName))
{
throw new ArgumentNullException("dnsName");
}
if (string.IsNullOrEmpty(location))
{
throw new ArgumentNullException("location");
}
try
{
var status = await this.GetStatus(dnsName, location, operationId);
return status.State != UserChangeRequestOperationStatus.Pending;
}
catch (InvalidExpectedStatusCodeException iEx)
{
string content = iEx.Response.Content != null ? iEx.Response.Content.ReadAsStringAsync().Result : string.Empty;
throw new HttpLayerException(iEx.ReceivedStatusCode, content);
}
}
/// <summary>
/// Queries an operation status.
/// </summary>
/// <param name="dnsName">The DNS name of the cluster.</param>
/// <param name="location">The location of the cluster.</param>
/// <param name="operationId">The Id of the operation to wait for.</param>
/// <returns>
/// A status object for the operation.
/// </returns>
public async Task<UserChangeRequestStatus> GetStatus(string dnsName, string location, Guid operationId)
{
if (string.IsNullOrEmpty(dnsName))
{
throw new ArgumentNullException("dnsName");
}
if (string.IsNullOrEmpty(location))
{
throw new ArgumentNullException("location");
}
try
{
var response =
await
this.rdfeClustersRestClient.CheckOperation(
this.credentials.SubscriptionId.ToString(),
this.GetCloudServiceName(location),
this.credentials.DeploymentNamespace,
dnsName,
operationId.ToString(),
this.Context.CancellationToken);
var operationStatus = (Contracts.May2014.Operation)response.Data;
PayloadErrorDetails payloadErrorDetails = null;
if (response.Error != null)
{
payloadErrorDetails = new PayloadErrorDetails
{
ErrorId = response.Error.ErrorId,
ErrorMessage = response.Error.ErrorMessage,
StatusCode = response.Error.StatusCode
};
}
return new UserChangeRequestStatus
{
ErrorDetails = payloadErrorDetails,
UserType = UserChangeRequestUserType.Http,
State = ConvertOperationStatusToUserChangeOperationState(operationStatus.Status)
};
}
catch (InvalidExpectedStatusCodeException iEx)
{
string content = iEx.Response.Content != null ? iEx.Response.Content.ReadAsStringAsync().Result : string.Empty;
throw new HttpLayerException(iEx.ReceivedStatusCode, content);
}
}
/// <inheritdoc />
public async Task<Data.Rdfe.Operation> GetRdfeOperationStatus(Guid operationId)
{
return await this.rdfeClustersRestClient.GetRdfeOperationStatus(
this.credentials.SubscriptionId.ToString(),
operationId.ToString(),
this.Context.CancellationToken);
}
private static UserChangeRequestOperationStatus ConvertOperationStatusToUserChangeOperationState(string operationStatus)
{
switch (operationStatus.ToUpperInvariant())
{
case "FAILED":
return UserChangeRequestOperationStatus.Error;
case "SUCCEEDED":
return UserChangeRequestOperationStatus.Completed;
case "INPROGRESS":
return UserChangeRequestOperationStatus.Pending;
}
return UserChangeRequestOperationStatus.Error;
}
private async Task<GetClusterResult> GetClusterFromCloudServiceResource(CloudService cloudService, Resource clusterResource)
{
var clusterDetails = PayloadConverterClusters.CreateClusterDetailsFromRdfeResourceOutput(
cloudService.GeoRegion,
clusterResource);
HDInsight.ClusterState clusterState = clusterDetails.State;
Cluster clusterFromGetClusterCall = null;
if (clusterState != HDInsight.ClusterState.Deleting &&
clusterState != HDInsight.ClusterState.DeletePending)
{
//we want to poll if we are either in error or unknown state.
//this is so that we can get the extended error information.
try
{
clusterFromGetClusterCall =
this.SafeGetDataFromPassthroughResponse<Cluster>(
await
this.rdfeClustersRestClient.GetCluster(
this.credentials.SubscriptionId.ToString(),
this.GetCloudServiceName(cloudService.GeoRegion),
this.credentials.DeploymentNamespace,
clusterResource.Name,
this.Context.CancellationToken));
clusterDetails = PayloadConverterClusters.CreateClusterDetailsFromGetClustersResult(clusterFromGetClusterCall);
}
catch (InvalidExpectedStatusCodeException ie)
{
//if we got a not found back that we means the RP has no record of this cluster.
//It would happen if one of the basic validations fail, cluster dns name uniqueness
if (ie.ReceivedStatusCode == HttpStatusCode.NotFound)
{
//We may sometimes have a record of the cluster on the server,
//which means we can populate extended error information
}
}
}
clusterDetails.SubscriptionId = this.credentials.SubscriptionId;
return new GetClusterResult(clusterDetails, clusterFromGetClusterCall);
}
private async Task<GetClusterResult> GetCluster(string dnsName)
{
var cloudServices = await this.ListCloudServices();
Resource clusterResource = null;
CloudService cloudServiceForResource = null;
foreach (CloudService service in cloudServices)
{
clusterResource =
service.Resources.FirstOrDefault(
r =>
r.Type.Equals(ClustersResourceType, StringComparison.OrdinalIgnoreCase) &&
r.Name.Equals(dnsName, StringComparison.OrdinalIgnoreCase));
if (clusterResource != null)
{
cloudServiceForResource = service;
break;
}
}
if (clusterResource == null)
{
return null;
}
var result = await this.GetClusterFromCloudServiceResource(cloudServiceForResource, clusterResource);
return result;
}
private async Task<GetClusterResult> GetCluster(string dnsName, string location)
{
var cloudServices = await this.ListCloudServices();
Resource clusterResource = null;
CloudService cloudServiceForResource = null;
foreach (CloudService service in cloudServices)
{
clusterResource =
service.Resources.FirstOrDefault(
r =>
r.Type.Equals(ClustersResourceType, StringComparison.OrdinalIgnoreCase) &&
r.Name.Equals(dnsName, StringComparison.OrdinalIgnoreCase) &&
service.GeoRegion.Equals(location, StringComparison.OrdinalIgnoreCase));
if (clusterResource != null)
{
cloudServiceForResource = service;
break;
}
}
if (clusterResource == null)
{
return null;
}
var result = await this.GetClusterFromCloudServiceResource(cloudServiceForResource, clusterResource);
return result;
}
/// <summary>
/// Lists a single HDInsight container by name.
/// </summary>
/// <param name="dnsName">The name of the HDInsight container.</param>
/// <returns>
/// A task that can be used to retrieve the requested HDInsight container.
/// </returns>
public async Task<ClusterDetails> ListContainer(string dnsName)
{
if (string.IsNullOrEmpty(dnsName))
{
throw new ArgumentNullException("dnsName");
}
try
{
var result = await this.GetCluster(dnsName);
return result == null ? null : result.ClusterDetails;
}
catch (InvalidExpectedStatusCodeException iEx)
{
var content = iEx.Response.Content != null ? iEx.Response.Content.ReadAsStringAsync().Result : string.Empty;
throw new HttpLayerException(iEx.ReceivedStatusCode, content);
}
}
/// <summary>
/// Lists a single HDInsight container by name and region.
/// </summary>
/// <param name="dnsName">The name of the HDInsight container.</param>
/// <param name="location">The location of the HDInsight container.</param>
/// <returns>
/// A task that can be used to retrieve the requested HDInsight container.
/// </returns>
public async Task<ClusterDetails> ListContainer(string dnsName, string location)
{
if (string.IsNullOrEmpty(dnsName))
{
throw new ArgumentNullException("dnsName");
}
if (string.IsNullOrEmpty(location))
{
throw new ArgumentNullException("location");
}
try
{
var result = await this.GetCluster(dnsName, location);
return result == null ? null : result.ClusterDetails;
}
catch (InvalidExpectedStatusCodeException iEx)
{
var content = iEx.Response.Content != null ? iEx.Response.Content.ReadAsStringAsync().Result : string.Empty;
throw new HttpLayerException(iEx.ReceivedStatusCode, content);
}
}
private async Task<CloudServiceList> ListCloudServices()
{
var cloudServices =
await
this.rdfeClustersRestClient.ListCloudServicesAsync(
this.credentials.SubscriptionId.ToString(), this.Context.CancellationToken);
return cloudServices;
}
/// <summary>
/// Enables the disable HTTP.
/// </summary>
/// <param name="dnsName">Name of the DNS.</param>
/// <param name="username">The username.</param>
/// <param name="password">The password.</param>
/// <param name="enable">If set to <c>true</c> enable http user.</param>
/// <returns>Operation id associated with this operation.</returns>
/// <exception cref="System.ArgumentException">
/// DnsName cannot be null or empty.;dnsName
/// or
/// Http username cannot be null or empty.
/// or
/// Http password cannot be null or empty.
/// </exception>
/// <exception cref="System.InvalidOperationException">
/// Http user is already enabled for the cluster. Please call Disable() first.
/// or
/// Http user is already disable for the cluster. Please call Enable() first.
/// </exception>
public async Task<Guid> EnableDisableHttp(string dnsName, string username, string password, bool enable)
{
if (string.IsNullOrEmpty(dnsName))
{
throw new ArgumentException("dnsName cannot be null or empty.", "dnsName");
}
try
{
var cloudServices = await this.ListCloudServices();
Resource clusterResource = null;
CloudService cloudServiceForResource = null;
foreach (CloudService service in cloudServices)
{
clusterResource = service.Resources.SingleOrDefault(r => r.Type.Equals(ClustersResourceType, StringComparison.OrdinalIgnoreCase)
&& r.Name.Equals(dnsName, StringComparison.OrdinalIgnoreCase));
if (clusterResource != null)
{
cloudServiceForResource = service;
break;
}
}
if (clusterResource == null)
{
throw new HDInsightClusterDoesNotExistException(dnsName);
}
var clusterResult = await this.GetClusterFromCloudServiceResource(cloudServiceForResource, clusterResource);
var gw = clusterResult.ResultOfGetClusterCall.Components.OfType<GatewayComponent>().SingleOrDefault();
if (enable)
{
if (string.IsNullOrEmpty(username))
{
throw new ArgumentException("Http username cannot be null or empty.", username);
}
if (string.IsNullOrEmpty(password))
{
throw new ArgumentException("Http password cannot be null or empty.", username);
}
gw.IsEnabled = true;
gw.RestAuthCredential = new UsernamePasswordCredential { Username = username, Password = password };
}
else
{
gw.IsEnabled = false;
gw.RestAuthCredential = null;
}
var cloudServiceName = this.GetCloudServiceName(clusterResult.ClusterDetails.Location);
var resp = this.SafeGetDataFromPassthroughResponse<Contracts.May2014.Operation>(
await this.rdfeClustersRestClient.UpdateComponent(
this.credentials.SubscriptionId.ToString(),
cloudServiceName,
this.credentials.DeploymentNamespace,
dnsName,
"GatewayComponent",
gw,
this.Context.CancellationToken));
return Guid.Parse(resp.OperationId);
}
catch (InvalidExpectedStatusCodeException iEx)
{
string content = iEx.Response.Content != null ? iEx.Response.Content.ReadAsStringAsync().Result : string.Empty;
throw new HttpLayerException(iEx.ReceivedStatusCode, content);
}
}
private string GetCloudServiceName(string location)
{
return ServiceLocator.Instance.Locate<ICloudServiceNameResolver>()
.GetCloudServiceName(
this.credentials.SubscriptionId,
this.credentials.DeploymentNamespace,
location);
}
private T SafeGetDataFromPassthroughResponse<T>(PassthroughResponse response)
{
if (response.Error != null)
{
throw new HttpLayerException(response.Error.StatusCode, response.Error.ErrorMessage);
}
return (T)response.Data;
}
private class GetClusterResult
{
private readonly ClusterDetails clusterDetails;
private readonly Cluster resultOfGetClusterCall;
internal GetClusterResult(ClusterDetails clusterDetails, Cluster resultOfGetClusterCall)
{
if (clusterDetails == null)
{
throw new ArgumentNullException("clusterDetails");
}
this.clusterDetails = clusterDetails;
this.resultOfGetClusterCall = resultOfGetClusterCall;
}
public ClusterDetails ClusterDetails
{
get { return this.clusterDetails; }
}
public Cluster ResultOfGetClusterCall
{
get { return this.resultOfGetClusterCall; }
}
}
public void Dispose()
{
//nothing to dispose here.
return;
}
public ILogger Logger { get; private set; }
}
}
| |
//! \file ImageHG3.cs
//! \date Sat Jul 19 17:31:09 2014
//! \brief CatSystem HG3 image format implementation.
//
// Copyright (C) 2014-2015 by morkt
//
// 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.IO;
using System.Linq;
using System.ComponentModel.Composition;
using System.Windows.Media.Imaging;
using System.Windows.Media;
using GameRes.Compression;
using GameRes.Utility;
namespace GameRes.Formats.CatSystem
{
internal class HgMetaData : ImageMetaData
{
public uint CanvasWidth;
public uint CanvasHeight;
public uint HeaderSize;
}
[Export(typeof(ImageFormat))]
public class Hg3Format : ImageFormat
{
public override string Tag { get { return "HG3"; } }
public override string Description { get { return "CatSystem engine image format"; } }
public override uint Signature { get { return 0x332d4748; } } // 'HG-3'
public override ImageMetaData ReadMetaData (Stream stream)
{
var header = new byte[0x4c];
if (0x4c != stream.Read (header, 0, header.Length))
return null;
if (LittleEndian.ToUInt32 (header, 4) != 0x0c)
return null;
if (!Binary.AsciiEqual (header, 0x14, "stdinfo\0"))
return null;
return new HgMetaData
{
HeaderSize = LittleEndian.ToUInt32 (header, 0x1C),
Width = LittleEndian.ToUInt32 (header, 0x24),
Height = LittleEndian.ToUInt32 (header, 0x28),
OffsetX = LittleEndian.ToInt32 (header, 0x30),
OffsetY = LittleEndian.ToInt32 (header, 0x34),
BPP = LittleEndian.ToInt32 (header, 0x2C),
CanvasWidth = LittleEndian.ToUInt32 (header, 0x44),
CanvasHeight = LittleEndian.ToUInt32 (header, 0x48),
};
}
public override ImageData Read (Stream stream, ImageMetaData info)
{
var meta = (HgMetaData)info;
if (0x20 != meta.BPP)
throw new NotSupportedException ("Not supported HG-3 color depth");
using (var input = new StreamRegion (stream, 0x14, true))
using (var reader = new Hg3Reader (input, meta))
{
var pixels = reader.Unpack();
if (reader.Flipped)
return ImageData.CreateFlipped (info, PixelFormats.Bgra32, null, pixels, reader.Stride);
else
return ImageData.Create (info, PixelFormats.Bgra32, null, pixels, reader.Stride);
}
}
public override void Write (Stream file, ImageData image)
{
throw new NotImplementedException ("Hg3Format.Write not implemented");
}
}
internal class HgReader : IDisposable
{
private BinaryReader m_input;
protected HgMetaData m_info;
protected int m_pixel_size;
protected BinaryReader Input { get { return m_input; } }
protected Stream InputStream { get { return m_input.BaseStream; } }
public int Stride { get; protected set; }
protected HgReader (Stream input, HgMetaData info)
{
m_input = new ArcView.Reader (input);
m_info = info;
m_pixel_size = m_info.BPP / 8;
Stride = (int)m_info.Width * m_pixel_size;
}
public byte[] UnpackStream (long data_offset, int data_packed, int data_unpacked, int ctl_packed, int ctl_unpacked)
{
var ctl_offset = data_offset + data_packed;
var data = new byte[data_unpacked];
using (var z = new StreamRegion (InputStream, data_offset, data_packed, true))
using (var data_in = new ZLibStream (z, CompressionMode.Decompress))
if (data.Length != data_in.Read (data, 0, data.Length))
throw new EndOfStreamException();
using (var z = new StreamRegion (InputStream, ctl_offset, ctl_packed, true))
using (var ctl_in = new ZLibStream (z, CompressionMode.Decompress))
using (var bits = new LsbBitStream (ctl_in))
{
bool copy = bits.GetNextBit() != 0;
int output_size = GetBitCount (bits);
var output = new byte[output_size];
int src = 0;
int dst = 0;
while (dst < output_size)
{
int count = GetBitCount (bits);
if (copy)
{
Buffer.BlockCopy (data, src, output, dst, count);
src += count;
}
dst += count;
copy = !copy;
}
return ApplyDelta (output);
}
}
static int GetBitCount (LsbBitStream bits)
{
int n = 0;
while (0 == bits.GetNextBit())
{
++n;
if (n >= 0x20)
throw new InvalidFormatException ("Overflow at HgReader.GetBitCount");
}
int value = 1;
while (n --> 0)
{
value = (value << 1) | bits.GetNextBit();
}
return value;
}
byte[] ApplyDelta (byte[] pixels)
{
var table = new uint[4, 0x100];
for (uint i = 0; i < 0x100; ++i)
{
uint val = i & 0xC0;
val <<= 6;
val |= i & 0x30;
val <<= 6;
val |= i & 0x0C;
val <<= 6;
val |= i & 0x03;
table[0,i] = val << 6;
table[1,i] = val << 4;
table[2,i] = val << 2;
table[3,i] = val;
}
int plane_size = pixels.Length / 4;
int plane0 = 0;
int plane1 = plane0 + plane_size;
int plane2 = plane1 + plane_size;
int plane3 = plane2 + plane_size;
byte[] output = new byte[pixels.Length];
int dst = 0;
while (dst < output.Length)
{
uint val = table[0,pixels[plane0++]] | table[1,pixels[plane1++]]
| table[2,pixels[plane2++]] | table[3,pixels[plane3++]];
output[dst++] = ConvertValue ((byte)val);
output[dst++] = ConvertValue ((byte)(val >> 8));
output[dst++] = ConvertValue ((byte)(val >> 16));
output[dst++] = ConvertValue ((byte)(val >> 24));
}
for (int x = m_pixel_size; x < Stride; x++)
{
output[x] += output[x - m_pixel_size];
}
int line = Stride;
for (uint y = 1; y < m_info.Height; y++)
{
int prev = line - Stride;
for (int x = 0; x < Stride; x++)
{
output[line+x] += output[prev+x];
}
line += Stride;
}
return output;
}
static byte ConvertValue (byte val)
{
bool carry = 0 != (val & 1);
val >>= 1;
return (byte)(carry ? val ^ 0xFF : val);
}
#region IDisposable Members
bool _disposed = false;
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
protected virtual void Dispose (bool disposing)
{
if (!_disposed)
{
if (disposing)
{
m_input.Dispose();
}
_disposed = true;
}
}
#endregion
}
internal sealed class Hg3Reader : HgReader
{
public bool Flipped { get; private set; }
public Hg3Reader (Stream input, HgMetaData info) : base (input, info)
{
}
public byte[] Unpack ()
{
InputStream.Position = m_info.HeaderSize;
var img_type = Input.ReadChars (8);
if (img_type.SequenceEqual ("img0000\0"))
return UnpackImg0000();
else if (img_type.SequenceEqual ("img_jpg\0"))
return UnpackJpeg();
else
throw new NotSupportedException ("Not supported HG-3 image");
}
byte[] UnpackImg0000 ()
{
Flipped = true;
InputStream.Position = m_info.HeaderSize+0x18;
int packed_data_size = Input.ReadInt32();
int data_size = Input.ReadInt32();
int packed_ctl_size = Input.ReadInt32();
int ctl_size = Input.ReadInt32();
return UnpackStream (m_info.HeaderSize+0x28, packed_data_size, data_size, packed_ctl_size, ctl_size);
}
byte[] UnpackJpeg ()
{
Flipped = false;
Input.ReadInt32();
var jpeg_size = Input.ReadInt32();
long next_section = InputStream.Position + jpeg_size;
var decoder = new JpegBitmapDecoder (InputStream,
BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
var frame = decoder.Frames[0];
if (frame.Format.BitsPerPixel < 24)
throw new NotSupportedException ("Not supported HG-3 JPEG color depth");
int src_pixel_size = frame.Format.BitsPerPixel/8;
int stride = (int)m_info.Width * src_pixel_size;
var pixels = new byte[stride*(int)m_info.Height];
frame.CopyPixels (pixels, stride, 0);
var output = new byte[m_info.Width*m_info.Height*4];
uint total = m_info.Width * m_info.Height;
int src = 0;
int dst = 0;
for (uint i = 0; i < total; ++i)
{
output[dst++] = pixels[src];
output[dst++] = pixels[src+1];
output[dst++] = pixels[src+2];
output[dst++] = 0xFF;
src += src_pixel_size;
}
InputStream.Position = next_section;
var section_header = Input.ReadChars (8);
if (!section_header.SequenceEqual ("img_al\0\0"))
return output;
InputStream.Seek (8, SeekOrigin.Current);
int alpha_size = Input.ReadInt32();
using (var alpha_in = new StreamRegion (InputStream, InputStream.Position+4, alpha_size, true))
using (var alpha = new ZLibStream (alpha_in, CompressionMode.Decompress))
{
for (int i = 3; i < output.Length; i += 4)
{
int b = alpha.ReadByte();
if (-1 == b)
throw new EndOfStreamException();
output[i] = (byte)b;
}
return output;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
/// <summary>
/// ToInt64(System.Int16)
/// </summary>
public class ConvertToInt64_6
{
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
//
// TODO: Add your negative test cases here
//
// TestLibrary.TestFramework.LogInformation("[Negative]");
// retVal = NegTest1() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest1: Verify methos ToInt64(random).");
try
{
short random = TestLibrary.Generator.GetInt16(-55);
long actual = Convert.ToInt64(random);
long expected = (long)random;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("001.1", "Method ToInt64 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest2: Verify method ToInt64(0)");
try
{
short i = 0;
long actual = Convert.ToInt64(i);
long expected = 0;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("002.1", "Method ToInt64 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest3: Verify method ToInt64(int16.max)");
try
{
Int16 i = Int16.MaxValue;
long actual = Convert.ToInt64(i);
long expected = (long)Int16.MaxValue;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("003.1", "Method ToInt64 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest4: Verify method ToInt64(int16.min)");
try
{
Int16 i = Int16.MinValue;
long actual = Convert.ToInt64(i);
long expected = (long)Int16.MinValue;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("004.1", "Method ToInt64 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
//public bool NegTest1()
//{
// bool retVal = true;
// TestLibrary.TestFramework.BeginScenario("NegTest1: ");
// try
// {
// //
// // Add your test logic here
// //
// }
// catch (Exception e)
// {
// TestLibrary.TestFramework.LogError("101", "Unexpected exception: " + e);
// TestLibrary.TestFramework.LogInformation(e.StackTrace);
// retVal = false;
// }
// return retVal;
//}
#endregion
#endregion
public static int Main()
{
ConvertToInt64_6 test = new ConvertToInt64_6();
TestLibrary.TestFramework.BeginTestCase("ConvertToInt64_6");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2015-2018 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using NUnit.Common;
using NUnit.Compatibility;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
namespace NUnitLite
{
public class TextUI
{
public ExtendedTextWriter Writer { get; }
private readonly TextReader _reader;
private readonly NUnitLiteOptions _options;
private readonly bool _displayBeforeTest;
private readonly bool _displayAfterTest;
private readonly bool _displayBeforeOutput;
#region Constructor
public TextUI(ExtendedTextWriter writer, TextReader reader, NUnitLiteOptions options)
{
Writer = writer;
_reader = reader;
_options = options;
string labelsOption = options.DisplayTestLabels?.ToUpperInvariant() ?? "ON";
_displayBeforeTest = labelsOption == "ALL" || labelsOption == "BEFORE";
_displayAfterTest = labelsOption == "AFTER";
_displayBeforeOutput = _displayBeforeTest || _displayAfterTest || labelsOption == "ON";
}
#endregion
#region Public Methods
#region DisplayHeader
/// <summary>
/// Writes the header.
/// </summary>
public void DisplayHeader()
{
Assembly executingAssembly = GetType().GetTypeInfo().Assembly;
AssemblyName assemblyName = AssemblyHelper.GetAssemblyName(executingAssembly);
Version version = assemblyName.Version;
string copyright = "Copyright (C) 2018 Charlie Poole, Rob Prouse";
string build = "";
var copyrightAttr = executingAssembly.GetCustomAttribute<AssemblyCopyrightAttribute>();
if (copyrightAttr != null)
copyright = copyrightAttr.Copyright;
var configAttr = executingAssembly.GetCustomAttribute<AssemblyConfigurationAttribute>();
if (configAttr != null)
build = string.Format("({0})", configAttr.Configuration);
WriteHeader(String.Format("NUnitLite {0} {1}", version.ToString(3), build));
WriteSubHeader(copyright);
Writer.WriteLine();
}
#endregion
#region DisplayTestFiles
public void DisplayTestFiles(IEnumerable<string> testFiles)
{
WriteSectionHeader("Test Files");
foreach (string testFile in testFiles)
Writer.WriteLine(ColorStyle.Default, " " + testFile);
Writer.WriteLine();
}
#endregion
#region DisplayHelp
public void DisplayHelp()
{
WriteHeader("Usage: NUNITLITE-RUNNER assembly [options]");
WriteHeader(" USER-EXECUTABLE [options]");
Writer.WriteLine();
WriteHelpLine("Runs a set of NUnitLite tests from the console.");
Writer.WriteLine();
WriteSectionHeader("Assembly:");
WriteHelpLine(" File name or path of the assembly from which to execute tests. Required");
WriteHelpLine(" when using the nunitlite-runner executable to run the tests. Not allowed");
WriteHelpLine(" when running a self-executing user test assembly.");
Writer.WriteLine();
WriteSectionHeader("Options:");
using (var sw = new StringWriter())
{
_options.WriteOptionDescriptions(sw);
Writer.Write(ColorStyle.Help, sw.ToString());
}
WriteSectionHeader("Notes:");
WriteHelpLine(" * File names may be listed by themselves, with a relative path or ");
WriteHelpLine(" using an absolute path. Any relative path is based on the current ");
WriteHelpLine(" directory.");
Writer.WriteLine();
WriteHelpLine(" * On Windows, options may be prefixed by a '/' character if desired");
Writer.WriteLine();
WriteHelpLine(" * Options that take values may use an equal sign or a colon");
WriteHelpLine(" to separate the option from its value.");
Writer.WriteLine();
WriteHelpLine(" * Several options that specify processing of XML output take");
WriteHelpLine(" an output specification as a value. A SPEC may take one of");
WriteHelpLine(" the following forms:");
WriteHelpLine(" --OPTION:filename");
WriteHelpLine(" --OPTION:filename;format=formatname");
Writer.WriteLine();
WriteHelpLine(" The --result option may use any of the following formats:");
WriteHelpLine(" nunit3 - the native XML format for NUnit 3");
WriteHelpLine(" nunit2 - legacy XML format used by earlier releases of NUnit");
Writer.WriteLine();
WriteHelpLine(" The --explore option may use any of the following formats:");
WriteHelpLine(" nunit3 - the native XML format for NUnit 3");
WriteHelpLine(" cases - a text file listing the full names of all test cases.");
WriteHelpLine(" If --explore is used without any specification following, a list of");
WriteHelpLine(" test cases is output to the console.");
Writer.WriteLine();
}
#endregion
#region DisplayRuntimeEnvironment
/// <summary>
/// Displays info about the runtime environment.
/// </summary>
public void DisplayRuntimeEnvironment()
{
WriteSectionHeader("Runtime Environment");
#if NETSTANDARD1_4 || NETSTANDARD2_0
Writer.WriteLabelLine(" OS Version: ", System.Runtime.InteropServices.RuntimeInformation.OSDescription);
#else
Writer.WriteLabelLine(" OS Version: ", OSPlatform.CurrentPlatform);
#endif
#if NETSTANDARD1_4
Writer.WriteLabelLine(" CLR Version: ", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription);
#else
Writer.WriteLabelLine(" CLR Version: ", Environment.Version);
#endif
Writer.WriteLine();
}
#endregion
#region Test Discovery Report
public void DisplayDiscoveryReport(TimeStamp startTime, TimeStamp endTime)
{
WriteSectionHeader("Test Discovery");
foreach (string filter in _options.PreFilters)
Writer.WriteLabelLine(" Pre-Filter: ", filter);
Writer.WriteLabelLine(" Start time: ", startTime.DateTime.ToString("u"));
Writer.WriteLabelLine(" End time: ", endTime.DateTime.ToString("u"));
double elapsedSeconds = TimeStamp.TicksToSeconds(endTime.Ticks - startTime.Ticks);
Writer.WriteLabelLine(" Duration: ", string.Format(NumberFormatInfo.InvariantInfo, "{0:0.000} seconds", elapsedSeconds));
Writer.WriteLine();
}
#endregion
#region DisplayTestFilters
public void DisplayTestFilters()
{
if (_options.TestList.Count > 0 || _options.WhereClauseSpecified)
{
WriteSectionHeader("Test Filters");
foreach (string testName in _options.TestList)
Writer.WriteLabelLine(" Test: ", testName);
if (_options.WhereClauseSpecified)
Writer.WriteLabelLine(" Where: ", _options.WhereClause.Trim());
Writer.WriteLine();
}
}
#endregion
#region DisplayRunSettings
public void DisplayRunSettings()
{
WriteSectionHeader("Run Settings");
if (_options.DefaultTimeout >= 0)
Writer.WriteLabelLine(" Default timeout: ", _options.DefaultTimeout);
#if PARALLEL
Writer.WriteLabelLine(
" Number of Test Workers: ",
_options.NumberOfTestWorkers >= 0
? _options.NumberOfTestWorkers
: Math.Max(Environment.ProcessorCount, 2));
#endif
Writer.WriteLabelLine(" Work Directory: ", _options.WorkDirectory ?? Directory.GetCurrentDirectory());
Writer.WriteLabelLine(" Internal Trace: ", _options.InternalTraceLevel ?? "Off");
if (_options.TeamCity)
Writer.WriteLine(ColorStyle.Value, " Display TeamCity Service Messages");
Writer.WriteLine();
}
#endregion
#region TestStarted
public void TestStarted(ITest test)
{
if (_displayBeforeTest && !test.IsSuite)
WriteLabelLine(test.FullName);
}
#endregion
#region TestFinished
private bool _testCreatedOutput = false;
private bool _needsNewLine = false;
public void TestFinished(ITestResult result)
{
if (result.Output.Length > 0)
{
if (_displayBeforeOutput)
WriteLabelLine(result.Test.FullName);
WriteOutput(result.Output);
if (!result.Output.EndsWith("\n"))
Writer.WriteLine();
}
if (!result.Test.IsSuite)
{
if (_displayAfterTest)
WriteLabelLineAfterTest(result.Test.FullName, result.ResultState);
}
if (result.Test is TestAssembly && _testCreatedOutput)
{
Writer.WriteLine();
_testCreatedOutput = false;
}
}
#endregion
#region TestOutput
public void TestOutput(TestOutput output)
{
if (_displayBeforeOutput && output.TestName != null)
WriteLabelLine(output.TestName);
WriteOutput(output.Stream == "Error" ? ColorStyle.Error : ColorStyle.Output, output.Text);
}
#endregion
#region WaitForUser
public void WaitForUser(string message)
{
// Ignore if we don't have a TextReader
if (_reader != null)
{
Writer.WriteLine(ColorStyle.Label, message);
_reader.ReadLine();
}
}
#endregion
#region Test Result Reports
#region DisplaySummaryReport
public void DisplaySummaryReport(ResultSummary summary)
{
var status = summary.ResultState.Status;
var overallResult = status.ToString();
if (overallResult == "Skipped")
overallResult = "Warning";
ColorStyle overallStyle = status == TestStatus.Passed
? ColorStyle.Pass
: status == TestStatus.Failed
? ColorStyle.Failure
: status == TestStatus.Skipped
? ColorStyle.Warning
: ColorStyle.Output;
if (_testCreatedOutput)
Writer.WriteLine();
WriteSectionHeader("Test Run Summary");
Writer.WriteLabelLine(" Overall result: ", overallResult, overallStyle);
WriteSummaryCount(" Test Count: ", summary.TestCount);
WriteSummaryCount(", Passed: ", summary.PassCount);
WriteSummaryCount(", Failed: ", summary.FailedCount, ColorStyle.Failure);
WriteSummaryCount(", Warnings: ", summary.WarningCount, ColorStyle.Warning);
WriteSummaryCount(", Inconclusive: ", summary.InconclusiveCount);
WriteSummaryCount(", Skipped: ", summary.TotalSkipCount);
Writer.WriteLine();
if (summary.FailedCount > 0)
{
WriteSummaryCount(" Failed Tests - Failures: ", summary.FailureCount, ColorStyle.Failure);
WriteSummaryCount(", Errors: ", summary.ErrorCount, ColorStyle.Error);
WriteSummaryCount(", Invalid: ", summary.InvalidCount, ColorStyle.Error);
Writer.WriteLine();
}
if (summary.TotalSkipCount > 0)
{
WriteSummaryCount(" Skipped Tests - Ignored: ", summary.IgnoreCount, ColorStyle.Warning);
WriteSummaryCount(", Explicit: ", summary.ExplicitCount);
WriteSummaryCount(", Other: ", summary.SkipCount);
Writer.WriteLine();
}
Writer.WriteLabelLine(" Start time: ", summary.StartTime.ToString("u"));
Writer.WriteLabelLine(" End time: ", summary.EndTime.ToString("u"));
Writer.WriteLabelLine(" Duration: ", string.Format(NumberFormatInfo.InvariantInfo, "{0:0.000} seconds", summary.Duration));
Writer.WriteLine();
}
private void WriteSummaryCount(string label, int count)
{
Writer.WriteLabel(label, count.ToString(CultureInfo.CurrentUICulture));
}
private void WriteSummaryCount(string label, int count, ColorStyle color)
{
Writer.WriteLabel(label, count.ToString(CultureInfo.CurrentUICulture), count > 0 ? color : ColorStyle.Value);
}
#endregion
#region DisplayErrorsAndFailuresReport
public void DisplayErrorsFailuresAndWarningsReport(ITestResult result)
{
_reportIndex = 0;
WriteSectionHeader("Errors, Failures and Warnings");
DisplayErrorsFailuresAndWarnings(result);
Writer.WriteLine();
if (_options.StopOnError)
{
Writer.WriteLine(ColorStyle.Failure, "Execution terminated after first error");
Writer.WriteLine();
}
}
#endregion
#region DisplayNotRunReport
public void DisplayNotRunReport(ITestResult result)
{
_reportIndex = 0;
WriteSectionHeader("Tests Not Run");
DisplayNotRunResults(result);
Writer.WriteLine();
}
#endregion
#region DisplayFullReport
#if FULL // Not currently used, but may be reactivated
/// <summary>
/// Prints a full report of all results
/// </summary>
public void DisplayFullReport(ITestResult result)
{
WriteLine(ColorStyle.SectionHeader, "All Test Results -");
_writer.WriteLine();
DisplayAllResults(result, " ");
_writer.WriteLine();
}
#endif
#endregion
#endregion
#region DisplayWarning
public void DisplayWarning(string text)
{
Writer.WriteLine(ColorStyle.Warning, text);
}
#endregion
#region DisplayError
public void DisplayError(string text)
{
Writer.WriteLine(ColorStyle.Error, text);
}
#endregion
#region DisplayErrors
public void DisplayErrors(IList<string> messages)
{
foreach (string message in messages)
DisplayError(message);
}
#endregion
#endregion
#region Helper Methods
private void DisplayErrorsFailuresAndWarnings(ITestResult result)
{
bool display =
result.ResultState.Status == TestStatus.Failed ||
result.ResultState.Status == TestStatus.Warning;
if (result.Test.IsSuite)
{
if (display)
{
var suite = result.Test as TestSuite;
var site = result.ResultState.Site;
if (suite.TestType == "Theory" || site == FailureSite.SetUp || site == FailureSite.TearDown)
DisplayTestResult(result);
if (site == FailureSite.SetUp) return;
}
foreach (ITestResult childResult in result.Children)
DisplayErrorsFailuresAndWarnings(childResult);
}
else if (display)
DisplayTestResult(result);
}
private void DisplayNotRunResults(ITestResult result)
{
if (result.HasChildren)
foreach (ITestResult childResult in result.Children)
DisplayNotRunResults(childResult);
else if (result.ResultState.Status == TestStatus.Skipped)
DisplayTestResult(result);
}
private static readonly char[] TRIM_CHARS = new char[] { '\r', '\n' };
private int _reportIndex;
private void DisplayTestResult(ITestResult result)
{
ResultState resultState = result.ResultState;
string fullName = result.FullName;
string message = result.Message;
string stackTrace = result.StackTrace;
string reportID = (++_reportIndex).ToString();
int numAsserts = result.AssertionResults.Count;
if (numAsserts > 0)
{
int assertionCounter = 0;
string assertID = reportID;
foreach (var assertion in result.AssertionResults)
{
if (numAsserts > 1)
assertID = string.Format("{0}-{1}", reportID, ++assertionCounter);
ColorStyle style = GetColorStyle(resultState);
string status = assertion.Status.ToString();
DisplayTestResult(style, assertID, status, fullName, assertion.Message, assertion.StackTrace);
}
}
else
{
ColorStyle style = GetColorStyle(resultState);
string status = GetResultStatus(resultState);
DisplayTestResult(style, reportID, status, fullName, message, stackTrace);
}
}
private void DisplayTestResult(ColorStyle style, string prefix, string status, string fullName, string message, string stackTrace)
{
Writer.WriteLine();
Writer.WriteLine(
style, string.Format("{0}) {1} : {2}", prefix, status, fullName));
if (!string.IsNullOrEmpty(message))
Writer.WriteLine(style, message.TrimEnd(TRIM_CHARS));
if (!string.IsNullOrEmpty(stackTrace))
Writer.WriteLine(style, stackTrace.TrimEnd(TRIM_CHARS));
}
private static ColorStyle GetColorStyle(ResultState resultState)
{
ColorStyle style = ColorStyle.Output;
switch (resultState.Status)
{
case TestStatus.Failed:
style = ColorStyle.Failure;
break;
case TestStatus.Warning:
style = ColorStyle.Warning;
break;
case TestStatus.Skipped:
style = resultState.Label == "Ignored" ? ColorStyle.Warning : ColorStyle.Output;
break;
case TestStatus.Passed:
style = ColorStyle.Pass;
break;
}
return style;
}
private static string GetResultStatus(ResultState resultState)
{
string status = resultState.Label;
if (string.IsNullOrEmpty(status))
status = resultState.Status.ToString();
if (status == "Failed" || status == "Error")
{
var site = resultState.Site.ToString();
if (site == "SetUp" || site == "TearDown")
status = site + " " + status;
}
return status;
}
#if FULL
private void DisplayAllResults(ITestResult result, string indent)
{
string status = null;
ColorStyle style = ColorStyle.Output;
switch (result.ResultState.Status)
{
case TestStatus.Failed:
status = "FAIL";
style = ColorStyle.Failure;
break;
case TestStatus.Skipped:
if (result.ResultState.Label == "Ignored")
{
status = "IGN ";
style = ColorStyle.Warning;
}
else
{
status = "SKIP";
style = ColorStyle.Output;
}
break;
case TestStatus.Inconclusive:
status = "INC ";
style = ColorStyle.Output;
break;
case TestStatus.Passed:
status = "OK ";
style = ColorStyle.Pass;
break;
}
WriteLine(style, status + indent + result.Name);
if (result.HasChildren)
foreach (ITestResult childResult in result.Children)
PrintAllResults(childResult, indent + " ");
}
#endif
private void WriteHeader(string text)
{
Writer.WriteLine(ColorStyle.Header, text);
}
private void WriteSubHeader(string text)
{
Writer.WriteLine(ColorStyle.SubHeader, text);
}
private void WriteSectionHeader(string text)
{
Writer.WriteLine(ColorStyle.SectionHeader, text);
}
private void WriteHelpLine(string text)
{
Writer.WriteLine(ColorStyle.Help, text);
}
private string _currentLabel;
private void WriteLabelLine(string label)
{
if (label != _currentLabel)
{
WriteNewLineIfNeeded();
Writer.WriteLine(ColorStyle.SectionHeader, "=> " + label);
_testCreatedOutput = true;
_currentLabel = label;
}
}
private void WriteLabelLineAfterTest(string label, ResultState resultState)
{
WriteNewLineIfNeeded();
string status = string.IsNullOrEmpty(resultState.Label)
? resultState.Status.ToString()
: resultState.Label;
Writer.Write(GetColorForResultStatus(status), status);
Writer.WriteLine(ColorStyle.SectionHeader, " => " + label);
_currentLabel = label;
}
private void WriteNewLineIfNeeded()
{
if (_needsNewLine)
{
Writer.WriteLine();
_needsNewLine = false;
}
}
private void WriteOutput(string text)
{
WriteOutput(ColorStyle.Output, text);
}
private void WriteOutput(ColorStyle color, string text)
{
Writer.Write(color, text);
_testCreatedOutput = true;
_needsNewLine = !text.EndsWith("\n");
}
private static ColorStyle GetColorForResultStatus(string status)
{
switch (status)
{
case "Passed":
return ColorStyle.Pass;
case "Failed":
return ColorStyle.Failure;
case "Error":
case "Invalid":
case "Cancelled":
return ColorStyle.Error;
case "Warning":
case "Ignored":
return ColorStyle.Warning;
default:
return ColorStyle.Output;
}
}
#endregion
}
}
| |
//-----------------------------------------------------------------------
// <copyright>
// Copyright (C) Ruslan Yakushev for the PHP Manager for IIS project.
//
// This file is subject to the terms and conditions of the Microsoft Public License (MS-PL).
// See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL for more details.
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows.Forms;
using Microsoft.Web.Management.Client;
using Microsoft.Web.Management.Client.Win32;
using Web.Management.PHP.Config;
namespace Web.Management.PHP.Settings
{
[ModulePageIdentifier(Globals.ErrorReportingPageIdentifier)]
internal sealed class ErrorReportingPage : ModuleDialogPage, IModuleChildPage
{
enum ErrorReportingPreset { Undefined = 0, Development = 1, Production = 2 };
private string _errorLogFile = String.Empty;
private ErrorReportingPreset _errorReportingPreset = ErrorReportingPreset.Undefined;
private bool _hasChanges;
private readonly string[] SettingNames = {
"error_reporting",
"display_errors",
"track_errors",
"html_errors",
"log_errors",
"fastcgi.logging"
};
private readonly string[] SettingsDevValues = {
"E_ALL | E_STRICT",
"On",
"On",
"On",
"On",
"1"
};
private readonly string[] SettingsProdValues = {
"E_ALL & ~E_DEPRECATED",
"Off",
"Off",
"Off",
"On",
"0"
};
private Label _devMachineLabel;
private Label _selectServerTypeLabel;
private RadioButton _devMachineRadioButton;
private RadioButton _prodMachineRadioButton;
private Label _prodMachineLabel;
private Label _errorLogFileLabel;
private TextBox _errorLogFileTextBox;
private Button _errorLogBrowseButton;
private GroupBox _serverTypeGroupBox;
private PageTaskList _taskList;
private IModulePage _parentPage;
protected override bool CanApplyChanges
{
get
{
return _hasChanges && (_devMachineRadioButton.Checked || _prodMachineRadioButton.Checked);
}
}
protected override bool HasChanges
{
get
{
return _hasChanges;
}
}
internal bool IsReadOnly
{
get
{
return Connection.ConfigurationPath.PathType == Microsoft.Web.Management.Server.ConfigurationPathType.Site &&
!Connection.IsUserServerAdministrator;
}
}
private new PHPModule Module
{
get
{
return (PHPModule)base.Module;
}
}
public IModulePage ParentPage
{
get
{
return _parentPage;
}
set
{
_parentPage = value;
}
}
protected override TaskListCollection Tasks
{
get
{
TaskListCollection tasks = base.Tasks;
if (_taskList == null)
{
_taskList = new PageTaskList(this);
}
tasks.Add(_taskList);
return tasks;
}
}
protected override bool ApplyChanges()
{
bool appliedChanges = false;
string[] settingValues = null;
Debug.Assert(_devMachineRadioButton.Checked || _prodMachineRadioButton.Checked);
if (_devMachineRadioButton.Checked)
{
settingValues = SettingsDevValues;
}
else if (_prodMachineRadioButton.Checked)
{
settingValues = SettingsProdValues;
}
RemoteObjectCollection<PHPIniSetting> settings = new RemoteObjectCollection<PHPIniSetting>();
for (int i = 0; i < settingValues.Length; i++)
{
settings.Add(new PHPIniSetting(SettingNames[i], settingValues[i], "PHP"));
}
string errorLogValue = '"' + _errorLogFileTextBox.Text.Trim(new char [] {' ', '"'}) + '"';
settings.Add(new PHPIniSetting("error_log", errorLogValue, "PHP"));
try
{
Module.Proxy.AddOrUpdateSettings(settings);
appliedChanges = true;
// Update the values used for determining if changes have been made
_errorLogFile = _errorLogFileTextBox.Text;
if (_devMachineRadioButton.Checked)
{
_errorReportingPreset = ErrorReportingPreset.Development;
}
else if (_prodMachineRadioButton.Checked)
{
_errorReportingPreset = ErrorReportingPreset.Production;
}
_hasChanges = false;
}
catch (Exception ex)
{
DisplayErrorMessage(ex, Resources.ResourceManager);
}
finally
{
Update();
}
return appliedChanges;
}
protected override void CancelChanges()
{
if (_errorReportingPreset == ErrorReportingPreset.Development)
{
_devMachineRadioButton.Checked = true;
}
else if (_errorReportingPreset == ErrorReportingPreset.Production)
{
_prodMachineRadioButton.Checked = true;
}
else
{
_devMachineRadioButton.Checked = false;
_prodMachineRadioButton.Checked = false;
}
_errorLogFileTextBox.Text = _errorLogFile;
_hasChanges = false;
Update();
}
private void GetSettings()
{
StartAsyncTask(Resources.AllSettingsPageGettingSettings, OnGetSettings, OnGetSettingsCompleted);
}
private void GoBack()
{
Navigate(typeof(PHPPage));
}
protected override void Initialize(object navigationData)
{
base.Initialize(navigationData);
InitializeComponent();
InitializeUI();
}
private void InitializeComponent()
{
this._serverTypeGroupBox = new System.Windows.Forms.GroupBox();
this._prodMachineLabel = new System.Windows.Forms.Label();
this._prodMachineRadioButton = new System.Windows.Forms.RadioButton();
this._devMachineLabel = new System.Windows.Forms.Label();
this._selectServerTypeLabel = new System.Windows.Forms.Label();
this._devMachineRadioButton = new System.Windows.Forms.RadioButton();
this._errorLogFileLabel = new System.Windows.Forms.Label();
this._errorLogFileTextBox = new System.Windows.Forms.TextBox();
this._errorLogBrowseButton = new System.Windows.Forms.Button();
this._serverTypeGroupBox.SuspendLayout();
this.SuspendLayout();
//
// _serverTypeGroupBox
//
this._serverTypeGroupBox.Controls.Add(this._prodMachineLabel);
this._serverTypeGroupBox.Controls.Add(this._prodMachineRadioButton);
this._serverTypeGroupBox.Controls.Add(this._devMachineLabel);
this._serverTypeGroupBox.Controls.Add(this._selectServerTypeLabel);
this._serverTypeGroupBox.Controls.Add(this._devMachineRadioButton);
this._serverTypeGroupBox.Location = new System.Drawing.Point(4, 12);
this._serverTypeGroupBox.Name = "_serverTypeGroupBox";
this._serverTypeGroupBox.Size = new System.Drawing.Size(472, 222);
this._serverTypeGroupBox.TabIndex = 0;
this._serverTypeGroupBox.TabStop = false;
this._serverTypeGroupBox.Text = Resources.ErrorReportingPageServerType;
//
// _prodMachineLabel
//
this._prodMachineLabel.Location = new System.Drawing.Point(37, 150);
this._prodMachineLabel.Name = "_prodMachineLabel";
this._prodMachineLabel.Size = new System.Drawing.Size(413, 48);
this._prodMachineLabel.TabIndex = 4;
this._prodMachineLabel.Text = Resources.ErrorReportingPageProdMachineDesc;
//
// _prodMachineRadioButton
//
this._prodMachineRadioButton.AutoSize = true;
this._prodMachineRadioButton.Location = new System.Drawing.Point(20, 130);
this._prodMachineRadioButton.Name = "_prodMachineRadioButton";
this._prodMachineRadioButton.Size = new System.Drawing.Size(119, 17);
this._prodMachineRadioButton.TabIndex = 3;
this._prodMachineRadioButton.TabStop = true;
this._prodMachineRadioButton.Text = Resources.ErrorReportingPageProdMachine;
this._prodMachineRadioButton.UseVisualStyleBackColor = true;
this._prodMachineRadioButton.CheckedChanged += new System.EventHandler(this.OnProdMachineRadioButtonCheckedChanged);
//
// _devMachineLabel
//
this._devMachineLabel.Location = new System.Drawing.Point(37, 75);
this._devMachineLabel.Name = "_devMachineLabel";
this._devMachineLabel.Size = new System.Drawing.Size(413, 46);
this._devMachineLabel.TabIndex = 2;
this._devMachineLabel.Text = Resources.ErrorReportingPageDevMachineDesc;
//
// _selectServerTypeLabel
//
this._selectServerTypeLabel.Location = new System.Drawing.Point(6, 20);
this._selectServerTypeLabel.Name = "_selectServerTypeLabel";
this._selectServerTypeLabel.Size = new System.Drawing.Size(458, 23);
this._selectServerTypeLabel.TabIndex = 0;
this._selectServerTypeLabel.Text = Resources.ErrorReportingPageSelectServerType;
//
// _devMachineRadioButton
//
this._devMachineRadioButton.AutoSize = true;
this._devMachineRadioButton.Location = new System.Drawing.Point(20, 55);
this._devMachineRadioButton.Name = "_devMachineRadioButton";
this._devMachineRadioButton.Size = new System.Drawing.Size(131, 17);
this._devMachineRadioButton.TabIndex = 1;
this._devMachineRadioButton.TabStop = true;
this._devMachineRadioButton.Text = Resources.ErrorReportingPageDevMachine;
this._devMachineRadioButton.UseVisualStyleBackColor = true;
this._devMachineRadioButton.CheckedChanged += new System.EventHandler(this.OnDevMachineRadioButtonCheckedChanged);
//
// _errorLogFileLabel
//
this._errorLogFileLabel.AutoSize = true;
this._errorLogFileLabel.Location = new System.Drawing.Point(3, 253);
this._errorLogFileLabel.Name = "_errorLogFileLabel";
this._errorLogFileLabel.Size = new System.Drawing.Size(65, 13);
this._errorLogFileLabel.TabIndex = 1;
this._errorLogFileLabel.Text = Resources.ErrorReportingErrorLogFile;
//
// _errorLogFileTextBox
//
this._errorLogFileTextBox.Location = new System.Drawing.Point(7, 269);
this._errorLogFileTextBox.Name = "_errorLogFileTextBox";
this._errorLogFileTextBox.Size = new System.Drawing.Size(438, 20);
this._errorLogFileTextBox.TabIndex = 2;
this._errorLogFileTextBox.TextChanged += new System.EventHandler(this.OnErrorLogFileTextBoxTextChanged);
//
// _errorLogBrowseButton
//
this._errorLogBrowseButton.Location = new System.Drawing.Point(451, 267);
this._errorLogBrowseButton.Name = "_errorLogBrowseButton";
this._errorLogBrowseButton.Size = new System.Drawing.Size(25, 23);
this._errorLogBrowseButton.TabIndex = 3;
this._errorLogBrowseButton.Text = "...";
this._errorLogBrowseButton.UseVisualStyleBackColor = true;
this._errorLogBrowseButton.Click += new System.EventHandler(this.OnErrorLogBrowseButtonClick);
//
// ErrorReportingPage
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScroll = true;
this.Controls.Add(this._errorLogBrowseButton);
this.Controls.Add(this._errorLogFileTextBox);
this.Controls.Add(this._errorLogFileLabel);
this.Controls.Add(this._serverTypeGroupBox);
this.Name = "ErrorReportingPage";
this.Size = new System.Drawing.Size(480, 360);
this._serverTypeGroupBox.ResumeLayout(false);
this._serverTypeGroupBox.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
private void InitializeUI()
{
if (this.IsReadOnly)
{
_devMachineRadioButton.Enabled = false;
_devMachineLabel.Enabled = false;
_prodMachineRadioButton.Enabled = false;
_prodMachineLabel.Enabled = false;
_errorLogFileTextBox.Enabled = false;
_errorLogBrowseButton.Enabled = false;
}
// Only show the auto suggest if it is a local connection.
// Otherwise do not show auto suggest and also hide the browse button.
if (Connection.IsLocalConnection)
{
this._errorLogFileTextBox.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest;
this._errorLogFileTextBox.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.FileSystem;
}
else
{
this._errorLogBrowseButton.Visible = false;
}
}
protected override void OnActivated(bool initialActivation)
{
base.OnActivated(initialActivation);
if (initialActivation)
{
GetSettings();
}
}
private void OnDevMachineRadioButtonCheckedChanged(object sender, EventArgs e)
{
bool oldHasChanges = _hasChanges;
if (_errorReportingPreset == ErrorReportingPreset.Development)
{
_hasChanges = !_devMachineRadioButton.Checked;
}
else
{
_hasChanges = _devMachineRadioButton.Checked;
}
_hasChanges = _hasChanges || oldHasChanges;
if (_hasChanges)
{
Update();
}
}
private void OnErrorLogBrowseButtonClick(object sender, EventArgs e)
{
using (SaveFileDialog dlg = new SaveFileDialog())
{
dlg.Title = Resources.ErrorLogSaveDialogTitle;
dlg.Filter = Resources.ErrorLogSaveDialogFilter;
if (!String.IsNullOrEmpty(_errorLogFileTextBox.Text))
{
dlg.InitialDirectory = System.IO.Path.GetDirectoryName(_errorLogFileTextBox.Text.Trim());
}
else
{
dlg.InitialDirectory = Environment.ExpandEnvironmentVariables("%SystemDrive%");
}
if (dlg.ShowDialog() == DialogResult.OK)
{
_errorLogFileTextBox.Text = dlg.FileName;
}
}
}
private void OnErrorLogFileTextBoxTextChanged(object sender, EventArgs e)
{
if (!String.Equals(_errorLogFileTextBox.Text, _errorLogFile, StringComparison.OrdinalIgnoreCase))
{
_hasChanges = true;
Update();
}
}
private void OnGetSettings(object sender, DoWorkEventArgs e)
{
e.Result = Module.Proxy.GetPHPIniSettings();
}
private void OnGetSettingsCompleted(object sender, RunWorkerCompletedEventArgs e)
{
try
{
object o = e.Result;
PHPIniFile file = new PHPIniFile();
file.SetData(o);
UpdateUI(file);
}
catch (Exception ex)
{
DisplayErrorMessage(ex, Resources.ResourceManager);
}
}
private void OnProdMachineRadioButtonCheckedChanged(object sender, EventArgs e)
{
bool oldHasChanges = _hasChanges;
if (_errorReportingPreset == ErrorReportingPreset.Production)
{
_hasChanges = !_prodMachineRadioButton.Checked;
}
else
{
_hasChanges = _prodMachineRadioButton.Checked;
}
_hasChanges = _hasChanges || oldHasChanges;
if (_hasChanges)
{
Update();
}
}
protected override bool ShowHelp()
{
return ShowOnlineHelp();
}
protected override bool ShowOnlineHelp()
{
return Helper.Browse(Globals.ErrorReportingOnlineHelp);
}
private void UpdateUI(PHPIniFile file)
{
PHPIniSetting setting = file.GetSetting(SettingNames[0]);
string[] settingValues = null;
if (setting != null)
{
if (String.Equals(setting.GetTrimmedValue(), SettingsDevValues[0]))
{
_errorReportingPreset = ErrorReportingPreset.Development;
settingValues = SettingsDevValues;
}
else if (String.Equals(setting.GetTrimmedValue(), SettingsProdValues[0]))
{
_errorReportingPreset = ErrorReportingPreset.Production;
settingValues = SettingsProdValues;
}
int i = 1;
while (_errorReportingPreset != ErrorReportingPreset.Undefined && i < SettingNames.Length)
{
setting = file.GetSetting(SettingNames[i]);
if (setting == null || !String.Equals(setting.GetTrimmedValue(), settingValues[i]))
{
_errorReportingPreset = ErrorReportingPreset.Undefined;
}
i = i + 1;
}
}
if (_errorReportingPreset == ErrorReportingPreset.Development)
{
_devMachineRadioButton.Checked = true;
}
else if (_errorReportingPreset == ErrorReportingPreset.Production)
{
_prodMachineRadioButton.Checked = true;
}
setting = file.GetSetting("error_log");
if (setting != null)
{
_errorLogFile = setting.GetTrimmedValue();
_errorLogFileTextBox.Text = setting.GetTrimmedValue();
}
}
private class PageTaskList : TaskList
{
private ErrorReportingPage _page;
public PageTaskList(ErrorReportingPage page)
{
_page = page;
}
public override System.Collections.ICollection GetTaskItems()
{
List<TaskItem> tasks = new List<TaskItem>();
if (_page.IsReadOnly)
{
tasks.Add(new MessageTaskItem(MessageTaskItemType.Information, Resources.AllPagesPageIsReadOnly, "Information"));
}
tasks.Add(new MethodTaskItem("GoBack", Resources.AllPagesGoBackTask, "Tasks", null, Resources.GoBack16));
return tasks;
}
public void GoBack()
{
_page.GoBack();
}
}
}
}
| |
using UnityEngine;
using System.Collections;
public class MegaNearestPointTest
{
public static Vector3 NearestPointOnMesh1(Vector3 pt, Vector3[] verts, int[] tri, ref int index, ref Vector3 bary)
{
float nearestSqDist = float.MaxValue;
Vector3 nearestPt = Vector3.zero;
nearestSqDist = float.MaxValue;
for ( int i = 0; i < tri.Length; i += 3 )
{
Vector3 a = verts[tri[i]];
Vector3 b = verts[tri[i + 1]];
Vector3 c = verts[tri[i + 2]];
float dist = DistPoint3Triangle3Dbl(pt, a, b, c);
float possNearestSqDist = dist;
if ( possNearestSqDist < nearestSqDist )
{
index = i;
bary = mTriangleBary;
nearestPt = mClosestPoint1;
nearestSqDist = possNearestSqDist;
}
}
return nearestPt;
}
public static Vector3 NearestPointOnMesh2(Vector3 pt, Vector3[] verts, int[] tri, ref int index, ref Vector3 bary)
{
float nearestSqDist = float.MaxValue;
Vector3 nearestPt = Vector3.zero;
nearestSqDist = float.MaxValue;
for ( int i = 0; i < tri.Length; i += 3 )
{
Vector3 a = verts[tri[i]];
Vector3 b = verts[tri[i + 1]];
Vector3 c = verts[tri[i + 2]];
float dist = DistPoint3Triangle3Dbl(pt, a, b, c);
float possNearestSqDist = dist;
if ( possNearestSqDist < nearestSqDist )
{
index = i;
bary = mTriangleBary;
nearestPt = mClosestPoint1;
nearestSqDist = possNearestSqDist;
}
}
return nearestPt;
}
public static float DistPoint3Triangle3Dbl(Vector3 mPoint, Vector3 v0, Vector3 v1, Vector3 v2)
{
Vector3 diff = v0 - mPoint;
Vector3 edge0 = v1 - v0;
Vector3 edge1 = v2 - v0;
double a00 = edge0.sqrMagnitude; //.SquaredLength();
double a01 = Vector3.Dot(edge1, edge0);
double a11 = edge1.sqrMagnitude;
double b0 = Vector3.Dot(edge0, diff);
double b1 = Vector3.Dot(edge1, diff);
double c = diff.sqrMagnitude;
double det = Mathf.Abs((float)a00 * (float)a11 - (float)a01 * (float)a01);
double s = a01 * b1 - a11 * b0;
double t = a01 * b0 - a00 * b1;
double sqrDistance;
if ( s + t <= det )
{
if ( s < (double)0.0 )
{
if ( t < (double)0 ) // region 4
{
if ( b0 < (double)0 )
{
t = (double)0;
if ( -b0 >= a00 )
{
s = (double)1;
sqrDistance = a00 + ((double)2) * b0 + c;
}
else
{
s = -b0 / a00;
sqrDistance = b0 * s + c;
}
}
else
{
s = (double)0;
if ( b1 >= (double)0 )
{
t = (double)0;
sqrDistance = c;
}
else if ( -b1 >= a11 )
{
t = (double)1;
sqrDistance = a11 + ((double)2) * b1 + c;
}
else
{
t = -b1 / a11;
sqrDistance = b1 * t + c;
}
}
}
else // region 3
{
s = (double)0;
if ( b1 >= (double)0 )
{
t = (double)0;
sqrDistance = c;
}
else if ( -b1 >= a11 )
{
t = (double)1;
sqrDistance = a11 + ((double)2) * b1 + c;
}
else
{
t = -b1 / a11;
sqrDistance = b1 * t + c;
}
}
}
else if ( t < (double)0 ) // region 5
{
t = (double)0;
if ( b0 >= (double)0 )
{
s = (double)0;
sqrDistance = c;
}
else if ( -b0 >= a00 )
{
s = (double)1;
sqrDistance = a00 + ((double)2) * b0 + c;
}
else
{
s = -b0 / a00;
sqrDistance = b0 * s + c;
}
}
else // region 0
{
// minimum at interior point
double invDet = ((double)1) / det;
s *= invDet;
t *= invDet;
sqrDistance = s * (a00 * s + a01 * t + ((double)2) * b0) +
t * (a01 * s + a11 * t + ((double)2) * b1) + c;
}
}
else
{
double tmp0, tmp1, numer, denom;
if ( s < (double)0 ) // region 2
{
tmp0 = a01 + b0;
tmp1 = a11 + b1;
if ( tmp1 > tmp0 )
{
numer = tmp1 - tmp0;
denom = a00 - ((double)2) * a01 + a11;
if ( numer >= denom )
{
s = (double)1;
t = (double)0;
sqrDistance = a00 + ((double)2) * b0 + c;
}
else
{
s = numer / denom;
t = (double)1 - s;
sqrDistance = s * (a00 * s + a01 * t + ((double)2) * b0) +
t * (a01 * s + a11 * t + ((double)2) * b1) + c;
}
}
else
{
s = (double)0;
if ( tmp1 <= (double)0 )
{
t = (double)1;
sqrDistance = a11 + ((double)2) * b1 + c;
}
else if ( b1 >= (double)0 )
{
t = (double)0;
sqrDistance = c;
}
else
{
t = -b1 / a11;
sqrDistance = b1 * t + c;
}
}
}
else if ( t < (double)0 ) // region 6
{
tmp0 = a01 + b1;
tmp1 = a00 + b0;
if ( tmp1 > tmp0 )
{
numer = tmp1 - tmp0;
denom = a00 - ((double)2) * a01 + a11;
if ( numer >= denom )
{
t = (double)1;
s = (double)0;
sqrDistance = a11 + ((double)2) * b1 + c;
}
else
{
t = numer / denom;
s = (double)1 - t;
sqrDistance = s * (a00 * s + a01 * t + ((double)2) * b0) +
t * (a01 * s + a11 * t + ((double)2) * b1) + c;
}
}
else
{
t = (double)0;
if ( tmp1 <= (double)0 )
{
s = (double)1;
sqrDistance = a00 + ((double)2) * b0 + c;
}
else if ( b0 >= (double)0 )
{
s = (double)0;
sqrDistance = c;
}
else
{
s = -b0 / a00;
sqrDistance = b0 * s + c;
}
}
}
else // region 1
{
numer = a11 + b1 - a01 - b0;
if ( numer <= (double)0 )
{
s = (double)0;
t = (double)1;
sqrDistance = a11 + ((double)2) * b1 + c;
}
else
{
denom = a00 - ((double)2) * a01 + a11;
if ( numer >= denom )
{
s = (double)1;
t = (double)0;
sqrDistance = a00 + ((double)2) * b0 + c;
}
else
{
s = numer / denom;
t = (double)1 - s;
sqrDistance = s * (a00 * s + a01 * t + ((double)2) * b0) +
t * (a01 * s + a11 * t + ((double)2) * b1) + c;
}
}
}
}
// Account for numerical round-off error.
if ( sqrDistance < (double)0 )
sqrDistance = (double)0;
mClosestPoint1.x = v0.x + (float)(s * edge0.x + t * edge1.x);
mClosestPoint1.y = v0.y + (float)(s * edge0.y + t * edge1.y);
mClosestPoint1.z = v0.z + (float)(s * edge0.z + t * edge1.z);
mTriangleBary[1] = (float)s;
mTriangleBary[2] = (float)t;
mTriangleBary[0] = (float)((double)1 - s - t);
return (float)sqrDistance;
}
static Vector3 mTriangleBary = Vector3.zero;
static Vector3 mClosestPoint1 = Vector3.zero;
}
| |
namespace Ocelot.AcceptanceTests
{
using System;
using System.Collections.Generic;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Ocelot.Configuration.File;
using Shouldly;
using TestStack.BDDfy;
using Xunit;
public class WebSocketTests : IDisposable
{
private readonly List<string> _secondRecieved;
private readonly List<string> _firstRecieved;
private readonly Steps _steps;
private readonly ServiceHandler _serviceHandler;
public WebSocketTests()
{
_serviceHandler = new ServiceHandler();
_steps = new Steps();
_firstRecieved = new List<string>();
_secondRecieved = new List<string>();
}
[Fact]
public void should_proxy_websocket_input_to_downstream_service()
{
var downstreamPort = 5001;
var downstreamHost = "localhost";
var config = new FileConfiguration
{
ReRoutes = new List<FileReRoute>
{
new FileReRoute
{
UpstreamPathTemplate = "/",
DownstreamPathTemplate = "/ws",
DownstreamScheme = "ws",
DownstreamHostAndPorts = new List<FileHostAndPort>
{
new FileHostAndPort
{
Host = downstreamHost,
Port = downstreamPort
}
}
}
}
};
this.Given(_ => _steps.GivenThereIsAConfiguration(config))
.And(_ => _steps.StartFakeOcelotWithWebSockets())
.And(_ => StartFakeDownstreamService($"http://{downstreamHost}:{downstreamPort}", "/ws"))
.When(_ => StartClient("ws://localhost:5000/"))
.Then(_ => _firstRecieved.Count.ShouldBe(10))
.BDDfy();
}
[Fact]
public void should_proxy_websocket_input_to_downstream_service_and_use_load_balancer()
{
var downstreamPort = 5005;
var downstreamHost = "localhost";
var secondDownstreamPort = 5006;
var secondDownstreamHost = "localhost";
var config = new FileConfiguration
{
ReRoutes = new List<FileReRoute>
{
new FileReRoute
{
UpstreamPathTemplate = "/",
DownstreamPathTemplate = "/ws",
DownstreamScheme = "ws",
DownstreamHostAndPorts = new List<FileHostAndPort>
{
new FileHostAndPort
{
Host = downstreamHost,
Port = downstreamPort
},
new FileHostAndPort
{
Host = secondDownstreamHost,
Port = secondDownstreamPort
}
},
LoadBalancerOptions = new FileLoadBalancerOptions { Type = "RoundRobin" }
}
}
};
this.Given(_ => _steps.GivenThereIsAConfiguration(config))
.And(_ => _steps.StartFakeOcelotWithWebSockets())
.And(_ => StartFakeDownstreamService($"http://{downstreamHost}:{downstreamPort}", "/ws"))
.And(_ => StartSecondFakeDownstreamService($"http://{secondDownstreamHost}:{secondDownstreamPort}","/ws"))
.When(_ => WhenIStartTheClients())
.Then(_ => ThenBothDownstreamServicesAreCalled())
.BDDfy();
}
private void ThenBothDownstreamServicesAreCalled()
{
_firstRecieved.Count.ShouldBe(10);
_firstRecieved.ForEach(x =>
{
x.ShouldBe("test");
});
_secondRecieved.Count.ShouldBe(10);
_secondRecieved.ForEach(x =>
{
x.ShouldBe("chocolate");
});
}
private async Task WhenIStartTheClients()
{
var firstClient = StartClient("ws://localhost:5000/");
var secondClient = StartSecondClient("ws://localhost:5000/");
await Task.WhenAll(firstClient, secondClient);
}
private async Task StartClient(string url)
{
var client = new ClientWebSocket();
await client.ConnectAsync(new Uri(url), CancellationToken.None);
var sending = Task.Run(async () =>
{
string line = "test";
for (int i = 0; i < 10; i++)
{
var bytes = Encoding.UTF8.GetBytes(line);
await client.SendAsync(new ArraySegment<byte>(bytes), WebSocketMessageType.Text, true,
CancellationToken.None);
await Task.Delay(10);
}
await client.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
});
var receiving = Task.Run(async () =>
{
var buffer = new byte[1024 * 4];
while (true)
{
var result = await client.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
if (result.MessageType == WebSocketMessageType.Text)
{
_firstRecieved.Add(Encoding.UTF8.GetString(buffer, 0, result.Count));
}
else if (result.MessageType == WebSocketMessageType.Close)
{
await client.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
break;
}
}
});
await Task.WhenAll(sending, receiving);
}
private async Task StartSecondClient(string url)
{
await Task.Delay(500);
var client = new ClientWebSocket();
await client.ConnectAsync(new Uri(url), CancellationToken.None);
var sending = Task.Run(async () =>
{
string line = "test";
for (int i = 0; i < 10; i++)
{
var bytes = Encoding.UTF8.GetBytes(line);
await client.SendAsync(new ArraySegment<byte>(bytes), WebSocketMessageType.Text, true,
CancellationToken.None);
await Task.Delay(10);
}
await client.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
});
var receiving = Task.Run(async () =>
{
var buffer = new byte[1024 * 4];
while (true)
{
var result = await client.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
if (result.MessageType == WebSocketMessageType.Text)
{
_secondRecieved.Add(Encoding.UTF8.GetString(buffer, 0, result.Count));
}
else if (result.MessageType == WebSocketMessageType.Close)
{
await client.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
break;
}
}
});
await Task.WhenAll(sending, receiving);
}
private async Task StartFakeDownstreamService(string url, string path)
{
await _serviceHandler.StartFakeDownstreamService(url, path, async(context, next) =>
{
if (context.Request.Path == path)
{
if (context.WebSockets.IsWebSocketRequest)
{
var webSocket = await context.WebSockets.AcceptWebSocketAsync();
await Echo(webSocket);
}
else
{
context.Response.StatusCode = 400;
}
}
else
{
await next();
}
});
}
private async Task StartSecondFakeDownstreamService(string url, string path)
{
await _serviceHandler.StartFakeDownstreamService(url, path, async (context, next) =>
{
if (context.Request.Path == path)
{
if (context.WebSockets.IsWebSocketRequest)
{
WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();
await Message(webSocket);
}
else
{
context.Response.StatusCode = 400;
}
}
else
{
await next();
}
});
}
private async Task Echo(WebSocket webSocket)
{
try
{
var buffer = new byte[1024 * 4];
var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
while (!result.CloseStatus.HasValue)
{
await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None);
result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
}
await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
private async Task Message(WebSocket webSocket)
{
try
{
var buffer = new byte[1024 * 4];
var bytes = Encoding.UTF8.GetBytes("chocolate");
var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
while (!result.CloseStatus.HasValue)
{
await webSocket.SendAsync(new ArraySegment<byte>(bytes), result.MessageType, result.EndOfMessage, CancellationToken.None);
result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
}
await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
public void Dispose()
{
_serviceHandler?.Dispose();
_steps.Dispose();
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Data.dll
// Description: The data access libraries for the DotSpatial project.
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
// Based on W3C png specification: http://www.w3.org/TR/2003/REC-PNG-20031110/#11PLTE
// The Initial Developer of this Original Code is Ted Dunsford. Created 2/18/2010 1:21:47 PM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices;
namespace DotSpatial.Data
{
/// <summary>
/// mw.png provides read-write support for a png format that also can provide overviews etc.
/// This cannot work with any possible png file, but rather provides at least one common
/// format that can be used natively for large files that is better at compression than
/// just storing the values directly.
/// http://www.w3.org/TR/2003/REC-PNG-20031110/#11PLTE
/// </summary>
public class MwPng
{
#region Private Variables
#endregion
#region Methods
/// <summary>
/// For testing, see if we can write a png ourself that can be opened by .Net png.
/// </summary>
/// <param name="image">The image to write to png format</param>
/// <param name="fileName">The string fileName</param>
public void Write(Bitmap image, string fileName)
{
if (File.Exists(fileName)) File.Delete(fileName);
Stream f = new FileStream(fileName, FileMode.CreateNew, FileAccess.Write, FileShare.None, 1000000);
WriteSignature(f);
PngHeader header = new PngHeader(image.Width, image.Height);
header.Write(f);
WriteSrgb(f);
byte[] refImage = GetBytesFromImage(image);
byte[] filtered = Filter(refImage, 0, refImage.Length, image.Width * 4);
byte[] compressed = Deflate.Compress(filtered);
WriteIDat(f, compressed);
WriteEnd(f);
f.Flush();
f.Close();
}
/// <summary>
/// Reads a fileName into the specified bitmap.
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
/// <exception cref="PngInvalidSignatureException">If the file signature doesn't match the png file signature</exception>
public Bitmap Read(string fileName)
{
Stream f = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, 1000000);
byte[] signature = new byte[8];
f.Read(signature, 0, 8);
if (!SignatureIsValid(signature))
{
throw new PngInvalidSignatureException();
}
f.Close();
return new Bitmap(10, 10);
}
///<summary>
///</summary>
///<param name="signature"></param>
///<returns></returns>
public static bool SignatureIsValid(byte[] signature)
{
byte[] test = new byte[] { 137, 80, 78, 71, 13, 10, 26, 10 };
for (int i = 0; i < 8; i++)
{
if (signature[i] != test[i]) return false;
}
return true;
}
private static void WriteIDat(Stream f, byte[] data)
{
f.Write(ToBytesAsUInt32((uint)data.Length), 0, 4);
byte[] tag = new byte[] { 73, 68, 65, 84 };
f.Write(tag, 0, 4); // IDAT
f.Write(data, 0, data.Length);
byte[] combined = new byte[data.Length + 4];
Array.Copy(tag, 0, combined, 0, 4);
Array.Copy(data, 0, combined, 4, data.Length);
f.Write(ToBytesAsUInt32(Crc32.ComputeChecksum(combined)), 0, 4);
//// The IDAT chunks can be no more than 32768, but can in fact be smaller than this.
//int numBlocks = (int) Math.Ceiling(data.Length/(double) 32768);
//for (int block = 0; block < numBlocks; block++)
//{
// int bs = 32768;
// if (block == numBlocks - 1) bs = data.Length - block*32768;
// f.Write(ToBytes((uint)bs), 0, 4); // length
// f.Write(new byte[]{73, 68, 65, 84}, 0, 4); // IDAT
// f.Write(data, block * 32768, bs); // Data Content
// f.Write(ToBytes(Crc32.ComputeChecksum(data)), 0, 4); // CRC
//}
}
/// <summary>
/// Writes an in Big-endian Uint format.
/// </summary>
/// <param name="value"></param>
public static byte[] ToBytesAsUInt32(long value)
{
uint temp = Convert.ToUInt32(value);
byte[] arr = BitConverter.GetBytes(temp);
if (BitConverter.IsLittleEndian) Array.Reverse(arr);
return arr;
}
private static byte[] GetBytesFromImage(Bitmap image)
{
BitmapData bd = image.LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadOnly,
PixelFormat.Format32bppPArgb);
int len = image.Width * image.Height * 4;
byte[] refImage = new byte[len];
Marshal.Copy(bd.Scan0, refImage, 0, len);
image.UnlockBits(bd);
return refImage;
}
private static void WriteSignature(Stream f)
{
f.Write(new byte[] { 137, 80, 78, 71, 13, 10, 26, 10 }, 0, 8);
}
private static void WriteSrgb(Stream f)
{
f.Write(ToBytesAsUInt32(1), 0, 4);
byte[] vals = new byte[] { 115, 82, 71, 66, 0 }; //sRGB and the value of 0
f.Write(vals, 0, 5);
f.Write(ToBytesAsUInt32(Crc32.ComputeChecksum(vals)), 0, 4);
}
private static void WriteEnd(Stream f)
{
f.Write(BitConverter.GetBytes(0), 0, 4);
byte[] vals = new byte[] { 73, 69, 78, 68 }; // IEND
f.Write(vals, 0, 4);
f.Write(ToBytesAsUInt32(Crc32.ComputeChecksum(vals)), 0, 4);
}
/// <summary>
/// Many rows may be evaluated by this process, but the first value in the array should
/// be aligned with the left side of the image.
/// </summary>
/// <param name="refData">The original bytes to apply the PaethPredictor to.</param>
/// <param name="offset">The integer offset in the array where the filter should begin application. If this is 0, then
/// it assumes that there is no previous scan-line to work with.</param>
/// <param name="length">The number of bytes to filter, starting at the specified offset. This should be evenly divisible by the width.</param>
/// <param name="width">The integer width of a scan-line for grabbing the c and b bytes</param>
/// <returns>The entire length of bytes starting with the specified offset</returns>
public static byte[] Filter(byte[] refData, int offset, int length, int width)
{
// the 'B' and 'C' values of the first row are considered to be 0.
// the 'A' value of the first column is considered to be 0.
if (refData.Length - offset < length)
{
throw new PngInsuficientLengthException(length, refData.Length, offset);
}
int numrows = length / width;
// The output also consists of a byte before each line that specifies the Paeth prediction filter is being used
byte[] result = new byte[numrows + length];
int source = offset;
int dest = 0;
for (int row = 0; row < numrows; row++)
{
result[dest] = 4;
dest++;
for (int col = 0; col < width; col++)
{
byte a = (col == 0) ? (byte)0 : refData[source - 1];
byte b = (row == 0 || col == 0) ? (byte)0 : refData[source - width - 1];
byte c = (row == 0) ? (byte)0 : refData[source - width];
result[dest] = (byte)((refData[source] - PaethPredictor(a, b, c)) % 256);
source++;
dest++;
}
}
return result;
}
/// <summary>
/// Unfilters the data in order to reconstruct the original values.
/// </summary>
/// <param name="filterStream">The filtered but decompressed bytes</param>
/// <param name="offset">the integer offset where reconstruction should begin</param>
/// <param name="length">The integer length of bytes to deconstruct</param>
/// <param name="width">The integer width of a scan-line in bytes (not counting any filter type bytes.</param>
/// <returns></returns>
/// <exception cref="PngInsuficientLengthException"></exception>
public byte[] UnFilter(byte[] filterStream, int offset, int length, int width)
{ // the 'B' and 'C' values of the first row are considered to be 0.
// the 'A' value of the first column is considered to be 0.
if (filterStream.Length - offset < length)
{
throw new PngInsuficientLengthException(length, filterStream.Length, offset);
}
int numrows = length / width;
// The output also consists of a byte before each line that specifies the Paeth prediction filter is being used
byte[] result = new byte[length - numrows];
int source = offset;
int dest = 0;
for (int row = 0; row < numrows; row++)
{
if (filterStream[source] == 0)
{
source++;
// No filtering
Array.Copy(filterStream, source, result, dest, width);
source += width;
dest += width;
}
else if (filterStream[source] == 1)
{
source++;
for (int col = 0; col < width; col++)
{
byte a = (col == 0) ? (byte)0 : result[dest - 1];
result[dest] = (byte)((filterStream[dest] + a) % 256);
source++;
dest++;
}
}
else if (filterStream[source] == 2)
{
source++;
for (int col = 0; col < width; col++)
{
byte b = (row == 0 || col == 0) ? (byte)0 : result[dest - width - 1];
result[dest] = (byte)((filterStream[dest] + b) % 256);
source++;
dest++;
}
}
else if (filterStream[source] == 3)
{
source++;
for (int col = 0; col < width; col++)
{
byte a = (col == 0) ? (byte)0 : result[dest - 1];
byte b = (row == 0 || col == 0) ? (byte)0 : result[dest - width - 1];
result[dest] = (byte)((filterStream[dest] + (a + b) / 2) % 256); // integer division automatically does "floor"
source++;
dest++;
}
}
else if (filterStream[source] == 4)
{
source++;
for (int col = 0; col < width; col++)
{
byte a = (col == 0) ? (byte)0 : result[dest - 1];
byte b = (row == 0 || col == 0) ? (byte)0 : result[dest - width - 1];
byte c = (row == 0) ? (byte)0 : result[dest - width];
result[dest] = (byte)((filterStream[dest] + PaethPredictor(a, b, c)) % 256);
source++;
dest++;
}
}
}
return result;
}
/// <summary>
/// B C - For the current pixel X, use the best fit from B, C or A to predict X.
/// A X
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <param name="c"></param>
/// <returns></returns>
private static byte PaethPredictor(byte a, byte b, byte c)
{
byte pR;
int p = a + b - c;
int pa = Math.Abs(p - a);
int pb = Math.Abs(p - b);
int pc = Math.Abs(p - c);
if (pa <= pb && pa <= pc) pR = a;
else if (pb <= pc) pR = b;
else pR = c;
return pR;
}
#endregion
#region Properties
#endregion
}
}
| |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
namespace MindTouch.Text.CharDet.Statistics {
internal class StatisticsGB2312 : AStatistics {
//--- Constructors ---
public StatisticsGB2312() {
FirstByteFreq = new[] {
0.011628f, // FreqH[a1]
0.000000f, // FreqH[a2]
0.000000f, // FreqH[a3]
0.000000f, // FreqH[a4]
0.000000f, // FreqH[a5]
0.000000f, // FreqH[a6]
0.000000f, // FreqH[a7]
0.000000f, // FreqH[a8]
0.000000f, // FreqH[a9]
0.000000f, // FreqH[aa]
0.000000f, // FreqH[ab]
0.000000f, // FreqH[ac]
0.000000f, // FreqH[ad]
0.000000f, // FreqH[ae]
0.000000f, // FreqH[af]
0.011628f, // FreqH[b0]
0.012403f, // FreqH[b1]
0.009302f, // FreqH[b2]
0.003876f, // FreqH[b3]
0.017829f, // FreqH[b4]
0.037209f, // FreqH[b5]
0.008527f, // FreqH[b6]
0.010078f, // FreqH[b7]
0.019380f, // FreqH[b8]
0.054264f, // FreqH[b9]
0.010078f, // FreqH[ba]
0.041085f, // FreqH[bb]
0.020930f, // FreqH[bc]
0.018605f, // FreqH[bd]
0.010078f, // FreqH[be]
0.013178f, // FreqH[bf]
0.016279f, // FreqH[c0]
0.006202f, // FreqH[c1]
0.009302f, // FreqH[c2]
0.017054f, // FreqH[c3]
0.011628f, // FreqH[c4]
0.008527f, // FreqH[c5]
0.004651f, // FreqH[c6]
0.006202f, // FreqH[c7]
0.017829f, // FreqH[c8]
0.024806f, // FreqH[c9]
0.020155f, // FreqH[ca]
0.013953f, // FreqH[cb]
0.032558f, // FreqH[cc]
0.035659f, // FreqH[cd]
0.068217f, // FreqH[ce]
0.010853f, // FreqH[cf]
0.036434f, // FreqH[d0]
0.117054f, // FreqH[d1]
0.027907f, // FreqH[d2]
0.100775f, // FreqH[d3]
0.010078f, // FreqH[d4]
0.017829f, // FreqH[d5]
0.062016f, // FreqH[d6]
0.012403f, // FreqH[d7]
0.000000f, // FreqH[d8]
0.000000f, // FreqH[d9]
0.000000f, // FreqH[da]
0.000000f, // FreqH[db]
0.000000f, // FreqH[dc]
0.000000f, // FreqH[dd]
0.000000f, // FreqH[de]
0.000000f, // FreqH[df]
0.000000f, // FreqH[e0]
0.000000f, // FreqH[e1]
0.000000f, // FreqH[e2]
0.000000f, // FreqH[e3]
0.000000f, // FreqH[e4]
0.000000f, // FreqH[e5]
0.000000f, // FreqH[e6]
0.000000f, // FreqH[e7]
0.000000f, // FreqH[e8]
0.000000f, // FreqH[e9]
0.001550f, // FreqH[ea]
0.000000f, // FreqH[eb]
0.000000f, // FreqH[ec]
0.000000f, // FreqH[ed]
0.000000f, // FreqH[ee]
0.000000f, // FreqH[ef]
0.000000f, // FreqH[f0]
0.000000f, // FreqH[f1]
0.000000f, // FreqH[f2]
0.000000f, // FreqH[f3]
0.000000f, // FreqH[f4]
0.000000f, // FreqH[f5]
0.000000f, // FreqH[f6]
0.000000f, // FreqH[f7]
0.000000f, // FreqH[f8]
0.000000f, // FreqH[f9]
0.000000f, // FreqH[fa]
0.000000f, // FreqH[fb]
0.000000f, // FreqH[fc]
0.000000f, // FreqH[fd]
0.000000f // FreqH[fe]
};
FirstByteStdDev = 0.020081f; // Lead Byte StdDev
FirstByteMean = 0.010638f; // Lead Byte Mean
FirstByteWeight = 0.586533f; // Lead Byte Weight
SecondByteFreq = new[] {
0.006202f, // FreqL[a1]
0.031008f, // FreqL[a2]
0.005426f, // FreqL[a3]
0.003101f, // FreqL[a4]
0.001550f, // FreqL[a5]
0.003101f, // FreqL[a6]
0.082171f, // FreqL[a7]
0.014729f, // FreqL[a8]
0.006977f, // FreqL[a9]
0.001550f, // FreqL[aa]
0.013953f, // FreqL[ab]
0.000000f, // FreqL[ac]
0.013953f, // FreqL[ad]
0.010078f, // FreqL[ae]
0.008527f, // FreqL[af]
0.006977f, // FreqL[b0]
0.004651f, // FreqL[b1]
0.003101f, // FreqL[b2]
0.003101f, // FreqL[b3]
0.003101f, // FreqL[b4]
0.008527f, // FreqL[b5]
0.003101f, // FreqL[b6]
0.005426f, // FreqL[b7]
0.005426f, // FreqL[b8]
0.005426f, // FreqL[b9]
0.003101f, // FreqL[ba]
0.001550f, // FreqL[bb]
0.006202f, // FreqL[bc]
0.014729f, // FreqL[bd]
0.010853f, // FreqL[be]
0.000000f, // FreqL[bf]
0.011628f, // FreqL[c0]
0.000000f, // FreqL[c1]
0.031783f, // FreqL[c2]
0.013953f, // FreqL[c3]
0.030233f, // FreqL[c4]
0.039535f, // FreqL[c5]
0.008527f, // FreqL[c6]
0.015504f, // FreqL[c7]
0.000000f, // FreqL[c8]
0.003101f, // FreqL[c9]
0.008527f, // FreqL[ca]
0.016279f, // FreqL[cb]
0.005426f, // FreqL[cc]
0.001550f, // FreqL[cd]
0.013953f, // FreqL[ce]
0.013953f, // FreqL[cf]
0.044961f, // FreqL[d0]
0.003101f, // FreqL[d1]
0.004651f, // FreqL[d2]
0.006977f, // FreqL[d3]
0.001550f, // FreqL[d4]
0.005426f, // FreqL[d5]
0.012403f, // FreqL[d6]
0.001550f, // FreqL[d7]
0.015504f, // FreqL[d8]
0.000000f, // FreqL[d9]
0.006202f, // FreqL[da]
0.001550f, // FreqL[db]
0.000000f, // FreqL[dc]
0.007752f, // FreqL[dd]
0.006977f, // FreqL[de]
0.001550f, // FreqL[df]
0.009302f, // FreqL[e0]
0.011628f, // FreqL[e1]
0.004651f, // FreqL[e2]
0.010853f, // FreqL[e3]
0.012403f, // FreqL[e4]
0.017829f, // FreqL[e5]
0.005426f, // FreqL[e6]
0.024806f, // FreqL[e7]
0.000000f, // FreqL[e8]
0.006202f, // FreqL[e9]
0.000000f, // FreqL[ea]
0.082171f, // FreqL[eb]
0.015504f, // FreqL[ec]
0.004651f, // FreqL[ed]
0.000000f, // FreqL[ee]
0.006977f, // FreqL[ef]
0.004651f, // FreqL[f0]
0.000000f, // FreqL[f1]
0.008527f, // FreqL[f2]
0.012403f, // FreqL[f3]
0.004651f, // FreqL[f4]
0.003876f, // FreqL[f5]
0.003101f, // FreqL[f6]
0.022481f, // FreqL[f7]
0.024031f, // FreqL[f8]
0.001550f, // FreqL[f9]
0.047287f, // FreqL[fa]
0.009302f, // FreqL[fb]
0.001550f, // FreqL[fc]
0.005426f, // FreqL[fd]
0.017054f // FreqL[fe]
};
SecondByteStdDev = 0.014156f; // Trail Byte StdDev
SecondByteMean = 0.010638f; // Trail Byte Mean
SecondByteWeight = 0.413467f; // Trial Byte Weight
}
}
}
| |
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
// Author(s):
//
// Atif Aziz, http://www.raboof.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
[assembly: Elmah.Scc("$Id: ErrorDetailPage.cs 659 2009-07-23 18:21:39Z jamesdriscoll@btinternet.com $")]
namespace Elmah
{
#region Imports
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NameValueCollection = System.Collections.Specialized.NameValueCollection;
#endregion
/// <summary>
/// Renders an HTML page displaying details about an error from the
/// error log.
/// </summary>
internal sealed class ErrorDetailPage : ErrorPageBase
{
private ErrorLogEntry _errorEntry;
protected override void OnLoad(EventArgs e)
{
//
// Retrieve the ID of the error to display and read it from
// the store.
//
string errorId = Mask.NullString(this.Request.QueryString["id"]);
if (errorId.Length == 0)
return;
_errorEntry = this.ErrorLog.GetError(errorId);
//
// Perhaps the error has been deleted from the store? Whatever
// the reason, bail out silently.
//
if (_errorEntry == null)
{
Response.Status = HttpStatus.NotFound.ToString();
return;
}
//
// Setup the title of the page.
//
this.PageTitle = string.Format("Error: {0} [{1}]", _errorEntry.Error.Type, _errorEntry.Id);
base.OnLoad(e);
}
protected override void RenderContents(HtmlTextWriter writer)
{
if (writer == null)
throw new ArgumentNullException("writer");
if (_errorEntry != null)
RenderError(writer);
else
RenderNoError(writer);
}
private static void RenderNoError(HtmlTextWriter writer)
{
Debug.Assert(writer != null);
writer.RenderBeginTag(HtmlTextWriterTag.P);
writer.Write("Error not found in log.");
writer.RenderEndTag(); // </p>
writer.WriteLine();
}
private void RenderError(HtmlTextWriter writer)
{
Debug.Assert(writer != null);
Error error = _errorEntry.Error;
//
// Write out the page title containing error type and message.
//
writer.AddAttribute(HtmlTextWriterAttribute.Id, "PageTitle");
writer.RenderBeginTag(HtmlTextWriterTag.H1);
Server.HtmlEncode(error.Message, writer);
writer.RenderEndTag(); // </h1>
writer.WriteLine();
SpeedBar.Render(writer,
SpeedBar.Home.Format(BasePageName),
SpeedBar.Help,
SpeedBar.About.Format(BasePageName));
writer.AddAttribute(HtmlTextWriterAttribute.Id, "ErrorTitle");
writer.RenderBeginTag(HtmlTextWriterTag.P);
writer.AddAttribute(HtmlTextWriterAttribute.Id, "ErrorType");
writer.RenderBeginTag(HtmlTextWriterTag.Span);
Server.HtmlEncode(error.Type, writer);
writer.RenderEndTag(); // </span>
writer.AddAttribute(HtmlTextWriterAttribute.Id, "ErrorTypeMessageSeparator");
writer.RenderBeginTag(HtmlTextWriterTag.Span);
writer.Write(": ");
writer.RenderEndTag(); // </span>
writer.AddAttribute(HtmlTextWriterAttribute.Id, "ErrorMessage");
writer.RenderBeginTag(HtmlTextWriterTag.Span);
Server.HtmlEncode(error.Message, writer);
writer.RenderEndTag(); // </span>
writer.RenderEndTag(); // </p>
writer.WriteLine();
//
// Do we have details, like the stack trace? If so, then write
// them out in a pre-formatted (pre) element.
// NOTE: There is an assumption here that detail will always
// contain a stack trace. If it doesn't then pre-formatting
// might not be the right thing to do here.
//
if (error.Detail.Length != 0)
{
writer.AddAttribute(HtmlTextWriterAttribute.Id, "ErrorDetail");
writer.RenderBeginTag(HtmlTextWriterTag.Pre);
writer.Flush();
Server.HtmlEncode(error.Detail, writer.InnerWriter);
writer.RenderEndTag(); // </pre>
writer.WriteLine();
}
//
// Write out the error log time. This will be in the local
// time zone of the server. Would be a good idea to indicate
// it here for the user.
//
writer.AddAttribute(HtmlTextWriterAttribute.Id, "ErrorLogTime");
writer.RenderBeginTag(HtmlTextWriterTag.P);
Server.HtmlEncode(string.Format("Logged on {0} at {1}",
error.Time.ToLongDateString(),
error.Time.ToLongTimeString()), writer);
writer.RenderEndTag(); // </p>
writer.WriteLine();
//
// Render alternate links.
//
writer.RenderBeginTag(HtmlTextWriterTag.P);
writer.Write("See also:");
writer.RenderEndTag(); // </p>
writer.WriteLine();
writer.RenderBeginTag(HtmlTextWriterTag.Ul);
//
// Do we have an HTML formatted message from ASP.NET? If yes
// then write out a link to it instead of embedding it
// with the rest of the content since it is an entire HTML
// document in itself.
//
if (error.WebHostHtmlMessage.Length != 0)
{
writer.RenderBeginTag(HtmlTextWriterTag.Li);
string htmlUrl = this.BasePageName + "/html?id=" + HttpUtility.UrlEncode(_errorEntry.Id);
writer.AddAttribute(HtmlTextWriterAttribute.Href, htmlUrl);
writer.RenderBeginTag(HtmlTextWriterTag.A);
writer.Write("Original ASP.NET error page");
writer.RenderEndTag(); // </a>
writer.RenderEndTag(); // </li>
}
//
// Add a link to the source XML and JSON data.
//
writer.RenderBeginTag(HtmlTextWriterTag.Li);
writer.Write("Raw/Source data in ");
writer.AddAttribute(HtmlTextWriterAttribute.Href, "xml" + Request.Url.Query);
#if NET_1_0 || NET_1_1
writer.AddAttribute("rel", HtmlLinkType.Alternate);
#else
writer.AddAttribute(HtmlTextWriterAttribute.Rel, HtmlLinkType.Alternate);
#endif
writer.AddAttribute(HtmlTextWriterAttribute.Type, "application/xml");
writer.RenderBeginTag(HtmlTextWriterTag.A);
writer.Write("XML");
writer.RenderEndTag(); // </a>
writer.Write(" or in ");
writer.AddAttribute(HtmlTextWriterAttribute.Href, "json" + Request.Url.Query);
#if NET_1_0 || NET_1_1
writer.AddAttribute("rel", HtmlLinkType.Alternate);
#else
writer.AddAttribute(HtmlTextWriterAttribute.Rel, HtmlLinkType.Alternate);
#endif
writer.AddAttribute(HtmlTextWriterAttribute.Type, "application/json");
writer.RenderBeginTag(HtmlTextWriterTag.A);
writer.Write("JSON");
writer.RenderEndTag(); // </a>
writer.RenderEndTag(); // </li>
//
// End of alternate links.
//
writer.RenderEndTag(); // </ul>
//
// If this error has context, then write it out.
// ServerVariables are good enough for most purposes, so
// we only write those out at this time.
//
RenderCollection(writer, error.ServerVariables,
"ServerVariables", "Server Variables");
base.RenderContents(writer);
}
private void RenderCollection(HtmlTextWriter writer,
NameValueCollection collection, string id, string title)
{
Debug.Assert(writer != null);
Debug.AssertStringNotEmpty(id);
Debug.AssertStringNotEmpty(title);
//
// If the collection isn't there or it's empty, then bail out.
//
if (collection == null || collection.Count == 0)
return;
//
// Surround the entire section with a <div> element.
//
writer.AddAttribute(HtmlTextWriterAttribute.Id, id);
writer.RenderBeginTag(HtmlTextWriterTag.Div);
//
// Write out the table caption.
//
writer.AddAttribute(HtmlTextWriterAttribute.Class, "table-caption");
writer.RenderBeginTag(HtmlTextWriterTag.P);
this.Server.HtmlEncode(title, writer);
writer.RenderEndTag(); // </p>
writer.WriteLine();
//
// Some values can be large and add scroll bars to the page
// as well as ruin some formatting. So we encapsulate the
// table into a scrollable view that is controlled via the
// style sheet.
//
writer.AddAttribute(HtmlTextWriterAttribute.Class, "scroll-view");
writer.RenderBeginTag(HtmlTextWriterTag.Div);
//
// Create a table to display the name/value pairs of the
// collection in 2 columns.
//
Table table = new Table();
table.CellSpacing = 0;
//
// Create the header row and columns.
//
TableRow headRow = new TableRow();
TableHeaderCell headCell;
headCell = new TableHeaderCell();
headCell.Wrap = false;
headCell.Text = "Name";
headCell.CssClass = "name-col";
headRow.Cells.Add(headCell);
headCell = new TableHeaderCell();
headCell.Wrap = false;
headCell.Text = "Value";
headCell.CssClass = "value-col";
headRow.Cells.Add(headCell);
table.Rows.Add(headRow);
//
// Create a row for each entry in the collection.
//
string[] keys = collection.AllKeys;
InvariantStringArray.Sort(keys);
for (int keyIndex = 0; keyIndex < keys.Length; keyIndex++)
{
string key = keys[keyIndex];
TableRow bodyRow = new TableRow();
bodyRow.CssClass = keyIndex % 2 == 0 ? "even-row" : "odd-row";
TableCell cell;
//
// Create the key column.
//
cell = new TableCell();
cell.Text = Server.HtmlEncode(key);
cell.CssClass = "key-col";
bodyRow.Cells.Add(cell);
//
// Create the value column.
//
cell = new TableCell();
cell.Text = Server.HtmlEncode(collection[key]);
cell.CssClass = "value-col";
bodyRow.Cells.Add(cell);
table.Rows.Add(bodyRow);
}
//
// Write out the table and close container tags.
//
table.RenderControl(writer);
writer.RenderEndTag(); // </div>
writer.WriteLine();
writer.RenderEndTag(); // </div>
writer.WriteLine();
}
}
}
| |
// DeflaterHuffman.cs
//
// Copyright (C) 2001 Mike Krueger
// Copyright (C) 2004 John Reilly
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 2001 Free Software Foundation, Inc.
//
// 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.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
// *************************************************************************
//
// Name: DeflaterHuffman.cs
//
// Created: 19-02-2008 SharedCache.com, rschuetz
// Modified: 19-02-2008 SharedCache.com, rschuetz : Creation
// *************************************************************************
using System;
namespace MergeSystem.Indexus.WinServiceCommon.SharpZipLib.Zip.Compression
{
/// <summary>
/// This is the DeflaterHuffman class.
///
/// This class is <i>not</i> thread safe. This is inherent in the API, due
/// to the split of Deflate and SetInput.
///
/// author of the original java version : Jochen Hoenicke
/// </summary>
public class DeflaterHuffman
{
const int BUFSIZE = 1 << (DeflaterConstants.DEFAULT_MEM_LEVEL + 6);
const int LITERAL_NUM = 286;
// Number of distance codes
const int DIST_NUM = 30;
// Number of codes used to transfer bit lengths
const int BITLEN_NUM = 19;
// repeat previous bit length 3-6 times (2 bits of repeat count)
const int REP_3_6 = 16;
// repeat a zero length 3-10 times (3 bits of repeat count)
const int REP_3_10 = 17;
// repeat a zero length 11-138 times (7 bits of repeat count)
const int REP_11_138 = 18;
const int EOF_SYMBOL = 256;
// The lengths of the bit length codes are sent in order of decreasing
// probability, to avoid transmitting the lengths for unused bit length codes.
static readonly int[] BL_ORDER = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 };
static readonly byte[] bit4Reverse = {
0,
8,
4,
12,
2,
10,
6,
14,
1,
9,
5,
13,
3,
11,
7,
15
};
static short[] staticLCodes;
static byte[] staticLLength;
static short[] staticDCodes;
static byte[] staticDLength;
class Tree
{
#region Instance Fields
public short[] freqs;
public byte[] length;
public int minNumCodes;
public int numCodes;
short[] codes;
int[] bl_counts;
int maxLength;
DeflaterHuffman dh;
#endregion
#region Constructors
public Tree(DeflaterHuffman dh, int elems, int minCodes, int maxLength)
{
this.dh = dh;
this.minNumCodes = minCodes;
this.maxLength = maxLength;
freqs = new short[elems];
bl_counts = new int[maxLength];
}
#endregion
/// <summary>
/// Resets the internal state of the tree
/// </summary>
public void Reset()
{
for (int i = 0; i < freqs.Length; i++)
{
freqs[i] = 0;
}
codes = null;
length = null;
}
public void WriteSymbol(int code)
{
// if (DeflaterConstants.DEBUGGING) {
// freqs[code]--;
// // Console.Write("writeSymbol("+freqs.length+","+code+"): ");
// }
dh.pending.WriteBits(codes[code] & 0xffff, length[code]);
}
/// <summary>
/// Check that all frequencies are zero
/// </summary>
/// <exception cref="SharpZipBaseException">
/// At least one frequency is non-zero
/// </exception>
public void CheckEmpty()
{
bool empty = true;
for (int i = 0; i < freqs.Length; i++)
{
if (freqs[i] != 0)
{
//Console.WriteLine("freqs[" + i + "] == " + freqs[i]);
empty = false;
}
}
if (!empty)
{
throw new SharpZipBaseException("!Empty");
}
}
/// <summary>
/// Set static codes and length
/// </summary>
/// <param name="staticCodes">new codes</param>
/// <param name="staticLengths">length for new codes</param>
public void SetStaticCodes(short[] staticCodes, byte[] staticLengths)
{
codes = staticCodes;
length = staticLengths;
}
/// <summary>
/// Build dynamic codes and lengths
/// </summary>
public void BuildCodes()
{
int numSymbols = freqs.Length;
int[] nextCode = new int[maxLength];
int code = 0;
codes = new short[freqs.Length];
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("buildCodes: "+freqs.Length);
// }
for (int bits = 0; bits < maxLength; bits++)
{
nextCode[bits] = code;
code += bl_counts[bits] << (15 - bits);
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("bits: " + ( bits + 1) + " count: " + bl_counts[bits]
// +" nextCode: "+code);
// }
}
#if DebugDeflation
if ( DeflaterConstants.DEBUGGING && (code != 65536) )
{
throw new SharpZipBaseException("Inconsistent bl_counts!");
}
#endif
for (int i = 0; i < numCodes; i++)
{
int bits = length[i];
if (bits > 0)
{
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("codes["+i+"] = rev(" + nextCode[bits-1]+"),
// +bits);
// }
codes[i] = BitReverse(nextCode[bits - 1]);
nextCode[bits - 1] += 1 << (16 - bits);
}
}
}
public void BuildTree()
{
int numSymbols = freqs.Length;
/* heap is a priority queue, sorted by frequency, least frequent
* nodes first. The heap is a binary tree, with the property, that
* the parent node is smaller than both child nodes. This assures
* that the smallest node is the first parent.
*
* The binary tree is encoded in an array: 0 is root node and
* the nodes 2*n+1, 2*n+2 are the child nodes of node n.
*/
int[] heap = new int[numSymbols];
int heapLen = 0;
int maxCode = 0;
for (int n = 0; n < numSymbols; n++)
{
int freq = freqs[n];
if (freq != 0)
{
// Insert n into heap
int pos = heapLen++;
int ppos;
while (pos > 0 && freqs[heap[ppos = (pos - 1) / 2]] > freq)
{
heap[pos] = heap[ppos];
pos = ppos;
}
heap[pos] = n;
maxCode = n;
}
}
/* We could encode a single literal with 0 bits but then we
* don't see the literals. Therefore we force at least two
* literals to avoid this case. We don't care about order in
* this case, both literals get a 1 bit code.
*/
while (heapLen < 2)
{
int node = maxCode < 2 ? ++maxCode : 0;
heap[heapLen++] = node;
}
numCodes = Math.Max(maxCode + 1, minNumCodes);
int numLeafs = heapLen;
int[] childs = new int[4 * heapLen - 2];
int[] values = new int[2 * heapLen - 1];
int numNodes = numLeafs;
for (int i = 0; i < heapLen; i++)
{
int node = heap[i];
childs[2 * i] = node;
childs[2 * i + 1] = -1;
values[i] = freqs[node] << 8;
heap[i] = i;
}
/* Construct the Huffman tree by repeatedly combining the least two
* frequent nodes.
*/
do
{
int first = heap[0];
int last = heap[--heapLen];
// Propagate the hole to the leafs of the heap
int ppos = 0;
int path = 1;
while (path < heapLen)
{
if (path + 1 < heapLen && values[heap[path]] > values[heap[path + 1]])
{
path++;
}
heap[ppos] = heap[path];
ppos = path;
path = path * 2 + 1;
}
/* Now propagate the last element down along path. Normally
* it shouldn't go too deep.
*/
int lastVal = values[last];
while ((path = ppos) > 0 && values[heap[ppos = (path - 1) / 2]] > lastVal)
{
heap[path] = heap[ppos];
}
heap[path] = last;
int second = heap[0];
// Create a new node father of first and second
last = numNodes++;
childs[2 * last] = first;
childs[2 * last + 1] = second;
int mindepth = Math.Min(values[first] & 0xff, values[second] & 0xff);
values[last] = lastVal = values[first] + values[second] - mindepth + 1;
// Again, propagate the hole to the leafs
ppos = 0;
path = 1;
while (path < heapLen)
{
if (path + 1 < heapLen && values[heap[path]] > values[heap[path + 1]])
{
path++;
}
heap[ppos] = heap[path];
ppos = path;
path = ppos * 2 + 1;
}
// Now propagate the new element down along path
while ((path = ppos) > 0 && values[heap[ppos = (path - 1) / 2]] > lastVal)
{
heap[path] = heap[ppos];
}
heap[path] = last;
} while (heapLen > 1);
if (heap[0] != childs.Length / 2 - 1)
{
throw new SharpZipBaseException("Heap invariant violated");
}
BuildLength(childs);
}
/// <summary>
/// Get encoded length
/// </summary>
/// <returns>Encoded length, the sum of frequencies * lengths</returns>
public int GetEncodedLength()
{
int len = 0;
for (int i = 0; i < freqs.Length; i++)
{
len += freqs[i] * length[i];
}
return len;
}
/// <summary>
/// Scan a literal or distance tree to determine the frequencies of the codes
/// in the bit length tree.
/// </summary>
public void CalcBLFreq(Tree blTree)
{
int max_count; /* max repeat count */
int min_count; /* min repeat count */
int count; /* repeat count of the current code */
int curlen = -1; /* length of current code */
int i = 0;
while (i < numCodes)
{
count = 1;
int nextlen = length[i];
if (nextlen == 0)
{
max_count = 138;
min_count = 3;
}
else
{
max_count = 6;
min_count = 3;
if (curlen != nextlen)
{
blTree.freqs[nextlen]++;
count = 0;
}
}
curlen = nextlen;
i++;
while (i < numCodes && curlen == length[i])
{
i++;
if (++count >= max_count)
{
break;
}
}
if (count < min_count)
{
blTree.freqs[curlen] += (short)count;
}
else if (curlen != 0)
{
blTree.freqs[REP_3_6]++;
}
else if (count <= 10)
{
blTree.freqs[REP_3_10]++;
}
else
{
blTree.freqs[REP_11_138]++;
}
}
}
/// <summary>
/// Write tree values
/// </summary>
/// <param name="blTree">Tree to write</param>
public void WriteTree(Tree blTree)
{
int max_count; // max repeat count
int min_count; // min repeat count
int count; // repeat count of the current code
int curlen = -1; // length of current code
int i = 0;
while (i < numCodes)
{
count = 1;
int nextlen = length[i];
if (nextlen == 0)
{
max_count = 138;
min_count = 3;
}
else
{
max_count = 6;
min_count = 3;
if (curlen != nextlen)
{
blTree.WriteSymbol(nextlen);
count = 0;
}
}
curlen = nextlen;
i++;
while (i < numCodes && curlen == length[i])
{
i++;
if (++count >= max_count)
{
break;
}
}
if (count < min_count)
{
while (count-- > 0)
{
blTree.WriteSymbol(curlen);
}
}
else if (curlen != 0)
{
blTree.WriteSymbol(REP_3_6);
dh.pending.WriteBits(count - 3, 2);
}
else if (count <= 10)
{
blTree.WriteSymbol(REP_3_10);
dh.pending.WriteBits(count - 3, 3);
}
else
{
blTree.WriteSymbol(REP_11_138);
dh.pending.WriteBits(count - 11, 7);
}
}
}
void BuildLength(int[] childs)
{
this.length = new byte[freqs.Length];
int numNodes = childs.Length / 2;
int numLeafs = (numNodes + 1) / 2;
int overflow = 0;
for (int i = 0; i < maxLength; i++)
{
bl_counts[i] = 0;
}
// First calculate optimal bit lengths
int[] lengths = new int[numNodes];
lengths[numNodes - 1] = 0;
for (int i = numNodes - 1; i >= 0; i--)
{
if (childs[2 * i + 1] != -1)
{
int bitLength = lengths[i] + 1;
if (bitLength > maxLength)
{
bitLength = maxLength;
overflow++;
}
lengths[childs[2 * i]] = lengths[childs[2 * i + 1]] = bitLength;
}
else
{
// A leaf node
int bitLength = lengths[i];
bl_counts[bitLength - 1]++;
this.length[childs[2 * i]] = (byte)lengths[i];
}
}
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("Tree "+freqs.Length+" lengths:");
// for (int i=0; i < numLeafs; i++) {
// //Console.WriteLine("Node "+childs[2*i]+" freq: "+freqs[childs[2*i]]
// + " len: "+length[childs[2*i]]);
// }
// }
if (overflow == 0)
{
return;
}
int incrBitLen = maxLength - 1;
do
{
// Find the first bit length which could increase:
while (bl_counts[--incrBitLen] == 0)
;
// Move this node one down and remove a corresponding
// number of overflow nodes.
do
{
bl_counts[incrBitLen]--;
bl_counts[++incrBitLen]++;
overflow -= 1 << (maxLength - 1 - incrBitLen);
} while (overflow > 0 && incrBitLen < maxLength - 1);
} while (overflow > 0);
/* We may have overshot above. Move some nodes from maxLength to
* maxLength-1 in that case.
*/
bl_counts[maxLength - 1] += overflow;
bl_counts[maxLength - 2] -= overflow;
/* Now recompute all bit lengths, scanning in increasing
* frequency. It is simpler to reconstruct all lengths instead of
* fixing only the wrong ones. This idea is taken from 'ar'
* written by Haruhiko Okumura.
*
* The nodes were inserted with decreasing frequency into the childs
* array.
*/
int nodePtr = 2 * numLeafs;
for (int bits = maxLength; bits != 0; bits--)
{
int n = bl_counts[bits - 1];
while (n > 0)
{
int childPtr = 2 * childs[nodePtr++];
if (childs[childPtr + 1] == -1)
{
// We found another leaf
length[childs[childPtr]] = (byte)bits;
n--;
}
}
}
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("*** After overflow elimination. ***");
// for (int i=0; i < numLeafs; i++) {
// //Console.WriteLine("Node "+childs[2*i]+" freq: "+freqs[childs[2*i]]
// + " len: "+length[childs[2*i]]);
// }
// }
}
}
#region Instance Fields
/// <summary>
/// Pending buffer to use
/// </summary>
public DeflaterPending pending;
Tree literalTree;
Tree distTree;
Tree blTree;
// Buffer for distances
short[] d_buf;
byte[] l_buf;
int last_lit;
int extra_bits;
#endregion
static DeflaterHuffman()
{
// See RFC 1951 3.2.6
// Literal codes
staticLCodes = new short[LITERAL_NUM];
staticLLength = new byte[LITERAL_NUM];
int i = 0;
while (i < 144)
{
staticLCodes[i] = BitReverse((0x030 + i) << 8);
staticLLength[i++] = 8;
}
while (i < 256)
{
staticLCodes[i] = BitReverse((0x190 - 144 + i) << 7);
staticLLength[i++] = 9;
}
while (i < 280)
{
staticLCodes[i] = BitReverse((0x000 - 256 + i) << 9);
staticLLength[i++] = 7;
}
while (i < LITERAL_NUM)
{
staticLCodes[i] = BitReverse((0x0c0 - 280 + i) << 8);
staticLLength[i++] = 8;
}
// Distance codes
staticDCodes = new short[DIST_NUM];
staticDLength = new byte[DIST_NUM];
for (i = 0; i < DIST_NUM; i++)
{
staticDCodes[i] = BitReverse(i << 11);
staticDLength[i] = 5;
}
}
/// <summary>
/// Construct instance with pending buffer
/// </summary>
/// <param name="pending">Pending buffer to use</param>
public DeflaterHuffman(DeflaterPending pending)
{
this.pending = pending;
literalTree = new Tree(this, LITERAL_NUM, 257, 15);
distTree = new Tree(this, DIST_NUM, 1, 15);
blTree = new Tree(this, BITLEN_NUM, 4, 7);
d_buf = new short[BUFSIZE];
l_buf = new byte[BUFSIZE];
}
/// <summary>
/// Reset internal state
/// </summary>
public void Reset()
{
last_lit = 0;
extra_bits = 0;
literalTree.Reset();
distTree.Reset();
blTree.Reset();
}
/// <summary>
/// Write all trees to pending buffer
/// </summary>
/// <param name="blTreeCodes">The number/rank of treecodes to send.</param>
public void SendAllTrees(int blTreeCodes)
{
blTree.BuildCodes();
literalTree.BuildCodes();
distTree.BuildCodes();
pending.WriteBits(literalTree.numCodes - 257, 5);
pending.WriteBits(distTree.numCodes - 1, 5);
pending.WriteBits(blTreeCodes - 4, 4);
for (int rank = 0; rank < blTreeCodes; rank++)
{
pending.WriteBits(blTree.length[BL_ORDER[rank]], 3);
}
literalTree.WriteTree(blTree);
distTree.WriteTree(blTree);
#if DebugDeflation
if (DeflaterConstants.DEBUGGING) {
blTree.CheckEmpty();
}
#endif
}
/// <summary>
/// Compress current buffer writing data to pending buffer
/// </summary>
public void CompressBlock()
{
for (int i = 0; i < last_lit; i++)
{
int litlen = l_buf[i] & 0xff;
int dist = d_buf[i];
if (dist-- != 0)
{
// if (DeflaterConstants.DEBUGGING) {
// Console.Write("["+(dist+1)+","+(litlen+3)+"]: ");
// }
int lc = Lcode(litlen);
literalTree.WriteSymbol(lc);
int bits = (lc - 261) / 4;
if (bits > 0 && bits <= 5)
{
pending.WriteBits(litlen & ((1 << bits) - 1), bits);
}
int dc = Dcode(dist);
distTree.WriteSymbol(dc);
bits = dc / 2 - 1;
if (bits > 0)
{
pending.WriteBits(dist & ((1 << bits) - 1), bits);
}
}
else
{
// if (DeflaterConstants.DEBUGGING) {
// if (litlen > 32 && litlen < 127) {
// Console.Write("("+(char)litlen+"): ");
// } else {
// Console.Write("{"+litlen+"}: ");
// }
// }
literalTree.WriteSymbol(litlen);
}
}
#if DebugDeflation
if (DeflaterConstants.DEBUGGING) {
Console.Write("EOF: ");
}
#endif
literalTree.WriteSymbol(EOF_SYMBOL);
#if DebugDeflation
if (DeflaterConstants.DEBUGGING) {
literalTree.CheckEmpty();
distTree.CheckEmpty();
}
#endif
}
/// <summary>
/// Flush block to output with no compression
/// </summary>
/// <param name="stored">Data to write</param>
/// <param name="storedOffset">Index of first byte to write</param>
/// <param name="storedLength">Count of bytes to write</param>
/// <param name="lastBlock">True if this is the last block</param>
public void FlushStoredBlock(byte[] stored, int storedOffset, int storedLength, bool lastBlock)
{
#if DebugDeflation
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("Flushing stored block "+ storedLength);
// }
#endif
pending.WriteBits((DeflaterConstants.STORED_BLOCK << 1) + (lastBlock ? 1 : 0), 3);
pending.AlignToByte();
pending.WriteShort(storedLength);
pending.WriteShort(~storedLength);
pending.WriteBlock(stored, storedOffset, storedLength);
Reset();
}
/// <summary>
/// Flush block to output with compression
/// </summary>
/// <param name="stored">Data to flush</param>
/// <param name="storedOffset">Index of first byte to flush</param>
/// <param name="storedLength">Count of bytes to flush</param>
/// <param name="lastBlock">True if this is the last block</param>
public void FlushBlock(byte[] stored, int storedOffset, int storedLength, bool lastBlock)
{
literalTree.freqs[EOF_SYMBOL]++;
// Build trees
literalTree.BuildTree();
distTree.BuildTree();
// Calculate bitlen frequency
literalTree.CalcBLFreq(blTree);
distTree.CalcBLFreq(blTree);
// Build bitlen tree
blTree.BuildTree();
int blTreeCodes = 4;
for (int i = 18; i > blTreeCodes; i--)
{
if (blTree.length[BL_ORDER[i]] > 0)
{
blTreeCodes = i + 1;
}
}
int opt_len = 14 + blTreeCodes * 3 + blTree.GetEncodedLength() +
literalTree.GetEncodedLength() + distTree.GetEncodedLength() +
extra_bits;
int static_len = extra_bits;
for (int i = 0; i < LITERAL_NUM; i++)
{
static_len += literalTree.freqs[i] * staticLLength[i];
}
for (int i = 0; i < DIST_NUM; i++)
{
static_len += distTree.freqs[i] * staticDLength[i];
}
if (opt_len >= static_len)
{
// Force static trees
opt_len = static_len;
}
if (storedOffset >= 0 && storedLength + 4 < opt_len >> 3)
{
// Store Block
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("Storing, since " + storedLength + " < " + opt_len
// + " <= " + static_len);
// }
FlushStoredBlock(stored, storedOffset, storedLength, lastBlock);
}
else if (opt_len == static_len)
{
// Encode with static tree
pending.WriteBits((DeflaterConstants.STATIC_TREES << 1) + (lastBlock ? 1 : 0), 3);
literalTree.SetStaticCodes(staticLCodes, staticLLength);
distTree.SetStaticCodes(staticDCodes, staticDLength);
CompressBlock();
Reset();
}
else
{
// Encode with dynamic tree
pending.WriteBits((DeflaterConstants.DYN_TREES << 1) + (lastBlock ? 1 : 0), 3);
SendAllTrees(blTreeCodes);
CompressBlock();
Reset();
}
}
/// <summary>
/// Get value indicating if internal buffer is full
/// </summary>
/// <returns>true if buffer is full</returns>
public bool IsFull()
{
return last_lit >= BUFSIZE;
}
/// <summary>
/// Add literal to buffer
/// </summary>
/// <param name="literal">Literal value to add to buffer.</param>
/// <returns>Value indicating internal buffer is full</returns>
public bool TallyLit(int literal)
{
// if (DeflaterConstants.DEBUGGING) {
// if (lit > 32 && lit < 127) {
// //Console.WriteLine("("+(char)lit+")");
// } else {
// //Console.WriteLine("{"+lit+"}");
// }
// }
d_buf[last_lit] = 0;
l_buf[last_lit++] = (byte)literal;
literalTree.freqs[literal]++;
return IsFull();
}
/// <summary>
/// Add distance code and length to literal and distance trees
/// </summary>
/// <param name="distance">Distance code</param>
/// <param name="length">Length</param>
/// <returns>Value indicating if internal buffer is full</returns>
public bool TallyDist(int distance, int length)
{
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("[" + distance + "," + length + "]");
// }
d_buf[last_lit] = (short)distance;
l_buf[last_lit++] = (byte)(length - 3);
int lc = Lcode(length - 3);
literalTree.freqs[lc]++;
if (lc >= 265 && lc < 285)
{
extra_bits += (lc - 261) / 4;
}
int dc = Dcode(distance - 1);
distTree.freqs[dc]++;
if (dc >= 4)
{
extra_bits += dc / 2 - 1;
}
return IsFull();
}
/// <summary>
/// Reverse the bits of a 16 bit value.
/// </summary>
/// <param name="toReverse">Value to reverse bits</param>
/// <returns>Value with bits reversed</returns>
public static short BitReverse(int toReverse)
{
return (short)(bit4Reverse[toReverse & 0xF] << 12 |
bit4Reverse[(toReverse >> 4) & 0xF] << 8 |
bit4Reverse[(toReverse >> 8) & 0xF] << 4 |
bit4Reverse[toReverse >> 12]);
}
static int Lcode(int length)
{
if (length == 255)
{
return 285;
}
int code = 257;
while (length >= 8)
{
code += 4;
length >>= 1;
}
return code + length;
}
static int Dcode(int distance)
{
int code = 0;
while (distance >= 4)
{
code += 2;
distance >>= 1;
}
return code + distance;
}
}
}
| |
using System;
using System.Collections.Generic;
using LabLog.Domain.Events;
using LabLog.Domain.Exceptions;
namespace LabLog.Domain.Entities
{
public class School
{
private readonly Action<ILabEvent> _eventHandler;
private School(Action<ILabEvent> eventHandler)
{
_eventHandler = eventHandler;
}
public School(List<LabEvent> events, Action<ILabEvent> eventHandler)
{
_eventHandler = eventHandler;
foreach (LabEvent _event in events)
{
Replay(_event);
}
}
public static School Create(string name, Action<ILabEvent> eventHandler)
{
if (name == "")
{
LabException ex = new LabException();
ex.AddException(new Exception("School names must not be null"));
throw ex;
}
var school = new School(eventHandler);
school.Id = Guid.NewGuid();
var e = LabEvent.Create(school.Id,
++school.Version, new SchoolCreatedEvent { Name = name });
school._eventHandler(e);
return school;
}
public List<Room> Rooms { get; } = new List<Room>();
public Guid Id { get; set; }
private String _name;
public String Name {
get { return _name; }
set
{
if (_eventHandler == null)
{
return;
}
_name = value;
var @event = LabEvent.Create(Id,
++Version,
new SchoolNameChangedEvent(_name)
);
_eventHandler(@event);
}
}
public int Version { get; private set; }
public void AddComputer(Guid roomId, Computer computer)
{
if (_eventHandler == null)
{
return;
}
LabException ex = new LabException();
foreach (Room _room in Rooms)
{
if (_room.Computers.FindAll(f => (f.SerialNumber == computer.SerialNumber)).Count > 0)
{
ex.AddException(new UniqueComputerSerialException());
}
}
Room room = Rooms.Find(f => (f.RoomId == roomId));
foreach (Computer _computer in room.Computers)
{
if (computer.Position == _computer.Position) { ex.AddException(new UniqueComputerRoomPositionException());}
}
if (ex.HasExceptions()) {throw ex;}
var @event = LabEvent.Create(
//Guid.NewGuid(),
Id,
++Version,
new ComputerAddedEvent(roomId, computer.SerialNumber, computer.ComputerName, computer.Position));
ApplyComputerAddedEvent(@event);
_eventHandler(@event);
}
public void AddRoom(string roomName)
{
if (_eventHandler == null)
{
return;
}
if (Rooms.FindAll(f => (f.RoomName == roomName)).Count > 0)
{
var exceptions = new LabException();
exceptions.AddException(new UniqueRoomNameException());
throw exceptions;
}
var @event = LabEvent.Create(
Id,
++Version,
new RoomAddedEvent(Guid.NewGuid(), roomName));
ApplyRoomAddedEvent(@event);
_eventHandler(@event);
}
public void AssignStudent(string username, string serialNumber)
{
if (_eventHandler == null)
{
return;
}
var @event = LabEvent.Create(Id, ++Version,
new StudentAssignedEvent(serialNumber, username));
ApplyStudentAssignedEvent(@event);
_eventHandler(@event);
}
public void RecordDamage(string roomName, string serialNumber, string damageDescription)
{
if (_eventHandler == null)
{
return;
}
Computer computer = GetComputerBySerial(serialNumber);
var @event = LabEvent.Create(Id, ++Version,
new DamageAddedEvent(roomName, serialNumber, computer.GetLastDamageId() + 1, damageDescription));
ApplyDamageAddedEvent(@event);
_eventHandler(@event);
}
public void UpdateDamageTicket(string roomName, string serialNumber, int damageId, string ticket)
{
if (_eventHandler == null)
{
return;
}
var @event = LabEvent.Create(Id, ++Version,
new UpdateDamageTicketEvent(roomName, serialNumber, damageId, ticket));
ApplyUpdateDamageTicketEvent(@event);
_eventHandler(@event);
}
public void ApplyUpdateDamageTicketEvent(ILabEvent e)
{
var body = e.GetEventBody<UpdateDamageTicketEvent>();
Computer computer = GetComputerBySerial(body.SerialNumber);
Damage damage = computer.DamageList.Find(f => f.DamageId == body.DamageId);
damage.TicketId = body.TicketId;
Version = e.Version;
}
private void ApplyDamageAddedEvent(ILabEvent e)
{
var body = e.GetEventBody<DamageAddedEvent>();
Computer computer = GetComputerBySerial(body.SerialNumber);
Damage damage = new Damage(computer.GetLastDamageId() + 1, body.DamageDescription);
computer.DamageList.Add(damage);
Version = e.Version;
}
private void ApplyComputerAddedEvent(ILabEvent e)
{
var body = e.GetEventBody<ComputerAddedEvent>();
Room room = Rooms.Find(f => (f.RoomId == body.RoomId));
if (room == null) { throw new Exception ("Could not find room with id " + body.RoomId + ". Found " + Rooms.Count + " rooms.");}
room.Computers.Add(new Computer(body.SerialNumber,
body.ComputerName, body.Position));
if (room.Computers == null) {throw new Exception("room.Computers is null");}
Version = e.Version;
}
private void ApplyStudentAssignedEvent(ILabEvent e)
{
var body = e.GetEventBody<StudentAssignedEvent>();
Version = e.Version;
}
private void ApplyRoomAddedEvent(ILabEvent e)
{
var body = e.GetEventBody<RoomAddedEvent>();
Room room = new Room(body.RoomId, body.RoomName);
Rooms.Add(room);
Version = e.Version;
}
private void ApplySchoolCreatedEvent(ILabEvent e)
{
Id = e.SchoolId;
var body = e.GetEventBody<SchoolCreatedEvent>();
_name = body.Name;
Version = e.Version;
}
public void Replay(ILabEvent labEvent)
{
switch (labEvent.EventType)
{
case SchoolCreatedEvent.EventTypeString:
ApplySchoolCreatedEvent(labEvent);
break;
case ComputerAddedEvent.EventTypeString:
ApplyComputerAddedEvent(labEvent);
break;
case RoomAddedEvent.EventTypeString:
ApplyRoomAddedEvent(labEvent);
break;
case StudentAssignedEvent.EventTypeString:
ApplyStudentAssignedEvent(labEvent);
break;
case DamageAddedEvent.EventTypeString:
ApplyDamageAddedEvent(labEvent);
break;
}
}
private Computer GetComputerBySerial(string serialNumber)
{
foreach (Room room in Rooms)
{
Computer _computer = room.Computers.Find(f => f.SerialNumber == serialNumber);
if (_computer.SerialNumber == serialNumber) { return _computer; }
}
throw new Exception("No computer found");
}
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.BusinessEntities.BusinessEntities
File: Exchange_Instances.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.BusinessEntities
{
using Ecng.Common;
using StockSharp.Localization;
partial class Exchange
{
static Exchange()
{
Test = new Exchange
{
Name = "TEST",
FullNameLoc = LocalizedStrings.TestExchangeKey,
};
Moex = new Exchange
{
Name = "MOEX",
FullNameLoc = LocalizedStrings.MoscowExchangeKey,
CountryCode = CountryCodes.RU,
};
Spb = new Exchange
{
Name = "SPB",
FullNameLoc = LocalizedStrings.SaintPetersburgExchangeKey,
CountryCode = CountryCodes.RU,
};
Ux = new Exchange
{
Name = "UX",
FullNameLoc = LocalizedStrings.UkrainExchangeKey,
CountryCode = CountryCodes.UA,
};
Amex = new Exchange
{
Name = "AMEX",
FullNameLoc = LocalizedStrings.AmericanStockExchangeKey,
CountryCode = CountryCodes.US,
};
Cme = new Exchange
{
Name = "CME",
FullNameLoc = LocalizedStrings.ChicagoMercantileExchangeKey,
CountryCode = CountryCodes.US,
};
Cce = new Exchange
{
Name = "CCE",
FullNameLoc = LocalizedStrings.ChicagoClimateExchangeKey,
CountryCode = CountryCodes.US,
};
Cbot = new Exchange
{
Name = "CBOT",
FullNameLoc = LocalizedStrings.ChicagoBoardofTradeKey,
CountryCode = CountryCodes.US,
};
Nymex = new Exchange
{
Name = "NYMEX",
FullNameLoc = LocalizedStrings.NewYorkMercantileExchangeKey,
CountryCode = CountryCodes.US,
};
Nyse = new Exchange
{
Name = "NYSE",
FullNameLoc = LocalizedStrings.NewYorkStockExchangeKey,
CountryCode = CountryCodes.US,
};
Nasdaq = new Exchange
{
Name = "NASDAQ",
FullNameLoc = LocalizedStrings.NASDAQKey,
CountryCode = CountryCodes.US,
};
Nqlx = new Exchange
{
Name = "NQLX",
FullNameLoc = LocalizedStrings.NasdaqLiffeMarketsKey,
CountryCode = CountryCodes.US,
};
Tsx = new Exchange
{
Name = "TSX",
FullNameLoc = LocalizedStrings.TorontoStockExchangeKey,
CountryCode = CountryCodes.CA,
};
Lse = new Exchange
{
Name = "LSE",
FullNameLoc = LocalizedStrings.LondonStockExchangeKey,
CountryCode = CountryCodes.GB,
};
Lme = new Exchange
{
Name = "LME",
FullNameLoc = LocalizedStrings.LondonMetalExchangeKey,
CountryCode = CountryCodes.GB,
};
Tse = new Exchange
{
Name = "TSE",
FullNameLoc = LocalizedStrings.TokyoStockExchangeKey,
CountryCode = CountryCodes.JP,
};
Hkex = new Exchange
{
Name = "HKEX",
FullNameLoc = LocalizedStrings.HongKongStockExchangeKey,
CountryCode = CountryCodes.HK,
};
Hkfe = new Exchange
{
Name = "HKFE",
FullNameLoc = LocalizedStrings.HongKongFuturesExchangeKey,
CountryCode = CountryCodes.HK,
};
Sse = new Exchange
{
Name = "SSE",
FullNameLoc = LocalizedStrings.ShanghaiStockExchangeKey,
CountryCode = CountryCodes.CN,
};
Szse = new Exchange
{
Name = "SZSE",
FullNameLoc = LocalizedStrings.ShenzhenStockExchangeKey,
CountryCode = CountryCodes.CN,
};
Tsec = new Exchange
{
Name = "TSEC",
FullNameLoc = LocalizedStrings.TaiwanStockExchangeKey,
CountryCode = CountryCodes.TW,
};
Sgx = new Exchange
{
Name = "SGX",
FullNameLoc = LocalizedStrings.SingaporeExchangeKey,
CountryCode = CountryCodes.SG,
};
Pse = new Exchange
{
Name = "PSE",
FullNameLoc = LocalizedStrings.PhilippineStockExchangeKey,
CountryCode = CountryCodes.PH,
};
Klse = new Exchange
{
Name = "MYX",
FullNameLoc = LocalizedStrings.BursaMalaysiaKey,
CountryCode = CountryCodes.MY,
};
Idx = new Exchange
{
Name = "IDX",
FullNameLoc = LocalizedStrings.IndonesiaStockExchangeKey,
CountryCode = CountryCodes.ID,
};
Set = new Exchange
{
Name = "SET",
FullNameLoc = LocalizedStrings.StockExchangeofThailandKey,
CountryCode = CountryCodes.TH,
};
Bse = new Exchange
{
Name = "BSE",
FullNameLoc = LocalizedStrings.BombayStockExchangeKey,
CountryCode = CountryCodes.IN,
};
Nse = new Exchange
{
Name = "NSE",
FullNameLoc = LocalizedStrings.NationalStockExchangeofIndiaKey,
CountryCode = CountryCodes.IN,
};
Cse = new Exchange
{
Name = "CSE",
FullNameLoc = LocalizedStrings.ColomboStockExchangeKey,
CountryCode = CountryCodes.CO,
};
Krx = new Exchange
{
Name = "KRX",
FullNameLoc = LocalizedStrings.KoreaExchangeKey,
CountryCode = CountryCodes.KR,
};
Asx = new Exchange
{
Name = "ASX",
FullNameLoc = LocalizedStrings.AustralianSecuritiesExchangeKey,
CountryCode = CountryCodes.AU,
};
Nzx = new Exchange
{
Name = "NZSX",
FullNameLoc = LocalizedStrings.NewZealandExchangeKey,
CountryCode = CountryCodes.NZ,
};
Tase = new Exchange
{
Name = "TASE",
FullNameLoc = LocalizedStrings.TelAvivStockExchangeKey,
CountryCode = CountryCodes.IL,
};
Fwb = new Exchange
{
Name = "FWB",
FullNameLoc = LocalizedStrings.FrankfurtStockExchangeKey,
CountryCode = CountryCodes.DE,
};
Mse = new Exchange
{
Name = "MSE",
FullNameLoc = LocalizedStrings.MadridStockExchangeKey,
CountryCode = CountryCodes.ES,
};
Swx = new Exchange
{
Name = "SWX",
FullNameLoc = LocalizedStrings.SwissExchangeKey,
CountryCode = CountryCodes.CH,
};
Jse = new Exchange
{
Name = "JSE",
FullNameLoc = LocalizedStrings.JohannesburgStockExchangeKey,
CountryCode = CountryCodes.ZA,
};
Lmax = new Exchange
{
Name = "LMAX",
FullNameLoc = LocalizedStrings.LmaxKey,
CountryCode = CountryCodes.GB,
};
DukasCopy = new Exchange
{
Name = "DUKAS",
FullNameLoc = LocalizedStrings.DukasCopyKey,
CountryCode = CountryCodes.CH,
};
GainCapital = new Exchange
{
Name = "GAIN",
FullNameLoc = LocalizedStrings.GainCapitalKey,
CountryCode = CountryCodes.US,
};
MBTrading = new Exchange
{
Name = "MBT",
FullNameLoc = LocalizedStrings.MBTradingKey,
CountryCode = CountryCodes.US,
};
TrueFX = new Exchange
{
Name = "TRUEFX",
FullNameLoc = LocalizedStrings.TrueFXKey,
CountryCode = CountryCodes.US,
};
Cfh = new Exchange
{
Name = "CFH",
FullNameLoc = LocalizedStrings.CFHKey,
CountryCode = CountryCodes.GB,
};
Ond = new Exchange
{
Name = "OANDA",
FullNameLoc = LocalizedStrings.OandaKey,
CountryCode = CountryCodes.US,
};
Integral = new Exchange
{
Name = "INTGRL",
FullNameLoc = LocalizedStrings.IntegralKey,
CountryCode = CountryCodes.US,
};
Btce = new Exchange
{
Name = "BTCE",
FullNameLoc = LocalizedStrings.BtceKey,
CountryCode = CountryCodes.RU,
};
BitStamp = new Exchange
{
Name = "BITSTAMP",
FullNameLoc = LocalizedStrings.BitStampKey,
CountryCode = CountryCodes.GB,
};
BtcChina = new Exchange
{
Name = "BTCCHINA",
FullNameLoc = LocalizedStrings.BtcChinaKey,
CountryCode = CountryCodes.CN,
};
Icbit = new Exchange
{
Name = "ICBIT",
FullNameLoc = LocalizedStrings.IcBitKey,
CountryCode = CountryCodes.RU,
};
}
/// <summary>
/// Information about <see cref="Test"/>.
/// </summary>
public static Exchange Test { get; }
/// <summary>
/// Information about <see cref="Moex"/>.
/// </summary>
public static Exchange Moex { get; }
/// <summary>
/// Information about <see cref="Spb"/>.
/// </summary>
public static Exchange Spb { get; }
/// <summary>
/// Information about <see cref="Ux"/>.
/// </summary>
public static Exchange Ux { get; }
/// <summary>
/// Information about <see cref="Amex"/>.
/// </summary>
public static Exchange Amex { get; }
/// <summary>
/// Information about <see cref="Cme"/>.
/// </summary>
public static Exchange Cme { get; }
/// <summary>
/// Information about <see cref="Cbot"/>.
/// </summary>
public static Exchange Cbot { get; }
/// <summary>
/// Information about <see cref="Cce"/>.
/// </summary>
public static Exchange Cce { get; }
/// <summary>
/// Information about <see cref="Nymex"/>.
/// </summary>
public static Exchange Nymex { get; }
/// <summary>
/// Information about <see cref="Nyse"/>.
/// </summary>
public static Exchange Nyse { get; }
/// <summary>
/// Information about <see cref="Nasdaq"/>.
/// </summary>
public static Exchange Nasdaq { get; }
/// <summary>
/// Information about <see cref="Nqlx"/>.
/// </summary>
public static Exchange Nqlx { get; }
/// <summary>
/// Information about <see cref="Lse"/>.
/// </summary>
public static Exchange Lse { get; }
/// <summary>
/// Information about <see cref="Lme"/>.
/// </summary>
public static Exchange Lme { get; }
/// <summary>
/// Information about <see cref="Tse"/>.
/// </summary>
public static Exchange Tse { get; }
/// <summary>
/// Information about <see cref="Hkex"/>.
/// </summary>
public static Exchange Hkex { get; }
/// <summary>
/// Information about <see cref="Hkfe"/>.
/// </summary>
public static Exchange Hkfe { get; }
/// <summary>
/// Information about <see cref="Sse"/>.
/// </summary>
public static Exchange Sse { get; }
/// <summary>
/// Information about <see cref="Szse"/>.
/// </summary>
public static Exchange Szse { get; }
/// <summary>
/// Information about <see cref="Tsx"/>.
/// </summary>
public static Exchange Tsx { get; }
/// <summary>
/// Information about <see cref="Fwb"/>.
/// </summary>
public static Exchange Fwb { get; }
/// <summary>
/// Information about <see cref="Asx"/>.
/// </summary>
public static Exchange Asx { get; }
/// <summary>
/// Information about <see cref="Nzx"/>.
/// </summary>
public static Exchange Nzx { get; }
/// <summary>
/// Information about <see cref="Bse"/>.
/// </summary>
public static Exchange Bse { get; }
/// <summary>
/// Information about <see cref="Nse"/>.
/// </summary>
public static Exchange Nse { get; }
/// <summary>
/// Information about <see cref="Swx"/>.
/// </summary>
public static Exchange Swx { get; }
/// <summary>
/// Information about <see cref="Krx"/>.
/// </summary>
public static Exchange Krx { get; }
/// <summary>
/// Information about <see cref="Mse"/>.
/// </summary>
public static Exchange Mse { get; }
/// <summary>
/// Information about <see cref="Jse"/>.
/// </summary>
public static Exchange Jse { get; }
/// <summary>
/// Information about <see cref="Sgx"/>.
/// </summary>
public static Exchange Sgx { get; }
/// <summary>
/// Information about <see cref="Tsec"/>.
/// </summary>
public static Exchange Tsec { get; }
/// <summary>
/// Information about <see cref="Pse"/>.
/// </summary>
public static Exchange Pse { get; }
/// <summary>
/// Information about <see cref="Klse"/>.
/// </summary>
public static Exchange Klse { get; }
/// <summary>
/// Information about <see cref="Idx"/>.
/// </summary>
public static Exchange Idx { get; }
/// <summary>
/// Information about <see cref="Set"/>.
/// </summary>
public static Exchange Set { get; }
/// <summary>
/// Information about <see cref="Cse"/>.
/// </summary>
public static Exchange Cse { get; }
/// <summary>
/// Information about <see cref="Tase"/>.
/// </summary>
public static Exchange Tase { get; }
/// <summary>
/// Information about <see cref="Lmax"/>.
/// </summary>
public static Exchange Lmax { get; }
/// <summary>
/// Information about <see cref="DukasCopy"/>.
/// </summary>
public static Exchange DukasCopy { get; }
/// <summary>
/// Information about <see cref="GainCapital"/>.
/// </summary>
public static Exchange GainCapital { get; }
/// <summary>
/// Information about <see cref="MBTrading"/>.
/// </summary>
public static Exchange MBTrading { get; }
/// <summary>
/// Information about <see cref="TrueFX"/>.
/// </summary>
public static Exchange TrueFX { get; }
/// <summary>
/// Information about <see cref="Cfh"/>.
/// </summary>
public static Exchange Cfh { get; }
/// <summary>
/// Information about <see cref="Ond"/>.
/// </summary>
public static Exchange Ond { get; }
/// <summary>
/// Information about <see cref="Integral"/>.
/// </summary>
public static Exchange Integral { get; }
/// <summary>
/// Information about <see cref="Btce"/>.
/// </summary>
public static Exchange Btce { get; }
/// <summary>
/// Information about <see cref="BitStamp"/>.
/// </summary>
public static Exchange BitStamp { get; }
/// <summary>
/// Information about <see cref="BtcChina"/>.
/// </summary>
public static Exchange BtcChina { get; }
/// <summary>
/// Information about <see cref="Icbit"/>.
/// </summary>
public static Exchange Icbit { get; }
/// <summary>
/// Information about <see cref="Currenex"/>.
/// </summary>
public static Exchange Currenex { get; } = new Exchange
{
Name = "CURRENEX",
FullNameLoc = LocalizedStrings.CurrenexKey,
CountryCode = CountryCodes.US,
};
/// <summary>
/// Information about <see cref="Fxcm"/>.
/// </summary>
public static Exchange Fxcm { get; } = new Exchange
{
Name = "FXCM",
FullNameLoc = LocalizedStrings.FxcmKey,
CountryCode = CountryCodes.US,
};
/// <summary>
/// Information about <see cref="Poloniex"/>.
/// </summary>
public static Exchange Poloniex { get; } = new Exchange
{
Name = "PLNX",
FullNameLoc = LocalizedStrings.PoloniexKey,
};
/// <summary>
/// Information about <see cref="Kraken"/>.
/// </summary>
public static Exchange Kraken { get; } = new Exchange
{
Name = "KRKN",
FullNameLoc = LocalizedStrings.KrakenKey,
};
/// <summary>
/// Information about <see cref="Bittrex"/>.
/// </summary>
public static Exchange Bittrex { get; } = new Exchange
{
Name = "BTRX",
FullNameLoc = LocalizedStrings.BittrexKey,
};
/// <summary>
/// Information about <see cref="Bitfinex"/>.
/// </summary>
public static Exchange Bitfinex { get; } = new Exchange
{
Name = "BTFX",
FullNameLoc = LocalizedStrings.BitfinexKey,
};
/// <summary>
/// Information about <see cref="Coinbase"/>.
/// </summary>
public static Exchange Coinbase { get; } = new Exchange
{
Name = "CNBS",
FullNameLoc = LocalizedStrings.CoinbaseKey,
};
/// <summary>
/// Information about <see cref="Gdax"/>.
/// </summary>
public static Exchange Gdax { get; } = new Exchange
{
Name = "GDAX",
FullNameLoc = LocalizedStrings.GdaxKey,
};
/// <summary>
/// Information about <see cref="Bithumb"/>.
/// </summary>
public static Exchange Bithumb { get; } = new Exchange
{
Name = "BTHB",
FullNameLoc = LocalizedStrings.BithumbKey,
};
/// <summary>
/// Information about <see cref="HitBtc"/>.
/// </summary>
public static Exchange HitBtc { get; } = new Exchange
{
Name = "HTBTC",
FullNameLoc = LocalizedStrings.HitBtcKey,
};
/// <summary>
/// Information about <see cref="OkCoin"/>.
/// </summary>
public static Exchange OkCoin { get; } = new Exchange
{
Name = "OKCN",
FullNameLoc = LocalizedStrings.OkcoinKey,
};
/// <summary>
/// Information about <see cref="Coincheck"/>.
/// </summary>
public static Exchange Coincheck { get; } = new Exchange
{
Name = "CNCK",
FullNameLoc = LocalizedStrings.CoincheckKey,
};
/// <summary>
/// Information about <see cref="Binance"/>.
/// </summary>
public static Exchange Binance { get; } = new Exchange
{
Name = "BNB",
FullNameLoc = LocalizedStrings.BinanceKey,
};
/// <summary>
/// Information about <see cref="Bitexbook"/>.
/// </summary>
public static Exchange Bitexbook { get; } = new Exchange
{
Name = "BTXB",
FullNameLoc = LocalizedStrings.BitexbookKey,
};
/// <summary>
/// Information about <see cref="Bitmex"/>.
/// </summary>
public static Exchange Bitmex { get; } = new Exchange
{
Name = "BMEX",
FullNameLoc = LocalizedStrings.BitmexKey,
};
/// <summary>
/// Information about <see cref="Cex"/>.
/// </summary>
public static Exchange Cex { get; } = new Exchange
{
Name = "CEXIO",
FullNameLoc = LocalizedStrings.CexKey,
};
/// <summary>
/// Information about <see cref="Cryptopia"/>.
/// </summary>
public static Exchange Cryptopia { get; } = new Exchange
{
Name = "CRTP",
FullNameLoc = LocalizedStrings.CryptopiaKey,
};
/// <summary>
/// Information about <see cref="Okex"/>.
/// </summary>
public static Exchange Okex { get; } = new Exchange
{
Name = "OKEX",
FullNameLoc = LocalizedStrings.OkexKey,
};
/// <summary>
/// Information about <see cref="Bitmart"/>.
/// </summary>
public static Exchange Bitmart { get; } = new Exchange
{
Name = "BIMA",
FullNameLoc = LocalizedStrings.BitmartKey,
};
/// <summary>
/// Information about <see cref="Yobit"/>.
/// </summary>
public static Exchange Yobit { get; } = new Exchange
{
Name = "YBIT",
FullNameLoc = LocalizedStrings.YobitKey,
};
/// <summary>
/// Information about <see cref="CoinExchange"/>.
/// </summary>
public static Exchange CoinExchange { get; } = new Exchange
{
Name = "CNEX",
FullNameLoc = LocalizedStrings.CoinExchangeKey,
};
/// <summary>
/// Information about <see cref="LiveCoin"/>.
/// </summary>
public static Exchange LiveCoin { get; } = new Exchange
{
Name = "LVCN",
FullNameLoc = LocalizedStrings.LiveCoinKey,
};
/// <summary>
/// Information about <see cref="Exmo"/>.
/// </summary>
public static Exchange Exmo { get; } = new Exchange
{
Name = "EXMO",
FullNameLoc = LocalizedStrings.ExmoKey,
};
/// <summary>
/// Information about <see cref="Deribit"/>.
/// </summary>
public static Exchange Deribit { get; } = new Exchange
{
Name = "DRBT",
FullNameLoc = LocalizedStrings.DeribitKey,
};
/// <summary>
/// Information about <see cref="Kucoin"/>.
/// </summary>
public static Exchange Kucoin { get; } = new Exchange
{
Name = "KUCN",
FullNameLoc = LocalizedStrings.KucoinKey,
};
/// <summary>
/// Information about <see cref="Liqui"/>.
/// </summary>
public static Exchange Liqui { get; } = new Exchange
{
Name = "LIQI",
FullNameLoc = LocalizedStrings.LiquiKey,
};
/// <summary>
/// Information about <see cref="Huobi"/>.
/// </summary>
public static Exchange Huobi { get; } = new Exchange
{
Name = "HUBI",
FullNameLoc = LocalizedStrings.HuobiKey,
};
/// <summary>
/// Information about <see cref="IEX"/>.
/// </summary>
public static Exchange IEX { get; } = new Exchange
{
Name = "IEX",
FullNameLoc = LocalizedStrings.IEXKey,
CountryCode = CountryCodes.US,
};
/// <summary>
/// Information about <see cref="AlphaVantage"/>.
/// </summary>
public static Exchange AlphaVantage { get; } = new Exchange
{
Name = "ALVG",
FullNameLoc = LocalizedStrings.AlphaVantageKey,
CountryCode = CountryCodes.US,
};
/// <summary>
/// Information about <see cref="Bitbank"/>.
/// </summary>
public static Exchange Bitbank { get; } = new Exchange
{
Name = "BTBN",
FullNameLoc = LocalizedStrings.BitbankKey,
};
/// <summary>
/// Information about <see cref="Zaif"/>.
/// </summary>
public static Exchange Zaif { get; } = new Exchange
{
Name = "ZAIF",
FullNameLoc = LocalizedStrings.ZaifKey,
};
/// <summary>
/// Information about <see cref="Quoinex"/>.
/// </summary>
public static Exchange Quoinex { get; } = new Exchange
{
Name = "QINX",
FullNameLoc = LocalizedStrings.QuoinexKey,
};
/// <summary>
/// Information about <see cref="Wiki"/>.
/// </summary>
public static Exchange Wiki { get; } = new Exchange
{
Name = "WIKI",
FullNameLoc = LocalizedStrings.WIKIKey,
};
/// <summary>
/// Information about <see cref="Idax"/>.
/// </summary>
public static Exchange Idax { get; } = new Exchange
{
Name = "IDAX",
FullNameLoc = LocalizedStrings.IdaxKey,
};
/// <summary>
/// Information about <see cref="Digifinex"/>.
/// </summary>
public static Exchange Digifinex { get; } = new Exchange
{
Name = "DGFX",
FullNameLoc = LocalizedStrings.DigifinexKey,
};
/// <summary>
/// Information about <see cref="TradeOgre"/>.
/// </summary>
public static Exchange TradeOgre { get; } = new Exchange
{
Name = "TOGR",
FullNameLoc = LocalizedStrings.TradeOgreKey,
};
/// <summary>
/// Information about <see cref="CoinCap"/>.
/// </summary>
public static Exchange CoinCap { get; } = new Exchange
{
Name = "CNCP",
FullNameLoc = LocalizedStrings.CoinCapKey,
};
/// <summary>
/// Information about <see cref="Coinigy"/>.
/// </summary>
public static Exchange Coinigy { get; } = new Exchange
{
Name = "CNGY",
FullNameLoc = LocalizedStrings.CoinigyKey,
};
/// <summary>
/// Information about <see cref="LBank"/>.
/// </summary>
public static Exchange LBank { get; } = new Exchange
{
Name = "LBNK",
FullNameLoc = LocalizedStrings.LBankKey,
};
/// <summary>
/// Information about <see cref="BitMax"/>.
/// </summary>
public static Exchange BitMax { get; } = new Exchange
{
Name = "BMAX",
FullNameLoc = LocalizedStrings.BitMaxKey,
};
/// <summary>
/// Information about <see cref="BW"/>.
/// </summary>
public static Exchange BW { get; } = new Exchange
{
Name = "BW",
FullNameLoc = LocalizedStrings.BWKey,
};
/// <summary>
/// Information about <see cref="Bibox"/>.
/// </summary>
public static Exchange Bibox { get; } = new Exchange
{
Name = "BBOX",
FullNameLoc = LocalizedStrings.BiboxKey,
};
/// <summary>
/// Information about <see cref="CoinBene"/>.
/// </summary>
public static Exchange CoinBene { get; } = new Exchange
{
Name = "CNBN",
FullNameLoc = LocalizedStrings.CoinBeneKey,
};
/// <summary>
/// Information about <see cref="BitZ"/>.
/// </summary>
public static Exchange BitZ { get; } = new Exchange
{
Name = "BITZ",
FullNameLoc = LocalizedStrings.BitZKey,
};
/// <summary>
/// Information about <see cref="ZB"/>.
/// </summary>
public static Exchange ZB { get; } = new Exchange
{
Name = "ZB",
FullNameLoc = LocalizedStrings.ZBKey,
};
/// <summary>
/// Information about <see cref="Tradier"/>.
/// </summary>
public static Exchange Tradier { get; } = new Exchange
{
Name = "TRDR",
FullNameLoc = LocalizedStrings.TradierKey,
};
/// <summary>
/// Information about <see cref="SwSq"/>.
/// </summary>
public static Exchange SwSq { get; } = new Exchange
{
Name = "SWSQ",
FullNameLoc = LocalizedStrings.SwissQuoteKey,
};
/// <summary>
/// Information about <see cref="StockSharp"/>.
/// </summary>
public static Exchange StockSharp { get; } = new Exchange
{
Name = "STSH",
FullNameLoc = LocalizedStrings.StockSharpKey,
};
/// <summary>
/// Information about <see cref="Upbit"/>.
/// </summary>
public static Exchange Upbit { get; } = new Exchange
{
Name = "UPBT",
FullNameLoc = LocalizedStrings.UpbitKey,
};
/// <summary>
/// Information about <see cref="CoinEx"/>.
/// </summary>
public static Exchange CoinEx { get; } = new Exchange
{
Name = "CIEX",
FullNameLoc = LocalizedStrings.CoinExKey,
};
/// <summary>
/// Information about <see cref="FatBtc"/>.
/// </summary>
public static Exchange FatBtc { get; } = new Exchange
{
Name = "FTBT",
FullNameLoc = LocalizedStrings.FatBtcKey,
};
/// <summary>
/// Information about <see cref="Latoken"/>.
/// </summary>
public static Exchange Latoken { get; } = new Exchange
{
Name = "LTKN",
FullNameLoc = LocalizedStrings.LatokenKey,
};
/// <summary>
/// Information about <see cref="Gopax"/>.
/// </summary>
public static Exchange Gopax { get; } = new Exchange
{
Name = "GPAX",
FullNameLoc = LocalizedStrings.GopaxKey,
};
/// <summary>
/// Information about <see cref="CoinHub"/>.
/// </summary>
public static Exchange CoinHub { get; } = new Exchange
{
Name = "CNHB",
FullNameLoc = LocalizedStrings.CoinHubKey,
};
/// <summary>
/// Information about <see cref="Hotbit"/>.
/// </summary>
public static Exchange Hotbit { get; } = new Exchange
{
Name = "HTBT",
FullNameLoc = LocalizedStrings.HotbitKey,
};
/// <summary>
/// Information about <see cref="Bitalong"/>.
/// </summary>
public static Exchange Bitalong { get; } = new Exchange
{
Name = "BTLG",
FullNameLoc = LocalizedStrings.BitalongKey,
};
/// <summary>
/// Information about <see cref="PrizmBit"/>.
/// </summary>
public static Exchange PrizmBit { get; } = new Exchange
{
Name = "PRZM",
FullNameLoc = LocalizedStrings.PrizmBitKey,
};
/// <summary>
/// Information about <see cref="DigitexFutures"/>.
/// </summary>
public static Exchange DigitexFutures { get; } = new Exchange
{
Name = "DGFT",
FullNameLoc = LocalizedStrings.DigitexFuturesKey,
};
/// <summary>
/// Information about <see cref="Bovespa"/>.
/// </summary>
public static Exchange Bovespa { get; } = new Exchange
{
Name = "B3",
FullNameLoc = LocalizedStrings.BrasilBolsaKey,
};
/// <summary>
/// Information about <see cref="Bvmt"/>.
/// </summary>
public static Exchange Bvmt { get; } = new Exchange
{
Name = "BVMT",
FullNameLoc = LocalizedStrings.TunisBvmtKey,
};
/// <summary>
/// Information about <see cref="IQFeed"/>.
/// </summary>
public static Exchange IQFeed { get; } = new Exchange
{
Name = "IQFD",
FullNameLoc = LocalizedStrings.IQFeedKey,
};
/// <summary>
/// Information about <see cref="IBKR"/>.
/// </summary>
public static Exchange IBKR { get; } = new Exchange
{
Name = "IBKR",
FullNameLoc = LocalizedStrings.InteractiveBrokersKey,
};
/// <summary>
/// Information about <see cref="STSH"/>.
/// </summary>
public static Exchange STSH { get; } = new Exchange
{
Name = "STSH",
FullNameLoc = LocalizedStrings.StockSharpKey,
};
/// <summary>
/// Information about <see cref="STRLG"/>.
/// </summary>
public static Exchange STRLG { get; } = new Exchange
{
Name = "STRLG",
FullNameLoc = LocalizedStrings.SterlingKey,
};
/// <summary>
/// Information about <see cref="QNDL"/>.
/// </summary>
public static Exchange QNDL { get; } = new Exchange
{
Name = "QNDL",
FullNameLoc = LocalizedStrings.QuandlKey,
};
/// <summary>
/// Information about <see cref="QTFD"/>.
/// </summary>
public static Exchange QTFD { get; } = new Exchange
{
Name = "QTFD",
FullNameLoc = LocalizedStrings.QuantFeed,
};
/// <summary>
/// Information about <see cref="FTX"/>.
/// </summary>
public static Exchange FTX { get; } = new Exchange
{
Name = "FTX",
FullNameLoc = LocalizedStrings.FTX,
CountryCode = CountryCodes.BS,
};
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.IO;
using System.Runtime;
using System.Runtime.Diagnostics;
using System.ServiceModel;
using System.ServiceModel.Diagnostics;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xml;
namespace System.ServiceModel.Channels
{
internal class BinaryMessageEncoderFactory : MessageEncoderFactory
{
private const int maxPooledXmlReaderPerMessage = 2;
private BinaryMessageEncoder _messageEncoder;
private MessageVersion _messageVersion;
private int _maxReadPoolSize;
private int _maxWritePoolSize;
private CompressionFormat _compressionFormat;
// Double-checked locking pattern requires volatile for read/write synchronization
private volatile SynchronizedPool<BinaryBufferedMessageData> _bufferedDataPool;
private volatile SynchronizedPool<BinaryBufferedMessageWriter> _bufferedWriterPool;
private volatile SynchronizedPool<RecycledMessageState> _recycledStatePool;
private object _thisLock;
private int _maxSessionSize;
private XmlDictionaryReaderQuotas _readerQuotas;
private XmlDictionaryReaderQuotas _bufferedReadReaderQuotas;
private BinaryVersion _binaryVersion;
public BinaryMessageEncoderFactory(MessageVersion messageVersion, int maxReadPoolSize, int maxWritePoolSize, int maxSessionSize,
XmlDictionaryReaderQuotas readerQuotas, long maxReceivedMessageSize, BinaryVersion version, CompressionFormat compressionFormat)
{
_messageVersion = messageVersion;
_maxReadPoolSize = maxReadPoolSize;
_maxWritePoolSize = maxWritePoolSize;
_maxSessionSize = maxSessionSize;
_thisLock = new object();
_readerQuotas = new XmlDictionaryReaderQuotas();
if (readerQuotas != null)
{
readerQuotas.CopyTo(_readerQuotas);
}
_bufferedReadReaderQuotas = EncoderHelpers.GetBufferedReadQuotas(_readerQuotas);
this.MaxReceivedMessageSize = maxReceivedMessageSize;
_binaryVersion = version;
_compressionFormat = compressionFormat;
_messageEncoder = new BinaryMessageEncoder(this, false, 0);
}
public static IXmlDictionary XmlDictionary
{
get { return XD.Dictionary; }
}
public override MessageEncoder Encoder
{
get
{
return _messageEncoder;
}
}
public override MessageVersion MessageVersion
{
get { return _messageVersion; }
}
public int MaxWritePoolSize
{
get { return _maxWritePoolSize; }
}
public XmlDictionaryReaderQuotas ReaderQuotas
{
get
{
return _readerQuotas;
}
}
public int MaxReadPoolSize
{
get { return _maxReadPoolSize; }
}
public int MaxSessionSize
{
get { return _maxSessionSize; }
}
public CompressionFormat CompressionFormat
{
get { return _compressionFormat; }
}
private long MaxReceivedMessageSize
{
get;
set;
}
private object ThisLock
{
get { return _thisLock; }
}
private SynchronizedPool<RecycledMessageState> RecycledStatePool
{
get
{
if (_recycledStatePool == null)
{
lock (ThisLock)
{
if (_recycledStatePool == null)
{
//running = true;
_recycledStatePool = new SynchronizedPool<RecycledMessageState>(_maxReadPoolSize);
}
}
}
return _recycledStatePool;
}
}
public override MessageEncoder CreateSessionEncoder()
{
return new BinaryMessageEncoder(this, true, _maxSessionSize);
}
private XmlDictionaryWriter TakeStreamedWriter(Stream stream)
{
return XmlDictionaryWriter.CreateBinaryWriter(stream, _binaryVersion.Dictionary, null, false);
}
private void ReturnStreamedWriter(XmlDictionaryWriter xmlWriter)
{
xmlWriter.Dispose();
}
private BinaryBufferedMessageWriter TakeBufferedWriter()
{
if (_bufferedWriterPool == null)
{
lock (ThisLock)
{
if (_bufferedWriterPool == null)
{
//running = true;
_bufferedWriterPool = new SynchronizedPool<BinaryBufferedMessageWriter>(_maxWritePoolSize);
}
}
}
BinaryBufferedMessageWriter messageWriter = _bufferedWriterPool.Take();
if (messageWriter == null)
{
messageWriter = new BinaryBufferedMessageWriter(_binaryVersion.Dictionary);
if (WcfEventSource.Instance.WritePoolMissIsEnabled())
{
WcfEventSource.Instance.WritePoolMiss(messageWriter.GetType().Name);
}
}
return messageWriter;
}
private void ReturnMessageWriter(BinaryBufferedMessageWriter messageWriter)
{
_bufferedWriterPool.Return(messageWriter);
}
private XmlDictionaryReader TakeStreamedReader(Stream stream)
{
return XmlDictionaryReader.CreateBinaryReader(stream,
_binaryVersion.Dictionary,
_readerQuotas,
null);
}
private BinaryBufferedMessageData TakeBufferedData(BinaryMessageEncoder messageEncoder)
{
if (_bufferedDataPool == null)
{
lock (ThisLock)
{
if (_bufferedDataPool == null)
{
//running = true;
_bufferedDataPool = new SynchronizedPool<BinaryBufferedMessageData>(_maxReadPoolSize);
}
}
}
BinaryBufferedMessageData messageData = _bufferedDataPool.Take();
if (messageData == null)
{
messageData = new BinaryBufferedMessageData(this, maxPooledXmlReaderPerMessage);
if (WcfEventSource.Instance.ReadPoolMissIsEnabled())
{
WcfEventSource.Instance.ReadPoolMiss(messageData.GetType().Name);
}
}
messageData.SetMessageEncoder(messageEncoder);
return messageData;
}
private void ReturnBufferedData(BinaryBufferedMessageData messageData)
{
messageData.SetMessageEncoder(null);
_bufferedDataPool.Return(messageData);
}
internal class BinaryBufferedMessageData : BufferedMessageData
{
private BinaryMessageEncoderFactory _factory;
private BinaryMessageEncoder _messageEncoder;
private Pool<XmlDictionaryReader> _readerPool;
private OnXmlDictionaryReaderClose _onClose;
public BinaryBufferedMessageData(BinaryMessageEncoderFactory factory, int maxPoolSize)
: base(factory.RecycledStatePool)
{
_factory = factory;
_readerPool = new Pool<XmlDictionaryReader>(maxPoolSize);
_onClose = new OnXmlDictionaryReaderClose(OnXmlReaderClosed);
}
public override MessageEncoder MessageEncoder
{
get { return _messageEncoder; }
}
public override XmlDictionaryReaderQuotas Quotas
{
get { return _factory._readerQuotas; }
}
public void SetMessageEncoder(BinaryMessageEncoder messageEncoder)
{
_messageEncoder = messageEncoder;
}
protected override XmlDictionaryReader TakeXmlReader()
{
ArraySegment<byte> buffer = this.Buffer;
return XmlDictionaryReader.CreateBinaryReader(buffer.Array, buffer.Offset, buffer.Count,
_factory._binaryVersion.Dictionary,
_factory._bufferedReadReaderQuotas,
_messageEncoder.ReaderSession);
}
protected override void ReturnXmlReader(XmlDictionaryReader reader)
{
_readerPool.Return(reader);
}
protected override void OnClosed()
{
_factory.ReturnBufferedData(this);
}
}
internal class BinaryBufferedMessageWriter : BufferedMessageWriter
{
private IXmlDictionary _dictionary;
private XmlBinaryWriterSession _session;
public BinaryBufferedMessageWriter(IXmlDictionary dictionary)
{
_dictionary = dictionary;
}
public BinaryBufferedMessageWriter(IXmlDictionary dictionary, XmlBinaryWriterSession session)
{
_dictionary = dictionary;
_session = session;
}
protected override XmlDictionaryWriter TakeXmlWriter(Stream stream)
{
return XmlDictionaryWriter.CreateBinaryWriter(stream, _dictionary, _session, false);
}
protected override void ReturnXmlWriter(XmlDictionaryWriter writer)
{
writer.Dispose();
}
}
internal class BinaryMessageEncoder : MessageEncoder, ICompressedMessageEncoder
{
private const string SupportedCompressionTypesMessageProperty = "BinaryMessageEncoder.SupportedCompressionTypes";
private BinaryMessageEncoderFactory _factory;
private bool _isSession;
private XmlBinaryWriterSessionWithQuota _writerSession;
private BinaryBufferedMessageWriter _sessionMessageWriter;
private XmlBinaryReaderSession _readerSession;
private XmlBinaryReaderSession _readerSessionForLogging;
private bool _readerSessionForLoggingIsInvalid = false;
private int _writeIdCounter;
private int _idCounter;
private int _maxSessionSize;
private int _remainingReaderSessionSize;
private bool _isReaderSessionInvalid;
private MessagePatterns _messagePatterns;
private string _contentType;
private string _normalContentType;
private string _gzipCompressedContentType;
private string _deflateCompressedContentType;
private CompressionFormat _sessionCompressionFormat;
private readonly long _maxReceivedMessageSize;
public BinaryMessageEncoder(BinaryMessageEncoderFactory factory, bool isSession, int maxSessionSize)
{
_factory = factory;
_isSession = isSession;
_maxSessionSize = maxSessionSize;
_remainingReaderSessionSize = maxSessionSize;
_normalContentType = isSession ? factory._binaryVersion.SessionContentType : factory._binaryVersion.ContentType;
_gzipCompressedContentType = isSession ? BinaryVersion.GZipVersion1.SessionContentType : BinaryVersion.GZipVersion1.ContentType;
_deflateCompressedContentType = isSession ? BinaryVersion.DeflateVersion1.SessionContentType : BinaryVersion.DeflateVersion1.ContentType;
_sessionCompressionFormat = _factory.CompressionFormat;
_maxReceivedMessageSize = _factory.MaxReceivedMessageSize;
switch (_factory.CompressionFormat)
{
case CompressionFormat.Deflate:
_contentType = _deflateCompressedContentType;
break;
case CompressionFormat.GZip:
_contentType = _gzipCompressedContentType;
break;
default:
_contentType = _normalContentType;
break;
}
}
public override string ContentType
{
get
{
return _contentType;
}
}
public override MessageVersion MessageVersion
{
get { return _factory._messageVersion; }
}
public override string MediaType
{
get { return _contentType; }
}
public XmlBinaryReaderSession ReaderSession
{
get { return _readerSession; }
}
public bool CompressionEnabled
{
get { return _factory.CompressionFormat != CompressionFormat.None; }
}
private ArraySegment<byte> AddSessionInformationToMessage(ArraySegment<byte> messageData, BufferManager bufferManager, int maxMessageSize)
{
int dictionarySize = 0;
byte[] buffer = messageData.Array;
if (_writerSession.HasNewStrings)
{
IList<XmlDictionaryString> newStrings = _writerSession.GetNewStrings();
for (int i = 0; i < newStrings.Count; i++)
{
int utf8ValueSize = Encoding.UTF8.GetByteCount(newStrings[i].Value);
dictionarySize += IntEncoder.GetEncodedSize(utf8ValueSize) + utf8ValueSize;
}
int messageSize = messageData.Offset + messageData.Count;
int remainingMessageSize = maxMessageSize - messageSize;
if (remainingMessageSize - dictionarySize < 0)
{
string excMsg = string.Format(SRServiceModel.MaxSentMessageSizeExceeded, maxMessageSize);
if (WcfEventSource.Instance.MaxSentMessageSizeExceededIsEnabled())
{
WcfEventSource.Instance.MaxSentMessageSizeExceeded(excMsg);
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new QuotaExceededException(excMsg));
}
int requiredBufferSize = messageData.Offset + messageData.Count + dictionarySize;
if (buffer.Length < requiredBufferSize)
{
byte[] newBuffer = bufferManager.TakeBuffer(requiredBufferSize);
Buffer.BlockCopy(buffer, messageData.Offset, newBuffer, messageData.Offset, messageData.Count);
bufferManager.ReturnBuffer(buffer);
buffer = newBuffer;
}
Buffer.BlockCopy(buffer, messageData.Offset, buffer, messageData.Offset + dictionarySize, messageData.Count);
int offset = messageData.Offset;
for (int i = 0; i < newStrings.Count; i++)
{
string newString = newStrings[i].Value;
int utf8ValueSize = Encoding.UTF8.GetByteCount(newString);
offset += IntEncoder.Encode(utf8ValueSize, buffer, offset);
offset += Encoding.UTF8.GetBytes(newString, 0, newString.Length, buffer, offset);
}
_writerSession.ClearNewStrings();
}
int headerSize = IntEncoder.GetEncodedSize(dictionarySize);
int newOffset = messageData.Offset - headerSize;
int newSize = headerSize + messageData.Count + dictionarySize;
IntEncoder.Encode(dictionarySize, buffer, newOffset);
return new ArraySegment<byte>(buffer, newOffset, newSize);
}
private ArraySegment<byte> ExtractSessionInformationFromMessage(ArraySegment<byte> messageData)
{
if (_isReaderSessionInvalid)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataException(SRServiceModel.BinaryEncoderSessionInvalid));
}
byte[] buffer = messageData.Array;
int dictionarySize;
int headerSize;
int newOffset;
int newSize;
bool throwing = true;
try
{
IntDecoder decoder = new IntDecoder();
headerSize = decoder.Decode(buffer, messageData.Offset, messageData.Count);
dictionarySize = decoder.Value;
if (dictionarySize > messageData.Count)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataException(SRServiceModel.BinaryEncoderSessionMalformed));
}
newOffset = messageData.Offset + headerSize + dictionarySize;
newSize = messageData.Count - headerSize - dictionarySize;
if (newSize < 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataException(SRServiceModel.BinaryEncoderSessionMalformed));
}
if (dictionarySize > 0)
{
if (dictionarySize > _remainingReaderSessionSize)
{
string message = string.Format(SRServiceModel.BinaryEncoderSessionTooLarge, _maxSessionSize);
if (WcfEventSource.Instance.MaxSessionSizeReachedIsEnabled())
{
WcfEventSource.Instance.MaxSessionSizeReached(message);
}
Exception inner = new QuotaExceededException(message);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(message, inner));
}
else
{
_remainingReaderSessionSize -= dictionarySize;
}
int size = dictionarySize;
int offset = messageData.Offset + headerSize;
while (size > 0)
{
decoder.Reset();
int bytesDecoded = decoder.Decode(buffer, offset, size);
int utf8ValueSize = decoder.Value;
offset += bytesDecoded;
size -= bytesDecoded;
if (utf8ValueSize > size)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataException(SRServiceModel.BinaryEncoderSessionMalformed));
}
string value = Encoding.UTF8.GetString(buffer, offset, utf8ValueSize);
offset += utf8ValueSize;
size -= utf8ValueSize;
_readerSession.Add(_idCounter, value);
_idCounter++;
}
}
throwing = false;
}
finally
{
if (throwing)
{
_isReaderSessionInvalid = true;
}
}
return new ArraySegment<byte>(buffer, newOffset, newSize);
}
public override Message ReadMessage(ArraySegment<byte> buffer, BufferManager bufferManager, string contentType)
{
if (bufferManager == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("bufferManager");
}
CompressionFormat compressionFormat = this.CheckContentType(contentType);
if (WcfEventSource.Instance.BinaryMessageDecodingStartIsEnabled())
{
WcfEventSource.Instance.BinaryMessageDecodingStart();
}
if (compressionFormat != CompressionFormat.None)
{
MessageEncoderCompressionHandler.DecompressBuffer(ref buffer, bufferManager, compressionFormat, _maxReceivedMessageSize);
}
if (_isSession)
{
if (_readerSession == null)
{
_readerSession = new XmlBinaryReaderSession();
_messagePatterns = new MessagePatterns(_factory._binaryVersion.Dictionary, _readerSession, this.MessageVersion);
}
try
{
buffer = ExtractSessionInformationFromMessage(buffer);
}
catch (InvalidDataException)
{
MessageLogger.LogMessage(buffer, MessageLoggingSource.Malformed);
throw;
}
}
BinaryBufferedMessageData messageData = _factory.TakeBufferedData(this);
Message message;
if (_messagePatterns != null)
{
message = _messagePatterns.TryCreateMessage(buffer.Array, buffer.Offset, buffer.Count, bufferManager, messageData);
}
else
{
message = null;
}
if (message == null)
{
messageData.Open(buffer, bufferManager);
RecycledMessageState messageState = messageData.TakeMessageState();
if (messageState == null)
{
messageState = new RecycledMessageState();
}
message = new BufferedMessage(messageData, messageState);
}
message.Properties.Encoder = this;
if (MessageLogger.LogMessagesAtTransportLevel)
{
MessageLogger.LogMessage(ref message, MessageLoggingSource.TransportReceive);
}
return message;
}
public override Message ReadMessage(Stream stream, int maxSizeOfHeaders, string contentType)
{
if (stream == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("stream");
}
CompressionFormat compressionFormat = this.CheckContentType(contentType);
if (WcfEventSource.Instance.BinaryMessageDecodingStartIsEnabled())
{
WcfEventSource.Instance.BinaryMessageDecodingStart();
}
if (compressionFormat != CompressionFormat.None)
{
stream = new MaxMessageSizeStream(
MessageEncoderCompressionHandler.GetDecompressStream(stream, compressionFormat), _maxReceivedMessageSize);
}
XmlDictionaryReader reader = _factory.TakeStreamedReader(stream);
Message message = Message.CreateMessage(reader, maxSizeOfHeaders, _factory._messageVersion);
message.Properties.Encoder = this;
if (WcfEventSource.Instance.StreamedMessageReadByEncoderIsEnabled())
{
WcfEventSource.Instance.StreamedMessageReadByEncoder(
EventTraceActivityHelper.TryExtractActivity(message, true));
}
if (MessageLogger.LogMessagesAtTransportLevel)
{
MessageLogger.LogMessage(ref message, MessageLoggingSource.TransportReceive);
}
return message;
}
public override ArraySegment<byte> WriteMessage(Message message, int maxMessageSize, BufferManager bufferManager, int messageOffset)
{
if (message == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message");
}
if (bufferManager == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("bufferManager");
}
if (maxMessageSize < 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("maxMessageSize", maxMessageSize,
SRServiceModel.ValueMustBeNonNegative));
}
EventTraceActivity eventTraceActivity = null;
if (WcfEventSource.Instance.BinaryMessageEncodingStartIsEnabled())
{
eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(message);
WcfEventSource.Instance.BinaryMessageEncodingStart(eventTraceActivity);
}
message.Properties.Encoder = this;
if (_isSession)
{
if (_writerSession == null)
{
_writerSession = new XmlBinaryWriterSessionWithQuota(_maxSessionSize);
_sessionMessageWriter = new BinaryBufferedMessageWriter(_factory._binaryVersion.Dictionary, _writerSession);
}
messageOffset += IntEncoder.MaxEncodedSize;
}
if (messageOffset < 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("messageOffset", messageOffset,
SRServiceModel.ValueMustBeNonNegative));
}
if (messageOffset > maxMessageSize)
{
string excMsg = string.Format(SRServiceModel.MaxSentMessageSizeExceeded, maxMessageSize);
if (WcfEventSource.Instance.MaxSentMessageSizeExceededIsEnabled())
{
WcfEventSource.Instance.MaxSentMessageSizeExceeded(excMsg);
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new QuotaExceededException(excMsg));
}
ThrowIfMismatchedMessageVersion(message);
BinaryBufferedMessageWriter messageWriter;
if (_isSession)
{
messageWriter = _sessionMessageWriter;
}
else
{
messageWriter = _factory.TakeBufferedWriter();
}
ArraySegment<byte> messageData = messageWriter.WriteMessage(message, bufferManager, messageOffset, maxMessageSize);
if (MessageLogger.LogMessagesAtTransportLevel && !_readerSessionForLoggingIsInvalid)
{
if (_isSession)
{
if (_readerSessionForLogging == null)
{
_readerSessionForLogging = new XmlBinaryReaderSession();
}
if (_writerSession.HasNewStrings)
{
foreach (XmlDictionaryString xmlDictionaryString in _writerSession.GetNewStrings())
{
_readerSessionForLogging.Add(_writeIdCounter++, xmlDictionaryString.Value);
}
}
}
XmlDictionaryReader xmlDictionaryReader = XmlDictionaryReader.CreateBinaryReader(messageData.Array, messageData.Offset, messageData.Count, XD.Dictionary, XmlDictionaryReaderQuotas.Max, _readerSessionForLogging);
MessageLogger.LogMessage(ref message, xmlDictionaryReader, MessageLoggingSource.TransportSend);
}
else
{
_readerSessionForLoggingIsInvalid = true;
}
if (_isSession)
{
messageData = AddSessionInformationToMessage(messageData, bufferManager, maxMessageSize);
}
else
{
_factory.ReturnMessageWriter(messageWriter);
}
CompressionFormat compressionFormat = this.CheckCompressedWrite(message);
if (compressionFormat != CompressionFormat.None)
{
MessageEncoderCompressionHandler.CompressBuffer(ref messageData, bufferManager, compressionFormat);
}
return messageData;
}
public override void WriteMessage(Message message, Stream stream)
{
if (message == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("message"));
}
if (stream == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("stream"));
}
EventTraceActivity eventTraceActivity = null;
if (WcfEventSource.Instance.BinaryMessageEncodingStartIsEnabled())
{
eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(message);
WcfEventSource.Instance.BinaryMessageEncodingStart(eventTraceActivity);
}
CompressionFormat compressionFormat = this.CheckCompressedWrite(message);
if (compressionFormat != CompressionFormat.None)
{
stream = MessageEncoderCompressionHandler.GetCompressStream(stream, compressionFormat);
}
ThrowIfMismatchedMessageVersion(message);
message.Properties.Encoder = this;
XmlDictionaryWriter xmlWriter = _factory.TakeStreamedWriter(stream);
message.WriteMessage(xmlWriter);
xmlWriter.Flush();
if (WcfEventSource.Instance.StreamedMessageWrittenByEncoderIsEnabled())
{
WcfEventSource.Instance.StreamedMessageWrittenByEncoder(eventTraceActivity ?? EventTraceActivityHelper.TryExtractActivity(message));
}
_factory.ReturnStreamedWriter(xmlWriter);
if (MessageLogger.LogMessagesAtTransportLevel)
{
MessageLogger.LogMessage(ref message, MessageLoggingSource.TransportSend);
}
if (compressionFormat != CompressionFormat.None)
{
// Stream.Close() has been replaced with Dispose()
stream.Dispose();
}
}
public override bool IsContentTypeSupported(string contentType)
{
bool supported = true;
if (!base.IsContentTypeSupported(contentType))
{
if (this.CompressionEnabled)
{
supported = (_factory.CompressionFormat == CompressionFormat.GZip &&
base.IsContentTypeSupported(contentType, _gzipCompressedContentType, _gzipCompressedContentType)) ||
(_factory.CompressionFormat == CompressionFormat.Deflate &&
base.IsContentTypeSupported(contentType, _deflateCompressedContentType, _deflateCompressedContentType)) ||
base.IsContentTypeSupported(contentType, _normalContentType, _normalContentType);
}
else
{
supported = false;
}
}
return supported;
}
public void SetSessionContentType(string contentType)
{
if (base.IsContentTypeSupported(contentType, _gzipCompressedContentType, _gzipCompressedContentType))
{
_sessionCompressionFormat = CompressionFormat.GZip;
}
else if (base.IsContentTypeSupported(contentType, _deflateCompressedContentType, _deflateCompressedContentType))
{
_sessionCompressionFormat = CompressionFormat.Deflate;
}
else
{
_sessionCompressionFormat = CompressionFormat.None;
}
}
public void AddCompressedMessageProperties(Message message, string supportedCompressionTypes)
{
message.Properties.Add(SupportedCompressionTypesMessageProperty, supportedCompressionTypes);
}
private static bool ContentTypeEqualsOrStartsWith(string contentType, string supportedContentType)
{
return contentType == supportedContentType || contentType.StartsWith(supportedContentType, StringComparison.OrdinalIgnoreCase);
}
private CompressionFormat CheckContentType(string contentType)
{
CompressionFormat compressionFormat = CompressionFormat.None;
if (contentType == null)
{
compressionFormat = _sessionCompressionFormat;
}
else
{
if (!this.CompressionEnabled)
{
if (!ContentTypeEqualsOrStartsWith(contentType, this.ContentType))
{
throw FxTrace.Exception.AsError(new ProtocolException(string.Format(SRServiceModel.EncoderUnrecognizedContentType, contentType, this.ContentType)));
}
}
else
{
if (_factory.CompressionFormat == CompressionFormat.GZip && ContentTypeEqualsOrStartsWith(contentType, _gzipCompressedContentType))
{
compressionFormat = CompressionFormat.GZip;
}
else if (_factory.CompressionFormat == CompressionFormat.Deflate && ContentTypeEqualsOrStartsWith(contentType, _deflateCompressedContentType))
{
compressionFormat = CompressionFormat.Deflate;
}
else if (ContentTypeEqualsOrStartsWith(contentType, _normalContentType))
{
compressionFormat = CompressionFormat.None;
}
else
{
throw FxTrace.Exception.AsError(new ProtocolException(string.Format(SRServiceModel.EncoderUnrecognizedContentType, contentType, this.ContentType)));
}
}
}
return compressionFormat;
}
private CompressionFormat CheckCompressedWrite(Message message)
{
CompressionFormat compressionFormat = _sessionCompressionFormat;
if (compressionFormat != CompressionFormat.None && !_isSession)
{
string acceptEncoding;
if (message.Properties.TryGetValue<string>(SupportedCompressionTypesMessageProperty, out acceptEncoding) &&
acceptEncoding != null)
{
acceptEncoding = acceptEncoding.ToLowerInvariant();
if ((compressionFormat == CompressionFormat.GZip &&
!acceptEncoding.Contains(MessageEncoderCompressionHandler.GZipContentEncoding)) ||
(compressionFormat == CompressionFormat.Deflate &&
!acceptEncoding.Contains(MessageEncoderCompressionHandler.DeflateContentEncoding)))
{
compressionFormat = CompressionFormat.None;
}
}
}
return compressionFormat;
}
}
internal class XmlBinaryWriterSessionWithQuota : XmlBinaryWriterSession
{
private int _bytesRemaining;
private List<XmlDictionaryString> _newStrings;
public XmlBinaryWriterSessionWithQuota(int maxSessionSize)
{
_bytesRemaining = maxSessionSize;
}
public bool HasNewStrings
{
get { return _newStrings != null; }
}
public override bool TryAdd(XmlDictionaryString s, out int key)
{
if (_bytesRemaining == 0)
{
key = -1;
return false;
}
int bytesRequired = Encoding.UTF8.GetByteCount(s.Value);
bytesRequired += IntEncoder.GetEncodedSize(bytesRequired);
if (bytesRequired > _bytesRemaining)
{
key = -1;
_bytesRemaining = 0;
return false;
}
if (base.TryAdd(s, out key))
{
if (_newStrings == null)
{
_newStrings = new List<XmlDictionaryString>();
}
_newStrings.Add(s);
_bytesRemaining -= bytesRequired;
return true;
}
else
{
return false;
}
}
public IList<XmlDictionaryString> GetNewStrings()
{
return _newStrings;
}
public void ClearNewStrings()
{
_newStrings = null;
}
}
}
internal class BinaryFormatBuilder
{
private List<byte> _bytes;
public BinaryFormatBuilder()
{
_bytes = new List<byte>();
}
public int Count
{
get { return _bytes.Count; }
}
public void AppendPrefixDictionaryElement(char prefix, int key)
{
this.AppendNode(XmlBinaryNodeType.PrefixDictionaryElementA + GetPrefixOffset(prefix));
this.AppendKey(key);
}
public void AppendDictionaryXmlnsAttribute(char prefix, int key)
{
this.AppendNode(XmlBinaryNodeType.DictionaryXmlnsAttribute);
this.AppendUtf8(prefix);
this.AppendKey(key);
}
public void AppendPrefixDictionaryAttribute(char prefix, int key, char value)
{
this.AppendNode(XmlBinaryNodeType.PrefixDictionaryAttributeA + GetPrefixOffset(prefix));
this.AppendKey(key);
if (value == '1')
{
this.AppendNode(XmlBinaryNodeType.OneText);
}
else
{
this.AppendNode(XmlBinaryNodeType.Chars8Text);
this.AppendUtf8(value);
}
}
public void AppendDictionaryAttribute(char prefix, int key, char value)
{
this.AppendNode(XmlBinaryNodeType.DictionaryAttribute);
this.AppendUtf8(prefix);
this.AppendKey(key);
this.AppendNode(XmlBinaryNodeType.Chars8Text);
this.AppendUtf8(value);
}
public void AppendDictionaryTextWithEndElement(int key)
{
this.AppendNode(XmlBinaryNodeType.DictionaryTextWithEndElement);
this.AppendKey(key);
}
public void AppendDictionaryTextWithEndElement()
{
this.AppendNode(XmlBinaryNodeType.DictionaryTextWithEndElement);
}
public void AppendUniqueIDWithEndElement()
{
this.AppendNode(XmlBinaryNodeType.UniqueIdTextWithEndElement);
}
public void AppendEndElement()
{
this.AppendNode(XmlBinaryNodeType.EndElement);
}
private void AppendKey(int key)
{
if (key < 0 || key >= 0x4000)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("key", key,
string.Format(SRServiceModel.ValueMustBeInRange, 0, 0x4000)));
}
if (key >= 0x80)
{
this.AppendByte((key & 0x7f) | 0x80);
this.AppendByte(key >> 7);
}
else
{
this.AppendByte(key);
}
}
private void AppendNode(XmlBinaryNodeType value)
{
this.AppendByte((int)value);
}
private void AppendByte(int value)
{
if (value < 0 || value > 0xFF)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
string.Format(SRServiceModel.ValueMustBeInRange, 0, 0xFF)));
}
_bytes.Add((byte)value);
}
private void AppendUtf8(char value)
{
AppendByte(1);
AppendByte((int)value);
}
public int GetStaticKey(int value)
{
return value * 2;
}
public int GetSessionKey(int value)
{
return value * 2 + 1;
}
private int GetPrefixOffset(char prefix)
{
if (prefix < 'a' && prefix > 'z')
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("prefix", prefix,
string.Format(SRServiceModel.ValueMustBeInRange, 'a', 'z')));
}
return prefix - 'a';
}
public byte[] ToByteArray()
{
byte[] array = _bytes.ToArray();
_bytes.Clear();
return array;
}
}
internal static class BinaryFormatParser
{
public static bool IsSessionKey(int value)
{
return (value & 1) != 0;
}
public static int GetSessionKey(int value)
{
return value / 2;
}
public static int GetStaticKey(int value)
{
return value / 2;
}
public static int ParseInt32(byte[] buffer, int offset, int size)
{
switch (size)
{
case 1:
return buffer[offset];
case 2:
return (buffer[offset] & 0x7f) + (buffer[offset + 1] << 7);
case 3:
return (buffer[offset] & 0x7f) + ((buffer[offset + 1] & 0x7f) << 7) + (buffer[offset + 2] << 14);
case 4:
return (buffer[offset] & 0x7f) + ((buffer[offset + 1] & 0x7f) << 7) + ((buffer[offset + 2] & 0x7f) << 14) + (buffer[offset + 3] << 21);
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("size", size,
string.Format(SRServiceModel.ValueMustBeInRange, 1, 4)));
}
}
public static int ParseKey(byte[] buffer, int offset, int size)
{
return ParseInt32(buffer, offset, size);
}
public unsafe static UniqueId ParseUniqueID(byte[] buffer, int offset, int size)
{
return new UniqueId(buffer, offset);
}
public static int MatchBytes(byte[] buffer, int offset, int size, byte[] buffer2)
{
if (size < buffer2.Length)
{
return 0;
}
int j = offset;
for (int i = 0; i < buffer2.Length; i++, j++)
{
if (buffer2[i] != buffer[j])
{
return 0;
}
}
return buffer2.Length;
}
public static bool MatchAttributeNode(byte[] buffer, int offset, int size)
{
const XmlBinaryNodeType minAttribute = XmlBinaryNodeType.ShortAttribute;
const XmlBinaryNodeType maxAttribute = XmlBinaryNodeType.DictionaryAttribute;
if (size < 1)
{
return false;
}
XmlBinaryNodeType nodeType = (XmlBinaryNodeType)buffer[offset];
return nodeType >= minAttribute && nodeType <= maxAttribute;
}
public static int MatchKey(byte[] buffer, int offset, int size)
{
return MatchInt32(buffer, offset, size);
}
public static int MatchInt32(byte[] buffer, int offset, int size)
{
if (size > 0)
{
if ((buffer[offset] & 0x80) == 0)
{
return 1;
}
}
if (size > 1)
{
if ((buffer[offset + 1] & 0x80) == 0)
{
return 2;
}
}
if (size > 2)
{
if ((buffer[offset + 2] & 0x80) == 0)
{
return 3;
}
}
if (size > 3)
{
if ((buffer[offset + 3] & 0x80) == 0)
{
return 4;
}
}
return 0;
}
public static int MatchUniqueID(byte[] buffer, int offset, int size)
{
if (size < 16)
{
return 0;
}
return 16;
}
}
internal class MessagePatterns
{
private static readonly byte[] s_commonFragment; // <Envelope><Headers><Action>
private static readonly byte[] s_requestFragment1; // </Action><MessageID>
private static readonly byte[] s_requestFragment2; // </MessageID><ReplyTo>...</ReplyTo><To>session-to-key</To></Headers><Body>
private static readonly byte[] s_responseFragment1; // </Action><RelatesTo>
private static readonly byte[] s_responseFragment2; // </RelatesTo><To>static-anonymous-key</To></Headers><Body>
private static readonly byte[] s_bodyFragment; // <Envelope><Body>
private const int ToValueSessionKey = 1;
private IXmlDictionary _dictionary;
private XmlBinaryReaderSession _readerSession;
private ToHeader _toHeader;
private MessageVersion _messageVersion;
static MessagePatterns()
{
BinaryFormatBuilder builder = new BinaryFormatBuilder();
MessageDictionary messageDictionary = XD.MessageDictionary;
Message12Dictionary message12Dictionary = XD.Message12Dictionary;
AddressingDictionary addressingDictionary = XD.AddressingDictionary;
Addressing10Dictionary addressing10Dictionary = XD.Addressing10Dictionary;
char messagePrefix = MessageStrings.Prefix[0];
char addressingPrefix = AddressingStrings.Prefix[0];
// <s:Envelope xmlns:s="soap-ns" xmlns="addressing-ns">
builder.AppendPrefixDictionaryElement(messagePrefix, builder.GetStaticKey(messageDictionary.Envelope.Key));
builder.AppendDictionaryXmlnsAttribute(messagePrefix, builder.GetStaticKey(message12Dictionary.Namespace.Key));
builder.AppendDictionaryXmlnsAttribute(addressingPrefix, builder.GetStaticKey(addressing10Dictionary.Namespace.Key));
// <s:Header>
builder.AppendPrefixDictionaryElement(messagePrefix, builder.GetStaticKey(messageDictionary.Header.Key));
// <a:Action>...
builder.AppendPrefixDictionaryElement(addressingPrefix, builder.GetStaticKey(addressingDictionary.Action.Key));
builder.AppendPrefixDictionaryAttribute(messagePrefix, builder.GetStaticKey(messageDictionary.MustUnderstand.Key), '1');
builder.AppendDictionaryTextWithEndElement();
s_commonFragment = builder.ToByteArray();
// <a:MessageID>...
builder.AppendPrefixDictionaryElement(addressingPrefix, builder.GetStaticKey(addressingDictionary.MessageId.Key));
builder.AppendUniqueIDWithEndElement();
s_requestFragment1 = builder.ToByteArray();
// <a:ReplyTo><a:Address>static-anonymous-key</a:Address></a:ReplyTo>
builder.AppendPrefixDictionaryElement(addressingPrefix, builder.GetStaticKey(addressingDictionary.ReplyTo.Key));
builder.AppendPrefixDictionaryElement(addressingPrefix, builder.GetStaticKey(addressingDictionary.Address.Key));
builder.AppendDictionaryTextWithEndElement(builder.GetStaticKey(addressing10Dictionary.Anonymous.Key));
builder.AppendEndElement();
// <a:To>session-to-key</a:To>
builder.AppendPrefixDictionaryElement(addressingPrefix, builder.GetStaticKey(addressingDictionary.To.Key));
builder.AppendPrefixDictionaryAttribute(messagePrefix, builder.GetStaticKey(messageDictionary.MustUnderstand.Key), '1');
builder.AppendDictionaryTextWithEndElement(builder.GetSessionKey(ToValueSessionKey));
// </s:Header>
builder.AppendEndElement();
// <s:Body>
builder.AppendPrefixDictionaryElement(messagePrefix, builder.GetStaticKey(messageDictionary.Body.Key));
s_requestFragment2 = builder.ToByteArray();
// <a:RelatesTo>...
builder.AppendPrefixDictionaryElement(addressingPrefix, builder.GetStaticKey(addressingDictionary.RelatesTo.Key));
builder.AppendUniqueIDWithEndElement();
s_responseFragment1 = builder.ToByteArray();
// <a:To>static-anonymous-key</a:To>
builder.AppendPrefixDictionaryElement(addressingPrefix, builder.GetStaticKey(addressingDictionary.To.Key));
builder.AppendPrefixDictionaryAttribute(messagePrefix, builder.GetStaticKey(messageDictionary.MustUnderstand.Key), '1');
builder.AppendDictionaryTextWithEndElement(builder.GetStaticKey(addressing10Dictionary.Anonymous.Key));
// </s:Header>
builder.AppendEndElement();
// <s:Body>
builder.AppendPrefixDictionaryElement(messagePrefix, builder.GetStaticKey(messageDictionary.Body.Key));
s_responseFragment2 = builder.ToByteArray();
// <s:Envelope xmlns:s="soap-ns" xmlns="addressing-ns">
builder.AppendPrefixDictionaryElement(messagePrefix, builder.GetStaticKey(messageDictionary.Envelope.Key));
builder.AppendDictionaryXmlnsAttribute(messagePrefix, builder.GetStaticKey(message12Dictionary.Namespace.Key));
builder.AppendDictionaryXmlnsAttribute(addressingPrefix, builder.GetStaticKey(addressing10Dictionary.Namespace.Key));
// <s:Body>
builder.AppendPrefixDictionaryElement(messagePrefix, builder.GetStaticKey(messageDictionary.Body.Key));
s_bodyFragment = builder.ToByteArray();
}
public MessagePatterns(IXmlDictionary dictionary, XmlBinaryReaderSession readerSession, MessageVersion messageVersion)
{
_dictionary = dictionary;
_readerSession = readerSession;
_messageVersion = messageVersion;
}
public Message TryCreateMessage(byte[] buffer, int offset, int size, BufferManager bufferManager, BufferedMessageData messageData)
{
RelatesToHeader relatesToHeader;
MessageIDHeader messageIDHeader;
XmlDictionaryString toString;
int currentOffset = offset;
int remainingSize = size;
int bytesMatched = BinaryFormatParser.MatchBytes(buffer, currentOffset, remainingSize, s_commonFragment);
if (bytesMatched == 0)
{
return null;
}
currentOffset += bytesMatched;
remainingSize -= bytesMatched;
bytesMatched = BinaryFormatParser.MatchKey(buffer, currentOffset, remainingSize);
if (bytesMatched == 0)
{
return null;
}
int actionOffset = currentOffset;
int actionSize = bytesMatched;
currentOffset += bytesMatched;
remainingSize -= bytesMatched;
int totalBytesMatched;
bytesMatched = BinaryFormatParser.MatchBytes(buffer, currentOffset, remainingSize, s_requestFragment1);
if (bytesMatched != 0)
{
currentOffset += bytesMatched;
remainingSize -= bytesMatched;
bytesMatched = BinaryFormatParser.MatchUniqueID(buffer, currentOffset, remainingSize);
if (bytesMatched == 0)
{
return null;
}
int messageIDOffset = currentOffset;
int messageIDSize = bytesMatched;
currentOffset += bytesMatched;
remainingSize -= bytesMatched;
bytesMatched = BinaryFormatParser.MatchBytes(buffer, currentOffset, remainingSize, s_requestFragment2);
if (bytesMatched == 0)
{
return null;
}
currentOffset += bytesMatched;
remainingSize -= bytesMatched;
if (BinaryFormatParser.MatchAttributeNode(buffer, currentOffset, remainingSize))
{
return null;
}
UniqueId messageId = BinaryFormatParser.ParseUniqueID(buffer, messageIDOffset, messageIDSize);
messageIDHeader = MessageIDHeader.Create(messageId, _messageVersion.Addressing);
relatesToHeader = null;
if (!_readerSession.TryLookup(ToValueSessionKey, out toString))
{
return null;
}
totalBytesMatched = s_requestFragment1.Length + messageIDSize + s_requestFragment2.Length;
}
else
{
bytesMatched = BinaryFormatParser.MatchBytes(buffer, currentOffset, remainingSize, s_responseFragment1);
if (bytesMatched == 0)
{
return null;
}
currentOffset += bytesMatched;
remainingSize -= bytesMatched;
bytesMatched = BinaryFormatParser.MatchUniqueID(buffer, currentOffset, remainingSize);
if (bytesMatched == 0)
{
return null;
}
int messageIDOffset = currentOffset;
int messageIDSize = bytesMatched;
currentOffset += bytesMatched;
remainingSize -= bytesMatched;
bytesMatched = BinaryFormatParser.MatchBytes(buffer, currentOffset, remainingSize, s_responseFragment2);
if (bytesMatched == 0)
{
return null;
}
currentOffset += bytesMatched;
remainingSize -= bytesMatched;
if (BinaryFormatParser.MatchAttributeNode(buffer, currentOffset, remainingSize))
{
return null;
}
UniqueId messageId = BinaryFormatParser.ParseUniqueID(buffer, messageIDOffset, messageIDSize);
relatesToHeader = RelatesToHeader.Create(messageId, _messageVersion.Addressing);
messageIDHeader = null;
toString = XD.Addressing10Dictionary.Anonymous;
totalBytesMatched = s_responseFragment1.Length + messageIDSize + s_responseFragment2.Length;
}
totalBytesMatched += s_commonFragment.Length + actionSize;
int actionKey = BinaryFormatParser.ParseKey(buffer, actionOffset, actionSize);
XmlDictionaryString actionString;
if (!TryLookupKey(actionKey, out actionString))
{
return null;
}
ActionHeader actionHeader = ActionHeader.Create(actionString, _messageVersion.Addressing);
if (_toHeader == null)
{
_toHeader = ToHeader.Create(new Uri(toString.Value), _messageVersion.Addressing);
}
int abandonedSize = totalBytesMatched - s_bodyFragment.Length;
offset += abandonedSize;
size -= abandonedSize;
Buffer.BlockCopy(s_bodyFragment, 0, buffer, offset, s_bodyFragment.Length);
messageData.Open(new ArraySegment<byte>(buffer, offset, size), bufferManager);
PatternMessage patternMessage = new PatternMessage(messageData, _messageVersion);
MessageHeaders headers = patternMessage.Headers;
headers.AddActionHeader(actionHeader);
if (messageIDHeader != null)
{
headers.AddMessageIDHeader(messageIDHeader);
headers.AddReplyToHeader(ReplyToHeader.AnonymousReplyTo10);
}
else
{
headers.AddRelatesToHeader(relatesToHeader);
}
headers.AddToHeader(_toHeader);
return patternMessage;
}
private bool TryLookupKey(int key, out XmlDictionaryString result)
{
if (BinaryFormatParser.IsSessionKey(key))
{
return _readerSession.TryLookup(BinaryFormatParser.GetSessionKey(key), out result);
}
else
{
return _dictionary.TryLookup(BinaryFormatParser.GetStaticKey(key), out result);
}
}
internal sealed class PatternMessage : ReceivedMessage
{
private IBufferedMessageData _messageData;
private MessageHeaders _headers;
private RecycledMessageState _recycledMessageState;
private MessageProperties _properties;
private XmlDictionaryReader _reader;
public PatternMessage(IBufferedMessageData messageData, MessageVersion messageVersion)
{
_messageData = messageData;
_recycledMessageState = messageData.TakeMessageState();
if (_recycledMessageState == null)
{
_recycledMessageState = new RecycledMessageState();
}
_properties = _recycledMessageState.TakeProperties();
if (_properties == null)
{
_properties = new MessageProperties();
}
_headers = _recycledMessageState.TakeHeaders();
if (_headers == null)
{
_headers = new MessageHeaders(messageVersion);
}
else
{
_headers.Init(messageVersion);
}
XmlDictionaryReader reader = messageData.GetMessageReader();
reader.ReadStartElement();
VerifyStartBody(reader, messageVersion.Envelope);
ReadStartBody(reader);
_reader = reader;
}
public PatternMessage(IBufferedMessageData messageData, MessageVersion messageVersion,
KeyValuePair<string, object>[] properties, MessageHeaders headers)
{
_messageData = messageData;
_messageData.Open();
_recycledMessageState = _messageData.TakeMessageState();
if (_recycledMessageState == null)
{
_recycledMessageState = new RecycledMessageState();
}
_properties = _recycledMessageState.TakeProperties();
if (_properties == null)
{
_properties = new MessageProperties();
}
if (properties != null)
{
_properties.CopyProperties(properties);
}
_headers = _recycledMessageState.TakeHeaders();
if (_headers == null)
{
_headers = new MessageHeaders(messageVersion);
}
if (headers != null)
{
_headers.CopyHeadersFrom(headers);
}
XmlDictionaryReader reader = messageData.GetMessageReader();
reader.ReadStartElement();
VerifyStartBody(reader, messageVersion.Envelope);
ReadStartBody(reader);
_reader = reader;
}
public override MessageHeaders Headers
{
get
{
if (IsDisposed)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateMessageDisposedException());
}
return _headers;
}
}
public override MessageProperties Properties
{
get
{
if (IsDisposed)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateMessageDisposedException());
}
return _properties;
}
}
public override MessageVersion Version
{
get
{
if (IsDisposed)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateMessageDisposedException());
}
return _headers.MessageVersion;
}
}
internal override RecycledMessageState RecycledMessageState
{
get { return _recycledMessageState; }
}
private XmlDictionaryReader GetBufferedReaderAtBody()
{
XmlDictionaryReader reader = _messageData.GetMessageReader();
reader.ReadStartElement();
reader.ReadStartElement();
return reader;
}
protected override void OnBodyToString(XmlDictionaryWriter writer)
{
using (XmlDictionaryReader reader = GetBufferedReaderAtBody())
{
while (reader.NodeType != XmlNodeType.EndElement)
{
writer.WriteNode(reader, false);
}
}
}
protected override void OnClose()
{
Exception ex = null;
try
{
base.OnClose();
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
ex = e;
}
try
{
_properties.Dispose();
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
if (ex == null)
{
ex = e;
}
}
try
{
if (_reader != null)
{
_reader.Dispose();
}
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
if (ex == null)
{
ex = e;
}
}
try
{
_recycledMessageState.ReturnHeaders(_headers);
_recycledMessageState.ReturnProperties(_properties);
_messageData.ReturnMessageState(_recycledMessageState);
_recycledMessageState = null;
_messageData.Close();
_messageData = null;
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
if (ex == null)
{
ex = e;
}
}
if (ex != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(ex);
}
}
protected override MessageBuffer OnCreateBufferedCopy(int maxBufferSize)
{
KeyValuePair<string, object>[] properties = new KeyValuePair<string, object>[Properties.Count];
((ICollection<KeyValuePair<string, object>>)Properties).CopyTo(properties, 0);
_messageData.EnableMultipleUsers();
return new PatternMessageBuffer(_messageData, this.Version, properties, _headers);
}
protected override XmlDictionaryReader OnGetReaderAtBodyContents()
{
XmlDictionaryReader reader = _reader;
_reader = null;
return reader;
}
protected override string OnGetBodyAttribute(string localName, string ns)
{
return null;
}
}
internal class PatternMessageBuffer : MessageBuffer
{
private bool _closed;
private MessageHeaders _headers;
private IBufferedMessageData _messageDataAtBody;
private MessageVersion _messageVersion;
private KeyValuePair<string, object>[] _properties;
private object _thisLock = new object();
private RecycledMessageState _recycledMessageState;
public PatternMessageBuffer(IBufferedMessageData messageDataAtBody, MessageVersion messageVersion,
KeyValuePair<string, object>[] properties, MessageHeaders headers)
{
_messageDataAtBody = messageDataAtBody;
_messageDataAtBody.Open();
_recycledMessageState = _messageDataAtBody.TakeMessageState();
if (_recycledMessageState == null)
{
_recycledMessageState = new RecycledMessageState();
}
_headers = _recycledMessageState.TakeHeaders();
if (_headers == null)
{
_headers = new MessageHeaders(messageVersion);
}
_headers.CopyHeadersFrom(headers);
_properties = properties;
_messageVersion = messageVersion;
}
public override int BufferSize
{
get
{
lock (this.ThisLock)
{
if (_closed)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateBufferDisposedException());
}
return _messageDataAtBody.Buffer.Count;
}
}
}
private object ThisLock
{
get
{
return _thisLock;
}
}
public override void Close()
{
lock (_thisLock)
{
if (!_closed)
{
_closed = true;
_recycledMessageState.ReturnHeaders(_headers);
_messageDataAtBody.ReturnMessageState(_recycledMessageState);
_messageDataAtBody.Close();
_recycledMessageState = null;
_messageDataAtBody = null;
_properties = null;
_messageVersion = null;
_headers = null;
}
}
}
public override Message CreateMessage()
{
lock (this.ThisLock)
{
if (_closed)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateBufferDisposedException());
}
return new PatternMessage(_messageDataAtBody, _messageVersion, _properties,
_headers);
}
}
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="ValidationTests.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: http://www.lhotka.net/cslanet/
// </copyright>
// <summary>no summary</summary>
//-----------------------------------------------------------------------
using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using Csla.Core;
using Csla.Rules;
using UnitDriven;
using Csla.Serialization;
#if NUNIT
using NUnit.Framework;
using TestClass = NUnit.Framework.TestFixtureAttribute;
using TestInitialize = NUnit.Framework.SetUpAttribute;
using TestCleanup = NUnit.Framework.TearDownAttribute;
using TestMethod = NUnit.Framework.TestAttribute;
#elif MSTEST
using Microsoft.VisualStudio.TestTools.UnitTesting;
#endif
namespace Csla.Test.ValidationRules
{
[TestClass()]
public class ValidationTests : TestBase
{
[TestMethod()]
public void TestValidationRulesWithPrivateMember()
{
//works now because we are calling ValidationRules.CheckRules() in DataPortal_Create
UnitTestContext context = GetContext();
Csla.ApplicationContext.GlobalContext.Clear();
HasRulesManager.NewHasRulesManager((o, e) =>
{
HasRulesManager root = e.Object;
context.Assert.AreEqual("<new>", root.Name);
context.Assert.AreEqual(true, root.IsValid, "should be valid on create");
context.Assert.AreEqual(0, root.BrokenRulesCollection.Count);
root.BeginEdit();
root.Name = "";
root.CancelEdit();
context.Assert.AreEqual("<new>", root.Name);
context.Assert.AreEqual(true, root.IsValid, "should be valid after CancelEdit");
context.Assert.AreEqual(0, root.BrokenRulesCollection.Count);
root.BeginEdit();
root.Name = "";
root.ApplyEdit();
context.Assert.AreEqual("", root.Name);
context.Assert.AreEqual(false, root.IsValid);
context.Assert.AreEqual(1, root.BrokenRulesCollection.Count);
context.Assert.AreEqual("Name required", root.BrokenRulesCollection[0].Description);
context.Assert.Success();
});
context.Complete();
}
[TestMethod()]
public void TestValidationRulesWithPublicProperty()
{
UnitTestContext context = GetContext();
//should work since ValidationRules.CheckRules() is called in DataPortal_Create
Csla.ApplicationContext.GlobalContext.Clear();
HasRulesManager2.NewHasRulesManager2((o, e) =>
{
HasRulesManager2 root = e.Object;
context.Assert.AreEqual("<new>", root.Name);
context.Assert.AreEqual(true, root.IsValid, "should be valid on create");
context.Assert.AreEqual(0, root.BrokenRulesCollection.Count);
root.BeginEdit();
root.Name = "";
root.CancelEdit();
context.Assert.AreEqual("<new>", root.Name);
context.Assert.AreEqual(true, root.IsValid, "should be valid after CancelEdit");
context.Assert.AreEqual(0, root.BrokenRulesCollection.Count);
root.BeginEdit();
root.Name = "";
root.ApplyEdit();
context.Assert.AreEqual("", root.Name);
context.Assert.AreEqual(false, root.IsValid);
context.Assert.AreEqual(1, root.BrokenRulesCollection.Count);
context.Assert.AreEqual("Name required", root.BrokenRulesCollection[0].Description);
context.Assert.AreEqual("Name required", root.BrokenRulesCollection.GetFirstMessage(HasRulesManager2.NameProperty).Description);
context.Assert.AreEqual("Name required", root.BrokenRulesCollection.GetFirstBrokenRule(HasRulesManager2.NameProperty).Description);
context.Assert.Success();
});
context.Complete();
}
[TestMethod()]
public void TestValidationAfterEditCycle()
{
//should work since ValidationRules.CheckRules() is called in DataPortal_Create
Csla.ApplicationContext.GlobalContext.Clear();
UnitTestContext context = GetContext();
HasRulesManager.NewHasRulesManager((o, e) =>
{
HasRulesManager root = e.Object;
context.Assert.AreEqual("<new>", root.Name);
context.Assert.AreEqual(true, root.IsValid, "should be valid on create");
context.Assert.AreEqual(0, root.BrokenRulesCollection.Count);
bool validationComplete = false;
root.ValidationComplete += (vo, ve) => { validationComplete = true; };
root.BeginEdit();
root.Name = "";
context.Assert.AreEqual("", root.Name);
context.Assert.AreEqual(false, root.IsValid);
context.Assert.AreEqual(1, root.BrokenRulesCollection.Count);
context.Assert.AreEqual("Name required", root.BrokenRulesCollection[0].Description);
context.Assert.IsTrue(validationComplete, "ValidationComplete should have run");
root.BeginEdit();
root.Name = "Begin 1";
context.Assert.AreEqual("Begin 1", root.Name);
context.Assert.AreEqual(true, root.IsValid);
context.Assert.AreEqual(0, root.BrokenRulesCollection.Count);
root.BeginEdit();
root.Name = "Begin 2";
context.Assert.AreEqual("Begin 2", root.Name);
context.Assert.AreEqual(true, root.IsValid);
context.Assert.AreEqual(0, root.BrokenRulesCollection.Count);
root.BeginEdit();
root.Name = "Begin 3";
context.Assert.AreEqual("Begin 3", root.Name);
context.Assert.AreEqual(true, root.IsValid);
context.Assert.AreEqual(0, root.BrokenRulesCollection.Count);
HasRulesManager hrmClone = root.Clone();
//Test validation rule cancels for both clone and cloned
root.CancelEdit();
context.Assert.AreEqual("Begin 2", root.Name);
context.Assert.AreEqual(true, root.IsValid);
context.Assert.AreEqual(0, root.BrokenRulesCollection.Count);
hrmClone.CancelEdit();
context.Assert.AreEqual("Begin 2", hrmClone.Name);
context.Assert.AreEqual(true, hrmClone.IsValid);
context.Assert.AreEqual(0, hrmClone.BrokenRulesCollection.Count);
root.CancelEdit();
context.Assert.AreEqual("Begin 1", root.Name);
context.Assert.AreEqual(true, root.IsValid);
context.Assert.AreEqual(0, root.BrokenRulesCollection.Count);
hrmClone.CancelEdit();
context.Assert.AreEqual("Begin 1", hrmClone.Name);
context.Assert.AreEqual(true, hrmClone.IsValid);
context.Assert.AreEqual(0, hrmClone.BrokenRulesCollection.Count);
root.CancelEdit();
context.Assert.AreEqual("", root.Name);
context.Assert.AreEqual(false, root.IsValid);
context.Assert.AreEqual(1, root.BrokenRulesCollection.Count);
context.Assert.AreEqual("Name required", root.BrokenRulesCollection[0].Description);
hrmClone.CancelEdit();
context.Assert.AreEqual("", hrmClone.Name);
context.Assert.AreEqual(false, hrmClone.IsValid);
context.Assert.AreEqual(1, hrmClone.BrokenRulesCollection.Count);
context.Assert.AreEqual("Name required", hrmClone.BrokenRulesCollection[0].Description);
root.CancelEdit();
context.Assert.AreEqual("<new>", root.Name);
context.Assert.AreEqual(true, root.IsValid);
context.Assert.AreEqual(0, root.BrokenRulesCollection.Count);
hrmClone.CancelEdit();
context.Assert.AreEqual("<new>", hrmClone.Name);
context.Assert.AreEqual(true, hrmClone.IsValid);
context.Assert.AreEqual(0, hrmClone.BrokenRulesCollection.Count);
context.Assert.Success();
});
context.Complete();
}
[TestMethod()]
public void TestValidationRulesAfterClone()
{
//this test uses HasRulesManager2, which assigns criteria._name to its public
//property in DataPortal_Create. If it used HasRulesManager, it would fail
//the first assert, but pass the others
Csla.ApplicationContext.GlobalContext.Clear();
UnitTestContext context = GetContext();
HasRulesManager2.NewHasRulesManager2((o, e) =>
{
context.Assert.Try(() =>
{
HasRulesManager2 root = e.Object;
context.Assert.AreEqual(true, root.IsValid);
root.BeginEdit();
root.Name = "";
root.ApplyEdit();
context.Assert.AreEqual(false, root.IsValid);
HasRulesManager2 rootClone = root.Clone();
context.Assert.AreEqual(false, rootClone.IsValid);
rootClone.Name = "something";
context.Assert.AreEqual(true, rootClone.IsValid);
context.Assert.Success();
});
});
context.Complete();
}
[TestMethod()]
[TestCategory("SkipWhenLiveUnitTesting")]
public void BreakRequiredRule()
{
Csla.ApplicationContext.GlobalContext.Clear();
UnitTestContext context = GetContext();
HasRulesManager.NewHasRulesManager((o, e) =>
{
context.Assert.Try(() =>
{
HasRulesManager root = e.Object;
root.Name = "";
context.Assert.AreEqual(false, root.IsValid, "should not be valid");
context.Assert.AreEqual(1, root.BrokenRulesCollection.Count);
context.Assert.AreEqual("Name required", root.BrokenRulesCollection[0].Description);
context.Assert.Success();
});
});
context.Complete();
}
[TestMethod()]
[TestCategory("SkipWhenLiveUnitTesting")]
public void BreakLengthRule()
{
Csla.ApplicationContext.GlobalContext.Clear();
UnitTestContext context = GetContext();
HasRulesManager.NewHasRulesManager((o, e) =>
{
HasRulesManager root = e.Object;
root.Name = "12345678901";
context.Assert.AreEqual(false, root.IsValid, "should not be valid");
context.Assert.AreEqual(1, root.BrokenRulesCollection.Count);
//Assert.AreEqual("Name too long", root.GetBrokenRulesCollection[0].Description);
Assert.AreEqual("Name can not exceed 10 characters", root.BrokenRulesCollection[0].Description);
root.Name = "1234567890";
context.Assert.AreEqual(true, root.IsValid, "should be valid");
context.Assert.AreEqual(0, root.BrokenRulesCollection.Count);
context.Assert.Success();
});
context.Complete();
}
[TestMethod()]
[TestCategory("SkipWhenLiveUnitTesting")]
public void BreakLengthRuleAndClone()
{
Csla.ApplicationContext.GlobalContext.Clear();
UnitTestContext context = GetContext();
HasRulesManager.NewHasRulesManager((o, e) =>
{
HasRulesManager root = e.Object;
root.Name = "12345678901";
context.Assert.AreEqual(false, root.IsValid, "should not be valid before clone");
context.Assert.AreEqual(1, root.BrokenRulesCollection.Count);
//Assert.AreEqual("Name too long", root.GetBrokenRulesCollection[0].Description;
Assert.AreEqual("Name can not exceed 10 characters", root.BrokenRulesCollection[0].Description);
root = (HasRulesManager)(root.Clone());
context.Assert.AreEqual(false, root.IsValid, "should not be valid after clone");
context.Assert.AreEqual(1, root.BrokenRulesCollection.Count);
//Assert.AreEqual("Name too long", root.GetBrokenRulesCollection[0].Description;
context.Assert.AreEqual("Name can not exceed 10 characters", root.BrokenRulesCollection[0].Description);
root.Name = "1234567890";
context.Assert.AreEqual(true, root.IsValid, "Should be valid");
context.Assert.AreEqual(0, root.BrokenRulesCollection.Count);
context.Assert.Success();
});
context.Complete();
}
[TestMethod()]
public void RegExSSN()
{
Csla.ApplicationContext.GlobalContext.Clear();
UnitTestContext context = GetContext();
HasRegEx root = new HasRegEx();
root.Ssn = "555-55-5555";
root.Ssn2 = "555-55-5555";
context.Assert.IsTrue(root.IsValid, "Ssn should be valid");
root.Ssn = "555-55-5555d";
context.Assert.IsFalse(root.IsValid, "Ssn should not be valid");
root.Ssn = "555-55-5555";
root.Ssn2 = "555-55-5555d";
context.Assert.IsFalse(root.IsValid, "Ssn should not be valid");
context.Assert.Success();
context.Complete();
}
[TestMethod]
public void MergeBrokenRules()
{
UnitTestContext context = GetContext();
var root = new BrokenRulesMergeRoot();
root.Validate();
Csla.Rules.BrokenRulesCollection list = root.BrokenRulesCollection;
context.Assert.AreEqual(2, list.Count, "Should have 2 broken rules");
context.Assert.AreEqual("rule://csla.test.validationrules.brokenrulesmergeroot-rulebroken/Test1", list[0].RuleName);
context.Assert.Success();
context.Complete();
}
[TestMethod]
public void VerifyUndoableStateStackOnClone()
{
Csla.ApplicationContext.GlobalContext.Clear();
using (UnitTestContext context = GetContext())
{
HasRulesManager2.NewHasRulesManager2((o, e) =>
{
context.Assert.IsNull(e.Error);
HasRulesManager2 root = e.Object;
string expected = root.Name;
root.BeginEdit();
root.Name = "";
HasRulesManager2 rootClone = root.Clone();
rootClone.CancelEdit();
string actual = rootClone.Name;
context.Assert.AreEqual(expected, actual);
context.Assert.Try(rootClone.ApplyEdit);
context.Assert.Success();
});
context.Complete();
}
}
[TestMethod()]
public void ListChangedEventTrigger()
{
Csla.ApplicationContext.GlobalContext.Clear();
UnitTestContext context = GetContext();
HasChildren.NewObject((o, e) =>
{
try
{
HasChildren root = e.Object;
context.Assert.AreEqual(false, root.IsValid);
root.BeginEdit();
root.ChildList.Add(Csla.DataPortal.CreateChild<Child>());
context.Assert.AreEqual(true, root.IsValid);
root.CancelEdit();
context.Assert.AreEqual(false, root.IsValid);
context.Assert.Success();
}
finally
{
context.Complete();
}
});
}
[TestMethod]
public void RuleThrowsException()
{
UnitTestContext context = GetContext();
var root = new HasBadRule();
root.Validate();
context.Assert.IsFalse(root.IsValid);
context.Assert.AreEqual(1, root.GetBrokenRules().Count);
#if WINDOWS_PHONE
context.Assert.AreEqual("rule://csla.test.validationrules.hasbadrule-badrule/null:InvalidOperationException", root.GetBrokenRules()[0].Description);
#else
context.Assert.AreEqual("rule://csla.test.validationrules.hasbadrule-badrule/(object):Operation is not valid due to the current state of the object.", root.GetBrokenRules()[0].Description);
#endif
context.Assert.Success();
context.Complete();
}
[TestMethod]
public void PrivateField()
{
UnitTestContext context = GetContext();
var root = new HasPrivateFields();
root.Validate();
context.Assert.IsFalse(root.IsValid);
root.Name = "abc";
context.Assert.IsTrue(root.IsValid);
context.Assert.Success();
context.Complete();
}
[TestMethod]
public void MinMaxValue()
{
var context = GetContext();
var root = Csla.DataPortal.Create<UsesCommonRules>();
context.Assert.AreEqual(1, root.Data);
context.Assert.IsFalse(root.IsValid);
context.Assert.IsTrue(root.BrokenRulesCollection[0].Description.Length > 0);
root.Data = 0;
context.Assert.IsFalse(root.IsValid);
root.Data = 20;
context.Assert.IsFalse(root.IsValid);
root.Data = 15;
context.Assert.IsTrue(root.IsValid);
context.Assert.Success();
context.Complete();
}
[TestMethod]
public void MinMaxNullableValue()
{
var context = GetContext();
var root = Csla.DataPortal.Create<MinMaxNullableRules>();
context.Assert.IsNull(root.DataNullable);
context.Assert.IsFalse(root.IsValid);
context.Assert.IsTrue(root.BrokenRulesCollection[0].Description.Length > 0);
root.DataNullable = 0;
context.Assert.IsFalse(root.IsValid);
root.DataNullable = 20;
context.Assert.IsFalse(root.IsValid);
root.DataNullable = 15;
context.Assert.IsTrue(root.IsValid);
context.Assert.Success();
context.Complete();
}
[TestMethod]
public void MinMaxLength()
{
var context = GetContext();
var root = Csla.DataPortal.Create<UsesCommonRules>();
root.Data = 15;
context.Assert.IsTrue(root.IsValid, "Should start valid");
root.MinCheck = "a";
context.Assert.IsFalse(root.IsValid, "Min too short");
root.MinCheck = "123456";
context.Assert.IsTrue(root.IsValid, "Min OK");
root.MaxCheck = "a";
context.Assert.IsTrue(root.IsValid, "Max OK");
root.MaxCheck = "123456";
context.Assert.IsFalse(root.IsValid, "Max too long");
context.Assert.Success();
context.Complete();
}
[TestMethod]
public void TwoRules()
{
var context = GetContext();
var root = new TwoPropertyRules();
var rule = new TwoProps(TwoPropertyRules.Value1Property, TwoPropertyRules.Value2Property);
var ctx = new Csla.Rules.RuleContext(null, rule, root,
new Dictionary<Core.IPropertyInfo, object> {
{ TwoPropertyRules.Value1Property, "a" },
{ TwoPropertyRules.Value2Property, "b" }
});
((Csla.Rules.IBusinessRule)rule).Execute(ctx);
context.Assert.AreEqual(0, ctx.Results.Count);
ctx = new Csla.Rules.RuleContext(null, rule, root,
new Dictionary<Core.IPropertyInfo, object> {
{ TwoPropertyRules.Value1Property, "" },
{ TwoPropertyRules.Value2Property, "a" }
});
((Csla.Rules.IBusinessRule)rule).Execute(ctx);
context.Assert.AreEqual(1, ctx.Results.Count);
context.Assert.Success();
context.Complete();
}
[TestMethod]
public void CanHaveRuleOnLazyField()
{
var context = GetContext();
context.Assert.Try(() =>
{
var root = new HasLazyField();
root.CheckRules();
string broken;
var rootEI = (IDataErrorInfo)root;
broken = rootEI[HasLazyField.Value1Property.Name];
context.Assert.AreEqual("PrimaryProperty does not exist.", broken);
var value = root.Value1; // intializes field
root.CheckRules();
broken = rootEI[HasLazyField.Value1Property.Name];
context.Assert.AreEqual("PrimaryProperty has value.", broken);
context.Assert.Success();
});
context.Complete();
}
[TestMethod]
public void ObjectDirtyWhenOutputValueChangesPropertyValue()
{
var context = GetContext();
var root = new DirtyAfterOutValueChangesProperty();
context.Assert.IsFalse(root.IsDirty);
context.Assert.AreEqual("csla rocks", root.Value1);
root.CheckRules();
context.Assert.IsTrue(root.IsDirty);
context.Assert.AreEqual("CSLA ROCKS", root.Value1);
context.Assert.Success();
context.Complete();
}
[TestMethod]
public void ObjectNotDirtyWhenOutputValueDoNotChangePropertyValue()
{
var context = GetContext();
var root = new DirtyAfterOutValueChangesProperty("CSLA ROCKS");
context.Assert.IsFalse(root.IsDirty);
context.Assert.AreEqual("CSLA ROCKS", root.Value1);
root.CheckRules();
context.Assert.IsFalse(root.IsDirty);
context.Assert.AreEqual("CSLA ROCKS", root.Value1);
context.Assert.Success();
context.Complete();
}
}
[Serializable]
public class HasBadRule : BusinessBase<HasBadRule>
{
public static PropertyInfo<int> IdProperty = RegisterProperty<int>(c => c.Id);
public int Id
{
get { return GetProperty(IdProperty); }
set { SetProperty(IdProperty, value); }
}
public void Validate()
{
BusinessRules.CheckRules();
}
public new Rules.BrokenRulesCollection GetBrokenRules()
{
return BusinessRules.GetBrokenRules();
}
protected override void AddBusinessRules()
{
base.AddBusinessRules();
BusinessRules.AddRule(new BadRule());
}
private class BadRule : Rules.BusinessRule
{
protected override void Execute(Rules.IRuleContext context)
{
throw new InvalidOperationException();
}
}
}
[Serializable]
public class HasPrivateFields : BusinessBase<HasPrivateFields>
{
public static PropertyInfo<string> NameProperty = RegisterProperty<string>(c => c.Name, RelationshipTypes.PrivateField);
private string _name = NameProperty.DefaultValue;
public string Name
{
get { return GetProperty(NameProperty, _name); }
set { SetProperty(NameProperty, ref _name, value); }
}
public void Validate()
{
BusinessRules.CheckRules();
}
protected override object ReadProperty(Core.IPropertyInfo propertyInfo)
{
if (ReferenceEquals(propertyInfo, NameProperty))
return _name;
else
return base.ReadProperty(propertyInfo);
}
protected override void AddBusinessRules()
{
base.AddBusinessRules();
BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(NameProperty));
}
}
[Serializable]
public class UsesCommonRules : BusinessBase<UsesCommonRules>
{
private static PropertyInfo<int> DataProperty = RegisterProperty<int>(c => c.Data, null, 1);
public int Data
{
get { return GetProperty(DataProperty); }
set { SetProperty(DataProperty, value); }
}
private static PropertyInfo<string> MinCheckProperty = RegisterProperty<string>(c => c.MinCheck, null, "123456");
public string MinCheck
{
get { return GetProperty(MinCheckProperty); }
set { SetProperty(MinCheckProperty, value); }
}
private static PropertyInfo<string> MaxCheckProperty = RegisterProperty<string>(c => c.MaxCheck);
public string MaxCheck
{
get { return GetProperty(MaxCheckProperty); }
set { SetProperty(MaxCheckProperty, value); }
}
protected override void AddBusinessRules()
{
base.AddBusinessRules();
BusinessRules.AddRule(new Csla.Rules.CommonRules.MinValue<int>(DataProperty, 5));
BusinessRules.AddRule(new Csla.Rules.CommonRules.MaxValue<int>(DataProperty, 15));
BusinessRules.AddRule(new Csla.Rules.CommonRules.MinLength(MinCheckProperty, 5));
BusinessRules.AddRule(new Csla.Rules.CommonRules.MaxLength(MaxCheckProperty, 5));
}
}
[Serializable]
public class MinMaxNullableRules : BusinessBase<MinMaxNullableRules>
{
private static PropertyInfo<int?> DataNullableProperty = RegisterProperty<int?>(c => c.DataNullable);
public int? DataNullable
{
get { return GetProperty(DataNullableProperty); }
set { SetProperty(DataNullableProperty, value); }
}
protected override void AddBusinessRules()
{
base.AddBusinessRules();
BusinessRules.AddRule(new Csla.Rules.CommonRules.MinValue<int>(DataNullableProperty, 5));
BusinessRules.AddRule(new Csla.Rules.CommonRules.MaxValue<int>(DataNullableProperty, 15));
}
}
[Serializable]
public class TwoPropertyRules : BusinessBase<TwoPropertyRules>
{
public static PropertyInfo<string> Value1Property = RegisterProperty<string>(c => c.Value1);
public string Value1
{
get { return GetProperty(Value1Property); }
set { SetProperty(Value1Property, value); }
}
public static PropertyInfo<string> Value2Property = RegisterProperty<string>(c => c.Value2);
public string Value2
{
get { return GetProperty(Value2Property); }
set { SetProperty(Value2Property, value); }
}
protected override void AddBusinessRules()
{
base.AddBusinessRules();
BusinessRules.AddRule(new TwoProps(Value1Property, Value2Property));
BusinessRules.AddRule(new TwoProps(Value2Property, Value1Property));
}
}
public class TwoProps : Csla.Rules.BusinessRule
{
public Csla.Core.IPropertyInfo SecondaryProperty { get; set; }
public TwoProps(Csla.Core.IPropertyInfo primaryProperty, Csla.Core.IPropertyInfo secondProperty)
: base(primaryProperty)
{
SecondaryProperty = secondProperty;
AffectedProperties.Add(SecondaryProperty);
InputProperties = new List<Core.IPropertyInfo> { PrimaryProperty, SecondaryProperty };
}
protected override void Execute(Rules.IRuleContext context)
{
var v1 = (string)context.InputPropertyValues[PrimaryProperty];
var v2 = (string)context.InputPropertyValues[SecondaryProperty];
if (string.IsNullOrEmpty(v1) || string.IsNullOrEmpty(v2))
context.AddErrorResult(string.Format("v1:{0}, v2:{1}", v1, v2));
}
}
[Serializable]
public class HasLazyField : BusinessBase<HasLazyField>
{
public static PropertyInfo<string> Value1Property = RegisterProperty<string>(c => c.Value1, RelationshipTypes.LazyLoad);
public string Value1
{
get
{
return LazyGetProperty(Value1Property, () => string.Empty);
//if (!FieldManager.FieldExists(Value1Property))
// SetProperty(Value1Property, string.Empty);
//return GetProperty(Value1Property);
}
set { SetProperty(Value1Property, value); }
}
protected override void AddBusinessRules()
{
base.AddBusinessRules();
BusinessRules.AddRule(new CheckLazyInputFieldExists(Value1Property));
}
public void CheckRules()
{
BusinessRules.CheckRules();
}
}
[Serializable]
public class DirtyAfterOutValueChangesProperty : BusinessBase<DirtyAfterOutValueChangesProperty>
{
public static PropertyInfo<string> Value1Property = RegisterProperty<string>(c => c.Value1);
public string Value1
{
get { return GetProperty(Value1Property); }
set { SetProperty(Value1Property, value); }
}
public DirtyAfterOutValueChangesProperty() : this("csla rocks")
{ }
public DirtyAfterOutValueChangesProperty(string value)
{
using (BypassPropertyChecks)
{
Value1 = value;
}
MarkOld();
MarkClean();
}
protected override void AddBusinessRules()
{
base.AddBusinessRules();
BusinessRules.AddRule(new ToUpper(Value1Property));
}
private class ToUpper : Csla.Rules.BusinessRule
{
public ToUpper(IPropertyInfo primaryProperty)
: base(primaryProperty)
{
InputProperties = new List<IPropertyInfo>(){primaryProperty};
}
protected override void Execute(IRuleContext context)
{
var value = (string) context.InputPropertyValues[PrimaryProperty];
context.AddOutValue(PrimaryProperty, value.ToUpperInvariant());
}
}
public void CheckRules()
{
BusinessRules.CheckRules();
}
}
public class CheckLazyInputFieldExists : Csla.Rules.BusinessRule
{
public CheckLazyInputFieldExists(Csla.Core.IPropertyInfo primaryProperty)
: base(primaryProperty)
{
InputProperties = new List<Core.IPropertyInfo> { primaryProperty };
}
protected override void Execute(Rules.IRuleContext context)
{
if (context.InputPropertyValues.ContainsKey(PrimaryProperty))
{
context.AddErrorResult("PrimaryProperty has value.");
}
else
{
context.AddErrorResult("PrimaryProperty does not exist.");
}
}
}
[TestClass]
public class RuleContextTests
{
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void AddErrorResultThrowsErrorWhenMessageIsEmpty()
{
var root = new TwoPropertyRules();
var rule = new TwoProps(TwoPropertyRules.Value1Property, TwoPropertyRules.Value2Property);
var ctx = new Csla.Rules.RuleContext(null, rule, root,
new Dictionary<Core.IPropertyInfo, object>
{
{TwoPropertyRules.Value1Property, "a"},
{TwoPropertyRules.Value2Property, "b"}
});
ctx.AddErrorResult(string.Empty, false);
Assert.Fail("Must throw exception.");
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void AddErrorResultOnPropertyThrowsErrorWhenMessageIsEmpty()
{
var root = new TwoPropertyRules();
var rule = new TwoProps(TwoPropertyRules.Value1Property, TwoPropertyRules.Value2Property);
var ctx = new Csla.Rules.RuleContext(null, rule, root,
new Dictionary<Core.IPropertyInfo, object>
{
{TwoPropertyRules.Value1Property, "a"},
{TwoPropertyRules.Value2Property, "b"}
});
ctx.AddErrorResult(TwoPropertyRules.Value1Property, string.Empty);
Assert.Fail("Must throw exception.");
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void AddWarningResultThrowsErrorWhenMessageIsEmpty()
{
var root = new TwoPropertyRules();
var rule = new TwoProps(TwoPropertyRules.Value1Property, TwoPropertyRules.Value2Property);
var ctx = new Csla.Rules.RuleContext(null, rule, root,
new Dictionary<Core.IPropertyInfo, object>
{
{TwoPropertyRules.Value1Property, "a"},
{TwoPropertyRules.Value2Property, "b"}
});
ctx.AddWarningResult(string.Empty, false);
Assert.Fail("Must throw exception.");
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void AddWarningResultOnPropertyThrowsErrorWhenMessageIsEmpty()
{
var root = new TwoPropertyRules();
var rule = new TwoProps(TwoPropertyRules.Value1Property, TwoPropertyRules.Value2Property);
var ctx = new Csla.Rules.RuleContext(null, rule, root,
new Dictionary<Core.IPropertyInfo, object>
{
{TwoPropertyRules.Value1Property, "a"},
{TwoPropertyRules.Value2Property, "b"}
});
ctx.AddWarningResult(TwoPropertyRules.Value1Property, string.Empty);
Assert.Fail("Must throw exception.");
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void AddInformationResultThrowsErrorWhenMessageIsEmpty()
{
var root = new TwoPropertyRules();
var rule = new TwoProps(TwoPropertyRules.Value1Property, TwoPropertyRules.Value2Property);
var ctx = new Csla.Rules.RuleContext(null, rule, root,
new Dictionary<Core.IPropertyInfo, object>
{
{TwoPropertyRules.Value1Property, "a"},
{TwoPropertyRules.Value2Property, "b"}
});
ctx.AddInformationResult(string.Empty, false);
Assert.Fail("Must throw exception.");
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void AddInformationResultOnPropertyThrowsErrorWhenMessageIsEmpty()
{
var root = new TwoPropertyRules();
var rule = new TwoProps(TwoPropertyRules.Value1Property, TwoPropertyRules.Value2Property);
var ctx = new Csla.Rules.RuleContext(null, rule, root,
new Dictionary<Core.IPropertyInfo, object>
{
{TwoPropertyRules.Value1Property, "a"},
{TwoPropertyRules.Value2Property, "b"}
});
ctx.AddInformationResult(TwoPropertyRules.Value1Property, string.Empty);
Assert.Fail("Must throw exception.");
}
[TestMethod]
public void AddSuccessResultDoesNotFail()
{
var root = new TwoPropertyRules();
var rule = new TwoProps(TwoPropertyRules.Value1Property, TwoPropertyRules.Value2Property);
var ctx = new Csla.Rules.RuleContext(null, rule, root,
new Dictionary<Core.IPropertyInfo, object>
{
{TwoPropertyRules.Value1Property, "a"},
{TwoPropertyRules.Value2Property, "b"}
});
ctx.AddSuccessResult(false);
Assert.IsTrue(true, "Must not fail.");
}
}
}
| |
/*
* DesignerHost.cs - IDesignerHost implementation. Designer transactions
* and service host. One level up from DesignContainer, tracks RootComponent.
*
* Authors:
* Michael Hutchinson <m.j.hutchinson@gmail.com>
*
* Copyright (C) 2005 Michael Hutchinson
*
* This sourcecode is licenced under The MIT License:
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
* NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
* USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Reflection;
using System.Collections;
using System.Drawing.Design;
using System.IO;
using System.Web.UI;
using System.Web.UI.Design;
using AspNetEdit.Editor.Persistence;
namespace AspNetEdit.Editor.ComponentModel
{
public class DesignerHost : IDesignerHost, IDisposable
{
private ServiceContainer parentServices;
private WebFormReferenceManager referenceManager;
public DesignerHost (ServiceContainer parentServices)
{
this.parentServices = parentServices;
container = new DesignContainer (this);
referenceManager = new WebFormReferenceManager (this);
//register services
parentServices.AddService (typeof (IDesignerHost), this);
parentServices.AddService (typeof (IComponentChangeService), container);
parentServices.AddService (typeof (IWebFormReferenceManager), referenceManager);
}
public WebFormReferenceManager WebFormReferenceManager
{
get { return referenceManager; }
}
#region Component management
private DesignContainer container;
private IComponent rootComponent = null;
private Document rootDocument;
public IContainer Container
{
get { return container; }
}
public IComponent CreateComponent (Type componentClass, string name)
{
Console.WriteLine("Attempting to create component "+name);
//check arguments
if (componentClass == null)
throw new ArgumentNullException ("componentClass");
if (!componentClass.IsSubclassOf (typeof (System.Web.UI.Control)) && componentClass != typeof (System.Web.UI.Control))
throw new ArgumentException ("componentClass must be a subclass of System.Web.UI.Control, but is a " + componentClass.ToString (), "componentClass");
if (componentClass.IsSubclassOf (typeof (System.Web.UI.Page)))
throw new InvalidOperationException ("You cannot directly add a page to the host. Use NewFile() instead");
//create the object
IComponent component = (IComponent) Activator.CreateInstance (componentClass);
//and add to container
container.Add (component, name);
//add to document, unless loading
if (RootDocument != null) {
((Control)RootComponent).Controls.Add ((Control) component);
RootDocument.AddControl ((Control)component);
}
//select it
ISelectionService sel = this.GetService (typeof (ISelectionService)) as ISelectionService;
if (sel != null)
sel.SetSelectedComponents (new IComponent[] {component});
return component;
}
public IComponent CreateComponent (Type componentClass)
{
return CreateComponent (componentClass, null);
}
public void DestroyComponent (IComponent component)
{
//deselect it if selected
ISelectionService sel = this.GetService (typeof (ISelectionService)) as ISelectionService;
bool found = false;
if (sel != null)
foreach (IComponent c in sel.GetSelectedComponents ())
if (c == component) {
found = true;
break;
}
//can't modify selection in loop
if (found) sel.SetSelectedComponents (null);
if (component != RootComponent) {
//remove from component and document
((Control) RootComponent).Controls.Remove ((Control) component);
RootDocument.RemoveControl ((Control)component);
}
//remove from container if still sited
if (component.Site != null)
container.Remove (component);
component.Dispose ();
}
public IDesigner GetDesigner (IComponent component)
{
if (component == null)
throw new ArgumentNullException ("component");
else
return container.GetDesigner (component);
}
public Type GetType (string typeName)
{
//use ITypeResolutionService if we have it, else Type.GetType();
object typeResSvc = GetService (typeof (ITypeResolutionService));
if (typeResSvc != null)
return (typeResSvc as ITypeResolutionService).GetType (typeName);
else
return Type.GetType (typeName);
}
public IComponent RootComponent {
get { return rootComponent; }
}
public Document RootDocument
{
get { return rootDocument; }
}
internal void SetRootComponent (IComponent rootComponent)
{
this.rootComponent = rootComponent;
if (rootComponent == null) {
rootDocument = null;
return;
}
if (!(rootComponent is Control))
throw new InvalidOperationException ("The root component must be a Control");
}
public string RootComponentClassName {
get { return RootComponent.GetType ().Name; }
}
#endregion
#region Transaction stuff
private Stack transactionStack = new Stack ();
public DesignerTransaction CreateTransaction (string description)
{
OnTransactionOpening ();
Transaction trans = new Transaction (this, description);
transactionStack.Push (trans);
OnTransactionOpened ();
return trans;
}
public DesignerTransaction CreateTransaction ()
{
return CreateTransaction (null);
}
public bool InTransaction
{
get { return (transactionStack.Count > 0); }
}
public string TransactionDescription
{
get {
if (transactionStack.Count == 0)
return null;
else
return (transactionStack.Peek () as DesignerTransaction).Description;
}
}
public event DesignerTransactionCloseEventHandler TransactionClosed;
public event DesignerTransactionCloseEventHandler TransactionClosing;
public event EventHandler TransactionOpened;
public event EventHandler TransactionOpening;
internal void OnTransactionClosed (bool commit, DesignerTransaction trans)
{
DesignerTransaction t = (DesignerTransaction) transactionStack.Pop();
if (t != trans)
throw new Exception ("Transactions cannot be closed out of order");
if (TransactionClosed != null)
TransactionClosed (this, new DesignerTransactionCloseEventArgs(commit));
}
internal void OnTransactionClosing (bool commit)
{
if (TransactionClosing != null)
TransactionClosing (this, new DesignerTransactionCloseEventArgs(commit));
}
protected void OnTransactionOpening()
{
if (TransactionOpening != null)
TransactionOpening (this, EventArgs.Empty);
}
protected void OnTransactionOpened ()
{
if (TransactionOpened != null)
TransactionOpened (this, EventArgs.Empty);
}
#endregion
#region Loading etc
private bool loading = false;
private bool activated = false;
public event EventHandler Activated;
public event EventHandler Deactivated;
public event EventHandler LoadComplete;
public void Activate ()
{
if (activated)
throw new InvalidOperationException ("The host is already activated");
//select the root component
ISelectionService sel = GetService (typeof (ISelectionService)) as ISelectionService;
if (sel == null)
throw new Exception ("Could not obtain ISelectionService.");
if (this.RootComponent == null)
throw new InvalidOperationException ("The document must be loaded before the host can be activated");
sel.SetSelectedComponents (new object[] {this.RootComponent});
activated = true;
OnActivated ();
}
public bool Loading {
get { return loading; }
}
protected void OnLoadComplete ()
{
if (LoadComplete != null)
LoadComplete (this, EventArgs.Empty);
}
protected void OnActivated ()
{
if (Activated != null)
Activated (this, EventArgs.Empty);
}
protected void OnDeactivated ()
{
if (Deactivated != null)
Deactivated (this, EventArgs.Empty);
}
#endregion
#region Wrapping parent ServiceContainer
public void AddService (Type serviceType, ServiceCreatorCallback callback, bool promote)
{
parentServices.AddService (serviceType, callback, promote);
}
public void AddService (Type serviceType, object serviceInstance, bool promote)
{
parentServices.AddService (serviceType, serviceInstance, promote);
}
public void AddService (Type serviceType, ServiceCreatorCallback callback)
{
parentServices.AddService (serviceType, callback);
}
public void AddService (Type serviceType, object serviceInstance)
{
parentServices.AddService (serviceType, serviceInstance);
}
public void RemoveService (Type serviceType, bool promote)
{
parentServices.RemoveService (serviceType, promote);
}
public void RemoveService (Type serviceType)
{
parentServices.RemoveService (serviceType);
}
public object GetService (Type serviceType)
{
object service = parentServices.GetService (serviceType);
if (service != null)
return service;
else
return null;
}
#endregion
#region IDisposable Members
private bool disposed = false;
public void Dispose ()
{
if (!this.disposed) {
//clean up the services we've registered
parentServices.RemoveService (typeof (IComponentChangeService));
parentServices.RemoveService (typeof (IDesignerHost));
//and the container
container.Dispose ();
disposed = true;
}
}
#endregion
public void NewFile ()
{
if (activated || RootComponent != null)
throw new InvalidOperationException ("You must reset the host before loading another file.");
loading = true;
this.Container.Add (new WebFormPage ());
this.rootDocument = new Document ((Control)rootComponent, this, "New Document");
loading = false;
OnLoadComplete ();
}
public void Load(Stream file, string fileName)
{
if (activated || RootComponent != null)
throw new InvalidOperationException ("You must reset the host before loading another file.");
loading = true;
this.Container.Add (new WebFormPage());
this.rootDocument = new Document ((Control)rootComponent, this, file, fileName);
loading = false;
OnLoadComplete ();
}
public void Reset ()
{
//container automatically destroys all children when this happens
if (rootComponent != null)
DestroyComponent (rootComponent);
if (activated) {
OnDeactivated ();
this.activated = false;
}
}
public void SaveDocument (Stream file)
{
StreamWriter writer = new StreamWriter (file);
writer.Write(RootDocument.PersistDocument ());
writer.Flush ();
}
/*TODO: Some .NET 2.0 System.Web.UI.Design.WebFormsRootDesigner methods
public abstract void RemoveControlFromDocument(Control control);
public virtual void SetControlID(Control control, string id);
public abstract string AddControlToDocument(Control newControl, Control referenceControl, ControlLocation location);
public virtual string GenerateEmptyDesignTimeHtml(Control control);
public virtual string GenerateErrorDesignTimeHtml(Control control, Exception e, string errorMessage);
*/
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using AutoMapper;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Commands.Common.Authentication;
using Microsoft.Azure.Commands.Common.Authentication.Models;
using Microsoft.WindowsAzure.Commands.Common;
using Microsoft.WindowsAzure.Commands.ServiceManagement.Model;
using Microsoft.WindowsAzure.Commands.Utilities.Properties;
using Microsoft.WindowsAzure.Management;
using Microsoft.WindowsAzure.Management.Compute;
using Microsoft.WindowsAzure.Management.Network;
using Microsoft.WindowsAzure.Management.Storage;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Management.Automation.Runspaces;
using System.ServiceModel;
using System.ServiceModel.Dispatcher;
namespace Microsoft.WindowsAzure.Commands.Utilities.Common
{
public abstract class ServiceManagementBaseCmdlet : CloudBaseCmdlet<IServiceManagement>
{
private Lazy<Runspace> runspace;
protected ServiceManagementBaseCmdlet()
{
IClientProvider clientProvider = new ClientProvider(this);
SetupClients(clientProvider);
}
private void SetupClients(IClientProvider clientProvider)
{
runspace = new Lazy<Runspace>(() =>
{
var localRunspace = RunspaceFactory.CreateRunspace(this.Host);
localRunspace.Open();
return localRunspace;
});
client = new Lazy<ManagementClient>(clientProvider.CreateClient);
computeClient = new Lazy<ComputeManagementClient>(clientProvider.CreateComputeClient);
storageClient = new Lazy<StorageManagementClient>(clientProvider.CreateStorageClient);
networkClient = new Lazy<NetworkManagementClient>(clientProvider.CreateNetworkClient);
}
protected ServiceManagementBaseCmdlet(IClientProvider clientProvider)
{
SetupClients(clientProvider);
}
private Lazy<ManagementClient> client;
public ManagementClient ManagementClient
{
get { return client.Value; }
}
private Lazy<ComputeManagementClient> computeClient;
public ComputeManagementClient ComputeClient
{
get { return computeClient.Value; }
}
private Lazy<StorageManagementClient> storageClient;
public StorageManagementClient StorageClient
{
get { return storageClient.Value; }
}
private Lazy<NetworkManagementClient> networkClient;
public NetworkManagementClient NetworkClient
{
get { return networkClient.Value; }
}
protected override void InitChannelCurrentSubscription(bool force)
{
// Do nothing for service management based cmdlets
}
protected OperationStatusResponse GetOperation(string operationId)
{
OperationStatusResponse operation = null;
try
{
operation = this.ManagementClient.GetOperationStatus(operationId);
if (operation.Status == OperationStatus.Failed)
{
var errorMessage = string.Format(CultureInfo.InvariantCulture, "{0}: {1}", operation.Status, operation.Error.Message);
throw new Exception(errorMessage);
}
}
catch (AggregateException ex)
{
if (ex.InnerException is CloudException)
{
WriteExceptionError(ex.InnerException);
}
else
{
WriteExceptionError(ex);
}
}
catch (Exception ex)
{
WriteExceptionError(ex);
}
return operation;
}
protected OperationStatusResponse GetOperation(AzureOperationResponse result)
{
OperationStatusResponse operation;
if (result is OperationStatusResponse)
{
operation = result as OperationStatusResponse;
}
else
{
operation = result == null ? null : GetOperation(result.RequestId);
}
return operation;
}
//TODO: Input argument is not used and should probably be removed.
protected void ExecuteClientActionNewSM<TResult>(object input, string operationDescription, Func<TResult> action, Func<OperationStatusResponse, TResult, object> contextFactory) where TResult : AzureOperationResponse
{
WriteVerboseWithTimestamp(Resources.ServiceManagementExecuteClientActionInOCSBeginOperation, operationDescription);
try
{
try
{
TResult result = action();
OperationStatusResponse operation = GetOperation(result);
var context = contextFactory(operation, result);
if (context != null)
{
WriteObject(context, true);
}
}
catch (CloudException ce)
{
throw new ComputeCloudException(ce);
}
}
catch (Exception ex)
{
WriteExceptionError(ex);
}
WriteVerboseWithTimestamp(Resources.ServiceManagementExecuteClientActionInOCSCompletedOperation, operationDescription);
}
protected void ExecuteClientActionNewSM<TResult>(object input, string operationDescription, Func<TResult> action) where TResult : AzureOperationResponse
{
this.ExecuteClientActionNewSM(input, operationDescription, action, (s, response) => this.ContextFactory<AzureOperationResponse, ManagementOperationContext>(response, s));
}
protected TDestination ContextFactory<TSource, TDestination>(TSource s1, OperationStatusResponse s2) where TDestination : ManagementOperationContext
{
TDestination result = Mapper.Map<TSource, TDestination>(s1);
result = Mapper.Map(s2, result);
result.OperationDescription = CommandRuntime.ToString();
return result;
}
protected void ExecuteClientAction(Action action)
{
try
{
try
{
action();
}
catch (CloudException ex)
{
throw new ComputeCloudException(ex);
}
}
catch (Exception ex)
{
WriteExceptionError(ex);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Orchard.Users.Indexes;
using Orchard.Users.Models;
using YesSql;
namespace Orchard.Users.Services
{
public class UserStore :
IUserStore<User>,
IUserRoleStore<User>,
IUserPasswordStore<User>,
IUserEmailStore<User>,
IUserSecurityStampStore<User>
{
private readonly ISession _session;
public UserStore(ISession session)
{
_session = session;
}
public void Dispose()
{
}
#region IUserStore<User>
public Task<IdentityResult> CreateAsync(User user, CancellationToken cancellationToken = default(CancellationToken))
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
_session.Save(user);
return Task.FromResult(IdentityResult.Success);
}
public async Task<IdentityResult> DeleteAsync(User user, CancellationToken cancellationToken = default(CancellationToken))
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
_session.Delete(user);
try
{
await _session.CommitAsync();
}
catch
{
return IdentityResult.Failed();
}
return IdentityResult.Success;
}
public Task<User> FindByIdAsync(string userId, CancellationToken cancellationToken = default(CancellationToken))
{
int id;
if(!int.TryParse(userId, out id))
{
return Task.FromResult<User>(null);
}
return _session.GetAsync<User>(id);
}
public Task<User> FindByNameAsync(string normalizedUserName, CancellationToken cancellationToken = default(CancellationToken))
{
return _session.Query<User, UserIndex>(u => u.NormalizedUserName == normalizedUserName).FirstOrDefaultAsync();
}
public Task<string> GetNormalizedUserNameAsync(User user, CancellationToken cancellationToken = default(CancellationToken))
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
return Task.FromResult(user.NormalizedUserName);
}
public Task<string> GetUserIdAsync(User user, CancellationToken cancellationToken = default(CancellationToken))
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
return Task.FromResult(user.Id.ToString(System.Globalization.CultureInfo.InvariantCulture));
}
public Task<string> GetUserNameAsync(User user, CancellationToken cancellationToken = default(CancellationToken))
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
return Task.FromResult(user.UserName);
}
public Task SetNormalizedUserNameAsync(User user, string normalizedName, CancellationToken cancellationToken = default(CancellationToken))
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
user.NormalizedUserName = normalizedName;
return Task.CompletedTask;
}
public Task SetUserNameAsync(User user, string userName, CancellationToken cancellationToken = default(CancellationToken))
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
user.UserName = userName;
return Task.CompletedTask;
}
public async Task<IdentityResult> UpdateAsync(User user, CancellationToken cancellationToken = default(CancellationToken))
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
_session.Save(user);
try
{
await _session.CommitAsync();
}
catch
{
return IdentityResult.Failed();
}
return IdentityResult.Success;
}
#endregion
#region IUserPasswordStore<User>
public Task<string> GetPasswordHashAsync(User user, CancellationToken cancellationToken = default(CancellationToken))
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
return Task.FromResult(user.PasswordHash);
}
public Task SetPasswordHashAsync(User user, string passwordHash, CancellationToken cancellationToken = default(CancellationToken))
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
user.PasswordHash = passwordHash;
return Task.CompletedTask;
}
public Task<bool> HasPasswordAsync(User user, CancellationToken cancellationToken = default(CancellationToken))
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
return Task.FromResult(user.PasswordHash != null);
}
#endregion
#region ISecurityStampValidator<User>
public Task SetSecurityStampAsync(User user, string stamp, CancellationToken cancellationToken = default(CancellationToken))
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
user.SecurityStamp = stamp;
return Task.CompletedTask;
}
public Task<string> GetSecurityStampAsync(User user, CancellationToken cancellationToken = default(CancellationToken))
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
return Task.FromResult(user.SecurityStamp);
}
#endregion
#region IUserEmailStore<User>
public Task SetEmailAsync(User user, string email, CancellationToken cancellationToken)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
user.Email = email;
return Task.CompletedTask;
}
public Task<string> GetEmailAsync(User user, CancellationToken cancellationToken)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
return Task.FromResult(user.Email);
}
public Task<bool> GetEmailConfirmedAsync(User user, CancellationToken cancellationToken)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
return Task.FromResult(user.EmailConfirmed);
}
public Task SetEmailConfirmedAsync(User user, bool confirmed, CancellationToken cancellationToken)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
user.EmailConfirmed = confirmed;
return Task.CompletedTask;
}
public Task<User> FindByEmailAsync(string normalizedEmail, CancellationToken cancellationToken)
{
return _session.Query<User, UserIndex>(u => u.NormalizedEmail == normalizedEmail).FirstOrDefaultAsync();
}
public Task<string> GetNormalizedEmailAsync(User user, CancellationToken cancellationToken)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
return Task.FromResult(user.NormalizedEmail);
}
public Task SetNormalizedEmailAsync(User user, string normalizedEmail, CancellationToken cancellationToken)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
user.NormalizedEmail = normalizedEmail;
return Task.CompletedTask;
}
#endregion
#region IUserRoleStore<User>
public Task AddToRoleAsync(User user, string roleName, CancellationToken cancellationToken)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
user.RoleNames.Add(roleName);
_session.Save(roleName);
return Task.CompletedTask;
}
public Task RemoveFromRoleAsync(User user, string roleName, CancellationToken cancellationToken)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
user.RoleNames.Remove(roleName);
_session.Save(roleName);
return Task.CompletedTask;
}
public Task<IList<string>> GetRolesAsync(User user, CancellationToken cancellationToken)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
return Task.FromResult<IList<string>>(user.RoleNames);
}
public Task<bool> IsInRoleAsync(User user, string roleName, CancellationToken cancellationToken)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
return Task.FromResult(user.RoleNames.Contains(roleName));
}
public Task<IList<User>> GetUsersInRoleAsync(string roleName, CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the 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 Mono.Addins;
using System;
using System.Reflection;
using System.Threading;
using System.Text;
using System.Net;
using System.Net.Sockets;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Scenes.Scripting;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using PermissionMask = OpenSim.Framework.PermissionMask;
namespace OpenSim.Region.OptionalModules.Scripting.JsonStore
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "JsonStoreScriptModule")]
public class JsonStoreScriptModule : INonSharedRegionModule
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private IConfig m_config = null;
private bool m_enabled = false;
private Scene m_scene = null;
private IScriptModuleComms m_comms;
private IJsonStoreModule m_store;
private Dictionary<UUID,HashSet<UUID>> m_scriptStores = new Dictionary<UUID,HashSet<UUID>>();
#region Region Module interface
// -----------------------------------------------------------------
/// <summary>
/// Name of this shared module is it's class name
/// </summary>
// -----------------------------------------------------------------
public string Name
{
get { return this.GetType().Name; }
}
// -----------------------------------------------------------------
/// <summary>
/// Initialise this shared module
/// </summary>
/// <param name="scene">this region is getting initialised</param>
/// <param name="source">nini config, we are not using this</param>
// -----------------------------------------------------------------
public void Initialise(IConfigSource config)
{
try
{
if ((m_config = config.Configs["JsonStore"]) == null)
{
// There is no configuration, the module is disabled
// m_log.InfoFormat("[JsonStoreScripts] no configuration info");
return;
}
m_enabled = m_config.GetBoolean("Enabled", m_enabled);
}
catch (Exception e)
{
m_log.ErrorFormat("[JsonStoreScripts]: initialization error: {0}", e.Message);
return;
}
if (m_enabled)
m_log.DebugFormat("[JsonStoreScripts]: module is enabled");
}
// -----------------------------------------------------------------
/// <summary>
/// everything is loaded, perform post load configuration
/// </summary>
// -----------------------------------------------------------------
public void PostInitialise()
{
}
// -----------------------------------------------------------------
/// <summary>
/// Nothing to do on close
/// </summary>
// -----------------------------------------------------------------
public void Close()
{
}
// -----------------------------------------------------------------
/// <summary>
/// </summary>
// -----------------------------------------------------------------
public void AddRegion(Scene scene)
{
scene.EventManager.OnScriptReset += HandleScriptReset;
scene.EventManager.OnRemoveScript += HandleScriptReset;
}
// -----------------------------------------------------------------
/// <summary>
/// </summary>
// -----------------------------------------------------------------
public void RemoveRegion(Scene scene)
{
scene.EventManager.OnScriptReset -= HandleScriptReset;
scene.EventManager.OnRemoveScript -= HandleScriptReset;
// need to remove all references to the scene in the subscription
// list to enable full garbage collection of the scene object
}
// -----------------------------------------------------------------
/// <summary>
/// </summary>
// -----------------------------------------------------------------
private void HandleScriptReset(uint localID, UUID itemID)
{
HashSet<UUID> stores;
lock (m_scriptStores)
{
if (! m_scriptStores.TryGetValue(itemID, out stores))
return;
m_scriptStores.Remove(itemID);
}
foreach (UUID id in stores)
m_store.DestroyStore(id);
}
// -----------------------------------------------------------------
/// <summary>
/// Called when all modules have been added for a region. This is
/// where we hook up events
/// </summary>
// -----------------------------------------------------------------
public void RegionLoaded(Scene scene)
{
if (m_enabled)
{
m_scene = scene;
m_comms = m_scene.RequestModuleInterface<IScriptModuleComms>();
if (m_comms == null)
{
m_log.ErrorFormat("[JsonStoreScripts]: ScriptModuleComms interface not defined");
m_enabled = false;
return;
}
m_store = m_scene.RequestModuleInterface<IJsonStoreModule>();
if (m_store == null)
{
m_log.ErrorFormat("[JsonStoreScripts]: JsonModule interface not defined");
m_enabled = false;
return;
}
try
{
m_comms.RegisterScriptInvocations(this);
m_comms.RegisterConstants(this);
}
catch (Exception e)
{
// See http://opensimulator.org/mantis/view.php?id=5971 for more information
m_log.WarnFormat("[JsonStoreScripts]: script method registration failed; {0}", e.Message);
m_enabled = false;
}
}
}
/// -----------------------------------------------------------------
/// <summary>
/// </summary>
// -----------------------------------------------------------------
public Type ReplaceableInterface
{
get { return null; }
}
#endregion
#region ScriptConstantsInterface
[ScriptConstant]
public static readonly int JSON_NODETYPE_UNDEF = (int)JsonStoreNodeType.Undefined;
[ScriptConstant]
public static readonly int JSON_NODETYPE_OBJECT = (int)JsonStoreNodeType.Object;
[ScriptConstant]
public static readonly int JSON_NODETYPE_ARRAY = (int)JsonStoreNodeType.Array;
[ScriptConstant]
public static readonly int JSON_NODETYPE_VALUE = (int)JsonStoreNodeType.Value;
[ScriptConstant]
public static readonly int JSON_VALUETYPE_UNDEF = (int)JsonStoreValueType.Undefined;
[ScriptConstant]
public static readonly int JSON_VALUETYPE_BOOLEAN = (int)JsonStoreValueType.Boolean;
[ScriptConstant]
public static readonly int JSON_VALUETYPE_INTEGER = (int)JsonStoreValueType.Integer;
[ScriptConstant]
public static readonly int JSON_VALUETYPE_FLOAT = (int)JsonStoreValueType.Float;
[ScriptConstant]
public static readonly int JSON_VALUETYPE_STRING = (int)JsonStoreValueType.String;
#endregion
#region ScriptInvocationInteface
// -----------------------------------------------------------------
/// <summary>
///
/// </summary>
// -----------------------------------------------------------------
[ScriptInvocation]
public UUID JsonAttachObjectStore(UUID hostID, UUID scriptID)
{
UUID uuid = UUID.Zero;
if (! m_store.AttachObjectStore(hostID))
GenerateRuntimeError("Failed to create Json store");
return hostID;
}
// -----------------------------------------------------------------
/// <summary>
///
/// </summary>
// -----------------------------------------------------------------
[ScriptInvocation]
public UUID JsonCreateStore(UUID hostID, UUID scriptID, string value)
{
UUID uuid = UUID.Zero;
if (! m_store.CreateStore(value, ref uuid))
GenerateRuntimeError("Failed to create Json store");
lock (m_scriptStores)
{
if (! m_scriptStores.ContainsKey(scriptID))
m_scriptStores[scriptID] = new HashSet<UUID>();
m_scriptStores[scriptID].Add(uuid);
}
return uuid;
}
// -----------------------------------------------------------------
/// <summary>
///
/// </summary>
// -----------------------------------------------------------------
[ScriptInvocation]
public int JsonDestroyStore(UUID hostID, UUID scriptID, UUID storeID)
{
lock(m_scriptStores)
{
if (m_scriptStores.ContainsKey(scriptID))
m_scriptStores[scriptID].Remove(storeID);
}
return m_store.DestroyStore(storeID) ? 1 : 0;
}
// -----------------------------------------------------------------
/// <summary>
///
/// </summary>
// -----------------------------------------------------------------
[ScriptInvocation]
public int JsonTestStore(UUID hostID, UUID scriptID, UUID storeID)
{
return m_store.TestStore(storeID) ? 1 : 0;
}
// -----------------------------------------------------------------
/// <summary>
///
/// </summary>
// -----------------------------------------------------------------
[ScriptInvocation]
public UUID JsonRezAtRoot(UUID hostID, UUID scriptID, string item, Vector3 pos, Vector3 vel, Quaternion rot, string param)
{
UUID reqID = UUID.Random();
Util.FireAndForget(
o => DoJsonRezObject(hostID, scriptID, reqID, item, pos, vel, rot, param), null, "JsonStoreScriptModule.DoJsonRezObject");
return reqID;
}
// -----------------------------------------------------------------
/// <summary>
///
/// </summary>
// -----------------------------------------------------------------
[ScriptInvocation]
public UUID JsonReadNotecard(UUID hostID, UUID scriptID, UUID storeID, string path, string notecardIdentifier)
{
UUID reqID = UUID.Random();
Util.FireAndForget(
o => DoJsonReadNotecard(reqID, hostID, scriptID, storeID, path, notecardIdentifier), null, "JsonStoreScriptModule.JsonReadNotecard");
return reqID;
}
// -----------------------------------------------------------------
/// <summary>
///
/// </summary>
// -----------------------------------------------------------------
[ScriptInvocation]
public UUID JsonWriteNotecard(UUID hostID, UUID scriptID, UUID storeID, string path, string name)
{
UUID reqID = UUID.Random();
Util.FireAndForget(
o => DoJsonWriteNotecard(reqID,hostID,scriptID,storeID,path,name), null, "JsonStoreScriptModule.DoJsonWriteNotecard");
return reqID;
}
// -----------------------------------------------------------------
/// <summary>
///
/// </summary>
// -----------------------------------------------------------------
[ScriptInvocation]
public string JsonList2Path(UUID hostID, UUID scriptID, object[] pathlist)
{
string ipath = ConvertList2Path(pathlist);
string opath;
if (JsonStore.CanonicalPathExpression(ipath,out opath))
return opath;
// This won't parse if passed to the other routines as opposed to
// returning an empty string which is a valid path and would overwrite
// the entire store
return "**INVALID**";
}
// -----------------------------------------------------------------
/// <summary>
///
/// </summary>
// -----------------------------------------------------------------
[ScriptInvocation]
public int JsonGetNodeType(UUID hostID, UUID scriptID, UUID storeID, string path)
{
return (int)m_store.GetNodeType(storeID,path);
}
// -----------------------------------------------------------------
/// <summary>
///
/// </summary>
// -----------------------------------------------------------------
[ScriptInvocation]
public int JsonGetValueType(UUID hostID, UUID scriptID, UUID storeID, string path)
{
return (int)m_store.GetValueType(storeID,path);
}
// -----------------------------------------------------------------
/// <summary>
///
/// </summary>
// -----------------------------------------------------------------
[ScriptInvocation]
public int JsonSetValue(UUID hostID, UUID scriptID, UUID storeID, string path, string value)
{
return m_store.SetValue(storeID,path,value,false) ? 1 : 0;
}
[ScriptInvocation]
public int JsonSetJson(UUID hostID, UUID scriptID, UUID storeID, string path, string value)
{
return m_store.SetValue(storeID,path,value,true) ? 1 : 0;
}
// -----------------------------------------------------------------
/// <summary>
///
/// </summary>
// -----------------------------------------------------------------
[ScriptInvocation]
public int JsonRemoveValue(UUID hostID, UUID scriptID, UUID storeID, string path)
{
return m_store.RemoveValue(storeID,path) ? 1 : 0;
}
// -----------------------------------------------------------------
/// <summary>
///
/// </summary>
// -----------------------------------------------------------------
[ScriptInvocation]
public int JsonGetArrayLength(UUID hostID, UUID scriptID, UUID storeID, string path)
{
return m_store.GetArrayLength(storeID,path);
}
// -----------------------------------------------------------------
/// <summary>
///
/// </summary>
// -----------------------------------------------------------------
[ScriptInvocation]
public string JsonGetValue(UUID hostID, UUID scriptID, UUID storeID, string path)
{
string value = String.Empty;
m_store.GetValue(storeID,path,false,out value);
return value;
}
[ScriptInvocation]
public string JsonGetJson(UUID hostID, UUID scriptID, UUID storeID, string path)
{
string value = String.Empty;
m_store.GetValue(storeID,path,true, out value);
return value;
}
// -----------------------------------------------------------------
/// <summary>
///
/// </summary>
// -----------------------------------------------------------------
[ScriptInvocation]
public UUID JsonTakeValue(UUID hostID, UUID scriptID, UUID storeID, string path)
{
UUID reqID = UUID.Random();
Util.FireAndForget(
o => DoJsonTakeValue(scriptID,reqID,storeID,path,false), null, "JsonStoreScriptModule.DoJsonTakeValue");
return reqID;
}
[ScriptInvocation]
public UUID JsonTakeValueJson(UUID hostID, UUID scriptID, UUID storeID, string path)
{
UUID reqID = UUID.Random();
Util.FireAndForget(
o => DoJsonTakeValue(scriptID,reqID,storeID,path,true), null, "JsonStoreScriptModule.DoJsonTakeValueJson");
return reqID;
}
// -----------------------------------------------------------------
/// <summary>
///
/// </summary>
// -----------------------------------------------------------------
[ScriptInvocation]
public UUID JsonReadValue(UUID hostID, UUID scriptID, UUID storeID, string path)
{
UUID reqID = UUID.Random();
Util.FireAndForget(
o => DoJsonReadValue(scriptID,reqID,storeID,path,false), null, "JsonStoreScriptModule.DoJsonReadValue");
return reqID;
}
[ScriptInvocation]
public UUID JsonReadValueJson(UUID hostID, UUID scriptID, UUID storeID, string path)
{
UUID reqID = UUID.Random();
Util.FireAndForget(
o => DoJsonReadValue(scriptID,reqID,storeID,path,true), null, "JsonStoreScriptModule.DoJsonReadValueJson");
return reqID;
}
#endregion
// -----------------------------------------------------------------
/// <summary>
///
/// </summary>
// -----------------------------------------------------------------
protected void GenerateRuntimeError(string msg)
{
m_log.InfoFormat("[JsonStore] runtime error: {0}",msg);
throw new Exception("JsonStore Runtime Error: " + msg);
}
// -----------------------------------------------------------------
/// <summary>
///
/// </summary>
// -----------------------------------------------------------------
protected void DispatchValue(UUID scriptID, UUID reqID, string value)
{
m_comms.DispatchReply(scriptID,1,value,reqID.ToString());
}
// -----------------------------------------------------------------
/// <summary>
///
/// </summary>
// -----------------------------------------------------------------
private void DoJsonTakeValue(UUID scriptID, UUID reqID, UUID storeID, string path, bool useJson)
{
try
{
m_store.TakeValue(storeID,path,useJson,delegate(string value) { DispatchValue(scriptID,reqID,value); });
return;
}
catch (Exception e)
{
m_log.InfoFormat("[JsonStoreScripts]: unable to retrieve value; {0}",e.ToString());
}
DispatchValue(scriptID,reqID,String.Empty);
}
// -----------------------------------------------------------------
/// <summary>
///
/// </summary>
// -----------------------------------------------------------------
private void DoJsonReadValue(UUID scriptID, UUID reqID, UUID storeID, string path, bool useJson)
{
try
{
m_store.ReadValue(storeID,path,useJson,delegate(string value) { DispatchValue(scriptID,reqID,value); });
return;
}
catch (Exception e)
{
m_log.InfoFormat("[JsonStoreScripts]: unable to retrieve value; {0}",e.ToString());
}
DispatchValue(scriptID,reqID,String.Empty);
}
// -----------------------------------------------------------------
/// <summary>
///
/// </summary>
// -----------------------------------------------------------------
private void DoJsonReadNotecard(
UUID reqID, UUID hostID, UUID scriptID, UUID storeID, string path, string notecardIdentifier)
{
UUID assetID;
if (!UUID.TryParse(notecardIdentifier, out assetID))
{
SceneObjectPart part = m_scene.GetSceneObjectPart(hostID);
assetID = ScriptUtils.GetAssetIdFromItemName(part, notecardIdentifier, (int)AssetType.Notecard);
}
AssetBase a = m_scene.AssetService.Get(assetID.ToString());
if (a == null)
GenerateRuntimeError(String.Format("Unable to find notecard asset {0}", assetID));
if (a.Type != (sbyte)AssetType.Notecard)
GenerateRuntimeError(String.Format("Invalid notecard asset {0}", assetID));
m_log.DebugFormat("[JsonStoreScripts]: read notecard in context {0}",storeID);
try
{
string jsondata = SLUtil.ParseNotecardToString(a.Data);
int result = m_store.SetValue(storeID, path, jsondata,true) ? 1 : 0;
m_comms.DispatchReply(scriptID, result, "", reqID.ToString());
return;
}
catch(SLUtil.NotANotecardFormatException e)
{
m_log.WarnFormat("[JsonStoreScripts]: Notecard parsing failed; assetId {0} at line number {1}", assetID.ToString(), e.lineNumber);
}
catch (Exception e)
{
m_log.WarnFormat("[JsonStoreScripts]: Json parsing failed; {0}", e.Message);
}
GenerateRuntimeError(String.Format("Json parsing failed for {0}", assetID));
m_comms.DispatchReply(scriptID, 0, "", reqID.ToString());
}
// -----------------------------------------------------------------
/// <summary>
///
/// </summary>
// -----------------------------------------------------------------
private void DoJsonWriteNotecard(UUID reqID, UUID hostID, UUID scriptID, UUID storeID, string path, string name)
{
string data;
if (! m_store.GetValue(storeID,path,true, out data))
{
m_comms.DispatchReply(scriptID,0,UUID.Zero.ToString(),reqID.ToString());
return;
}
SceneObjectPart host = m_scene.GetSceneObjectPart(hostID);
// Create new asset
UUID assetID = UUID.Random();
AssetBase asset = new AssetBase(assetID, name, (sbyte)AssetType.Notecard, host.OwnerID.ToString());
asset.Description = "Json store";
int textLength = data.Length;
data = "Linden text version 2\n{\nLLEmbeddedItems version 1\n{\ncount 0\n}\nText length "
+ textLength.ToString() + "\n" + data + "}\n";
asset.Data = Util.UTF8.GetBytes(data);
m_scene.AssetService.Store(asset);
// Create Task Entry
TaskInventoryItem taskItem = new TaskInventoryItem();
taskItem.ResetIDs(host.UUID);
taskItem.ParentID = host.UUID;
taskItem.CreationDate = (uint)Util.UnixTimeSinceEpoch();
taskItem.Name = asset.Name;
taskItem.Description = asset.Description;
taskItem.Type = (int)AssetType.Notecard;
taskItem.InvType = (int)InventoryType.Notecard;
taskItem.OwnerID = host.OwnerID;
taskItem.CreatorID = host.OwnerID;
taskItem.BasePermissions = (uint)PermissionMask.All;
taskItem.CurrentPermissions = (uint)PermissionMask.All;
taskItem.EveryonePermissions = 0;
taskItem.NextPermissions = (uint)PermissionMask.All;
taskItem.GroupID = host.GroupID;
taskItem.GroupPermissions = 0;
taskItem.Flags = 0;
taskItem.PermsGranter = UUID.Zero;
taskItem.PermsMask = 0;
taskItem.AssetID = asset.FullID;
host.Inventory.AddInventoryItem(taskItem, false);
host.ParentGroup.InvalidateEffectivePerms();
m_comms.DispatchReply(scriptID,1,assetID.ToString(),reqID.ToString());
}
// -----------------------------------------------------------------
/// <summary>
/// Convert a list of values that are path components to a single string path
/// </summary>
// -----------------------------------------------------------------
protected static Regex m_ArrayPattern = new Regex("^([0-9]+|\\+)$");
private string ConvertList2Path(object[] pathlist)
{
string path = "";
for (int i = 0; i < pathlist.Length; i++)
{
string token = "";
if (pathlist[i] is string)
{
token = pathlist[i].ToString();
// Check to see if this is a bare number which would not be a valid
// identifier otherwise
if (m_ArrayPattern.IsMatch(token))
token = '[' + token + ']';
}
else if (pathlist[i] is int)
{
token = "[" + pathlist[i].ToString() + "]";
}
else
{
token = "." + pathlist[i].ToString() + ".";
}
path += token + ".";
}
return path;
}
// -----------------------------------------------------------------
/// <summary>
///
/// </summary>
// -----------------------------------------------------------------
private void DoJsonRezObject(UUID hostID, UUID scriptID, UUID reqID, string name, Vector3 pos, Vector3 vel, Quaternion rot, string param)
{
if (Double.IsNaN(rot.X) || Double.IsNaN(rot.Y) || Double.IsNaN(rot.Z) || Double.IsNaN(rot.W))
{
GenerateRuntimeError("Invalid rez rotation");
return;
}
SceneObjectGroup host = m_scene.GetSceneObjectGroup(hostID);
if (host == null)
{
GenerateRuntimeError(String.Format("Unable to find rezzing host '{0}'",hostID));
return;
}
// hpos = host.RootPart.GetWorldPosition()
// float dist = (float)llVecDist(hpos, pos);
// if (dist > m_ScriptDistanceFactor * 10.0f)
// return;
TaskInventoryItem item = host.RootPart.Inventory.GetInventoryItem(name);
if (item == null)
{
GenerateRuntimeError(String.Format("Unable to find object to rez '{0}'",name));
return;
}
if (item.InvType != (int)InventoryType.Object)
{
GenerateRuntimeError("Can't create requested object; object is missing from database");
return;
}
List<SceneObjectGroup> objlist;
List<Vector3> veclist;
Vector3 bbox = new Vector3();
float offsetHeight;
bool success = host.RootPart.Inventory.GetRezReadySceneObjects(item, out objlist, out veclist, out bbox, out offsetHeight);
if (! success)
{
GenerateRuntimeError("Failed to create object");
return;
}
int totalPrims = 0;
foreach (SceneObjectGroup group in objlist)
totalPrims += group.PrimCount;
if (! m_scene.Permissions.CanRezObject(totalPrims, item.OwnerID, pos))
{
GenerateRuntimeError("Not allowed to create the object");
return;
}
if (! m_scene.Permissions.BypassPermissions())
{
if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0)
host.RootPart.Inventory.RemoveInventoryItem(item.ItemID);
}
for (int i = 0; i < objlist.Count; i++)
{
SceneObjectGroup group = objlist[i];
Vector3 curpos = pos + veclist[i];
if (group.IsAttachment == false && group.RootPart.Shape.State != 0)
{
group.RootPart.AttachedPos = group.AbsolutePosition;
group.RootPart.Shape.LastAttachPoint = (byte)group.AttachmentPoint;
}
group.RezzerID = host.RootPart.UUID;
m_scene.AddNewSceneObject(group, true, curpos, rot, vel);
UUID storeID = group.UUID;
if (! m_store.CreateStore(param, ref storeID))
{
GenerateRuntimeError("Unable to create jsonstore for new object");
continue;
}
// We can only call this after adding the scene object, since the scene object references the scene
// to find out if scripts should be activated at all.
group.RootPart.SetDieAtEdge(true);
group.CreateScriptInstances(0, true, m_scene.DefaultScriptEngine, 3);
group.ResumeScripts();
group.ScheduleGroupForFullUpdate();
// send the reply back to the host object, use the integer param to indicate the number
// of remaining objects
m_comms.DispatchReply(scriptID, objlist.Count-i-1, group.RootPart.UUID.ToString(), reqID.ToString());
}
}
}
}
| |
/*
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2.1
* Contact: devcenter@docusign.com
* 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 = DocuSign.eSign.Client.SwaggerDateConverter;
namespace DocuSign.eSign.Model
{
/// <summary>
/// PowerFormsResponse
/// </summary>
[DataContract]
public partial class PowerFormsResponse : IEquatable<PowerFormsResponse>, IValidatableObject
{
public PowerFormsResponse()
{
// Empty Constructor
}
/// <summary>
/// Initializes a new instance of the <see cref="PowerFormsResponse" /> class.
/// </summary>
/// <param name="EndPosition">The last position in the result set. .</param>
/// <param name="NextUri">The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null. .</param>
/// <param name="PowerForms">PowerForms.</param>
/// <param name="PreviousUri">The postal code for the billing address..</param>
/// <param name="ResultSetSize">The number of results returned in this response. .</param>
/// <param name="StartPosition">Starting position of the current result set..</param>
/// <param name="TotalSetSize">The total number of items available in the result set. This will always be greater than or equal to the value of the property returning the results in the in the response..</param>
public PowerFormsResponse(int? EndPosition = default(int?), string NextUri = default(string), List<PowerForm> PowerForms = default(List<PowerForm>), string PreviousUri = default(string), int? ResultSetSize = default(int?), int? StartPosition = default(int?), int? TotalSetSize = default(int?))
{
this.EndPosition = EndPosition;
this.NextUri = NextUri;
this.PowerForms = PowerForms;
this.PreviousUri = PreviousUri;
this.ResultSetSize = ResultSetSize;
this.StartPosition = StartPosition;
this.TotalSetSize = TotalSetSize;
}
/// <summary>
/// The last position in the result set.
/// </summary>
/// <value>The last position in the result set. </value>
[DataMember(Name="endPosition", EmitDefaultValue=false)]
public int? EndPosition { get; set; }
/// <summary>
/// The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null.
/// </summary>
/// <value>The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null. </value>
[DataMember(Name="nextUri", EmitDefaultValue=false)]
public string NextUri { get; set; }
/// <summary>
/// Gets or Sets PowerForms
/// </summary>
[DataMember(Name="powerForms", EmitDefaultValue=false)]
public List<PowerForm> PowerForms { get; set; }
/// <summary>
/// The postal code for the billing address.
/// </summary>
/// <value>The postal code for the billing address.</value>
[DataMember(Name="previousUri", EmitDefaultValue=false)]
public string PreviousUri { get; set; }
/// <summary>
/// The number of results returned in this response.
/// </summary>
/// <value>The number of results returned in this response. </value>
[DataMember(Name="resultSetSize", EmitDefaultValue=false)]
public int? ResultSetSize { get; set; }
/// <summary>
/// Starting position of the current result set.
/// </summary>
/// <value>Starting position of the current result set.</value>
[DataMember(Name="startPosition", EmitDefaultValue=false)]
public int? StartPosition { get; set; }
/// <summary>
/// The total number of items available in the result set. This will always be greater than or equal to the value of the property returning the results in the in the response.
/// </summary>
/// <value>The total number of items available in the result set. This will always be greater than or equal to the value of the property returning the results in the in the response.</value>
[DataMember(Name="totalSetSize", EmitDefaultValue=false)]
public int? TotalSetSize { 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 PowerFormsResponse {\n");
sb.Append(" EndPosition: ").Append(EndPosition).Append("\n");
sb.Append(" NextUri: ").Append(NextUri).Append("\n");
sb.Append(" PowerForms: ").Append(PowerForms).Append("\n");
sb.Append(" PreviousUri: ").Append(PreviousUri).Append("\n");
sb.Append(" ResultSetSize: ").Append(ResultSetSize).Append("\n");
sb.Append(" StartPosition: ").Append(StartPosition).Append("\n");
sb.Append(" TotalSetSize: ").Append(TotalSetSize).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 PowerFormsResponse);
}
/// <summary>
/// Returns true if PowerFormsResponse instances are equal
/// </summary>
/// <param name="other">Instance of PowerFormsResponse to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(PowerFormsResponse other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.EndPosition == other.EndPosition ||
this.EndPosition != null &&
this.EndPosition.Equals(other.EndPosition)
) &&
(
this.NextUri == other.NextUri ||
this.NextUri != null &&
this.NextUri.Equals(other.NextUri)
) &&
(
this.PowerForms == other.PowerForms ||
this.PowerForms != null &&
this.PowerForms.SequenceEqual(other.PowerForms)
) &&
(
this.PreviousUri == other.PreviousUri ||
this.PreviousUri != null &&
this.PreviousUri.Equals(other.PreviousUri)
) &&
(
this.ResultSetSize == other.ResultSetSize ||
this.ResultSetSize != null &&
this.ResultSetSize.Equals(other.ResultSetSize)
) &&
(
this.StartPosition == other.StartPosition ||
this.StartPosition != null &&
this.StartPosition.Equals(other.StartPosition)
) &&
(
this.TotalSetSize == other.TotalSetSize ||
this.TotalSetSize != null &&
this.TotalSetSize.Equals(other.TotalSetSize)
);
}
/// <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.EndPosition != null)
hash = hash * 59 + this.EndPosition.GetHashCode();
if (this.NextUri != null)
hash = hash * 59 + this.NextUri.GetHashCode();
if (this.PowerForms != null)
hash = hash * 59 + this.PowerForms.GetHashCode();
if (this.PreviousUri != null)
hash = hash * 59 + this.PreviousUri.GetHashCode();
if (this.ResultSetSize != null)
hash = hash * 59 + this.ResultSetSize.GetHashCode();
if (this.StartPosition != null)
hash = hash * 59 + this.StartPosition.GetHashCode();
if (this.TotalSetSize != null)
hash = hash * 59 + this.TotalSetSize.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
using System;
using System.Collections.Generic;
using Gtk;
using Moscrif.IDE.Workspace;
using Moscrif.IDE.Controls;
using MessageDialogs = Moscrif.IDE.Controls.MessageDialog;
using Moscrif.IDE.Iface.Entities;
using Moscrif.IDE.Components;
namespace Moscrif.IDE.Option
{
internal class GlobalOptionsPanel : OptionsPanel
{
GlobalOptionsWidget widget;
public override Widget CreatePanelWidget ()
{
return widget = new GlobalOptionsWidget (ParentDialog);
}
public override void ApplyChanges ()
{
widget.Store ();
}
public override void Initialize(PreferencesDialog dialog, object dataObject)
{
base.Initialize(dialog, dataObject);
}
public override void ShowPanel()
{
}
public override bool ValidateChanges ()
{
return widget.Validate ();
}
public override string Label {
get { return MainClass.Languages.Translate("general_prferencies_ide"); }
}
public override string Icon {
get { return "preferences.png"; }
}
}
internal partial class GlobalOptionsWidget : Gtk.Bin
{
ListStore storeIFo = new ListStore(typeof(string),typeof(bool),typeof(bool), typeof(IgnoreFolder));
ListStore storeIFi = new ListStore(typeof(string),typeof(bool),typeof(bool), typeof(IgnoreFolder));
private List<IgnoreFolder> ignoreFolder;
private List<IgnoreFolder> ignoreFile;
Gtk.Menu popupColor = new Gtk.Menu();
Gtk.Window parentWindow;
FavoriteEntry feLib ;
FavoriteEntry fePublishTool ;
FavoriteEntry feEmulator ;
public GlobalOptionsWidget(Gtk.Window parent)
{
parentWindow = parent;
this.Build();
this.chbShowUnsupportDevic.Sensitive = false;
feLib = new FavoriteEntry(NavigationBar.NavigationType.libs);
feLib.IsFolder = true;
fePublishTool = new FavoriteEntry(NavigationBar.NavigationType.publish);
fePublishTool.IsFolder = true;
feEmulator = new FavoriteEntry(NavigationBar.NavigationType.emulator);
feEmulator.IsFolder = true;
if (!String.IsNullOrEmpty(MainClass.Settings.EmulatorDirectory) ){
feEmulator.Path= MainClass.Settings.EmulatorDirectory;
}
if (!String.IsNullOrEmpty(MainClass.Settings.LibDirectory) ){
feLib.Path= MainClass.Settings.LibDirectory;
}
if (!String.IsNullOrEmpty(MainClass.Settings.PublishDirectory) ){
fePublishTool.Path = MainClass.Settings.PublishDirectory;
}
table1.Attach(fePublishTool,1,2,0,1,AttachOptions.Fill|AttachOptions.Expand,AttachOptions.Fill,0,0);
table1.Attach(feLib,1,2,1,2,AttachOptions.Fill|AttachOptions.Expand,AttachOptions.Fill,0,0);
table1.Attach(feEmulator,1,2,2,3,AttachOptions.Fill|AttachOptions.Expand,AttachOptions.Fill,0,0);
fontbutton1.FontName = MainClass.Settings.ConsoleTaskFont;
chbAutoselectProject.Active = MainClass.Settings.AutoSelectProject;
chbOpenLastOpenedW.Active= MainClass.Settings.OpenLastOpenedWorkspace;
chbShowUnsupportDevic.Active = MainClass.Settings.ShowUnsupportedDevices;
chbShowDebugDevic.Active =MainClass.Settings.ShowDebugDevices;
cbBackground.UseAlpha = false;
cbBackground.Color = new Gdk.Color(MainClass.Settings.BackgroundColor.Red,
MainClass.Settings.BackgroundColor.Green,MainClass.Settings.BackgroundColor.Blue);
ignoreFolder = new List<IgnoreFolder>( MainClass.Settings.IgnoresFolders.ToArray());
tvIgnoreFolder.AppendColumn(MainClass.Languages.Translate("name"), new Gtk.CellRendererText(), "text", 0);
CellRendererToggle crt = new CellRendererToggle();
crt.Activatable = true;
crt.Toggled += delegate(object o, ToggledArgs args) {
TreeIter iter;
if (storeIFo.GetIter (out iter, new TreePath(args.Path))) {
bool old = (bool) storeIFo.GetValue(iter,1);
IgnoreFolder iFol = (IgnoreFolder) storeIFo.GetValue(iter,3);
iFol.IsForIde =!old;
storeIFo.SetValue(iter,1,!old);
}
};
tvIgnoreFolder.AppendColumn(MainClass.Languages.Translate("ignore_for_ide"), crt , "active", 1);
CellRendererToggle crt2 = new CellRendererToggle();
crt2.Activatable = true;
crt2.Toggled += delegate(object o, ToggledArgs args) {
TreeIter iter;
if (storeIFo.GetIter (out iter, new TreePath(args.Path))) {
bool old = (bool) storeIFo.GetValue(iter,2);
IgnoreFolder iFol = (IgnoreFolder) storeIFo.GetValue(iter,3);
//CombinePublish cp =(CombinePublish) fontListStore.GetValue(iter,2);
//cp.IsSelected = !old;
iFol.IsForPublish =!old;
storeIFo.SetValue(iter,2,!old);
}
};
tvIgnoreFolder.AppendColumn(MainClass.Languages.Translate("ignore_for_Pub"), crt2 , "active", 2);
tvIgnoreFolder.Model = storeIFo;
foreach (IgnoreFolder ignoref in MainClass.Settings.IgnoresFolders){
storeIFo.AppendValues(ignoref.Folder,ignoref.IsForIde,ignoref.IsForPublish,ignoref);
}
/* Ignore Files */
ignoreFile = new List<IgnoreFolder>( MainClass.Settings.IgnoresFiles.ToArray());
tvIgnoreFiles.AppendColumn(MainClass.Languages.Translate("name"), new Gtk.CellRendererText(), "text", 0);
CellRendererToggle crtFi = new CellRendererToggle();
crtFi.Activatable = true;
crtFi.Toggled += delegate(object o, ToggledArgs args) {
TreeIter iter;
if (storeIFi.GetIter (out iter, new TreePath(args.Path))) {
bool old = (bool) storeIFi.GetValue(iter,1);
IgnoreFolder iFol = (IgnoreFolder) storeIFi.GetValue(iter,3);
iFol.IsForIde =!old;
storeIFi.SetValue(iter,1,!old);
}
};
tvIgnoreFiles.AppendColumn(MainClass.Languages.Translate("ignore_for_ide"), crtFi , "active", 1);
CellRendererToggle crtFi2 = new CellRendererToggle();
crtFi2.Activatable = true;
crtFi2.Toggled += delegate(object o, ToggledArgs args) {
TreeIter iter;
if (storeIFi.GetIter (out iter, new TreePath(args.Path))) {
bool old = (bool) storeIFi.GetValue(iter,2);
IgnoreFolder iFol = (IgnoreFolder) storeIFi.GetValue(iter,3);
iFol.IsForPublish =!old;
storeIFi.SetValue(iter,2,!old);
}
};
tvIgnoreFiles.AppendColumn(MainClass.Languages.Translate("ignore_for_Pub"), crtFi2 , "active", 2);
tvIgnoreFiles.Model = storeIFi;
foreach (IgnoreFolder ignoref in MainClass.Settings.IgnoresFiles){
storeIFi.AppendValues(ignoref.Folder,ignoref.IsForIde,ignoref.IsForPublish,ignoref);
}
/**/
Gdk.Pixbuf default_pixbuf = null;
string file = System.IO.Path.Combine(MainClass.Paths.ResDir, "stock-menu.png");
if (System.IO.File.Exists(file)) {
default_pixbuf = new Gdk.Pixbuf(file);
popupColor = new Gtk.Menu();
CreateMenu();
Gtk.Button btnClose = new Gtk.Button(new Gtk.Image(default_pixbuf));
btnClose.TooltipText = MainClass.Languages.Translate("select_color");
btnClose.Relief = Gtk.ReliefStyle.None;
btnClose.CanFocus = false;
btnClose.WidthRequest = btnClose.HeightRequest = 22;
popupColor.AttachToWidget(btnClose,new Gtk.MenuDetachFunc(DetachWidget));
btnClose.Clicked += delegate {
popupColor.Popup(null,null, new Gtk.MenuPositionFunc (GetPosition) ,3,Gtk.Global.CurrentEventTime);
};
table1.Attach(btnClose,2,3,3,4, AttachOptions.Shrink, AttachOptions.Shrink, 0, 0);
popupColor.ShowAll();
}
}
private void DetachWidget(Gtk.Widget attach_widget, Gtk.Menu menu){}
static void GetPosition(Gtk.Menu menu, out int x, out int y, out bool push_in){
menu.AttachWidget.GdkWindow.GetOrigin(out x, out y);
//Console.WriteLine("GetOrigin -->>> x->{0} ; y->{1}",x,y);
x =menu.AttachWidget.Allocation.X+x;//+menu.AttachWidget.WidthRequest;
y =menu.AttachWidget.Allocation.Y+y+menu.AttachWidget.HeightRequest;
push_in = true;
}
public bool Validate(){
//return true;
if ((String.IsNullOrEmpty(feLib.Path) ) ||
(String.IsNullOrEmpty(fePublishTool.Path) ) ||
(String.IsNullOrEmpty(feEmulator.Path) )
){
MessageDialogs ms = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, "Error", MainClass.Languages.Translate("please_set_all_folder"), MessageType.Error);
ms.ShowDialog();
return false;
}
return true;
}
public void Store ()
{
MainClass.Settings.EmulatorDirectory =feEmulator.Path;
MainClass.Settings.LibDirectory =feLib.Path;
MainClass.Settings.PublishDirectory = fePublishTool.Path;
MainClass.Settings.AutoSelectProject =chbAutoselectProject.Active;
MainClass.Settings.OpenLastOpenedWorkspace = chbOpenLastOpenedW.Active;
MainClass.Settings.ShowUnsupportedDevices = chbShowUnsupportDevic.Active;
MainClass.Settings.ShowDebugDevices = chbShowDebugDevic.Active;
MainClass.Settings.ConsoleTaskFont = fontbutton1.FontName;
//byte red = (byte)cbBackground.Color.Red;
//byte green =(byte)cbBackground.Color.Green;
//byte blue =(byte)cbBackground.Color.Blue;
MainClass.Settings.BackgroundColor.Red = (byte)cbBackground.Color.Red;
MainClass.Settings.BackgroundColor.Green= (byte)cbBackground.Color.Green;
MainClass.Settings.BackgroundColor.Blue= (byte)cbBackground.Color.Blue;
MainClass.Settings.IgnoresFolders.Clear();
MainClass.Settings.IgnoresFolders = new List<IgnoreFolder>(ignoreFolder.ToArray());
MainClass.Settings.IgnoresFiles.Clear();
MainClass.Settings.IgnoresFiles = new List<IgnoreFolder>(ignoreFile.ToArray());
}
protected virtual void OnBtnAddIFClicked (object sender, System.EventArgs e)
{
EntryDialog ed = new EntryDialog("",MainClass.Languages.Translate("name"),parentWindow);
int result = ed.Run();
if (result == (int)ResponseType.Ok){
if (!String.IsNullOrEmpty(ed.TextEntry) ){
IgnoreFolder ifol = new IgnoreFolder(ed.TextEntry,true,true);
storeIFo.AppendValues(ed.TextEntry,true,true,ifol);
ignoreFolder.Add(ifol);
}
}
ed.Destroy();
}
protected virtual void OnBtnEditIFClicked (object sender, System.EventArgs e)
{
TreeSelection ts = tvIgnoreFolder.Selection;
TreeIter ti = new TreeIter();
ts.GetSelected(out ti);
TreePath[] tp = ts.GetSelectedRows();
if (tp.Length < 1)
return ;
IgnoreFolder iFol = (IgnoreFolder)tvIgnoreFolder.Model.GetValue(ti, 3);
if (String.IsNullOrEmpty(iFol.Folder) ) return;
EntryDialog ed = new EntryDialog(iFol.Folder,MainClass.Languages.Translate("new_name"),parentWindow);
int result = ed.Run();
if (result == (int)ResponseType.Ok){
if (!String.IsNullOrEmpty(ed.TextEntry) ){
iFol.Folder =ed.TextEntry;
storeIFo.SetValues(ti,ed.TextEntry,iFol.IsForIde,iFol.IsForPublish,iFol);
}
}
ed.Destroy();
}
protected virtual void OnBtnDeleteIFClicked (object sender, System.EventArgs e)
{
TreeSelection ts = tvIgnoreFolder.Selection;
TreeIter ti = new TreeIter();
ts.GetSelected(out ti);
TreePath[] tp = ts.GetSelectedRows();
if (tp.Length < 1)
return ;
IgnoreFolder iFol = (IgnoreFolder)tvIgnoreFolder.Model.GetValue(ti, 3);
if (iFol == null ) return;
MessageDialogs md = new MessageDialogs(MessageDialogs.DialogButtonType.YesNo, MainClass.Languages.Translate("delete_resolution", iFol.Folder), "", Gtk.MessageType.Question,parentWindow);
int result = md.ShowDialog();
if (result != (int)Gtk.ResponseType.Yes)
return;
ignoreFolder.Remove(iFol);
storeIFo.Remove(ref ti);
}
private void CreateMenu(){
Gtk.MenuItem miRed = new Gtk.MenuItem("Red");
miRed.Activated += delegate(object sender, EventArgs e) {
if (sender.GetType() == typeof(Gtk.MenuItem)){
cbBackground.Color = new Gdk.Color(224, 41, 47);
}
};
popupColor.Add(miRed);
Gtk.MenuItem miBlue = new Gtk.MenuItem("Blue");
miBlue.Activated += delegate(object sender, EventArgs e) {
if (sender.GetType() == typeof(Gtk.MenuItem)){
cbBackground.Color = new Gdk.Color(164, 192,222);
}
};
popupColor.Add(miBlue);
Gtk.MenuItem miUbuntu = new Gtk.MenuItem("Ubuntu");
miUbuntu.Activated += delegate(object sender, EventArgs e) {
if (sender.GetType() == typeof(Gtk.MenuItem)){
cbBackground.Color = new Gdk.Color(240, 119,70);
}
};
popupColor.Add(miUbuntu);
Gtk.MenuItem miOsx = new Gtk.MenuItem("Mac");
miOsx.Activated += delegate(object sender, EventArgs e) {
if (sender.GetType() == typeof(Gtk.MenuItem)){
cbBackground.Color = new Gdk.Color(218,218 ,218);
}
};
popupColor.Add(miOsx);
}
protected void OnButton8Clicked (object sender, System.EventArgs e)
{
MessageDialogs md = new MessageDialogs(MessageDialogs.DialogButtonType.YesNo, MainClass.Languages.Translate("question_default_ignorelist"), "", Gtk.MessageType.Question,parentWindow);
int result = md.ShowDialog();
if (result != (int)Gtk.ResponseType.Yes)
return;
MainClass.Settings.GenerateIgnoreFolder();
storeIFo.Clear();
foreach (IgnoreFolder ignoref in MainClass.Settings.IgnoresFolders){
storeIFo.AppendValues(ignoref.Folder,ignoref.IsForIde,ignoref.IsForPublish,ignoref);
}
}
protected void OnBtnEditIFiClicked (object sender, EventArgs e)
{
TreeSelection ts = tvIgnoreFiles.Selection;
TreeIter ti = new TreeIter();
ts.GetSelected(out ti);
TreePath[] tp = ts.GetSelectedRows();
if (tp.Length < 1)
return ;
IgnoreFolder iFol = (IgnoreFolder)tvIgnoreFiles.Model.GetValue(ti, 3);
if (String.IsNullOrEmpty(iFol.Folder) ) return;
EntryDialog ed = new EntryDialog(iFol.Folder,MainClass.Languages.Translate("new_name"),parentWindow);
int result = ed.Run();
if (result == (int)ResponseType.Ok){
if (!String.IsNullOrEmpty(ed.TextEntry) ){
iFol.Folder =ed.TextEntry;
storeIFi.SetValues(ti,ed.TextEntry,iFol.IsForIde,iFol.IsForPublish,iFol);
}
}
ed.Destroy();
}
protected void OnBtnDeleteIFiClicked (object sender, EventArgs e)
{
TreeSelection ts = tvIgnoreFiles.Selection;
TreeIter ti = new TreeIter();
ts.GetSelected(out ti);
TreePath[] tp = ts.GetSelectedRows();
if (tp.Length < 1)
return ;
IgnoreFolder iFol = (IgnoreFolder)tvIgnoreFiles.Model.GetValue(ti, 3);
if (iFol == null ) return;
MessageDialogs md = new MessageDialogs(MessageDialogs.DialogButtonType.YesNo, MainClass.Languages.Translate("delete_resolution", iFol.Folder), "", Gtk.MessageType.Question,parentWindow);
int result = md.ShowDialog();
if (result != (int)Gtk.ResponseType.Yes)
return;
ignoreFile.Remove(iFol);
storeIFi.Remove(ref ti);
}
protected void OnBtnResetIFiClicked (object sender, EventArgs e)
{
MessageDialogs md = new MessageDialogs(MessageDialogs.DialogButtonType.YesNo, MainClass.Languages.Translate("question_default_ignorelist"), "", Gtk.MessageType.Question,parentWindow);
int result = md.ShowDialog();
if (result != (int)Gtk.ResponseType.Yes)
return;
MainClass.Settings.GenerateIgnoreFiles();
storeIFi.Clear();
foreach (IgnoreFolder ignoref in MainClass.Settings.IgnoresFiles){
storeIFi.AppendValues(ignoref.Folder,ignoref.IsForIde,ignoref.IsForPublish,ignoref);
}
}
protected void OnBtnAddIFiClicked (object sender, EventArgs e)
{
EntryDialog ed = new EntryDialog("",MainClass.Languages.Translate("name"),parentWindow);
int result = ed.Run();
if (result == (int)ResponseType.Ok){
if (!String.IsNullOrEmpty(ed.TextEntry) ){
IgnoreFolder ifol = new IgnoreFolder(ed.TextEntry,true,true);
storeIFi.AppendValues(ed.TextEntry,true,true,ifol);
ignoreFile.Add(ifol);
}
}
ed.Destroy();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Security;
using System.Threading;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace System.IO
{
internal partial class Win32FileStream
{
#if USE_OVERLAPPED
// This is an internal object extending TaskCompletionSource with fields
// for all of the relevant data necessary to complete the IO operation.
// This is used by AsyncFSCallback and all of the async methods.
unsafe private sealed class FileStreamCompletionSource : TaskCompletionSource<int>
{
private const long NoResult = 0;
private const long ResultSuccess = (long)1 << 32;
private const long ResultError = (long)2 << 32;
private const long RegisteringCancellation = (long)4 << 32;
private const long CompletedCallback = (long)8 << 32;
private const ulong ResultMask = ((ulong)uint.MaxValue) << 32;
private readonly ThreadPoolBoundHandle _handle;
private readonly int _numBufferedBytes;
private readonly CancellationToken _cancellationToken;
private CancellationTokenRegistration _cancellationRegistration;
#if DEBUG
private bool _cancellationHasBeenRegistered;
#endif
// Overlapped class will take care of the async IO operations in progress
// when an appdomain unload occurs.
private NativeOverlapped* _overlapped;
// Using long since this needs to be used in Interlocked APIs
private long _result;
private unsafe static IOCompletionCallback s_IOCallback;
private static Action<object> s_cancelCallback;
// Using RunContinuationsAsynchronously for compat reasons (old API used Task.Factory.StartNew for continuations)
internal FileStreamCompletionSource(int numBufferedBytes, byte[] bytes, ThreadPoolBoundHandle handle, CancellationToken cancellationToken)
: base(TaskCreationOptions.RunContinuationsAsynchronously)
{
_numBufferedBytes = numBufferedBytes;
_handle = handle;
_result = NoResult;
_cancellationToken = cancellationToken;
// Create a managed overlapped class
// We will set the file offsets later
var ioCallback = s_IOCallback; // cached static delegate; delay initialized due to it being SecurityCritical
if (ioCallback == null) s_IOCallback = ioCallback = new IOCompletionCallback(AsyncFSCallback);
_overlapped = handle.AllocateNativeOverlapped(ioCallback, this, bytes);
Debug.Assert(_overlapped != null, "Did Overlapped.Pack or Overlapped.UnsafePack just return a null?");
}
internal NativeOverlapped* Overlapped
{
[SecurityCritical]get { return _overlapped; }
}
public void SetCompletedSynchronously(int numBytes)
{
ReleaseNativeResource();
TrySetResult(numBytes + _numBufferedBytes);
}
public void RegisterForCancellation()
{
#if DEBUG
Debug.Assert(!_cancellationHasBeenRegistered, "Cannot register for cancellation twice");
_cancellationHasBeenRegistered = true;
#endif
// Quick check to make sure that the cancellation token supports cancellation, and that the IO hasn't completed
if ((_cancellationToken.CanBeCanceled) && (_overlapped != null))
{
var cancelCallback = s_cancelCallback;
if (cancelCallback == null) s_cancelCallback = cancelCallback = Cancel;
// Register the cancellation only if the IO hasn't completed
long packedResult = Interlocked.CompareExchange(ref _result, RegisteringCancellation, NoResult);
if (packedResult == NoResult)
{
_cancellationRegistration = _cancellationToken.Register(cancelCallback, this);
// Switch the result, just in case IO completed while we were setting the registration
packedResult = Interlocked.Exchange(ref _result, NoResult);
}
else if (packedResult != CompletedCallback)
{
// Failed to set the result, IO is in the process of completing
// Attempt to take the packed result
packedResult = Interlocked.Exchange(ref _result, NoResult);
}
// If we have a callback that needs to be completed
if ((packedResult != NoResult) && (packedResult != CompletedCallback) && (packedResult != RegisteringCancellation))
{
CompleteCallback((ulong)packedResult);
}
}
}
internal void ReleaseNativeResource()
{
// Ensure that cancellation has been completed and cleaned up
_cancellationRegistration.Dispose();
// Free the overlapped
// NOTE: The cancellation must *NOT* be running at this point, or it may observe freed memory
// (this is why we disposed the registration above)
if (_overlapped != null)
{
_handle.FreeNativeOverlapped(_overlapped);
_overlapped = null;
}
}
// When doing IO asynchronously (ie, _isAsync==true), this callback is
// called by a free thread in the threadpool when the IO operation
// completes.
unsafe private static void AsyncFSCallback(uint errorCode, uint numBytes, NativeOverlapped* pOverlapped)
{
// Extract async result from overlapped
FileStreamCompletionSource completionSource = (FileStreamCompletionSource)ThreadPoolBoundHandle.GetNativeOverlappedState(pOverlapped);
Debug.Assert(completionSource._overlapped == pOverlapped, "Overlaps don't match");
// Handle reading from & writing to closed pipes. While I'm not sure
// this is entirely necessary anymore, maybe it's possible for
// an async read on a pipe to be issued and then the pipe is closed,
// returning this error. This may very well be necessary.
ulong packedResult;
if (errorCode != 0 && errorCode != Win32FileStream.ERROR_BROKEN_PIPE && errorCode != Win32FileStream.ERROR_NO_DATA)
{
packedResult = ((ulong)ResultError | errorCode);
}
else
{
packedResult = ((ulong)ResultSuccess | numBytes);
}
// Stow the result so that other threads can observe it
// And, if no other thread is registering cancellation, continue
if (NoResult == Interlocked.Exchange(ref completionSource._result, (long)packedResult))
{
// Successfully set the state, attempt to take back the callback
if (Interlocked.Exchange(ref completionSource._result, CompletedCallback) != NoResult)
{
// Successfully got the callback, finish the callback
completionSource.CompleteCallback(packedResult);
}
// else: Some other thread stole the result, so now it is responsible to finish the callback
}
// else: Some other thread is registering a cancellation, so it *must* finish the callback
}
private void CompleteCallback(ulong packedResult) {
// Free up the native resource and cancellation registration
ReleaseNativeResource();
// Unpack the result and send it to the user
long result = (long)(packedResult & ResultMask);
if (result == ResultError)
{
int errorCode = unchecked((int)(packedResult & uint.MaxValue));
if (errorCode == Interop.mincore.Errors.ERROR_OPERATION_ABORTED)
{
TrySetCanceled(_cancellationToken.IsCancellationRequested ? _cancellationToken : new CancellationToken(true));
}
else
{
TrySetException(Win32Marshal.GetExceptionForWin32Error(errorCode));
}
}
else
{
Debug.Assert(result == ResultSuccess, "Unknown result");
TrySetResult((int)(packedResult & uint.MaxValue) + _numBufferedBytes);
}
}
private static void Cancel(object state)
{
// WARNING: This may potentially be called under a lock (during cancellation registration)
FileStreamCompletionSource completionSource = state as FileStreamCompletionSource;
Debug.Assert(completionSource != null, "Unknown state passed to cancellation");
Debug.Assert(completionSource._overlapped != null && !completionSource.Task.IsCompleted, "IO should not have completed yet");
// If the handle is still valid, attempt to cancel the IO
if ((!completionSource._handle.Handle.IsInvalid) && (!Interop.mincore.CancelIoEx(completionSource._handle.Handle, completionSource._overlapped)))
{
int errorCode = Marshal.GetLastWin32Error();
// ERROR_NOT_FOUND is returned if CancelIoEx cannot find the request to cancel.
// This probably means that the IO operation has completed.
if (errorCode != Interop.mincore.Errors.ERROR_NOT_FOUND)
{
throw Win32Marshal.GetExceptionForWin32Error(errorCode);
}
}
}
}
#endif
}
}
| |
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Batch.Protocol
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// CertificateOperations operations.
/// </summary>
internal partial class CertificateOperations : Microsoft.Rest.IServiceOperations<BatchServiceClient>, ICertificateOperations
{
/// <summary>
/// Initializes a new instance of the CertificateOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal CertificateOperations(BatchServiceClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the BatchServiceClient
/// </summary>
public BatchServiceClient Client { get; private set; }
/// <summary>
/// Adds a certificate to the specified account.
/// </summary>
/// <param name='certificate'>
/// The certificate to be added.
/// </param>
/// <param name='certificateAddOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// 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.AzureOperationHeaderResponse<CertificateAddHeaders>> AddWithHttpMessagesAsync(CertificateAddParameter certificate, CertificateAddOptions certificateAddOptions = default(CertificateAddOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (certificate == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "certificate");
}
if (certificate != null)
{
certificate.Validate();
}
if (this.Client.ApiVersion == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
int? timeout = default(int?);
if (certificateAddOptions != null)
{
timeout = certificateAddOptions.Timeout;
}
string clientRequestId = default(string);
if (certificateAddOptions != null)
{
clientRequestId = certificateAddOptions.ClientRequestId;
}
bool? returnClientRequestId = default(bool?);
if (certificateAddOptions != null)
{
returnClientRequestId = certificateAddOptions.ReturnClientRequestId;
}
System.DateTime? ocpDate = default(System.DateTime?);
if (certificateAddOptions != null)
{
ocpDate = certificateAddOptions.OcpDate;
}
// 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("certificate", certificate);
tracingParameters.Add("timeout", timeout);
tracingParameters.Add("clientRequestId", clientRequestId);
tracingParameters.Add("returnClientRequestId", returnClientRequestId);
tracingParameters.Add("ocpDate", ocpDate);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Add", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "certificates").ToString();
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 (timeout != null)
{
_queryParameters.Add(string.Format("timeout={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(timeout, this.Client.SerializationSettings).Trim('"'))));
}
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("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("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 (clientRequestId != null)
{
if (_httpRequest.Headers.Contains("client-request-id"))
{
_httpRequest.Headers.Remove("client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("client-request-id", clientRequestId);
}
if (returnClientRequestId != null)
{
if (_httpRequest.Headers.Contains("return-client-request-id"))
{
_httpRequest.Headers.Remove("return-client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("return-client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(returnClientRequestId, this.Client.SerializationSettings).Trim('"'));
}
if (ocpDate != null)
{
if (_httpRequest.Headers.Contains("ocp-date"))
{
_httpRequest.Headers.Remove("ocp-date");
}
_httpRequest.Headers.TryAddWithoutValidation("ocp-date", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(ocpDate, new Microsoft.Rest.Serialization.DateTimeRfc1123JsonConverter()).Trim('"'));
}
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(certificate != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(certificate, 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; odata=minimalmetadata; 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 != 201)
{
var ex = new BatchErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
BatchError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<BatchError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
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 (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationHeaderResponse<CertificateAddHeaders>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault();
}
try
{
_result.Headers = _httpResponse.GetHeadersAsJson().ToObject<CertificateAddHeaders>(Newtonsoft.Json.JsonSerializer.Create(this.Client.DeserializationSettings));
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Lists all of the certificates that have been added to the specified
/// account.
/// </summary>
/// <param name='certificateListOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// 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<Microsoft.Rest.Azure.IPage<Certificate>,CertificateListHeaders>> ListWithHttpMessagesAsync(CertificateListOptions certificateListOptions = default(CertificateListOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (this.Client.ApiVersion == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
string filter = default(string);
if (certificateListOptions != null)
{
filter = certificateListOptions.Filter;
}
string select = default(string);
if (certificateListOptions != null)
{
select = certificateListOptions.Select;
}
int? maxResults = default(int?);
if (certificateListOptions != null)
{
maxResults = certificateListOptions.MaxResults;
}
int? timeout = default(int?);
if (certificateListOptions != null)
{
timeout = certificateListOptions.Timeout;
}
string clientRequestId = default(string);
if (certificateListOptions != null)
{
clientRequestId = certificateListOptions.ClientRequestId;
}
bool? returnClientRequestId = default(bool?);
if (certificateListOptions != null)
{
returnClientRequestId = certificateListOptions.ReturnClientRequestId;
}
System.DateTime? ocpDate = default(System.DateTime?);
if (certificateListOptions != null)
{
ocpDate = certificateListOptions.OcpDate;
}
// 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("filter", filter);
tracingParameters.Add("select", select);
tracingParameters.Add("maxResults", maxResults);
tracingParameters.Add("timeout", timeout);
tracingParameters.Add("clientRequestId", clientRequestId);
tracingParameters.Add("returnClientRequestId", returnClientRequestId);
tracingParameters.Add("ocpDate", ocpDate);
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("/") ? "" : "/")), "certificates").ToString();
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 (filter != null)
{
_queryParameters.Add(string.Format("$filter={0}", System.Uri.EscapeDataString(filter)));
}
if (select != null)
{
_queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(select)));
}
if (maxResults != null)
{
_queryParameters.Add(string.Format("maxresults={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(maxResults, this.Client.SerializationSettings).Trim('"'))));
}
if (timeout != null)
{
_queryParameters.Add(string.Format("timeout={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(timeout, this.Client.SerializationSettings).Trim('"'))));
}
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("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 (clientRequestId != null)
{
if (_httpRequest.Headers.Contains("client-request-id"))
{
_httpRequest.Headers.Remove("client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("client-request-id", clientRequestId);
}
if (returnClientRequestId != null)
{
if (_httpRequest.Headers.Contains("return-client-request-id"))
{
_httpRequest.Headers.Remove("return-client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("return-client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(returnClientRequestId, this.Client.SerializationSettings).Trim('"'));
}
if (ocpDate != null)
{
if (_httpRequest.Headers.Contains("ocp-date"))
{
_httpRequest.Headers.Remove("ocp-date");
}
_httpRequest.Headers.TryAddWithoutValidation("ocp-date", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(ocpDate, new Microsoft.Rest.Serialization.DateTimeRfc1123JsonConverter()).Trim('"'));
}
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 BatchErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
BatchError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<BatchError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
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 (_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<Microsoft.Rest.Azure.IPage<Certificate>,CertificateListHeaders>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Certificate>>(_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);
}
}
try
{
_result.Headers = _httpResponse.GetHeadersAsJson().ToObject<CertificateListHeaders>(Newtonsoft.Json.JsonSerializer.Create(this.Client.DeserializationSettings));
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Cancels a failed deletion of a certificate from the specified account.
/// </summary>
/// <param name='thumbprintAlgorithm'>
/// The algorithm used to derive the thumbprint parameter. This must be sha1.
/// </param>
/// <param name='thumbprint'>
/// The thumbprint of the certificate being deleted.
/// </param>
/// <param name='certificateCancelDeletionOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// 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.AzureOperationHeaderResponse<CertificateCancelDeletionHeaders>> CancelDeletionWithHttpMessagesAsync(string thumbprintAlgorithm, string thumbprint, CertificateCancelDeletionOptions certificateCancelDeletionOptions = default(CertificateCancelDeletionOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (thumbprintAlgorithm == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "thumbprintAlgorithm");
}
if (thumbprint == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "thumbprint");
}
if (this.Client.ApiVersion == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
int? timeout = default(int?);
if (certificateCancelDeletionOptions != null)
{
timeout = certificateCancelDeletionOptions.Timeout;
}
string clientRequestId = default(string);
if (certificateCancelDeletionOptions != null)
{
clientRequestId = certificateCancelDeletionOptions.ClientRequestId;
}
bool? returnClientRequestId = default(bool?);
if (certificateCancelDeletionOptions != null)
{
returnClientRequestId = certificateCancelDeletionOptions.ReturnClientRequestId;
}
System.DateTime? ocpDate = default(System.DateTime?);
if (certificateCancelDeletionOptions != null)
{
ocpDate = certificateCancelDeletionOptions.OcpDate;
}
// 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("thumbprintAlgorithm", thumbprintAlgorithm);
tracingParameters.Add("thumbprint", thumbprint);
tracingParameters.Add("timeout", timeout);
tracingParameters.Add("clientRequestId", clientRequestId);
tracingParameters.Add("returnClientRequestId", returnClientRequestId);
tracingParameters.Add("ocpDate", ocpDate);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "CancelDeletion", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "certificates(thumbprintAlgorithm={thumbprintAlgorithm},thumbprint={thumbprint})/canceldelete").ToString();
_url = _url.Replace("{thumbprintAlgorithm}", System.Uri.EscapeDataString(thumbprintAlgorithm));
_url = _url.Replace("{thumbprint}", System.Uri.EscapeDataString(thumbprint));
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 (timeout != null)
{
_queryParameters.Add(string.Format("timeout={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(timeout, this.Client.SerializationSettings).Trim('"'))));
}
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("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("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 (clientRequestId != null)
{
if (_httpRequest.Headers.Contains("client-request-id"))
{
_httpRequest.Headers.Remove("client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("client-request-id", clientRequestId);
}
if (returnClientRequestId != null)
{
if (_httpRequest.Headers.Contains("return-client-request-id"))
{
_httpRequest.Headers.Remove("return-client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("return-client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(returnClientRequestId, this.Client.SerializationSettings).Trim('"'));
}
if (ocpDate != null)
{
if (_httpRequest.Headers.Contains("ocp-date"))
{
_httpRequest.Headers.Remove("ocp-date");
}
_httpRequest.Headers.TryAddWithoutValidation("ocp-date", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(ocpDate, new Microsoft.Rest.Serialization.DateTimeRfc1123JsonConverter()).Trim('"'));
}
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 != 204)
{
var ex = new BatchErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
BatchError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<BatchError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
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 (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationHeaderResponse<CertificateCancelDeletionHeaders>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault();
}
try
{
_result.Headers = _httpResponse.GetHeadersAsJson().ToObject<CertificateCancelDeletionHeaders>(Newtonsoft.Json.JsonSerializer.Create(this.Client.DeserializationSettings));
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes a certificate from the specified account.
/// </summary>
/// <param name='thumbprintAlgorithm'>
/// The algorithm used to derive the thumbprint parameter. This must be sha1.
/// </param>
/// <param name='thumbprint'>
/// The thumbprint of the certificate to be deleted.
/// </param>
/// <param name='certificateDeleteOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// 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.AzureOperationHeaderResponse<CertificateDeleteHeaders>> DeleteWithHttpMessagesAsync(string thumbprintAlgorithm, string thumbprint, CertificateDeleteOptions certificateDeleteOptions = default(CertificateDeleteOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (thumbprintAlgorithm == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "thumbprintAlgorithm");
}
if (thumbprint == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "thumbprint");
}
if (this.Client.ApiVersion == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
int? timeout = default(int?);
if (certificateDeleteOptions != null)
{
timeout = certificateDeleteOptions.Timeout;
}
string clientRequestId = default(string);
if (certificateDeleteOptions != null)
{
clientRequestId = certificateDeleteOptions.ClientRequestId;
}
bool? returnClientRequestId = default(bool?);
if (certificateDeleteOptions != null)
{
returnClientRequestId = certificateDeleteOptions.ReturnClientRequestId;
}
System.DateTime? ocpDate = default(System.DateTime?);
if (certificateDeleteOptions != null)
{
ocpDate = certificateDeleteOptions.OcpDate;
}
// 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("thumbprintAlgorithm", thumbprintAlgorithm);
tracingParameters.Add("thumbprint", thumbprint);
tracingParameters.Add("timeout", timeout);
tracingParameters.Add("clientRequestId", clientRequestId);
tracingParameters.Add("returnClientRequestId", returnClientRequestId);
tracingParameters.Add("ocpDate", ocpDate);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "certificates(thumbprintAlgorithm={thumbprintAlgorithm},thumbprint={thumbprint})").ToString();
_url = _url.Replace("{thumbprintAlgorithm}", System.Uri.EscapeDataString(thumbprintAlgorithm));
_url = _url.Replace("{thumbprint}", System.Uri.EscapeDataString(thumbprint));
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 (timeout != null)
{
_queryParameters.Add(string.Format("timeout={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(timeout, this.Client.SerializationSettings).Trim('"'))));
}
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("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 (clientRequestId != null)
{
if (_httpRequest.Headers.Contains("client-request-id"))
{
_httpRequest.Headers.Remove("client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("client-request-id", clientRequestId);
}
if (returnClientRequestId != null)
{
if (_httpRequest.Headers.Contains("return-client-request-id"))
{
_httpRequest.Headers.Remove("return-client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("return-client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(returnClientRequestId, this.Client.SerializationSettings).Trim('"'));
}
if (ocpDate != null)
{
if (_httpRequest.Headers.Contains("ocp-date"))
{
_httpRequest.Headers.Remove("ocp-date");
}
_httpRequest.Headers.TryAddWithoutValidation("ocp-date", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(ocpDate, new Microsoft.Rest.Serialization.DateTimeRfc1123JsonConverter()).Trim('"'));
}
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)
{
var ex = new BatchErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
BatchError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<BatchError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
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 (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationHeaderResponse<CertificateDeleteHeaders>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault();
}
try
{
_result.Headers = _httpResponse.GetHeadersAsJson().ToObject<CertificateDeleteHeaders>(Newtonsoft.Json.JsonSerializer.Create(this.Client.DeserializationSettings));
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets information about the specified certificate.
/// </summary>
/// <param name='thumbprintAlgorithm'>
/// The algorithm used to derive the thumbprint parameter. This must be sha1.
/// </param>
/// <param name='thumbprint'>
/// The thumbprint of the certificate to get.
/// </param>
/// <param name='certificateGetOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// 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<Certificate,CertificateGetHeaders>> GetWithHttpMessagesAsync(string thumbprintAlgorithm, string thumbprint, CertificateGetOptions certificateGetOptions = default(CertificateGetOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (thumbprintAlgorithm == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "thumbprintAlgorithm");
}
if (thumbprint == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "thumbprint");
}
if (this.Client.ApiVersion == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
string select = default(string);
if (certificateGetOptions != null)
{
select = certificateGetOptions.Select;
}
int? timeout = default(int?);
if (certificateGetOptions != null)
{
timeout = certificateGetOptions.Timeout;
}
string clientRequestId = default(string);
if (certificateGetOptions != null)
{
clientRequestId = certificateGetOptions.ClientRequestId;
}
bool? returnClientRequestId = default(bool?);
if (certificateGetOptions != null)
{
returnClientRequestId = certificateGetOptions.ReturnClientRequestId;
}
System.DateTime? ocpDate = default(System.DateTime?);
if (certificateGetOptions != null)
{
ocpDate = certificateGetOptions.OcpDate;
}
// 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("thumbprintAlgorithm", thumbprintAlgorithm);
tracingParameters.Add("thumbprint", thumbprint);
tracingParameters.Add("select", select);
tracingParameters.Add("timeout", timeout);
tracingParameters.Add("clientRequestId", clientRequestId);
tracingParameters.Add("returnClientRequestId", returnClientRequestId);
tracingParameters.Add("ocpDate", ocpDate);
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("/") ? "" : "/")), "certificates(thumbprintAlgorithm={thumbprintAlgorithm},thumbprint={thumbprint})").ToString();
_url = _url.Replace("{thumbprintAlgorithm}", System.Uri.EscapeDataString(thumbprintAlgorithm));
_url = _url.Replace("{thumbprint}", System.Uri.EscapeDataString(thumbprint));
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 (select != null)
{
_queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(select)));
}
if (timeout != null)
{
_queryParameters.Add(string.Format("timeout={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(timeout, this.Client.SerializationSettings).Trim('"'))));
}
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("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 (clientRequestId != null)
{
if (_httpRequest.Headers.Contains("client-request-id"))
{
_httpRequest.Headers.Remove("client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("client-request-id", clientRequestId);
}
if (returnClientRequestId != null)
{
if (_httpRequest.Headers.Contains("return-client-request-id"))
{
_httpRequest.Headers.Remove("return-client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("return-client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(returnClientRequestId, this.Client.SerializationSettings).Trim('"'));
}
if (ocpDate != null)
{
if (_httpRequest.Headers.Contains("ocp-date"))
{
_httpRequest.Headers.Remove("ocp-date");
}
_httpRequest.Headers.TryAddWithoutValidation("ocp-date", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(ocpDate, new Microsoft.Rest.Serialization.DateTimeRfc1123JsonConverter()).Trim('"'));
}
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 BatchErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
BatchError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<BatchError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
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 (_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<Certificate,CertificateGetHeaders>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Certificate>(_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);
}
}
try
{
_result.Headers = _httpResponse.GetHeadersAsJson().ToObject<CertificateGetHeaders>(Newtonsoft.Json.JsonSerializer.Create(this.Client.DeserializationSettings));
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Lists all of the certificates that have been added to the specified
/// account.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='certificateListNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// 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<Microsoft.Rest.Azure.IPage<Certificate>,CertificateListHeaders>> ListNextWithHttpMessagesAsync(string nextPageLink, CertificateListNextOptions certificateListNextOptions = default(CertificateListNextOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (nextPageLink == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "nextPageLink");
}
string clientRequestId = default(string);
if (certificateListNextOptions != null)
{
clientRequestId = certificateListNextOptions.ClientRequestId;
}
bool? returnClientRequestId = default(bool?);
if (certificateListNextOptions != null)
{
returnClientRequestId = certificateListNextOptions.ReturnClientRequestId;
}
System.DateTime? ocpDate = default(System.DateTime?);
if (certificateListNextOptions != null)
{
ocpDate = certificateListNextOptions.OcpDate;
}
// 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("nextPageLink", nextPageLink);
tracingParameters.Add("clientRequestId", clientRequestId);
tracingParameters.Add("returnClientRequestId", returnClientRequestId);
tracingParameters.Add("ocpDate", ocpDate);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
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("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 (clientRequestId != null)
{
if (_httpRequest.Headers.Contains("client-request-id"))
{
_httpRequest.Headers.Remove("client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("client-request-id", clientRequestId);
}
if (returnClientRequestId != null)
{
if (_httpRequest.Headers.Contains("return-client-request-id"))
{
_httpRequest.Headers.Remove("return-client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("return-client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(returnClientRequestId, this.Client.SerializationSettings).Trim('"'));
}
if (ocpDate != null)
{
if (_httpRequest.Headers.Contains("ocp-date"))
{
_httpRequest.Headers.Remove("ocp-date");
}
_httpRequest.Headers.TryAddWithoutValidation("ocp-date", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(ocpDate, new Microsoft.Rest.Serialization.DateTimeRfc1123JsonConverter()).Trim('"'));
}
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 BatchErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
BatchError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<BatchError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
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 (_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<Microsoft.Rest.Azure.IPage<Certificate>,CertificateListHeaders>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Certificate>>(_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);
}
}
try
{
_result.Headers = _httpResponse.GetHeadersAsJson().ToObject<CertificateListHeaders>(Newtonsoft.Json.JsonSerializer.Create(this.Client.DeserializationSettings));
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
/*
** SGI FREE SOFTWARE LICENSE B (Version 2.0, Sept. 18, 2008)
** Copyright (C) 2011 Silicon Graphics, Inc.
** All Rights Reserved.
**
** 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 including the dates of first publication and either this
** permission notice or a reference to http://oss.sgi.com/projects/FreeB/ 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 SILICON GRAPHICS, INC.
** 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.
**
** Except as contained in this notice, the name of Silicon Graphics, Inc. shall not
** be used in advertising or otherwise to promote the sale, use or other dealings in
** this Software without prior written authorization from Silicon Graphics, Inc.
*/
/*
** Original Author: Eric Veach, July 1994.
** libtess2: Mikko Mononen, http://code.google.com/p/libtess2/.
** LibTessDotNet: Remi Gillig, https://github.com/speps/LibTessDotNet
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace UnityEngine.Experimental.Rendering.LWRP
{
#if DOUBLE
using Real = System.Double;
namespace LibTessDotNet.Double
#else
using Real = System.Single;
namespace LibTessDotNet
#endif
{
internal struct Vec3
{
public readonly static Vec3 Zero = new Vec3();
public Real X, Y, Z;
public Real this[int index]
{
get
{
if (index == 0) return X;
if (index == 1) return Y;
if (index == 2) return Z;
throw new IndexOutOfRangeException();
}
set
{
if (index == 0) X = value;
else if (index == 1) Y = value;
else if (index == 2) Z = value;
else throw new IndexOutOfRangeException();
}
}
public static void Sub(ref Vec3 lhs, ref Vec3 rhs, out Vec3 result)
{
result.X = lhs.X - rhs.X;
result.Y = lhs.Y - rhs.Y;
result.Z = lhs.Z - rhs.Z;
}
public static void Neg(ref Vec3 v)
{
v.X = -v.X;
v.Y = -v.Y;
v.Z = -v.Z;
}
public static void Dot(ref Vec3 u, ref Vec3 v, out Real dot)
{
dot = u.X * v.X + u.Y * v.Y + u.Z * v.Z;
}
public static void Normalize(ref Vec3 v)
{
var len = v.X * v.X + v.Y * v.Y + v.Z * v.Z;
Debug.Assert(len >= 0.0f);
len = 1.0f / (Real)Math.Sqrt(len);
v.X *= len;
v.Y *= len;
v.Z *= len;
}
public static int LongAxis(ref Vec3 v)
{
int i = 0;
if (Math.Abs(v.Y) > Math.Abs(v.X)) i = 1;
if (Math.Abs(v.Z) > Math.Abs(i == 0 ? v.X : v.Y)) i = 2;
return i;
}
public override string ToString()
{
return string.Format("{0}, {1}, {2}", X, Y, Z);
}
}
internal static class MeshUtils
{
public const int Undef = ~0;
public abstract class Pooled<T> where T : Pooled<T>, new()
{
private static Stack<T> _stack;
public abstract void Reset();
public virtual void OnFree() { }
public static T Create()
{
if (_stack != null && _stack.Count > 0)
{
return _stack.Pop();
}
return new T();
}
public void Free()
{
OnFree();
Reset();
if (_stack == null)
{
_stack = new Stack<T>();
}
_stack.Push((T)this);
}
}
public class Vertex : Pooled<Vertex>
{
internal Vertex _prev, _next;
internal Edge _anEdge;
internal Vec3 _coords;
internal Real _s, _t;
internal PQHandle _pqHandle;
internal int _n;
internal object _data;
public override void Reset()
{
_prev = _next = null;
_anEdge = null;
_coords = Vec3.Zero;
_s = 0;
_t = 0;
_pqHandle = new PQHandle();
_n = 0;
_data = null;
}
}
public class Face : Pooled<Face>
{
internal Face _prev, _next;
internal Edge _anEdge;
internal Face _trail;
internal int _n;
internal bool _marked, _inside;
internal int VertsCount
{
get
{
int n = 0;
var eCur = _anEdge;
do {
n++;
eCur = eCur._Lnext;
} while (eCur != _anEdge);
return n;
}
}
public override void Reset()
{
_prev = _next = null;
_anEdge = null;
_trail = null;
_n = 0;
_marked = false;
_inside = false;
}
}
public struct EdgePair
{
internal Edge _e, _eSym;
public static EdgePair Create()
{
var pair = new MeshUtils.EdgePair();
pair._e = MeshUtils.Edge.Create();
pair._e._pair = pair;
pair._eSym = MeshUtils.Edge.Create();
pair._eSym._pair = pair;
return pair;
}
public void Reset()
{
_e = _eSym = null;
}
}
public class Edge : Pooled<Edge>
{
internal EdgePair _pair;
internal Edge _next, _Sym, _Onext, _Lnext;
internal Vertex _Org;
internal Face _Lface;
internal Tess.ActiveRegion _activeRegion;
internal int _winding;
internal Face _Rface { get { return _Sym._Lface; } set { _Sym._Lface = value; } }
internal Vertex _Dst { get { return _Sym._Org; } set { _Sym._Org = value; } }
internal Edge _Oprev { get { return _Sym._Lnext; } set { _Sym._Lnext = value; } }
internal Edge _Lprev { get { return _Onext._Sym; } set { _Onext._Sym = value; } }
internal Edge _Dprev { get { return _Lnext._Sym; } set { _Lnext._Sym = value; } }
internal Edge _Rprev { get { return _Sym._Onext; } set { _Sym._Onext = value; } }
internal Edge _Dnext { get { return _Rprev._Sym; } set { _Rprev._Sym = value; } }
internal Edge _Rnext { get { return _Oprev._Sym; } set { _Oprev._Sym = value; } }
internal static void EnsureFirst(ref Edge e)
{
if (e == e._pair._eSym)
{
e = e._Sym;
}
}
public override void Reset()
{
_pair.Reset();
_next = _Sym = _Onext = _Lnext = null;
_Org = null;
_Lface = null;
_activeRegion = null;
_winding = 0;
}
}
/// <summary>
/// MakeEdge creates a new pair of half-edges which form their own loop.
/// No vertex or face structures are allocated, but these must be assigned
/// before the current edge operation is completed.
/// </summary>
public static Edge MakeEdge(Edge eNext)
{
Debug.Assert(eNext != null);
var pair = EdgePair.Create();
var e = pair._e;
var eSym = pair._eSym;
// Make sure eNext points to the first edge of the edge pair
Edge.EnsureFirst(ref eNext);
// Insert in circular doubly-linked list before eNext.
// Note that the prev pointer is stored in Sym->next.
var ePrev = eNext._Sym._next;
eSym._next = ePrev;
ePrev._Sym._next = e;
e._next = eNext;
eNext._Sym._next = eSym;
e._Sym = eSym;
e._Onext = e;
e._Lnext = eSym;
e._Org = null;
e._Lface = null;
e._winding = 0;
e._activeRegion = null;
eSym._Sym = e;
eSym._Onext = eSym;
eSym._Lnext = e;
eSym._Org = null;
eSym._Lface = null;
eSym._winding = 0;
eSym._activeRegion = null;
return e;
}
/// <summary>
/// Splice( a, b ) is best described by the Guibas/Stolfi paper or the
/// CS348a notes (see Mesh.cs). Basically it modifies the mesh so that
/// a->Onext and b->Onext are exchanged. This can have various effects
/// depending on whether a and b belong to different face or vertex rings.
/// For more explanation see Mesh.Splice().
/// </summary>
public static void Splice(Edge a, Edge b)
{
var aOnext = a._Onext;
var bOnext = b._Onext;
aOnext._Sym._Lnext = b;
bOnext._Sym._Lnext = a;
a._Onext = bOnext;
b._Onext = aOnext;
}
/// <summary>
/// MakeVertex( eOrig, vNext ) attaches a new vertex and makes it the
/// origin of all edges in the vertex loop to which eOrig belongs. "vNext" gives
/// a place to insert the new vertex in the global vertex list. We insert
/// the new vertex *before* vNext so that algorithms which walk the vertex
/// list will not see the newly created vertices.
/// </summary>
public static void MakeVertex(Edge eOrig, Vertex vNext)
{
var vNew = MeshUtils.Vertex.Create();
// insert in circular doubly-linked list before vNext
var vPrev = vNext._prev;
vNew._prev = vPrev;
vPrev._next = vNew;
vNew._next = vNext;
vNext._prev = vNew;
vNew._anEdge = eOrig;
// leave coords, s, t undefined
// fix other edges on this vertex loop
var e = eOrig;
do {
e._Org = vNew;
e = e._Onext;
} while (e != eOrig);
}
/// <summary>
/// MakeFace( eOrig, fNext ) attaches a new face and makes it the left
/// face of all edges in the face loop to which eOrig belongs. "fNext" gives
/// a place to insert the new face in the global face list. We insert
/// the new face *before* fNext so that algorithms which walk the face
/// list will not see the newly created faces.
/// </summary>
public static void MakeFace(Edge eOrig, Face fNext)
{
var fNew = MeshUtils.Face.Create();
// insert in circular doubly-linked list before fNext
var fPrev = fNext._prev;
fNew._prev = fPrev;
fPrev._next = fNew;
fNew._next = fNext;
fNext._prev = fNew;
fNew._anEdge = eOrig;
fNew._trail = null;
fNew._marked = false;
// The new face is marked "inside" if the old one was. This is a
// convenience for the common case where a face has been split in two.
fNew._inside = fNext._inside;
// fix other edges on this face loop
var e = eOrig;
do {
e._Lface = fNew;
e = e._Lnext;
} while (e != eOrig);
}
/// <summary>
/// KillEdge( eDel ) destroys an edge (the half-edges eDel and eDel->Sym),
/// and removes from the global edge list.
/// </summary>
public static void KillEdge(Edge eDel)
{
// Half-edges are allocated in pairs, see EdgePair above
Edge.EnsureFirst(ref eDel);
// delete from circular doubly-linked list
var eNext = eDel._next;
var ePrev = eDel._Sym._next;
eNext._Sym._next = ePrev;
ePrev._Sym._next = eNext;
eDel.Free();
}
/// <summary>
/// KillVertex( vDel ) destroys a vertex and removes it from the global
/// vertex list. It updates the vertex loop to point to a given new vertex.
/// </summary>
public static void KillVertex(Vertex vDel, Vertex newOrg)
{
var eStart = vDel._anEdge;
// change the origin of all affected edges
var e = eStart;
do {
e._Org = newOrg;
e = e._Onext;
} while (e != eStart);
// delete from circular doubly-linked list
var vPrev = vDel._prev;
var vNext = vDel._next;
vNext._prev = vPrev;
vPrev._next = vNext;
vDel.Free();
}
/// <summary>
/// KillFace( fDel ) destroys a face and removes it from the global face
/// list. It updates the face loop to point to a given new face.
/// </summary>
public static void KillFace(Face fDel, Face newLFace)
{
var eStart = fDel._anEdge;
// change the left face of all affected edges
var e = eStart;
do {
e._Lface = newLFace;
e = e._Lnext;
} while (e != eStart);
// delete from circular doubly-linked list
var fPrev = fDel._prev;
var fNext = fDel._next;
fNext._prev = fPrev;
fPrev._next = fNext;
fDel.Free();
}
/// <summary>
/// Return signed area of face.
/// </summary>
public static Real FaceArea(Face f)
{
Real area = 0;
var e = f._anEdge;
do
{
area += (e._Org._s - e._Dst._s) * (e._Org._t + e._Dst._t);
e = e._Lnext;
} while (e != f._anEdge);
return area;
}
}
}
}
| |
#region Disclaimer/Info
///////////////////////////////////////////////////////////////////////////////////////////////////
// Subtext WebLog
//
// Subtext is an open source weblog system that is a fork of the .TEXT
// weblog system.
//
// For updated news and information please visit http://subtextproject.com/
// Subtext is hosted at Google Code at http://code.google.com/p/subtext/
// The development mailing list is at subtext@googlegroups.com
//
// This project is licensed under the BSD license. See the License.txt file for more information.
///////////////////////////////////////////////////////////////////////////////////////////////////
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Web.UI.WebControls;
using Subtext.Extensibility.Interfaces;
using Subtext.Framework;
using Subtext.Framework.Components;
using Subtext.Framework.Configuration;
using Subtext.Web.Admin.Commands;
using Subtext.Web.Properties;
namespace Subtext.Web.Admin.Pages
{
// TODO: import - reconcile duplicates
// TODO: CheckAll client-side, confirm bulk delete (add cmd)
public partial class EditLinks : AdminPage
{
private const string VSKEY_LINKID = "LinkID";
private bool _isListHidden = false;
protected CheckBoxList cklCategories;
private int _resultsPageNumber = 0;
public EditLinks()
{
TabSectionId = "Links";
}
private int? filterCategoryID
{
get
{
if(ViewState["filterCategoryID"] == null)
{
return null;
}
else
{
return (int)ViewState["filterCategoryID"];
}
}
set { ViewState["filterCategoryID"] = value; }
}
public int LinkID
{
get
{
if(ViewState[VSKEY_LINKID] != null)
{
return (int)ViewState[VSKEY_LINKID];
}
else
{
return NullValue.NullInt32;
}
}
set { ViewState[VSKEY_LINKID] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
rprSelectionList.Visible = true;
headerLiteral.Visible = true;
BindLocalUI();
if(!IsPostBack)
{
if(Request.QueryString[Keys.QRYSTR_PAGEINDEX] != null)
{
_resultsPageNumber = Convert.ToInt32(Request.QueryString[Keys.QRYSTR_PAGEINDEX]);
}
if(Request.QueryString[Keys.QRYSTR_CATEGORYID] != null)
{
filterCategoryID = Convert.ToInt32(Request.QueryString[Keys.QRYSTR_CATEGORYID]);
}
resultsPager.PageSize = Preferences.ListingItemCount;
resultsPager.PageIndex = _resultsPageNumber;
if(filterCategoryID != null)
{
resultsPager.UrlFormat += string.Format(CultureInfo.InvariantCulture, "&{0}={1}",
Keys.QRYSTR_CATEGORYID, filterCategoryID);
}
BindList();
}
}
private void BindLocalUI()
{
LinkButton lkbNewLink = Utilities.CreateLinkButton("New Link");
lkbNewLink.Click += lkbNewLink_Click;
lkbNewLink.CausesValidation = false;
AdminMasterPage.AddToActions(lkbNewLink);
HyperLink lnkEditCategories = Utilities.CreateHyperLink(Resources.Label_EditCategories,
string.Format(CultureInfo.InvariantCulture,
"{0}?{1}={2}",
Constants.URL_EDITCATEGORIES,
Keys.QRYSTR_CATEGORYTYPE,
CategoryType.LinkCollection));
AdminMasterPage.AddToActions(lnkEditCategories);
}
private void BindList()
{
Edit.Visible = false;
IPagedCollection<Link> selectionList = Repository.GetPagedLinks(filterCategoryID, _resultsPageNumber,
resultsPager.PageSize, true);
if(selectionList.Count > 0)
{
resultsPager.ItemCount = selectionList.MaxItems;
rprSelectionList.DataSource = selectionList;
rprSelectionList.DataBind();
}
else
{
// TODO: no existing items handling. add label and indicate no existing items. pop open edit.
}
}
private void BindLinkEdit()
{
Link currentLink = Repository.GetLink(LinkID);
rprSelectionList.Visible = false;
headerLiteral.Visible = false;
// ImportExport.Visible = false;
Edit.Visible = true;
lblEntryID.Text = currentLink.Id.ToString(CultureInfo.InvariantCulture);
txbTitle.Text = currentLink.Title;
txbUrl.Text = currentLink.Url;
txbRss.Text = currentLink.Rss;
txtXfn.Text = currentLink.Relation;
chkNewWindow.Checked = currentLink.NewWindow;
ckbIsActive.Checked = currentLink.IsActive;
BindLinkCategories();
ddlCategories.Items.FindByValue(currentLink.CategoryId.ToString(CultureInfo.InvariantCulture)).Selected =
true;
if(AdminMasterPage != null)
{
string title = string.Format(CultureInfo.InvariantCulture, "Editing Link \"{0}\"", currentLink.Title);
AdminMasterPage.Title = title;
}
}
public void BindLinkCategories()
{
ICollection<LinkCategory> selectionList = Links.GetCategories(CategoryType.LinkCollection, ActiveFilter.None);
if(selectionList != null && selectionList.Count != 0)
{
ddlCategories.DataSource = selectionList;
ddlCategories.DataValueField = "Id";
ddlCategories.DataTextField = "Title";
ddlCategories.DataBind();
}
else
{
Messages.ShowError(Resources.EditLinks_NeedToAddCategoryFirst);
Edit.Visible = false;
}
}
private void UpdateLink()
{
string successMessage = Constants.RES_SUCCESSNEW;
try
{
var link = new Link
{
Title = txbTitle.Text,
Url = txbUrl.Text,
Rss = txbRss.Text,
IsActive = ckbIsActive.Checked,
CategoryId = Convert.ToInt32(ddlCategories.SelectedItem.Value),
NewWindow = chkNewWindow.Checked,
Id = Config.CurrentBlog.Id,
Relation = txtXfn.Text
};
if(LinkID > 0)
{
successMessage = Constants.RES_SUCCESSEDIT;
link.Id = LinkID;
Repository.UpdateLink(link);
}
else
{
LinkID = Repository.CreateLink(link);
}
if(LinkID > 0)
{
BindList();
Messages.ShowMessage(successMessage);
}
else
{
Messages.ShowError(Constants.RES_FAILUREEDIT
+ " There was a baseline problem posting your link.");
}
}
catch(Exception ex)
{
Messages.ShowError(String.Format(Constants.RES_EXCEPTION,
Constants.RES_FAILUREEDIT, ex.Message));
}
finally
{
rprSelectionList.Visible = true;
headerLiteral.Visible = true;
}
}
private void ResetPostEdit(bool showEdit)
{
LinkID = NullValue.NullInt32;
rprSelectionList.Visible = !showEdit;
headerLiteral.Visible = !showEdit;
Edit.Visible = showEdit;
lblEntryID.Text = String.Empty;
txbTitle.Text = String.Empty;
txbUrl.Text = String.Empty;
txbRss.Text = String.Empty;
chkNewWindow.Checked = false;
ckbIsActive.Checked = Preferences.AlwaysCreateIsActive;
if(showEdit)
{
BindLinkCategories();
}
ddlCategories.SelectedIndex = -1;
}
private void ConfirmDelete(int linkID, string linkTitle)
{
var command = new DeleteLinkCommand(linkID, linkTitle)
{
ExecuteSuccessMessage = String.Format(CultureInfo.CurrentCulture, "Link '{0}' deleted", linkTitle)
};
Messages.ShowMessage(command.Execute());
BindList();
}
private void ImportOpml()
{
if(OpmlImportFile.PostedFile.FileName.Trim().Length > 0)
{
OpmlItemCollection importedLinks = OpmlProvider.Import(OpmlImportFile.PostedFile.InputStream);
if(importedLinks.Count > 0)
{
var command = new ImportLinksCommand(importedLinks,
Int32.Parse(ddlImportExportCategories.SelectedItem.Value));
Messages.ShowMessage(command.Execute());
}
BindList();
}
}
// REFACTOR
public string CheckHiddenStyle()
{
if(_isListHidden)
{
return Constants.CSSSTYLE_HIDDEN;
}
else
{
return String.Empty;
}
}
override protected void OnInit(EventArgs e)
{
rprSelectionList.ItemCommand += new RepeaterCommandEventHandler(rprSelectionList_ItemCommand);
base.OnInit(e);
}
protected void lkbImportOpml_Click(object sender, EventArgs e)
{
if(Page.IsValid)
{
ImportOpml();
}
}
private void rprSelectionList_ItemCommand(object source, RepeaterCommandEventArgs e)
{
switch(e.CommandName.ToLower(CultureInfo.InvariantCulture))
{
case "edit":
LinkID = Convert.ToInt32(e.CommandArgument);
BindLinkEdit();
break;
case "delete":
int id = Convert.ToInt32(e.CommandArgument);
Link link = Repository.GetLink(id);
ConfirmDelete(id, link.Title);
break;
default:
break;
}
}
protected void lkbCancel_Click(object sender, EventArgs e)
{
ResetPostEdit(false);
}
protected void lkbPost_Click(object sender, EventArgs e)
{
UpdateLink();
}
private void lkbNewLink_Click(object sender, EventArgs e)
{
ResetPostEdit(true);
}
}
}
| |
#region [ license and copyright boilerplate ]
/*
MiscCorLib
ConvertEnum.cs
Copyright (c) 2016 Jim Kropa (https://github.com/jimkropa)
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
namespace MiscCorLib
{
using System;
using System.Collections.Generic;
using System.Linq;
using MiscCorLib.Collections.Generic;
/// <summary>
/// A set of static method for converting an
/// enumeration type into other constructs.
/// </summary>
[CLSCompliant(true)]
public static class ConvertEnum
{
#region [ Main Overloads of ToDictionary ]
/// <summary>
/// Returns a dictionary of enumeration
/// values and names to use for each value.
/// </summary>
/// <typeparam name="T">
/// An <see cref="Enum"/> type.
/// </typeparam>
/// <returns>
/// A dictionary with the enumeration values as the keys,
/// and the name of each value as the values.
/// </returns>
/// <exception cref="ArgumentException">
/// The generic type parameter <typeparamref name="T"/>
/// does not derive from <see cref="Enum"/>.
/// </exception>
public static IDictionary<T, string> ToDictionary<T>()
where T : struct, IComparable, IFormattable
{
Type underlyingType;
return ToDictionary<T>(out underlyingType);
}
/// <summary>
/// Returns a dictionary of enumeration
/// values and names to use for each value.
/// </summary>
/// <typeparam name="T">
/// An <see cref="Enum"/> type.
/// </typeparam>
/// <param name="underlyingType">
/// Returns the integral type underlying the enumeration,
/// from the <see cref="Enum.GetUnderlyingType"/> method.
/// </param>
/// <returns>
/// A dictionary with the enumeration values as the keys,
/// and the name of each value as the values.
/// </returns>
/// <exception cref="ArgumentException">
/// The generic type parameter <typeparamref name="T"/>
/// does not derive from <see cref="Enum"/>.
/// </exception>
public static IDictionary<T, string> ToDictionary<T>(out Type underlyingType)
where T : struct, IComparable, IFormattable
{
Type enumType = typeof(T);
if (!enumType.IsEnum)
{
throw new ArgumentException("The generic type parameter must be a System.Enum type.");
}
underlyingType = Enum.GetUnderlyingType(enumType);
Array values = Enum.GetValues(enumType);
IDictionary<T, string> dict = new Dictionary<T, string>();
foreach (object value in values)
{
string name;
if (TryParseName<T>(enumType, value, out name))
{
dict.Add((T)value, name);
}
}
return dict;
}
/// <summary>
/// Returns a dictionary of values of an enumeration's
/// underlying type, and names to use for each value.
/// </summary>
/// <typeparam name="T">
/// An <see cref="Enum"/> type.
/// </typeparam>
/// <typeparam name="TU">
/// The underlying type of the <see cref="Enum"/>
/// value of <typeparamref name="T"/>, from the
/// <see cref="Enum.GetUnderlyingType"/> method.
/// </typeparam>
/// <returns>
/// The generic type parameter <typeparamref name="T"/>
/// does not derive from <see cref="Enum"/>.
/// </returns>
public static IDictionary<TU, string> ToDictionary<T, TU>()
where T : struct, IComparable, IFormattable
where TU : struct
{
Type enumType = typeof(T);
if (!enumType.IsEnum)
{
throw new ArgumentException("The generic type parameter must be a System.Enum type.");
}
Type underlyingType = Enum.GetUnderlyingType(enumType);
if (underlyingType != typeof(TU))
{
throw new InvalidCastException(
"Cannot convert the System.Enum type to the specified type becaues the underlying type does not match.");
}
Array values = Enum.GetValues(enumType);
IDictionary<TU, string> dict = new Dictionary<TU, string>();
foreach (object value in values)
{
string name;
if (TryParseName<T>(enumType, value, out name))
{
dict.Add((TU)value, name);
}
}
return dict;
}
#endregion
#region [ Overloads of ToDictionary for Signed Integral Types ]
/// <summary>
/// Returns a dictionary of byte keys based on
/// an enumeration with byte as its underlying type,
/// and names to use for each value.
/// </summary>
/// <typeparam name="T">
/// An <see cref="Enum"/> type.
/// </typeparam>
/// <returns>
/// The generic type parameter <typeparamref name="T"/>
/// does not derive from <see cref="Enum"/>.
/// </returns>
public static IDictionary<byte, string> ToDictionaryByte<T>()
where T : struct, IComparable, IFormattable
{
return ToDictionary<T, byte>();
}
/// <summary>
/// Returns a dictionary of short integer keys based on
/// an enumeration with byte as its underlying type,
/// and names to use for each value.
/// </summary>
/// <typeparam name="T">
/// An <see cref="Enum"/> type.
/// </typeparam>
/// <returns>
/// The generic type parameter <typeparamref name="T"/>
/// does not derive from <see cref="Enum"/>.
/// </returns>
public static IDictionary<short, string> ToDictionaryInt16<T>()
where T : struct, IComparable, IFormattable
{
return ToDictionary<T, short>();
}
/// <summary>
/// Returns a dictionary of integer keys based on
/// an enumeration with byte as its underlying type,
/// and names to use for each value.
/// </summary>
/// <typeparam name="T">
/// An <see cref="Enum"/> type.
/// </typeparam>
/// <returns>
/// The generic type parameter <typeparamref name="T"/>
/// does not derive from <see cref="Enum"/>.
/// </returns>
public static IDictionary<int, string> ToDictionaryInt32<T>()
where T : struct, IComparable, IFormattable
{
return ToDictionary<T, int>();
}
/// <summary>
/// Returns a dictionary of long integer keys based on
/// an enumeration with byte as its underlying type,
/// and names to use for each value.
/// </summary>
/// <typeparam name="T">
/// An <see cref="Enum"/> type.
/// </typeparam>
/// <returns>
/// The generic type parameter <typeparamref name="T"/>
/// does not derive from <see cref="Enum"/>.
/// </returns>
public static IDictionary<long, string> ToDictionaryInt64<T>()
where T : struct, IComparable, IFormattable
{
return ToDictionary<T, long>();
}
#endregion
#region [ Overloads of ToDictionary for Unsigned Integral Types (commented, not CLS compliant) ]
/*
/// <summary>
/// Returns a dictionary of signed byte keys based on
/// an enumeration with byte as its underlying type,
/// and names to use for each value.
/// </summary>
/// <typeparam name="T">
/// An <see cref="Enum" /> type.
/// </typeparam>
/// <returns>
/// The generic type parameter <typeparamref name="T" />
/// does not derive from <see cref="Enum" />.
/// </returns>
public static IDictionary<sbyte, string> ToDictionarySByte<T>()
where T : struct, IComparable, IFormattable
{
return ToDictionary<T, sbyte>();
}
/// <summary>
/// Returns a dictionary of unsigned short integer keys based on
/// an enumeration with byte as its underlying type,
/// and names to use for each value.
/// </summary>
/// <typeparam name="T">
/// An <see cref="Enum" /> type.
/// </typeparam>
/// <returns>
/// The generic type parameter <typeparamref name="T" />
/// does not derive from <see cref="Enum" />.
/// </returns>
public static IDictionary<ushort, string> ToDictionaryUInt16<T>()
where T : struct, IComparable, IFormattable
{
return ToDictionary<T, ushort>();
}
/// <summary>
/// Returns a dictionary of unsigned integer keys based on
/// an enumeration with byte as its underlying type,
/// and names to use for each value.
/// </summary>
/// <typeparam name="T">
/// An <see cref="Enum" /> type.
/// </typeparam>
/// <returns>
/// The generic type parameter <typeparamref name="T" />
/// does not derive from <see cref="Enum" />.
/// </returns>
public static IDictionary<uint, string> ToDictionaryUInt32<T>()
where T : struct, IComparable, IFormattable
{
return ToDictionary<T, uint>();
}
/// <summary>
/// Returns a dictionary of unsigned long integer keys based on
/// an enumeration with byte as its underlying type,
/// and names to use for each value.
/// </summary>
/// <typeparam name="T">
/// An <see cref="Enum" /> type.
/// </typeparam>
/// <returns>
/// The generic type parameter <typeparamref name="T" />
/// does not derive from <see cref="Enum" />.
/// </returns>
public static IDictionary<ulong, string> ToDictionaryUInt64<T>()
where T : struct, IComparable, IFormattable
{
return ToDictionary<T, ulong>();
}
*/
#endregion
#region [ TryParse Methods For Enums ]
/// <summary>
/// This method takes a string and attempts to return the enumeration value.
/// If the conversion is not possible the function returns false,
/// and the default enumeration is returned via the output parameter.
/// otherwise true is returned from the function and the converted value is returned.
/// </summary>
/// <typeparam name="TEnum">
/// The type of enumeration to parse.
/// </typeparam>
/// <param name="enumValue">
/// A byte representing a value of the
/// <typeparamref name="TEnum"/>.
/// </param>
/// <param name="enumOut">
/// If this method returns true, returns
/// the enumeration value matching the
/// given <paramref name="enumValue"/>.
/// Otherwise, returns zero.
/// </param>
/// <returns>
/// True if the <paramref name="enumValue"/>
/// was parsed into exactly one value of the
/// <typeparamref name="TEnum"/>. Otherwise, false.
/// </returns>
public static bool TryParse<TEnum>(this byte enumValue, out TEnum enumOut)
where TEnum : struct, IComparable, IFormattable
{
return TryParseInternal(enumValue, out enumOut);
}
/// <summary>
/// This method takes a string and attempts to return the enumeration value.
/// If the conversion is not possible the function returns false,
/// and the default enumeration is returned via the output parameter.
/// otherwise true is returned from the function and the converted value is returned.
/// </summary>
/// <typeparam name="TEnum">
/// The type of enumeration to parse.
/// </typeparam>
/// <param name="enumValue">
/// A byte representing a value of the
/// <typeparamref name="TEnum"/>.
/// </param>
/// <param name="enumOut">
/// If this method returns true, returns
/// the enumeration value matching the
/// given <paramref name="enumValue"/>.
/// Otherwise, returns zero.
/// </param>
/// <returns>
/// True if the <paramref name="enumValue"/>
/// was parsed into exactly one value of the
/// <typeparamref name="TEnum"/>. Otherwise, false.
/// </returns>
public static bool TryParse<TEnum>(this short enumValue, out TEnum enumOut)
where TEnum : struct, IComparable, IFormattable
{
return TryParseInternal(enumValue, out enumOut);
}
/// <summary>
/// This method takes a string and attempts to return the enumeration value.
/// if the conversion is not possible the function returns false, and the default enumeration is returned via the output parameter.
/// otherwise true is returned from the function and the converted value is returned.
/// </summary>
/// <typeparam name="TEnum">
/// The type of enumeration to parse.
/// </typeparam>
/// <param name="enumValue">
/// A byte representing a value of the
/// <typeparamref name="TEnum"/>.
/// </param>
/// <param name="enumOut">
/// If this method returns true, returns
/// the enumeration value matching the
/// given <paramref name="enumValue"/>.
/// Otherwise, returns zero.
/// </param>
/// <returns>
/// True if the <paramref name="enumValue"/>
/// was parsed into exactly one value of the
/// <typeparamref name="TEnum"/>. Otherwise, false.
/// </returns>
public static bool TryParse<TEnum>(this int enumValue, out TEnum enumOut)
where TEnum : struct, IComparable, IFormattable
{
return TryParseInternal(enumValue, out enumOut);
}
/// <summary>
/// This method takes a string and attempts to return the enumeration value.
/// if the conversion is not possible the function returns false, and the default enumeration is returned via the output parameter.
/// otherwise true is returned from the function and the converted value is returned.
/// </summary>
/// <typeparam name="TEnum">
/// The type of enumeration to parse.
/// </typeparam>
/// <param name="enumValue">
/// A byte representing a value of the
/// <typeparamref name="TEnum"/>.
/// </param>
/// <param name="enumOut">
/// If this method returns true, returns
/// the enumeration value matching the
/// given <paramref name="enumValue"/>.
/// Otherwise, returns zero.
/// </param>
/// <returns>
/// True if the <paramref name="enumValue"/>
/// was parsed into exactly one value of the
/// <typeparamref name="TEnum"/>. Otherwise, false.
/// </returns>
public static bool TryParse<TEnum>(this long enumValue, out TEnum enumOut)
where TEnum : struct, IComparable, IFormattable
{
return TryParseInternal(enumValue, out enumOut);
}
/// <summary>
/// This method takes an Enum and returns the same enumeration value.
/// </summary>
/// <typeparam name="TEnum">
/// The type of enumeration to parse.
/// </typeparam>
/// <param name="enumValue">
/// A byte representing a value of the
/// <typeparamref name="TEnum"/>.
/// </param>
/// <param name="enumOut">
/// If this method returns true, returns
/// the enumeration value matching the
/// given <paramref name="enumValue"/>.
/// Otherwise, returns zero.
/// </param>
/// <returns>
/// True if the <paramref name="enumValue"/>
/// was parsed into exactly one value of the
/// <typeparamref name="TEnum"/>. Otherwise, false.
/// </returns>
public static bool TryParse<TEnum>(this TEnum enumValue, out TEnum enumOut)
where TEnum : struct, IComparable, IFormattable
{
VerifyIsEnumType<TEnum>();
enumOut = enumValue;
return true;
}
/// <summary>
/// This method takes a string and attempts to return the enumeration value.
/// If the conversion is not possible the function returns false,
/// and the default enumeration is returned via the output parameter.
/// otherwise true is returned from the function and the converted value is returned.
/// </summary>
/// <typeparam name="TEnum">
/// The type of enumeration to parse.
/// </typeparam>
/// <param name="enumValue">
/// A byte representing a value of the
/// <typeparamref name="TEnum"/>.
/// </param>
/// <param name="enumOut">
/// If this method returns true, returns
/// the enumeration value matching the
/// given <paramref name="enumValue"/>.
/// Otherwise, returns zero.
/// </param>
/// <returns>
/// True if the <paramref name="enumValue"/>
/// was parsed into exactly one value of the
/// <typeparamref name="TEnum"/>. Otherwise, false.
/// </returns>
public static bool TryParse<TEnum>(this string enumValue, out TEnum enumOut)
where TEnum : struct, IComparable, IFormattable
{
VerifyIsEnumType<TEnum>();
Type enumType = typeof(TEnum);
if ((enumValue == null) || (!Enum.IsDefined(enumType, enumValue)))
{
enumOut = default(TEnum);
return false;
}
enumOut = (TEnum)Enum.Parse(enumType, enumValue, false);
return true;
}
#endregion
#region [ TryParse Methods For Enums with the Flags Attribute ]
/*
/// <summary>
/// Returns the values of a flags
/// enumeration from a given byte value.
/// </summary>
/// <typeparam name="TEnum">
/// The type of enumeration to parse.
/// </typeparam>
/// <param name="enumValue">
/// A byte representing a set of bits of
/// the <typeparamref name="TEnum"/>.
/// </param>
/// <param name="enumOut">
/// If this method returns true, returns
/// an array with the bits of a flags
/// enumeration contained in the given
/// <paramref name="enumValue"/>.
/// Otherwise, returns an empty array.
/// </param>
/// <returns>
/// True if the <paramref name="enumValue"/>
/// was parsed into at least one value of the
/// <typeparamref name="TEnum"/>. Otherwise, false.
/// </returns>
public static bool TryParse<TEnum>(this byte enumValue, out TEnum[] enumOut)
where TEnum : struct, IComparable, IFormattable
{
return TryParseInternal(enumValue, out enumOut);
}
/// <summary>
/// This method takes a short and returns the Prime Parts that Compose the Flags Enumeration.
/// </summary>
/// <typeparam name="TEnum">
/// The type of enumeration to parse.
/// </typeparam>
/// <param name="enumValue">
/// A short integer representing a set of bits
/// of the <typeparamref name="TEnum"/>.
/// </param>
/// <param name="enumOut">
/// If this method returns true, returns
/// an array with the bits of a flags
/// enumeration contained in the given
/// <paramref name="enumValue"/>.
/// Otherwise, returns an empty array.
/// </param>
/// <returns>
/// True if the <paramref name="enumValue"/>
/// was parsed into at least one value of the
/// <typeparamref name="TEnum"/>. Otherwise, false.
/// </returns>
public static bool TryParse<TEnum>(this short enumValue, out TEnum[] enumOut)
where TEnum : struct, IComparable, IFormattable
{
return TryParseInternal(enumValue, out enumOut);
}
/// <summary>
/// This method takes an int and returns the Prime Parts that Compose the Flags Enumeration.
/// </summary>
/// <typeparam name="TEnum">
/// The type of enumeration to parse.
/// </typeparam>
/// <param name="enumValue">
/// An integer representing a set of bits
/// of the <typeparamref name="TEnum"/>.
/// </param>
/// <param name="enumOut">
/// If this method returns true, returns
/// an array with the bits of a flags
/// enumeration contained in the given
/// <paramref name="enumValue"/>.
/// Otherwise, returns an empty array.
/// </param>
/// <returns>
/// True if the <paramref name="enumValue"/>
/// was parsed into at least one value of the
/// <typeparamref name="TEnum"/>. Otherwise, false.
/// </returns>
public static bool TryParse<TEnum>(this int enumValue, out TEnum[] enumOut)
where TEnum : struct, IComparable, IFormattable
{
return TryParseInternal(enumValue, out enumOut);
}
/// <summary>
/// This method takes a long and returns the Prime Parts that Compose the Flags Enumeration.
/// </summary>
/// <typeparam name="TEnum">
/// The type of enumeration to parse.
/// </typeparam>
/// <param name="enumValue">
/// A long integer representing a set of bits
/// of the <typeparamref name="TEnum"/>.
/// </param>
/// <param name="enumOut">
/// If this method returns true, returns
/// an array with the bits of a flags
/// enumeration contained in the given
/// <paramref name="enumValue"/>.
/// Otherwise, returns an empty array.
/// </param>
/// <returns>
/// True if the <paramref name="enumValue"/>
/// was parsed into at least one value of the
/// <typeparamref name="TEnum"/>. Otherwise, false.
/// </returns>
public static bool TryParse<TEnum>(this long enumValue, out TEnum[] enumOut)
where TEnum : struct, IComparable, IFormattable
{
return TryParseInternal(enumValue, out enumOut);
}
/// <summary>
/// This method is used to split an enumeration that is flags
/// into its defined values, which are typically powers of two.
/// This implementation always returns true.
/// </summary>
/// <typeparam name="TEnum">
/// The type of enumeration to parse.
/// </typeparam>
/// <param name="enumValue">
/// A <typeparamref name="TEnum"/> value to
/// be parsed into its individually defined values.
/// </param>
/// <param name="enumOut">
/// If this method returns true, returns
/// an array with the bits of a flags
/// enumeration contained in the given
/// <paramref name="enumValue"/>.
/// Otherwise, returns an empty array.
/// </param>
/// <returns>
/// Always returns true.
/// </returns>
public static bool TryParse<TEnum>(this TEnum enumValue, out TEnum[] enumOut)
where TEnum : struct, IComparable, IFormattable
{
VerifyIsEnumType<TEnum>();
ICollection<TEnum> enumsOut = new List<TEnum>();
foreach (TEnum actualEnumValue in Enum.GetValues(typeof(TEnum)))
{
if ((enumValue & actualEnumValue) == actualEnumValue))
{
enumsOut.Add(actualEnumValue);
}
}
RemoveNoneIfFlagsAndHasOtherValues(enumsOut);
enumOut = enumsOut.ToArray<TEnum>();
return true;
}
*/
/// <summary>
/// This method is used to determine if a string value is the text of an enumeration.
/// returns true if any values in the string were in the enumeration.
/// This method is to be used if flags are involved.
/// </summary>
/// <typeparam name="TEnum">
/// The type of enumeration to parse.
/// </typeparam>
/// <param name="enumValue">
/// A string to be converted <typeparamref name="TEnum"/>.
/// </param>
/// <param name="enumOut">
/// If this method returns true, returns
/// an array with the bits of a flags
/// enumeration contained in the given
/// <paramref name="enumValue"/>.
/// Otherwise, returns an empty array.
/// </param>
/// <returns>
/// <c>true</c> if the <paramref name="enumValue"/>
/// was parsed into at least one value of the
/// <typeparamref name="TEnum"/>.
/// Otherwise, <c>false</c>.
/// </returns>
public static bool TryParse<TEnum>(this string enumValue, out TEnum[] enumOut)
where TEnum : struct, IComparable, IFormattable
{
VerifyIsEnumType<TEnum>();
if (enumValue == null)
{
enumOut = new TEnum[0];
return false;
}
string[] enumValues = enumValue.Split(
ConvertDelimitedString.DefaultStringSplitter,
StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < enumValues.Length; i++)
{
enumValues[i] = enumValues[i].Trim();
}
Type enumType = typeof(TEnum);
List<TEnum> enumsOut = (
from item in enumValues where Enum.IsDefined(enumType, item)
select (TEnum) Enum.Parse(enumType, item)).ToList();
enumOut = enumsOut.ToArray();
if (enumsOut.Count > 0)
{
return true;
}
return false;
}
#endregion
#region [ Private Static Methods used by TryParse Overloads ]
/// <summary>
/// Verifies that the generic type parameter is an enumeration,
/// throws an exception if not.
/// </summary>
/// <typeparam name="TEnum">
/// Generic type parameter which should be an enumeration.
/// </typeparam>
private static void VerifyIsEnumType<TEnum>()
where TEnum : struct, IComparable, IFormattable
{
if (!typeof(TEnum).IsEnum)
{
throw new ArgumentException("The generic type parameter must be a System.Enum type.");
}
}
/// <summary>
/// Gets the the value of an enumeration
/// as its underlying type.
/// </summary>
/// <typeparam name="TUnderlyingType">
/// The underlying type of <typeparamref name="TEnum"/>,
/// or an integer type which may be converted to that type.
/// </typeparam>
/// <typeparam name="TEnum">
/// Generic type parameter which should be an enumeration.
/// </typeparam>
/// <param name="enumValue">
/// A value of type <typeparamref name="TEnum"/> to be
/// be converted to <typeparamref name="TUnderlyingType"/>.
/// </param>
/// <returns>
/// The <paramref name="enumValue"/> converted
/// to <typeparamref name="TUnderlyingType"/>.
/// </returns>
private static TUnderlyingType GetUnderlyingValueOfEnum<TUnderlyingType, TEnum>(TEnum enumValue)
where TEnum : struct, IComparable, IFormattable
where TUnderlyingType : struct
{
object convertedEnumValue = enumValue;
Type underlyingType = Enum.GetUnderlyingType(typeof(TUnderlyingType));
if (underlyingType == typeof (TUnderlyingType))
{
return (TUnderlyingType)convertedEnumValue;
}
if (underlyingType == typeof(byte))
{
convertedEnumValue = Convert.ToByte(enumValue);
}
else if (underlyingType == typeof(short))
{
convertedEnumValue = Convert.ToInt16(enumValue);
}
else if (underlyingType == typeof(int))
{
convertedEnumValue = Convert.ToInt32(enumValue);
}
else if (underlyingType == typeof(long))
{
convertedEnumValue = Convert.ToInt64(enumValue);
}
return (TUnderlyingType)convertedEnumValue;
}
/// <summary>
/// Parses a single integer value to its
/// corresponding value in an enumeration.
/// </summary>
/// <typeparam name="TEnum">
/// Generic type parameter which should be an enumeration.
/// </typeparam>
/// <typeparam name="TValue">
/// The underlying type of <typeparamref name="TEnum"/>,
/// or an integer type which may be converted to that type.
/// </typeparam>
/// <param name="enumValue">
/// An integer value which may be converted
/// to <typeparamref name="TEnum"/>.
/// </param>
/// <param name="enumOut">
/// If this method returns true, returns an
/// enumeration value corresponding to the
/// given <paramref name="enumValue"/>.
/// Otherwise, returns zero.
/// </param>
/// <returns>
/// <c>true</c> if the <paramref name="enumValue"/>
/// was parsed into at least one value of the
/// <typeparamref name="TEnum"/>.
/// Otherwise, <c>false</c>.
/// </returns>
private static bool TryParseInternal<TEnum, TValue>(TValue enumValue, out TEnum enumOut)
where TEnum : struct, IComparable, IFormattable
where TValue : struct, IComparable, IFormattable
{
VerifyIsEnumType<TEnum>();
Type enumType = typeof(TEnum);
TEnum convertedEnumValue = GetUnderlyingValueOfEnum<TEnum, TValue>(enumValue);
if (Enum.IsDefined(enumType, convertedEnumValue))
{
enumOut = (TEnum)Enum.ToObject(enumType, convertedEnumValue);
return true;
}
enumOut = default(TEnum);
return false;
}
/*
/// <summary>
/// Returns the values of a flags
/// enumeration from a given byte value.
/// </summary>
/// <typeparam name="TEnum">
/// The type of enumeration to parse.
/// </typeparam>
/// <typeparam name="TValue">
/// The underlying type of <typeparamref name="TEnum"/>,
/// or an integer type which may be converted to that type.
/// </typeparam>
/// <param name="enumValue">
/// A byte representing a set of bits of
/// the <typeparamref name="TEnum"/>.
/// </param>
/// <param name="enumOut">
/// If this method returns true, returns
/// an array with the bits of a flags
/// enumeration contained in the given
/// <paramref name="enumValue"/>.
/// Otherwise, returns an empty array.
/// </param>
/// <returns>
/// <c>true</c> if the <paramref name="enumValue"/>
/// was parsed into at least one value of the
/// <typeparamref name="TEnum"/>.
/// Otherwise, <c>false</c>.
/// </returns>
private static bool TryParseInternal<TEnum, TValue>(TValue enumValue, out TEnum[] enumOut)
where TEnum : struct, IComparable, IFormattable
where TValue : struct, IComparable, IFormattable
{
VerifyIsEnumType<TEnum>();
TEnum convertedEnumValue = GetUnderlyingValueOfEnum<TEnum, TValue>(enumValue);
ICollection<TEnum> enumsOut = new List<TEnum>();
foreach (TEnum actualEnumValue in Enum.GetValues(typeof(TEnum)))
{
if ((convertedEnumValue & actualEnumValue) == actualEnumValue))
{
enumsOut.Add(actualEnumValue);
}
}
RemoveNoneIfFlagsAndHasOtherValues(enumsOut);
enumOut = enumsOut.ToArray<TEnum>();
if (enumsOut.Count > 0)
{
return true;
}
return false;
}
/// <summary>
/// Removes the "zero" value from the given
/// collection if it contains other values.
/// </summary>
/// <typeparam name="TEnum">
/// The type of enumeration to parse.
/// </typeparam>
/// <param name="enumsOut">
/// A reference to an <see cref="ICollection{TEnum}"/>
/// which may contain the "zero" value and others.
/// </param>
private static void RemoveNoneIfFlagsAndHasOtherValues<TEnum>(ICollection<TEnum> enumsOut)
where TEnum : struct, IComparable, IFormattable
{
Type enumType = typeof(TEnum);
if ((enumsOut.Count > 1)
&& Enum.IsDefined(enumType, GetUnderlyingValueOfEnum<TEnum, int>(0))
&& enumsOut.Contains(default(TEnum)))
{
enumsOut.Remove(default(TEnum));
}
}
*/
/// <summary>
/// Private method used by the ToDictionary overloads.
/// </summary>
/// <typeparam name="T">
/// An <see cref="Enum"/> type which is the same
/// as the <paramref name="enumType"/> parameter.
/// </typeparam>
/// <param name="enumType">
/// The type of <typeparamref name="T"/>.
/// </param>
/// <param name="value">
/// A value to convert to the <paramref name="enumType"/>.
/// </param>
/// <param name="name">
/// The name resolved for the <paramref name="value"/>.
/// </param>
/// <returns>
/// True if the <paramref name="name"/> is resolved
/// for the <paramref name="value"/>, otherwise false.
/// </returns>
private static bool TryParseName<T>(Type enumType, object value, out string name)
where T : struct, IComparable, IFormattable
{
if (!enumType.IsEnum)
{
throw new ArgumentException("The generic type parameter must be a System.Enum type.", "enumType");
}
if (enumType != typeof(T))
{
throw new ArgumentException("The generic type parameter must be the same as the enumType parameter.", "enumType");
}
if (!Enum.IsDefined(enumType, value))
{
name = string.Empty;
return false;
}
name = Enum.GetName(enumType, value);
if (string.IsNullOrEmpty(name))
{
return false;
}
// Remove underscores, replace with spaces.
name = name.Replace("_", " ");
return true;
}
#endregion
}
}
| |
/*
* 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.Reflection;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Framework.Communications.Cache;
namespace OpenSim.Region.CoreModules.World.Land
{
/// <summary>
/// Keeps track of a specific piece of land's information
/// </summary>
public class LandObject : ILandObject
{
#region Member Variables
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private bool[,] m_landBitmap = new bool[64,64];
protected LandData m_landData = new LandData();
protected Scene m_scene;
protected List<SceneObjectGroup> primsOverMe = new List<SceneObjectGroup>();
private bool landInfoNeedsUpdate = true;
#endregion
#region ILandObject Members
public LandData landData
{
get { return m_landData; }
set
{
m_landData = value;
landInfoNeedsUpdate = true;
}
}
public UUID regionUUID
{
get { return m_scene.RegionInfo.RegionID; }
}
public string regionName
{
get { return m_scene.RegionInfo.RegionName; }
}
#region Constructors
public LandObject(UUID owner_id, bool is_group_owned, Scene scene)
{
m_scene = scene;
landData.OwnerID = owner_id;
landData.IsGroupOwned = is_group_owned;
}
#endregion
#region Member Functions
#region General Functions
/// <summary>
/// Checks to see if this land object contains a point
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns>Returns true if the piece of land contains the specified point</returns>
public bool containsPoint(int x, int y)
{
if (x >= 0 && y >= 0 && x <= Constants.RegionSize && x <= Constants.RegionSize)
{
return (m_landBitmap[x / 4, y / 4] == true);
}
else
{
return false;
}
}
public ILandObject Copy()
{
LandObject newLand = new LandObject(landData.OwnerID, landData.IsGroupOwned, m_scene);
//Place all new variables here!
newLand.m_landBitmap = (bool[,]) (m_landBitmap.Clone());
newLand.landData = landData.Copy();
return newLand;
}
static overrideParcelMaxPrimCountDelegate overrideParcelMaxPrimCount;
static overrideSimulatorMaxPrimCountDelegate overrideSimulatorMaxPrimCount;
public void setParcelObjectMaxOverride(overrideParcelMaxPrimCountDelegate overrideDel)
{
overrideParcelMaxPrimCount = overrideDel;
}
public void setSimulatorObjectMaxOverride(overrideSimulatorMaxPrimCountDelegate overrideDel)
{
overrideSimulatorMaxPrimCount = overrideDel;
}
public int getMaxPrimCount(int areaSize, bool includeBonusFactor)
{
//Normal Calculations
double bonus = 1.0;
if (includeBonusFactor)
bonus = m_scene.RegionInfo.RegionSettings.ObjectBonus;
int prims = Convert.ToInt32(
Math.Round((Convert.ToDouble(areaSize) / 65536.0)
* Convert.ToDouble(m_scene.RegionInfo.PrimLimit)
* bonus
));
if (prims > m_scene.RegionInfo.PrimLimit)
prims = m_scene.RegionInfo.PrimLimit;
return prims;
}
public int getParcelMaxPrimCount(ILandObject thisObject, bool includeBonusFactor)
{
if (overrideParcelMaxPrimCount != null)
{
return overrideParcelMaxPrimCount(thisObject);
}
else
{
//Normal Calculations
m_scene.LandChannel.UpdateLandPrimCounts();
return getMaxPrimCount(landData.Area, includeBonusFactor);
}
}
public int getSimulatorMaxPrimCount(ILandObject thisObject)
{
if (overrideSimulatorMaxPrimCount != null)
{
return overrideSimulatorMaxPrimCount(thisObject);
}
else
{
//Normal Calculations
m_scene.LandChannel.UpdateLandPrimCounts();
int area = landData.SimwideArea;
if (area == 0)
area = landData.Area;
if (area == 0)
return m_scene.RegionInfo.PrimLimit;
else
return getMaxPrimCount(area, true);
}
}
#endregion
#region Packet Request Handling
public void sendLandProperties(int sequence_id, bool snap_selection, int request_result, IClientAPI remote_client)
{
IEstateModule estateModule = m_scene.RequestModuleInterface<IEstateModule>();
uint regionFlags = (uint)(RegionFlags.PublicAllowed | RegionFlags.AllowDirectTeleport | RegionFlags.AllowParcelChanges | RegionFlags.AllowVoice);
if (estateModule != null)
regionFlags = estateModule.GetRegionFlags();
LandData parcel = landData.Copy();
if (m_scene.RegionInfo.Product == ProductRulesUse.ScenicUse)
{
// the current AgentId should already be cached, with presence, etc.
UserProfileData profile = m_scene.CommsManager.UserService.GetUserProfile(remote_client.AgentId);
if (profile != null)
{
// If it's the parnter of the owner of the scenic region...
if (profile.Partner == landData.OwnerID)
{
// enable Create at the viewer end, checked at the server end
parcel.Flags |= (uint)ParcelFlags.CreateObjects;
}
}
}
remote_client.SendLandProperties(sequence_id,
snap_selection, request_result, parcel,
(float)m_scene.RegionInfo.RegionSettings.ObjectBonus,
getParcelMaxPrimCount(this, false),
getSimulatorMaxPrimCount(this), regionFlags);
}
public void updateLandProperties(LandUpdateArgs args, IClientAPI remote_client)
{
//Needs later group support
LandData newData = landData.Copy();
uint allowedDelta = 0;
bool snap_selection = false;
bool needsInspect = false;
// These two are always blocked as no client can set them anyway
// ParcelFlags.ForSaleObjects
// ParcelFlags.LindenHome
if (m_scene.Permissions.CanEditParcel(remote_client.AgentId, this, GroupPowers.LandOptions))
{
allowedDelta |= (uint)(
ParcelFlags.AllowFly |
ParcelFlags.AllowLandmark |
ParcelFlags.AllowTerraform |
ParcelFlags.AllowDamage |
ParcelFlags.CreateObjects |
ParcelFlags.RestrictPushObject |
ParcelFlags.AllowOtherScripts |
ParcelFlags.AllowGroupScripts |
ParcelFlags.CreateGroupObjects |
ParcelFlags.AllowAPrimitiveEntry |
ParcelFlags.AllowGroupObjectEntry);
}
if (m_scene.Permissions.CanEditParcel(remote_client.AgentId, this, GroupPowers.LandSetSale))
{
if (m_scene.RegionInfo.AllowOwners != ProductRulesWho.OnlyEO)
{
bool ownerTransfer = false;
if (args.AuthBuyerID != newData.AuthBuyerID || args.SalePrice != newData.SalePrice)
{
ownerTransfer = true;
snap_selection = true;
}
if (m_scene.RegionInfo.AllowSales)
{
newData.AuthBuyerID = args.AuthBuyerID;
newData.SalePrice = args.SalePrice;
allowedDelta |= (uint)ParcelFlags.ForSale;
}
else
if (ownerTransfer)
{
newData.ClearSaleInfo(); // SalePrice, AuthBuyerID and sale-related Flags
remote_client.SendAgentAlertMessage("This parcel cannot be set for sale.", false);
}
}
if (m_scene.RegionInfo.AllowGroupTags && !landData.IsGroupOwned)
{
if (newData.GroupID != args.GroupID)
{
// Group tag change
if (m_scene.RegionInfo.AllowGroupTags || (args.GroupID == UUID.Zero))
{
newData.GroupID = args.GroupID;
needsInspect = true;
}
else
remote_client.SendAgentAlertMessage("This parcel cannot be tagged with a group.", false);
}
if (newData.GroupID != UUID.Zero)
{
allowedDelta |= (uint) ParcelFlags.SellParcelObjects;
if (m_scene.RegionInfo.AllowDeeding && !landData.IsGroupOwned)
allowedDelta |= (uint)(ParcelFlags.AllowDeedToGroup | ParcelFlags.ContributeWithDeed);
}
}
}
if (m_scene.Permissions.CanEditParcel(remote_client.AgentId, this, GroupPowers.FindPlaces))
{
newData.Category = args.Category;
allowedDelta |= (uint)(ParcelFlags.ShowDirectory |
ParcelFlags.AllowPublish |
ParcelFlags.MaturePublish);
}
if (m_scene.Permissions.CanEditParcel(remote_client.AgentId, this, GroupPowers.LandChangeIdentity))
{
newData.Description = args.Desc;
newData.Name = args.Name;
newData.SnapshotID = args.SnapshotID;
}
if (m_scene.Permissions.CanEditParcel(remote_client.AgentId, this, GroupPowers.SetLandingPoint))
{
newData.LandingType = args.LandingType;
newData.UserLocation = args.UserLocation;
newData.UserLookAt = args.UserLookAt;
}
if (m_scene.Permissions.CanEditParcel(remote_client.AgentId, this, GroupPowers.ChangeMedia))
{
newData.MediaAutoScale = args.MediaAutoScale;
newData.MediaID = args.MediaID;
newData.MediaURL = args.MediaURL.Trim();
newData.MusicURL = args.MusicURL.Trim();
newData.MediaType = args.MediaType;
newData.MediaDescription = args.MediaDescription;
newData.MediaWidth = args.MediaWidth;
newData.MediaHeight = args.MediaHeight;
newData.MediaLoop = args.MediaLoop;
newData.ObscureMusic = args.ObscureMusic;
newData.ObscureMedia = args.ObscureMedia;
allowedDelta |= (uint)(ParcelFlags.SoundLocal |
ParcelFlags.UrlWebPage |
ParcelFlags.UrlRawHtml |
ParcelFlags.AllowVoiceChat |
ParcelFlags.UseEstateVoiceChan);
}
if (m_scene.Permissions.CanEditParcel(remote_client.AgentId, this, GroupPowers.LandManagePasses))
{
newData.PassHours = args.PassHours;
newData.PassPrice = args.PassPrice;
allowedDelta |= (uint)ParcelFlags.UsePassList;
}
if (m_scene.Permissions.CanEditParcel(remote_client.AgentId, this, GroupPowers.LandManageAllowed))
{
allowedDelta |= (uint)(ParcelFlags.UseAccessGroup |
ParcelFlags.UseAccessList);
}
if (m_scene.Permissions.CanEditParcel(remote_client.AgentId, this, GroupPowers.LandManageBanned))
{
allowedDelta |= (uint)(ParcelFlags.UseBanList |
ParcelFlags.DenyAnonymous |
ParcelFlags.DenyAgeUnverified);
}
uint preserve = landData.Flags & ~allowedDelta;
newData.Flags = preserve | (args.ParcelFlags & allowedDelta);
// Override: Parcels in Plus regions are always [x] Public access parcels
if (m_scene.RegionInfo.Product == ProductRulesUse.PlusUse)
newData.Flags &= ~(uint)ParcelFlags.UseAccessList;
m_log.InfoFormat("[LAND]: updateLandProperties for land parcel {0} [{1}] flags {2} -> {3} by {4}",
newData.LocalID, newData.GlobalID, landData.Flags.ToString("X8"), newData.Flags.ToString("X8"), remote_client.Name);
m_scene.LandChannel.UpdateLandObject(landData.LocalID, newData);
sendLandUpdateToAvatarsOverParcel(snap_selection);
SendSelectedLandUpdate(remote_client);
if (needsInspect)
InspectParcelForAutoReturn();
}
public void updateLandSold(UUID avatarID, UUID groupID, bool groupOwned)
{
LandData newData = landData.Copy();
newData.OwnerID = avatarID;
newData.GroupID = groupID;
newData.IsGroupOwned = groupOwned;
newData.AuctionID = 0;
newData.ClaimDate = Util.UnixTimeSinceEpoch();
newData.ClaimPrice = landData.SalePrice;
newData.ClearSaleInfo(); // SalePrice, AuthBuyerID and sale-related Flags
m_log.InfoFormat("[LAND]: updateLandSold for land parcel {0} [{1}] flags {2} -> {3}",
newData.LocalID, newData.GlobalID, landData.Flags.ToString("X8"), newData.Flags.ToString("X8"));
m_scene.LandChannel.UpdateLandObject(landData.LocalID, newData);
m_scene.EventManager.TriggerParcelPrimCountUpdate();
sendLandUpdateToAvatarsOverParcel(true);
InspectParcelForAutoReturn();
}
public void deedToGroup(UUID groupID)
{
LandData newData = landData.Copy();
newData.OwnerID = groupID;
newData.GroupID = groupID;
newData.IsGroupOwned = true;
newData.ClearSaleInfo();
m_scene.LandChannel.UpdateLandObject(landData.LocalID, newData);
m_scene.EventManager.TriggerParcelPrimCountUpdate();
sendLandUpdateToAvatarsOverParcel(true);
InspectParcelForAutoReturn();
}
public bool AllowAccessEstatewide(UUID avatar)
{
if (m_scene.Permissions.BypassPermissions())
return true;
ScenePresence sp = m_scene.GetScenePresence(avatar);
if ((sp != null) && (sp.GodLevel > 0.0))
return true; // never deny grid gods in godmode
if (avatar == m_scene.RegionInfo.MasterAvatarAssignedUUID)
return true; // never deny the master avatar
if (avatar == m_scene.RegionInfo.EstateSettings.EstateOwner)
return true; // never deny the estate owner
if (m_scene.IsEstateManager(avatar)) // includes Estate Owner
return true;
if (m_scene.IsEstateOwnerPartner(avatar))
return true;
return false;
}
// Returns false and reason == ParcelPropertiesStatus.ParcelSelected if access is allowed, otherwise reason enum.
public bool DenyParcelAccess(UUID avatar, out ParcelPropertiesStatus reason)
{
ScenePresence sp = m_scene.GetScenePresence(avatar);
if (isBannedFromLand(avatar) || (sp != null && sp.IsBot && isBannedFromLand(sp.OwnerID)))
{
reason = ParcelPropertiesStatus.CollisionBanned;
return true;
}
if (isRestrictedFromLand(avatar) || (sp != null && sp.IsBot && isRestrictedFromLand(sp.OwnerID)))
{
reason = ParcelPropertiesStatus.CollisionNotOnAccessList;
return true;
}
reason = ParcelPropertiesStatus.ParcelSelected; // we can treat this as the no error case.
return false;
}
// Returns false and reason == ParcelPropertiesStatus.ParcelSelected if access is allowed, otherwise reason enum.
public bool DenyParcelAccess(SceneObjectGroup group, bool checkSitters, out ParcelPropertiesStatus reason)
{
if (checkSitters)
{
// some voodo with reason variables to avoid compiler problems.
ParcelPropertiesStatus reason2;
ParcelPropertiesStatus sitterReason = 0;
bool result = true;
group.ForEachSittingAvatar((ScenePresence sp) =>
{
if (sp.UUID != group.OwnerID) // checked separately below
{
if (DenyParcelAccess(sp.UUID, out reason2))
{
sitterReason = reason2;
result = false;
}
}
});
if (!result)
{
reason = sitterReason;
return false;
}
}
return DenyParcelAccess(group.OwnerID, out reason);
}
public bool isBannedFromLand(UUID avatar)
{
if (m_scene.Permissions.BypassPermissions())
return false;
if (landData.OwnerID == avatar)
return false;
ParcelManager.ParcelAccessEntry entry = new ParcelManager.ParcelAccessEntry();
entry.AgentID = avatar;
entry.Flags = AccessList.Ban;
entry.Time = new DateTime();
if (landData.ParcelAccessList.Contains(entry))
{
// Banned, but ignore if EO etc? Delay this call to here because
// this call is potentially slightly expensive due to partner check profile lookup.
if (!AllowAccessEstatewide(avatar))
return true;
}
return false;
}
public bool isRestrictedFromLand(UUID avatar)
{
if (m_scene.Permissions.BypassPermissions())
return false;
// Is everyone allowed in? Most common case, just permit entry.
if ((landData.Flags & (uint)ParcelFlags.UseAccessList) == 0)
return false;
// Land owner always has access. Just permit entry.
if (landData.OwnerID == avatar)
return false;
// Not public access, not the owner. Check other overrides.
// Check if this user is listed with access.
if (landData.ParcelAccessList.Count != 0)
{
ParcelManager.ParcelAccessEntry entry = new ParcelManager.ParcelAccessEntry();
entry.AgentID = avatar;
entry.Flags = AccessList.Access;
entry.Time = new DateTime();
if (landData.ParcelAccessList.Contains(entry))
return false; // explicitly permitted to enter
}
// Note: AllowAccessEstatewide is potentially slightly expensive due to partner check profile lookup.
if (AllowAccessEstatewide(avatar))
return false;
if (landData.GroupID != UUID.Zero) // It has a group set.
{
// If it's group-owned land or group-based access enabled, allow in group members.
if (landData.IsGroupOwned || ((landData.Flags & (uint)ParcelFlags.UseAccessGroup) != 0))
{
// FastConfirmGroupMember is light if the avatar has a root or child connection to this region.
if (m_scene.FastConfirmGroupMember(avatar, landData.GroupID))
return false;
}
}
// Parcel not public access and no qualifications to allow in.
return true;
}
public void RemoveAvatarFromParcel(UUID userID)
{
ScenePresence sp = m_scene.GetScenePresence(userID);
EntityBase.PositionInfo posInfo = sp.GetPosInfo();
if (posInfo.Parent != null)
{
// can't find the prim seated on, stand up
sp.StandUp(false, true);
// fall through to unseated avatar code.
}
// If they are moving, stop them. This updates the physics object as well.
sp.Velocity = Vector3.Zero;
Vector3 pos = sp.AbsolutePosition; // may have changed from posInfo by StandUp above.
ParcelPropertiesStatus reason2;
if (!sp.lastKnownAllowedPosition.Equals(Vector3.Zero))
{
pos = sp.lastKnownAllowedPosition;
}
else
{
// Still a forbidden parcel, they must have been above the limit or entering region for the first time.
// Let's put them up higher, over the restricted parcel.
// We could add 50m to avatar.Scene.Heightmap[x,y] but then we need subscript checks, etc.
// For now, this is simple and safer than TPing them home.
pos.Z += 50.0f;
}
ILandObject parcel = m_scene.LandChannel.GetLandObject(pos.X, pos.Y);
float minZ;
if ((parcel != null) && m_scene.TestBelowHeightLimit(sp.UUID, pos, parcel, out minZ, out reason2))
{
if (pos.Z < minZ)
pos.Z = minZ + Constants.AVATAR_BOUNCE;
}
// Now force the non-sitting avatar to a position above the parcel
sp.Teleport(pos); // this is really just a move
}
public void sendLandUpdateToClient(IClientAPI remote_client, int sequence_id, bool snap_selection)
{
sendLandProperties(sequence_id, snap_selection, 0, remote_client);
}
public void sendLandUpdateToClient(IClientAPI remote_client, bool snap_selection)
{
sendLandProperties(0, snap_selection, 0, remote_client);
}
public void sendLandUpdateToClient(IClientAPI remote_client)
{
sendLandProperties(0, false, 0, remote_client);
}
public const int SELECTED_PARCEL_SEQ_ID = -10000;
public void SendSelectedLandUpdate(IClientAPI client)
{
sendLandUpdateToClient(client, SELECTED_PARCEL_SEQ_ID, true);
}
public void sendLandUpdateToAllAvatars(bool snap_selection)
{
List<ScenePresence> avatars = m_scene.GetAvatars();
foreach (ScenePresence avatar in avatars)
{
Vector3 avpos;
if (avatar.HasSafePosition(out avpos))
{
sendLandUpdateToClient(avatar.ControllingClient, snap_selection);
}
}
}
public void sendLandUpdateToAllAvatars()
{
sendLandUpdateToAllAvatars(false);
}
public void sendLandUpdateToAvatarsOverParcel(bool snap_selection)
{
List<ScenePresence> avatars = m_scene.GetAvatars();
foreach (ScenePresence avatar in avatars)
{
Vector3 avpos;
if (avatar.HasSafePosition(out avpos))
{
ILandObject over = null;
try
{
over =
m_scene.LandChannel.GetLandObject(Util.Clamp<int>((int)Math.Round(avpos.X), 0, 255),
Util.Clamp<int>((int)Math.Round(avpos.Y), 0, 255));
}
catch (Exception)
{
m_log.Warn("[LAND]: Unable to get land at " + Math.Round(avpos.X) + "," + Math.Round(avpos.Y));
}
if (over != null)
{
if (over.landData.LocalID == landData.LocalID)
{
if (((over.landData.Flags & (uint)ParcelFlags.AllowDamage) != 0) && m_scene.RegionInfo.RegionSettings.AllowDamage)
avatar.Invulnerable = false;
else
avatar.Invulnerable = true;
sendLandUpdateToClient(avatar.ControllingClient, snap_selection);
}
}
}
}
}
public void sendLandUpdateToAvatarsOverParcel()
{
sendLandUpdateToAvatarsOverParcel(false);
}
#endregion
#region AccessList Functions
public List<UUID> createAccessListArrayByFlag(AccessList flag)
{
List<UUID> list = new List<UUID>();
foreach (ParcelManager.ParcelAccessEntry entry in landData.ParcelAccessList)
{
if (entry.Flags == flag)
{
list.Add(entry.AgentID);
}
}
if (list.Count == 0)
{
list.Add(UUID.Zero);
}
return list;
}
public void sendAccessList(uint flags, IClientAPI remote_client)
{
if ((flags & (uint) AccessList.Access) == (uint)AccessList.Access)
{
List<UUID> avatars = createAccessListArrayByFlag(AccessList.Access);
remote_client.SendLandAccessListData(avatars,(uint) AccessList.Access,landData.LocalID);
}
if ((flags & (uint)AccessList.Ban) == (uint)AccessList.Ban)
{
List<UUID> avatars = createAccessListArrayByFlag(AccessList.Ban);
remote_client.SendLandAccessListData(avatars, (uint)AccessList.Ban, landData.LocalID);
}
}
public void updateAccessList(uint flags, List<ParcelManager.ParcelAccessEntry> entries, IClientAPI remote_client)
{
LandData newData = landData.Copy();
if (entries.Count == 1 && entries[0].AgentID == UUID.Zero)
{
entries.Clear();
}
List<ParcelManager.ParcelAccessEntry> toRemove = new List<ParcelManager.ParcelAccessEntry>();
foreach (ParcelManager.ParcelAccessEntry entry in newData.ParcelAccessList)
{
if (entry.Flags == (AccessList)flags)
{
toRemove.Add(entry);
}
}
foreach (ParcelManager.ParcelAccessEntry entry in toRemove)
{
newData.ParcelAccessList.Remove(entry);
}
foreach (ParcelManager.ParcelAccessEntry entry in entries)
{
ParcelManager.ParcelAccessEntry temp = new ParcelManager.ParcelAccessEntry();
temp.AgentID = entry.AgentID;
temp.Time = new DateTime(); //Pointless? Yes.
temp.Flags = (AccessList)flags;
if (!newData.ParcelAccessList.Contains(temp))
{
newData.ParcelAccessList.Add(temp);
}
}
m_log.InfoFormat("[LAND]: updateAccessList for land parcel {0} [{1}] flags {2} -> {3} by {4}",
newData.LocalID, newData.GlobalID, landData.Flags.ToString("X8"), newData.Flags.ToString("X8"), remote_client.Name);
m_scene.LandChannel.UpdateLandObject(landData.LocalID, newData);
}
#endregion
#region Update Functions
private void updateLandBitmapByteArray()
{
landData.Bitmap = convertLandBitmapToBytes();
}
/// <summary>
/// Update all settings in land such as area, bitmap byte array, etc
/// </summary>
public void forceUpdateLandInfo()
{
updateAABBAndAreaValues();
updateLandBitmapByteArray();
landInfoNeedsUpdate = false;
}
public void updateLandInfoIfNeeded()
{
if (landInfoNeedsUpdate)
{
forceUpdateLandInfo();
}
}
public void setLandBitmapFromByteArray()
{
m_landBitmap = convertBytesToLandBitmap();
landInfoNeedsUpdate = true;
}
/// <summary>
/// Updates the AABBMin and AABBMax values after area/shape modification of the land object
/// </summary>
private void updateAABBAndAreaValues()
{
int min_x = 64;
int min_y = 64;
int max_x = 0;
int max_y = 0;
int tempArea = 0;
int x, y;
for (x = 0; x < 64; x++)
{
for (y = 0; y < 64; y++)
{
if (m_landBitmap[x, y] == true)
{
if (min_x > x) min_x = x;
if (min_y > y) min_y = y;
if (max_x < x) max_x = x;
if (max_y < y) max_y = y;
tempArea += 16; //16sqm peice of land
}
}
}
int tx = min_x * 4;
if (tx > ((int)Constants.RegionSize - 1))
tx = ((int)Constants.RegionSize - 1);
int ty = min_y * 4;
if (ty > ((int)Constants.RegionSize - 1))
ty = ((int)Constants.RegionSize - 1);
landData.AABBMin =
new Vector3((float) (min_x * 4), (float) (min_y * 4),
(float) m_scene.Heightmap[tx, ty]);
tx = max_x * 4;
if (tx > ((int)Constants.RegionSize - 1))
tx = ((int)Constants.RegionSize - 1);
ty = max_y * 4;
if (ty > ((int)Constants.RegionSize - 1))
ty = ((int)Constants.RegionSize - 1);
landData.AABBMax =
new Vector3((float) (max_x * 4), (float) (max_y * 4),
(float) m_scene.Heightmap[tx, ty]);
landData.Area = tempArea;
}
#endregion
#region Land Bitmap Functions
/// <summary>
/// Sets the land's bitmap manually
/// </summary>
/// <param name="bitmap">64x64 block representing where this land is on a map</param>
public void setLandBitmap(bool[,] bitmap)
{
if (bitmap.GetLength(0) != 64 || bitmap.GetLength(1) != 64 || bitmap.Rank != 2)
{
//Throw an exception - The bitmap is not 64x64
//throw new Exception("Error: Invalid Parcel Bitmap");
}
else
{
//Valid: Lets set it
m_landBitmap = bitmap;
landInfoNeedsUpdate = true;
forceUpdateLandInfo();
}
}
/// <summary>
/// Gets the land's bitmap manually
/// </summary>
/// <returns></returns>
public bool[,] getLandBitmap()
{
return m_landBitmap;
}
/// <summary>
/// Used to modify the bitmap between the x and y points. Points use 64 scale
/// </summary>
/// <param name="start_x"></param>
/// <param name="start_y"></param>
/// <param name="end_x"></param>
/// <param name="end_y"></param>
/// <returns></returns>
public bool[,] getSquareLandBitmap(int start_x, int start_y, int end_x, int end_y)
{
bool[,] tempBitmap = new bool[64,64];
tempBitmap.Initialize();
tempBitmap = modifyLandBitmapSquare(tempBitmap, start_x, start_y, end_x, end_y, true);
return tempBitmap;
}
/// <summary>
/// Change a land bitmap at within a square and set those points to a specific value
/// </summary>
/// <param name="land_bitmap"></param>
/// <param name="start_x"></param>
/// <param name="start_y"></param>
/// <param name="end_x"></param>
/// <param name="end_y"></param>
/// <param name="set_value"></param>
/// <returns></returns>
public bool[,] modifyLandBitmapSquare(bool[,] land_bitmap, int start_x, int start_y, int end_x, int end_y,
bool set_value)
{
if (land_bitmap.GetLength(0) != 64 || land_bitmap.GetLength(1) != 64 || land_bitmap.Rank != 2)
{
//Throw an exception - The bitmap is not 64x64
//throw new Exception("Error: Invalid Parcel Bitmap in modifyLandBitmapSquare()");
}
int x, y;
for (y = 0; y < 64; y++)
{
for (x = 0; x < 64; x++)
{
if (x >= start_x / 4 && x < end_x / 4
&& y >= start_y / 4 && y < end_y / 4)
{
land_bitmap[x, y] = set_value;
}
}
}
return land_bitmap;
}
/// <summary>
/// Join the true values of 2 bitmaps together
/// </summary>
/// <param name="bitmap_base"></param>
/// <param name="bitmap_add"></param>
/// <returns></returns>
public bool[,] mergeLandBitmaps(bool[,] bitmap_base, bool[,] bitmap_add)
{
if (bitmap_base.GetLength(0) != 64 || bitmap_base.GetLength(1) != 64 || bitmap_base.Rank != 2)
{
//Throw an exception - The bitmap is not 64x64
throw new Exception("Error: Invalid Parcel Bitmap - Bitmap_base in mergeLandBitmaps");
}
if (bitmap_add.GetLength(0) != 64 || bitmap_add.GetLength(1) != 64 || bitmap_add.Rank != 2)
{
//Throw an exception - The bitmap is not 64x64
throw new Exception("Error: Invalid Parcel Bitmap - Bitmap_add in mergeLandBitmaps");
}
int x, y;
for (y = 0; y < 64; y++)
{
for (x = 0; x < 64; x++)
{
if (bitmap_add[x, y])
{
bitmap_base[x, y] = true;
}
}
}
return bitmap_base;
}
/// <summary>
/// Converts the land bitmap to a packet friendly byte array
/// </summary>
/// <returns></returns>
private byte[] convertLandBitmapToBytes()
{
byte[] tempConvertArr = new byte[512];
byte tempByte = 0;
int x, y, i, byteNum = 0;
i = 0;
for (y = 0; y < 64; y++)
{
for (x = 0; x < 64; x++)
{
tempByte = Convert.ToByte(tempByte | Convert.ToByte(m_landBitmap[x, y]) << (i++ % 8));
if (i % 8 == 0)
{
tempConvertArr[byteNum] = tempByte;
tempByte = (byte) 0;
i = 0;
byteNum++;
}
}
}
return tempConvertArr;
}
private bool[,] convertBytesToLandBitmap()
{
bool[,] tempConvertMap = new bool[64,64];
tempConvertMap.Initialize();
byte tempByte = 0;
int x = 0, y = 0, i = 0, bitNum = 0;
for (i = 0; i < 512; i++)
{
tempByte = landData.Bitmap[i];
for (bitNum = 0; bitNum < 8; bitNum++)
{
bool bit = Convert.ToBoolean(Convert.ToByte(tempByte >> bitNum) & (byte) 1);
tempConvertMap[x, y] = bit;
x++;
if (x > 63)
{
x = 0;
y++;
}
}
}
return tempConvertMap;
}
#endregion
#region Object Select and Object Owner Listing
public void sendForceObjectSelect(int local_id, int request_type, List<UUID> returnIDs, IClientAPI remote_client)
{
if (m_scene.Permissions.CanEditParcel(remote_client.AgentId, this, GroupPowers.LandOptions))
{
List<uint> resultLocalIDs = new List<uint>();
try
{
lock (primsOverMe)
{
foreach (SceneObjectGroup obj in primsOverMe)
{
if (obj.LocalId > 0)
{
if (request_type == LandChannel.LAND_SELECT_OBJECTS_OWNER && obj.OwnerID == landData.OwnerID)
{
resultLocalIDs.Add(obj.LocalId);
}
else if (request_type == LandChannel.LAND_SELECT_OBJECTS_GROUP && obj.GroupID == landData.GroupID && landData.GroupID != UUID.Zero)
{
resultLocalIDs.Add(obj.LocalId);
}
else if (request_type == LandChannel.LAND_SELECT_OBJECTS_OTHER &&
obj.OwnerID != remote_client.AgentId)
{
resultLocalIDs.Add(obj.LocalId);
}
else if (request_type == (int)ObjectReturnType.List && returnIDs.Contains(obj.OwnerID))
{
resultLocalIDs.Add(obj.LocalId);
}
}
}
}
} catch (InvalidOperationException)
{
m_log.Error("[LAND]: Unable to force select the parcel objects. Arr.");
}
remote_client.SendForceClientSelectObjects(resultLocalIDs);
}
}
/// <summary>
/// Notify the parcel owner each avatar that owns prims situated on their land. This notification includes
/// aggreagete details such as the number of prims.
///
/// </summary>
/// <param name="remote_client">
/// A <see cref="IClientAPI"/>
/// </param>
public void sendLandObjectOwners(IClientAPI remote_client)
{
if (m_scene.Permissions.CanEditParcel(remote_client.AgentId, this, GroupPowers.LandOptions))
{
Dictionary<UUID, int> primCount = new Dictionary<UUID, int>();
List<UUID> groups = new List<UUID>();
lock (primsOverMe)
{
try
{
foreach (SceneObjectGroup obj in primsOverMe)
{
try
{
if (!primCount.ContainsKey(obj.OwnerID))
{
primCount.Add(obj.OwnerID, 0);
}
}
catch (NullReferenceException)
{
m_log.Info("[LAND]: " + "Got Null Reference when searching land owners from the parcel panel");
}
try
{
primCount[obj.OwnerID] += obj.LandImpact;
}
catch (KeyNotFoundException)
{
m_log.Error("[LAND]: Unable to match a prim with it's owner.");
}
if (obj.OwnerID == obj.GroupID && (!groups.Contains(obj.OwnerID)))
groups.Add(obj.OwnerID);
}
}
catch (InvalidOperationException)
{
m_log.Error("[LAND]: Unable to Enumerate Land object arr.");
}
}
remote_client.SendLandObjectOwners(landData, groups, primCount);
}
}
public Dictionary<UUID, int> getLandObjectOwners()
{
Dictionary<UUID, int> ownersAndCount = new Dictionary<UUID, int>();
lock (primsOverMe)
{
try
{
foreach (SceneObjectGroup obj in primsOverMe)
{
if (!ownersAndCount.ContainsKey(obj.OwnerID))
{
ownersAndCount.Add(obj.OwnerID, 0);
}
ownersAndCount[obj.OwnerID] += obj.LandImpact;
}
}
catch (InvalidOperationException)
{
m_log.Error("[LAND]: Unable to enumerate land owners. arr.");
}
}
return ownersAndCount;
}
#endregion
#region Object Returning
public void returnObject(SceneObjectGroup obj)
{
SceneObjectGroup[] objs = new SceneObjectGroup[1];
objs[0] = obj;
m_scene.returnObjects(objs);
}
public List<SceneObjectGroup> GetPrimsOverByOwner(UUID targetID, bool scriptedOnly)
{
List<SceneObjectGroup> prims = new List<SceneObjectGroup>();
List<SceneObjectGroup> myPrims;
lock (primsOverMe)
{
myPrims = new List<SceneObjectGroup>(primsOverMe);
}
foreach (SceneObjectGroup obj in myPrims)
{
if (obj.OwnerID == targetID)
{
if (scriptedOnly)
{
bool containsScripts = false;
foreach (SceneObjectPart part in obj.GetParts())
{
if (part.Inventory.ContainsScripts())
{
containsScripts = true;
break;
}
}
if (!containsScripts)
continue;
}
prims.Add(obj);
}
}
return prims;
}
public void returnLandObjects(uint type, UUID[] owners, UUID[] tasks, IClientAPI remote_client)
{
m_log.InfoFormat("[LAND]: ReturnLandObjects requested by {0} with: type {1}, {2} owners, {3} tasks", remote_client.Name, type, owners.Length, tasks.Length);
Dictionary<UUID,List<SceneObjectGroup>> returns =
new Dictionary<UUID,List<SceneObjectGroup>>();
lock (primsOverMe)
{
if (type == (uint)ObjectReturnType.Owner)
{
foreach (SceneObjectGroup obj in primsOverMe)
{
if (obj.OwnerID == m_landData.OwnerID)
{
if (!returns.ContainsKey(obj.OwnerID))
returns[obj.OwnerID] =
new List<SceneObjectGroup>();
returns[obj.OwnerID].Add(obj);
}
}
}
else if (type == (uint)ObjectReturnType.Group && m_landData.GroupID != UUID.Zero)
{
foreach (SceneObjectGroup obj in primsOverMe)
{
if (obj.GroupID == m_landData.GroupID)
{
if (!returns.ContainsKey(obj.OwnerID))
returns[obj.OwnerID] =
new List<SceneObjectGroup>();
returns[obj.OwnerID].Add(obj);
}
}
}
else if (type == (uint)ObjectReturnType.Other)
{
foreach (SceneObjectGroup obj in primsOverMe)
{
if (obj.OwnerID != m_landData.OwnerID &&
(obj.GroupID != m_landData.GroupID ||
m_landData.GroupID == UUID.Zero))
{
if (!returns.ContainsKey(obj.OwnerID))
returns[obj.OwnerID] =
new List<SceneObjectGroup>();
returns[obj.OwnerID].Add(obj);
}
}
}
else if (type == (uint)ObjectReturnType.List)
{
List<UUID> ownerlist = new List<UUID>(owners);
foreach (SceneObjectGroup obj in primsOverMe)
{
if (ownerlist.Contains(obj.OwnerID))
{
if (!returns.ContainsKey(obj.OwnerID))
returns[obj.OwnerID] =
new List<SceneObjectGroup>();
returns[obj.OwnerID].Add(obj);
}
}
}
else if (type == 1)//Return by sim owner by object UUID
{
List<UUID> Tasks = new List<UUID>(tasks);
foreach (SceneObjectGroup obj in primsOverMe)
{
if (Tasks.Contains(obj.UUID))
{
if (!returns.ContainsKey(obj.OwnerID))
returns[obj.OwnerID] =
new List<SceneObjectGroup>();
if (!returns[obj.OwnerID].Contains(obj))
returns[obj.OwnerID].Add(obj);
}
}
}
}
foreach (List<SceneObjectGroup> ol in returns.Values)
{
if (m_scene.Permissions.CanUseObjectReturn(this, type, remote_client, remote_client.AgentId, ol))
m_scene.returnObjects(ol.ToArray());
}
}
// This is a fast check for the case where there's an agent present and we've loaded group info.
public bool IsAgentGroupOwner(IClientAPI remoteClient, UUID groupID)
{
if (groupID == UUID.Zero)
return false;
// Use the known in-memory group membership data if available before going to db.
if (remoteClient == null)
return false; // we don't know who to check
// This isn't quite the same as being in the Owners role, but close enough in
// order to avoid multiple complex queries in order to check Role membership.
return remoteClient.GetGroupPowers(groupID) == (ulong)Constants.OWNER_GROUP_POWERS;
}
public bool IsAgentGroupOwner(UUID agentID, UUID groupID)
{
if (groupID == UUID.Zero)
return false;
ScenePresence sp = m_scene.GetScenePresence(agentID);
if (sp != null) {
IClientAPI remoteClient = sp.ControllingClient;
if (remoteClient != null)
return IsAgentGroupOwner(remoteClient, groupID);
}
// Otherwise, do it the hard way.
IGroupsModule groupsModule = m_scene.RequestModuleInterface<IGroupsModule>();
GroupRecord groupRec = groupsModule.GetGroupRecord(groupID);
if (groupRec == null) return false;
List<GroupRolesData> agentRoles = groupsModule.GroupRoleDataRequest(null, groupID);
foreach (GroupRolesData role in agentRoles)
{
if (role.RoleID == groupRec.OwnerRoleID)
return true;
}
return false;
}
// Anyone can grant PERMISSION_RETURN_OBJECTS but it can be only used under strict rules.
// Returns 0 on success, or LSL error code on error.
int canUseReturnPermission(ILandObject targetParcel, TaskInventoryItem scriptItem)
{
// First check the runtime perms to see if we're allowed to do returns at all.
if (scriptItem.PermsGranter == UUID.Zero)
return Constants.ERR_RUNTIME_PERMISSIONS;
// For both the user-owned and group-deeded script cases, there is a script check and a parcel check.
// The non-group PermsGranter is simpler, so check that first.
// Script Check: If script owned by an agent, PERMISSION_RETURN_OBJECTS granted by owner of the script.
if (scriptItem.OwnerID == scriptItem.PermsGranter)
{
// a user owns the scripted object, not a group.
// Parcel Check: owner of the parcel with the target prim == perms granter / script owner?
if (targetParcel.landData.OwnerID == scriptItem.OwnerID)
return 0; // passed both tests
return Constants.ERR_PARCEL_PERMISSIONS; // not parcel owner
}
// else, granter is not the owner of the script, see if it's group-owned and granter a group Owner
// Script Check: If script is group-deeded, permission granted by an agent belonging to group's "Owners" role.
if ((scriptItem.GroupID == UUID.Zero) || (scriptItem.GroupID != scriptItem.OwnerID))
return Constants.ERR_RUNTIME_PERMISSIONS; // not group-owned object
// Parcel Check: first check if parcel is group-owned, the only remaining valid usage case.
if ((targetParcel.landData.GroupID == UUID.Zero) || (targetParcel.landData.GroupID != targetParcel.landData.OwnerID))
return Constants.ERR_PARCEL_PERMISSIONS; // not group-deeded (so not parcel owner)
// Parcel Check: group-owned, so check if granter is an Owner in group
if (IsAgentGroupOwner(scriptItem.PermsGranter, targetParcel.landData.GroupID))
return 0; // passed both tests
return Constants.ERR_PARCEL_PERMISSIONS;
}
public int scriptedReturnLandObjectsByOwner(TaskInventoryItem scriptItem, UUID targetOwnerID)
{
// Check if we're allowed to be using return permission at all, and if so, allowed in this parcel.
int rc = canUseReturnPermission(this, scriptItem);
if (rc != 0) return rc;
// EO, EM and parcel owner's objects cannot be returned by this method.
if (targetOwnerID == landData.OwnerID)
return 0;
if (m_scene.IsEstateManager(targetOwnerID))
return 0;
// This function will only work properly if one of the following is true:
// - the land is owned by the scripted owner and this permission has been granted by the land owner, or
// - the land is group owned and this permission has been granted by a group member filling the group "Owners" role.
List<SceneObjectGroup> returns = new List<SceneObjectGroup>();
lock (primsOverMe)
{
foreach (SceneObjectGroup grp in primsOverMe)
{
// ignore anything not owned by the target
if (grp.OwnerID != targetOwnerID)
continue;
// Objects owned (deeded), to the group that the land is set to, will not be returned (ByOwner only)
if (grp.IsGroupDeeded && (grp.GroupID == landData.GroupID))
continue;
returns.Add(grp);
}
}
if (returns.Count > 0)
return m_scene.returnObjects(returns.ToArray(), "scripted parcel owner return");
return 0; // nothing to return
}
public int scriptedReturnLandObjectsByIDs(SceneObjectPart callingPart, TaskInventoryItem scriptItem, List<UUID> IDs)
{
int count = 0;
// Check if we're allowed to be using return permission at all, and if so, allowed in this parcel.
int rc = canUseReturnPermission(this, scriptItem);
if (rc != 0) return rc;
// This function will only work properly if one of the following is true:
// - the land is owned by the scripted owner and this permission has been granted by the land owner, or
// - the land is group owned and this permission has been granted by a group member filling the group "Owners" role.
List<SceneObjectGroup> returns = new List<SceneObjectGroup>();
lock (primsOverMe)
{
foreach (UUID id in IDs)
{
SceneObjectPart part = m_scene.GetSceneObjectPart(id);
SceneObjectGroup grp = part == null ? null : part.ParentGroup;
if ((grp != null) && (primsOverMe.Contains(grp)))
{
// The rules inside this IF only apply if the calling prim is not specifying itself.
if (grp.UUID != callingPart.ParentGroup.UUID)
{
// EO, EM and parcel owner's objects cannot be returned by this method.
if (grp.OwnerID == landData.OwnerID)
continue;
if (m_scene.IsEstateManager(grp.OwnerID))
continue;
if (!m_scene.IsEstateManager(scriptItem.OwnerID))
{
// EO and EM can return from any parcel, otherwise allowed only on
// objects located in any parcel owned by the script owner in the region.
if (landData.OwnerID != scriptItem.OwnerID)
continue; // parcel has different owner
}
}
returns.Add(grp);
}
}
}
foreach (var grp in returns)
{
// the returns list by ID could be a variety of owners and group settings, need to check each one separately.
List<SceneObjectGroup> singleList = new List<SceneObjectGroup>();
singleList.Add(grp);
if (singleList.Count > 0)
count += m_scene.returnObjects(singleList.ToArray(), "scripted parcel owner return by ID");
}
return count;
}
public void InspectParcelForAutoReturn()
{
lock (primsOverMe)
{
foreach (SceneObjectGroup obj in primsOverMe)
{
m_scene.InspectForAutoReturn(obj, this.landData);
}
}
}
#endregion
#region Object Adding/Removing from Parcel
public void resetLandPrimCounts()
{
landData.GroupPrims = 0;
landData.OwnerPrims = 0;
landData.OtherPrims = 0;
landData.SelectedPrims = 0;
lock (primsOverMe)
primsOverMe.Clear();
}
public void addPrimToCount(SceneObjectGroup obj)
{
UUID prim_owner = obj.OwnerID;
int prim_count = obj.LandImpact;
if (obj.IsSelected)
{
landData.SelectedPrims += prim_count;
}
else
{
if (prim_owner == landData.OwnerID)
{
landData.OwnerPrims += prim_count;
}
else if ((obj.GroupID == landData.GroupID ||
prim_owner == landData.GroupID) &&
landData.GroupID != UUID.Zero)
{
landData.GroupPrims += prim_count;
}
else
{
landData.OtherPrims += prim_count;
}
}
lock (primsOverMe)
primsOverMe.Add(obj);
}
public void removePrimFromCount(SceneObjectGroup obj)
{
lock (primsOverMe)
{
if (primsOverMe.Contains(obj))
{
UUID prim_owner = obj.OwnerID;
int prim_count = obj.LandImpact;
if (prim_owner == landData.OwnerID)
{
landData.OwnerPrims -= prim_count;
}
else if (obj.GroupID == landData.GroupID ||
prim_owner == landData.GroupID)
{
landData.GroupPrims -= prim_count;
}
else
{
landData.OtherPrims -= prim_count;
}
primsOverMe.Remove(obj);
}
}
}
#endregion
#endregion
#endregion
/// <summary>
/// Set the media url for this land parcel
/// </summary>
/// <param name="url"></param>
public void SetMediaUrl(string url)
{
landData.MediaURL = url.Trim();
sendLandUpdateToAvatarsOverParcel(false);
}
/// <summary>
/// Set the music url for this land parcel
/// </summary>
/// <param name="url"></param>
public void SetMusicUrl(string url)
{
landData.MusicURL = url.Trim();
sendLandUpdateToAvatarsOverParcel(false);
}
/// <summary>
/// Get the music url for this land parcel
/// </summary>
/// <param name="url"></param>
public string GetMusicUrl()
{
return landData.MusicURL;
}
}
}
| |
// 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.Globalization;
using System.IO;
using System.Net.Security;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using SafeWinHttpHandle = Interop.WinHttp.SafeWinHttpHandle;
namespace System.Net.Http
{
#if HTTP_DLL
internal enum WindowsProxyUsePolicy
#else
public enum WindowsProxyUsePolicy
#endif
{
DoNotUseProxy = 0, // Don't use a proxy at all.
UseWinHttpProxy = 1, // Use configuration as specified by "netsh winhttp" machine config command. Automatic detect not supported.
UseWinInetProxy = 2, // WPAD protocol and PAC files supported.
UseCustomProxy = 3 // Use the custom proxy specified in the Proxy property.
}
#if HTTP_DLL
internal enum CookieUsePolicy
#else
public enum CookieUsePolicy
#endif
{
IgnoreCookies = 0,
UseInternalCookieStoreOnly = 1,
UseSpecifiedCookieContainer = 2
}
#if HTTP_DLL
internal class WinHttpHandler : HttpMessageHandler
#else
public class WinHttpHandler : HttpMessageHandler
#endif
{
#if NET46
internal static readonly Version HttpVersion20 = new Version(2, 0);
internal static readonly Version HttpVersionUnknown = new Version(0, 0);
#else
internal static Version HttpVersion20 => HttpVersionInternal.Version20;
internal static Version HttpVersionUnknown => HttpVersionInternal.Unknown;
#endif
private static readonly TimeSpan s_maxTimeout = TimeSpan.FromMilliseconds(int.MaxValue);
[ThreadStatic]
private static StringBuilder t_requestHeadersBuilder;
private object _lockObject = new object();
private bool _doManualDecompressionCheck = false;
private WinInetProxyHelper _proxyHelper = null;
private bool _automaticRedirection = HttpHandlerDefaults.DefaultAutomaticRedirection;
private int _maxAutomaticRedirections = HttpHandlerDefaults.DefaultMaxAutomaticRedirections;
private DecompressionMethods _automaticDecompression = HttpHandlerDefaults.DefaultAutomaticDecompression;
private CookieUsePolicy _cookieUsePolicy = CookieUsePolicy.UseInternalCookieStoreOnly;
private CookieContainer _cookieContainer = null;
private SslProtocols _sslProtocols = SslProtocols.None; // Use most secure protocols available.
private Func<
HttpRequestMessage,
X509Certificate2,
X509Chain,
SslPolicyErrors,
bool> _serverCertificateValidationCallback = null;
private bool _checkCertificateRevocationList = false;
private ClientCertificateOption _clientCertificateOption = ClientCertificateOption.Manual;
private X509Certificate2Collection _clientCertificates = null; // Only create collection when required.
private ICredentials _serverCredentials = null;
private bool _preAuthenticate = false;
private WindowsProxyUsePolicy _windowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinHttpProxy;
private ICredentials _defaultProxyCredentials = null;
private IWebProxy _proxy = null;
private int _maxConnectionsPerServer = int.MaxValue;
private TimeSpan _sendTimeout = TimeSpan.FromSeconds(30);
private TimeSpan _receiveHeadersTimeout = TimeSpan.FromSeconds(30);
private TimeSpan _receiveDataTimeout = TimeSpan.FromSeconds(30);
private int _maxResponseHeadersLength = HttpHandlerDefaults.DefaultMaxResponseHeadersLength;
private int _maxResponseDrainSize = 64 * 1024;
private IDictionary<String, Object> _properties; // Only create dictionary when required.
private volatile bool _operationStarted;
private volatile bool _disposed;
private SafeWinHttpHandle _sessionHandle;
private WinHttpAuthHelper _authHelper = new WinHttpAuthHelper();
public WinHttpHandler()
{
}
#region Properties
public bool AutomaticRedirection
{
get
{
return _automaticRedirection;
}
set
{
CheckDisposedOrStarted();
_automaticRedirection = value;
}
}
public int MaxAutomaticRedirections
{
get
{
return _maxAutomaticRedirections;
}
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(
nameof(value),
value,
SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxAutomaticRedirections = value;
}
}
public DecompressionMethods AutomaticDecompression
{
get
{
return _automaticDecompression;
}
set
{
CheckDisposedOrStarted();
_automaticDecompression = value;
}
}
public CookieUsePolicy CookieUsePolicy
{
get
{
return _cookieUsePolicy;
}
set
{
if (value != CookieUsePolicy.IgnoreCookies
&& value != CookieUsePolicy.UseInternalCookieStoreOnly
&& value != CookieUsePolicy.UseSpecifiedCookieContainer)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_cookieUsePolicy = value;
}
}
public CookieContainer CookieContainer
{
get
{
return _cookieContainer;
}
set
{
CheckDisposedOrStarted();
_cookieContainer = value;
}
}
public SslProtocols SslProtocols
{
get
{
return _sslProtocols;
}
set
{
SecurityProtocol.ThrowOnNotAllowed(value, allowNone: true);
CheckDisposedOrStarted();
_sslProtocols = value;
}
}
public Func<
HttpRequestMessage,
X509Certificate2,
X509Chain,
SslPolicyErrors,
bool> ServerCertificateValidationCallback
{
get
{
return _serverCertificateValidationCallback;
}
set
{
CheckDisposedOrStarted();
_serverCertificateValidationCallback = value;
}
}
public bool CheckCertificateRevocationList
{
get
{
return _checkCertificateRevocationList;
}
set
{
CheckDisposedOrStarted();
_checkCertificateRevocationList = value;
}
}
public ClientCertificateOption ClientCertificateOption
{
get
{
return _clientCertificateOption;
}
set
{
if (value != ClientCertificateOption.Manual
&& value != ClientCertificateOption.Automatic)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_clientCertificateOption = value;
}
}
public X509Certificate2Collection ClientCertificates
{
get
{
if (_clientCertificateOption != ClientCertificateOption.Manual)
{
throw new InvalidOperationException(SR.Format(SR.net_http_invalid_enable_first, "ClientCertificateOptions", "Manual"));
}
if (_clientCertificates == null)
{
_clientCertificates = new X509Certificate2Collection();
}
return _clientCertificates;
}
}
public bool PreAuthenticate
{
get
{
return _preAuthenticate;
}
set
{
_preAuthenticate = value;
}
}
public ICredentials ServerCredentials
{
get
{
return _serverCredentials;
}
set
{
_serverCredentials = value;
}
}
public WindowsProxyUsePolicy WindowsProxyUsePolicy
{
get
{
return _windowsProxyUsePolicy;
}
set
{
if (value != WindowsProxyUsePolicy.DoNotUseProxy &&
value != WindowsProxyUsePolicy.UseWinHttpProxy &&
value != WindowsProxyUsePolicy.UseWinInetProxy &&
value != WindowsProxyUsePolicy.UseCustomProxy)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_windowsProxyUsePolicy = value;
}
}
public ICredentials DefaultProxyCredentials
{
get
{
return _defaultProxyCredentials;
}
set
{
CheckDisposedOrStarted();
_defaultProxyCredentials = value;
}
}
public IWebProxy Proxy
{
get
{
return _proxy;
}
set
{
CheckDisposedOrStarted();
_proxy = value;
}
}
public int MaxConnectionsPerServer
{
get
{
return _maxConnectionsPerServer;
}
set
{
if (value < 1)
{
// In WinHTTP, setting this to 0 results in it being reset to 2.
// So, we'll only allow settings above 0.
throw new ArgumentOutOfRangeException(
nameof(value),
value,
SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxConnectionsPerServer = value;
}
}
public TimeSpan SendTimeout
{
get
{
return _sendTimeout;
}
set
{
if (value != Timeout.InfiniteTimeSpan && (value <= TimeSpan.Zero || value > s_maxTimeout))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_sendTimeout = value;
}
}
public TimeSpan ReceiveHeadersTimeout
{
get
{
return _receiveHeadersTimeout;
}
set
{
if (value != Timeout.InfiniteTimeSpan && (value <= TimeSpan.Zero || value > s_maxTimeout))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_receiveHeadersTimeout = value;
}
}
public TimeSpan ReceiveDataTimeout
{
get
{
return _receiveDataTimeout;
}
set
{
if (value != Timeout.InfiniteTimeSpan && (value <= TimeSpan.Zero || value > s_maxTimeout))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_receiveDataTimeout = value;
}
}
public int MaxResponseHeadersLength
{
get
{
return _maxResponseHeadersLength;
}
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(
nameof(value),
value,
SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxResponseHeadersLength = value;
}
}
public int MaxResponseDrainSize
{
get
{
return _maxResponseDrainSize;
}
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(
nameof(value),
value,
SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxResponseDrainSize = value;
}
}
public IDictionary<string, object> Properties
{
get
{
if (_properties == null)
{
_properties = new Dictionary<String, object>();
}
return _properties;
}
}
#endregion
protected override void Dispose(bool disposing)
{
if (!_disposed)
{
_disposed = true;
if (disposing && _sessionHandle != null)
{
SafeWinHttpHandle.DisposeAndClearHandle(ref _sessionHandle);
}
}
base.Dispose(disposing);
}
#if HTTP_DLL
protected internal override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
#else
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
#endif
{
if (request == null)
{
throw new ArgumentNullException(nameof(request), SR.net_http_handler_norequest);
}
// Check for invalid combinations of properties.
if (_proxy != null && _windowsProxyUsePolicy != WindowsProxyUsePolicy.UseCustomProxy)
{
throw new InvalidOperationException(SR.net_http_invalid_proxyusepolicy);
}
if (_windowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy && _proxy == null)
{
throw new InvalidOperationException(SR.net_http_invalid_proxy);
}
if (_cookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer &&
_cookieContainer == null)
{
throw new InvalidOperationException(SR.net_http_invalid_cookiecontainer);
}
CheckDisposed();
SetOperationStarted();
TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();
// Create state object and save current values of handler settings.
var state = new WinHttpRequestState();
state.Tcs = tcs;
state.CancellationToken = cancellationToken;
state.RequestMessage = request;
state.Handler = this;
state.CheckCertificateRevocationList = _checkCertificateRevocationList;
state.ServerCertificateValidationCallback = _serverCertificateValidationCallback;
state.WindowsProxyUsePolicy = _windowsProxyUsePolicy;
state.Proxy = _proxy;
state.ServerCredentials = _serverCredentials;
state.DefaultProxyCredentials = _defaultProxyCredentials;
state.PreAuthenticate = _preAuthenticate;
Task.Factory.StartNew(
s => {
var whrs = (WinHttpRequestState)s;
whrs.Handler.StartRequest(whrs);
},
state,
CancellationToken.None,
TaskCreationOptions.DenyChildAttach,
TaskScheduler.Default);
return tcs.Task;
}
private static bool IsChunkedModeForSend(HttpRequestMessage requestMessage)
{
bool chunkedMode = requestMessage.Headers.TransferEncodingChunked.HasValue &&
requestMessage.Headers.TransferEncodingChunked.Value;
HttpContent requestContent = requestMessage.Content;
if (requestContent != null)
{
if (requestContent.Headers.ContentLength.HasValue)
{
if (chunkedMode)
{
// Deal with conflict between 'Content-Length' vs. 'Transfer-Encoding: chunked' semantics.
// Current .NET Desktop HttpClientHandler allows both headers to be specified but ends up
// stripping out 'Content-Length' and using chunked semantics. WinHttpHandler will maintain
// the same behavior.
requestContent.Headers.ContentLength = null;
}
}
else
{
if (!chunkedMode)
{
// Neither 'Content-Length' nor 'Transfer-Encoding: chunked' semantics was given.
// Current .NET Desktop HttpClientHandler uses 'Content-Length' semantics and
// buffers the content as well in some cases. But the WinHttpHandler can't access
// the protected internal TryComputeLength() method of the content. So, it
// will use'Transfer-Encoding: chunked' semantics.
chunkedMode = true;
requestMessage.Headers.TransferEncodingChunked = true;
}
}
}
else if (chunkedMode)
{
throw new InvalidOperationException(SR.net_http_chunked_not_allowed_with_empty_content);
}
return chunkedMode;
}
private static void AddRequestHeaders(
SafeWinHttpHandle requestHandle,
HttpRequestMessage requestMessage,
CookieContainer cookies)
{
// Get a StringBuilder to use for creating the request headers.
// We cache one in TLS to avoid creating a new one for each request.
StringBuilder requestHeadersBuffer = t_requestHeadersBuilder;
if (requestHeadersBuffer != null)
{
requestHeadersBuffer.Clear();
}
else
{
t_requestHeadersBuilder = requestHeadersBuffer = new StringBuilder();
}
// Manually add cookies.
if (cookies != null && cookies.Count > 0)
{
string cookieHeader = WinHttpCookieContainerAdapter.GetCookieHeader(requestMessage.RequestUri, cookies);
if (!string.IsNullOrEmpty(cookieHeader))
{
requestHeadersBuffer.AppendLine(cookieHeader);
}
}
// Serialize general request headers.
requestHeadersBuffer.AppendLine(requestMessage.Headers.ToString());
// Serialize entity-body (content) headers.
if (requestMessage.Content != null)
{
// TODO (#5523): Content-Length header isn't getting correctly placed using ToString()
// This is a bug in HttpContentHeaders that needs to be fixed.
if (requestMessage.Content.Headers.ContentLength.HasValue)
{
long contentLength = requestMessage.Content.Headers.ContentLength.Value;
requestMessage.Content.Headers.ContentLength = null;
requestMessage.Content.Headers.ContentLength = contentLength;
}
requestHeadersBuffer.AppendLine(requestMessage.Content.Headers.ToString());
}
// Add request headers to WinHTTP request handle.
if (!Interop.WinHttp.WinHttpAddRequestHeaders(
requestHandle,
requestHeadersBuffer,
(uint)requestHeadersBuffer.Length,
Interop.WinHttp.WINHTTP_ADDREQ_FLAG_ADD))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private void EnsureSessionHandleExists(WinHttpRequestState state)
{
if (_sessionHandle == null)
{
lock (_lockObject)
{
if (_sessionHandle == null)
{
SafeWinHttpHandle sessionHandle;
uint accessType;
// If a custom proxy is specified and it is really the system web proxy
// (initial WebRequest.DefaultWebProxy) then we need to update the settings
// since that object is only a sentinel.
if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy)
{
Debug.Assert(state.Proxy != null);
try
{
state.Proxy.GetProxy(state.RequestMessage.RequestUri);
}
catch (PlatformNotSupportedException)
{
// This is the system web proxy.
state.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
state.Proxy = null;
}
}
if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.DoNotUseProxy ||
state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy)
{
// Either no proxy at all or a custom IWebProxy proxy is specified.
// For a custom IWebProxy, we'll need to calculate and set the proxy
// on a per request handle basis using the request Uri. For now,
// we set the session handle to have no proxy.
accessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY;
}
else if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseWinHttpProxy)
{
// Use WinHTTP per-machine proxy settings which are set using the "netsh winhttp" command.
accessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_DEFAULT_PROXY;
}
else
{
// Use WinInet per-user proxy settings.
accessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY;
}
WinHttpTraceHelper.Trace("WinHttpHandler.EnsureSessionHandleExists: proxy accessType={0}", accessType);
sessionHandle = Interop.WinHttp.WinHttpOpen(
IntPtr.Zero,
accessType,
Interop.WinHttp.WINHTTP_NO_PROXY_NAME,
Interop.WinHttp.WINHTTP_NO_PROXY_BYPASS,
(int)Interop.WinHttp.WINHTTP_FLAG_ASYNC);
if (sessionHandle.IsInvalid)
{
int lastError = Marshal.GetLastWin32Error();
WinHttpTraceHelper.Trace("WinHttpHandler.EnsureSessionHandleExists: error={0}", lastError);
if (lastError != Interop.WinHttp.ERROR_INVALID_PARAMETER)
{
ThrowOnInvalidHandle(sessionHandle);
}
// We must be running on a platform earlier than Win8.1/Win2K12R2 which doesn't support
// WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY. So, we'll need to read the Wininet style proxy
// settings ourself using our WinInetProxyHelper object.
_proxyHelper = new WinInetProxyHelper();
sessionHandle = Interop.WinHttp.WinHttpOpen(
IntPtr.Zero,
_proxyHelper.ManualSettingsOnly ? Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY : Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY,
_proxyHelper.ManualSettingsOnly ? _proxyHelper.Proxy : Interop.WinHttp.WINHTTP_NO_PROXY_NAME,
_proxyHelper.ManualSettingsOnly ? _proxyHelper.ProxyBypass : Interop.WinHttp.WINHTTP_NO_PROXY_BYPASS,
(int)Interop.WinHttp.WINHTTP_FLAG_ASYNC);
ThrowOnInvalidHandle(sessionHandle);
}
uint optionAssuredNonBlockingTrue = 1; // TRUE
if (!Interop.WinHttp.WinHttpSetOption(
sessionHandle,
Interop.WinHttp.WINHTTP_OPTION_ASSURED_NON_BLOCKING_CALLBACKS,
ref optionAssuredNonBlockingTrue,
(uint)sizeof(uint)))
{
// This option is not available on downlevel Windows versions. While it improves
// performance, we can ignore the error that the option is not available.
int lastError = Marshal.GetLastWin32Error();
if (lastError != Interop.WinHttp.ERROR_WINHTTP_INVALID_OPTION)
{
throw WinHttpException.CreateExceptionUsingError(lastError);
}
}
SetSessionHandleOptions(sessionHandle);
_sessionHandle = sessionHandle;
}
}
}
}
private async void StartRequest(WinHttpRequestState state)
{
if (state.CancellationToken.IsCancellationRequested)
{
state.Tcs.TrySetCanceled(state.CancellationToken);
state.ClearSendRequestState();
return;
}
SafeWinHttpHandle connectHandle = null;
try
{
EnsureSessionHandleExists(state);
// Specify an HTTP server.
connectHandle = Interop.WinHttp.WinHttpConnect(
_sessionHandle,
state.RequestMessage.RequestUri.Host,
(ushort)state.RequestMessage.RequestUri.Port,
0);
ThrowOnInvalidHandle(connectHandle);
connectHandle.SetParentHandle(_sessionHandle);
// Try to use the requested version if a known/supported version was explicitly requested.
// Otherwise, we simply use winhttp's default.
string httpVersion = null;
if (state.RequestMessage.Version == HttpVersionInternal.Version10)
{
httpVersion = "HTTP/1.0";
}
else if (state.RequestMessage.Version == HttpVersionInternal.Version11)
{
httpVersion = "HTTP/1.1";
}
// Turn off additional URI reserved character escaping (percent-encoding). This matches
// .NET Framework behavior. System.Uri establishes the baseline rules for percent-encoding
// of reserved characters.
uint flags = Interop.WinHttp.WINHTTP_FLAG_ESCAPE_DISABLE;
if (state.RequestMessage.RequestUri.Scheme == UriScheme.Https)
{
flags |= Interop.WinHttp.WINHTTP_FLAG_SECURE;
}
// Create an HTTP request handle.
state.RequestHandle = Interop.WinHttp.WinHttpOpenRequest(
connectHandle,
state.RequestMessage.Method.Method,
state.RequestMessage.RequestUri.PathAndQuery,
httpVersion,
Interop.WinHttp.WINHTTP_NO_REFERER,
Interop.WinHttp.WINHTTP_DEFAULT_ACCEPT_TYPES,
flags);
ThrowOnInvalidHandle(state.RequestHandle);
state.RequestHandle.SetParentHandle(connectHandle);
// Set callback function.
SetStatusCallback(state.RequestHandle, WinHttpRequestCallback.StaticCallbackDelegate);
// Set needed options on the request handle.
SetRequestHandleOptions(state);
bool chunkedModeForSend = IsChunkedModeForSend(state.RequestMessage);
AddRequestHeaders(
state.RequestHandle,
state.RequestMessage,
_cookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer ? _cookieContainer : null);
uint proxyAuthScheme = 0;
uint serverAuthScheme = 0;
state.RetryRequest = false;
// The only way to abort pending async operations in WinHTTP is to close the WinHTTP handle.
// We will detect a cancellation request on the cancellation token by registering a callback.
// If the callback is invoked, then we begin the abort process by disposing the handle. This
// will have the side-effect of WinHTTP cancelling any pending I/O and accelerating its callbacks
// on the handle and thus releasing the awaiting tasks in the loop below. This helps to provide
// a more timely, cooperative, cancellation pattern.
using (state.CancellationToken.Register(s => ((WinHttpRequestState)s).RequestHandle.Dispose(), state))
{
do
{
_authHelper.PreAuthenticateRequest(state, proxyAuthScheme);
await InternalSendRequestAsync(state);
if (state.RequestMessage.Content != null)
{
await InternalSendRequestBodyAsync(state, chunkedModeForSend).ConfigureAwait(false);
}
bool receivedResponse = await InternalReceiveResponseHeadersAsync(state) != 0;
if (receivedResponse)
{
// If we're manually handling cookies, we need to add them to the container after
// each response has been received.
if (state.Handler.CookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer)
{
WinHttpCookieContainerAdapter.AddResponseCookiesToContainer(state);
}
_authHelper.CheckResponseForAuthentication(
state,
ref proxyAuthScheme,
ref serverAuthScheme);
}
} while (state.RetryRequest);
}
state.CancellationToken.ThrowIfCancellationRequested();
// Since the headers have been read, set the "receive" timeout to be based on each read
// call of the response body data. WINHTTP_OPTION_RECEIVE_TIMEOUT sets a timeout on each
// lower layer winsock read.
uint optionData = unchecked((uint)_receiveDataTimeout.TotalMilliseconds);
SetWinHttpOption(state.RequestHandle, Interop.WinHttp.WINHTTP_OPTION_RECEIVE_TIMEOUT, ref optionData);
HttpResponseMessage responseMessage = WinHttpResponseParser.CreateResponseMessage(state, _doManualDecompressionCheck);
state.Tcs.TrySetResult(responseMessage);
}
catch (Exception ex)
{
HandleAsyncException(state, state.SavedException ?? ex);
}
finally
{
SafeWinHttpHandle.DisposeAndClearHandle(ref connectHandle);
state.ClearSendRequestState();
}
}
private void SetSessionHandleOptions(SafeWinHttpHandle sessionHandle)
{
SetSessionHandleConnectionOptions(sessionHandle);
SetSessionHandleTlsOptions(sessionHandle);
SetSessionHandleTimeoutOptions(sessionHandle);
}
private void SetSessionHandleConnectionOptions(SafeWinHttpHandle sessionHandle)
{
uint optionData = (uint)_maxConnectionsPerServer;
SetWinHttpOption(sessionHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_CONNS_PER_SERVER, ref optionData);
SetWinHttpOption(sessionHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_CONNS_PER_1_0_SERVER, ref optionData);
}
private void SetSessionHandleTlsOptions(SafeWinHttpHandle sessionHandle)
{
uint optionData = 0;
SslProtocols sslProtocols =
(_sslProtocols == SslProtocols.None) ? SecurityProtocol.DefaultSecurityProtocols : _sslProtocols;
if ((sslProtocols & SslProtocols.Tls) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1;
}
if ((sslProtocols & SslProtocols.Tls11) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1;
}
if ((sslProtocols & SslProtocols.Tls12) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2;
}
SetWinHttpOption(sessionHandle, Interop.WinHttp.WINHTTP_OPTION_SECURE_PROTOCOLS, ref optionData);
}
private void SetSessionHandleTimeoutOptions(SafeWinHttpHandle sessionHandle)
{
if (!Interop.WinHttp.WinHttpSetTimeouts(
sessionHandle,
0,
0,
(int)_sendTimeout.TotalMilliseconds,
(int)_receiveHeadersTimeout.TotalMilliseconds))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private void SetRequestHandleOptions(WinHttpRequestState state)
{
SetRequestHandleProxyOptions(state);
SetRequestHandleDecompressionOptions(state.RequestHandle);
SetRequestHandleRedirectionOptions(state.RequestHandle);
SetRequestHandleCookieOptions(state.RequestHandle);
SetRequestHandleTlsOptions(state.RequestHandle);
SetRequestHandleClientCertificateOptions(state.RequestHandle, state.RequestMessage.RequestUri);
SetRequestHandleCredentialsOptions(state);
SetRequestHandleBufferingOptions(state.RequestHandle);
SetRequestHandleHttp2Options(state.RequestHandle, state.RequestMessage.Version);
}
private void SetRequestHandleProxyOptions(WinHttpRequestState state)
{
// We've already set the proxy on the session handle if we're using no proxy or default proxy settings.
// We only need to change it on the request handle if we have a specific IWebProxy or need to manually
// implement Wininet-style auto proxy detection.
if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy ||
state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseWinInetProxy)
{
var proxyInfo = new Interop.WinHttp.WINHTTP_PROXY_INFO();
bool updateProxySettings = false;
Uri uri = state.RequestMessage.RequestUri;
try
{
if (state.Proxy != null)
{
Debug.Assert(state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy);
updateProxySettings = true;
if (state.Proxy.IsBypassed(uri))
{
proxyInfo.AccessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY;
}
else
{
proxyInfo.AccessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY;
Uri proxyUri = state.Proxy.GetProxy(uri);
string proxyString = proxyUri.Scheme + "://" + proxyUri.Authority;
proxyInfo.Proxy = Marshal.StringToHGlobalUni(proxyString);
}
}
else if (_proxyHelper != null && _proxyHelper.AutoSettingsUsed)
{
if (_proxyHelper.GetProxyForUrl(_sessionHandle, uri, out proxyInfo))
{
updateProxySettings = true;
}
}
if (updateProxySettings)
{
GCHandle pinnedHandle = GCHandle.Alloc(proxyInfo, GCHandleType.Pinned);
try
{
SetWinHttpOption(
state.RequestHandle,
Interop.WinHttp.WINHTTP_OPTION_PROXY,
pinnedHandle.AddrOfPinnedObject(),
(uint)Marshal.SizeOf(proxyInfo));
}
finally
{
pinnedHandle.Free();
}
}
}
finally
{
Marshal.FreeHGlobal(proxyInfo.Proxy);
Marshal.FreeHGlobal(proxyInfo.ProxyBypass);
}
}
}
private void SetRequestHandleDecompressionOptions(SafeWinHttpHandle requestHandle)
{
uint optionData = 0;
if (_automaticDecompression != DecompressionMethods.None)
{
if ((_automaticDecompression & DecompressionMethods.GZip) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_DECOMPRESSION_FLAG_GZIP;
}
if ((_automaticDecompression & DecompressionMethods.Deflate) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_DECOMPRESSION_FLAG_DEFLATE;
}
try
{
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_DECOMPRESSION, ref optionData);
}
catch (WinHttpException ex)
{
if (ex.NativeErrorCode != (int)Interop.WinHttp.ERROR_WINHTTP_INVALID_OPTION)
{
throw;
}
// We are running on a platform earlier than Win8.1 for which WINHTTP.DLL
// doesn't support this option. So, we'll have to do the decompression
// manually.
_doManualDecompressionCheck = true;
}
}
}
private void SetRequestHandleRedirectionOptions(SafeWinHttpHandle requestHandle)
{
uint optionData = 0;
if (_automaticRedirection)
{
optionData = (uint)_maxAutomaticRedirections;
SetWinHttpOption(
requestHandle,
Interop.WinHttp.WINHTTP_OPTION_MAX_HTTP_AUTOMATIC_REDIRECTS,
ref optionData);
}
optionData = _automaticRedirection ?
Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP :
Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY_NEVER;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY, ref optionData);
}
private void SetRequestHandleCookieOptions(SafeWinHttpHandle requestHandle)
{
if (_cookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer ||
_cookieUsePolicy == CookieUsePolicy.IgnoreCookies)
{
uint optionData = Interop.WinHttp.WINHTTP_DISABLE_COOKIES;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_DISABLE_FEATURE, ref optionData);
}
}
private void SetRequestHandleTlsOptions(SafeWinHttpHandle requestHandle)
{
// If we have a custom server certificate validation callback method then
// we need to have WinHTTP ignore some errors so that the callback method
// will have a chance to be called.
uint optionData;
if (_serverCertificateValidationCallback != null)
{
optionData =
Interop.WinHttp.SECURITY_FLAG_IGNORE_UNKNOWN_CA |
Interop.WinHttp.SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE |
Interop.WinHttp.SECURITY_FLAG_IGNORE_CERT_CN_INVALID |
Interop.WinHttp.SECURITY_FLAG_IGNORE_CERT_DATE_INVALID;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_SECURITY_FLAGS, ref optionData);
}
else if (_checkCertificateRevocationList)
{
// If no custom validation method, then we let WinHTTP do the revocation check itself.
optionData = Interop.WinHttp.WINHTTP_ENABLE_SSL_REVOCATION;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_ENABLE_FEATURE, ref optionData);
}
}
private void SetRequestHandleClientCertificateOptions(SafeWinHttpHandle requestHandle, Uri requestUri)
{
if (requestUri.Scheme != UriScheme.Https)
{
return;
}
X509Certificate2 clientCertificate = null;
if (_clientCertificateOption == ClientCertificateOption.Manual)
{
clientCertificate = WinHttpCertificateHelper.GetEligibleClientCertificate(ClientCertificates);
}
else
{
clientCertificate = WinHttpCertificateHelper.GetEligibleClientCertificate();
}
if (clientCertificate != null)
{
SetWinHttpOption(
requestHandle,
Interop.WinHttp.WINHTTP_OPTION_CLIENT_CERT_CONTEXT,
clientCertificate.Handle,
(uint)Marshal.SizeOf<Interop.Crypt32.CERT_CONTEXT>());
}
else
{
SetNoClientCertificate(requestHandle);
}
}
internal static void SetNoClientCertificate(SafeWinHttpHandle requestHandle)
{
SetWinHttpOption(
requestHandle,
Interop.WinHttp.WINHTTP_OPTION_CLIENT_CERT_CONTEXT,
IntPtr.Zero,
0);
}
private void SetRequestHandleCredentialsOptions(WinHttpRequestState state)
{
// By default, WinHTTP sets the default credentials policy such that it automatically sends default credentials
// (current user's logged on Windows credentials) to a proxy when needed (407 response). It only sends
// default credentials to a server (401 response) if the server is considered to be on the Intranet.
// WinHttpHandler uses a more granual opt-in model for using default credentials that can be different between
// proxy and server credentials. It will explicitly allow default credentials to be sent at a later stage in
// the request processing (after getting a 401/407 response) when the proxy or server credential is set as
// CredentialCache.DefaultNetworkCredential. For now, we set the policy to prevent any default credentials
// from being automatically sent until we get a 401/407 response.
_authHelper.ChangeDefaultCredentialsPolicy(
state.RequestHandle,
Interop.WinHttp.WINHTTP_AUTH_TARGET_SERVER,
allowDefaultCredentials:false);
}
private void SetRequestHandleBufferingOptions(SafeWinHttpHandle requestHandle)
{
uint optionData = (uint)(_maxResponseHeadersLength * 1024);
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_RESPONSE_HEADER_SIZE, ref optionData);
optionData = (uint)_maxResponseDrainSize;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_RESPONSE_DRAIN_SIZE, ref optionData);
}
private void SetRequestHandleHttp2Options(SafeWinHttpHandle requestHandle, Version requestVersion)
{
Debug.Assert(requestHandle != null);
if (requestVersion == HttpVersion20)
{
WinHttpTraceHelper.Trace("WinHttpHandler.SetRequestHandleHttp2Options: setting HTTP/2 option");
uint optionData = Interop.WinHttp.WINHTTP_PROTOCOL_FLAG_HTTP2;
if (Interop.WinHttp.WinHttpSetOption(
requestHandle,
Interop.WinHttp.WINHTTP_OPTION_ENABLE_HTTP_PROTOCOL,
ref optionData))
{
WinHttpTraceHelper.Trace("WinHttpHandler.SetRequestHandleHttp2Options: HTTP/2 option supported");
}
else
{
WinHttpTraceHelper.Trace("WinHttpHandler.SetRequestHandleHttp2Options: HTTP/2 option not supported");
}
}
}
private void SetWinHttpOption(SafeWinHttpHandle handle, uint option, ref uint optionData)
{
Debug.Assert(handle != null);
if (!Interop.WinHttp.WinHttpSetOption(
handle,
option,
ref optionData))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private void SetWinHttpOption(SafeWinHttpHandle handle, uint option, string optionData)
{
Debug.Assert(handle != null);
if (!Interop.WinHttp.WinHttpSetOption(
handle,
option,
optionData,
(uint)optionData.Length))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private static void SetWinHttpOption(
SafeWinHttpHandle handle,
uint option,
IntPtr optionData,
uint optionSize)
{
Debug.Assert(handle != null);
if (!Interop.WinHttp.WinHttpSetOption(
handle,
option,
optionData,
optionSize))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private void HandleAsyncException(WinHttpRequestState state, Exception ex)
{
if (state.CancellationToken.IsCancellationRequested)
{
// If the exception was due to the cancellation token being canceled, throw cancellation exception.
state.Tcs.TrySetCanceled(state.CancellationToken);
}
else if (ex is WinHttpException || ex is IOException)
{
// Wrap expected exceptions as HttpRequestExceptions since this is considered an error during
// execution. All other exception types, including ArgumentExceptions and ProtocolViolationExceptions
// are 'unexpected' or caused by user error and should not be wrapped.
state.Tcs.TrySetException(new HttpRequestException(SR.net_http_client_execution_error, ex));
}
else
{
state.Tcs.TrySetException(ex);
}
}
private void SetOperationStarted()
{
if (!_operationStarted)
{
_operationStarted = true;
}
}
private void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
}
private void CheckDisposedOrStarted()
{
CheckDisposed();
if (_operationStarted)
{
throw new InvalidOperationException(SR.net_http_operation_started);
}
}
private void SetStatusCallback(
SafeWinHttpHandle requestHandle,
Interop.WinHttp.WINHTTP_STATUS_CALLBACK callback)
{
const uint notificationFlags =
Interop.WinHttp.WINHTTP_CALLBACK_FLAG_ALL_COMPLETIONS |
Interop.WinHttp.WINHTTP_CALLBACK_FLAG_HANDLES |
Interop.WinHttp.WINHTTP_CALLBACK_FLAG_REDIRECT |
Interop.WinHttp.WINHTTP_CALLBACK_FLAG_SEND_REQUEST;
IntPtr oldCallback = Interop.WinHttp.WinHttpSetStatusCallback(
requestHandle,
callback,
notificationFlags,
IntPtr.Zero);
if (oldCallback == new IntPtr(Interop.WinHttp.WINHTTP_INVALID_STATUS_CALLBACK))
{
int lastError = Marshal.GetLastWin32Error();
if (lastError != Interop.WinHttp.ERROR_INVALID_HANDLE) // Ignore error if handle was already closed.
{
throw WinHttpException.CreateExceptionUsingError(lastError);
}
}
}
private void ThrowOnInvalidHandle(SafeWinHttpHandle handle)
{
if (handle.IsInvalid)
{
int lastError = Marshal.GetLastWin32Error();
WinHttpTraceHelper.Trace("WinHttpHandler.ThrowOnInvalidHandle: error={0}", lastError);
throw WinHttpException.CreateExceptionUsingError(lastError);
}
}
private RendezvousAwaitable<int> InternalSendRequestAsync(WinHttpRequestState state)
{
lock (state.Lock)
{
state.Pin();
if (!Interop.WinHttp.WinHttpSendRequest(
state.RequestHandle,
null,
0,
IntPtr.Zero,
0,
0,
state.ToIntPtr()))
{
// Dispose (which will unpin) the state object. Since this failed, WinHTTP won't associate
// our context value (state object) to the request handle. And thus we won't get HANDLE_CLOSING
// notifications which would normally cause the state object to be unpinned and disposed.
state.Dispose();
WinHttpException.ThrowExceptionUsingLastError();
}
}
return state.LifecycleAwaitable;
}
private async Task InternalSendRequestBodyAsync(WinHttpRequestState state, bool chunkedModeForSend)
{
using (var requestStream = new WinHttpRequestStream(state, chunkedModeForSend))
{
await state.RequestMessage.Content.CopyToAsync(
requestStream,
state.TransportContext).ConfigureAwait(false);
await requestStream.EndUploadAsync(state.CancellationToken).ConfigureAwait(false);
}
}
private RendezvousAwaitable<int> InternalReceiveResponseHeadersAsync(WinHttpRequestState state)
{
lock (state.Lock)
{
if (!Interop.WinHttp.WinHttpReceiveResponse(state.RequestHandle, IntPtr.Zero))
{
throw WinHttpException.CreateExceptionUsingLastError();
}
}
return state.LifecycleAwaitable;
}
}
}
| |
#region Copyright (c) Roni Schuetz - All Rights Reserved
// * --------------------------------------------------------------------- *
// * Roni Schuetz *
// * Copyright (c) 2008 All Rights reserved *
// * *
// * Shared Cache high-performance, distributed caching and *
// * replicated caching system, generic in nature, but intended to *
// * speeding up dynamic web and / or win applications by alleviating *
// * database load. *
// * *
// * This Software is written by Roni Schuetz (schuetz AT gmail DOT com) *
// * *
// * This library is free software; you can redistribute it and/or *
// * modify it under the terms of the GNU Lesser General Public License *
// * as published by the Free Software Foundation; either version 2.1 *
// * of the License, or (at your option) any later version. *
// * *
// * This library is distributed in the hope that it will be useful, *
// * but WITHOUT ANY WARRANTY; without even the implied warranty of *
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
// * Lesser General Public License for more details. *
// * *
// * You should have received a copy of the GNU Lesser General Public *
// * License along with this library; if not, write to the Free *
// * Software Foundation, Inc., 59 Temple Place, Suite 330, *
// * Boston, MA 02111-1307 USA *
// * *
// * THIS COPYRIGHT NOTICE MAY NOT BE REMOVED FROM THIS FILE. *
// * --------------------------------------------------------------------- *
#endregion
// *************************************************************************
//
// Name: IndexusProviderBase.cs
//
// Created: 23-09-2007 SharedCache.com, rschuetz
// Modified: 23-09-2007 SharedCache.com, rschuetz : Creation
// Modified: 30-09-2007 SharedCache.com, rschuetz : updated summery + changed from bool to void back
// Modified: 30-09-2007 SharedCache.com, rschuetz : implemented additional overloads
// Modified: 01-01-2008 SharedCache.com, rschuetz : added a method to add data with prioirty
// Modified: 04-01-2008 SharedCache.com, rschuetz : added several Add methods to work with byte[] from the client
// Modified: 04-01-2008 SharedCache.com, rschuetz : change from method name RemoveAll to Clear()
// Modified: 24-02-2008 SharedCache.com, rschuetz : updated logging part for tracking, instead of using appsetting we use precompiler definition #if TRACE
// Modified: 28-01-2010 SharedCache.com, chrisme : clean up code
// *************************************************************************
// http://www.codeproject.com/useritems/memcached_aspnet.asp
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration.Provider;
using CCLIENT = SharedCache.WinServiceCommon.Configuration.Client;
namespace SharedCache.WinServiceCommon.Provider.Cache
{
/// <summary>
/// Implements the provider base for Shared Cache, based on Microsoft Provider Model.
/// <example>
/// <![CDATA[<?xml version="1.0" encoding="utf-8" ?>]]>
/// <configSections>
/// <section name="indexusNetSharedCache" type="SharedCache.WinServiceCommon.Configuration.Client.IndexusProviderSection, SharedCache.WinServiceCommon" />
/// </configSections>
///
/// <indexusNetSharedCache defaultProvider="IndexusSharedCacheProvider">
/// <servers>
/// <add key="Server1" ipaddress="10.0.0.3" port="48888" />
/// <add key="Server2" ipaddress="10.0.0.4" port="48888" />
/// </servers>
/// <providers>
/// <add
/// name="IndexusSharedCacheProvider"
/// type="SharedCache.WinServiceCommon.Provider.Cache.IndexusSharedCacheProvider, SharedCache.WinServiceCommon" />
/// </providers>
/// </indexusNetSharedCache>
/// </example>
/// </summary>
public abstract class IndexusProviderBase : ProviderBase
{
/// <summary>
/// Adding an item to cache. Items are added with Normal priority and
/// DateTime.MaxValue. Items are only get cleared from cache in case
/// max. cache factor arrived or the cache get refreshed.
/// </summary>
/// <remarks>
/// Data which is add with DataContractXxx() Methods need to receive Data from cache with DataContractGetXxx() Methods.
/// </remarks>
/// <param name="key">The key for cache item</param>
/// <param name="payload">The payload which is the object itself.</param>
public abstract void DataContractAdd(string key, object payload);
/// <summary>
/// Adding an item to cache. Items are added with Normal priority and
/// provided <see cref="DateTime"/>. Items get cleared from cache in case
/// max. cache factor arrived, cache get refreshed or provided <see cref="DateTime"/>
/// reached provided <see cref="DateTime"/>. The server takes care of items
/// with provided <see cref="DateTime"/>.
/// </summary>
/// <remarks>
/// Data which is add with DataContractXxx() Methods need to receive Data from cache with DataContractGetXxx() Methods.
/// </remarks>
/// <param name="key">The key for cache item</param>
/// <param name="payload">The payload which is the object itself.</param>
/// <param name="expires">Identify when item will expire from the cache.</param>
public abstract void DataContractAdd(string key, object payload, DateTime expires);
/// <summary>
/// Adding an item to cache. Items are added with provided priority <see cref="IndexusMessage.CacheItemPriority"/> and
/// DateTime.MaxValue. Items are only get cleared from cache in case max. cache factor arrived or the cache get refreshed.
/// </summary>
/// <remarks>
/// Data which is add with DataContractXxx() Methods need to receive Data from cache with DataContractGetXxx() Methods.
/// </remarks>
/// <param name="key">The key for cache item</param>
/// <param name="payload">The payload which is the object itself.</param>
/// <param name="prio">Item priority - See also <see cref="IndexusMessage.CacheItemPriority"/></param>
public abstract void DataContractAdd(string key, object payload, IndexusMessage.CacheItemPriority prio);
/// <summary>
/// Adding an item to specific cache node. It let user to control on which server node the item will be placed.
/// Items are added with normal priority <see cref="IndexusMessage.CacheItemPriority"/> and
/// DateTime.MaxValue <see cref="DateTime"/>. Items are only get cleared from cache in case max. cache factor
/// arrived or the cache get refreshed.
/// </summary>
/// <remarks>
/// Data which is add with DataContractXxx() Methods need to receive Data from cache with DataContractGetXxx() Methods.
/// </remarks>
/// <param name="key">The key for cache item</param>
/// <param name="payload">The payload which is the object itself.</param>
/// <param name="host">The host represents the ip address of a server node.</param>
public abstract void DataContractAdd(string key, object payload, string host);
/// <summary>
/// Adding an item to cache. Items are added with provided priority <see cref="IndexusMessage.CacheItemPriority"/> and
/// provided <see cref="DateTime"/>. Items get cleared from cache in case
/// max. cache factor arrived, cache get refreshed or provided <see cref="DateTime"/>
/// reached provided <see cref="DateTime"/>. The server takes care of items with provided <see cref="DateTime"/>.
/// </summary>
/// <remarks>
/// Data which is add with DataContractXxx() Methods need to receive Data from cache with DataContractGetXxx() Methods.
/// </remarks>
/// <param name="key">The key for cache item</param>
/// <param name="payload">The payload which is the object itself.</param>
/// <param name="expires">Identify when item will expire from the cache.</param>
/// <param name="prio">Item priority - See also <see cref="IndexusMessage.CacheItemPriority"/></param>
public abstract void DataContractAdd(string key, object payload, DateTime expires, IndexusMessage.CacheItemPriority prio);
/// <summary>
/// Retrieve specific item from cache based on provided key.
/// </summary>
/// <remarks>
/// Data need to be added to cache over DataContractAdd() methods otherwise the application throws an exception.
/// </remarks>
/// <remarks>
/// Data which is add with DataContractXxx() Methods need to receive Data from cache with DataContractGetXxx() Methods.
/// </remarks>
/// <typeparam name="T"></typeparam>
/// <param name="key">The key for cache item</param>
/// <returns>Returns received item as casted object T</returns>
public abstract T DataContractGet<T>(string key);
/// <summary>
/// Retrieve specific item from cache based on provided key.
/// </summary>
/// <remarks>
/// Data need to be added to cache over DataContractAdd() methods otherwise the application throws an exception.
/// </remarks>
/// <param name="key">The key for cache item</param>
/// <returns>Returns received item as casted <see cref="object"/></returns>
public abstract object DataContractGet(string key);
/// <summary>
/// Adding a bunch of data to the cache, prevents to make several calls
/// from the client to the server. All data is tranported with
/// a <see cref="IDictionary"/> with a <see cref="string"/> and <see cref="byte"/>
/// array combination.
/// </summary>
/// <param name="data">The data to add as a <see cref="IDictionary"/></param>
public abstract void DataContractMultiAdd(IDictionary<string, byte[]> data);
/// <summary>
/// Based on a list of key's the client receives a dictonary with
/// all available data depending on the keys.
/// </summary>
/// <remarks>
/// Data need to be added to cache over DataContractAdd() methods otherwise the application throws an exception.
/// </remarks>
/// <param name="keys">A List of <see cref="string"/> with all requested keys.</param>
/// <returns>A <see cref="IDictionary"/> with <see cref="string"/> and <see cref="byte"/> array element.</returns>
public abstract IDictionary<string, byte[]> DataContractMultiGet(List<string> keys);
/// <summary>
/// Returns items from cache node based on provided pattern.
/// </summary>
/// <remarks>
/// Data need to be added to cache over DataContractAdd() methods otherwise the application throws an exception.
/// </remarks>
/// <param name="regularExpression">The regular expression.</param>
/// <returns>An IDictionary with <see cref="string"/> and <see cref="byte"/> array with all founded elementes</returns>
public abstract IDictionary<string, byte[]> DataContractRegexGet(string regularExpression);
/// <summary>
/// Adding an item to cache with all possibility options. All overloads are using this
/// method to add items based on various provided variables. e.g. expire date time,
/// item priority or to a specific host
/// </summary>
/// <param name="key">The key for cache item</param>
/// <param name="payload">The payload which is the object itself.</param>
/// <param name="expires">Identify when item will expire from the cache.</param>
/// <param name="action">The action is always Add item to cache. See also <see cref="IndexusMessage.ActionValue"/> options.</param>
/// <param name="prio">Item priority - See also <see cref="IndexusMessage.CacheItemPriority"/></param>
/// <param name="status">The status of the request. See also <see cref="IndexusMessage.StatusValue"/></param>
/// <param name="host">The host, represents the specific server node.</param>
internal abstract void Add(string key, byte[] payload, DateTime expires, IndexusMessage.ActionValue action, IndexusMessage.CacheItemPriority prio, IndexusMessage.StatusValue status, string host);
/// <summary>
/// Adding an item to cache. Items are added with Normal priority and
/// DateTime.MaxValue. Items are only get cleared from cache in case
/// max. cache factor arrived or the cache get refreshed.
/// </summary>
/// <param name="key">The key for cache item</param>
/// <param name="payload">The payload which is the object itself.</param>
public abstract void Add(string key, object payload);
/// <summary>
/// Adding an item to cache. Items are added with Normal priority and
/// DateTime.MaxValue. Items are only get cleared from cache in case
/// max. cache factor arrived or the cache get refreshed.
/// </summary>
/// <param name="key">The key for cache item</param>
/// <param name="payload">The payload which is the object itself.</param>
public abstract void Add(string key, byte[] payload);
/// <summary>
/// Adding an item to cache. Items are added with Normal priority and
/// provided <see cref="DateTime"/>. Items get cleared from cache in case
/// max. cache factor arrived, cache get refreshed or provided <see cref="DateTime"/>
/// reached provided <see cref="DateTime"/>. The server takes care of items
/// with provided <see cref="DateTime"/>.
/// </summary>
/// <param name="key">The key for cache item</param>
/// <param name="payload">The payload which is the object itself.</param>
/// <param name="expires">Identify when item will expire from the cache.</param>
public abstract void Add(string key, object payload, DateTime expires);
/// <summary>
/// Adding an item to cache. Items are added with Normal priority and
/// provided <see cref="DateTime"/>. Items get cleared from cache in case
/// max. cache factor arrived, cache get refreshed or provided <see cref="DateTime"/>
/// reached provided <see cref="DateTime"/>. The server takes care of items
/// with provided <see cref="DateTime"/>.
/// </summary>
/// <param name="key">The key for cache item</param>
/// <param name="payload">The payload which is the object itself.</param>
/// <param name="expires">Identify when item will expire from the cache.</param>
public abstract void Add(string key, byte[] payload, DateTime expires);
/// <summary>
/// Adding an item to cache. Items are added with provided priority <see cref="IndexusMessage.CacheItemPriority"/> and
/// DateTime.MaxValue. Items are only get cleared from cache in case max. cache factor arrived or the cache get refreshed.
/// </summary>
/// <param name="key">The key for cache item</param>
/// <param name="payload">The payload which is the object itself.</param>
/// <param name="prio">Item priority - See also <see cref="IndexusMessage.CacheItemPriority"/></param>
public abstract void Add(string key, object payload, IndexusMessage.CacheItemPriority prio);
/// <summary>
/// Adding an item to cache. Items are added with provided priority <see cref="IndexusMessage.CacheItemPriority"/> and
/// DateTime.MaxValue. Items are only get cleared from cache in case max. cache factor arrived or the cache get refreshed.
/// </summary>
/// <param name="key">The key for cache item</param>
/// <param name="payload">The payload which is the object itself.</param>
/// <param name="prio">Item priority - See also <see cref="IndexusMessage.CacheItemPriority"/></param>
public abstract void Add(string key, byte[] payload, IndexusMessage.CacheItemPriority prio);
/// <summary>
/// Adding an item to specific cache node. It let user to control on which server node the item will be placed.
/// Items are added with normal priority <see cref="IndexusMessage.CacheItemPriority"/> and
/// DateTime.MaxValue <see cref="DateTime"/>. Items are only get cleared from cache in case max. cache factor
/// arrived or the cache get refreshed.
/// </summary>
/// <param name="key">The key for cache item</param>
/// <param name="payload">The payload which is the object itself.</param>
/// <param name="host">The host represents the ip address of a server node.</param>
public abstract void Add(string key, object payload, string host);
/// <summary>
/// Adding an item to specific cache node. It let user to control on which server node the item will be placed.
/// Items are added with normal priority <see cref="IndexusMessage.CacheItemPriority"/> and
/// DateTime.MaxValue <see cref="DateTime"/>. Items are only get cleared from cache in case max. cache factor
/// arrived or the cache get refreshed.
/// </summary>
/// <param name="key">The key for cache item</param>
/// <param name="payload">The payload which is the object itself.</param>
/// <param name="host">The host represents the ip address of a server node.</param>
public abstract void Add(string key, byte[] payload, string host);
/// <summary>
/// Adding an item to cache. Items are added with provided priority <see cref="IndexusMessage.CacheItemPriority"/> and
/// provided <see cref="DateTime"/>. Items get cleared from cache in case
/// max. cache factor arrived, cache get refreshed or provided <see cref="DateTime"/>
/// reached provided <see cref="DateTime"/>. The server takes care of items with provided <see cref="DateTime"/>.
/// </summary>
/// <param name="key">The key for cache item</param>
/// <param name="payload">The payload which is the object itself.</param>
/// <param name="expires">Identify when item will expire from the cache.</param>
/// <param name="prio">Item priority - See also <see cref="IndexusMessage.CacheItemPriority"/></param>
public abstract void Add(string key, object payload, DateTime expires, IndexusMessage.CacheItemPriority prio);
/// <summary>
/// Adding an item to cache. Items are added with provided priority <see cref="IndexusMessage.CacheItemPriority"/> and
/// provided <see cref="DateTime"/>. Items get cleared from cache in case
/// max. cache factor arrived, cache get refreshed or provided <see cref="DateTime"/>
/// reached provided <see cref="DateTime"/>. The server takes care of items with provided <see cref="DateTime"/>.
/// </summary>
/// <param name="key">The key for cache item</param>
/// <param name="payload">The payload which is the object itself.</param>
/// <param name="expires">Identify when item will expire from the cache.</param>
/// <param name="prio">Item priority - See also <see cref="IndexusMessage.CacheItemPriority"/></param>
public abstract void Add(string key, byte[] payload, DateTime expires, IndexusMessage.CacheItemPriority prio);
/// <summary>
/// This Method extends items time to live.
/// </summary>
/// <remarks>WorkItem Request: http://www.codeplex.com/SharedCache/WorkItem/View.aspx?WorkItemId=6129</remarks>
/// <param name="key">The key for cache item</param>
/// <param name="expires">Identify when item will expire from the cache.</param>
public abstract void ExtendTtl(string key, DateTime expires);
/// <summary>
/// Remove cache item with provided key.
/// </summary>
/// <param name="key">The key for cache item</param>
public abstract void Remove(string key);
/// <summary>
/// Retrieve specific item from cache based on provided key.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key">The key for cache item</param>
/// <returns>Returns received item as casted object T</returns>
public abstract T Get<T>(string key);
/// <summary>
/// Retrieve specific item from cache based on provided key.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key">The key for cache item</param>
/// <returns>Returns received item as casted object T</returns>
public abstract byte[] GetBinary(string key);
/// <summary>
/// Retrieve specific item from cache based on provided key.
/// </summary>
/// <param name="key">The key for cache item</param>
/// <returns>Returns received item as casted <see cref="object"/></returns>
public abstract object Get(string key);
/// <summary>
/// Based on a list of key's the client receives a dictonary with
/// all available data depending on the keys.
/// </summary>
/// <param name="keys">A List of <see cref="string"/> with all requested keys.</param>
/// <returns>A <see cref="IDictionary"/> with <see cref="string"/> and <see cref="byte"/> array element.</returns>
public abstract IDictionary<string, byte[]> MultiGet(List<string> keys);
/// <summary>
/// Adding a bunch of data to the cache, prevents to make several calls
/// from the client to the server. All data is tranported with
/// a <see cref="IDictionary{TKey,TValue}"/> with a <see cref="string"/> and <see cref="byte"/>
/// array combination.
/// </summary>
/// <param name="data">The data to add as a <see cref="IDictionary"/></param>
public abstract void MultiAdd(IDictionary<string, byte[]> data);
/// <summary>
/// Delete a bunch of data from the cache. This prevents several calls from
/// the client to the server. Only one single call is done with all relevant
/// key's for the server node.
/// </summary>
/// <param name="keys">A List of <see cref="string"/> with all requested keys to delete</param>
public abstract void MultiDelete(List<string> keys);
/// <summary>
/// Retrieve amount of configured server nodes.
/// </summary>
/// <value>The count.</value>
public abstract long Count { get;}
/// <summary>
/// Retrieve configured server nodes as an array of <see cref="string"/>
/// </summary>
/// <value>The servers.</value>
public abstract string[] Servers { get;}
/// <summary>
/// Retrieve configured server nodes configuration as a <see cref="List{T}"/>. This
/// is provides the Key and IPAddress of each item in the configuration section.
/// </summary>
/// <value>The servers list.</value>
public abstract List<CCLIENT.IndexusServerSetting> ServersList { get; }
/// <summary>
/// Retrieve replication server nodes configuration as an array of <see cref="string"/>. This
/// is provides the Key and IPAddress of each item in the configuration section.
/// </summary>
/// <value>An array of <see cref="string"/> with all configured replicated servers.</value>
public abstract string[] ReplicatedServers { get;}
/// <summary>
/// Retrieve replication server nodes configuration as a <see cref="List{T}"/>. This
/// is provides the Key and IPAddress of each item in the configuration section.
/// </summary>
/// <value>A List of <see cref="string"/> with all configured replicated servers.</value>
public abstract List<CCLIENT.IndexusServerSetting> ReplicatedServersList { get; }
/// <summary>
/// Force each configured cache server node to clear the cache.
/// </summary>
public abstract void Clear();
/// <summary>
/// Retrieve all statistic information <see cref="IndexusStatistic"/> from each configured
/// server as one item.
/// </summary>
/// <returns>an aggrigated <see cref="IndexusStatistic"/> object with all server statistics</returns>
public abstract IndexusStatistic GetStats();
/// <summary>
/// Retrieve statistic information <see cref="IndexusStatistic"/> from specific
/// server based on provided host.
/// </summary>
/// <param name="host">The host represents the ip address of a server node.</param>
/// <returns>an <see cref="IndexusStatistic"/> object</returns>
public abstract IndexusStatistic GetStats(string host);
/// <summary>
/// Evaluate the correct server node for provided key.
/// </summary>
/// <param name="key">The key for cache item</param>
/// <returns>returns the correct server for provided key</returns>
public abstract string GetServerForKey(string key);
/// <summary>
/// Retrieve a list with all key which are available on cache.
/// </summary>
/// <returns>A <see cref="List{T}"/> of strings with all available keys.</returns>
public abstract List<string> GetAllKeys();
/// <summary>
/// Retrieve a list with all key which are available on all cofnigured server nodes.
/// </summary>
/// <param name="host">The host represents the ip address of a server node.</param>
/// <returns>A <see cref="List{T}"/> of strings with all available keys.</returns>
public abstract List<string> GetAllKeys(string host);
/// <summary>
/// Pings the specified host.
/// </summary>
/// <param name="host">The host.</param>
/// <returns>if the server is available then it returns true otherwise false.</returns>
public abstract bool Ping(string host);
/// <summary>
/// Remove Cache Items on server node based on regular expression. Each item which matches
/// will be automatically removed from each server.
/// </summary>
/// <param name="regularExpression">The regular expression.</param>
/// <returns></returns>
public abstract bool RegexRemove(string regularExpression);
/// <summary>
/// Returns items from cache node based on provided pattern.
/// </summary>
/// <param name="regularExpression">The regular expression.</param>
/// <returns>An IDictionary with <see cref="string"/> and <see cref="byte"/> array with all founded elementes</returns>
public abstract IDictionary<string, byte[]> RegexGet(string regularExpression);
/// <summary>
/// Return Servers CLR (Common Language Runtime), this is needed to decide which
/// Hashing codes can be used.
/// </summary>
/// <returns>CLR (Common Language Runtime) version number as <see cref="string"/> e.g. xxxx.xxxx.xxxx.xxxx</returns>
public abstract IDictionary<string, string> ServerNodeVersionClr();
/// <summary>
/// Returns current build version of Shared Cache
/// </summary>
/// <returns>Shared Cache version number as <see cref="string"/> e.g. xxxx.xxxx.xxxx.xxxx</returns>
public abstract IDictionary<string, string> ServerNodeVersionSharedCache();
/// <summary>
/// Gets the absolute time expiration of items within cache nodes
/// </summary>
/// <param name="keys">A list with keys of type <see cref="string"/></param>
/// <returns>A <see cref="IDictionary{TKey,TValue}"/> were each key has its expiration absolute DateTime</returns>
public abstract IDictionary<string, DateTime> GetAbsoluteTimeExpiration(List<string> keys);
}
}
| |
// 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.Collections.ObjectModel;
using System.Dynamic.Utils;
namespace System.Runtime.CompilerServices
{
/// <summary>
/// The builder for read only collection.
/// </summary>
/// <typeparam name="T">The type of the collection element.</typeparam>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
internal sealed class ReadOnlyCollectionBuilder<T> : IList<T>, System.Collections.IList
{
private const int DefaultCapacity = 4;
private T[] _items;
private int _size;
private int _version;
private Object _syncRoot;
/// <summary>
/// Constructs a ReadOnlyCollectionBuilder.
/// </summary>
public ReadOnlyCollectionBuilder()
{
_items = Array.Empty<T>();
}
/// <summary>
/// Constructs a ReadOnlyCollectionBuilder with a given initial capacity.
/// The contents are empty but builder will have reserved room for the given
/// number of elements before any reallocations are required.
/// </summary>
public ReadOnlyCollectionBuilder(int capacity)
{
ContractUtils.Requires(capacity >= 0, "capacity");
_items = new T[capacity];
}
/// <summary>
/// Constructs a ReadOnlyCollectionBuilder, copying contents of the given collection.
/// </summary>
/// <param name="collection"></param>
public ReadOnlyCollectionBuilder(IEnumerable<T> collection)
{
ContractUtils.Requires(collection != null, "collection");
ICollection<T> c = collection as ICollection<T>;
if (c != null)
{
int count = c.Count;
_items = new T[count];
c.CopyTo(_items, 0);
_size = count;
}
else
{
_size = 0;
_items = new T[DefaultCapacity];
using (IEnumerator<T> en = collection.GetEnumerator())
{
while (en.MoveNext())
{
Add(en.Current);
}
}
}
}
/// <summary>
/// Gets and sets the capacity of this ReadOnlyCollectionBuilder
/// </summary>
public int Capacity
{
get { return _items.Length; }
set
{
ContractUtils.Requires(value >= _size, "value");
if (value != _items.Length)
{
if (value > 0)
{
T[] newItems = new T[value];
if (_size > 0)
{
Array.Copy(_items, 0, newItems, 0, _size);
}
_items = newItems;
}
else
{
_items = Array.Empty<T>();
}
}
}
}
/// <summary>
/// Returns number of elements in the ReadOnlyCollectionBuilder.
/// </summary>
public int Count
{
get { return _size; }
}
#region IList<T> Members
/// <summary>
/// Returns the index of the first occurrence of a given value in the builder.
/// </summary>
/// <param name="item">An item to search for.</param>
/// <returns>The index of the first occurrence of an item.</returns>
public int IndexOf(T item)
{
return Array.IndexOf(_items, item, 0, _size);
}
/// <summary>
/// Inserts an item to the <see cref="ReadOnlyCollectionBuilder{T}"/> at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which item should be inserted.</param>
/// <param name="item">The object to insert into the <see cref="ReadOnlyCollectionBuilder{T}"/>.</param>
public void Insert(int index, T item)
{
ContractUtils.Requires(index <= _size, "index");
if (_size == _items.Length)
{
EnsureCapacity(_size + 1);
}
if (index < _size)
{
Array.Copy(_items, index, _items, index + 1, _size - index);
}
_items[index] = item;
_size++;
_version++;
}
/// <summary>
/// Removes the <see cref="ReadOnlyCollectionBuilder{T}"/> item at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the item to remove.</param>
public void RemoveAt(int index)
{
ContractUtils.Requires(index >= 0 && index < _size, "index");
_size--;
if (index < _size)
{
Array.Copy(_items, index + 1, _items, index, _size - index);
}
_items[_size] = default(T);
_version++;
}
/// <summary>
/// Gets or sets the element at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the element to get or set.</param>
/// <returns>The element at the specified index.</returns>
public T this[int index]
{
get
{
ContractUtils.Requires(index < _size, "index");
return _items[index];
}
set
{
ContractUtils.Requires(index < _size, "index");
_items[index] = value;
_version++;
}
}
#endregion
#region ICollection<T> Members
/// <summary>
/// Adds an item to the <see cref="ReadOnlyCollectionBuilder{T}"/>.
/// </summary>
/// <param name="item">The object to add to the <see cref="ReadOnlyCollectionBuilder{T}"/>.</param>
public void Add(T item)
{
if (_size == _items.Length)
{
EnsureCapacity(_size + 1);
}
_items[_size++] = item;
_version++;
}
/// <summary>
/// Removes all items from the <see cref="ReadOnlyCollectionBuilder{T}"/>.
/// </summary>
public void Clear()
{
if (_size > 0)
{
Array.Clear(_items, 0, _size);
_size = 0;
}
_version++;
}
/// <summary>
/// Determines whether the <see cref="ReadOnlyCollectionBuilder{T}"/> contains a specific value
/// </summary>
/// <param name="item">the object to locate in the <see cref="ReadOnlyCollectionBuilder{T}"/>.</param>
/// <returns>true if item is found in the <see cref="ReadOnlyCollectionBuilder{T}"/>; otherwise, false.</returns>
public bool Contains(T item)
{
if ((Object)item == null)
{
for (int i = 0; i < _size; i++)
{
if ((Object)_items[i] == null)
{
return true;
}
}
return false;
}
else
{
EqualityComparer<T> c = EqualityComparer<T>.Default;
for (int i = 0; i < _size; i++)
{
if (c.Equals(_items[i], item))
{
return true;
}
}
return false;
}
}
/// <summary>
/// Copies the elements of the <see cref="ReadOnlyCollectionBuilder{T}"/> to an <see cref="Array"/>,
/// starting at particular <see cref="Array"/> index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="Array"/> that is the destination of the elements copied from <see cref="ReadOnlyCollectionBuilder{T}"/>.</param>
/// <param name="arrayIndex">The zero-based index in array at which copying begins.</param>
public void CopyTo(T[] array, int arrayIndex)
{
Array.Copy(_items, 0, array, arrayIndex, _size);
}
bool ICollection<T>.IsReadOnly
{
get { return false; }
}
/// <summary>
/// Removes the first occurrence of a specific object from the <see cref="ReadOnlyCollectionBuilder{T}"/>.
/// </summary>
/// <param name="item">The object to remove from the <see cref="ReadOnlyCollectionBuilder{T}"/>.</param>
/// <returns>true if item was successfully removed from the <see cref="ReadOnlyCollectionBuilder{T}"/>;
/// otherwise, false. This method also returns false if item is not found in the original <see cref="ReadOnlyCollectionBuilder{T}"/>.
/// </returns>
public bool Remove(T item)
{
int index = IndexOf(item);
if (index >= 0)
{
RemoveAt(index);
return true;
}
return false;
}
#endregion
#region IEnumerable<T> Members
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.</returns>
public IEnumerator<T> GetEnumerator()
{
return new Enumerator(this);
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
#region IList Members
bool System.Collections.IList.IsReadOnly
{
get { return false; }
}
int System.Collections.IList.Add(object value)
{
ValidateNullValue(value, "value");
try
{
Add((T)value);
}
catch (InvalidCastException)
{
ThrowInvalidTypeException(value, "value");
}
return Count - 1;
}
bool System.Collections.IList.Contains(object value)
{
if (IsCompatibleObject(value))
{
return Contains((T)value);
}
else return false;
}
int System.Collections.IList.IndexOf(object value)
{
if (IsCompatibleObject(value))
{
return IndexOf((T)value);
}
return -1;
}
void System.Collections.IList.Insert(int index, object value)
{
ValidateNullValue(value, "value");
try
{
Insert(index, (T)value);
}
catch (InvalidCastException)
{
ThrowInvalidTypeException(value, "value");
}
}
bool System.Collections.IList.IsFixedSize
{
get { return false; }
}
void System.Collections.IList.Remove(object value)
{
if (IsCompatibleObject(value))
{
Remove((T)value);
}
}
object System.Collections.IList.this[int index]
{
get
{
return this[index];
}
set
{
ValidateNullValue(value, "value");
try
{
this[index] = (T)value;
}
catch (InvalidCastException)
{
ThrowInvalidTypeException(value, "value");
}
}
}
#endregion
#region ICollection Members
void System.Collections.ICollection.CopyTo(Array array, int index)
{
ContractUtils.RequiresNotNull(array, "array");
ContractUtils.Requires(array.Rank == 1, "array");
Array.Copy(_items, 0, array, index, _size);
}
bool System.Collections.ICollection.IsSynchronized
{
get { return false; }
}
object System.Collections.ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
{
System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
return _syncRoot;
}
}
#endregion
/// <summary>
/// Reverses the order of the elements in the entire <see cref="ReadOnlyCollectionBuilder{T}"/>.
/// </summary>
public void Reverse()
{
Reverse(0, Count);
}
/// <summary>
/// Reverses the order of the elements in the specified range.
/// </summary>
/// <param name="index">The zero-based starting index of the range to reverse.</param>
/// <param name="count">The number of elements in the range to reverse.</param>
public void Reverse(int index, int count)
{
ContractUtils.Requires(index >= 0, "index");
ContractUtils.Requires(count >= 0, "count");
Array.Reverse(_items, index, count);
_version++;
}
/// <summary>
/// Copies the elements of the <see cref="ReadOnlyCollectionBuilder{T}"/> to a new array.
/// </summary>
/// <returns>An array containing copies of the elements of the <see cref="ReadOnlyCollectionBuilder{T}"/>.</returns>
public T[] ToArray()
{
T[] array = new T[_size];
Array.Copy(_items, 0, array, 0, _size);
return array;
}
/// <summary>
/// Creates a <see cref="ReadOnlyCollection{T}"/> containing all of the the elements of the <see cref="ReadOnlyCollectionBuilder{T}"/>,
/// avoiding copying the elements to the new array if possible. Resets the <see cref="ReadOnlyCollectionBuilder{T}"/> after the
/// <see cref="ReadOnlyCollection{T}"/> has been created.
/// </summary>
/// <returns>A new instance of <see cref="ReadOnlyCollection{T}"/>.</returns>
public ReadOnlyCollection<T> ToReadOnlyCollection()
{
// Can we use the stored array?
T[] items;
if (_size == _items.Length)
{
items = _items;
}
else
{
items = ToArray();
}
_items = Array.Empty<T>();
_size = 0;
_version++;
return new TrueReadOnlyCollection<T>(items);
}
private void EnsureCapacity(int min)
{
if (_items.Length < min)
{
int newCapacity = DefaultCapacity;
if (_items.Length > 0)
{
newCapacity = _items.Length * 2;
}
if (newCapacity < min)
{
newCapacity = min;
}
Capacity = newCapacity;
}
}
private static bool IsCompatibleObject(object value)
{
return ((value is T) || (value == null && default(T) == null));
}
private static void ValidateNullValue(object value, string argument)
{
if (value == null && !(default(T) == null))
{
throw new ArgumentException(Strings.InvalidNullValue(typeof(T)), argument);
}
}
private static void ThrowInvalidTypeException(object value, string argument)
{
throw new ArgumentException(Strings.InvalidObjectType(value != null ? value.GetType() : (object)"null", typeof(T)), argument);
}
private class Enumerator : IEnumerator<T>, System.Collections.IEnumerator
{
private readonly ReadOnlyCollectionBuilder<T> _builder;
private readonly int _version;
private int _index;
private T _current;
internal Enumerator(ReadOnlyCollectionBuilder<T> builder)
{
_builder = builder;
_version = builder._version;
_index = 0;
_current = default(T);
}
#region IEnumerator<T> Members
public T Current
{
get { return _current; }
}
#endregion
#region IDisposable Members
public void Dispose()
{
GC.SuppressFinalize(this);
}
#endregion
#region IEnumerator Members
object System.Collections.IEnumerator.Current
{
get
{
if (_index == 0 || _index > _builder._size)
{
throw Error.EnumerationIsDone();
}
return _current;
}
}
public bool MoveNext()
{
if (_version == _builder._version)
{
if (_index < _builder._size)
{
_current = _builder._items[_index++];
return true;
}
else
{
_index = _builder._size + 1;
_current = default(T);
return false;
}
}
else
{
throw Error.CollectionModifiedWhileEnumerating();
}
}
#endregion
#region IEnumerator Members
void System.Collections.IEnumerator.Reset()
{
if (_version != _builder._version)
{
throw Error.CollectionModifiedWhileEnumerating();
}
_index = 0;
_current = default(T);
}
#endregion
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.CompilerServices;
using Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib01.dlgatedeclarelib01
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib01.dlgatedeclarelib01;
// <Area> Dynamic type in delegates </Area>
// <Title> Delegate declaration at top level or under namespaces</Title>
// <Description></Description>
// <RelatedBugs></RelatedBugs>
//<Expects status=success></Expects>
// <Code>
using System;
public delegate dynamic D001(dynamic d);
public delegate object D002(dynamic d, object o);
public delegate dynamic D003(ref dynamic d1, object o, out dynamic d3);
public delegate void D004(ref int n, dynamic[] d1, params dynamic[] d2);
namespace DynNamespace01
{
public interface DynInterface01
{
}
public class DynClass01
{
public int n = 0;
}
public struct DynStruct01
{
}
public delegate dynamic D101(dynamic d, DynInterface01 i);
public delegate void D102(ref DynClass01 c, dynamic d1, ref object d2);
namespace DynNamespace02
{
public delegate void D201(ref dynamic d1, DynClass01 c, out dynamic[] d2, DynStruct01 st);
public delegate dynamic D202(DynStruct01 st, params object[] d2);
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgate001.dlgate001
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib01.dlgatedeclarelib01;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgate001.dlgate001;
// <Area> Dynamic type in delegates </Area>
// <Title> Delegate instantiation</Title>
// <Description> interchangable dynamic and object parameters </Description>
// <RelatedBugs></RelatedBugs>
//<Expects status=success></Expects>
using System;
namespace nms
{
public class Foo
{
// public delegate dynamic D001(dynamic v);
static public dynamic M01(dynamic v)
{
return 0x01;
}
public object M02(dynamic v)
{
return 0x02;
}
public dynamic M03(object v)
{
return 0x03;
}
static public dynamic M04(object v)
{
return 0x04;
}
// public delegate object D002(dynamic d, object o);
static public object M05(dynamic v1, object v2)
{
return 0x05;
}
public object M06(object v1, dynamic v2)
{
return 0x06;
}
static public dynamic M07(dynamic v1, object v2)
{
return 0x07;
}
public dynamic M08(object v1, dynamic v2)
{
return 0x08;
}
// dynamic D003(ref dynamic d1, object o, out dynamic d3);
static public dynamic M09(ref dynamic v1, object v2, out dynamic v3)
{
v3 = null;
return 0x09;
}
public object M0A(ref object v1, object v2, out object v3)
{
v3 = null;
return 0x0A;
}
public object M0B(ref dynamic v1, dynamic v2, out dynamic v3)
{
v3 = null;
return 0x0B;
}
// public delegate void D004(dynamic[] d1, params dynamic[] d2);
static public void M0C(ref int n, dynamic[] v1, params dynamic[] v2)
{
n += 0x0C;
}
public void M0D(ref int n, object[] v1, params object[] v2)
{
n += 0x0D;
}
}
public class start
{
private static int s_retval = (int)((1 + 0x0D) * 0x0D) / 2;
// field
private static D001 s_del001 = null;
private static D003 s_del003 = null;
private static dynamic s_sd = null;
private static object s_so = new object();
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
static public int MainMethod()
{
Foo foo = new Foo();
dynamic d = new object();
object o = null;
s_del001 = new D001(Foo.M01);
s_retval -= (int)s_del001(s_sd);
D001 d001 = new D001(foo.M02);
s_retval -= (int)d001(o);
d001 = new D001(foo.M03);
s_retval -= (int)d001(s_sd);
s_del001 = new D001(Foo.M04);
s_retval -= (int)s_del001(d);
D002 del002 = null;
del002 = new D002(Foo.M05);
s_retval -= (int)del002(d, o);
D002 d002 = new D002(foo.M06);
s_retval -= (int)d002(o, s_sd);
del002 = new D002(Foo.M07);
s_retval -= (int)del002(s_so, o);
d002 = new D002(foo.M08);
s_retval -= (int)d002(s_sd, s_so);
s_del003 = new D003(Foo.M09);
s_retval -= (int)s_del003(ref d, s_so, out s_sd);
D003 d003 = new D003(foo.M0A);
// Ex: Null ref
// retval -= (int)d003(ref o, sd, out so);
s_retval -= (int)d003(ref o, o, out o);
d003 = new D003(foo.M0B);
// Ex: Null ref
// retval -= (int)d003(ref so, d, out d);
s_retval -= (int)d003(ref s_so, s_so, out s_so);
dynamic[] dary = new object[]
{
}
;
int ret = 0;
D004 del004 = new D004(Foo.M0C);
del004(ref ret, new object[]
{
}
, dary);
s_retval -= ret;
del004 = new D004(foo.M0D);
ret = 0;
del004(ref ret, new dynamic[]
{
}
, dary);
s_retval -= ret;
return s_retval;
}
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgate002.dlgate002
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib01.dlgatedeclarelib01;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgate002.dlgate002;
// <Area> Dynamic type in delegates </Area>
// <Title> Delegate instantiation</Title>
// <Description> delegate can be assigned by ternary operator| +=, compared for equality
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects status=success></Expects>
using System;
namespace nms
{
public class Foo
{
// DynNamespace01: public delegate dynamic D101(dynamic d, DynInterface01 i);
static public dynamic M01(dynamic v1, ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib01.dlgatedeclarelib01.DynNamespace01.DynInterface01 v2)
{
return 0x01;
}
public dynamic M02(object v1, ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib01.dlgatedeclarelib01.DynNamespace01.DynInterface01 v2)
{
return 0x01;
}
// DynNamespace01: public delegate void D102(DynClass01 c, ref dynamic d1, ref object d2)
static public void M03(ref ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib01.dlgatedeclarelib01.DynNamespace01.DynClass01 v1, dynamic v2, ref object v3)
{
v1.n = 3;
}
public void M04(ref ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib01.dlgatedeclarelib01.DynNamespace01.DynClass01 v1, object v2, ref dynamic v3)
{
v1.n = 4;
}
// DynNamespace01:
// public delegate void D201(ref dynamic d1, DynClass01[] c, out dynamic d2, DynStruct01 st)
public void M05(ref dynamic v1, ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib01.dlgatedeclarelib01.DynNamespace01.DynClass01 v2, out dynamic[] v3, ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib01.dlgatedeclarelib01.DynNamespace01.DynStruct01 v4)
{
v1 = 5;
v3 = null;
}
static public void M06(ref object v1, ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib01.dlgatedeclarelib01.DynNamespace01.DynClass01 v2, out dynamic[] v3, ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib01.dlgatedeclarelib01.DynNamespace01.DynStruct01 v4)
{
v1 = 6;
v3 = null;
}
public void M07(ref object v1, ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib01.dlgatedeclarelib01.DynNamespace01.DynClass01 v2, out object[] v3, ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib01.dlgatedeclarelib01.DynNamespace01.DynStruct01 v4)
{
v1 = 7;
v3 = null;
}
// DynNamespace01:
// public delegate dynamic D202(DynStruct01 st, params object[] d2)
static public dynamic M08(ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib01.dlgatedeclarelib01.DynNamespace01.DynStruct01 v1, params object[] v2)
{
return 0x08;
}
public object M09(ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib01.dlgatedeclarelib01.DynNamespace01.DynStruct01 v1, params dynamic[] v2)
{
return 0x09;
}
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgate003.dlgate003;
// <Area> Dynamic type in delegates </Area>
// <Title> Delegate declaration under other types</Title>
// <Description></Description>
// <RelatedBugs></RelatedBugs>
//<Expects status=success></Expects>
// <Code>
using System;
namespace DynNamespace01
{
public class DynClass
{
public delegate string D001(object v1, dynamic v2, DynEnum v3);
public struct DynStruct
{
public delegate string D101(DynEnum v1, ref object v2, params dynamic[] v3);
public delegate string D102(DynEnum v1, ref dynamic v2, params object[] v3);
}
}
public enum DynEnum
{
item0,
item1,
item2,
item3,
item4,
item5,
item6
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgate003.dlgate003
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgate003.dlgate003;
// <Area> Dynamic type in delegates </Area>
// <Title> Delegate instantiation</Title>
// <Description> delegates can be aggregated in arrays and compared for equality.
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects status=success></Expects>
using System;
namespace nms
{
public class Foo
{
// DynNamespace01.DynClass:
// public delegate string D001(object v1, dynamic v2, ref DynEnum v3)
static public string M01(object v1, object v2, ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynEnum v3)
{
return v3.ToString();
}
public string M11(object v1, object v2, ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynEnum v3)
{
return v3.ToString();
}
public string M21(object v1, object v2, ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynEnum v3)
{
return v3.ToString();
}
static public string M02(dynamic v1, dynamic v2, ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynEnum v3)
{
return v3.ToString();
}
// DynNamespace01.DynClass.DynStruct:
// public delegate string D101(ref DynEnum v1, ref object v2, params dynamic[] v3);
public string M03(ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynEnum v1, ref object v2, params dynamic[] v3)
{
return v1.ToString();
}
// DynNamespace01.DynClass.DynStruct:
// blic delegate string D101(ref DynEnum v1, ref dynamic v2, params object[] v3)
public string M04(ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynEnum v1, ref dynamic v2, params object[] v3)
{
return v1.ToString();
}
}
public class start
{
// field
private static ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynClass.D001[] s_d001 = new ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynClass.D001[3];
private static dynamic s_sd = null;
private static object s_so = new object();
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
static public int MainMethod()
{
bool ret = true;
Foo foo = new Foo();
dynamic d = new object();
object o = null;
s_d001[0] = new ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynClass.D001(foo.M11);
s_d001[1] = new ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynClass.D001(foo.M21);
s_d001[2] = new ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynClass.D001(Foo.M01);
ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynClass.D001[] ary101 =
{
new ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynClass.D001(Foo.M01), new ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynClass.D001(foo.M21), new ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynClass.D001(foo.M11)}
;
if (s_d001[0] != ary101[2])
{
ret = false;
}
if (s_d001[1] != ary101[1])
{
ret = false;
}
if (s_d001[2] != ary101[0])
{
ret = false;
}
ary101[0] = new ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynClass.D001(Foo.M02);
string st1 = ary101[0](s_so, s_sd, ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynEnum.item1);
if (ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynEnum.item1.ToString() != s_d001[0](s_so, d, ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynEnum.item1))
{
ret = false;
}
if (ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynEnum.item1.ToString() != st1)
{
ret = false;
}
dynamic[] dary = new object[]
{
}
;
object[] oary = new object[]
{
}
;
ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynClass.DynStruct.D101 d101 = null;
d101 = new ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynClass.DynStruct.D101(foo.M03);
ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynClass.DynStruct.D101 d111 = new ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynClass.DynStruct.D101(foo.M04);
st1 = d101(ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynEnum.item2, ref d, dary);
if (ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynEnum.item2.ToString() != st1)
{
ret = false;
}
st1 = d101(ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynEnum.item3, ref o, oary);
if (ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynEnum.item3.ToString() != st1)
{
ret = false;
}
st1 = d111(ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynEnum.item3, ref o, oary);
if (ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynEnum.item3.ToString() != st1)
{
ret = false;
}
st1 = d111(ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynEnum.item4, ref s_so, dary);
if (ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynEnum.item4.ToString() != st1)
{
ret = false;
}
ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynClass.DynStruct.D102 d102 = new ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynClass.DynStruct.D102(foo.M04);
st1 = d102(ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynEnum.item5, ref d, dary);
if (ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynEnum.item5.ToString() != st1)
{
ret = false;
}
ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynClass.DynStruct.D102 d122 = new ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynClass.DynStruct.D102(foo.M03);
st1 = d122(ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynEnum.item6, ref s_so, oary);
if (ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynEnum.item6.ToString() != st1)
{
ret = false;
}
return ret ? 0 : 1;
}
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib03.dlgatedeclarelib03
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib03.dlgatedeclarelib03;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgate004.dlgate004;
// <Area> Dynamic type in delegates </Area>
// <Title> Delegate declaration with different modifiers</Title>
// <Description></Description>
// <RelatedBugs></RelatedBugs>
//<Expects status=success></Expects>
// <Code>
using System;
namespace DynNamespace31
{
public class DynClassBase
{
public delegate void PublicDel(dynamic v, ref int n);
private delegate void PrivateDel(dynamic d);
}
public class DynClassDrived : DynClassBase
{
private new delegate void PublicDel(dynamic v, ref int n);
// protected: can not access if in dll
public delegate long InternalDel(sbyte v1, dynamic v2, short v3, dynamic v4, int v5, dynamic v6, long v7, dynamic v8, dynamic v9);
protected delegate void ProtectedDel(dynamic d);
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgate004.dlgate004
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib03.dlgatedeclarelib03;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgate004.dlgate004;
// <Area> Dynamic type in delegates </Area>
// <Title> Delegate instantiation</Title>
// <Description> delegates can be combined by using +, - +=, -=
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects status=success></Expects>
using System;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib03.dlgatedeclarelib03.DynNamespace31;
namespace nms
{
public class Foo
{
// DynNamespace31.DynClassBase: public delegate void PublicDel(dynamic v, ref int n)
// DynNamespace31.DynClassDrived: new delegate void NewPublicDel(dynamic v, ref int n);
public void M01(dynamic v, ref int n)
{
n = 1;
}
internal void M02(dynamic v, ref int n)
{
n = 2;
}
public void M03(object v, ref int n)
{
n = 4;
}
internal void M04(object v, ref int n)
{
n = 8;
}
// DynNamespace31.DynClassDrived:
// internal delegate long InternalDel(sbyte v1, dynamic v2, short v3, dynamic v4, int v5, dynamic v6, long v7, dynamic v8, dynamic v9)
static public long M11(sbyte v1, dynamic v2, short v3, dynamic v4, int v5, dynamic v6, long v7, dynamic v8, dynamic v9)
{
return v1 + (int)v2 + v3 + (int)v4 + v5 + (int)v6 + v7 + (int)v8 + (int)v9;
}
static internal long M12(sbyte v1, dynamic v2, short v3, dynamic v4, int v5, dynamic v6, long v7, dynamic v8, object v9)
{
return v1 + v3 + v5 + v7 + (int)v9;
}
static public long M13(sbyte v1, dynamic v2, short v3, object v4, int v5, dynamic v6, long v7, dynamic v8, object v9)
{
return (int)v2 + (int)v4 + (int)v6 + (int)v8;
}
// DynNamespace31.DynClassDrived:
// static public delegate int StPublicDel(dynamic v1, decimal v2);
internal int M21(dynamic v1, decimal v2)
{
return 33;
}
internal int M22(object v1, decimal v2)
{
return 66;
}
internal int M23(dynamic v1, decimal v2)
{
return 99;
}
internal int M24(object v1, decimal v2)
{
return -1;
}
}
public struct start
{
// field
private static DynClassDrived.InternalDel s_interDel;
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
static public int MainMethod()
{
bool ret = true;
Foo foo = new Foo();
dynamic d = new object();
object o = new object();
DynClassBase.PublicDel pd01 = new DynClassBase.PublicDel(foo.M01);
DynClassDrived.PublicDel pd02 = new DynClassBase.PublicDel(foo.M02);
DynClassBase.PublicDel pd03 = new DynClassBase.PublicDel(foo.M03);
DynClassDrived.PublicDel pd04 = new DynClassBase.PublicDel(foo.M04);
DynClassBase.PublicDel pd05 = pd01 + pd02;
pd05 += new DynClassBase.PublicDel(pd01);
DynClassBase.PublicDel pd06 = pd03 + new DynClassDrived.PublicDel(foo.M04);
pd06 = pd04 + pd05 + pd06; // M04+M01+M02+M01+M03+M04 => 8 (last one)
int n = 0;
pd06(d, ref n);
if (8 != n)
{
ret = false;
}
pd06 -= pd04;
pd06(d, ref n);
if (4 != n)
{
ret = false;
}
pd06 -= pd01;
pd06(d, ref n);
if (4 != n)
{
ret = false;
}
//
s_interDel = new DynClassDrived.InternalDel(Foo.M11);
DynClassDrived.InternalDel dd01 = new DynClassDrived.InternalDel(s_interDel); //45
DynClassDrived.InternalDel dd02 = new DynClassDrived.InternalDel(Foo.M12); // 25
DynClassDrived.InternalDel dd03 = new DynClassDrived.InternalDel(Foo.M13); // 20
DynClassDrived.InternalDel dd04 = dd01; // 45
dd04 += dd02; // 25
DynClassDrived.InternalDel dd05 = dd02 + dd03;
dd04 += dd05 + new DynClassDrived.InternalDel(dd05); // new(1)+2+ 2+3 + new(2+3)
long lg = dd04(1, 2, 3, 4, 5, 6, 7, 8, 9);
if (20 != lg) // dd03
{
ret = false;
}
dd04 = dd04 - dd02 - dd02 - dd03; // new(1)+ new(2+3)
lg = dd04(1, 2, 3, 4, 5, 6, 7, 8, 9);
if (20 != lg) // dd03
{
ret = false;
}
dd04 -= new DynClassDrived.InternalDel(dd05); // new(1)
lg = dd04(1, 2, 3, 4, 5, 6, 7, 8, 9);
if (45 != lg)
{
ret = false;
}
return ret ? 0 : 1;
}
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib04.dlgatedeclarelib04
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib04.dlgatedeclarelib04;
// <Area> Dynamic type in delegates </Area>
// <Title> Delegate declaration with generic types</Title>
// <Description></Description>
// <RelatedBugs></RelatedBugs>
//<Expects status=success></Expects>
// <Code>
using System;
public delegate R D001<R>(dynamic d);
namespace DynNamespace41
{
public delegate void D002<T1, T2>(T1 t1, T2 t2);
public class DynClass
{
public delegate R D011<T, R>(T[] v1, dynamic v2);
// internal: can not access if in dll
public delegate dynamic D012<T>(ref T v1, ref dynamic[] v2);
}
public struct DynStruct
{
public delegate R D021<T, R>(out dynamic d, out T t);
// internal: can not access if in dll
public delegate dynamic D022<T1, T2, T3>(T1 t1, ref T2 t2, out T3 t3, params dynamic[] d);
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib05.dlgatedeclarelib05
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib05.dlgatedeclarelib05;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgate006.dlgate006;
// <Area> Dynamic type in delegates </Area>
// <Title> Delegate declaration with optional parameters</Title>
// <Description></Description>
// <RelatedBugs></RelatedBugs>
//<Expects status=success></Expects>
// <Code>
using System;
public delegate void D001(dynamic d = null); // not allow init with values other than null:(
public delegate void D002(dynamic v1, object v2 = null, dynamic v3 = null /*DynNamespace51.DynClass.strDyn*/);
namespace DynNamespace51
{
public delegate void D011(dynamic d1 = null, params dynamic[] d2);
public class DynClass
{
public const string strDyn = "dynamic";
// internal: can not access if in dll
public delegate int D021(params dynamic[] d);
public delegate void D022(DynStruct01 v1, dynamic v2 = null, int v3 = -1);
public struct DynStruct
{
public delegate dynamic D031(DynClass01 v1, DynStruct01 v2 = new DynStruct01(), dynamic[] v3 = null);
}
}
public class DynClass01
{
}
public struct DynStruct01
{
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgate006.dlgate006
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib05.dlgatedeclarelib05;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgate006.dlgate006;
// <Area> Dynamic type in delegates </Area>
// <Title> Delegate instantiation</Title>
// <Description> delegates can has optional parameters
// default value of dynamic can only be set to null :(
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects status=success></Expects>
using System;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib05.dlgatedeclarelib05.DynNamespace51;
namespace nms
{
public class Foo
{
static public int val = -1;
static public int? nval = -1;
static public string str = string.Empty;
// public delegate void D001(dynamic d = null);
public void M01(dynamic d = null)
{
val = d;
}
internal void M02(dynamic d)
{
nval = d;
}
// internal delegate void D002(dynamic v1, object v2 = null, dynamic v3 = null)
static internal void M11(dynamic v1, object v2, dynamic v3 = null)
{
str = v3;
}
// public delegate void D011(dynamic d1 = null, params dynamic[] d2);
public void M21(dynamic d1, params dynamic[] d2)
{
nval = d1;
}
// internal delegate int D021(params dynamic[] d);
static internal int M31(params dynamic[] d)
{
return 31;
}
// public delegate void D022(DynStruct01 v1, dynamic v2 = 0.123f, int v3 = -1);
static internal void M41(DynStruct01 v1, dynamic v2 = null, int v3 = 41)
{
val = v3;
}
// public delegate dynamic D031(DynClass01 v1, DynStruct01 v2 = new DynStruct01(), dynamic[] v3 = null);
static public dynamic M51(DynClass01 v1, DynStruct01 v2 = new DynStruct01(), dynamic[] v3 = null)
{
return 51;
}
}
public class TestClass
{
[Fact]
public void RunTest()
{
start.DynamicCSharpRunTest();
}
}
public struct start
{
// field
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
static public int MainMethod()
{
bool ret = true;
Foo foo = new Foo();
dynamic d = new object();
D001 dd01 = new D001(foo.M01);
dd01(123); // use delegate's default value
if (123 != Foo.val)
{
ret = false;
}
dd01(100);
if (100 != Foo.val)
{
ret = false;
}
Foo.val = -1;
D001 dd11 = new D001(foo.M02);
dd11();
if (null != Foo.nval)
{
ret = false;
}
dd11(101);
if (101 != Foo.nval)
{
ret = false;
}
D002 dd021;
dd021 = new D002(Foo.M11);
dd021(88);
if (null != Foo.str)
{
ret = false;
}
dd021(66, "boo", "Dah");
if (0 != String.CompareOrdinal("Dah", Foo.str))
{
ret = false;
}
dynamic dstr = "Hello";
dd021(88, null, dstr);
if ((string)dstr != Foo.str)
{
ret = false;
}
D011 dd011 = new D011(foo.M21);
dd011();
if (Foo.nval.HasValue)
{
ret = false;
}
dd011(102);
if (!Foo.nval.HasValue || 102 != Foo.nval)
{
ret = false;
}
DynClass.D021 dd21 = new DynClass.D021(Foo.M31);
int n = dd21();
n = dd21(d);
DynClass.D022 dd22 = null;
dd22 = new DynClass.D022(Foo.M41);
dd22(new DynStruct01());
if (-1 != Foo.val) // 41
{
ret = false;
}
dd22(new DynStruct01(), 0.780f, 103);
if (103 != Foo.val)
{
ret = false;
}
DynClass.DynStruct.D031 dd31 = new DynClass.DynStruct.D031(Foo.M51);
n = dd31(new DynClass01());
if (51 != n)
{
ret = false;
}
n = dd31(null, new DynStruct01());
if (51 != n)
{
ret = false;
}
n = dd31(new DynClass01(), new DynStruct01(), null);
if (51 != n)
{
ret = false;
}
return ret ? 0 : 1;
}
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgate007bug.dlgate007bug
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgate007bug.dlgate007bug;
// <Area> Dynamic type in delegates </Area>
// <Title> Delegate instantiation</Title>
// <Description> Assert and NullRef Exception when call with delegate 2nd as out param </Description>
// <RelatedBugs></RelatedBugs>
//<Expects status=success></Expects>
using System;
namespace nms
{
public delegate void DelOut(object v1, out object v2);
public class Foo
{
static public void M01(object v1, out object v2)
{
v2 = null;
}
static public void M02(object v1, out dynamic v2)
{
v2 = null;
}
static public void M03(dynamic v1, out object v2)
{
v2 = null;
}
static internal void M04(dynamic v1, out dynamic v2)
{
v2 = null;
}
}
public class start
{
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
static public int MainMethod()
{
dynamic nd = null;
dynamic d = new object();
object no = null;
object o = new object();
DelOut d_oo = new DelOut(Foo.M01);
DelOut d_od = new DelOut(Foo.M02);
DelOut d_do = new DelOut(Foo.M03);
DelOut d_dd = new DelOut(Foo.M03);
// object, object
d_oo(no, out o);
d_od(o, out no);
d_do(no, out o);
d_od(o, out no);
// object, dynamic
d_oo(o, out nd);
d_od(no, out d);
d_do(o, out nd);
d_od(no, out d);
// Assert and Null Ref Exception
// dynamic, object
d_oo(nd, out o);
d_od(nd, out no);
d_do(d, out o);
d_od(d, out no);
// dynamic, dynamic
d_oo(d, out d);
d_od(d, out nd);
d_do(nd, out d);
d_od(nd, out nd);
return 0;
}
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgate008bug.dlgate008bug
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgate008bug.dlgate008bug;
// <Area> Dynamic type in delegates </Area>
// <Title> Delegate instantiation (Behavior is 'by design' as they are 2 different boxed instances)</Title>
// <Description> Delegate: compare same delegates return false if the method is struct's not staic method </Description>
// <RelatedBugs></RelatedBugs>
//<Expects status=success></Expects>
using System;
namespace nms
{
public delegate void Del(dynamic v1);
public struct Foo
{
public void MinStruct(dynamic v1)
{
}
static public void SMinStruct(dynamic v1)
{
}
}
public class Bar
{
public void MinClass(dynamic v1)
{
}
static public void SMinClass(dynamic v1)
{
}
}
public class start
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
static public int MainMethod()
{
bool ret = true;
Bar bar = new Bar();
Del[] ary01 =
{
new Del(Foo.SMinStruct), new Del(bar.MinClass), new Del(Bar.SMinClass)}
;
Del[] ary02 =
{
new Del(Foo.SMinStruct), new Del(bar.MinClass), new Del(Bar.SMinClass)}
;
int idx = 0;
foreach (Del d in ary01)
{
if (d != ary02[idx])
{
ret = false;
}
idx++;
}
return ret ? 0 : 1;
}
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgate009bug.dlgate009bug
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgate009bug.dlgate009bug;
// <Area> Dynamic type in delegates </Area>
// <Title> Delegate instantiation</Title>
// <Description>
// Delegate with params: ASSERT FAILED,(result) ? (GetOutputContext().m_bHadNamedAndOptionalArguments) : true, File: ... transformpass.cpp, Line: 234
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects status=success></Expects>
using System;
namespace nms
{
internal delegate void DOptObj(params object[] ary);
internal delegate void DOptDyn(params dynamic[] ary);
public class Foo
{
public void M01(params dynamic[] d)
{
}
public void M02(params object[] d)
{
}
}
public class TestClass
{
[Fact]
public void RunTest()
{
start.DynamicCSharpRunTest();
}
}
public struct start
{
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
static public int MainMethod()
{
Foo foo = new Foo();
DOptObj dobj01 = new DOptObj(foo.M01);
DOptObj dobj02 = new DOptObj(foo.M02);
DOptDyn ddyn01 = new DOptDyn(foo.M01);
DOptDyn ddyn02 = new DOptDyn(foo.M02);
// Assert
dobj01(1, 2, 3);
dobj02(1, 2, 3);
ddyn01(1, 2, 3);
ddyn02(1, 2, 3);
return 0;
}
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.generic001.generic001
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.generic001.generic001;
// <Title>+= on a generic event does work</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Program
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic d = new SubGenericClass<int>();
d.myDel += (GenDlg<int>)null;
d.myDel -= (GenDlg<int>)null;
return 0;
}
public GenDlg<int> GetMe()
{
return null;
}
}
public delegate T GenDlg<T>(int t);
public class SubGenericClass<T>
{
public GenDlg<T> myDel;
public void Foo<U>(U x)
{
GenDlg<U> d = null;
d += (GenDlg<U>)null;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.generic002.generic002
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.generic002.generic002;
// <Title>+= on a generic event does work</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
//<Expects Status=warning>\(39,28\).*CS0067</Expects>
using System;
public class Program
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic t = new SubGenericClass<int>();
t.Foo(4);
var p = new Program();
dynamic d = new SubGenericClass<int>();
d.myDel += (GenDlg<int>)p.GetMe();
d.myDel -= (GenDlg<int>)p.GetMe();
d = new SubGenericClass<string>();
d.vEv += (GenDlg<string>)null;
d.vEv -= (GenDlg<string>)null;
return 0;
}
public GenDlg<int> GetMe()
{
return null;
}
}
public delegate T GenDlg<out T>(int t);
public class SubGenericClass<T>
{
public GenDlg<T> myDel;
public event GenDlg<T> vEv;
public void Foo<U>(U x)
{
GenDlg<U> d = null;
d += (GenDlg<U>)null;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.generic003.generic003
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.generic003.generic003;
// <Title>+= on a generic event does work</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
//<Expects Status=warning>\(42,31\).*CS0067</Expects>
using System;
public class Program
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic t = new SubGenericClass<int>();
t.Foo(4);
dynamic d = new SubGenericClass<int>();
d.myDel += (GenDlg<C<int>>)null;
d.myDel -= (GenDlg<C<int>>)null;
d = new SubGenericClass<string>();
d.vEv += (GenDlg<C<string>>)null;
d.vEv -= (GenDlg<C<string>>)null;
return 0;
}
public GenDlg<int> GetMe()
{
return null;
}
}
public delegate T GenDlg<T>(int t);
public class C<T>
{
}
public class SubGenericClass<T>
{
public GenDlg<C<T>> myDel;
public event GenDlg<C<T>> vEv;
public void Foo<U>(U x)
{
GenDlg<U> d = null;
d += (GenDlg<U>)null;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.generic004.generic004
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.generic004.generic004;
// <Title>+= on a generic event does work</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
//<Expects Status=warning>\(41,28\).*CS0067</Expects>
using System;
public class Program
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic t = new SubGenericClass<int>();
t.Foo(4);
dynamic d = new SubGenericClass<int>();
d.myDel += (GenDlg<int>)(x => 4);
d.myDel -= (GenDlg<int>)(x => 4);
d = new SubGenericClass<string>();
d.vEv += (GenDlg<string>)(x => "");
d.vEv -= (GenDlg<string>)(x => "");
return 0;
}
public GenDlg<int> GetMe()
{
return null;
}
}
public delegate T GenDlg<T>(int t);
public class SubGenericClass<T>
{
public GenDlg<T> myDel;
public event GenDlg<T> vEv;
public void Foo<U>(U x)
{
GenDlg<U> d = null;
d += (GenDlg<U>)null;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.generic005.generic005
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.generic005.generic005;
// <Title>+= on a generic event does work</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
//<Expects Status=warning>\(48,28\).*CS0067</Expects>
using System;
public class C
{
public static implicit operator GenDlg<int>(C c)
{
return null;
}
}
public class Program
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic t = new SubGenericClass<int>();
t.Foo(4);
dynamic d = new SubGenericClass<int>();
d.myDel += (GenDlg<int>)new C(); //RuntimeBinderException
d.myDel -= (GenDlg<int>)(x => 4); //RuntimeBinderException
d = new SubGenericClass<string>();
d.vEv += (GenDlg<string>)(x => ""); //RuntimeBinderException
d.vEv -= (GenDlg<string>)(x => ""); //RuntimeBinderException
return 0;
}
public GenDlg<int> GetMe()
{
return null;
}
}
public delegate T GenDlg<T>(int t);
public class SubGenericClass<T>
{
public GenDlg<T> myDel;
public event GenDlg<T> vEv;
public void Foo<U>(U x)
{
GenDlg<U> d = null;
d += (GenDlg<U>)null;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.generic006.generic006
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.generic006.generic006;
// <Title>+= on a generic event does work</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
//<Expects Status=warning>\(43,35\).*CS0067</Expects>
using System;
public class C
{
public static implicit operator GenDlg<int>(C c)
{
return null;
}
}
public class Program
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic t = new SubGenericClass<int>();
t.Foo(4);
dynamic d = new SubGenericClass<int>();
SubGenericClass<int>.myDel += (GenDlg<int>)(dynamic)new C();
SubGenericClass<int>.vEv += (GenDlg<int>)(dynamic)new C();
return 0;
}
public GenDlg<int> GetMe()
{
return null;
}
}
public delegate T GenDlg<T>(int t);
public class SubGenericClass<T>
{
public static GenDlg<T> myDel;
public static event GenDlg<T> vEv;
public void Foo<U>(U x)
{
GenDlg<U> d = null;
d += (GenDlg<U>)null;
}
}
// </Code>
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Orchard.Caching;
using Orchard.Environment.Extensions.Models;
using Orchard.FileSystems.Dependencies;
using Orchard.FileSystems.VirtualPath;
using Orchard.Logging;
namespace Orchard.Environment.Extensions.Loaders {
/// <summary>
/// Load an extension by looking into the "bin" subdirectory of an
/// extension directory.
/// </summary>
public class PrecompiledExtensionLoader : ExtensionLoaderBase {
private readonly IHostEnvironment _hostEnvironment;
private readonly IAssemblyProbingFolder _assemblyProbingFolder;
private readonly IVirtualPathProvider _virtualPathProvider;
private readonly IVirtualPathMonitor _virtualPathMonitor;
public PrecompiledExtensionLoader(
IHostEnvironment hostEnvironment,
IDependenciesFolder dependenciesFolder,
IAssemblyProbingFolder assemblyProbingFolder,
IVirtualPathProvider virtualPathProvider,
IVirtualPathMonitor virtualPathMonitor)
: base(dependenciesFolder) {
_hostEnvironment = hostEnvironment;
_assemblyProbingFolder = assemblyProbingFolder;
_virtualPathProvider = virtualPathProvider;
_virtualPathMonitor = virtualPathMonitor;
Logger = NullLogger.Instance;
}
public ILogger Logger { get; set; }
public bool Disabled { get; set; }
public override int Order { get { return 30; } }
public override IEnumerable<ExtensionCompilationReference> GetCompilationReferences(DependencyDescriptor dependency) {
yield return new ExtensionCompilationReference { AssemblyName = dependency.Name };
}
public override IEnumerable<string> GetVirtualPathDependencies(DependencyDescriptor dependency) {
yield return _assemblyProbingFolder.GetAssemblyVirtualPath(dependency.Name);
}
public override void ExtensionRemoved(ExtensionLoadingContext ctx, DependencyDescriptor dependency) {
if (_assemblyProbingFolder.AssemblyExists(dependency.Name)) {
ctx.DeleteActions.Add(
() => {
Logger.Information("ExtensionRemoved: Deleting assembly \"{0}\" from probing directory", dependency.Name);
_assemblyProbingFolder.DeleteAssembly(dependency.Name);
});
// We need to restart the appDomain if the assembly is loaded
if (_hostEnvironment.IsAssemblyLoaded(dependency.Name)) {
Logger.Information("ExtensionRemoved: Module \"{0}\" is removed and its assembly is loaded, forcing AppDomain restart", dependency.Name);
ctx.RestartAppDomain = true;
}
}
}
public override void ExtensionActivated(ExtensionLoadingContext ctx, ExtensionDescriptor extension) {
string sourceFileName = _virtualPathProvider.MapPath(GetAssemblyPath(extension));
// Copy the assembly if it doesn't exist or if it is older than the source file.
bool copyAssembly =
!_assemblyProbingFolder.AssemblyExists(extension.Id) ||
File.GetLastWriteTimeUtc(sourceFileName) > _assemblyProbingFolder.GetAssemblyDateTimeUtc(extension.Id);
if (copyAssembly) {
ctx.CopyActions.Add(() => _assemblyProbingFolder.StoreAssembly(extension.Id, sourceFileName));
// We need to restart the appDomain if the assembly is loaded
if (_hostEnvironment.IsAssemblyLoaded(extension.Id)) {
Logger.Information("ExtensionRemoved: Module \"{0}\" is activated with newer file and its assembly is loaded, forcing AppDomain restart", extension.Id);
ctx.RestartAppDomain = true;
}
}
}
public override void ExtensionDeactivated(ExtensionLoadingContext ctx, ExtensionDescriptor extension) {
if (_assemblyProbingFolder.AssemblyExists(extension.Id)) {
ctx.DeleteActions.Add(
() => {
Logger.Information("ExtensionDeactivated: Deleting assembly \"{0}\" from probing directory", extension.Id);
_assemblyProbingFolder.DeleteAssembly(extension.Id);
});
// We need to restart the appDomain if the assembly is loaded
if (_hostEnvironment.IsAssemblyLoaded(extension.Id)) {
Logger.Information("ExtensionDeactivated: Module \"{0}\" is deactivated and its assembly is loaded, forcing AppDomain restart", extension.Id);
ctx.RestartAppDomain = true;
}
}
}
public override void ReferenceActivated(ExtensionLoadingContext context, ExtensionReferenceProbeEntry referenceEntry) {
if (string.IsNullOrEmpty(referenceEntry.VirtualPath))
return;
string sourceFileName = _virtualPathProvider.MapPath(referenceEntry.VirtualPath);
// Copy the assembly if it doesn't exist or if it is older than the source file.
bool copyAssembly =
!_assemblyProbingFolder.AssemblyExists(referenceEntry.Name) ||
File.GetLastWriteTimeUtc(sourceFileName) > _assemblyProbingFolder.GetAssemblyDateTimeUtc(referenceEntry.Name);
if (copyAssembly) {
context.CopyActions.Add(() => _assemblyProbingFolder.StoreAssembly(referenceEntry.Name, sourceFileName));
// We need to restart the appDomain if the assembly is loaded
if (_hostEnvironment.IsAssemblyLoaded(referenceEntry.Name)) {
Logger.Information("ReferenceActivated: Reference \"{0}\" is activated with newer file and its assembly is loaded, forcing AppDomain restart", referenceEntry.Name);
context.RestartAppDomain = true;
}
}
}
public override void Monitor(ExtensionDescriptor descriptor, Action<IVolatileToken> monitor) {
if (Disabled)
return;
// If the assembly exists, monitor it
string assemblyPath = GetAssemblyPath(descriptor);
if (assemblyPath != null) {
Logger.Debug("Monitoring virtual path \"{0}\"", assemblyPath);
monitor(_virtualPathMonitor.WhenPathChanges(assemblyPath));
return;
}
// If the assembly doesn't exist, we monitor the containing "bin" folder, as the assembly
// may exist later if it is recompiled in Visual Studio for example, and we need to
// detect that as a change of configuration.
var assemblyDirectory = _virtualPathProvider.Combine(descriptor.Location, descriptor.Id, "bin");
if (_virtualPathProvider.DirectoryExists(assemblyDirectory)) {
Logger.Debug("Monitoring virtual path \"{0}\"", assemblyDirectory);
monitor(_virtualPathMonitor.WhenPathChanges(assemblyDirectory));
}
}
public override IEnumerable<ExtensionReferenceProbeEntry> ProbeReferences(ExtensionDescriptor descriptor) {
if (Disabled)
return Enumerable.Empty<ExtensionReferenceProbeEntry>();
Logger.Information("Probing references for module '{0}'", descriptor.Id);
var assemblyPath = GetAssemblyPath(descriptor);
if (assemblyPath == null)
return Enumerable.Empty<ExtensionReferenceProbeEntry>();
var result = _virtualPathProvider
.ListFiles(_virtualPathProvider.GetDirectoryName(assemblyPath))
.Where(s => StringComparer.OrdinalIgnoreCase.Equals(Path.GetExtension(s), ".dll"))
.Where(s => !StringComparer.OrdinalIgnoreCase.Equals(Path.GetFileNameWithoutExtension(s), descriptor.Id))
.Select(path => new ExtensionReferenceProbeEntry {
Descriptor = descriptor,
Loader = this,
Name = Path.GetFileNameWithoutExtension(path),
VirtualPath = path
} )
.ToList();
Logger.Information("Done probing references for module '{0}'", descriptor.Id);
return result;
}
public override bool IsCompatibleWithModuleReferences(ExtensionDescriptor extension, IEnumerable<ExtensionProbeEntry> references) {
// A pre-compiled module is _not_ compatible with a dynamically loaded module
// because a pre-compiled module usually references a pre-compiled assembly binary
// which will have a different identity (i.e. name) from the dynamic module.
bool result = references.All(r => r.Loader.GetType() != typeof (DynamicExtensionLoader));
if (!result) {
Logger.Information("Extension \"{0}\" will not be loaded as pre-compiled extension because one or more referenced extension is dynamically compiled", extension.Id);
}
return result;
}
public override ExtensionProbeEntry Probe(ExtensionDescriptor descriptor) {
if (Disabled)
return null;
Logger.Information("Probing for module '{0}'", descriptor.Id);
var assemblyPath = GetAssemblyPath(descriptor);
if (assemblyPath == null)
return null;
var result = new ExtensionProbeEntry {
Descriptor = descriptor,
Loader = this,
VirtualPath = assemblyPath,
VirtualPathDependencies = new[] { assemblyPath },
};
Logger.Information("Done probing for module '{0}'", descriptor.Id);
return result;
}
public override Assembly LoadReference(DependencyReferenceDescriptor reference) {
if (Disabled)
return null;
Logger.Information("Loading reference '{0}'", reference.Name);
var result = _assemblyProbingFolder.LoadAssembly(reference.Name);
Logger.Information("Done loading reference '{0}'", reference.Name);
return result;
}
protected override ExtensionEntry LoadWorker(ExtensionDescriptor descriptor) {
if (Disabled)
return null;
Logger.Information("Start loading pre-compiled extension \"{0}\"", descriptor.Name);
var assembly = _assemblyProbingFolder.LoadAssembly(descriptor.Id);
if (assembly == null)
return null;
Logger.Information("Done loading pre-compiled extension \"{0}\": assembly name=\"{1}\"", descriptor.Name, assembly.FullName);
return new ExtensionEntry {
Descriptor = descriptor,
Assembly = assembly,
ExportedTypes = assembly.GetExportedTypes()
};
}
public string GetAssemblyPath(ExtensionDescriptor descriptor) {
var assemblyPath = _virtualPathProvider.Combine(descriptor.Location, descriptor.Id, "bin",
descriptor.Id + ".dll");
if (!_virtualPathProvider.FileExists(assemblyPath))
return null;
return assemblyPath;
}
}
}
| |
using Microsoft.VisualStudio.Services.Agent.Util;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.VisualStudio.Services.Agent
{
[ServiceLocator(Default = typeof(ProcessInvoker))]
public interface IProcessInvoker : IDisposable, IAgentService
{
event EventHandler<ProcessDataReceivedEventArgs> OutputDataReceived;
event EventHandler<ProcessDataReceivedEventArgs> ErrorDataReceived;
Task<int> ExecuteAsync(
string workingDirectory,
string fileName,
string arguments,
IDictionary<string, string> environment,
CancellationToken cancellationToken);
Task<int> ExecuteAsync(
string workingDirectory,
string fileName,
string arguments,
IDictionary<string, string> environment,
bool requireExitCodeZero,
CancellationToken cancellationToken);
Task<int> ExecuteAsync(
string workingDirectory,
string fileName,
string arguments,
IDictionary<string, string> environment,
bool requireExitCodeZero,
Encoding outputEncoding,
CancellationToken cancellationToken);
Task<int> ExecuteAsync(
string workingDirectory,
string fileName,
string arguments,
IDictionary<string, string> environment,
bool requireExitCodeZero,
Encoding outputEncoding,
bool killProcessOnCancel,
CancellationToken cancellationToken);
}
// The implementation of the process invoker does not hook up DataReceivedEvent and ErrorReceivedEvent of Process,
// instead, we read both STDOUT and STDERR stream manually on seperate thread.
// The reason is we find a huge perf issue about process STDOUT/STDERR with those events.
//
// Missing functionalities:
// 1. Cancel/Kill process tree
// 2. Make sure STDOUT and STDERR not process out of order
public sealed class ProcessInvoker : AgentService, IProcessInvoker
{
private Process _proc;
private Stopwatch _stopWatch;
private int _asyncStreamReaderCount = 0;
private bool _waitingOnStreams = false;
private readonly AsyncManualResetEvent _outputProcessEvent = new AsyncManualResetEvent();
private readonly TaskCompletionSource<bool> _processExitedCompletionSource = new TaskCompletionSource<bool>();
private readonly ConcurrentQueue<string> _errorData = new ConcurrentQueue<string>();
private readonly ConcurrentQueue<string> _outputData = new ConcurrentQueue<string>();
private readonly TimeSpan _sigintTimeout = TimeSpan.FromSeconds(10);
private readonly TimeSpan _sigtermTimeout = TimeSpan.FromSeconds(5);
public event EventHandler<ProcessDataReceivedEventArgs> OutputDataReceived;
public event EventHandler<ProcessDataReceivedEventArgs> ErrorDataReceived;
public Task<int> ExecuteAsync(
string workingDirectory,
string fileName,
string arguments,
IDictionary<string, string> environment,
CancellationToken cancellationToken)
{
return ExecuteAsync(
workingDirectory: workingDirectory,
fileName: fileName,
arguments: arguments,
environment: environment,
requireExitCodeZero: false,
cancellationToken: cancellationToken);
}
public Task<int> ExecuteAsync(
string workingDirectory,
string fileName,
string arguments,
IDictionary<string, string> environment,
bool requireExitCodeZero,
CancellationToken cancellationToken)
{
return ExecuteAsync(
workingDirectory: workingDirectory,
fileName: fileName,
arguments: arguments,
environment: environment,
requireExitCodeZero: requireExitCodeZero,
outputEncoding: null,
cancellationToken: cancellationToken);
}
public Task<int> ExecuteAsync(
string workingDirectory,
string fileName,
string arguments,
IDictionary<string, string> environment,
bool requireExitCodeZero,
Encoding outputEncoding,
CancellationToken cancellationToken)
{
return ExecuteAsync(
workingDirectory: workingDirectory,
fileName: fileName,
arguments: arguments,
environment: environment,
requireExitCodeZero: requireExitCodeZero,
outputEncoding: outputEncoding,
killProcessOnCancel: false,
cancellationToken: cancellationToken);
}
public async Task<int> ExecuteAsync(
string workingDirectory,
string fileName,
string arguments,
IDictionary<string, string> environment,
bool requireExitCodeZero,
Encoding outputEncoding,
bool killProcessOnCancel,
CancellationToken cancellationToken)
{
ArgUtil.Null(_proc, nameof(_proc));
ArgUtil.NotNullOrEmpty(fileName, nameof(fileName));
Trace.Info("Starting process:");
Trace.Info($" File name: '{fileName}'");
Trace.Info($" Arguments: '{arguments}'");
Trace.Info($" Working directory: '{workingDirectory}'");
Trace.Info($" Require exit code zero: '{requireExitCodeZero}'");
Trace.Info($" Encoding web name: {outputEncoding?.WebName} ; code page: '{outputEncoding?.CodePage}'");
Trace.Info($" Force kill process on cancellation: '{killProcessOnCancel}'");
_proc = new Process();
_proc.StartInfo.FileName = fileName;
_proc.StartInfo.Arguments = arguments;
_proc.StartInfo.WorkingDirectory = workingDirectory;
_proc.StartInfo.UseShellExecute = false;
_proc.StartInfo.CreateNoWindow = true;
_proc.StartInfo.RedirectStandardInput = true;
_proc.StartInfo.RedirectStandardError = true;
_proc.StartInfo.RedirectStandardOutput = true;
// Ensure we process STDERR even the process exit event happen before we start read STDERR stream.
if (_proc.StartInfo.RedirectStandardError)
{
Interlocked.Increment(ref _asyncStreamReaderCount);
}
// Ensure we process STDOUT even the process exit event happen before we start read STDOUT stream.
if (_proc.StartInfo.RedirectStandardOutput)
{
Interlocked.Increment(ref _asyncStreamReaderCount);
}
#if OS_WINDOWS
// If StandardErrorEncoding or StandardOutputEncoding is not specified the on the
// ProcessStartInfo object, then .NET PInvokes to resolve the default console output
// code page:
// [DllImport("api-ms-win-core-console-l1-1-0.dll", SetLastError = true)]
// public extern static uint GetConsoleOutputCP();
StringUtil.EnsureRegisterEncodings();
#endif
if (outputEncoding != null)
{
_proc.StartInfo.StandardErrorEncoding = outputEncoding;
_proc.StartInfo.StandardOutputEncoding = outputEncoding;
}
// Copy the environment variables.
if (environment != null && environment.Count > 0)
{
foreach (KeyValuePair<string, string> kvp in environment)
{
_proc.StartInfo.Environment[kvp.Key] = kvp.Value;
}
}
// Set the TF_BUILD env variable.
_proc.StartInfo.Environment[Constants.TFBuild] = "True";
// Hook up the events.
_proc.EnableRaisingEvents = true;
_proc.Exited += ProcessExitedHandler;
// Start the process.
_stopWatch = Stopwatch.StartNew();
_proc.Start();
// Close the input stream. This is done to prevent commands from blocking the build waiting for input from the user.
if (_proc.StartInfo.RedirectStandardInput)
{
_proc.StandardInput.Dispose();
}
// Start the standard error notifications, if appropriate.
if (_proc.StartInfo.RedirectStandardError)
{
StartReadStream(_proc.StandardError, _errorData);
}
// Start the standard output notifications, if appropriate.
if (_proc.StartInfo.RedirectStandardOutput)
{
StartReadStream(_proc.StandardOutput, _outputData);
}
using (var registration = cancellationToken.Register(async () => await CancelAndKillProcessTree(killProcessOnCancel)))
{
Trace.Info($"Process started with process id {_proc.Id}, waiting for process exit.");
while (true)
{
Task outputSignal = _outputProcessEvent.WaitAsync();
var signaled = await Task.WhenAny(outputSignal, _processExitedCompletionSource.Task);
if (signaled == outputSignal)
{
ProcessOutput();
}
else
{
_stopWatch.Stop();
break;
}
}
// Just in case there was some pending output when the process shut down go ahead and check the
// data buffers one last time before returning
ProcessOutput();
Trace.Info($"Finished process with exit code {_proc.ExitCode}, and elapsed time {_stopWatch.Elapsed}.");
}
cancellationToken.ThrowIfCancellationRequested();
// Wait for process to finish.
if (_proc.ExitCode != 0 && requireExitCodeZero)
{
throw new ProcessExitCodeException(exitCode: _proc.ExitCode, fileName: fileName, arguments: arguments);
}
return _proc.ExitCode;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (disposing)
{
if (_proc != null)
{
_proc.Dispose();
_proc = null;
}
}
}
private void ProcessOutput()
{
List<string> errorData = new List<string>();
List<string> outputData = new List<string>();
string errorLine;
while (_errorData.TryDequeue(out errorLine))
{
errorData.Add(errorLine);
}
string outputLine;
while (_outputData.TryDequeue(out outputLine))
{
outputData.Add(outputLine);
}
_outputProcessEvent.Reset();
// Write the error lines.
if (errorData != null && this.ErrorDataReceived != null)
{
foreach (string line in errorData)
{
if (line != null)
{
this.ErrorDataReceived(this, new ProcessDataReceivedEventArgs(line));
}
}
}
// Process the output lines.
if (outputData != null && this.OutputDataReceived != null)
{
foreach (string line in outputData)
{
if (line != null)
{
// The line is output from the process that was invoked.
this.OutputDataReceived(this, new ProcessDataReceivedEventArgs(line));
}
}
}
}
private async Task CancelAndKillProcessTree(bool killProcessOnCancel)
{
ArgUtil.NotNull(_proc, nameof(_proc));
if (!killProcessOnCancel)
{
bool sigint_succeed = await SendSIGINT(_sigintTimeout);
if (sigint_succeed)
{
Trace.Info("Process cancelled successfully through Ctrl+C/SIGINT.");
return;
}
bool sigterm_succeed = await SendSIGTERM(_sigtermTimeout);
if (sigterm_succeed)
{
Trace.Info("Process terminate successfully through Ctrl+Break/SIGTERM.");
return;
}
}
Trace.Info("Kill entire process tree since both cancel and terminate signal has been ignored by the target process.");
KillProcessTree();
}
private async Task<bool> SendSIGINT(TimeSpan timeout)
{
#if OS_WINDOWS
return await SendCtrlSignal(ConsoleCtrlEvent.CTRL_C, timeout);
#else
return await SendSignal(Signals.SIGINT, timeout);
#endif
}
private async Task<bool> SendSIGTERM(TimeSpan timeout)
{
#if OS_WINDOWS
return await SendCtrlSignal(ConsoleCtrlEvent.CTRL_BREAK, timeout);
#else
return await SendSignal(Signals.SIGTERM, timeout);
#endif
}
private void ProcessExitedHandler(object sender, EventArgs e)
{
if ((_proc.StartInfo.RedirectStandardError || _proc.StartInfo.RedirectStandardOutput) && _asyncStreamReaderCount != 0)
{
_waitingOnStreams = true;
Task.Run(async () =>
{
// Wait 5 seconds and then Cancel/Kill process tree
await Task.Delay(TimeSpan.FromSeconds(5));
KillProcessTree();
_processExitedCompletionSource.TrySetResult(true);
});
}
else
{
_processExitedCompletionSource.TrySetResult(true);
}
}
private void StartReadStream(StreamReader reader, ConcurrentQueue<string> dataBuffer)
{
Task.Run(() =>
{
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
if (line != null)
{
dataBuffer.Enqueue(line);
_outputProcessEvent.Set();
}
}
if (Interlocked.Decrement(ref _asyncStreamReaderCount) == 0 && _waitingOnStreams)
{
_processExitedCompletionSource.TrySetResult(true);
}
});
}
private void KillProcessTree()
{
#if OS_WINDOWS
WindowsKillProcessTree();
#else
NixKillProcessTree();
#endif
}
#if OS_WINDOWS
private async Task<bool> SendCtrlSignal(ConsoleCtrlEvent signal, TimeSpan timeout)
{
Trace.Info($"Sending {signal} to process {_proc.Id}.");
ConsoleCtrlDelegate ctrlEventHandler = new ConsoleCtrlDelegate(ConsoleCtrlHandler);
try
{
if (!FreeConsole())
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
if (!AttachConsole(_proc.Id))
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
if (!SetConsoleCtrlHandler(ctrlEventHandler, true))
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
if (!GenerateConsoleCtrlEvent(signal, 0))
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
Trace.Info($"Successfully send {signal} to process {_proc.Id}.");
Trace.Info($"Waiting for process exit or {timeout.TotalSeconds} seconds after {signal} signal fired.");
var completedTask = await Task.WhenAny(Task.Delay(timeout), _processExitedCompletionSource.Task);
if (completedTask == _processExitedCompletionSource.Task)
{
Trace.Info("Process exit successfully.");
return true;
}
else
{
Trace.Info($"Process did not honor {signal} signal within {timeout.TotalSeconds} seconds.");
return false;
}
}
catch (Exception ex)
{
Trace.Info($"{signal} signal doesn't fire successfully.");
Trace.Error($"Catch exception during send {signal} event to process {_proc.Id}");
Trace.Error(ex);
return false;
}
finally
{
FreeConsole();
SetConsoleCtrlHandler(ctrlEventHandler, false);
}
}
private bool ConsoleCtrlHandler(ConsoleCtrlEvent ctrlType)
{
switch (ctrlType)
{
case ConsoleCtrlEvent.CTRL_C:
Trace.Info($"Ignore Ctrl+C to current process.");
// We return True, so the default Ctrl handler will not take action.
return true;
case ConsoleCtrlEvent.CTRL_BREAK:
Trace.Info($"Ignore Ctrl+Break to current process.");
// We return True, so the default Ctrl handler will not take action.
return true;
}
// If the function handles the control signal, it should return TRUE.
// If it returns FALSE, the next handler function in the list of handlers for this process is used.
return false;
}
private void WindowsKillProcessTree()
{
Dictionary<int, int> processRelationship = new Dictionary<int, int>();
Trace.Info($"Scan all processes to find relationship between all processes.");
foreach (Process proc in Process.GetProcesses())
{
try
{
if (!proc.SafeHandle.IsInvalid)
{
PROCESS_BASIC_INFORMATION pbi = new PROCESS_BASIC_INFORMATION();
int returnLength = 0;
int queryResult = NtQueryInformationProcess(proc.SafeHandle.DangerousGetHandle(), PROCESSINFOCLASS.ProcessBasicInformation, ref pbi, pbi.Size, ref returnLength);
if (queryResult == 0) // == 0 is OK
{
Trace.Verbose($"Process: {proc.Id} is child process of {pbi.InheritedFromUniqueProcessId}.");
processRelationship[proc.Id] = (int)pbi.InheritedFromUniqueProcessId;
}
else
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
}
catch (Exception ex)
{
// Ignore all exceptions, since KillProcessTree is best effort.
Trace.Verbose("Ignore any catched exception during detecting process relationship.");
Trace.Verbose(ex.ToString());
}
}
Trace.Verbose($"Start killing process tree of process '{_proc.Id}'.");
Stack<ProcessTerminationInfo> processesNeedtoKill = new Stack<ProcessTerminationInfo>();
processesNeedtoKill.Push(new ProcessTerminationInfo(_proc.Id, false));
while (processesNeedtoKill.Count() > 0)
{
ProcessTerminationInfo procInfo = processesNeedtoKill.Pop();
List<int> childProcessesIds = new List<int>();
if (!procInfo.ChildPidExpanded)
{
Trace.Info($"Find all child processes of process '{procInfo.Pid}'.");
childProcessesIds = processRelationship.Where(p => p.Value == procInfo.Pid).Select(k => k.Key).ToList();
}
if (childProcessesIds.Count > 0)
{
Trace.Info($"Need kill all child processes trees before kill process '{procInfo.Pid}'.");
processesNeedtoKill.Push(new ProcessTerminationInfo(procInfo.Pid, true));
foreach (var childPid in childProcessesIds)
{
Trace.Info($"Child process '{childPid}' needs be killed first.");
processesNeedtoKill.Push(new ProcessTerminationInfo(childPid, false));
}
}
else
{
Trace.Info($"Kill process '{procInfo.Pid}'.");
try
{
Process leafProcess = Process.GetProcessById(procInfo.Pid);
try
{
leafProcess.Kill();
}
catch (InvalidOperationException ex)
{
// The process has already exited
Trace.Error("Ignore InvalidOperationException during Process.Kill().");
Trace.Error(ex);
}
catch (Win32Exception ex) when (ex.NativeErrorCode == 5)
{
// The associated process could not be terminated
// The process is terminating
// NativeErrorCode 5 means Access Denied
Trace.Error("Ignore Win32Exception with NativeErrorCode 5 during Process.Kill().");
Trace.Error(ex);
}
catch (Exception ex)
{
// Ignore any additional exception
Trace.Error("Ignore additional exceptions during Process.Kill().");
Trace.Error(ex);
}
}
catch (ArgumentException ex)
{
// process already gone, nothing needs killed.
Trace.Error("Ignore ArgumentException during Process.GetProcessById().");
Trace.Error(ex);
}
catch (Exception ex)
{
// Ignore any additional exception
Trace.Error("Ignore additional exceptions during Process.GetProcessById().");
Trace.Error(ex);
}
}
}
}
private class ProcessTerminationInfo
{
public ProcessTerminationInfo(int pid, bool expanded)
{
Pid = pid;
ChildPidExpanded = expanded;
}
public int Pid { get; }
public bool ChildPidExpanded { get; }
}
private enum ConsoleCtrlEvent
{
CTRL_C = 0,
CTRL_BREAK = 1
}
private enum PROCESSINFOCLASS : int
{
ProcessBasicInformation = 0
};
[StructLayout(LayoutKind.Sequential)]
private struct PROCESS_BASIC_INFORMATION
{
public long ExitStatus;
public long PebBaseAddress;
public long AffinityMask;
public long BasePriority;
public long UniqueProcessId;
public long InheritedFromUniqueProcessId;
public uint Size
{
get { return (6 * sizeof(long)); }
}
};
[DllImport("ntdll.dll", SetLastError = true)]
private static extern int NtQueryInformationProcess(IntPtr processHandle, PROCESSINFOCLASS processInformationClass, ref PROCESS_BASIC_INFORMATION processInformation, uint processInformationLength, ref int returnLength);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool GenerateConsoleCtrlEvent(ConsoleCtrlEvent sigevent, int dwProcessGroupId);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool FreeConsole();
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool AttachConsole(int dwProcessId);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool SetConsoleCtrlHandler(ConsoleCtrlDelegate HandlerRoutine, bool Add);
// Delegate type to be used as the Handler Routine for SetConsoleCtrlHandler
private delegate Boolean ConsoleCtrlDelegate(ConsoleCtrlEvent CtrlType);
#else
private async Task<bool> SendSignal(Signals signal, TimeSpan timeout)
{
Trace.Info($"Sending {signal} to process {_proc.Id}.");
int errorCode = kill(_proc.Id, (int)signal);
if (errorCode != 0)
{
Trace.Info($"{signal} signal doesn't fire successfully.");
Trace.Error($"Error code: {errorCode}.");
return false;
}
Trace.Info($"Successfully send {signal} to process {_proc.Id}.");
Trace.Info($"Waiting for process exit or {timeout.TotalSeconds} seconds after {signal} signal fired.");
var completedTask = await Task.WhenAny(Task.Delay(timeout), _processExitedCompletionSource.Task);
if (completedTask == _processExitedCompletionSource.Task)
{
Trace.Info("Process exit successfully.");
return true;
}
else
{
Trace.Info($"Process did not honor {signal} signal within {timeout.TotalSeconds} seconds.");
return false;
}
}
private void NixKillProcessTree()
{
try
{
if (!_proc.HasExited)
{
_proc.Kill();
}
}
catch (InvalidOperationException ex)
{
Trace.Error("Ignore InvalidOperationException during Process.Kill().");
Trace.Error(ex);
}
}
private enum Signals : int
{
SIGINT = 2,
SIGTERM = 15
}
[DllImport("libc", SetLastError = true)]
private static extern int kill(int pid, int sig);
#endif
}
public sealed class ProcessExitCodeException : Exception
{
public int ExitCode { get; private set; }
public ProcessExitCodeException(int exitCode, string fileName, string arguments)
: base(StringUtil.Loc("ProcessExitCode", exitCode, fileName, arguments))
{
ExitCode = exitCode;
}
}
public sealed class ProcessDataReceivedEventArgs : EventArgs
{
public ProcessDataReceivedEventArgs(string data)
{
Data = data;
}
public string Data { get; private set; }
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Orleans.CodeGenerator.Compatibility;
using Orleans.CodeGenerator.Model;
using Orleans.CodeGenerator.Utilities;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace Orleans.CodeGenerator.Generators
{
/// <summary>
/// Generates GrainReference implementations for grains.
/// </summary>
internal static class GrainReferenceGenerator
{
/// <summary>
/// Returns the name of the generated class for the provided type.
/// </summary>
internal static string GetGeneratedClassName(INamedTypeSymbol type)
{
return CodeGenerator.ToolName + type.GetSuitableClassName() + "Reference";
}
/// <summary>
/// Generates the class for the provided grain types.
/// </summary>
internal static TypeDeclarationSyntax GenerateClass(WellKnownTypes wellKnownTypes, GrainInterfaceDescription description)
{
var generatedTypeName = description.ReferenceTypeName;
var grainType = description.Type;
var genericTypes = grainType.GetHierarchyTypeParameters()
.Select(_ => TypeParameter(_.ToString()))
.ToArray();
// Create the special marker attribute.
var grainTypeArgument = TypeOfExpression(grainType.WithoutTypeParameters().ToTypeSyntax());
var attributes = AttributeList()
.AddAttributes(
GeneratedCodeAttributeGenerator.GetGeneratedCodeAttributeSyntax(wellKnownTypes),
Attribute(wellKnownTypes.SerializableAttribute.ToNameSyntax()),
Attribute(wellKnownTypes.ExcludeFromCodeCoverageAttribute.ToNameSyntax()),
Attribute(wellKnownTypes.GrainReferenceAttribute.ToNameSyntax())
.AddArgumentListArguments(AttributeArgument(grainTypeArgument)));
var classDeclaration =
ClassDeclaration(generatedTypeName)
.AddModifiers(Token(SyntaxKind.InternalKeyword))
.AddBaseListTypes(
SimpleBaseType(wellKnownTypes.GrainReference.ToTypeSyntax()),
SimpleBaseType(grainType.ToTypeSyntax()))
.AddConstraintClauses(grainType.GetTypeConstraintSyntax())
.AddMembers(GenerateConstructors(wellKnownTypes, generatedTypeName))
.AddMembers(
GrainInterfaceCommon.GenerateInterfaceIdProperty(wellKnownTypes, description).AddModifiers(Token(SyntaxKind.OverrideKeyword)),
GrainInterfaceCommon.GenerateInterfaceVersionProperty(wellKnownTypes, description).AddModifiers(Token(SyntaxKind.OverrideKeyword)),
GenerateInterfaceNameProperty(wellKnownTypes, description),
GenerateIsCompatibleMethod(wellKnownTypes, description),
GenerateGetMethodNameMethod(wellKnownTypes, description))
.AddMembers(GenerateInvokeMethods(wellKnownTypes, description))
.AddAttributeLists(attributes);
if (genericTypes.Length > 0)
{
classDeclaration = classDeclaration.AddTypeParameterListParameters(genericTypes);
}
return classDeclaration;
}
/// <summary>
/// Generates constructors.
/// </summary>
private static MemberDeclarationSyntax[] GenerateConstructors(WellKnownTypes wellKnownTypes, string className)
{
var baseConstructors =
wellKnownTypes.GrainReference.Constructors.Where(c => c.DeclaredAccessibility != Accessibility.Private);
var constructors = new List<MemberDeclarationSyntax>();
foreach (var baseConstructor in baseConstructors)
{
var args = baseConstructor.Parameters
.Select(arg => Argument(arg.Name.ToIdentifierName()))
.ToArray();
var declaration =
baseConstructor.GetConstructorDeclarationSyntax(className)
.WithInitializer(
ConstructorInitializer(SyntaxKind.BaseConstructorInitializer)
.AddArgumentListArguments(args))
.AddBodyStatements();
constructors.Add(declaration);
}
return constructors.ToArray();
}
/// <summary>
/// Generates invoker methods.
/// </summary>
private static MemberDeclarationSyntax[] GenerateInvokeMethods(WellKnownTypes wellKnownTypes, GrainInterfaceDescription description)
{
var baseReference = BaseExpression();
var methods = description.Methods;
var members = new List<MemberDeclarationSyntax>();
foreach (var methodDescription in methods)
{
var method = methodDescription.Method;
var methodIdArgument = Argument(methodDescription.MethodId.ToHexLiteral());
// Construct a new object array from all method arguments.
var parameters = method.Parameters;
var body = new List<StatementSyntax>();
foreach (var parameter in parameters)
{
if (parameter.Type.HasInterface(wellKnownTypes.IGrainObserver))
{
body.Add(
ExpressionStatement(
InvocationExpression(wellKnownTypes.GrainFactoryBase.ToDisplayString().ToIdentifierName().Member("CheckGrainObserverParamInternal"))
.AddArgumentListArguments(Argument(parameter.Name.ToIdentifierName()))));
}
}
// Get the parameters argument value.
var objectArrayType = wellKnownTypes.Object.ToTypeSyntax().GetArrayTypeSyntax();
ExpressionSyntax args;
if (method.IsGenericMethod)
{
// Create an arguments array which includes the method's type parameters followed by the method's parameter list.
var allParameters = new List<ExpressionSyntax>();
foreach (var typeParameter in method.TypeParameters)
{
allParameters.Add(TypeOfExpression(typeParameter.ToTypeSyntax()));
}
allParameters.AddRange(parameters.Select(GetParameterForInvocation));
args =
ArrayCreationExpression(objectArrayType)
.WithInitializer(
InitializerExpression(SyntaxKind.ArrayInitializerExpression)
.AddExpressions(allParameters.ToArray()));
}
else if (parameters.Length == 0)
{
args = LiteralExpression(SyntaxKind.NullLiteralExpression);
}
else
{
args =
ArrayCreationExpression(objectArrayType)
.WithInitializer(
InitializerExpression(SyntaxKind.ArrayInitializerExpression)
.AddExpressions(parameters.Select(GetParameterForInvocation).ToArray()));
}
var options = GetInvokeOptions(wellKnownTypes, method);
// Construct the invocation call.
bool asyncMethod;
var isOneWayTask = method.HasAttribute(wellKnownTypes.OneWayAttribute);
if (method.ReturnsVoid || isOneWayTask)
{
// One-way methods are never marked async.
asyncMethod = false;
var invocation = InvocationExpression(baseReference.Member("InvokeOneWayMethod"))
.AddArgumentListArguments(methodIdArgument)
.AddArgumentListArguments(Argument(args));
if (options != null)
{
invocation = invocation.AddArgumentListArguments(options);
}
body.Add(ExpressionStatement(invocation));
if (isOneWayTask)
{
if (!wellKnownTypes.Task.Equals(method.ReturnType))
{
throw new CodeGenerationException(
$"Method {method} is marked with [{wellKnownTypes.OneWayAttribute.Name}], " +
$"but has a return type which is not assignable from {typeof(Task)}");
}
var done = wellKnownTypes.Task.ToNameSyntax().Member((object _) => Task.CompletedTask);
body.Add(ReturnStatement(done));
}
}
else if (method.ReturnType is INamedTypeSymbol methodReturnType)
{
// If the method doesn't return a Task type (eg, it returns ValueTask<T>), then we must make an async method and await the invocation result.
var isTaskMethod = wellKnownTypes.Task.Equals(methodReturnType)
|| methodReturnType.IsGenericType && wellKnownTypes.Task_1.Equals(methodReturnType.ConstructedFrom);
asyncMethod = !isTaskMethod;
var returnType = methodReturnType.IsGenericType
? methodReturnType.TypeArguments[0]
: wellKnownTypes.Object;
var invokeMethodAsync = "InvokeMethodAsync".ToGenericName().AddTypeArgumentListArguments(returnType.ToTypeSyntax());
var invocation =
InvocationExpression(MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression,
baseReference,
invokeMethodAsync))
.AddArgumentListArguments(methodIdArgument)
.AddArgumentListArguments(Argument(args));
if (options != null)
{
invocation = invocation.AddArgumentListArguments(options);
}
var methodResult = asyncMethod ? AwaitExpression(invocation) : (ExpressionSyntax)invocation;
body.Add(ReturnStatement(methodResult));
}
else throw new NotSupportedException($"Method {method} has unsupported return type, {method.ReturnType}.");
var methodDeclaration = method.GetDeclarationSyntax()
.WithModifiers(TokenList())
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(method.ContainingType.ToNameSyntax()))
.AddBodyStatements(body.ToArray())
// Since explicit implementation is used, constraints must not be specified.
.WithConstraintClauses(new SyntaxList<TypeParameterConstraintClauseSyntax>());
if (asyncMethod) methodDeclaration = methodDeclaration.AddModifiers(Token(SyntaxKind.AsyncKeyword));
members.Add(methodDeclaration);
}
return members.ToArray();
ExpressionSyntax GetParameterForInvocation(IParameterSymbol arg, int argIndex)
{
var argIdentifier = GetParameterName(arg, argIndex).ToIdentifierName();
// Addressable arguments must be converted to references before passing.
if (arg.Type.HasInterface(wellKnownTypes.IAddressable)
&& arg.Type.TypeKind == TypeKind.Interface)
{
return
ConditionalExpression(
BinaryExpression(SyntaxKind.IsExpression, argIdentifier, wellKnownTypes.Grain.ToTypeSyntax()),
InvocationExpression(argIdentifier.Member("AsReference".ToGenericName().AddTypeArgumentListArguments(arg.Type.ToTypeSyntax()))),
argIdentifier);
}
return argIdentifier;
string GetParameterName(IParameterSymbol parameter, int index)
{
var argName = parameter.Name;
if (string.IsNullOrWhiteSpace(argName))
{
argName = string.Format(CultureInfo.InvariantCulture, "arg{0:G}", index);
}
return argName;
}
}
}
/// <summary>
/// Returns syntax for the options argument to GrainReference.InvokeMethodAsync{T} and GrainReference.InvokeOneWayMethod.
/// </summary>
private static ArgumentSyntax GetInvokeOptions(WellKnownTypes wellKnownTypes, IMethodSymbol method)
{
var options = new List<ExpressionSyntax>();
var imo = wellKnownTypes.InvokeMethodOptions.ToNameSyntax();
if (method.HasAttribute(wellKnownTypes.ReadOnlyAttribute))
{
options.Add(imo.Member("ReadOnly"));
}
if (method.HasAttribute(wellKnownTypes.UnorderedAttribute))
{
options.Add(imo.Member("Unordered"));
}
if (method.HasAttribute(wellKnownTypes.AlwaysInterleaveAttribute))
{
options.Add(imo.Member("AlwaysInterleave"));
}
if (method.GetAttribute(wellKnownTypes.TransactionAttribute, out var attr))
{
var enumType = wellKnownTypes.TransactionOption;
var txRequirement = (int)attr.ConstructorArguments.First().Value;
var values = enumType.GetMembers().OfType<IFieldSymbol>().ToList();
var mapping = values.ToDictionary(m => (int) m.ConstantValue, m => m.Name);
if (!mapping.TryGetValue(txRequirement, out var value))
{
throw new NotSupportedException($"Transaction requirement {txRequirement} on method {method} was not understood.");
}
switch (value)
{
case "Suppress":
options.Add(imo.Member("TransactionSuppress"));
break;
case "CreateOrJoin":
options.Add(imo.Member("TransactionCreateOrJoin"));
break;
case "Create":
options.Add(imo.Member("TransactionCreate"));
break;
case "Join":
options.Add(imo.Member("TransactionJoin"));
break;
case "Supported":
options.Add(imo.Member("TransactionSupported"));
break;
case "NotAllowed":
options.Add(imo.Member("TransactionNotAllowed"));
break;
default:
throw new NotSupportedException($"Transaction requirement {value} on method {method} was not understood.");
}
}
ExpressionSyntax allOptions;
if (options.Count <= 1)
{
allOptions = options.FirstOrDefault();
}
else
{
allOptions =
options.Aggregate((a, b) => BinaryExpression(SyntaxKind.BitwiseOrExpression, a, b));
}
if (allOptions == null)
{
return null;
}
return Argument(NameColon("options"), Token(SyntaxKind.None), allOptions);
}
private static MemberDeclarationSyntax GenerateIsCompatibleMethod(WellKnownTypes wellKnownTypes, GrainInterfaceDescription description)
{
var method = wellKnownTypes.GrainReference.Method("IsCompatible");
var interfaceIdParameter = method.Parameters[0].Name.ToIdentifierName();
var interfaceIds =
new HashSet<int>(
new[] { description.InterfaceId }.Concat(
description.Type.AllInterfaces.Where(wellKnownTypes.IsGrainInterface).Select(wellKnownTypes.GetTypeId)));
var returnValue = default(BinaryExpressionSyntax);
foreach (var interfaceId in interfaceIds)
{
var check = BinaryExpression(
SyntaxKind.EqualsExpression,
interfaceIdParameter,
interfaceId.ToHexLiteral());
// If this is the first check, assign it, otherwise OR this check with the previous checks.
returnValue = returnValue == null
? check
: BinaryExpression(SyntaxKind.LogicalOrExpression, returnValue, check);
}
return
method.GetDeclarationSyntax()
.AddModifiers(Token(SyntaxKind.OverrideKeyword))
.WithExpressionBody(ArrowExpressionClause(returnValue))
.WithSemicolonToken(Token(SyntaxKind.SemicolonToken));
}
private static MemberDeclarationSyntax GenerateInterfaceNameProperty(WellKnownTypes wellKnownTypes, GrainInterfaceDescription description)
{
var returnValue = description.Type.Name.ToLiteralExpression();
return
PropertyDeclaration(wellKnownTypes.String.ToTypeSyntax(), "InterfaceName")
.WithExpressionBody(ArrowExpressionClause(returnValue))
.AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.OverrideKeyword))
.WithSemicolonToken(Token(SyntaxKind.SemicolonToken));
}
private static MethodDeclarationSyntax GenerateGetMethodNameMethod(WellKnownTypes wellKnownTypes, GrainInterfaceDescription description)
{
var method = wellKnownTypes.GrainReference.Method("GetMethodName");
var methodDeclaration = method.GetDeclarationSyntax().AddModifiers(Token(SyntaxKind.OverrideKeyword));
var parameters = method.Parameters;
var interfaceIdArgument = parameters[0].Name.ToIdentifierName();
var methodIdArgument = parameters[1].Name.ToIdentifierName();
var callThrowMethodNotImplemented = InvocationExpression(IdentifierName("ThrowMethodNotImplemented"))
.WithArgumentList(ArgumentList(SeparatedList(new[]
{
Argument(interfaceIdArgument),
Argument(methodIdArgument)
})));
// This method is used directly after its declaration to create blocks for each interface id, comprising
// primarily of a nested switch statement for each of the methods in the given interface.
BlockSyntax ComposeInterfaceBlock(INamedTypeSymbol interfaceType, SwitchStatementSyntax methodSwitch)
{
return Block(methodSwitch.AddSections(SwitchSection()
.AddLabels(DefaultSwitchLabel())
.AddStatements(
ExpressionStatement(callThrowMethodNotImplemented),
ReturnStatement(LiteralExpression(SyntaxKind.NullLiteralExpression)))));
}
var interfaceCases = GrainInterfaceCommon.GenerateGrainInterfaceAndMethodSwitch(
wellKnownTypes,
description.Type,
methodIdArgument,
methodType => new StatementSyntax[] { ReturnStatement(methodType.Name.ToLiteralExpression()) },
ComposeInterfaceBlock);
// Generate the default case, which will throw a NotImplementedException.
var callThrowInterfaceNotImplemented = InvocationExpression(IdentifierName("ThrowInterfaceNotImplemented"))
.WithArgumentList(ArgumentList(SingletonSeparatedList(Argument(interfaceIdArgument))));
var defaultCase = SwitchSection()
.AddLabels(DefaultSwitchLabel())
.AddStatements(
ExpressionStatement(callThrowInterfaceNotImplemented),
ReturnStatement(LiteralExpression(SyntaxKind.NullLiteralExpression)));
var throwInterfaceNotImplemented = GrainInterfaceCommon.GenerateMethodNotImplementedFunction(wellKnownTypes);
var throwMethodNotImplemented = GrainInterfaceCommon.GenerateInterfaceNotImplementedFunction(wellKnownTypes);
var interfaceIdSwitch =
SwitchStatement(interfaceIdArgument).AddSections(interfaceCases.ToArray()).AddSections(defaultCase);
return methodDeclaration.AddBodyStatements(interfaceIdSwitch, throwInterfaceNotImplemented, throwMethodNotImplemented);
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Net;
using System.Text;
using Microsoft.PowerShell.Commands.Internal.Format;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// Class comment.
/// </summary>
[Cmdlet(VerbsData.ConvertTo, "Html", DefaultParameterSetName = "Page",
HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096595", RemotingCapability = RemotingCapability.None)]
public sealed
class ConvertToHtmlCommand : PSCmdlet
{
/// <summary>The incoming object</summary>
/// <value></value>
[Parameter(ValueFromPipeline = true)]
public PSObject InputObject
{
get
{
return _inputObject;
}
set
{
_inputObject = value;
}
}
private PSObject _inputObject;
/// <summary>
/// The list of properties to display.
/// These take the form of a PSPropertyExpression.
/// </summary>
/// <value></value>
[Parameter(Position = 0)]
public object[] Property
{
get
{
return _property;
}
set
{
_property = value;
}
}
private object[] _property;
/// <summary>
/// Text to go after the opening body tag and before the table.
/// </summary>
/// <value></value>
[Parameter(ParameterSetName = "Page", Position = 3)]
public string[] Body
{
get
{
return _body;
}
set
{
_body = value;
}
}
private string[] _body;
/// <summary>
/// Text to go into the head section of the html doc.
/// </summary>
/// <value></value>
[Parameter(ParameterSetName = "Page", Position = 1)]
public string[] Head
{
get
{
return _head;
}
set
{
_head = value;
}
}
private string[] _head;
/// <summary>
/// The string for the title tag
/// The title is also placed in the body of the document
/// before the table between h3 tags
/// If the -Head parameter is used, this parameter has no
/// effect.
/// </summary>
/// <value></value>
[Parameter(ParameterSetName = "Page", Position = 2)]
[ValidateNotNullOrEmpty]
public string Title
{
get
{
return _title;
}
set
{
_title = value;
}
}
private string _title = "HTML TABLE";
/// <summary>
/// This specifies whether the objects should
/// be rendered as an HTML TABLE or
/// HTML LIST.
/// </summary>
/// <value></value>
[Parameter]
[ValidateNotNullOrEmpty]
[ValidateSet("Table", "List")]
public string As
{
get
{
return _as;
}
set
{
_as = value;
}
}
private string _as = "Table";
/// <summary>
/// This specifies a full or partial URI
/// for the CSS information.
/// The HTML should reference the CSS file specified.
/// </summary>
[Parameter(ParameterSetName = "Page")]
[Alias("cu", "uri")]
[ValidateNotNullOrEmpty]
public Uri CssUri
{
get
{
return _cssuri;
}
set
{
_cssuri = value;
_cssuriSpecified = true;
}
}
private Uri _cssuri;
private bool _cssuriSpecified;
/// <summary>
/// When this switch is specified generate only the
/// HTML representation of the incoming object
/// without the HTML,HEAD,TITLE,BODY,etc tags.
/// </summary>
[Parameter(ParameterSetName = "Fragment")]
[ValidateNotNullOrEmpty]
public SwitchParameter Fragment
{
get
{
return _fragment;
}
set
{
_fragment = value;
}
}
private SwitchParameter _fragment;
/// <summary>
/// Specifies the text to include prior the closing body tag of the HTML output.
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] PostContent
{
get
{
return _postContent;
}
set
{
_postContent = value;
}
}
private string[] _postContent;
/// <summary>
/// Specifies the text to include after the body tag of the HTML output.
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] PreContent
{
get
{
return _preContent;
}
set
{
_preContent = value;
}
}
private string[] _preContent;
/// <summary>
/// Sets and Gets the meta property of the HTML head.
/// </summary>
/// <returns></returns>
[Parameter(ParameterSetName = "Page")]
[ValidateNotNullOrEmpty]
public Hashtable Meta
{
get
{
return _meta;
}
set
{
_meta = value;
_metaSpecified = true;
}
}
private Hashtable _meta;
private bool _metaSpecified = false;
/// <summary>
/// Specifies the charset encoding for the HTML document.
/// </summary>
[Parameter(ParameterSetName = "Page")]
[ValidateNotNullOrEmpty]
[ValidatePattern("^[A-Za-z0-9]\\w+\\S+[A-Za-z0-9]$")]
public string Charset
{
get
{
return _charset;
}
set
{
_charset = value;
_charsetSpecified = true;
}
}
private string _charset;
private bool _charsetSpecified = false;
/// <summary>
/// When this switch statement is specified,
/// it will change the DOCTYPE to XHTML Transitional DTD.
/// </summary>
/// <returns></returns>
[Parameter(ParameterSetName = "Page")]
[ValidateNotNullOrEmpty]
public SwitchParameter Transitional
{
get
{
return _transitional;
}
set
{
_transitional = true;
}
}
private bool _transitional = false;
/// <summary>
/// Definitions for hash table keys.
/// </summary>
internal static class ConvertHTMLParameterDefinitionKeys
{
internal const string LabelEntryKey = "label";
internal const string AlignmentEntryKey = "alignment";
internal const string WidthEntryKey = "width";
}
/// <summary>
/// This allows for @{e='foo';label='bar';alignment='center';width='20'}.
/// </summary>
internal class ConvertHTMLExpressionParameterDefinition : CommandParameterDefinition
{
protected override void SetEntries()
{
this.hashEntries.Add(new ExpressionEntryDefinition());
this.hashEntries.Add(new LabelEntryDefinition());
this.hashEntries.Add(new HashtableEntryDefinition(ConvertHTMLParameterDefinitionKeys.AlignmentEntryKey, new[] { typeof(string) }));
// Note: We accept "width" as either string or int.
this.hashEntries.Add(new HashtableEntryDefinition(ConvertHTMLParameterDefinitionKeys.WidthEntryKey, new[] { typeof(string), typeof(int) }));
}
}
/// <summary>
/// Create a list of MshParameter from properties.
/// </summary>
/// <param name="properties">Can be a string, ScriptBlock, or Hashtable.</param>
/// <returns></returns>
private List<MshParameter> ProcessParameter(object[] properties)
{
TerminatingErrorContext invocationContext = new(this);
ParameterProcessor processor =
new(new ConvertHTMLExpressionParameterDefinition());
if (properties == null)
{
properties = new object[] { "*" };
}
return processor.ProcessParameters(properties, invocationContext);
}
/// <summary>
/// Resolve all wildcards in user input Property into resolvedNameMshParameters.
/// </summary>
private void InitializeResolvedNameMshParameters()
{
// temp list of properties with wildcards resolved
var resolvedNameProperty = new List<object>();
foreach (MshParameter p in _propertyMshParameterList)
{
string label = p.GetEntry(ConvertHTMLParameterDefinitionKeys.LabelEntryKey) as string;
string alignment = p.GetEntry(ConvertHTMLParameterDefinitionKeys.AlignmentEntryKey) as string;
// Accept the width both as a string and as an int.
string width;
int? widthNum = p.GetEntry(ConvertHTMLParameterDefinitionKeys.WidthEntryKey) as int?;
width = widthNum != null ? widthNum.Value.ToString() : p.GetEntry(ConvertHTMLParameterDefinitionKeys.WidthEntryKey) as string;
PSPropertyExpression ex = p.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey) as PSPropertyExpression;
List<PSPropertyExpression> resolvedNames = ex.ResolveNames(_inputObject);
foreach (PSPropertyExpression resolvedName in resolvedNames)
{
Hashtable ht = CreateAuxPropertyHT(label, alignment, width);
if (resolvedName.Script != null)
{
// The argument is a calculated property whose value is calculated by a script block.
ht.Add(FormatParameterDefinitionKeys.ExpressionEntryKey, resolvedName.Script);
}
else
{
ht.Add(FormatParameterDefinitionKeys.ExpressionEntryKey, resolvedName.ToString());
}
resolvedNameProperty.Add(ht);
}
}
_resolvedNameMshParameters = ProcessParameter(resolvedNameProperty.ToArray());
}
private static Hashtable CreateAuxPropertyHT(
string label,
string alignment,
string width)
{
Hashtable ht = new();
if (label != null)
{
ht.Add(ConvertHTMLParameterDefinitionKeys.LabelEntryKey, label);
}
if (alignment != null)
{
ht.Add(ConvertHTMLParameterDefinitionKeys.AlignmentEntryKey, alignment);
}
if (width != null)
{
ht.Add(ConvertHTMLParameterDefinitionKeys.WidthEntryKey, width);
}
return ht;
}
/// <summary>
/// Calls ToString. If an exception occurs, eats it and return string.Empty.
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
private static string SafeToString(object obj)
{
if (obj == null)
{
return string.Empty;
}
try
{
return obj.ToString();
}
catch (Exception)
{
// eats exception if safe
}
return string.Empty;
}
/// <summary>
/// </summary>
protected override void BeginProcessing()
{
// ValidateNotNullOrEmpty attribute is not working for System.Uri datatype, so handling it here
if ((_cssuriSpecified) && (string.IsNullOrEmpty(_cssuri.OriginalString.Trim())))
{
ArgumentException ex = new(StringUtil.Format(UtilityCommonStrings.EmptyCSSUri, "CSSUri"));
ErrorRecord er = new(ex, "ArgumentException", ErrorCategory.InvalidArgument, "CSSUri");
ThrowTerminatingError(er);
}
_propertyMshParameterList = ProcessParameter(_property);
if (!string.IsNullOrEmpty(_title))
{
WebUtility.HtmlEncode(_title);
}
// This first line ensures w3c validation will succeed. However we are not specifying
// an encoding in the HTML because we don't know where the text will be written and
// if a particular encoding will be used.
if (!_fragment)
{
if (!_transitional)
{
WriteObject("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">");
}
else
{
WriteObject("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
}
WriteObject("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
WriteObject("<head>");
if (_charsetSpecified)
{
WriteObject("<meta charset=\"" + _charset + "\">");
}
if (_metaSpecified)
{
List<string> useditems = new();
foreach (string s in _meta.Keys)
{
if (!useditems.Contains(s))
{
switch (s.ToLower())
{
case "content-type":
case "default-style":
case "x-ua-compatible":
WriteObject("<meta http-equiv=\"" + s + "\" content=\"" + _meta[s] + "\">");
break;
case "application-name":
case "author":
case "description":
case "generator":
case "keywords":
case "viewport":
WriteObject("<meta name=\"" + s + "\" content=\"" + _meta[s] + "\">");
break;
default:
MshCommandRuntime mshCommandRuntime = this.CommandRuntime as MshCommandRuntime;
string Message = StringUtil.Format(ConvertHTMLStrings.MetaPropertyNotFound, s, _meta[s]);
WarningRecord record = new(Message);
InvocationInfo invocationInfo = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo;
if (invocationInfo != null)
{
record.SetInvocationInfo(invocationInfo);
}
mshCommandRuntime.WriteWarning(record);
WriteObject("<meta name=\"" + s + "\" content=\"" + _meta[s] + "\">");
break;
}
useditems.Add(s);
}
}
}
WriteObject(_head ?? new string[] { "<title>" + _title + "</title>" }, true);
if (_cssuriSpecified)
{
WriteObject("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + _cssuri + "\" />");
}
WriteObject("</head><body>");
if (_body != null)
{
WriteObject(_body, true);
}
}
if (_preContent != null)
{
WriteObject(_preContent, true);
}
WriteObject("<table>");
_isTHWritten = false;
}
/// <summary>
/// Reads Width and Alignment from Property and write Col tags.
/// </summary>
/// <param name="mshParams"></param>
private void WriteColumns(List<MshParameter> mshParams)
{
StringBuilder COLTag = new();
COLTag.Append("<colgroup>");
foreach (MshParameter p in mshParams)
{
COLTag.Append("<col");
string width = p.GetEntry(ConvertHTMLParameterDefinitionKeys.WidthEntryKey) as string;
if (width != null)
{
COLTag.Append(" width = \"");
COLTag.Append(width);
COLTag.Append('"');
}
string alignment = p.GetEntry(ConvertHTMLParameterDefinitionKeys.AlignmentEntryKey) as string;
if (alignment != null)
{
COLTag.Append(" align = \"");
COLTag.Append(alignment);
COLTag.Append('"');
}
COLTag.Append("/>");
}
COLTag.Append("</colgroup>");
// The columngroup and col nodes will be printed in a single line.
WriteObject(COLTag.ToString());
}
/// <summary>
/// Writes the list entries when the As parameter has value List.
/// </summary>
private void WriteListEntry()
{
foreach (MshParameter p in _resolvedNameMshParameters)
{
StringBuilder Listtag = new();
Listtag.Append("<tr><td>");
// for writing the property name
WritePropertyName(Listtag, p);
Listtag.Append(':');
Listtag.Append("</td>");
// for writing the property value
Listtag.Append("<td>");
WritePropertyValue(Listtag, p);
Listtag.Append("</td></tr>");
WriteObject(Listtag.ToString());
}
}
/// <summary>
/// To write the Property name.
/// </summary>
private static void WritePropertyName(StringBuilder Listtag, MshParameter p)
{
// for writing the property name
string label = p.GetEntry(ConvertHTMLParameterDefinitionKeys.LabelEntryKey) as string;
if (label != null)
{
Listtag.Append(label);
}
else
{
PSPropertyExpression ex = p.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey) as PSPropertyExpression;
Listtag.Append(ex.ToString());
}
}
/// <summary>
/// To write the Property value.
/// </summary>
private void WritePropertyValue(StringBuilder Listtag, MshParameter p)
{
PSPropertyExpression exValue = p.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey) as PSPropertyExpression;
// get the value of the property
List<PSPropertyExpressionResult> resultList = exValue.GetValues(_inputObject);
foreach (PSPropertyExpressionResult result in resultList)
{
// create comma sep list for multiple results
if (result.Result != null)
{
string htmlEncodedResult = WebUtility.HtmlEncode(SafeToString(result.Result));
Listtag.Append(htmlEncodedResult);
}
Listtag.Append(", ");
}
if (Listtag.ToString().EndsWith(", ", StringComparison.Ordinal))
{
Listtag.Remove(Listtag.Length - 2, 2);
}
}
/// <summary>
/// To write the Table header for the object property names.
/// </summary>
private static void WriteTableHeader(StringBuilder THtag, List<MshParameter> resolvedNameMshParameters)
{
// write the property names
foreach (MshParameter p in resolvedNameMshParameters)
{
THtag.Append("<th>");
WritePropertyName(THtag, p);
THtag.Append("</th>");
}
}
/// <summary>
/// To write the Table row for the object property values.
/// </summary>
private void WriteTableRow(StringBuilder TRtag, List<MshParameter> resolvedNameMshParameters)
{
// write the property values
foreach (MshParameter p in resolvedNameMshParameters)
{
TRtag.Append("<td>");
WritePropertyValue(TRtag, p);
TRtag.Append("</td>");
}
}
// count of the objects
private int _numberObjects = 0;
/// <summary>
/// </summary>
protected override void ProcessRecord()
{
// writes the table headers
// it is not in BeginProcessing because the first inputObject is needed for
// the number of columns and column name
if (_inputObject == null || _inputObject == AutomationNull.Value)
{
return;
}
_numberObjects++;
if (!_isTHWritten)
{
InitializeResolvedNameMshParameters();
if (_resolvedNameMshParameters == null || _resolvedNameMshParameters.Count == 0)
{
return;
}
// if the As parameter is given as List
if (_as.Equals("List", StringComparison.OrdinalIgnoreCase))
{
// if more than one object,write the horizontal rule to put visual separator
if (_numberObjects > 1)
WriteObject("<tr><td><hr></td></tr>");
WriteListEntry();
}
else // if the As parameter is Table, first we have to write the property names
{
WriteColumns(_resolvedNameMshParameters);
StringBuilder THtag = new("<tr>");
// write the table header
WriteTableHeader(THtag, _resolvedNameMshParameters);
THtag.Append("</tr>");
WriteObject(THtag.ToString());
_isTHWritten = true;
}
}
// if the As parameter is Table, write the property values
if (_as.Equals("Table", StringComparison.OrdinalIgnoreCase))
{
StringBuilder TRtag = new("<tr>");
// write the table row
WriteTableRow(TRtag, _resolvedNameMshParameters);
TRtag.Append("</tr>");
WriteObject(TRtag.ToString());
}
}
/// <summary>
/// </summary>
protected override void EndProcessing()
{
// if fragment,end with table
WriteObject("</table>");
if (_postContent != null)
WriteObject(_postContent, true);
// if not fragment end with body and html also
if (!_fragment)
{
WriteObject("</body></html>");
}
}
#region private
/// <summary>
/// List of incoming objects to compare.
/// </summary>
private bool _isTHWritten;
private List<MshParameter> _propertyMshParameterList;
private List<MshParameter> _resolvedNameMshParameters;
// private string ResourcesBaseName = "ConvertHTMLStrings";
#endregion private
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class AnimateTiledTexture : MonoBehaviour
{
public bool _useCoroutine = false; // Use coroutines for PC targets. For mobile targets WaitForSeconds doesn't work.
[HideInInspector] public float _framesPerSecond = 1f; // Frames per second that you want to texture to play at
[HideInInspector] public bool _pingPongAnim = false; // True for going forward and backwards in the animation
public float _rowsTotalInSprite = 1; // How much rows the sprite has. This value is defined once
public float _maxColsInRows = 1; // The greatest number of columns from the rows the anim covers, not the total columns the anim has
[HideInInspector] public bool _playOnce = false; // Enable this if you want the animation to only play one time
[HideInInspector] public bool _disableUponCompletion = false; // Enable this if you want the texture to disable the renderer when it is finished playing
[HideInInspector] public bool _enableEvents = false; // Enable this if you want to register an event that fires when the animation is finished playing
[HideInInspector] public bool _playOnEnable = true; // The animation will play when the object is enabled
public bool _newMaterialInstance = false; // Set this to true when having more than one game object using same sprite
[HideInInspector] public Vector2 _scale = new Vector2(1f, 1f); // scale the texture. This must be a non-zero number. Negative scale flips the image.
[HideInInspector] public Vector2 _offset = Vector2.zero; // You can use this if you don't want the texture centered. (These are very small numbers .001)
[HideInInspector] public Vector2 _buffer = Vector2.zero; // You can use this to buffer frames to hide unwanted grid lines or artifacts
// these two vars will change depending on the sequence to be displayed.
[HideInInspector] public int[] _rowLimits = new int[]{0,1}; // start row and number of rows for current animation (0-based)
[HideInInspector] public int[] _colLimits = new int[]{0,1}; // start column and number of sprite frames for current animation (0-based)
private int _index = 0; // Keeps track of the current frame
private int _direction = 1; // 1: forward direction. -1: backwards
private int _maxIndex; // Max index for current animation
private Vector2 _textureTiling = Vector2.zero; // Keeps track of the texture scale
private Material _materialInstance = null; // Material instance of the material we create
private bool _hasMaterialInstance = false; // A flag so we know if we have a material instance we need to clean up (better than a null check i think)
private bool _isPlaying = false; // A flag to determine if the animation is currently playing
private float updateTime; // Use for none coroutine function. Keeps track of time passed during game loops
private float period; // The inverse of frames per second. Calculated every time the fps is changed
private float offsetYStart; // what is the offset in Y the current animation starts from
private Vector2 offsetTemp;
//private Vector4 setupVec1, setupVec2;
private List<VoidEvent> _voidEventCallbackList; // A list of functions we need to call if events are enabled
public delegate void VoidEvent(); // The Event delegate
private void Awake()
{
// Allocate memory for the events, if needed
if (_enableEvents)
_voidEventCallbackList = new List<VoidEvent>();
//Create the material instance. Else, just use this function to recalc the texture size
ChangeMaterial(GetComponent<Renderer>().sharedMaterial, _newMaterialInstance);
updateTime = Time.time;
period = 1f / _framesPerSecond;
// it can change if we modify the columns's limits when selecting another animation sequence in the sprite
_maxIndex = _colLimits[0] + _colLimits[1] - 1;
// what is the offset in Y the current animation starts from
offsetYStart = 1f / (_rowsTotalInSprite - _rowLimits[0]);
}
private void OnEnable()
{
CalcTextureTiling();
if (_playOnEnable)
Play();
}
private void OnDestroy() {
// If we wanted new material instances, we need to destroy the material
if (_hasMaterialInstance) {
Object.Destroy(GetComponent<Renderer>().sharedMaterial);
_hasMaterialInstance = false;
}
}
public void setRowLimits(int start, int numRows) {
_rowLimits[0] = start;
_rowLimits[1] = numRows;
offsetYStart = (start + 1) / _rowsTotalInSprite; // add 1 since start is 0 based and _rowsTotalInSprite isn't
}
public void setColLimits(int start, int length) {
_colLimits[0] = start;
_colLimits[1] = length;
_maxIndex = start + length - 1;
_index = start;
}
public void setFPS (float fps) {
_framesPerSecond = fps;
period = 1f / fps;
}
public void setPingPongAnim (bool val) {
_direction = 1; // reset direction
_pingPongAnim = val;
}
// Use this function to register your callback function with this script
public void RegisterCallback(VoidEvent cbFunction) {
// If events are enabled, add the callback function to the event list
if (_enableEvents)
_voidEventCallbackList.Add(cbFunction);
#if DEBUG
else
Debug.LogWarning("AnimateTiledTexture: You are attempting to register a callback but the events of this object are not enabled!");
#endif
}
// Use this function to unregister a callback function with this script
public void UnRegisterCallback(VoidEvent cbFunction)
{
// If events are enabled, unregister the callback function from the event list
if (_enableEvents)
_voidEventCallbackList.Remove(cbFunction);
#if DEBUG
else
Debug.LogWarning("AnimateTiledTexture: You are attempting to un-register a callback but the events of this object are not enabled!");
#endif
}
// Handles all event triggers to callback functions
private void HandleCallbacks(List<VoidEvent> cbList)
{
// For now simply loop through them all and call yet.
for (int i = 0; i < cbList.Count; ++i)
cbList[i]();
}
public void ChangeMaterial(Material newMaterial, bool newInstance = false)
{
Renderer renderer = GetComponent<Renderer>();
if (newInstance) {
// First check our material instance, if we already have a material instance
// and we want to create a new one, we need to clean up the old one
if (_hasMaterialInstance)
Object.Destroy(renderer.sharedMaterial);
// create the new material
_materialInstance = new Material(newMaterial);
// Assign it to the renderer
renderer.sharedMaterial = _materialInstance;
// Set the flag
_hasMaterialInstance = true;
}
else // if we dont have create a new instance, just assign the texture
renderer.sharedMaterial = newMaterial;
// We need to recalc the texture tiling (since different material = possible different texture)
CalcTextureTiling();
}
private void CalcTextureTiling()
{
//set the tile size of the texture (in UV units), based on the rows and columns
_textureTiling.x = 1f / _maxColsInRows;
_textureTiling.y = 1f / _rowsTotalInSprite;
// Add in the scale
_textureTiling.x = _textureTiling.x / _scale.x;
_textureTiling.y = _textureTiling.y / _scale.y;
// Buffer some of the image out (removes gridlines and stufF)
_textureTiling -= _buffer;
// Assign the new texture tiling
Renderer renderer = GetComponent<Renderer>();
// old approach:
renderer.sharedMaterial.SetTextureScale("_MainTex", _textureTiling);
// new approach:
/*renderer.sharedMaterial.SetFloat("_TilingX", _textureTiling.x);
renderer.sharedMaterial.SetFloat("_TilingY", _textureTiling.y);*/
}
public void Play()
{
// If the animation is playing with a coroutine, stop it
if (_isPlaying && _useCoroutine)
StopCoroutine("updateCoroutine");
// Make sure the renderer is enabled
//renderer.enabled = true;
// Because of the way textures calculate the y value, we need to start at the max y value
//_index = _rowsTotal * _maxColsCurrentAnim;
_index = _colLimits[0];
// Start the update tiling coroutine
if (_useCoroutine)
StartCoroutine(updateCoroutine());
else
updateTiling();
}
void Update () {
if (_useCoroutine || !_isPlaying)
return;
float t = Time.time;
if (t - updateTime > period) {
updateTiling();
updateTime = t;
}
}
private IEnumerator updateCoroutine() {
while (true) {
updateTiling();
if (!_isPlaying)
// Break out of the loop, we are finished
yield break;
// Wait a time before we move to the next frame. Note, this gives unexpected results on mobile devices
yield return new WaitForSeconds(period);
}
}
// The main update function of this script
private void updateTiling()
{
_isPlaying = true;
if (_index > _maxIndex) {
if (_playOnce)
{
// We are done with the coroutine. Fire the event, if needed
if(_enableEvents)
HandleCallbacks(_voidEventCallbackList);
if (_disableUponCompletion)
GetComponent<Renderer>().enabled = false;
_isPlaying = false;
}
_index = _colLimits[0]; // reset index
if (_pingPongAnim) {
_direction = -1;
_index = Mathf.Max(_colLimits[0], _maxIndex - 1); // reset the index fo backward animation
}
}
else if (_pingPongAnim && _index < _colLimits[0]) {
_direction = 1;
_index = Mathf.Min(_colLimits[0] + 1, _maxIndex); // reset the index for forward animation
}
// Apply the offset in order to move to the next frame
ApplyOffset();
// Increment/Decrement the index of current frame in sprite
_index += _direction;
}
private void ApplyOffset() {
float xTemp = (float)_index / _maxColsInRows;
float xTempFloor = _index / (int)_maxColsInRows;
float x = xTemp - xTempFloor;
float y = 1f - (xTempFloor / _rowsTotalInSprite) - offsetYStart;
// Reset the y offset, if needed
if (y == 1f)
y = 0f;
// If we have scaled the texture, we need to reposition the texture to the center of the object
x += ((1f / _maxColsInRows) - _textureTiling.x) * 0.5f;
y += ((1f / _rowsTotalInSprite) - _textureTiling.y) * 0.5f;
// Add an additional offset if the user does not want the texture centered
offsetTemp.x = x + _offset.x;
offsetTemp.y = y + _offset.y;
// Update the material
Renderer renderer = GetComponent<Renderer>();
// old approach:
renderer.sharedMaterial.SetTextureOffset("_MainTex", offsetTemp);
// new approach:
/*renderer.sharedMaterial.SetFloat("_OffsetX", offsetTemp.x);
renderer.sharedMaterial.SetFloat("_OffsetY", offsetTemp.y);*/
// new approach with calculations of offset in the shader
// setupVec1: _index, _maxColsInRows, _rowsTotalInSprite, offsetYStart
/*setupVec1.x = _index;
setupVec1.y = _maxColsInRows;
setupVec1.z = _rowsTotalInSprite;
setupVec1.w = offsetYStart;
// setupVec2: _textureTiling.x, _textureTiling.y, _offset.x, _offset.y
setupVec2.x = _textureTiling.x;
setupVec2.y = _textureTiling.y;
setupVec2.z = _offset.x;
setupVec2.w = _offset.y;
// update shader params
renderer.sharedMaterial.SetVector("_SetupVec1", setupVec1);
renderer.sharedMaterial.SetVector("_SetupVec2", setupVec2);*/
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.