context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace EncompassRest.Loans
{
/// <summary>
/// DisclosureTrackingLog
/// </summary>
public sealed partial class DisclosureTrackingLog : DirtyExtensibleObject, IIdentifiable
{
private DirtyList<LogAlert>? _alerts;
private DirtyValue<string?>? _alertsXml;
private DirtyValue<DateTime?>? _applicationDate;
private DirtyValue<string?>? _borrowerName;
private DirtyValue<string?>? _borrowerPairId;
private DirtyValue<string?>? _coBorrowerName;
private DirtyList<LogComment>? _commentList;
private DirtyValue<string?>? _commentListXml;
private DirtyValue<string?>? _comments;
private DirtyValue<bool?>? _containGfe;
private DirtyValue<bool?>? _containSafeHarbor;
private DirtyValue<bool?>? _containTil;
private DirtyValue<DateTime?>? _dateUtc;
private DirtyValue<string?>? _disclosedAPR;
private DirtyValue<string?>? _disclosedBy;
private DirtyValue<string?>? _disclosedByFullName;
private DirtyValue<string?>? _disclosedMethod;
private DirtyValue<DateTime?>? _disclosureCreatedDttmUtc;
private DirtyValue<bool?>? _eDisclosureApplicationPackageIndicator;
private DirtyValue<bool?>? _eDisclosureApprovalPackageIndicator;
private DirtyValue<DateTime?>? _eDisclosureBorrowerAcceptConsentDate;
private DirtyValue<DateTime?>? _eDisclosureBorrowereSignedDate;
private DirtyValue<DateTime?>? _eDisclosureBorrowerRejectConsentDate;
private DirtyValue<DateTime?>? _eDisclosureBorrowerViewConsentDate;
private DirtyValue<DateTime?>? _eDisclosureBorrowerViewMessageDate;
private DirtyValue<DateTime?>? _eDisclosureBorrowerWetSignedDate;
private DirtyValue<DateTime?>? _eDisclosureCoBorrowerAcceptConsentDate;
private DirtyValue<DateTime?>? _eDisclosureCoBorrowereSignedDate;
private DirtyValue<DateTime?>? _eDisclosureCoBorrowerRejectConsentDate;
private DirtyValue<DateTime?>? _eDisclosureCoBorrowerViewConsentDate;
private DirtyValue<DateTime?>? _eDisclosureCoBorrowerViewMessageDate;
private DirtyValue<DateTime?>? _eDisclosureCoBorrowerWebSignedDate;
private DirtyValue<string?>? _eDisclosureConsentPdf;
private DirtyValue<string?>? _eDisclosureDisclosedMessage;
private DirtyValue<bool?>? _eDisclosureLockPackageIndicator;
private DirtyValue<string?>? _eDisclosureManualFulfillmentComment;
private DirtyValue<DateTime?>? _eDisclosureManualFulfillmentDate;
private DirtyValue<string?>? _eDisclosureManualFulfillmentMethod;
private DirtyValue<string?>? _eDisclosureManuallyFulfilledBy;
private DirtyValue<DateTime?>? _eDisclosurePackageCreatedDate;
private DirtyValue<string?>? _eDisclosurePackageId;
private DirtyValue<string?>? _eDisclosurePackageViewableFile;
private DirtyValue<bool?>? _eDisclosureThreeDayPackageIndicator;
private DirtyValue<bool?>? _fileAttachmentsMigrated;
private DirtyValue<string?>? _financeCharge;
private DirtyList<DisclosureForm>? _forms;
private DirtyValue<string?>? _formsXml;
private DirtyValue<string?>? _fulfillmentOrderedBy;
private DirtyValue<string?>? _fullfillmentProcessedDate;
private DirtyValue<string?>? _guid;
private DirtyValue<string?>? _id;
private DirtyValue<string?>? _isDisclosed;
private DirtyValue<string?>? _isDisclosedAprLocked;
private DirtyValue<string?>? _isDisclosedByLocked;
private DirtyValue<string?>? _isDisclosedFinanceChargeLocked;
private DirtyValue<string?>? _isDisclosedReceivedDateLocked;
private DirtyValue<string?>? _isLocked;
private DirtyValue<bool?>? _isSystemSpecificIndicator;
private DirtyValue<bool?>? _isWetSignedIndicator;
private DirtyValue<string?>? _loanAmount;
private DirtyValue<string?>? _loanProgram;
private DirtyValue<string?>? _lockedDisclosedAprField;
private DirtyValue<string?>? _lockedDisclosedByField;
private DirtyValue<string?>? _lockedDisclosedFinanceChargeField;
private DirtyValue<DateTime?>? _lockedDisclosedReceivedDate;
private DirtyValue<int?>? _logRecordIndex;
private DirtyValue<string?>? _manuallyCreated;
private DirtyValue<string?>? _propertyAddress;
private DirtyValue<string?>? _propertyCity;
private DirtyValue<string?>? _propertyState;
private DirtyValue<string?>? _propertyZip;
private DirtyValue<DateTime?>? _receivedDate;
private DirtyList<LogSnapshotField>? _snapshotFields;
private DirtyValue<string?>? _snapshotXml;
private DirtyValue<string?>? _systemId;
private DirtyValue<DateTime?>? _updatedDateUtc;
/// <summary>
/// DisclosureTrackingLog Alerts
/// </summary>
[AllowNull]
public IList<LogAlert> Alerts { get => GetField(ref _alerts); set => SetField(ref _alerts, value); }
/// <summary>
/// DisclosureTrackingLog AlertsXml
/// </summary>
public string? AlertsXml { get => _alertsXml; set => SetField(ref _alertsXml, value); }
/// <summary>
/// DisclosureTrackingLog ApplicationDate
/// </summary>
public DateTime? ApplicationDate { get => _applicationDate; set => SetField(ref _applicationDate, value); }
/// <summary>
/// DisclosureTrackingLog BorrowerName
/// </summary>
public string? BorrowerName { get => _borrowerName; set => SetField(ref _borrowerName, value); }
/// <summary>
/// DisclosureTrackingLog BorrowerPairId
/// </summary>
public string? BorrowerPairId { get => _borrowerPairId; set => SetField(ref _borrowerPairId, value); }
/// <summary>
/// DisclosureTrackingLog CoBorrowerName
/// </summary>
public string? CoBorrowerName { get => _coBorrowerName; set => SetField(ref _coBorrowerName, value); }
/// <summary>
/// DisclosureTrackingLog CommentList
/// </summary>
[AllowNull]
public IList<LogComment> CommentList { get => GetField(ref _commentList); set => SetField(ref _commentList, value); }
/// <summary>
/// DisclosureTrackingLog CommentListXml
/// </summary>
public string? CommentListXml { get => _commentListXml; set => SetField(ref _commentListXml, value); }
/// <summary>
/// DisclosureTrackingLog Comments
/// </summary>
public string? Comments { get => _comments; set => SetField(ref _comments, value); }
/// <summary>
/// DisclosureTrackingLog ContainGfe
/// </summary>
public bool? ContainGfe { get => _containGfe; set => SetField(ref _containGfe, value); }
/// <summary>
/// DisclosureTrackingLog ContainSafeHarbor
/// </summary>
public bool? ContainSafeHarbor { get => _containSafeHarbor; set => SetField(ref _containSafeHarbor, value); }
/// <summary>
/// DisclosureTrackingLog ContainTil
/// </summary>
public bool? ContainTil { get => _containTil; set => SetField(ref _containTil, value); }
/// <summary>
/// DisclosureTrackingLog DateUtc
/// </summary>
public DateTime? DateUtc { get => _dateUtc; set => SetField(ref _dateUtc, value); }
/// <summary>
/// DisclosureTrackingLog DisclosedAPR
/// </summary>
public string? DisclosedAPR { get => _disclosedAPR; set => SetField(ref _disclosedAPR, value); }
/// <summary>
/// DisclosureTrackingLog DisclosedBy
/// </summary>
public string? DisclosedBy { get => _disclosedBy; set => SetField(ref _disclosedBy, value); }
/// <summary>
/// DisclosureTrackingLog DisclosedByFullName
/// </summary>
public string? DisclosedByFullName { get => _disclosedByFullName; set => SetField(ref _disclosedByFullName, value); }
/// <summary>
/// DisclosureTrackingLog DisclosedMethod
/// </summary>
public string? DisclosedMethod { get => _disclosedMethod; set => SetField(ref _disclosedMethod, value); }
/// <summary>
/// DisclosureTrackingLog DisclosureCreatedDttmUtc
/// </summary>
public DateTime? DisclosureCreatedDttmUtc { get => _disclosureCreatedDttmUtc; set => SetField(ref _disclosureCreatedDttmUtc, value); }
/// <summary>
/// DisclosureTrackingLog EDisclosureApplicationPackageIndicator
/// </summary>
public bool? EDisclosureApplicationPackageIndicator { get => _eDisclosureApplicationPackageIndicator; set => SetField(ref _eDisclosureApplicationPackageIndicator, value); }
/// <summary>
/// DisclosureTrackingLog EDisclosureApprovalPackageIndicator
/// </summary>
public bool? EDisclosureApprovalPackageIndicator { get => _eDisclosureApprovalPackageIndicator; set => SetField(ref _eDisclosureApprovalPackageIndicator, value); }
/// <summary>
/// DisclosureTrackingLog EDisclosureBorrowerAcceptConsentDate
/// </summary>
public DateTime? EDisclosureBorrowerAcceptConsentDate { get => _eDisclosureBorrowerAcceptConsentDate; set => SetField(ref _eDisclosureBorrowerAcceptConsentDate, value); }
/// <summary>
/// DisclosureTrackingLog EDisclosureBorrowereSignedDate
/// </summary>
public DateTime? EDisclosureBorrowereSignedDate { get => _eDisclosureBorrowereSignedDate; set => SetField(ref _eDisclosureBorrowereSignedDate, value); }
/// <summary>
/// DisclosureTrackingLog EDisclosureBorrowerRejectConsentDate
/// </summary>
public DateTime? EDisclosureBorrowerRejectConsentDate { get => _eDisclosureBorrowerRejectConsentDate; set => SetField(ref _eDisclosureBorrowerRejectConsentDate, value); }
/// <summary>
/// DisclosureTrackingLog EDisclosureBorrowerViewConsentDate
/// </summary>
public DateTime? EDisclosureBorrowerViewConsentDate { get => _eDisclosureBorrowerViewConsentDate; set => SetField(ref _eDisclosureBorrowerViewConsentDate, value); }
/// <summary>
/// DisclosureTrackingLog EDisclosureBorrowerViewMessageDate
/// </summary>
public DateTime? EDisclosureBorrowerViewMessageDate { get => _eDisclosureBorrowerViewMessageDate; set => SetField(ref _eDisclosureBorrowerViewMessageDate, value); }
/// <summary>
/// DisclosureTrackingLog EDisclosureBorrowerWetSignedDate
/// </summary>
public DateTime? EDisclosureBorrowerWetSignedDate { get => _eDisclosureBorrowerWetSignedDate; set => SetField(ref _eDisclosureBorrowerWetSignedDate, value); }
/// <summary>
/// DisclosureTrackingLog EDisclosureCoBorrowerAcceptConsentDate
/// </summary>
public DateTime? EDisclosureCoBorrowerAcceptConsentDate { get => _eDisclosureCoBorrowerAcceptConsentDate; set => SetField(ref _eDisclosureCoBorrowerAcceptConsentDate, value); }
/// <summary>
/// DisclosureTrackingLog EDisclosureCoBorrowereSignedDate
/// </summary>
public DateTime? EDisclosureCoBorrowereSignedDate { get => _eDisclosureCoBorrowereSignedDate; set => SetField(ref _eDisclosureCoBorrowereSignedDate, value); }
/// <summary>
/// DisclosureTrackingLog EDisclosureCoBorrowerRejectConsentDate
/// </summary>
public DateTime? EDisclosureCoBorrowerRejectConsentDate { get => _eDisclosureCoBorrowerRejectConsentDate; set => SetField(ref _eDisclosureCoBorrowerRejectConsentDate, value); }
/// <summary>
/// DisclosureTrackingLog EDisclosureCoBorrowerViewConsentDate
/// </summary>
public DateTime? EDisclosureCoBorrowerViewConsentDate { get => _eDisclosureCoBorrowerViewConsentDate; set => SetField(ref _eDisclosureCoBorrowerViewConsentDate, value); }
/// <summary>
/// DisclosureTrackingLog EDisclosureCoBorrowerViewMessageDate
/// </summary>
public DateTime? EDisclosureCoBorrowerViewMessageDate { get => _eDisclosureCoBorrowerViewMessageDate; set => SetField(ref _eDisclosureCoBorrowerViewMessageDate, value); }
/// <summary>
/// DisclosureTrackingLog EDisclosureCoBorrowerWebSignedDate
/// </summary>
public DateTime? EDisclosureCoBorrowerWebSignedDate { get => _eDisclosureCoBorrowerWebSignedDate; set => SetField(ref _eDisclosureCoBorrowerWebSignedDate, value); }
/// <summary>
/// DisclosureTrackingLog EDisclosureConsentPdf
/// </summary>
public string? EDisclosureConsentPdf { get => _eDisclosureConsentPdf; set => SetField(ref _eDisclosureConsentPdf, value); }
/// <summary>
/// DisclosureTrackingLog EDisclosureDisclosedMessage
/// </summary>
public string? EDisclosureDisclosedMessage { get => _eDisclosureDisclosedMessage; set => SetField(ref _eDisclosureDisclosedMessage, value); }
/// <summary>
/// DisclosureTrackingLog EDisclosureLockPackageIndicator
/// </summary>
public bool? EDisclosureLockPackageIndicator { get => _eDisclosureLockPackageIndicator; set => SetField(ref _eDisclosureLockPackageIndicator, value); }
/// <summary>
/// DisclosureTrackingLog EDisclosureManualFulfillmentComment
/// </summary>
public string? EDisclosureManualFulfillmentComment { get => _eDisclosureManualFulfillmentComment; set => SetField(ref _eDisclosureManualFulfillmentComment, value); }
/// <summary>
/// DisclosureTrackingLog EDisclosureManualFulfillmentDate
/// </summary>
public DateTime? EDisclosureManualFulfillmentDate { get => _eDisclosureManualFulfillmentDate; set => SetField(ref _eDisclosureManualFulfillmentDate, value); }
/// <summary>
/// DisclosureTrackingLog EDisclosureManualFulfillmentMethod
/// </summary>
public string? EDisclosureManualFulfillmentMethod { get => _eDisclosureManualFulfillmentMethod; set => SetField(ref _eDisclosureManualFulfillmentMethod, value); }
/// <summary>
/// DisclosureTrackingLog EDisclosureManuallyFulfilledBy
/// </summary>
public string? EDisclosureManuallyFulfilledBy { get => _eDisclosureManuallyFulfilledBy; set => SetField(ref _eDisclosureManuallyFulfilledBy, value); }
/// <summary>
/// DisclosureTrackingLog EDisclosurePackageCreatedDate
/// </summary>
public DateTime? EDisclosurePackageCreatedDate { get => _eDisclosurePackageCreatedDate; set => SetField(ref _eDisclosurePackageCreatedDate, value); }
/// <summary>
/// DisclosureTrackingLog EDisclosurePackageId
/// </summary>
public string? EDisclosurePackageId { get => _eDisclosurePackageId; set => SetField(ref _eDisclosurePackageId, value); }
/// <summary>
/// DisclosureTrackingLog EDisclosurePackageViewableFile
/// </summary>
public string? EDisclosurePackageViewableFile { get => _eDisclosurePackageViewableFile; set => SetField(ref _eDisclosurePackageViewableFile, value); }
/// <summary>
/// DisclosureTrackingLog EDisclosureThreeDayPackageIndicator
/// </summary>
public bool? EDisclosureThreeDayPackageIndicator { get => _eDisclosureThreeDayPackageIndicator; set => SetField(ref _eDisclosureThreeDayPackageIndicator, value); }
/// <summary>
/// DisclosureTrackingLog FileAttachmentsMigrated
/// </summary>
public bool? FileAttachmentsMigrated { get => _fileAttachmentsMigrated; set => SetField(ref _fileAttachmentsMigrated, value); }
/// <summary>
/// DisclosureTrackingLog FinanceCharge
/// </summary>
public string? FinanceCharge { get => _financeCharge; set => SetField(ref _financeCharge, value); }
/// <summary>
/// DisclosureTrackingLog Forms
/// </summary>
[AllowNull]
public IList<DisclosureForm> Forms { get => GetField(ref _forms); set => SetField(ref _forms, value); }
/// <summary>
/// DisclosureTrackingLog FormsXml
/// </summary>
public string? FormsXml { get => _formsXml; set => SetField(ref _formsXml, value); }
/// <summary>
/// DisclosureTrackingLog FulfillmentOrderedBy
/// </summary>
public string? FulfillmentOrderedBy { get => _fulfillmentOrderedBy; set => SetField(ref _fulfillmentOrderedBy, value); }
/// <summary>
/// DisclosureTrackingLog FullfillmentProcessedDate
/// </summary>
public string? FullfillmentProcessedDate { get => _fullfillmentProcessedDate; set => SetField(ref _fullfillmentProcessedDate, value); }
/// <summary>
/// DisclosureTrackingLog Guid
/// </summary>
public string? Guid { get => _guid; set => SetField(ref _guid, value); }
/// <summary>
/// DisclosureTrackingLog Id
/// </summary>
public string? Id { get => _id; set => SetField(ref _id, value); }
/// <summary>
/// DisclosureTrackingLog IsDisclosed
/// </summary>
public string? IsDisclosed { get => _isDisclosed; set => SetField(ref _isDisclosed, value); }
/// <summary>
/// DisclosureTrackingLog IsDisclosedAprLocked
/// </summary>
public string? IsDisclosedAprLocked { get => _isDisclosedAprLocked; set => SetField(ref _isDisclosedAprLocked, value); }
/// <summary>
/// DisclosureTrackingLog IsDisclosedByLocked
/// </summary>
public string? IsDisclosedByLocked { get => _isDisclosedByLocked; set => SetField(ref _isDisclosedByLocked, value); }
/// <summary>
/// DisclosureTrackingLog IsDisclosedFinanceChargeLocked
/// </summary>
public string? IsDisclosedFinanceChargeLocked { get => _isDisclosedFinanceChargeLocked; set => SetField(ref _isDisclosedFinanceChargeLocked, value); }
/// <summary>
/// DisclosureTrackingLog IsDisclosedReceivedDateLocked
/// </summary>
public string? IsDisclosedReceivedDateLocked { get => _isDisclosedReceivedDateLocked; set => SetField(ref _isDisclosedReceivedDateLocked, value); }
/// <summary>
/// DisclosureTrackingLog IsLocked
/// </summary>
public string? IsLocked { get => _isLocked; set => SetField(ref _isLocked, value); }
/// <summary>
/// DisclosureTrackingLog IsSystemSpecificIndicator
/// </summary>
public bool? IsSystemSpecificIndicator { get => _isSystemSpecificIndicator; set => SetField(ref _isSystemSpecificIndicator, value); }
/// <summary>
/// DisclosureTrackingLog IsWetSignedIndicator
/// </summary>
public bool? IsWetSignedIndicator { get => _isWetSignedIndicator; set => SetField(ref _isWetSignedIndicator, value); }
/// <summary>
/// DisclosureTrackingLog LoanAmount
/// </summary>
public string? LoanAmount { get => _loanAmount; set => SetField(ref _loanAmount, value); }
/// <summary>
/// DisclosureTrackingLog LoanProgram
/// </summary>
public string? LoanProgram { get => _loanProgram; set => SetField(ref _loanProgram, value); }
/// <summary>
/// DisclosureTrackingLog LockedDisclosedAprField
/// </summary>
public string? LockedDisclosedAprField { get => _lockedDisclosedAprField; set => SetField(ref _lockedDisclosedAprField, value); }
/// <summary>
/// DisclosureTrackingLog LockedDisclosedByField
/// </summary>
public string? LockedDisclosedByField { get => _lockedDisclosedByField; set => SetField(ref _lockedDisclosedByField, value); }
/// <summary>
/// DisclosureTrackingLog LockedDisclosedFinanceChargeField
/// </summary>
public string? LockedDisclosedFinanceChargeField { get => _lockedDisclosedFinanceChargeField; set => SetField(ref _lockedDisclosedFinanceChargeField, value); }
/// <summary>
/// DisclosureTrackingLog LockedDisclosedReceivedDate
/// </summary>
public DateTime? LockedDisclosedReceivedDate { get => _lockedDisclosedReceivedDate; set => SetField(ref _lockedDisclosedReceivedDate, value); }
/// <summary>
/// DisclosureTrackingLog LogRecordIndex
/// </summary>
public int? LogRecordIndex { get => _logRecordIndex; set => SetField(ref _logRecordIndex, value); }
/// <summary>
/// DisclosureTrackingLog ManuallyCreated
/// </summary>
public string? ManuallyCreated { get => _manuallyCreated; set => SetField(ref _manuallyCreated, value); }
/// <summary>
/// DisclosureTrackingLog PropertyAddress
/// </summary>
public string? PropertyAddress { get => _propertyAddress; set => SetField(ref _propertyAddress, value); }
/// <summary>
/// DisclosureTrackingLog PropertyCity
/// </summary>
public string? PropertyCity { get => _propertyCity; set => SetField(ref _propertyCity, value); }
/// <summary>
/// DisclosureTrackingLog PropertyState
/// </summary>
public string? PropertyState { get => _propertyState; set => SetField(ref _propertyState, value); }
/// <summary>
/// DisclosureTrackingLog PropertyZip
/// </summary>
public string? PropertyZip { get => _propertyZip; set => SetField(ref _propertyZip, value); }
/// <summary>
/// DisclosureTrackingLog ReceivedDate
/// </summary>
public DateTime? ReceivedDate { get => _receivedDate; set => SetField(ref _receivedDate, value); }
/// <summary>
/// DisclosureTrackingLog SnapshotFields
/// </summary>
[AllowNull]
public IList<LogSnapshotField> SnapshotFields { get => GetField(ref _snapshotFields); set => SetField(ref _snapshotFields, value); }
/// <summary>
/// DisclosureTrackingLog SnapshotXml
/// </summary>
public string? SnapshotXml { get => _snapshotXml; set => SetField(ref _snapshotXml, value); }
/// <summary>
/// DisclosureTrackingLog SystemId
/// </summary>
public string? SystemId { get => _systemId; set => SetField(ref _systemId, value); }
/// <summary>
/// DisclosureTrackingLog UpdatedDateUtc
/// </summary>
public DateTime? UpdatedDateUtc { get => _updatedDateUtc; set => SetField(ref _updatedDateUtc, value); }
}
}
| |
//#define B2_DEBUG_SOLVER
/*
* Velcro Physics:
* Copyright (c) 2017 Ian Qvist
*
* Original source Box2D:
* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
using System;
using Microsoft.Xna.Framework;
using QEngine.Physics.Collision.ContactSystem;
using QEngine.Physics.Collision.Narrowphase;
using QEngine.Physics.Collision.Shapes;
using QEngine.Physics.Shared;
using QEngine.Physics.Shared.Optimization;
using QEngine.Physics.Utilities;
namespace QEngine.Physics.Dynamics.Solver
{
public class ContactSolver
{
private Contact[] _contacts;
private int _count;
private ContactPositionConstraint[] _positionConstraints;
private Position[] _positions;
private TimeStep _step;
private Velocity[] _velocities;
public ContactVelocityConstraint[] VelocityConstraints;
public void Reset(TimeStep step, int count, Contact[] contacts, Position[] positions, Velocity[] velocities)
{
_step = step;
_count = count;
_positions = positions;
_velocities = velocities;
_contacts = contacts;
// grow the array
if (VelocityConstraints == null || VelocityConstraints.Length < count)
{
VelocityConstraints = new ContactVelocityConstraint[count * 2];
_positionConstraints = new ContactPositionConstraint[count * 2];
for (int i = 0; i < VelocityConstraints.Length; i++)
{
VelocityConstraints[i] = new ContactVelocityConstraint();
}
for (int i = 0; i < _positionConstraints.Length; i++)
{
_positionConstraints[i] = new ContactPositionConstraint();
}
}
// Initialize position independent portions of the constraints.
for (int i = 0; i < _count; ++i)
{
Contact contact = contacts[i];
Fixture fixtureA = contact.FixtureA;
Fixture fixtureB = contact.FixtureB;
Shape shapeA = fixtureA.Shape;
Shape shapeB = fixtureB.Shape;
float radiusA = shapeA.Radius;
float radiusB = shapeB.Radius;
Body bodyA = fixtureA.Body;
Body bodyB = fixtureB.Body;
Manifold manifold = contact.Manifold;
int pointCount = manifold.PointCount;
System.Diagnostics.Debug.Assert(pointCount > 0);
ContactVelocityConstraint vc = VelocityConstraints[i];
vc.Friction = contact.Friction;
vc.Restitution = contact.Restitution;
vc.TangentSpeed = contact.TangentSpeed;
vc.IndexA = bodyA.IslandIndex;
vc.IndexB = bodyB.IslandIndex;
vc.InvMassA = bodyA._invMass;
vc.InvMassB = bodyB._invMass;
vc.InvIA = bodyA._invI;
vc.InvIB = bodyB._invI;
vc.ContactIndex = i;
vc.PointCount = pointCount;
vc.K.SetZero();
vc.NormalMass.SetZero();
ContactPositionConstraint pc = _positionConstraints[i];
pc.IndexA = bodyA.IslandIndex;
pc.IndexB = bodyB.IslandIndex;
pc.InvMassA = bodyA._invMass;
pc.InvMassB = bodyB._invMass;
pc.LocalCenterA = bodyA._sweep.LocalCenter;
pc.LocalCenterB = bodyB._sweep.LocalCenter;
pc.InvIA = bodyA._invI;
pc.InvIB = bodyB._invI;
pc.LocalNormal = manifold.LocalNormal;
pc.LocalPoint = manifold.LocalPoint;
pc.PointCount = pointCount;
pc.RadiusA = radiusA;
pc.RadiusB = radiusB;
pc.Type = manifold.Type;
for (int j = 0; j < pointCount; ++j)
{
ManifoldPoint cp = manifold.Points[j];
VelocityConstraintPoint vcp = vc.Points[j];
if (Settings.EnableWarmstarting)
{
vcp.NormalImpulse = _step.dtRatio * cp.NormalImpulse;
vcp.TangentImpulse = _step.dtRatio * cp.TangentImpulse;
}
else
{
vcp.NormalImpulse = 0.0f;
vcp.TangentImpulse = 0.0f;
}
vcp.rA = Vector2.Zero;
vcp.rB = Vector2.Zero;
vcp.NormalMass = 0.0f;
vcp.TangentMass = 0.0f;
vcp.VelocityBias = 0.0f;
pc.LocalPoints[j] = cp.LocalPoint;
}
}
}
/// <summary>
/// Initialize position dependent portions of the velocity constraints.
/// </summary>
public void InitializeVelocityConstraints()
{
for (int i = 0; i < _count; ++i)
{
ContactVelocityConstraint vc = VelocityConstraints[i];
ContactPositionConstraint pc = _positionConstraints[i];
float radiusA = pc.RadiusA;
float radiusB = pc.RadiusB;
Manifold manifold = _contacts[vc.ContactIndex].Manifold;
int indexA = vc.IndexA;
int indexB = vc.IndexB;
float mA = vc.InvMassA;
float mB = vc.InvMassB;
float iA = vc.InvIA;
float iB = vc.InvIB;
Vector2 localCenterA = pc.LocalCenterA;
Vector2 localCenterB = pc.LocalCenterB;
Vector2 cA = _positions[indexA].C;
float aA = _positions[indexA].A;
Vector2 vA = _velocities[indexA].V;
float wA = _velocities[indexA].W;
Vector2 cB = _positions[indexB].C;
float aB = _positions[indexB].A;
Vector2 vB = _velocities[indexB].V;
float wB = _velocities[indexB].W;
System.Diagnostics.Debug.Assert(manifold.PointCount > 0);
Transform xfA = new Transform();
Transform xfB = new Transform();
xfA.q.Set(aA);
xfB.q.Set(aB);
xfA.p = cA - MathUtils.Mul(xfA.q, localCenterA);
xfB.p = cB - MathUtils.Mul(xfB.q, localCenterB);
WorldManifold.Initialize(ref manifold, ref xfA, radiusA, ref xfB, radiusB, out Vector2 normal, out FixedArray2<Vector2> points, out _);
vc.Normal = normal;
int pointCount = vc.PointCount;
for (int j = 0; j < pointCount; ++j)
{
VelocityConstraintPoint vcp = vc.Points[j];
vcp.rA = points[j] - cA;
vcp.rB = points[j] - cB;
float rnA = MathUtils.Cross(vcp.rA, vc.Normal);
float rnB = MathUtils.Cross(vcp.rB, vc.Normal);
float kNormal = mA + mB + iA * rnA * rnA + iB * rnB * rnB;
vcp.NormalMass = kNormal > 0.0f ? 1.0f / kNormal : 0.0f;
Vector2 tangent = MathUtils.Cross(vc.Normal, 1.0f);
float rtA = MathUtils.Cross(vcp.rA, tangent);
float rtB = MathUtils.Cross(vcp.rB, tangent);
float kTangent = mA + mB + iA * rtA * rtA + iB * rtB * rtB;
vcp.TangentMass = kTangent > 0.0f ? 1.0f / kTangent : 0.0f;
// Setup a velocity bias for restitution.
vcp.VelocityBias = 0.0f;
float vRel = Vector2.Dot(vc.Normal, vB + MathUtils.Cross(wB, vcp.rB) - vA - MathUtils.Cross(wA, vcp.rA));
if (vRel < -Settings.VelocityThreshold)
{
vcp.VelocityBias = -vc.Restitution * vRel;
}
}
// If we have two points, then prepare the block solver.
if (vc.PointCount == 2 && Settings.BlockSolve)
{
VelocityConstraintPoint vcp1 = vc.Points[0];
VelocityConstraintPoint vcp2 = vc.Points[1];
float rn1A = MathUtils.Cross(vcp1.rA, vc.Normal);
float rn1B = MathUtils.Cross(vcp1.rB, vc.Normal);
float rn2A = MathUtils.Cross(vcp2.rA, vc.Normal);
float rn2B = MathUtils.Cross(vcp2.rB, vc.Normal);
float k11 = mA + mB + iA * rn1A * rn1A + iB * rn1B * rn1B;
float k22 = mA + mB + iA * rn2A * rn2A + iB * rn2B * rn2B;
float k12 = mA + mB + iA * rn1A * rn2A + iB * rn1B * rn2B;
// Ensure a reasonable condition number.
const float k_maxConditionNumber = 1000.0f;
if (k11 * k11 < k_maxConditionNumber * (k11 * k22 - k12 * k12))
{
// K is safe to invert.
vc.K.ex = new Vector2(k11, k12);
vc.K.ey = new Vector2(k12, k22);
vc.NormalMass = vc.K.Inverse;
}
else
{
// The constraints are redundant, just use one.
// TODO_ERIN use deepest?
vc.PointCount = 1;
}
}
}
}
public void WarmStart()
{
// Warm start.
for (int i = 0; i < _count; ++i)
{
ContactVelocityConstraint vc = VelocityConstraints[i];
int indexA = vc.IndexA;
int indexB = vc.IndexB;
float mA = vc.InvMassA;
float iA = vc.InvIA;
float mB = vc.InvMassB;
float iB = vc.InvIB;
int pointCount = vc.PointCount;
Vector2 vA = _velocities[indexA].V;
float wA = _velocities[indexA].W;
Vector2 vB = _velocities[indexB].V;
float wB = _velocities[indexB].W;
Vector2 normal = vc.Normal;
Vector2 tangent = MathUtils.Cross(normal, 1.0f);
for (int j = 0; j < pointCount; ++j)
{
VelocityConstraintPoint vcp = vc.Points[j];
Vector2 P = vcp.NormalImpulse * normal + vcp.TangentImpulse * tangent;
wA -= iA * MathUtils.Cross(vcp.rA, P);
vA -= mA * P;
wB += iB * MathUtils.Cross(vcp.rB, P);
vB += mB * P;
}
_velocities[indexA].V = vA;
_velocities[indexA].W = wA;
_velocities[indexB].V = vB;
_velocities[indexB].W = wB;
}
}
public void SolveVelocityConstraints()
{
for (int i = 0; i < _count; ++i)
{
ContactVelocityConstraint vc = VelocityConstraints[i];
int indexA = vc.IndexA;
int indexB = vc.IndexB;
float mA = vc.InvMassA;
float iA = vc.InvIA;
float mB = vc.InvMassB;
float iB = vc.InvIB;
int pointCount = vc.PointCount;
Vector2 vA = _velocities[indexA].V;
float wA = _velocities[indexA].W;
Vector2 vB = _velocities[indexB].V;
float wB = _velocities[indexB].W;
Vector2 normal = vc.Normal;
Vector2 tangent = MathUtils.Cross(normal, 1.0f);
float friction = vc.Friction;
System.Diagnostics.Debug.Assert(pointCount == 1 || pointCount == 2);
// Solve tangent constraints first because non-penetration is more important
// than friction.
for (int j = 0; j < pointCount; ++j)
{
VelocityConstraintPoint vcp = vc.Points[j];
// Relative velocity at contact
Vector2 dv = vB + MathUtils.Cross(wB, vcp.rB) - vA - MathUtils.Cross(wA, vcp.rA);
// Compute tangent force
float vt = Vector2.Dot(dv, tangent) - vc.TangentSpeed;
float lambda = vcp.TangentMass * (-vt);
// b2Clamp the accumulated force
float maxFriction = friction * vcp.NormalImpulse;
float newImpulse = MathUtils.Clamp(vcp.TangentImpulse + lambda, -maxFriction, maxFriction);
lambda = newImpulse - vcp.TangentImpulse;
vcp.TangentImpulse = newImpulse;
// Apply contact impulse
Vector2 P = lambda * tangent;
vA -= mA * P;
wA -= iA * MathUtils.Cross(vcp.rA, P);
vB += mB * P;
wB += iB * MathUtils.Cross(vcp.rB, P);
}
// Solve normal constraints
if (pointCount == 1 || Settings.BlockSolve == false)
{
for (int j = 0; j < pointCount; ++j)
{
VelocityConstraintPoint vcp = vc.Points[j];
// Relative velocity at contact
Vector2 dv = vB + MathUtils.Cross(wB, vcp.rB) - vA - MathUtils.Cross(wA, vcp.rA);
// Compute normal impulse
float vn = Vector2.Dot(dv, normal);
float lambda = -vcp.NormalMass * (vn - vcp.VelocityBias);
// b2Clamp the accumulated impulse
float newImpulse = Math.Max(vcp.NormalImpulse + lambda, 0.0f);
lambda = newImpulse - vcp.NormalImpulse;
vcp.NormalImpulse = newImpulse;
// Apply contact impulse
Vector2 P = lambda * normal;
vA -= mA * P;
wA -= iA * MathUtils.Cross(vcp.rA, P);
vB += mB * P;
wB += iB * MathUtils.Cross(vcp.rB, P);
}
}
else
{
// Block solver developed in collaboration with Dirk Gregorius (back in 01/07 on Box2D_Lite).
// Build the mini LCP for this contact patch
//
// vn = A * x + b, vn >= 0, x >= 0 and vn_i * x_i = 0 with i = 1..2
//
// A = J * W * JT and J = ( -n, -r1 x n, n, r2 x n )
// b = vn0 - velocityBias
//
// The system is solved using the "Total enumeration method" (s. Murty). The complementary constraint vn_i * x_i
// implies that we must have in any solution either vn_i = 0 or x_i = 0. So for the 2D contact problem the cases
// vn1 = 0 and vn2 = 0, x1 = 0 and x2 = 0, x1 = 0 and vn2 = 0, x2 = 0 and vn1 = 0 need to be tested. The first valid
// solution that satisfies the problem is chosen.
//
// In order to account of the accumulated impulse 'a' (because of the iterative nature of the solver which only requires
// that the accumulated impulse is clamped and not the incremental impulse) we change the impulse variable (x_i).
//
// Substitute:
//
// x = a + d
//
// a := old total impulse
// x := new total impulse
// d := incremental impulse
//
// For the current iteration we extend the formula for the incremental impulse
// to compute the new total impulse:
//
// vn = A * d + b
// = A * (x - a) + b
// = A * x + b - A * a
// = A * x + b'
// b' = b - A * a;
VelocityConstraintPoint cp1 = vc.Points[0];
VelocityConstraintPoint cp2 = vc.Points[1];
Vector2 a = new Vector2(cp1.NormalImpulse, cp2.NormalImpulse);
System.Diagnostics.Debug.Assert(a.X >= 0.0f && a.Y >= 0.0f);
// Relative velocity at contact
Vector2 dv1 = vB + MathUtils.Cross(wB, cp1.rB) - vA - MathUtils.Cross(wA, cp1.rA);
Vector2 dv2 = vB + MathUtils.Cross(wB, cp2.rB) - vA - MathUtils.Cross(wA, cp2.rA);
// Compute normal velocity
float vn1 = Vector2.Dot(dv1, normal);
float vn2 = Vector2.Dot(dv2, normal);
Vector2 b = Vector2.Zero;
b.X = vn1 - cp1.VelocityBias;
b.Y = vn2 - cp2.VelocityBias;
const float k_errorTol = 1e-3f;
// Compute b'
b -= MathUtils.Mul(ref vc.K, a);
for (;;)
{
//
// Case 1: vn = 0
//
// 0 = A * x + b'
//
// Solve for x:
//
// x = - inv(A) * b'
//
Vector2 x = -MathUtils.Mul(ref vc.NormalMass, b);
if (x.X >= 0.0f && x.Y >= 0.0f)
{
// Get the incremental impulse
Vector2 d = x - a;
// Apply incremental impulse
Vector2 P1 = d.X * normal;
Vector2 P2 = d.Y * normal;
vA -= mA * (P1 + P2);
wA -= iA * (MathUtils.Cross(cp1.rA, P1) + MathUtils.Cross(cp2.rA, P2));
vB += mB * (P1 + P2);
wB += iB * (MathUtils.Cross(cp1.rB, P1) + MathUtils.Cross(cp2.rB, P2));
// Accumulate
cp1.NormalImpulse = x.X;
cp2.NormalImpulse = x.Y;
#if B2_DEBUG_SOLVER
// Postconditions
dv1 = vB + MathUtils.Cross(wB, cp1.rB) - vA - MathUtils.Cross(wA, cp1.rA);
dv2 = vB + MathUtils.Cross(wB, cp2.rB) - vA - MathUtils.Cross(wA, cp2.rA);
// Compute normal velocity
vn1 = Vector2.Dot(dv1, normal);
vn2 = Vector2.Dot(dv2, normal);
Debug.Assert(Math.Abs(vn1 - cp1.VelocityBias) < k_errorTol);
Debug.Assert(Math.Abs(vn2 - cp2.VelocityBias) < k_errorTol);
#endif
break;
}
//
// Case 2: vn1 = 0 and x2 = 0
//
// 0 = a11 * x1 + a12 * 0 + b1'
// vn2 = a21 * x1 + a22 * 0 + b2'
//
x.X = -cp1.NormalMass * b.X;
x.Y = 0.0f;
vn1 = 0.0f;
vn2 = vc.K.ex.Y * x.X + b.Y;
if (x.X >= 0.0f && vn2 >= 0.0f)
{
// Get the incremental impulse
Vector2 d = x - a;
// Apply incremental impulse
Vector2 P1 = d.X * normal;
Vector2 P2 = d.Y * normal;
vA -= mA * (P1 + P2);
wA -= iA * (MathUtils.Cross(cp1.rA, P1) + MathUtils.Cross(cp2.rA, P2));
vB += mB * (P1 + P2);
wB += iB * (MathUtils.Cross(cp1.rB, P1) + MathUtils.Cross(cp2.rB, P2));
// Accumulate
cp1.NormalImpulse = x.X;
cp2.NormalImpulse = x.Y;
#if B2_DEBUG_SOLVER
// Postconditions
dv1 = vB + MathUtils.Cross(wB, cp1.rB) - vA - MathUtils.Cross(wA, cp1.rA);
// Compute normal velocity
vn1 = Vector2.Dot(dv1, normal);
Debug.Assert(Math.Abs(vn1 - cp1.VelocityBias) < k_errorTol);
#endif
break;
}
//
// Case 3: vn2 = 0 and x1 = 0
//
// vn1 = a11 * 0 + a12 * x2 + b1'
// 0 = a21 * 0 + a22 * x2 + b2'
//
x.X = 0.0f;
x.Y = -cp2.NormalMass * b.Y;
vn1 = vc.K.ey.X * x.Y + b.X;
vn2 = 0.0f;
if (x.Y >= 0.0f && vn1 >= 0.0f)
{
// Resubstitute for the incremental impulse
Vector2 d = x - a;
// Apply incremental impulse
Vector2 P1 = d.X * normal;
Vector2 P2 = d.Y * normal;
vA -= mA * (P1 + P2);
wA -= iA * (MathUtils.Cross(cp1.rA, P1) + MathUtils.Cross(cp2.rA, P2));
vB += mB * (P1 + P2);
wB += iB * (MathUtils.Cross(cp1.rB, P1) + MathUtils.Cross(cp2.rB, P2));
// Accumulate
cp1.NormalImpulse = x.X;
cp2.NormalImpulse = x.Y;
#if B2_DEBUG_SOLVER
// Postconditions
dv2 = vB + MathUtils.Cross(wB, cp2.rB) - vA - MathUtils.Cross(wA, cp2.rA);
// Compute normal velocity
vn2 = Vector2.Dot(dv2, normal);
Debug.Assert(Math.Abs(vn2 - cp2.VelocityBias) < k_errorTol);
#endif
break;
}
//
// Case 4: x1 = 0 and x2 = 0
//
// vn1 = b1
// vn2 = b2;
x.X = 0.0f;
x.Y = 0.0f;
vn1 = b.X;
vn2 = b.Y;
if (vn1 >= 0.0f && vn2 >= 0.0f)
{
// Resubstitute for the incremental impulse
Vector2 d = x - a;
// Apply incremental impulse
Vector2 P1 = d.X * normal;
Vector2 P2 = d.Y * normal;
vA -= mA * (P1 + P2);
wA -= iA * (MathUtils.Cross(cp1.rA, P1) + MathUtils.Cross(cp2.rA, P2));
vB += mB * (P1 + P2);
wB += iB * (MathUtils.Cross(cp1.rB, P1) + MathUtils.Cross(cp2.rB, P2));
// Accumulate
cp1.NormalImpulse = x.X;
cp2.NormalImpulse = x.Y;
break;
}
// No solution, give up. This is hit sometimes, but it doesn't seem to matter.
break;
}
}
_velocities[indexA].V = vA;
_velocities[indexA].W = wA;
_velocities[indexB].V = vB;
_velocities[indexB].W = wB;
}
}
public void StoreImpulses()
{
for (int i = 0; i < _count; ++i)
{
ContactVelocityConstraint vc = VelocityConstraints[i];
Manifold manifold = _contacts[vc.ContactIndex].Manifold;
for (int j = 0; j < vc.PointCount; ++j)
{
ManifoldPoint point = manifold.Points[j];
point.NormalImpulse = vc.Points[j].NormalImpulse;
point.TangentImpulse = vc.Points[j].TangentImpulse;
manifold.Points[j] = point;
}
_contacts[vc.ContactIndex].Manifold = manifold;
}
}
public bool SolvePositionConstraints()
{
float minSeparation = 0.0f;
for (int i = 0; i < _count; ++i)
{
ContactPositionConstraint pc = _positionConstraints[i];
int indexA = pc.IndexA;
int indexB = pc.IndexB;
Vector2 localCenterA = pc.LocalCenterA;
float mA = pc.InvMassA;
float iA = pc.InvIA;
Vector2 localCenterB = pc.LocalCenterB;
float mB = pc.InvMassB;
float iB = pc.InvIB;
int pointCount = pc.PointCount;
Vector2 cA = _positions[indexA].C;
float aA = _positions[indexA].A;
Vector2 cB = _positions[indexB].C;
float aB = _positions[indexB].A;
// Solve normal constraints
for (int j = 0; j < pointCount; ++j)
{
Transform xfA = new Transform();
Transform xfB = new Transform();
xfA.q.Set(aA);
xfB.q.Set(aB);
xfA.p = cA - MathUtils.Mul(xfA.q, localCenterA);
xfB.p = cB - MathUtils.Mul(xfB.q, localCenterB);
PositionSolverManifold.Initialize(pc, xfA, xfB, j, out Vector2 normal, out Vector2 point, out float separation);
Vector2 rA = point - cA;
Vector2 rB = point - cB;
// Track max constraint error.
minSeparation = Math.Min(minSeparation, separation);
// Prevent large corrections and allow slop.
float C = MathUtils.Clamp(Settings.Baumgarte * (separation + Settings.LinearSlop), -Settings.MaxLinearCorrection, 0.0f);
// Compute the effective mass.
float rnA = MathUtils.Cross(rA, normal);
float rnB = MathUtils.Cross(rB, normal);
float K = mA + mB + iA * rnA * rnA + iB * rnB * rnB;
// Compute normal impulse
float impulse = K > 0.0f ? -C / K : 0.0f;
Vector2 P = impulse * normal;
cA -= mA * P;
aA -= iA * MathUtils.Cross(rA, P);
cB += mB * P;
aB += iB * MathUtils.Cross(rB, P);
}
_positions[indexA].C = cA;
_positions[indexA].A = aA;
_positions[indexB].C = cB;
_positions[indexB].A = aB;
}
// We can't expect minSpeparation >= -b2_linearSlop because we don't
// push the separation above -b2_linearSlop.
return minSeparation >= -3.0f * Settings.LinearSlop;
}
// Sequential position solver for position constraints.
public bool SolveTOIPositionConstraints(int toiIndexA, int toiIndexB)
{
float minSeparation = 0.0f;
for (int i = 0; i < _count; ++i)
{
ContactPositionConstraint pc = _positionConstraints[i];
int indexA = pc.IndexA;
int indexB = pc.IndexB;
Vector2 localCenterA = pc.LocalCenterA;
Vector2 localCenterB = pc.LocalCenterB;
int pointCount = pc.PointCount;
float mA = 0.0f;
float iA = 0.0f;
if (indexA == toiIndexA || indexA == toiIndexB)
{
mA = pc.InvMassA;
iA = pc.InvIA;
}
float mB = 0.0f;
float iB = 0.0f;
if (indexB == toiIndexA || indexB == toiIndexB)
{
mB = pc.InvMassB;
iB = pc.InvIB;
}
Vector2 cA = _positions[indexA].C;
float aA = _positions[indexA].A;
Vector2 cB = _positions[indexB].C;
float aB = _positions[indexB].A;
// Solve normal constraints
for (int j = 0; j < pointCount; ++j)
{
Transform xfA = new Transform();
Transform xfB = new Transform();
xfA.q.Set(aA);
xfB.q.Set(aB);
xfA.p = cA - MathUtils.Mul(xfA.q, localCenterA);
xfB.p = cB - MathUtils.Mul(xfB.q, localCenterB);
PositionSolverManifold.Initialize(pc, xfA, xfB, j, out Vector2 normal, out Vector2 point, out float separation);
Vector2 rA = point - cA;
Vector2 rB = point - cB;
// Track max constraint error.
minSeparation = Math.Min(minSeparation, separation);
// Prevent large corrections and allow slop.
float C = MathUtils.Clamp(Settings.Baumgarte * (separation + Settings.LinearSlop), -Settings.MaxLinearCorrection, 0.0f);
// Compute the effective mass.
float rnA = MathUtils.Cross(rA, normal);
float rnB = MathUtils.Cross(rB, normal);
float K = mA + mB + iA * rnA * rnA + iB * rnB * rnB;
// Compute normal impulse
float impulse = K > 0.0f ? -C / K : 0.0f;
Vector2 P = impulse * normal;
cA -= mA * P;
aA -= iA * MathUtils.Cross(rA, P);
cB += mB * P;
aB += iB * MathUtils.Cross(rB, P);
}
_positions[indexA].C = cA;
_positions[indexA].A = aA;
_positions[indexB].C = cB;
_positions[indexB].A = aB;
}
// We can't expect minSpeparation >= -b2_linearSlop because we don't
// push the separation above -b2_linearSlop.
return minSeparation >= -1.5f * Settings.LinearSlop;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using Test.Cryptography;
using Xunit;
namespace System.Security.Cryptography.Pkcs.Tests
{
public static class TimestampTokenTests
{
[Theory]
[InlineData(nameof(TimestampTokenTestData.FreeTsaDotOrg1))]
[InlineData(nameof(TimestampTokenTestData.Symantec1))]
[InlineData(nameof(TimestampTokenTestData.DigiCert1))]
public static void ParseDocument(string testDataName)
{
TimestampTokenTestData testData = TimestampTokenTestData.GetTestData(testDataName);
TestParseDocument(testData.FullTokenBytes, testData, testData.FullTokenBytes.Length);
}
[Theory]
[InlineData(nameof(TimestampTokenTestData.FreeTsaDotOrg1))]
[InlineData(nameof(TimestampTokenTestData.Symantec1))]
[InlineData(nameof(TimestampTokenTestData.DigiCert1))]
public static void ParseDocument_ExcessData(string testDataName)
{
TimestampTokenTestData testData = TimestampTokenTestData.GetTestData(testDataName);
int baseLen = testData.FullTokenBytes.Length;
byte[] tooMuchData = new byte[baseLen + 30];
testData.FullTokenBytes.CopyTo(tooMuchData);
// Look like an octet string of the remainder of the payload. Should be ignored.
tooMuchData[baseLen] = 0x04;
tooMuchData[baseLen + 1] = 28;
TestParseDocument(tooMuchData, testData, baseLen);
}
private static void TestParseDocument(
ReadOnlyMemory<byte> tokenBytes,
TimestampTokenTestData testData,
int? expectedBytesRead)
{
int bytesRead;
Rfc3161TimestampToken token;
Assert.True(
Rfc3161TimestampToken.TryDecode(tokenBytes, out token, out bytesRead),
"Rfc3161TimestampToken.TryDecode");
if (expectedBytesRead != null)
{
Assert.Equal(expectedBytesRead.Value, bytesRead);
}
Assert.NotNull(token);
TimestampTokenInfoTests.AssertEqual(testData, token.TokenInfo);
SignedCms signedCms = token.AsSignedCms();
Assert.NotNull(signedCms);
Assert.Equal(Oids.TstInfo, signedCms.ContentInfo.ContentType.Value);
Assert.Equal(
testData.TokenInfoBytes.ByteArrayToHex(),
signedCms.ContentInfo.Content.ByteArrayToHex());
if (testData.EmbeddedSigningCertificate != null)
{
Assert.NotNull(signedCms.SignerInfos[0].Certificate);
Assert.Equal(
testData.EmbeddedSigningCertificate.Value.ByteArrayToHex(),
signedCms.SignerInfos[0].Certificate.RawData.ByteArrayToHex());
// Assert.NoThrow
signedCms.CheckSignature(true);
}
else
{
Assert.Null(signedCms.SignerInfos[0].Certificate);
using (var signerCert = new X509Certificate2(testData.ExternalCertificateBytes))
{
// Assert.NoThrow
signedCms.CheckSignature(
new X509Certificate2Collection(signerCert),
true);
}
}
X509Certificate2 returnedCert;
ReadOnlySpan<byte> messageContentSpan = testData.MessageContent.Span;
X509Certificate2Collection candidates = null;
if (testData.EmbeddedSigningCertificate != null)
{
Assert.True(
token.VerifySignatureForData(messageContentSpan, out returnedCert),
"token.VerifySignatureForData(correct)");
Assert.NotNull(returnedCert);
Assert.Equal(signedCms.SignerInfos[0].Certificate, returnedCert);
}
else
{
candidates = new X509Certificate2Collection
{
new X509Certificate2(testData.ExternalCertificateBytes),
};
Assert.False(
token.VerifySignatureForData(messageContentSpan, out returnedCert),
"token.VerifySignatureForData(correct, no cert)");
Assert.Null(returnedCert);
Assert.True(
token.VerifySignatureForData(messageContentSpan, out returnedCert, candidates),
"token.VerifySignatureForData(correct, certs)");
Assert.NotNull(returnedCert);
Assert.Equal(candidates[0], returnedCert);
}
X509Certificate2 previousCert = returnedCert;
Assert.False(
token.VerifySignatureForData(messageContentSpan.Slice(1), out returnedCert, candidates),
"token.VerifySignatureForData(incorrect)");
Assert.Null(returnedCert);
byte[] messageHash = testData.HashBytes.ToArray();
Assert.False(
token.VerifySignatureForHash(messageHash, HashAlgorithmName.MD5, out returnedCert, candidates),
"token.VerifyHash(correct, MD5)");
Assert.Null(returnedCert);
Assert.False(
token.VerifySignatureForHash(messageHash, new Oid(Oids.Md5), out returnedCert, candidates),
"token.VerifyHash(correct, Oid(MD5))");
Assert.Null(returnedCert);
Assert.True(
token.VerifySignatureForHash(messageHash, new Oid(testData.HashAlgorithmId), out returnedCert, candidates),
"token.VerifyHash(correct, Oid(algId))");
Assert.NotNull(returnedCert);
Assert.Equal(previousCert, returnedCert);
messageHash[0] ^= 0xFF;
Assert.False(
token.VerifySignatureForHash(messageHash, new Oid(testData.HashAlgorithmId), out returnedCert, candidates),
"token.VerifyHash(incorrect, Oid(algId))");
Assert.Null(returnedCert);
}
[Fact]
public static void TryDecode_Fails_SignedCmsOfData()
{
Assert.False(
Rfc3161TimestampToken.TryDecode(
SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber,
out Rfc3161TimestampToken token,
out int bytesRead),
"Rfc3161TimestampToken.TryDecode");
Assert.Equal(0, bytesRead);
Assert.Null(token);
}
[Fact]
public static void TryDecode_Fails_Empty()
{
Assert.False(
Rfc3161TimestampToken.TryDecode(
ReadOnlyMemory<byte>.Empty,
out Rfc3161TimestampToken token,
out int bytesRead),
"Rfc3161TimestampToken.TryDecode");
Assert.Equal(0, bytesRead);
Assert.Null(token);
}
[Fact]
public static void TryDecode_Fails_EnvelopedCms()
{
byte[] encodedMessage =
("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253"
+ "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d010101050004818013"
+ "dc0eb2984a445d04a1f6246b8fe41f1d24507548d449d454d5bb5e0638d75ed101bf78c0155a5d208eb746755fbccbc86923"
+ "8443760a9ae94770d6373e0197be23a6a891f0c522ca96b3e8008bf23547474b7e24e7f32e8134df3862d84f4dea2470548e"
+ "c774dd74f149a56cdd966e141122900d00ad9d10ea1848541294a1302b06092a864886f70d010701301406082a864886f70d"
+ "030704089c8119f6cf6b174c8008bcea3a10d0737eb9").HexToByteArray();
Assert.False(
Rfc3161TimestampToken.TryDecode(
encodedMessage,
out Rfc3161TimestampToken token,
out int bytesRead),
"Rfc3161TimestampToken.TryDecode");
Assert.Equal(0, bytesRead);
Assert.Null(token);
}
[Fact]
public static void TryDecode_Fails_MalformedToken()
{
ContentInfo contentInfo = new ContentInfo(
new Oid(Oids.TstInfo, Oids.TstInfo),
new byte[] { 1 });
SignedCms cms = new SignedCms(contentInfo);
using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey())
{
cms.ComputeSignature(new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, cert));
}
Assert.False(
Rfc3161TimestampToken.TryDecode(
cms.Encode(),
out Rfc3161TimestampToken token,
out int bytesRead),
"Rfc3161TimestampToken.TryDecode");
Assert.Equal(0, bytesRead);
Assert.Null(token);
}
[Theory]
[InlineData(X509IncludeOption.WholeChain, SigningCertificateOption.ValidHashNoName)]
[InlineData(X509IncludeOption.None, SigningCertificateOption.ValidHashNoName)]
[InlineData(X509IncludeOption.WholeChain, SigningCertificateOption.ValidHashWithName)]
[InlineData(X509IncludeOption.None, SigningCertificateOption.ValidHashWithName)]
public static void MatchV1(X509IncludeOption includeOption, SigningCertificateOption v1Option)
{
CustomBuild_CertMatch(
Certificates.ValidLookingTsaCert,
new DateTimeOffset(2018, 1, 10, 17, 21, 11, 802, TimeSpan.Zero),
v1Option,
SigningCertificateOption.Omit,
includeOption: includeOption);
}
[Theory]
[InlineData(X509IncludeOption.WholeChain)]
[InlineData(X509IncludeOption.None)]
public static void CertHashMismatchV1(X509IncludeOption includeOption)
{
CustomBuild_CertMismatch(
Certificates.ValidLookingTsaCert,
new DateTimeOffset(2018, 1, 10, 17, 21, 11, 802, TimeSpan.Zero),
SigningCertificateOption.InvalidHashNoName,
SigningCertificateOption.Omit,
includeOption: includeOption);
}
[Theory]
[InlineData(
X509IncludeOption.WholeChain,
SigningCertificateOption.ValidHashWithInvalidName,
SubjectIdentifierType.SubjectKeyIdentifier)]
[InlineData(
X509IncludeOption.None,
SigningCertificateOption.ValidHashWithInvalidName,
SubjectIdentifierType.SubjectKeyIdentifier)]
[InlineData(
X509IncludeOption.WholeChain,
SigningCertificateOption.ValidHashWithInvalidName,
SubjectIdentifierType.IssuerAndSerialNumber)]
[InlineData(
X509IncludeOption.None,
SigningCertificateOption.ValidHashWithInvalidName,
SubjectIdentifierType.IssuerAndSerialNumber)]
public static void CertMismatchIssuerAndSerialV1(
X509IncludeOption includeOption,
SigningCertificateOption v1Option,
SubjectIdentifierType identifierType)
{
CustomBuild_CertMismatch(
Certificates.ValidLookingTsaCert,
new DateTimeOffset(2018, 1, 10, 17, 21, 11, 802, TimeSpan.Zero),
v1Option,
SigningCertificateOption.Omit,
includeOption: includeOption,
identifierType: identifierType);
}
[Theory]
[InlineData(
X509IncludeOption.WholeChain,
SigningCertificateOption.ValidHashNoName,
null)]
[InlineData(
X509IncludeOption.None,
SigningCertificateOption.ValidHashNoName,
null)]
[InlineData(
X509IncludeOption.WholeChain,
SigningCertificateOption.ValidHashWithName,
"MD5")]
[InlineData(
X509IncludeOption.None,
SigningCertificateOption.ValidHashWithName,
"MD5")]
[InlineData(
X509IncludeOption.WholeChain,
SigningCertificateOption.ValidHashWithName,
"SHA1")]
[InlineData(
X509IncludeOption.None,
SigningCertificateOption.ValidHashWithName,
"SHA1")]
[InlineData(
X509IncludeOption.WholeChain,
SigningCertificateOption.ValidHashWithName,
"SHA384")]
[InlineData(
X509IncludeOption.None,
SigningCertificateOption.ValidHashWithName,
"SHA384")]
public static void MatchV2(
X509IncludeOption includeOption,
SigningCertificateOption v2Option,
string hashAlgName)
{
CustomBuild_CertMatch(
Certificates.ValidLookingTsaCert,
new DateTimeOffset(2018, 1, 10, 17, 21, 11, 802, TimeSpan.Zero),
SigningCertificateOption.Omit,
v2Option,
hashAlgName == null ? default(HashAlgorithmName) : new HashAlgorithmName(hashAlgName),
includeOption);
}
[Theory]
[InlineData(X509IncludeOption.WholeChain, null)]
[InlineData(X509IncludeOption.None, null)]
[InlineData(X509IncludeOption.WholeChain, "MD5")]
[InlineData(X509IncludeOption.None, "MD5")]
[InlineData(X509IncludeOption.WholeChain, "SHA1")]
[InlineData(X509IncludeOption.None, "SHA1")]
[InlineData(X509IncludeOption.WholeChain, "SHA384")]
[InlineData(X509IncludeOption.None, "SHA384")]
public static void CertHashMismatchV2(X509IncludeOption includeOption, string hashAlgName)
{
CustomBuild_CertMismatch(
Certificates.ValidLookingTsaCert,
new DateTimeOffset(2018, 1, 10, 17, 21, 11, 802, TimeSpan.Zero),
SigningCertificateOption.Omit,
SigningCertificateOption.InvalidHashNoName,
hashAlgName == null ? default(HashAlgorithmName) : new HashAlgorithmName(hashAlgName),
includeOption: includeOption);
}
[Theory]
[InlineData(
X509IncludeOption.WholeChain,
SigningCertificateOption.ValidHashWithInvalidName,
SubjectIdentifierType.SubjectKeyIdentifier,
null)]
[InlineData(
X509IncludeOption.None,
SigningCertificateOption.ValidHashWithInvalidName,
SubjectIdentifierType.SubjectKeyIdentifier,
null)]
[InlineData(
X509IncludeOption.WholeChain,
SigningCertificateOption.ValidHashWithInvalidName,
SubjectIdentifierType.SubjectKeyIdentifier,
"SHA384")]
[InlineData(
X509IncludeOption.None,
SigningCertificateOption.ValidHashWithInvalidName,
SubjectIdentifierType.SubjectKeyIdentifier,
"SHA384")]
[InlineData(
X509IncludeOption.WholeChain,
SigningCertificateOption.ValidHashWithInvalidName,
SubjectIdentifierType.IssuerAndSerialNumber,
null)]
[InlineData(
X509IncludeOption.None,
SigningCertificateOption.ValidHashWithInvalidName,
SubjectIdentifierType.IssuerAndSerialNumber,
null)]
[InlineData(
X509IncludeOption.WholeChain,
SigningCertificateOption.ValidHashWithInvalidName,
SubjectIdentifierType.IssuerAndSerialNumber,
"SHA384")]
[InlineData(
X509IncludeOption.None,
SigningCertificateOption.ValidHashWithInvalidName,
SubjectIdentifierType.IssuerAndSerialNumber,
"SHA384")]
public static void CertMismatchIssuerAndSerialV2(
X509IncludeOption includeOption,
SigningCertificateOption v2Option,
SubjectIdentifierType identifierType,
string hashAlgName)
{
CustomBuild_CertMismatch(
Certificates.ValidLookingTsaCert,
new DateTimeOffset(2018, 1, 10, 17, 21, 11, 802, TimeSpan.Zero),
SigningCertificateOption.Omit,
v2Option,
hashAlgName == null ? default(HashAlgorithmName) : new HashAlgorithmName(hashAlgName),
includeOption: includeOption,
identifierType: identifierType);
}
[Theory]
[InlineData(
X509IncludeOption.WholeChain,
SigningCertificateOption.ValidHashNoName,
SigningCertificateOption.ValidHashNoName,
null)]
[InlineData(
X509IncludeOption.WholeChain,
SigningCertificateOption.ValidHashNoName,
SigningCertificateOption.ValidHashNoName,
"SHA512")]
[InlineData(
X509IncludeOption.None,
SigningCertificateOption.ValidHashNoName,
SigningCertificateOption.ValidHashNoName,
null)]
[InlineData(
X509IncludeOption.None,
SigningCertificateOption.ValidHashNoName,
SigningCertificateOption.ValidHashNoName,
"SHA512")]
[InlineData(
X509IncludeOption.WholeChain,
SigningCertificateOption.ValidHashNoName,
SigningCertificateOption.ValidHashWithName,
null)]
[InlineData(
X509IncludeOption.WholeChain,
SigningCertificateOption.ValidHashNoName,
SigningCertificateOption.ValidHashWithName,
"SHA384")]
[InlineData(
X509IncludeOption.None,
SigningCertificateOption.ValidHashNoName,
SigningCertificateOption.ValidHashWithName,
null)]
[InlineData(
X509IncludeOption.None,
SigningCertificateOption.ValidHashNoName,
SigningCertificateOption.ValidHashWithName,
"SHA384")]
[InlineData(
X509IncludeOption.WholeChain,
SigningCertificateOption.ValidHashWithName,
SigningCertificateOption.ValidHashNoName,
null)]
[InlineData(
X509IncludeOption.WholeChain,
SigningCertificateOption.ValidHashWithName,
SigningCertificateOption.ValidHashNoName,
"SHA512")]
[InlineData(
X509IncludeOption.None,
SigningCertificateOption.ValidHashWithName,
SigningCertificateOption.ValidHashNoName,
null)]
[InlineData(
X509IncludeOption.None,
SigningCertificateOption.ValidHashWithName,
SigningCertificateOption.ValidHashNoName,
"SHA512")]
[InlineData(
X509IncludeOption.WholeChain,
SigningCertificateOption.ValidHashWithName,
SigningCertificateOption.ValidHashWithName,
null)]
[InlineData(
X509IncludeOption.WholeChain,
SigningCertificateOption.ValidHashWithName,
SigningCertificateOption.ValidHashWithName,
"SHA384")]
[InlineData(
X509IncludeOption.None,
SigningCertificateOption.ValidHashWithName,
SigningCertificateOption.ValidHashWithName,
null)]
[InlineData(
X509IncludeOption.None,
SigningCertificateOption.ValidHashWithName,
SigningCertificateOption.ValidHashWithName,
"SHA384")]
public static void CertMatchV1AndV2(
X509IncludeOption includeOption,
SigningCertificateOption v1Option,
SigningCertificateOption v2Option,
string hashAlgName)
{
CustomBuild_CertMatch(
Certificates.ValidLookingTsaCert,
new DateTimeOffset(2018, 1, 10, 17, 21, 11, 802, TimeSpan.Zero),
v1Option,
v2Option,
hashAlgName == null ? default(HashAlgorithmName) : new HashAlgorithmName(hashAlgName),
includeOption);
}
[Theory]
[InlineData(
X509IncludeOption.None,
SigningCertificateOption.InvalidHashNoName,
SigningCertificateOption.ValidHashWithName,
SubjectIdentifierType.IssuerAndSerialNumber,
null)]
[InlineData(
X509IncludeOption.WholeChain,
SigningCertificateOption.ValidHashWithInvalidSerial,
SigningCertificateOption.ValidHashWithName,
SubjectIdentifierType.IssuerAndSerialNumber,
"SHA384")]
[InlineData(
X509IncludeOption.WholeChain,
SigningCertificateOption.ValidHashWithInvalidName,
SigningCertificateOption.InvalidHashNoName,
SubjectIdentifierType.SubjectKeyIdentifier,
null)]
[InlineData(
X509IncludeOption.None,
SigningCertificateOption.ValidHashWithName,
SigningCertificateOption.InvalidHashNoName,
SubjectIdentifierType.SubjectKeyIdentifier,
"SHA512")]
[InlineData(
X509IncludeOption.WholeChain,
SigningCertificateOption.InvalidHashWithInvalidSerial,
SigningCertificateOption.ValidHashNoName,
SubjectIdentifierType.IssuerAndSerialNumber,
null)]
public static void CertMismatchV1OrV2(
X509IncludeOption includeOption,
SigningCertificateOption v1Option,
SigningCertificateOption v2Option,
SubjectIdentifierType identifierType,
string hashAlgName)
{
CustomBuild_CertMismatch(
Certificates.ValidLookingTsaCert,
new DateTimeOffset(2018, 1, 10, 17, 21, 11, 802, TimeSpan.Zero),
v1Option,
v2Option,
hashAlgName == null ? default(HashAlgorithmName) : new HashAlgorithmName(hashAlgName),
includeOption: includeOption,
identifierType: identifierType);
}
[Theory]
[InlineData(X509IncludeOption.WholeChain)]
[InlineData(X509IncludeOption.None)]
public static void TimestampTooOld(X509IncludeOption includeOption)
{
CertLoader loader = Certificates.ValidLookingTsaCert;
DateTimeOffset referenceTime;
using (X509Certificate2 cert = loader.GetCertificate())
{
referenceTime = cert.NotBefore.AddSeconds(-1);
}
CustomBuild_CertMismatch(
loader,
referenceTime,
SigningCertificateOption.ValidHashNoName,
SigningCertificateOption.Omit,
includeOption: includeOption);
}
[Theory]
[InlineData(X509IncludeOption.WholeChain)]
[InlineData(X509IncludeOption.None)]
public static void TimestampTooNew(X509IncludeOption includeOption)
{
CertLoader loader = Certificates.ValidLookingTsaCert;
DateTimeOffset referenceTime;
using (X509Certificate2 cert = loader.GetCertificate())
{
referenceTime = cert.NotAfter.AddSeconds(1);
}
CustomBuild_CertMismatch(
loader,
referenceTime,
SigningCertificateOption.ValidHashNoName,
SigningCertificateOption.Omit,
includeOption: includeOption);
}
[Theory]
[InlineData(X509IncludeOption.WholeChain)]
[InlineData(X509IncludeOption.None)]
public static void NoEkuExtension(X509IncludeOption includeOption)
{
CertLoader loader = Certificates.RSA2048SignatureOnly;
DateTimeOffset referenceTime;
using (X509Certificate2 cert = loader.GetCertificate())
{
referenceTime = cert.NotAfter.AddDays(-1);
Assert.Equal(0, cert.Extensions.OfType<X509EnhancedKeyUsageExtension>().Count());
}
CustomBuild_CertMismatch(
loader,
referenceTime,
SigningCertificateOption.ValidHashNoName,
SigningCertificateOption.Omit,
includeOption: includeOption);
}
[Theory]
[InlineData(X509IncludeOption.WholeChain)]
[InlineData(X509IncludeOption.None)]
public static void TwoEkuExtensions(X509IncludeOption includeOption)
{
CertLoader loader = Certificates.TwoEkuTsaCert;
DateTimeOffset referenceTime;
using (X509Certificate2 cert = loader.GetCertificate())
{
referenceTime = cert.NotAfter.AddDays(-1);
var ekuExts = cert.Extensions.OfType<X509EnhancedKeyUsageExtension>().ToList();
Assert.Equal(2, ekuExts.Count);
// Make sure we're validating that "early success" doesn't happen.
Assert.Contains(
Oids.TimeStampingPurpose,
ekuExts[0].EnhancedKeyUsages.OfType<Oid>().Select(o => o.Value));
}
CustomBuild_CertMismatch(
loader,
referenceTime,
SigningCertificateOption.ValidHashNoName,
SigningCertificateOption.Omit,
includeOption: includeOption);
}
[Theory]
[InlineData(X509IncludeOption.WholeChain)]
[InlineData(X509IncludeOption.None)]
public static void NonCriticalEkuExtension(X509IncludeOption includeOption)
{
CertLoader loader = Certificates.NonCriticalTsaEku;
DateTimeOffset referenceTime;
using (X509Certificate2 cert = loader.GetCertificate())
{
referenceTime = cert.NotAfter.AddDays(-1);
var ekuExts = cert.Extensions.OfType<X509EnhancedKeyUsageExtension>().ToList();
Assert.Equal(1, ekuExts.Count);
Assert.False(ekuExts[0].Critical, "ekuExts[0].Critical");
}
CustomBuild_CertMismatch(
loader,
referenceTime,
SigningCertificateOption.ValidHashNoName,
SigningCertificateOption.Omit,
includeOption: includeOption);
}
[Theory]
[InlineData(X509IncludeOption.WholeChain)]
[InlineData(X509IncludeOption.None)]
public static void NoTsaEku(X509IncludeOption includeOption)
{
CertLoader loader = Certificates.TlsClientServerCert;
DateTimeOffset referenceTime;
using (X509Certificate2 cert = loader.GetCertificate())
{
referenceTime = cert.NotAfter.AddDays(-1);
}
CustomBuild_CertMismatch(
loader,
referenceTime,
SigningCertificateOption.ValidHashNoName,
SigningCertificateOption.Omit,
includeOption: includeOption);
}
private static void CustomBuild_CertMatch(
CertLoader loader,
DateTimeOffset referenceTime,
SigningCertificateOption v1Option,
SigningCertificateOption v2Option,
HashAlgorithmName v2AlgorithmName = default,
X509IncludeOption includeOption = default,
SubjectIdentifierType identifierType = SubjectIdentifierType.IssuerAndSerialNumber)
{
byte[] tokenBytes = BuildCustomToken(
loader,
referenceTime,
v1Option,
v2Option,
v2AlgorithmName,
includeOption,
identifierType);
Rfc3161TimestampToken token;
Assert.True(Rfc3161TimestampToken.TryDecode(tokenBytes, out token, out int bytesRead));
Assert.Equal(tokenBytes.Length, bytesRead);
Assert.NotNull(token);
Assert.Equal(referenceTime, token.TokenInfo.Timestamp);
using (X509Certificate2 cert = Certificates.ValidLookingTsaCert.GetCertificate())
{
Assert.True(
token.VerifySignatureForHash(
token.TokenInfo.GetMessageHash().Span,
token.TokenInfo.HashAlgorithmId,
out X509Certificate2 signer,
new X509Certificate2Collection(cert)));
Assert.Equal(cert, signer);
}
}
private static void CustomBuild_CertMismatch(
CertLoader loader,
DateTimeOffset referenceTime,
SigningCertificateOption v1Option,
SigningCertificateOption v2Option,
HashAlgorithmName v2AlgorithmName = default,
X509IncludeOption includeOption = default,
SubjectIdentifierType identifierType = SubjectIdentifierType.IssuerAndSerialNumber)
{
byte[] tokenBytes = BuildCustomToken(
loader,
referenceTime,
v1Option,
v2Option,
v2AlgorithmName,
includeOption,
identifierType);
Rfc3161TimestampToken token;
bool willParse = includeOption == X509IncludeOption.None;
if (willParse && identifierType == SubjectIdentifierType.IssuerAndSerialNumber)
{
// Because IASN matches against the ESSCertId(V2) directly it will reject the token.
switch (v1Option)
{
case SigningCertificateOption.ValidHashWithInvalidName:
case SigningCertificateOption.ValidHashWithInvalidSerial:
case SigningCertificateOption.InvalidHashWithInvalidName:
case SigningCertificateOption.InvalidHashWithInvalidSerial:
willParse = false;
break;
}
switch (v2Option)
{
case SigningCertificateOption.ValidHashWithInvalidName:
case SigningCertificateOption.ValidHashWithInvalidSerial:
case SigningCertificateOption.InvalidHashWithInvalidName:
case SigningCertificateOption.InvalidHashWithInvalidSerial:
willParse = false;
break;
}
}
if (willParse)
{
Assert.True(Rfc3161TimestampToken.TryDecode(tokenBytes, out token, out int bytesRead));
Assert.NotNull(token);
Assert.Equal(tokenBytes.Length, bytesRead);
using (X509Certificate2 cert = loader.GetCertificate())
{
Assert.False(
token.VerifySignatureForHash(
token.TokenInfo.GetMessageHash().Span,
token.TokenInfo.HashAlgorithmId,
out X509Certificate2 signer,
new X509Certificate2Collection(cert)));
Assert.Null(signer);
}
}
else
{
Assert.False(Rfc3161TimestampToken.TryDecode(tokenBytes, out token, out int bytesRead));
Assert.Null(token);
Assert.Equal(0, bytesRead);
}
}
private static byte[] BuildCustomToken(
CertLoader cert,
DateTimeOffset timestamp,
SigningCertificateOption v1Option,
SigningCertificateOption v2Option,
HashAlgorithmName v2DigestAlg=default,
X509IncludeOption includeOption=X509IncludeOption.ExcludeRoot,
SubjectIdentifierType identifierType=SubjectIdentifierType.IssuerAndSerialNumber)
{
long accuracyMicroSeconds = (long)(TimeSpan.FromMinutes(1).TotalMilliseconds * 1000);
byte[] serialNumber = BitConverter.GetBytes(DateTimeOffset.UtcNow.Ticks);
Array.Reverse(serialNumber);
Rfc3161TimestampTokenInfo info = new Rfc3161TimestampTokenInfo(
new Oid("0.0", "0.0"),
new Oid(Oids.Sha384),
new byte[384 / 8],
serialNumber,
timestamp,
accuracyMicroSeconds,
isOrdering: true);
ContentInfo contentInfo = new ContentInfo(new Oid(Oids.TstInfo, Oids.TstInfo), info.Encode());
SignedCms cms = new SignedCms(contentInfo);
using (X509Certificate2 tsaCert = cert.TryGetCertificateWithPrivateKey())
{
CmsSigner signer = new CmsSigner(identifierType, tsaCert)
{
IncludeOption = includeOption
};
if (v1Option != SigningCertificateOption.Omit)
{
ExpandOption(v1Option, out bool validHash, out bool skipIssuerSerial, out bool validName, out bool validSerial);
// simple SigningCertificate
byte[] signingCertificateV1Bytes =
"301A3018301604140000000000000000000000000000000000000000".HexToByteArray();
if (validHash)
{
using (SHA1 hasher = SHA1.Create())
{
byte[] hash = hasher.ComputeHash(tsaCert.RawData);
Buffer.BlockCopy(
hash,
0,
signingCertificateV1Bytes,
signingCertificateV1Bytes.Length - hash.Length,
hash.Length);
}
}
if (!skipIssuerSerial)
{
byte[] footer = BuildIssuerAndSerialNumber(tsaCert, validName, validSerial);
signingCertificateV1Bytes[1] += (byte)footer.Length;
signingCertificateV1Bytes[3] += (byte)footer.Length;
signingCertificateV1Bytes[5] += (byte)footer.Length;
Assert.InRange(signingCertificateV1Bytes[1], 0, 127);
signingCertificateV1Bytes = signingCertificateV1Bytes.Concat(footer).ToArray();
}
signer.SignedAttributes.Add(
new AsnEncodedData("1.2.840.113549.1.9.16.2.12", signingCertificateV1Bytes));
}
if (v2Option != SigningCertificateOption.Omit)
{
byte[] attrBytes;
byte[] algBytes = Array.Empty<byte>();
byte[] hashBytes;
byte[] issuerNameBytes = Array.Empty<byte>();
if (v2DigestAlg != default)
{
switch (v2DigestAlg.Name)
{
case "MD5":
algBytes = "300C06082A864886F70D02050500".HexToByteArray();
break;
case "SHA1":
algBytes = "300906052B0E03021A0500".HexToByteArray();
break;
case "SHA256":
// Invalid under DER, because it's the default.
algBytes = "300D06096086480165030402010500".HexToByteArray();
break;
case "SHA384":
algBytes = "300D06096086480165030402020500".HexToByteArray();
break;
case "SHA512":
algBytes = "300D06096086480165030402030500".HexToByteArray();
break;
default:
throw new NotSupportedException(v2DigestAlg.Name);
}
}
else
{
v2DigestAlg = HashAlgorithmName.SHA256;
}
hashBytes = tsaCert.GetCertHash(v2DigestAlg);
ExpandOption(v2Option, out bool validHash, out bool skipIssuerSerial, out bool validName, out bool validSerial);
if (!validHash)
{
hashBytes[0] ^= 0xFF;
}
if (!skipIssuerSerial)
{
issuerNameBytes = BuildIssuerAndSerialNumber(tsaCert, validName, validSerial);
}
// hashBytes hasn't been wrapped in an OCTET STRING yet, so add 2 more.
int payloadSize = algBytes.Length + hashBytes.Length + issuerNameBytes.Length + 2;
Assert.InRange(payloadSize, 0, 123);
attrBytes = new byte[payloadSize + 6];
int index = 0;
// SEQUENCE (SigningCertificateV2)
attrBytes[index++] = 0x30;
attrBytes[index++] = (byte)(payloadSize + 4);
// SEQUENCE OF => certs
attrBytes[index++] = 0x30;
attrBytes[index++] = (byte)(payloadSize + 2);
// SEQUENCE (ESSCertIdV2)
attrBytes[index++] = 0x30;
attrBytes[index++] = (byte)payloadSize;
Buffer.BlockCopy(algBytes, 0, attrBytes, index, algBytes.Length);
index += algBytes.Length;
// OCTET STRING (Hash)
attrBytes[index++] = 0x04;
attrBytes[index++] = (byte)hashBytes.Length;
Buffer.BlockCopy(hashBytes, 0, attrBytes, index, hashBytes.Length);
index += hashBytes.Length;
Buffer.BlockCopy(issuerNameBytes, 0, attrBytes, index, issuerNameBytes.Length);
signer.SignedAttributes.Add(
new AsnEncodedData("1.2.840.113549.1.9.16.2.47", attrBytes));
}
cms.ComputeSignature(signer);
}
return cms.Encode();
}
private static byte[] BuildIssuerAndSerialNumber(X509Certificate2 tsaCert, bool validName, bool validSerial)
{
byte[] issuerNameBytes;
if (validName)
{
issuerNameBytes = tsaCert.IssuerName.RawData;
}
else
{
issuerNameBytes = new X500DistinguishedName("CN=No Match").RawData;
}
byte[] serialBytes = tsaCert.GetSerialNumber();
if (validSerial)
{
Array.Reverse(serialBytes);
}
else
{
// If the byte sequence was a palindrome it's still a match,
// so flip some bits.
serialBytes[0] ^= 0x7F;
}
if (issuerNameBytes.Length + serialBytes.Length > 80)
{
throw new NotSupportedException(
"Issuer name and serial length are bigger than this code can handle");
}
// SEQUENCE
// SEQUENCE
// CONTEXT-SPECIFIC 4
// [IssuerName]
// INTEGER
// [SerialNumber, big endian]
byte[] issuerAndSerialNumber = new byte[issuerNameBytes.Length + serialBytes.Length + 8];
issuerAndSerialNumber[0] = 0x30;
issuerAndSerialNumber[1] = (byte)(issuerAndSerialNumber.Length - 2);
issuerAndSerialNumber[2] = 0x30;
issuerAndSerialNumber[3] = (byte)(issuerNameBytes.Length + 2);
issuerAndSerialNumber[4] = 0xA4;
issuerAndSerialNumber[5] = (byte)(issuerNameBytes.Length);
Buffer.BlockCopy(issuerNameBytes, 0, issuerAndSerialNumber, 6, issuerNameBytes.Length);
issuerAndSerialNumber[issuerNameBytes.Length + 6] = 0x02;
issuerAndSerialNumber[issuerNameBytes.Length + 7] = (byte)serialBytes.Length;
Buffer.BlockCopy(serialBytes, 0, issuerAndSerialNumber, issuerNameBytes.Length + 8, serialBytes.Length);
return issuerAndSerialNumber;
}
private static void ExpandOption(
SigningCertificateOption option,
out bool validHash,
out bool skipIssuerSerial,
out bool validName,
out bool validSerial)
{
Assert.NotEqual(SigningCertificateOption.Omit, option);
validHash = option < SigningCertificateOption.InvalidHashNoName;
skipIssuerSerial =
option == SigningCertificateOption.ValidHashNoName ||
option == SigningCertificateOption.InvalidHashNoName;
if (skipIssuerSerial)
{
validName = validSerial = false;
}
else
{
validName =
option == SigningCertificateOption.ValidHashWithName ||
option == SigningCertificateOption.InvalidHashWithName ||
option == SigningCertificateOption.ValidHashWithInvalidSerial ||
option == SigningCertificateOption.InvalidHashWithInvalidSerial;
validSerial =
option == SigningCertificateOption.ValidHashWithName ||
option == SigningCertificateOption.InvalidHashWithName ||
option == SigningCertificateOption.ValidHashWithInvalidName ||
option == SigningCertificateOption.InvalidHashWithInvalidName;
}
}
public enum SigningCertificateOption
{
Omit,
ValidHashNoName,
ValidHashWithName,
ValidHashWithInvalidName,
ValidHashWithInvalidSerial,
InvalidHashNoName,
InvalidHashWithName,
InvalidHashWithInvalidName,
InvalidHashWithInvalidSerial,
}
}
}
| |
//-----------------------------------------------------------------------------
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the Microsoft Public License.
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//-----------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
namespace Microsoft.Cci.Pdb {
internal class PdbFunction {
static internal readonly Guid msilMetaData = new Guid(0xc6ea3fc9, 0x59b3, 0x49d6, 0xbc, 0x25,
0x09, 0x02, 0xbb, 0xab, 0xb4, 0x60);
static internal readonly IComparer byAddress = new PdbFunctionsByAddress();
static internal readonly IComparer byAddressAndToken = new PdbFunctionsByAddressAndToken();
//static internal readonly IComparer byToken = new PdbFunctionsByToken();
internal uint token;
internal uint slotToken;
internal uint tokenOfMethodWhoseUsingInfoAppliesToThisMethod;
//internal string name;
//internal string module;
//internal ushort flags;
internal uint segment;
internal uint address;
//internal uint length;
//internal byte[] metadata;
internal PdbScope[] scopes;
internal PdbSlot[] slots;
internal PdbConstant[] constants;
internal string[] usedNamespaces;
internal PdbLines[] lines;
internal ushort[]/*?*/ usingCounts;
internal IEnumerable<INamespaceScope>/*?*/ namespaceScopes;
internal string/*?*/ iteratorClass;
internal List<ILocalScope>/*?*/ iteratorScopes;
internal PdbSynchronizationInformation/*?*/ synchronizationInformation;
private static string StripNamespace(string module) {
int li = module.LastIndexOf('.');
if (li > 0) {
return module.Substring(li + 1);
}
return module;
}
internal static PdbFunction[] LoadManagedFunctions(/*string module,*/
BitAccess bits, uint limit,
bool readStrings) {
//string mod = StripNamespace(module);
int begin = bits.Position;
int count = 0;
while (bits.Position < limit) {
ushort siz;
ushort rec;
bits.ReadUInt16(out siz);
int star = bits.Position;
int stop = bits.Position + siz;
bits.Position = star;
bits.ReadUInt16(out rec);
switch ((SYM)rec) {
case SYM.S_GMANPROC:
case SYM.S_LMANPROC:
ManProcSym proc;
bits.ReadUInt32(out proc.parent);
bits.ReadUInt32(out proc.end);
bits.Position = (int)proc.end;
count++;
break;
case SYM.S_END:
bits.Position = stop;
break;
default:
//Console.WriteLine("{0,6}: {1:x2} {2}",
// bits.Position, rec, (SYM)rec);
bits.Position = stop;
break;
}
}
if (count == 0) {
return null;
}
bits.Position = begin;
PdbFunction[] funcs = new PdbFunction[count];
int func = 0;
while (bits.Position < limit) {
ushort siz;
ushort rec;
bits.ReadUInt16(out siz);
int star = bits.Position;
int stop = bits.Position + siz;
bits.ReadUInt16(out rec);
switch ((SYM)rec) {
case SYM.S_GMANPROC:
case SYM.S_LMANPROC:
ManProcSym proc;
//int offset = bits.Position;
bits.ReadUInt32(out proc.parent);
bits.ReadUInt32(out proc.end);
bits.ReadUInt32(out proc.next);
bits.ReadUInt32(out proc.len);
bits.ReadUInt32(out proc.dbgStart);
bits.ReadUInt32(out proc.dbgEnd);
bits.ReadUInt32(out proc.token);
bits.ReadUInt32(out proc.off);
bits.ReadUInt16(out proc.seg);
bits.ReadUInt8(out proc.flags);
bits.ReadUInt16(out proc.retReg);
if (readStrings) {
bits.ReadCString(out proc.name);
} else {
bits.SkipCString(out proc.name);
}
//Console.WriteLine("token={0:X8} [{1}::{2}]", proc.token, module, proc.name);
bits.Position = stop;
funcs[func++] = new PdbFunction(/*module,*/ proc, bits);
break;
default: {
//throw new PdbDebugException("Unknown SYMREC {0}", (SYM)rec);
bits.Position = stop;
break;
}
}
}
return funcs;
}
internal static void CountScopesAndSlots(BitAccess bits, uint limit,
out int constants, out int scopes, out int slots, out int usedNamespaces) {
int pos = bits.Position;
BlockSym32 block;
constants = 0;
slots = 0;
scopes = 0;
usedNamespaces = 0;
while (bits.Position < limit) {
ushort siz;
ushort rec;
bits.ReadUInt16(out siz);
int star = bits.Position;
int stop = bits.Position + siz;
bits.Position = star;
bits.ReadUInt16(out rec);
switch ((SYM)rec) {
case SYM.S_BLOCK32: {
bits.ReadUInt32(out block.parent);
bits.ReadUInt32(out block.end);
scopes++;
bits.Position = (int)block.end;
break;
}
case SYM.S_MANSLOT:
slots++;
bits.Position = stop;
break;
case SYM.S_UNAMESPACE:
usedNamespaces++;
bits.Position = stop;
break;
case SYM.S_MANCONSTANT:
constants++;
bits.Position = stop;
break;
default:
bits.Position = stop;
break;
}
}
bits.Position = pos;
}
internal PdbFunction() {
}
internal PdbFunction(/*string module, */ManProcSym proc, BitAccess bits) {
this.token = proc.token;
//this.module = module;
//this.name = proc.name;
//this.flags = proc.flags;
this.segment = proc.seg;
this.address = proc.off;
//this.length = proc.len;
if (proc.seg != 1) {
throw new PdbDebugException("Segment is {0}, not 1.", proc.seg);
}
if (proc.parent != 0 || proc.next != 0) {
throw new PdbDebugException("Warning parent={0}, next={1}",
proc.parent, proc.next);
}
//if (proc.dbgStart != 0 || proc.dbgEnd != 0) {
// throw new PdbDebugException("Warning DBG start={0}, end={1}",
// proc.dbgStart, proc.dbgEnd);
//}
int constantCount;
int scopeCount;
int slotCount;
int usedNamespacesCount;
CountScopesAndSlots(bits, proc.end, out constantCount, out scopeCount, out slotCount, out usedNamespacesCount);
int scope = constantCount > 0 || slotCount > 0 || usedNamespacesCount > 0 ? 1 : 0;
int slot = 0;
int constant = 0;
int usedNs = 0;
scopes = new PdbScope[scopeCount+scope];
slots = new PdbSlot[slotCount];
constants = new PdbConstant[constantCount];
usedNamespaces = new string[usedNamespacesCount];
if (scope > 0)
scopes[0] = new PdbScope(this.address, proc.len, slots, constants, usedNamespaces);
while (bits.Position < proc.end) {
ushort siz;
ushort rec;
bits.ReadUInt16(out siz);
int star = bits.Position;
int stop = bits.Position + siz;
bits.Position = star;
bits.ReadUInt16(out rec);
switch ((SYM)rec) {
case SYM.S_OEM: { // 0x0404
OemSymbol oem;
bits.ReadGuid(out oem.idOem);
bits.ReadUInt32(out oem.typind);
// internal byte[] rgl; // user data, force 4-byte alignment
if (oem.idOem == msilMetaData) {
string name = bits.ReadString();
if (name == "MD2") {
byte version;
bits.ReadUInt8(out version);
if (version == 4) {
byte count;
bits.ReadUInt8(out count);
bits.Align(4);
while (count-- > 0)
this.ReadCustomMetadata(bits);
}
} else if (name == "asyncMethodInfo") {
this.synchronizationInformation = new PdbSynchronizationInformation(bits);
}
bits.Position = stop;
break;
} else {
throw new PdbDebugException("OEM section: guid={0} ti={1}",
oem.idOem, oem.typind);
// bits.Position = stop;
}
}
case SYM.S_BLOCK32: {
BlockSym32 block = new BlockSym32();
bits.ReadUInt32(out block.parent);
bits.ReadUInt32(out block.end);
bits.ReadUInt32(out block.len);
bits.ReadUInt32(out block.off);
bits.ReadUInt16(out block.seg);
bits.SkipCString(out block.name);
bits.Position = stop;
scopes[scope++] = new PdbScope(this.address, block, bits, out slotToken);
bits.Position = (int)block.end;
break;
}
case SYM.S_MANSLOT:
slots[slot++] = new PdbSlot(bits);
bits.Position = stop;
break;
case SYM.S_MANCONSTANT:
constants[constant++] = new PdbConstant(bits);
bits.Position = stop;
break;
case SYM.S_UNAMESPACE:
bits.ReadCString(out usedNamespaces[usedNs++]);
bits.Position = stop;
break;
case SYM.S_END:
bits.Position = stop;
break;
default: {
//throw new PdbDebugException("Unknown SYM: {0}", (SYM)rec);
bits.Position = stop;
break;
}
}
}
if (bits.Position != proc.end) {
throw new PdbDebugException("Not at S_END");
}
ushort esiz;
ushort erec;
bits.ReadUInt16(out esiz);
bits.ReadUInt16(out erec);
if (erec != (ushort)SYM.S_END) {
throw new PdbDebugException("Missing S_END");
}
}
private void ReadCustomMetadata(BitAccess bits) {
int savedPosition = bits.Position;
byte version;
bits.ReadUInt8(out version);
if (version != 4) {
throw new PdbDebugException("Unknown custom metadata item version: {0}", version);
}
byte kind;
bits.ReadUInt8(out kind);
bits.Align(4);
uint numberOfBytesInItem;
bits.ReadUInt32(out numberOfBytesInItem);
switch (kind) {
case 0: this.ReadUsingInfo(bits); break;
case 1: this.ReadForwardInfo(bits); break;
case 2: break; // this.ReadForwardedToModuleInfo(bits); break;
case 3: this.ReadIteratorLocals(bits); break;
case 4: this.ReadForwardIterator(bits); break;
// TODO: handle unknown custom metadata, 5 & 6 are new with roslyn, see https://roslyn.codeplex.com/workitem/54
}
bits.Position = savedPosition+(int)numberOfBytesInItem;
}
private void ReadForwardIterator(BitAccess bits) {
this.iteratorClass = bits.ReadString();
}
private void ReadIteratorLocals(BitAccess bits) {
uint numberOfLocals;
bits.ReadUInt32(out numberOfLocals);
this.iteratorScopes = new List<ILocalScope>((int)numberOfLocals);
while (numberOfLocals-- > 0) {
uint ilStartOffset;
uint ilEndOffset;
bits.ReadUInt32(out ilStartOffset);
bits.ReadUInt32(out ilEndOffset);
this.iteratorScopes.Add(new PdbIteratorScope(ilStartOffset, ilEndOffset-ilStartOffset));
}
}
//private void ReadForwardedToModuleInfo(BitAccess bits) {
//}
private void ReadForwardInfo(BitAccess bits) {
bits.ReadUInt32(out this.tokenOfMethodWhoseUsingInfoAppliesToThisMethod);
}
private void ReadUsingInfo(BitAccess bits) {
ushort numberOfNamespaces;
bits.ReadUInt16(out numberOfNamespaces);
this.usingCounts = new ushort[numberOfNamespaces];
for (ushort i = 0; i < numberOfNamespaces; i++) {
bits.ReadUInt16(out this.usingCounts[i]);
}
}
internal class PdbFunctionsByAddress : IComparer {
public int Compare(Object x, Object y) {
PdbFunction fx = (PdbFunction)x;
PdbFunction fy = (PdbFunction)y;
if (fx.segment < fy.segment) {
return -1;
} else if (fx.segment > fy.segment) {
return 1;
} else if (fx.address < fy.address) {
return -1;
} else if (fx.address > fy.address) {
return 1;
} else {
return 0;
}
}
}
internal class PdbFunctionsByAddressAndToken : IComparer {
public int Compare(Object x, Object y) {
PdbFunction fx = (PdbFunction)x;
PdbFunction fy = (PdbFunction)y;
if (fx.segment < fy.segment) {
return -1;
} else if (fx.segment > fy.segment) {
return 1;
} else if (fx.address < fy.address) {
return -1;
} else if (fx.address > fy.address) {
return 1;
} else {
if (fx.token < fy.token)
return -1;
else if (fx.token > fy.token)
return 1;
else
return 0;
}
}
}
//internal class PdbFunctionsByToken : IComparer {
// public int Compare(Object x, Object y) {
// PdbFunction fx = (PdbFunction)x;
// PdbFunction fy = (PdbFunction)y;
// if (fx.token < fy.token) {
// return -1;
// } else if (fx.token > fy.token) {
// return 1;
// } else {
// return 0;
// }
// }
//}
}
internal class PdbSynchronizationInformation {
internal uint kickoffMethodToken;
internal uint generatedCatchHandlerIlOffset;
internal PdbSynchronizationPoint[] synchronizationPoints;
internal PdbSynchronizationInformation(BitAccess bits) {
uint asyncStepInfoCount;
bits.ReadUInt32(out this.kickoffMethodToken);
bits.ReadUInt32(out this.generatedCatchHandlerIlOffset);
bits.ReadUInt32(out asyncStepInfoCount);
this.synchronizationPoints = new PdbSynchronizationPoint[asyncStepInfoCount];
for (uint i = 0; i < asyncStepInfoCount; i += 1) {
this.synchronizationPoints[i] = new PdbSynchronizationPoint(bits);
}
}
public uint GeneratedCatchHandlerOffset {
get { return this.generatedCatchHandlerIlOffset; }
}
}
internal class PdbSynchronizationPoint {
internal uint synchronizeOffset;
internal uint continuationMethodToken;
internal uint continuationOffset;
internal PdbSynchronizationPoint(BitAccess bits) {
bits.ReadUInt32(out this.synchronizeOffset);
bits.ReadUInt32(out this.continuationMethodToken);
bits.ReadUInt32(out this.continuationOffset);
}
public uint SynchronizeOffset {
get { return this.synchronizeOffset; }
}
public uint ContinuationOffset {
get { return this.continuationOffset; }
}
}
}
| |
using System;
using System.Text;
using PalmeralGenNHibernate.CEN.Default_;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Criterion;
using NHibernate.Exceptions;
using PalmeralGenNHibernate.EN.Default_;
using PalmeralGenNHibernate.Exceptions;
namespace PalmeralGenNHibernate.CAD.Default_
{
public partial class TrabajadorCAD : BasicCAD, ITrabajadorCAD
{
public TrabajadorCAD() : base ()
{
}
public TrabajadorCAD(ISession sessionAux) : base (sessionAux)
{
}
public TrabajadorEN ReadOIDDefault (string nif)
{
TrabajadorEN trabajadorEN = null;
try
{
SessionInitializeTransaction ();
trabajadorEN = (TrabajadorEN)session.Get (typeof(TrabajadorEN), nif);
SessionCommit ();
}
catch (Exception ex) {
SessionRollBack ();
if (ex is PalmeralGenNHibernate.Exceptions.ModelException)
throw ex;
throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in TrabajadorCAD.", ex);
}
finally
{
SessionClose ();
}
return trabajadorEN;
}
public string Crear (TrabajadorEN trabajador)
{
try
{
SessionInitializeTransaction ();
session.Save (trabajador);
SessionCommit ();
}
catch (Exception ex) {
SessionRollBack ();
if (ex is PalmeralGenNHibernate.Exceptions.ModelException)
throw ex;
throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in TrabajadorCAD.", ex);
}
finally
{
SessionClose ();
}
return trabajador.Nif;
}
public void Editar (TrabajadorEN trabajador)
{
try
{
SessionInitializeTransaction ();
TrabajadorEN trabajadorEN = (TrabajadorEN)session.Load (typeof(TrabajadorEN), trabajador.Nif);
trabajadorEN.Nombre = trabajador.Nombre;
trabajadorEN.Apellidos = trabajador.Apellidos;
trabajadorEN.Direccion = trabajador.Direccion;
trabajadorEN.Telefono = trabajador.Telefono;
trabajadorEN.CodigoPostal = trabajador.CodigoPostal;
trabajadorEN.Pais = trabajador.Pais;
trabajadorEN.Localidad = trabajador.Localidad;
trabajadorEN.Provincia = trabajador.Provincia;
trabajadorEN.Tipo = trabajador.Tipo;
session.Update (trabajadorEN);
SessionCommit ();
}
catch (Exception ex) {
SessionRollBack ();
if (ex is PalmeralGenNHibernate.Exceptions.ModelException)
throw ex;
throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in TrabajadorCAD.", ex);
}
finally
{
SessionClose ();
}
}
public void Eliminar (string nif)
{
try
{
SessionInitializeTransaction ();
TrabajadorEN trabajadorEN = (TrabajadorEN)session.Load (typeof(TrabajadorEN), nif);
session.Delete (trabajadorEN);
SessionCommit ();
}
catch (Exception ex) {
SessionRollBack ();
if (ex is PalmeralGenNHibernate.Exceptions.ModelException)
throw ex;
throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in TrabajadorCAD.", ex);
}
finally
{
SessionClose ();
}
}
public System.Collections.Generic.IList<TrabajadorEN> ObtenerTodos (int first, int size)
{
System.Collections.Generic.IList<TrabajadorEN> result = null;
try
{
SessionInitializeTransaction ();
if (size > 0)
result = session.CreateCriteria (typeof(TrabajadorEN)).
SetFirstResult (first).SetMaxResults (size).List<TrabajadorEN>();
else
result = session.CreateCriteria (typeof(TrabajadorEN)).List<TrabajadorEN>();
SessionCommit ();
}
catch (Exception ex) {
SessionRollBack ();
if (ex is PalmeralGenNHibernate.Exceptions.ModelException)
throw ex;
throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in TrabajadorCAD.", ex);
}
finally
{
SessionClose ();
}
return result;
}
public TrabajadorEN ObtenerTrabajador (string nif)
{
TrabajadorEN trabajadorEN = null;
try
{
SessionInitializeTransaction ();
trabajadorEN = (TrabajadorEN)session.Get (typeof(TrabajadorEN), nif);
SessionCommit ();
}
catch (Exception ex) {
SessionRollBack ();
if (ex is PalmeralGenNHibernate.Exceptions.ModelException)
throw ex;
throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in TrabajadorCAD.", ex);
}
finally
{
SessionClose ();
}
return trabajadorEN;
}
public System.Collections.Generic.IList<PalmeralGenNHibernate.EN.Default_.TrabajadorEN> BuscarPorLocalidad (string p_localidad)
{
System.Collections.Generic.IList<PalmeralGenNHibernate.EN.Default_.TrabajadorEN> result;
try
{
SessionInitializeTransaction ();
//String sql = @"FROM TrabajadorEN self where FROM TrabajadorEN AS trab WHERE trab.Localidad LIKE CONCAT('%', :p_localidad , '%')";
//IQuery query = session.CreateQuery(sql);
IQuery query = (IQuery)session.GetNamedQuery ("TrabajadorENbuscarPorLocalidadHQL");
query.SetParameter ("p_localidad", p_localidad);
result = query.List<PalmeralGenNHibernate.EN.Default_.TrabajadorEN>();
SessionCommit ();
}
catch (Exception ex) {
SessionRollBack ();
if (ex is PalmeralGenNHibernate.Exceptions.ModelException)
throw ex;
throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in TrabajadorCAD.", ex);
}
finally
{
SessionClose ();
}
return result;
}
public System.Collections.Generic.IList<PalmeralGenNHibernate.EN.Default_.TrabajadorEN> BuscarPorProvincia (string p_provincia)
{
System.Collections.Generic.IList<PalmeralGenNHibernate.EN.Default_.TrabajadorEN> result;
try
{
SessionInitializeTransaction ();
//String sql = @"FROM TrabajadorEN self where FROM TrabajadorEN AS trab WHERE trab.Provincia LIKE CONCAT('%', :p_provincia , '%')";
//IQuery query = session.CreateQuery(sql);
IQuery query = (IQuery)session.GetNamedQuery ("TrabajadorENbuscarPorProvinciaHQL");
query.SetParameter ("p_provincia", p_provincia);
result = query.List<PalmeralGenNHibernate.EN.Default_.TrabajadorEN>();
SessionCommit ();
}
catch (Exception ex) {
SessionRollBack ();
if (ex is PalmeralGenNHibernate.Exceptions.ModelException)
throw ex;
throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in TrabajadorCAD.", ex);
}
finally
{
SessionClose ();
}
return result;
}
public System.Collections.Generic.IList<PalmeralGenNHibernate.EN.Default_.TrabajadorEN> BuscarPorTipo (PalmeralGenNHibernate.Enumerated.Default_.TipoEmpleoEnum p_tipoEmpleo)
{
System.Collections.Generic.IList<PalmeralGenNHibernate.EN.Default_.TrabajadorEN> result;
try
{
SessionInitializeTransaction ();
//String sql = @"FROM TrabajadorEN self where FROM TrabajadorEN AS trab WHERE trab.Tipo LIKE CONCAT('%', :p_tipoEmpleo , '%')";
//IQuery query = session.CreateQuery(sql);
IQuery query = (IQuery)session.GetNamedQuery ("TrabajadorENbuscarPorTipoHQL");
query.SetParameter ("p_tipoEmpleo", p_tipoEmpleo);
result = query.List<PalmeralGenNHibernate.EN.Default_.TrabajadorEN>();
SessionCommit ();
}
catch (Exception ex) {
SessionRollBack ();
if (ex is PalmeralGenNHibernate.Exceptions.ModelException)
throw ex;
throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in TrabajadorCAD.", ex);
}
finally
{
SessionClose ();
}
return result;
}
public System.Collections.Generic.IList<PalmeralGenNHibernate.EN.Default_.TrabajadorEN> BuscarPorNombre (string p_nombre)
{
System.Collections.Generic.IList<PalmeralGenNHibernate.EN.Default_.TrabajadorEN> result;
try
{
SessionInitializeTransaction ();
//String sql = @"FROM TrabajadorEN self where FROM TrabajadorEN AS trab WHERE trab.Nombre LIKE CONCAT('%', :p_nombre , '%')";
//IQuery query = session.CreateQuery(sql);
IQuery query = (IQuery)session.GetNamedQuery ("TrabajadorENbuscarPorNombreHQL");
query.SetParameter ("p_nombre", p_nombre);
result = query.List<PalmeralGenNHibernate.EN.Default_.TrabajadorEN>();
SessionCommit ();
}
catch (Exception ex) {
SessionRollBack ();
if (ex is PalmeralGenNHibernate.Exceptions.ModelException)
throw ex;
throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in TrabajadorCAD.", ex);
}
finally
{
SessionClose ();
}
return result;
}
public void Relationer_jornadas (string p_trabajador, System.Collections.Generic.IList<int> p_jornadafecha)
{
PalmeralGenNHibernate.EN.Default_.TrabajadorEN trabajadorEN = null;
try
{
SessionInitializeTransaction ();
trabajadorEN = (TrabajadorEN)session.Load (typeof(TrabajadorEN), p_trabajador);
PalmeralGenNHibernate.EN.Default_.JornadaFechaEN jornadasENAux = null;
if (trabajadorEN.Jornadas == null) {
trabajadorEN.Jornadas = new System.Collections.Generic.List<PalmeralGenNHibernate.EN.Default_.JornadaFechaEN>();
}
foreach (int item in p_jornadafecha) {
jornadasENAux = new PalmeralGenNHibernate.EN.Default_.JornadaFechaEN ();
jornadasENAux = (PalmeralGenNHibernate.EN.Default_.JornadaFechaEN)session.Load (typeof(PalmeralGenNHibernate.EN.Default_.JornadaFechaEN), item);
jornadasENAux.Trabajadores.Add (trabajadorEN);
trabajadorEN.Jornadas.Add (jornadasENAux);
}
session.Update (trabajadorEN);
SessionCommit ();
}
catch (Exception ex) {
SessionRollBack ();
if (ex is PalmeralGenNHibernate.Exceptions.ModelException)
throw ex;
throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in TrabajadorCAD.", ex);
}
finally
{
SessionClose ();
}
}
public void Relationer_nominas (string p_trabajador, System.Collections.Generic.IList<string> p_nomina)
{
PalmeralGenNHibernate.EN.Default_.TrabajadorEN trabajadorEN = null;
try
{
SessionInitializeTransaction ();
trabajadorEN = (TrabajadorEN)session.Load (typeof(TrabajadorEN), p_trabajador);
PalmeralGenNHibernate.EN.Default_.NominaEN nominasENAux = null;
if (trabajadorEN.Nominas == null) {
trabajadorEN.Nominas = new System.Collections.Generic.List<PalmeralGenNHibernate.EN.Default_.NominaEN>();
}
foreach (string item in p_nomina) {
nominasENAux = new PalmeralGenNHibernate.EN.Default_.NominaEN ();
nominasENAux = (PalmeralGenNHibernate.EN.Default_.NominaEN)session.Load (typeof(PalmeralGenNHibernate.EN.Default_.NominaEN), item);
nominasENAux.Trabajador = trabajadorEN;
trabajadorEN.Nominas.Add (nominasENAux);
}
session.Update (trabajadorEN);
SessionCommit ();
}
catch (Exception ex) {
SessionRollBack ();
if (ex is PalmeralGenNHibernate.Exceptions.ModelException)
throw ex;
throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in TrabajadorCAD.", ex);
}
finally
{
SessionClose ();
}
}
public void Unrelationer_jornadas (string p_trabajador, System.Collections.Generic.IList<int> p_jornadafecha)
{
try
{
SessionInitializeTransaction ();
PalmeralGenNHibernate.EN.Default_.TrabajadorEN trabajadorEN = null;
trabajadorEN = (TrabajadorEN)session.Load (typeof(TrabajadorEN), p_trabajador);
PalmeralGenNHibernate.EN.Default_.JornadaFechaEN jornadasENAux = null;
if (trabajadorEN.Jornadas != null) {
foreach (int item in p_jornadafecha) {
jornadasENAux = (PalmeralGenNHibernate.EN.Default_.JornadaFechaEN)session.Load (typeof(PalmeralGenNHibernate.EN.Default_.JornadaFechaEN), item);
if (trabajadorEN.Jornadas.Contains (jornadasENAux) == true) {
trabajadorEN.Jornadas.Remove (jornadasENAux);
jornadasENAux.Trabajadores.Remove (trabajadorEN);
}
else
throw new ModelException ("The identifier " + item + " in p_jornadafecha you are trying to unrelationer, doesn't exist in TrabajadorEN");
}
}
session.Update (trabajadorEN);
SessionCommit ();
}
catch (Exception ex) {
SessionRollBack ();
if (ex is PalmeralGenNHibernate.Exceptions.ModelException)
throw ex;
throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in TrabajadorCAD.", ex);
}
finally
{
SessionClose ();
}
}
public void Unrelationer_nominas (string p_trabajador, System.Collections.Generic.IList<string> p_nomina)
{
try
{
SessionInitializeTransaction ();
PalmeralGenNHibernate.EN.Default_.TrabajadorEN trabajadorEN = null;
trabajadorEN = (TrabajadorEN)session.Load (typeof(TrabajadorEN), p_trabajador);
PalmeralGenNHibernate.EN.Default_.NominaEN nominasENAux = null;
if (trabajadorEN.Nominas != null) {
foreach (string item in p_nomina) {
nominasENAux = (PalmeralGenNHibernate.EN.Default_.NominaEN)session.Load (typeof(PalmeralGenNHibernate.EN.Default_.NominaEN), item);
if (trabajadorEN.Nominas.Contains (nominasENAux) == true) {
trabajadorEN.Nominas.Remove (nominasENAux);
nominasENAux.Trabajador = null;
}
else
throw new ModelException ("The identifier " + item + " in p_nomina you are trying to unrelationer, doesn't exist in TrabajadorEN");
}
}
session.Update (trabajadorEN);
SessionCommit ();
}
catch (Exception ex) {
SessionRollBack ();
if (ex is PalmeralGenNHibernate.Exceptions.ModelException)
throw ex;
throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in TrabajadorCAD.", ex);
}
finally
{
SessionClose ();
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace nH.Api.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//------------------------------------------------------------------------------
// </copyright>
//------------------------------------------------------------------------------
using System.Xml.Extensions;
namespace System.Xml.Serialization
{
internal class XmlSerializationPrimitiveWriter : System.Xml.Serialization.XmlSerializationWriter
{
internal void Write_string(object o)
{
WriteStartDocument();
if (o == null)
{
WriteNullTagLiteral(@"string", @"");
return;
}
TopLevelElement();
WriteNullableStringLiteral(@"string", @"", ((System.String)o));
}
internal void Write_int(object o)
{
WriteStartDocument();
if (o == null)
{
WriteEmptyTag(@"int", @"");
return;
}
WriteElementStringRaw(@"int", @"", System.Xml.XmlConvert.ToString((System.Int32)((System.Int32)o)));
}
internal void Write_boolean(object o)
{
WriteStartDocument();
if (o == null)
{
WriteEmptyTag(@"boolean", @"");
return;
}
WriteElementStringRaw(@"boolean", @"", System.Xml.XmlConvert.ToString((System.Boolean)((System.Boolean)o)));
}
internal void Write_short(object o)
{
WriteStartDocument();
if (o == null)
{
WriteEmptyTag(@"short", @"");
return;
}
WriteElementStringRaw(@"short", @"", System.Xml.XmlConvert.ToString((System.Int16)((System.Int16)o)));
}
internal void Write_long(object o)
{
WriteStartDocument();
if (o == null)
{
WriteEmptyTag(@"long", @"");
return;
}
WriteElementStringRaw(@"long", @"", System.Xml.XmlConvert.ToString((System.Int64)((System.Int64)o)));
}
internal void Write_float(object o)
{
WriteStartDocument();
if (o == null)
{
WriteEmptyTag(@"float", @"");
return;
}
WriteElementStringRaw(@"float", @"", System.Xml.XmlConvert.ToString((System.Single)((System.Single)o)));
}
internal void Write_double(object o)
{
WriteStartDocument();
if (o == null)
{
WriteEmptyTag(@"double", @"");
return;
}
WriteElementStringRaw(@"double", @"", System.Xml.XmlConvert.ToString((System.Double)((System.Double)o)));
}
internal void Write_decimal(object o)
{
WriteStartDocument();
if (o == null)
{
WriteEmptyTag(@"decimal", @"");
return;
}
// Preventing inlining optimization which is causing issue for XmlConvert.ToString(Decimal)
Decimal d = (System.Decimal)o;
WriteElementStringRaw(@"decimal", @"", System.Xml.XmlConvert.ToString(d));
}
internal void Write_dateTime(object o)
{
WriteStartDocument();
if (o == null)
{
WriteEmptyTag(@"dateTime", @"");
return;
}
WriteElementStringRaw(@"dateTime", @"", FromDateTime(((System.DateTime)o)));
}
internal void Write_unsignedByte(object o)
{
WriteStartDocument();
if (o == null)
{
WriteEmptyTag(@"unsignedByte", @"");
return;
}
WriteElementStringRaw(@"unsignedByte", @"", System.Xml.XmlConvert.ToString((System.Byte)((System.Byte)o)));
}
internal void Write_byte(object o)
{
WriteStartDocument();
if (o == null)
{
WriteEmptyTag(@"byte", @"");
return;
}
WriteElementStringRaw(@"byte", @"", System.Xml.XmlConvert.ToString((System.SByte)((System.SByte)o)));
}
internal void Write_unsignedShort(object o)
{
WriteStartDocument();
if (o == null)
{
WriteEmptyTag(@"unsignedShort", @"");
return;
}
WriteElementStringRaw(@"unsignedShort", @"", System.Xml.XmlConvert.ToString((System.UInt16)((System.UInt16)o)));
}
internal void Write_unsignedInt(object o)
{
WriteStartDocument();
if (o == null)
{
WriteEmptyTag(@"unsignedInt", @"");
return;
}
WriteElementStringRaw(@"unsignedInt", @"", System.Xml.XmlConvert.ToString((System.UInt32)((System.UInt32)o)));
}
internal void Write_unsignedLong(object o)
{
WriteStartDocument();
if (o == null)
{
WriteEmptyTag(@"unsignedLong", @"");
return;
}
WriteElementStringRaw(@"unsignedLong", @"", System.Xml.XmlConvert.ToString((System.UInt64)((System.UInt64)o)));
}
internal void Write_base64Binary(object o)
{
WriteStartDocument();
if (o == null)
{
WriteNullTagLiteral(@"base64Binary", @"");
return;
}
TopLevelElement();
WriteNullableStringLiteralRaw(@"base64Binary", @"", FromByteArrayBase64(((System.Byte[])o)));
}
internal void Write_guid(object o)
{
WriteStartDocument();
if (o == null)
{
WriteEmptyTag(@"guid", @"");
return;
}
// Preventing inlining optimization which is causing issue for XmlConvert.ToString(Guid)
Guid guid = (Guid)o;
WriteElementStringRaw(@"guid", @"", System.Xml.XmlConvert.ToString(guid));
}
internal void Write_char(object o)
{
WriteStartDocument();
if (o == null)
{
WriteEmptyTag(@"char", @"");
return;
}
WriteElementString(@"char", @"", FromChar(((System.Char)o)));
}
internal void Write_QName(object o)
{
WriteStartDocument();
if (o == null)
{
WriteNullTagLiteral(@"QName", @"");
return;
}
TopLevelElement();
WriteNullableQualifiedNameLiteral(@"QName", @"", ((global::System.Xml.XmlQualifiedName)o));
}
protected override void InitCallbacks()
{
}
}
internal class XmlSerializationPrimitiveReader : System.Xml.Serialization.XmlSerializationReader
{
internal object Read_string()
{
object o = null;
Reader.MoveToContent();
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (((object)Reader.LocalName == (object)_id1_string && (object)Reader.NamespaceURI == (object)_id2_Item))
{
if (ReadNull())
{
o = null;
}
else
{
o = Reader.ReadElementString();
}
}
else
{
throw CreateUnknownNodeException();
}
}
else
{
UnknownNode(null);
}
return (object)o;
}
internal object Read_int()
{
object o = null;
Reader.MoveToContent();
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (((object)Reader.LocalName == (object)_id3_int && (object)Reader.NamespaceURI == (object)_id2_Item))
{
{
o = System.Xml.XmlConvert.ToInt32(Reader.ReadElementString());
}
}
else
{
throw CreateUnknownNodeException();
}
}
else
{
UnknownNode(null);
}
return (object)o;
}
internal object Read_boolean()
{
object o = null;
Reader.MoveToContent();
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (((object)Reader.LocalName == (object)_id4_boolean && (object)Reader.NamespaceURI == (object)_id2_Item))
{
{
o = System.Xml.XmlConvert.ToBoolean(Reader.ReadElementString());
}
}
else
{
throw CreateUnknownNodeException();
}
}
else
{
UnknownNode(null);
}
return (object)o;
}
internal object Read_short()
{
object o = null;
Reader.MoveToContent();
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (((object)Reader.LocalName == (object)_id5_short && (object)Reader.NamespaceURI == (object)_id2_Item))
{
{
o = System.Xml.XmlConvert.ToInt16(Reader.ReadElementString());
}
}
else
{
throw CreateUnknownNodeException();
}
}
else
{
UnknownNode(null);
}
return (object)o;
}
internal object Read_long()
{
object o = null;
Reader.MoveToContent();
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (((object)Reader.LocalName == (object)_id6_long && (object)Reader.NamespaceURI == (object)_id2_Item))
{
{
o = System.Xml.XmlConvert.ToInt64(Reader.ReadElementString());
}
}
else
{
throw CreateUnknownNodeException();
}
}
else
{
UnknownNode(null);
}
return (object)o;
}
internal object Read_float()
{
object o = null;
Reader.MoveToContent();
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (((object)Reader.LocalName == (object)_id7_float && (object)Reader.NamespaceURI == (object)_id2_Item))
{
{
o = System.Xml.XmlConvert.ToSingle(Reader.ReadElementString());
}
}
else
{
throw CreateUnknownNodeException();
}
}
else
{
UnknownNode(null);
}
return (object)o;
}
internal object Read_double()
{
object o = null;
Reader.MoveToContent();
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (((object)Reader.LocalName == (object)_id8_double && (object)Reader.NamespaceURI == (object)_id2_Item))
{
{
o = System.Xml.XmlConvert.ToDouble(Reader.ReadElementString());
}
}
else
{
throw CreateUnknownNodeException();
}
}
else
{
UnknownNode(null);
}
return (object)o;
}
internal object Read_decimal()
{
object o = null;
Reader.MoveToContent();
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (((object)Reader.LocalName == (object)_id9_decimal && (object)Reader.NamespaceURI == (object)_id2_Item))
{
{
o = System.Xml.XmlConvert.ToDecimal(Reader.ReadElementString());
}
}
else
{
throw CreateUnknownNodeException();
}
}
else
{
UnknownNode(null);
}
return (object)o;
}
internal object Read_dateTime()
{
object o = null;
Reader.MoveToContent();
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (((object)Reader.LocalName == (object)_id10_dateTime && (object)Reader.NamespaceURI == (object)_id2_Item))
{
{
o = ToDateTime(Reader.ReadElementString());
}
}
else
{
throw CreateUnknownNodeException();
}
}
else
{
UnknownNode(null);
}
return (object)o;
}
internal object Read_unsignedByte()
{
object o = null;
Reader.MoveToContent();
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (((object)Reader.LocalName == (object)_id11_unsignedByte && (object)Reader.NamespaceURI == (object)_id2_Item))
{
{
o = System.Xml.XmlConvert.ToByte(Reader.ReadElementString());
}
}
else
{
throw CreateUnknownNodeException();
}
}
else
{
UnknownNode(null);
}
return (object)o;
}
internal object Read_byte()
{
object o = null;
Reader.MoveToContent();
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (((object)Reader.LocalName == (object)_id12_byte && (object)Reader.NamespaceURI == (object)_id2_Item))
{
{
o = System.Xml.XmlConvert.ToSByte(Reader.ReadElementString());
}
}
else
{
throw CreateUnknownNodeException();
}
}
else
{
UnknownNode(null);
}
return (object)o;
}
internal object Read_unsignedShort()
{
object o = null;
Reader.MoveToContent();
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (((object)Reader.LocalName == (object)_id13_unsignedShort && (object)Reader.NamespaceURI == (object)_id2_Item))
{
{
o = System.Xml.XmlConvert.ToUInt16(Reader.ReadElementString());
}
}
else
{
throw CreateUnknownNodeException();
}
}
else
{
UnknownNode(null);
}
return (object)o;
}
internal object Read_unsignedInt()
{
object o = null;
Reader.MoveToContent();
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (((object)Reader.LocalName == (object)_id14_unsignedInt && (object)Reader.NamespaceURI == (object)_id2_Item))
{
{
o = System.Xml.XmlConvert.ToUInt32(Reader.ReadElementString());
}
}
else
{
throw CreateUnknownNodeException();
}
}
else
{
UnknownNode(null);
}
return (object)o;
}
internal object Read_unsignedLong()
{
object o = null;
Reader.MoveToContent();
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (((object)Reader.LocalName == (object)_id15_unsignedLong && (object)Reader.NamespaceURI == (object)_id2_Item))
{
{
o = System.Xml.XmlConvert.ToUInt64(Reader.ReadElementString());
}
}
else
{
throw CreateUnknownNodeException();
}
}
else
{
UnknownNode(null);
}
return (object)o;
}
internal object Read_base64Binary()
{
object o = null;
Reader.MoveToContent();
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (((object)Reader.LocalName == (object)_id16_base64Binary && (object)Reader.NamespaceURI == (object)_id2_Item))
{
if (ReadNull())
{
o = null;
}
else
{
o = ToByteArrayBase64(false);
}
}
else
{
throw CreateUnknownNodeException();
}
}
else
{
UnknownNode(null);
}
return (object)o;
}
internal object Read_guid()
{
object o = null;
Reader.MoveToContent();
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (((object)Reader.LocalName == (object)_id17_guid && (object)Reader.NamespaceURI == (object)_id2_Item))
{
{
o = System.Xml.XmlConvert.ToGuid(Reader.ReadElementString());
}
}
else
{
throw CreateUnknownNodeException();
}
}
else
{
UnknownNode(null);
}
return (object)o;
}
internal object Read_char()
{
object o = null;
Reader.MoveToContent();
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (((object)Reader.LocalName == (object)_id18_char && (object)Reader.NamespaceURI == (object)_id2_Item))
{
{
o = ToChar(Reader.ReadElementString());
}
}
else
{
throw CreateUnknownNodeException();
}
}
else
{
UnknownNode(null);
}
return (object)o;
}
internal object Read_QName()
{
object o = null;
Reader.MoveToContent();
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (((object)Reader.LocalName == (object)_id1_QName && (object)Reader.NamespaceURI == (object)_id2_Item))
{
if (ReadNull())
{
o = null;
}
else
{
o = ReadElementQualifiedName();
}
}
else
{
throw CreateUnknownNodeException();
}
}
else
{
UnknownNode(null);
}
return (object)o;
}
protected override void InitCallbacks()
{
}
private System.String _id4_boolean;
private System.String _id14_unsignedInt;
private System.String _id15_unsignedLong;
private System.String _id7_float;
private System.String _id10_dateTime;
private System.String _id6_long;
private System.String _id9_decimal;
private System.String _id8_double;
private System.String _id17_guid;
private System.String _id2_Item;
private System.String _id13_unsignedShort;
private System.String _id18_char;
private System.String _id3_int;
private System.String _id12_byte;
private System.String _id16_base64Binary;
private System.String _id11_unsignedByte;
private System.String _id5_short;
private System.String _id1_string;
private System.String _id1_QName;
protected override void InitIDs()
{
_id4_boolean = Reader.NameTable.Add(@"boolean");
_id14_unsignedInt = Reader.NameTable.Add(@"unsignedInt");
_id15_unsignedLong = Reader.NameTable.Add(@"unsignedLong");
_id7_float = Reader.NameTable.Add(@"float");
_id10_dateTime = Reader.NameTable.Add(@"dateTime");
_id6_long = Reader.NameTable.Add(@"long");
_id9_decimal = Reader.NameTable.Add(@"decimal");
_id8_double = Reader.NameTable.Add(@"double");
_id17_guid = Reader.NameTable.Add(@"guid");
_id2_Item = Reader.NameTable.Add(@"");
_id13_unsignedShort = Reader.NameTable.Add(@"unsignedShort");
_id18_char = Reader.NameTable.Add(@"char");
_id3_int = Reader.NameTable.Add(@"int");
_id12_byte = Reader.NameTable.Add(@"byte");
_id16_base64Binary = Reader.NameTable.Add(@"base64Binary");
_id11_unsignedByte = Reader.NameTable.Add(@"unsignedByte");
_id5_short = Reader.NameTable.Add(@"short");
_id1_string = Reader.NameTable.Add(@"string");
_id1_QName = Reader.NameTable.Add(@"QName");
}
}
}
| |
namespace Microsoft.Azure.Management.Blueprint
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for ArtifactsOperations.
/// </summary>
public static partial class ManagementGroupArtifactsExtensions
{
/// <summary>
/// Create or update Blueprint artifact.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='managementGroupName'>
/// azure managementGroup name, which we save the blueprint to.
/// </param>
/// <param name='blueprintName'>
/// name of the blueprint.
/// </param>
/// <param name='artifactName'>
/// name of the artifact.
/// </param>
/// <param name='artifact'>
/// Blueprint artifact to save.
/// </param>
public static Artifact CreateOrUpdateInManagementGroup(this IArtifactsOperations operations, string managementGroupName, string blueprintName, string artifactName, Artifact artifact)
{
var scope = string.Format(Constants.ResourceScopes.ManagementGroupScope, managementGroupName);
return operations.CreateOrUpdateAsync(scope, blueprintName, artifactName, artifact).GetAwaiter().GetResult();
}
/// <summary>
/// Create or update Blueprint artifact.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='managementGroupName'>
/// azure managementGroup name, which we save the blueprint to.
/// </param>
/// <param name='blueprintName'>
/// name of the blueprint.
/// </param>
/// <param name='artifactName'>
/// name of the artifact.
/// </param>
/// <param name='artifact'>
/// Blueprint artifact to save.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Artifact> CreateOrUpdateInManagementGroupAsync(this IArtifactsOperations operations, string managementGroupName, string blueprintName, string artifactName, Artifact artifact, CancellationToken cancellationToken = default(CancellationToken))
{
var scope = string.Format(Constants.ResourceScopes.ManagementGroupScope, managementGroupName);
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(scope, blueprintName, artifactName, artifact, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get a Blueprint artifact.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='managementGroupName'>
/// azure managementGroup name, which we save the blueprint to.
/// </param>
/// <param name='blueprintName'>
/// name of the blueprint.
/// </param>
/// <param name='artifactName'>
/// name of the artifact.
/// </param>
public static Artifact GetInManagementGroup(this IArtifactsOperations operations, string managementGroupName, string blueprintName, string artifactName)
{
var scope = string.Format(Constants.ResourceScopes.ManagementGroupScope, managementGroupName);
return operations.GetAsync(scope, blueprintName, artifactName).GetAwaiter().GetResult();
}
/// <summary>
/// Get a Blueprint artifact.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='managementGroupName'>
/// azure managementGroup name, which we save the blueprint to.
/// </param>
/// <param name='blueprintName'>
/// name of the blueprint.
/// </param>
/// <param name='artifactName'>
/// name of the artifact.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Artifact> GetInManagementGroupAsync(this IArtifactsOperations operations, string managementGroupName, string blueprintName, string artifactName, CancellationToken cancellationToken = default(CancellationToken))
{
var scope = string.Format(Constants.ResourceScopes.ManagementGroupScope, managementGroupName);
using (var _result = await operations.GetWithHttpMessagesAsync(scope, blueprintName, artifactName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Delete a Blueprint artifact.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='managementGroupName'>
/// azure managementGroup name, which we save the blueprint to.
/// </param>
/// <param name='blueprintName'>
/// name of the blueprint.
/// </param>
/// <param name='artifactName'>
/// name of the artifact.
/// </param>
public static Artifact DeleteInManagementGroup(this IArtifactsOperations operations, string managementGroupName, string blueprintName, string artifactName)
{
var scope = string.Format(Constants.ResourceScopes.ManagementGroupScope, managementGroupName);
return operations.DeleteAsync(scope, blueprintName, artifactName).GetAwaiter().GetResult();
}
/// <summary>
/// Delete a Blueprint artifact.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='managementGroupName'>
/// azure managementGroup name, which we save the blueprint to.
/// </param>
/// <param name='blueprintName'>
/// name of the blueprint.
/// </param>
/// <param name='artifactName'>
/// name of the artifact.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Artifact> DeleteInManagementGroupAsync(this IArtifactsOperations operations, string managementGroupName, string blueprintName, string artifactName, CancellationToken cancellationToken = default(CancellationToken))
{
var scope = string.Format(Constants.ResourceScopes.ManagementGroupScope, managementGroupName);
using (var _result = await operations.DeleteWithHttpMessagesAsync(scope, blueprintName, artifactName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// List artifacts for a given Blueprint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='managementGroupName'>
/// azure managementGroup name, which we save the blueprint to.
/// </param>
/// <param name='blueprintName'>
/// name of the blueprint.
/// </param>
public static IPage<Artifact> ListInManagementGroup(this IArtifactsOperations operations, string managementGroupName, string blueprintName)
{
var scope = string.Format(Constants.ResourceScopes.ManagementGroupScope, managementGroupName);
return operations.ListAsync(scope, blueprintName).GetAwaiter().GetResult();
}
/// <summary>
/// List artifacts for a given Blueprint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='managementGroupName'>
/// azure managementGroup name, which we save the blueprint to.
/// </param>
/// <param name='blueprintName'>
/// name of the blueprint.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Artifact>> ListInManagementGroupAsync(this IArtifactsOperations operations, string managementGroupName, string blueprintName, CancellationToken cancellationToken = default(CancellationToken))
{
var scope = string.Format(Constants.ResourceScopes.ManagementGroupScope, managementGroupName);
using (var _result = await operations.ListWithHttpMessagesAsync(scope, blueprintName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.Content.Res;
using Android.OS;
using Android.Runtime;
using Android.Support.Design.Widget;
using Android.Support.V4.Widget;
using Android.Support.V7.App;
using Android.Views;
using Android.Widget;
using Toolbar = Android.Support.V7.Widget.Toolbar;
namespace MusicPlayer.Droid.UI
{
public class ActionBarCastActivity : AppCompatActivity, FragmentManager.IOnBackStackChangedListener, DrawerLayout.IDrawerListener, NavigationView.IOnNavigationItemSelectedListener
{
const string TAG = "ActionBarCastActivity";
//private VideoCastManager mCastManager;
DrawerLayout drawerLayout;
ActionBarDrawerToggle drawerToggle;
IMenuItem mediaRouteMenuItem;
Toolbar toolbar;
bool toolBarInitialized;
int itemToOpenWhenDrawerCloses = -1;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Ensure that Google Play Service is available.
//VideoCastManager.checkGooglePlayServices(this);
//mCastManager = ((UAMPApplication)Application).getCastManager(this);
//mCastManager.reconnectSessionIfPossible();
}
protected override void OnStart()
{
base.OnStart();
if(!toolBarInitialized)
throw new Exception("You must initilize toolbar at the end of your oncreate method");
}
protected override void OnPostCreate(Bundle savedInstanceState)
{
base.OnPostCreate(savedInstanceState);
drawerToggle?.SyncState();
}
protected override void OnResume()
{
base.OnResume();
//mCastManager.addVideoCastConsumer(mCastConsumer);
//mCastManager.incrementUiCounter();
// Whenever the fragment back stack changes, we may need to update the
// action bar toggle: only top level screens show the hamburger-like icon, inner
// screens - either Activities or fragments - show the "Up" icon instead.
FragmentManager.AddOnBackStackChangedListener(this);
}
public override void OnConfigurationChanged(Configuration newConfig)
{
base.OnConfigurationChanged(newConfig);
drawerToggle?.OnConfigurationChanged(newConfig);
}
protected override void OnPause()
{
base.OnPause();
//mCastManager.RemoveVideoCastConsumer(mCastCnsumer);
//mCastManager.DecrementUiCounter();
FragmentManager.RemoveOnBackStackChangedListener(this);
}
public override bool OnCreateOptionsMenu(IMenu menu)
{
base.OnCreateOptionsMenu(menu);
MenuInflater.Inflate(Resource.Menu.main,menu);
//mediaRouteMenuItem = mCastManager.AddMEdiaRouterButton(menu, Resource.Id.media_route_menu_item);
return true;
}
public override bool OnOptionsItemSelected(IMenuItem item)
{
if (drawerToggle != null && drawerToggle.OnOptionsItemSelected(item))
return true;
if (item != null && item.ItemId == Android.Resource.Id.Home)
{
OnBackPressed();
return true;
}
return base.OnOptionsItemSelected(item);
}
public override void OnBackPressed()
{
if (drawerLayout?.IsDrawerOpen((int)GravityFlags.Start) ?? false)
{
drawerLayout.CloseDrawers();
return;
}
var manager = FragmentManager;
if(manager.BackStackEntryCount > 1)
manager.PopBackStack();
else
base.OnBackPressed();
}
protected virtual void InitializeToolbar()
{
toolbar = this.FindViewById<Toolbar>(Resource.Id.toolbar);
if(toolbar == null)
throw new Exception("Layout is required to include a Toolbar with id Toolbar");
toolbar.InflateMenu(Resource.Menu.main);
drawerLayout = FindViewById<DrawerLayout>(Resource.Id.drawer_layout);
this.SetSupportActionBar(toolbar);
toolBarInitialized = true;
if (drawerLayout == null)
{
return;
}
var navView = FindViewById<NavigationView>(Resource.Id.nav_view);
if(navView == null)
throw new Exception("A layout with a drawerLAyout is required to include a ListView with id 'drawerList'");
drawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,Resource.String.open_content_drawer,Resource.String.close_content_drawer);
drawerLayout.SetDrawerListener(this);
//drawerLayout.SetStatusBarBackgroundColor(ResourceHelper.);
populateDrawerItems(navView);
UpdateDrawerToggle();
}
void populateDrawerItems(NavigationView navView)
{
navView.SetNavigationItemSelectedListener(this);
// if (MusicPlayerActivity.class.isAssignableFrom(getClass())) {
// navigationView.setCheckedItem(R.id.navigation_allmusic);
//} else if (PlaceholderActivity.class.isAssignableFrom(getClass())) {
// navigationView.setCheckedItem(R.id.navigation_playlists);
//}
}
protected virtual void UpdateDrawerToggle()
{
if (drawerToggle == null)
return;
var isRoot = FragmentManager.BackStackEntryCount == 0;
drawerToggle.DrawerIndicatorEnabled = isRoot;
SupportActionBar.SetDisplayShowHomeEnabled(!isRoot);
SupportActionBar.SetDisplayHomeAsUpEnabled(!isRoot);
SupportActionBar.SetHomeButtonEnabled(!isRoot);
if(isRoot)
drawerToggle.SyncState();
}
void showFtu()
{
var menu = toolbar.Menu;
var view = menu.FindItem(Resource.Id.media_route_menu_item).ActionView;
//if (view != null && view instanceof MediaRouteButton) {
// IntroductoryOverlay overlay = new IntroductoryOverlay.Builder(this)
// .setMenuItem(mMediaRouteMenuItem)
// .setTitleText(R.string.touch_to_cast)
// .setSingleTime()
// .build();
// overlay.show();
//}
}
public void OnBackStackChanged()
{
UpdateDrawerToggle();
}
public void OnDrawerClosed(View drawerView)
{
drawerToggle?.OnDrawerClosed(drawerView);
if (itemToOpenWhenDrawerCloses < 0)
return;
var extras =
ActivityOptions.MakeCustomAnimation(this, Resource.Animation.fade_in, Resource.Animation.fade_out).ToBundle();
Type activityClass = null;
//TODO: clean up this navigation hell
//Class activityClass = null;
//switch (mItemToOpenWhenDrawerCloses)
//{
// case R.id.navigation_allmusic:
// activityClass = MusicPlayerActivity.class;
// break;
// case R.id.navigation_playlists:
// activityClass = PlaceholderActivity.class;
// break;
// }
// if (activityClass != null) {
// startActivity(new Intent(ActionBarCastActivity.this, activityClass), extras);
// finish();
//}
}
public void OnDrawerOpened(View drawerView)
{
drawerToggle?.OnDrawerOpened(drawerView);
SupportActionBar?.SetTitle(Resource.String.home_title);
}
public void OnDrawerSlide(View drawerView, float slideOffset)
{
drawerToggle?.OnDrawerSlide(drawerView,slideOffset);
}
public void OnDrawerStateChanged(int newState)
{
drawerToggle?.OnDrawerStateChanged(newState);
}
public bool OnNavigationItemSelected(IMenuItem menuItem)
{
menuItem.SetChecked(true);
itemToOpenWhenDrawerCloses = menuItem.ItemId;
drawerLayout.CloseDrawers();
return true;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Threading.Tasks;
using Azure.Core.TestFramework;
using NUnit.Framework;
using Azure.ResourceManager.Dns.Models;
using Azure.ResourceManager.Dns.Tests;
using System.Collections.Generic;
using Azure.Core;
namespace Azure.Management.Dns.Tests
{
[TestFixture]
public class ScenarioTestsRecordSets : DnsManagementClientBase
{
private string location;
private string resourceGroup;
private string zoneNameForList;
private ChangeTrackingList<AaaaRecord> dummyAaaaRecords;
private ChangeTrackingList<ARecord> dummyARecords;
private ChangeTrackingList<MxRecord> dummyMxRecords;
private ChangeTrackingList<NsRecord> dummyNsRecords;
private ChangeTrackingList<PtrRecord> dummyPtrRecords;
private ChangeTrackingList<SrvRecord> dummySrvRecords;
private ChangeTrackingList<TxtRecord> dummyTxtRecords;
private ChangeTrackingList<CaaRecord> dummyCaaRecords;
private Dictionary<string, string> metadata;
private bool setupRun = false;
public ScenarioTestsRecordSets()
: base(true)
{
resourceGroup = null;
location = "West US";
zoneNameForList = "azure.ameredmond.dns";
dummyAaaaRecords = new ChangeTrackingList<AaaaRecord>();
dummyARecords = new ChangeTrackingList<ARecord>();
dummyMxRecords = new ChangeTrackingList<MxRecord>();
dummyNsRecords = new ChangeTrackingList<NsRecord>();
dummyPtrRecords = new ChangeTrackingList<PtrRecord>();
dummySrvRecords = new ChangeTrackingList<SrvRecord>();
dummyTxtRecords = new ChangeTrackingList<TxtRecord>();
dummyCaaRecords = new ChangeTrackingList<CaaRecord>();
metadata = new Dictionary<string, string>
{
{"tag1", "value1"}
};
}
[SetUp]
public async Task ClearChallengeCacheforRecord()
{
if ((Mode == RecordedTestMode.Record || Mode == RecordedTestMode.Playback) && !setupRun)
{
InitializeClients();
this.resourceGroup = Recording.GenerateAssetName("Default-Dns-");
await Helper.TryRegisterResourceGroupAsync(ResourceGroupsOperations, this.location, this.resourceGroup);
var aZone = new Zone("Global");
await ZonesOperations.CreateOrUpdateAsync(this.resourceGroup, this.zoneNameForList, aZone);
setupRun = true;
}
else if (setupRun)
{
initNewRecord();
}
}
[OneTimeTearDown]
public async Task CleanupResourceGroup()
{
await CleanupResourceGroupsAsync();
}
[TestCase]
public async Task DnsCreateARecordDelete()
{
var namespaceName = Recording.GenerateAssetName("sdk-RecordSet");
var aRecords = new ChangeTrackingList<ARecord>
{
new ARecord {Ipv4Address = "127.0.0.1"}
};
var recordName = "a_record";
var testARecordSet = new RecordSet("test_id", recordName, "A", null, this.metadata, 3600, null, null, null, aRecords, this.dummyAaaaRecords, this.dummyMxRecords,
this.dummyNsRecords, this.dummyPtrRecords, this.dummySrvRecords, this.dummyTxtRecords, null, null, this.dummyCaaRecords);
var createRecordSetResponse = await RecordSetsOperations.CreateOrUpdateAsync(this.resourceGroup, zoneNameForList, recordName, RecordType.A, testARecordSet);
Assert.NotNull(createRecordSetResponse);
Assert.AreEqual(createRecordSetResponse.Value.Name, recordName);
var deleteRecordSetResponse = await RecordSetsOperations.DeleteAsync(this.resourceGroup, zoneNameForList, recordName, RecordType.A);
Assert.NotNull(deleteRecordSetResponse);
}
[TestCase]
public async Task DnsMultiRecordCreateDelete()
{
var namespaceName = Recording.GenerateAssetName("sdk-RecordSet");
var AaaaRecords = new ChangeTrackingList<AaaaRecord>
{
new AaaaRecord {Ipv6Address = "1:1:1:1:1:ffff:783f:e6dc"},
new AaaaRecord {Ipv6Address = "0:0:0:0:0:ffff:403:201"},
};
var recordName = "aaaa_multi_record";
var testARecordSet = new RecordSet("test_id", recordName, "Aaaa", null, this.metadata, 3600, null, null, null, this.dummyARecords, AaaaRecords,
this.dummyMxRecords, this.dummyNsRecords, this.dummyPtrRecords, this.dummySrvRecords, this.dummyTxtRecords, null, null, this.dummyCaaRecords);
var createRecordSetResponse = await RecordSetsOperations.CreateOrUpdateAsync(resourceGroup, this.zoneNameForList, recordName, RecordType.Aaaa, testARecordSet);
Assert.NotNull(createRecordSetResponse);
Assert.AreEqual(createRecordSetResponse.Value.Name, recordName);
var deleteRecordSetResponse = await RecordSetsOperations.DeleteAsync(resourceGroup, this.zoneNameForList, recordName, RecordType.A);
Assert.NotNull(deleteRecordSetResponse);
}
[TestCase]
public async Task DnsRecordSetListByResourceGroup()
{
var namespaceName = Recording.GenerateAssetName("sdk-RecordSet");
var aZone = new Zone("Global");
var zoneName = "azure.ameredmondlocal2.dns";
await ZonesOperations.CreateOrUpdateAsync(resourceGroup, zoneName, aZone);
var ipv6Addr = "1:1:1:1:1:ffff:783f:e6dc";
var AaaaRecords = new ChangeTrackingList<AaaaRecord>
{
new AaaaRecord {Ipv6Address = ipv6Addr},
};
var recordName = "aaaa_record";
var testARecordSet = new RecordSet("test_id", recordName, "Aaaa", null, this.metadata, 3600, null, null, null, this.dummyARecords, AaaaRecords, this.dummyMxRecords,
this.dummyNsRecords, this.dummyPtrRecords, this.dummySrvRecords, this.dummyTxtRecords, null, null, this.dummyCaaRecords);
var createRecordSetResponse = await RecordSetsOperations.CreateOrUpdateAsync(this.resourceGroup, zoneName, recordName, RecordType.Aaaa, testARecordSet);
Assert.NotNull(createRecordSetResponse);
var listResponse = RecordSetsOperations.ListAllByDnsZoneAsync(this.resourceGroup, zoneName);
Assert.NotNull(listResponse);
var allResults = await listResponse.ToEnumerableAsync();
Assert.True(allResults.Count == 3); //SOA and NS record should exist
RecordSet aaaaRecord = null;
foreach (var arecord in allResults)
{
if (arecord.Type == "Microsoft.Network/dnszones/AAAA")
{
aaaaRecord = arecord;
break;
}
}
Assert.NotNull(aaaaRecord); ;
Assert.AreEqual(aaaaRecord.AaaaRecords[0].Ipv6Address, ipv6Addr);
var deleteRecordSetResponse = await RecordSetsOperations.DeleteAsync(this.resourceGroup, zoneName, recordName, RecordType.A);
var deleteZoneResponse = await ZonesOperations.StartDeleteAsync(resourceGroup, zoneName);
Assert.NotNull(deleteZoneResponse);
}
[TestCase]
public async Task DnsRecordSetListByResourceGroupTop()
{
var namespaceName = Recording.GenerateAssetName("sdk-RecordSet");
var aZone = new Zone("Global");
var zoneName = "azure.ameredmondlocaltoptest.dns";
await ZonesOperations.CreateOrUpdateAsync(resourceGroup, zoneName, aZone);
//var ipv6Addr = "1:1:1:1:1:ffff:783f:e6dc";
var AaaaRecords = new ChangeTrackingList<AaaaRecord>
{
new AaaaRecord {Ipv6Address = "1:1:1:1:1:ffff:783f:e6dc"},
new AaaaRecord {Ipv6Address = "0:0:0:0:0:ffff:403:201"},
};
var recordName = "aaaa_record666";
var testARecordSet = new RecordSet("test_id1", recordName, "Aaaa", null, this.metadata, 3600, null, null, null, this.dummyARecords, AaaaRecords, this.dummyMxRecords,
this.dummyNsRecords, this.dummyPtrRecords, this.dummySrvRecords, this.dummyTxtRecords, null, null, this.dummyCaaRecords);
var createRecordSetResponse = await RecordSetsOperations.CreateOrUpdateAsync(this.resourceGroup, zoneName, recordName, RecordType.Aaaa, testARecordSet);
Assert.NotNull(createRecordSetResponse);
recordName = "aaaa_record2";
testARecordSet = new RecordSet("test_id2", recordName, "Aaaa", null, this.metadata, 3600, null, null, null, this.dummyARecords, AaaaRecords, this.dummyMxRecords,
this.dummyNsRecords, this.dummyPtrRecords, this.dummySrvRecords, this.dummyTxtRecords, null, null, this.dummyCaaRecords);
createRecordSetResponse = await RecordSetsOperations.CreateOrUpdateAsync(this.resourceGroup, zoneName, recordName, RecordType.Aaaa, testARecordSet);
var listResponse = RecordSetsOperations.ListByDnsZoneAsync(this.resourceGroup, zoneName, 1);
var t = listResponse.AsPages();
var pageResults = await t.ToEnumerableAsync();
Assert.True(pageResults.Count > 1);
var deleteRecordSetResponse = await RecordSetsOperations.DeleteAsync(this.resourceGroup, zoneName, recordName, RecordType.A);
var deleteZoneResponse = await ZonesOperations.StartDeleteAsync(resourceGroup, zoneName);
Assert.NotNull(deleteZoneResponse);
}
[TestCase]
public async Task DnsRecordSetListByResourceGroupNoTop()
{
var namespaceName = Recording.GenerateAssetName("sdk-RecordSet");
var aZone = new Zone("Global");
var zoneName = "azure.ameredmondlocalNotoptest.dns";
await ZonesOperations.CreateOrUpdateAsync(resourceGroup, zoneName, aZone);
var AaaaRecords = new ChangeTrackingList<AaaaRecord>
{
new AaaaRecord {Ipv6Address = "1:1:1:1:1:ffff:783f:e6dc"},
new AaaaRecord {Ipv6Address = "0:0:0:0:0:ffff:403:201"},
};
var recordName = "aaaa_record66";
var testARecordSet = new RecordSet("test_id1", recordName, "Aaaa", null, this.metadata, 3600, null, null, null, this.dummyARecords, AaaaRecords, this.dummyMxRecords,
this.dummyNsRecords, this.dummyPtrRecords, this.dummySrvRecords, this.dummyTxtRecords, null, null, this.dummyCaaRecords);
var createRecordSetResponse = await RecordSetsOperations.CreateOrUpdateAsync(this.resourceGroup, zoneName, recordName, RecordType.Aaaa, testARecordSet);
Assert.NotNull(createRecordSetResponse);
recordName = "aaaa_record2";
testARecordSet = new RecordSet("test_id2", recordName, "Aaaa", null, this.metadata, 3600, null, null, null, this.dummyARecords, AaaaRecords, this.dummyMxRecords,
this.dummyNsRecords, this.dummyPtrRecords, this.dummySrvRecords, this.dummyTxtRecords, null, null, this.dummyCaaRecords);
createRecordSetResponse = await RecordSetsOperations.CreateOrUpdateAsync(this.resourceGroup, zoneName, recordName, RecordType.Aaaa, testARecordSet);
var listResponse = RecordSetsOperations.ListByDnsZoneAsync(this.resourceGroup, zoneName);
var t = listResponse.AsPages();
var pageResults = await t.ToEnumerableAsync();
Assert.True(pageResults.Count == 1);
var deleteRecordSetResponse = await RecordSetsOperations.DeleteAsync(this.resourceGroup, zoneName, recordName, RecordType.A);
var deleteZoneResponse = await ZonesOperations.StartDeleteAsync(resourceGroup, zoneName);
Assert.NotNull(deleteZoneResponse);
}
[TestCase]
public async Task DnsRecordSetUpdateSoa()
{
var namespaceName = Recording.GenerateAssetName("sdk-RecordSet");
var ipv6Addr = "1:1:1:1:1:ffff:783f:e6dc";
var AaaaRecords = new ChangeTrackingList<AaaaRecord>
{
new AaaaRecord {Ipv6Address = ipv6Addr},
};
var recordName = "soa_record";
var testARecordSet = new RecordSet("test_id", recordName, "Aaaa", null, this.metadata, 3600, null, null, null, this.dummyARecords, AaaaRecords, this.dummyMxRecords,
this.dummyNsRecords, this.dummyPtrRecords, this.dummySrvRecords, this.dummyTxtRecords, null, null, this.dummyCaaRecords);
var createRecordSetResponse = await RecordSetsOperations.CreateOrUpdateAsync(resourceGroup, this.zoneNameForList, recordName, RecordType.Aaaa, testARecordSet);
Assert.NotNull(createRecordSetResponse);
var getResponseSoa = await RecordSetsOperations.GetAsync(this.resourceGroup, this.zoneNameForList, "@", RecordType.SOA);
var soaRecord = getResponseSoa.Value;
soaRecord.SoaRecord.ExpireTime = 123;
soaRecord.SoaRecord.MinimumTtl = 1234;
soaRecord.SoaRecord.RefreshTime = 12345;
soaRecord.SoaRecord.RetryTime = 123456;
var updateResponse = await RecordSetsOperations.CreateOrUpdateAsync(this.resourceGroup, this.zoneNameForList, "@", RecordType.SOA, soaRecord);
Assert.True(Helper.AreEqual(updateResponse, soaRecord, ignoreEtag: true));
var deleteRecordSetResponse = await RecordSetsOperations.DeleteAsync(resourceGroup, this.zoneNameForList, recordName, RecordType.A);
}
[TestCase]
public async Task DnsUpdateARecord()
{
var namespaceName = Recording.GenerateAssetName("sdk-RecordSet");
var aRecords = new ChangeTrackingList<ARecord>
{
new ARecord {Ipv4Address = "123.32.1.0"}
};
var recordName = "a_update_record";
var testARecordSet = new RecordSet("test_id", recordName, "A", null, this.metadata, 60, null, null, null, aRecords, this.dummyAaaaRecords, this.dummyMxRecords,
this.dummyNsRecords, this.dummyPtrRecords, this.dummySrvRecords, this.dummyTxtRecords, null, null, this.dummyCaaRecords);
var createRecordSetResponse = await RecordSetsOperations.CreateOrUpdateAsync(resourceGroup, this.zoneNameForList, recordName, RecordType.A, testARecordSet);
Assert.True(Helper.AreEqual(createRecordSetResponse, testARecordSet, ignoreEtag: true));
var getResponseARecord = await RecordSetsOperations.GetAsync(this.resourceGroup, this.zoneNameForList, recordName, RecordType.A);
var aRecord = getResponseARecord.Value;
aRecord.TTL = 120; //update TTL from 60 to 120
var updateResponse = await RecordSetsOperations.CreateOrUpdateAsync(this.resourceGroup, this.zoneNameForList, recordName, RecordType.A, aRecord);
Assert.AreEqual(updateResponse.Value.TTL, 120);
var deleteRecordSetResponse = await RecordSetsOperations.DeleteAsync(resourceGroup, this.zoneNameForList, recordName, RecordType.A);
Assert.NotNull(deleteRecordSetResponse);
}
[TestCase]
public async Task CreateGetMx()
{
var mxRecords = new ChangeTrackingList<MxRecord>
{
new MxRecord {Exchange = "mail1.scsfsm.com", Preference = 1},
new MxRecord {Exchange = "mail2.scsfsm.com", Preference = 2},
};
var recordName = "mx_record";
var testMxRecordSet = new RecordSet("test_id", recordName, "MX", null, this.metadata, 60, null, null, null, this.dummyARecords, this.dummyAaaaRecords, mxRecords,
this.dummyNsRecords, this.dummyPtrRecords, this.dummySrvRecords, this.dummyTxtRecords, null, null, this.dummyCaaRecords);
var createRecordSetResponse = await RecordSetsOperations.CreateOrUpdateAsync(resourceGroup, this.zoneNameForList, recordName, RecordType.MX, testMxRecordSet);
Assert.True(Helper.AreEqual(createRecordSetResponse, testMxRecordSet, ignoreEtag: true));
}
[TestCase]
public async Task CreateGetNs()
{
var nsRecords = new ChangeTrackingList<NsRecord>
{
new NsRecord {Nsdname = "ns1.scsfsm.com"},
new NsRecord {Nsdname = "ns2.scsfsm.com"},
};
var recordName = "ns_record";
var testNsecordSet = new RecordSet("test_id", recordName, "NS", null, this.metadata, 60, null, null, null, this.dummyARecords, this.dummyAaaaRecords, this.dummyMxRecords,
nsRecords, this.dummyPtrRecords, this.dummySrvRecords, this.dummyTxtRecords, null, null, this.dummyCaaRecords);
var createRecordSetResponse = await RecordSetsOperations.CreateOrUpdateAsync(resourceGroup, this.zoneNameForList, recordName, RecordType.NS, testNsecordSet);
Assert.True(Helper.AreEqual(createRecordSetResponse, testNsecordSet, ignoreEtag: true));
}
[TestCase]
public async Task CreateGetPtr()
{
var ptrRecords = new ChangeTrackingList<PtrRecord>
{
new PtrRecord {Ptrdname = "www1.scsfsm.com"},
new PtrRecord {Ptrdname = "www2.scsfsm.com"},
};
var recordName = "ptr_record";
var testPtrRecordSet = new RecordSet("test_id", recordName, "PTR", null, this.metadata, 60, null, null, null, this.dummyARecords, this.dummyAaaaRecords, this.dummyMxRecords,
this.dummyNsRecords, ptrRecords, this.dummySrvRecords, this.dummyTxtRecords, null, null, this.dummyCaaRecords);
var createRecordSetResponse = await RecordSetsOperations.CreateOrUpdateAsync(resourceGroup, this.zoneNameForList, recordName, RecordType.PTR, testPtrRecordSet);
Assert.True(Helper.AreEqual(createRecordSetResponse, testPtrRecordSet, ignoreEtag: true));
}
[TestCase]
public async Task CreateGetSrv()
{
var srvRecords = new ChangeTrackingList<SrvRecord>
{
new SrvRecord
{
Target = "bt2.scsfsm.com",
Priority = 0,
Weight = 2,
Port = 44
},
new SrvRecord
{
Target = "bt1.scsfsm.com",
Priority = 1,
Weight = 1,
Port = 45
},
};
var recordName = "srv_record";
var testSrvRecordSet = new RecordSet("test_id", recordName, "SRV", null, this.metadata, 60, null, null, null, this.dummyARecords, this.dummyAaaaRecords, this.dummyMxRecords,
this.dummyNsRecords, this.dummyPtrRecords, srvRecords, this.dummyTxtRecords, null, null, this.dummyCaaRecords);
var createRecordSetResponse = await RecordSetsOperations.CreateOrUpdateAsync(resourceGroup, this.zoneNameForList, recordName, RecordType.SRV, testSrvRecordSet);
Assert.True(Helper.AreEqual(createRecordSetResponse, testSrvRecordSet, ignoreEtag: true));
}
[TestCase]
public async Task CreateGetTxt()
{
var txtRecords = new ChangeTrackingList<TxtRecord>
{
new TxtRecord(new List<string>{"lorem"}),
new TxtRecord(new List<string>{"ipsum"}),
};
var recordName = "txt_record";
var testTxtRecordSet = new RecordSet("test_id", recordName, "TXT", null, this.metadata, 60, null, null, null, this.dummyARecords, this.dummyAaaaRecords, this.dummyMxRecords,
this.dummyNsRecords, this.dummyPtrRecords, this.dummySrvRecords, txtRecords, null, null, this.dummyCaaRecords);
var createRecordSetResponse = await RecordSetsOperations.CreateOrUpdateAsync(resourceGroup, this.zoneNameForList, recordName, RecordType.TXT, testTxtRecordSet);
Assert.True(Helper.AreEqual(createRecordSetResponse, testTxtRecordSet, ignoreEtag: true));
}
[TestCase]
public async Task DnsUpdateARecordMultiRecord()
{
var namespaceName = Recording.GenerateAssetName("sdk-RecordSet");
var aRecords = new ChangeTrackingList<ARecord>
{
new ARecord {Ipv4Address = "123.32.1.0"}
};
var recordName = "a_multi_record";
var testARecordSet = new RecordSet("test_id", recordName, "A", null, this.metadata, 60, null, null, null, aRecords, this.dummyAaaaRecords, this.dummyMxRecords,
this.dummyNsRecords, this.dummyPtrRecords, this.dummySrvRecords, this.dummyTxtRecords, null, null, this.dummyCaaRecords);
var createRecordSetResponse = await RecordSetsOperations.CreateOrUpdateAsync(resourceGroup, this.zoneNameForList, recordName, RecordType.A, testARecordSet);
Assert.True(Helper.AreEqual(createRecordSetResponse, testARecordSet, ignoreEtag: true));
var getResponseARecord = await RecordSetsOperations.GetAsync(this.resourceGroup, this.zoneNameForList, recordName, RecordType.A);
var aRecord = getResponseARecord.Value;
aRecord.TTL = 120; //update TTL from 60 to 120
aRecord.ARecords.Clear();
var aList = new List<ARecord>
{
new ARecord {Ipv4Address = "123.32.1.0"},
new ARecord {Ipv4Address = "101.10.0.1"},
new ARecord {Ipv4Address = "22.33.44.55"},
};
((List<ARecord>)aRecord.ARecords).AddRange(aList);
var updateResponse = await RecordSetsOperations.CreateOrUpdateAsync(this.resourceGroup, this.zoneNameForList, recordName, RecordType.A, aRecord);
var updatedRecords = updateResponse.Value;
Assert.AreEqual(updatedRecords.TTL, 120);
for (int i = 0; i < aList.Count; i++)
{
Assert.True(updatedRecords.ARecords[i].Ipv4Address == aList[i].Ipv4Address);
}
Assert.False(string.IsNullOrWhiteSpace(updatedRecords.Etag));
var deleteRecordSetResponse = await RecordSetsOperations.DeleteAsync(resourceGroup, this.zoneNameForList, recordName, RecordType.A);
Assert.NotNull(deleteRecordSetResponse);
}
[TestCase]
public async Task UpdateRecordSetPreconditionFailed()
{
var namespaceName = Recording.GenerateAssetName("sdk-RecordSet");
var cnameRecord = new CnameRecord { Cname = "www.contoso.example.com" };
var recordName = "cname_record";
var testCnameRecordSet = new RecordSet("test_id", recordName, "Cname", null, this.metadata, 60, null, null, null, this.dummyARecords, this.dummyAaaaRecords, this.dummyMxRecords,
this.dummyNsRecords, this.dummyPtrRecords, this.dummySrvRecords, this.dummyTxtRecords, cnameRecord, null, this.dummyCaaRecords);
var createRecordSetResponse = await RecordSetsOperations.CreateOrUpdateAsync(resourceGroup, this.zoneNameForList, recordName, RecordType.Cname, testCnameRecordSet);
bool exceptionCaught = false;
try
{
await RecordSetsOperations.CreateOrUpdateAsync(
this.resourceGroup,
this.zoneNameForList,
recordName,
RecordType.Cname,
ifMatch: "somegibberish",
ifNoneMatch: null,
parameters: testCnameRecordSet);
}
catch (Azure.RequestFailedException)
{
exceptionCaught = true;
}
finally
{
Assert.True(exceptionCaught);
}
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.Reflection;
using Newtonsoft.Json.Utilities;
using System.Collections;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json.Serialization
{
/// <summary>
/// Contract details for a <see cref="Type"/> used by the <see cref="JsonSerializer"/>.
/// </summary>
public class JsonArrayContract : JsonContainerContract
{
/// <summary>
/// Gets the <see cref="Type"/> of the collection items.
/// </summary>
/// <value>The <see cref="Type"/> of the collection items.</value>
public Type CollectionItemType { get; private set; }
/// <summary>
/// Gets a value indicating whether the collection type is a multidimensional array.
/// </summary>
/// <value><c>true</c> if the collection type is a multidimensional array; otherwise, <c>false</c>.</value>
public bool IsMultidimensionalArray { get; private set; }
private readonly bool _isCollectionItemTypeNullableType;
private readonly Type _genericCollectionDefinitionType;
private Type _genericWrapperType;
private MethodCall<object, object> _genericWrapperCreator;
private Func<object> _genericTemporaryCollectionCreator;
internal bool ShouldCreateWrapper { get; private set; }
internal bool CanDeserialize { get; private set; }
internal ConstructorInfo ParametrizedConstructor { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="JsonArrayContract"/> class.
/// </summary>
/// <param name="underlyingType">The underlying type for the contract.</param>
public JsonArrayContract(Type underlyingType)
: base(underlyingType)
{
ContractType = JsonContractType.Array;
bool canDeserialize;
Type tempCollectionType;
if (CreatedType.IsArray)
{
CollectionItemType = ReflectionUtils.GetCollectionItemType(UnderlyingType);
IsReadOnlyOrFixedSize = true;
_genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType);
canDeserialize = true;
IsMultidimensionalArray = (UnderlyingType.IsArray && UnderlyingType.GetArrayRank() > 1);
}
else if (typeof(IList).IsAssignableFrom(underlyingType))
{
if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(ICollection<>), out _genericCollectionDefinitionType))
CollectionItemType = _genericCollectionDefinitionType.GetGenericArguments()[0];
else
CollectionItemType = ReflectionUtils.GetCollectionItemType(underlyingType);
if (underlyingType == typeof (IList))
CreatedType = typeof (List<object>);
if (CollectionItemType != null)
ParametrizedConstructor = CollectionUtils.ResolveEnumableCollectionConstructor(underlyingType, CollectionItemType);
IsReadOnlyOrFixedSize = ReflectionUtils.InheritsGenericDefinition(underlyingType, typeof(ReadOnlyCollection<>));
canDeserialize = true;
}
else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(ICollection<>), out _genericCollectionDefinitionType))
{
CollectionItemType = _genericCollectionDefinitionType.GetGenericArguments()[0];
if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(ICollection<>))
|| ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IList<>)))
CreatedType = typeof(List<>).MakeGenericType(CollectionItemType);
#if !(NET20 || NET35 || PORTABLE40)
if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(ISet<>)))
CreatedType = typeof(HashSet<>).MakeGenericType(CollectionItemType);
#endif
ParametrizedConstructor = CollectionUtils.ResolveEnumableCollectionConstructor(underlyingType, CollectionItemType);
canDeserialize = true;
ShouldCreateWrapper = true;
}
#if !(NET40 || NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE || PORTABLE40)
else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof (IReadOnlyCollection<>), out tempCollectionType))
{
CollectionItemType = underlyingType.GetGenericArguments()[0];
if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof (IReadOnlyCollection<>))
|| ReflectionUtils.IsGenericDefinition(underlyingType, typeof (IReadOnlyList<>)))
CreatedType = typeof(ReadOnlyCollection<>).MakeGenericType(CollectionItemType);
_genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType);
ParametrizedConstructor = CollectionUtils.ResolveEnumableCollectionConstructor(CreatedType, CollectionItemType);
IsReadOnlyOrFixedSize = true;
canDeserialize = (ParametrizedConstructor != null);
}
#endif
else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof (IEnumerable<>), out tempCollectionType))
{
CollectionItemType = tempCollectionType.GetGenericArguments()[0];
if (ReflectionUtils.IsGenericDefinition(UnderlyingType, typeof(IEnumerable<>)))
CreatedType = typeof(List<>).MakeGenericType(CollectionItemType);
ParametrizedConstructor = CollectionUtils.ResolveEnumableCollectionConstructor(underlyingType, CollectionItemType);
if (underlyingType.IsGenericType() && underlyingType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
{
_genericCollectionDefinitionType = tempCollectionType;
IsReadOnlyOrFixedSize = false;
ShouldCreateWrapper = false;
canDeserialize = true;
}
else
{
_genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType);
IsReadOnlyOrFixedSize = true;
ShouldCreateWrapper = true;
canDeserialize = (ParametrizedConstructor != null);
}
}
else
{
// types that implement IEnumerable and nothing else
canDeserialize = false;
ShouldCreateWrapper = true;
}
CanDeserialize = canDeserialize;
if (CollectionItemType != null)
_isCollectionItemTypeNullableType = ReflectionUtils.IsNullableType(CollectionItemType);
#if (NET20 || NET35)
// bug in .NET 2.0 & 3.5 that List<Nullable<T>> throws an error when adding null via IList.Add(object)
// wrapper will handle calling Add(T) instead
if (_isCollectionItemTypeNullableType
&& (ReflectionUtils.InheritsGenericDefinition(CreatedType, typeof(List<>), out tempCollectionType)
|| (CreatedType.IsArray && !IsMultidimensionalArray)))
{
ShouldCreateWrapper = true;
}
#endif
}
internal IWrappedCollection CreateWrapper(object list)
{
if (_genericWrapperCreator == null)
{
_genericWrapperType = typeof(CollectionWrapper<>).MakeGenericType(CollectionItemType);
Type constructorArgument;
if (ReflectionUtils.InheritsGenericDefinition(_genericCollectionDefinitionType, typeof(List<>))
|| _genericCollectionDefinitionType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
constructorArgument = typeof(ICollection<>).MakeGenericType(CollectionItemType);
else
constructorArgument = _genericCollectionDefinitionType;
ConstructorInfo genericWrapperConstructor = _genericWrapperType.GetConstructor(new[] { constructorArgument });
_genericWrapperCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>(genericWrapperConstructor);
}
return (IWrappedCollection) _genericWrapperCreator(null, list);
}
internal IList CreateTemporaryCollection()
{
if (_genericTemporaryCollectionCreator == null)
{
// multidimensional array will also have array instances in it
Type collectionItemType = (IsMultidimensionalArray) ? typeof (object) : CollectionItemType;
Type temporaryListType = typeof(List<>).MakeGenericType(collectionItemType);
_genericTemporaryCollectionCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateDefaultConstructor<object>(temporaryListType);
}
return (IList)_genericTemporaryCollectionCreator();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace IngService.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using Microsoft.TeamFoundation.DistributedTask.WebApi;
using Microsoft.VisualStudio.Services.Agent.Listener;
using Microsoft.VisualStudio.Services.Agent.Listener.Capabilities;
using Microsoft.VisualStudio.Services.Agent.Listener.Configuration;
using Microsoft.VisualStudio.Services.Agent.Util;
using Microsoft.VisualStudio.Services.WebApi;
using Moq;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Threading.Tasks;
using Xunit;
namespace Microsoft.VisualStudio.Services.Agent.Tests.Listener.Configuration
{
public class ConfigurationManagerL0
{
private Mock<IAgentServer> _agentServer;
private Mock<ICredentialManager> _credMgr;
private Mock<IPromptManager> _promptManager;
private Mock<IConfigurationStore> _store;
private Mock<IExtensionManager> _extnMgr;
private Mock<IDeploymentGroupServer> _machineGroupServer;
private Mock<INetFrameworkUtil> _netFrameworkUtil;
#if OS_WINDOWS
private Mock<IWindowsServiceControlManager> _serviceControlManager;
#endif
#if !OS_WINDOWS
private Mock<ILinuxServiceControlManager> _serviceControlManager;
#endif
private Mock<IRSAKeyManager> _rsaKeyManager;
private ICapabilitiesManager _capabilitiesManager;
private DeploymentGroupAgentConfigProvider _deploymentGroupAgentConfigProvider;
private string _expectedToken = "expectedToken";
private string _expectedServerUrl = "https://localhost";
private string _expectedVSTSServerUrl = "https://L0ConfigTest.visualstudio.com";
private string _expectedAgentName = "expectedAgentName";
private string _expectedPoolName = "poolName";
private string _expectedCollectionName = "testCollectionName";
private string _expectedProjectName = "testProjectName";
private string _expectedProjectId = "edf3f94e-d251-49df-bfce-602d6c967409";
private string _expectedMachineGroupName = "testMachineGroupName";
private string _expectedAuthType = "pat";
private string _expectedWorkFolder = "_work";
private int _expectedPoolId = 1;
private int _expectedDeploymentMachineId = 81;
private RSA rsa = null;
private AgentSettings _configMgrAgentSettings = new AgentSettings();
public ConfigurationManagerL0()
{
_agentServer = new Mock<IAgentServer>();
_credMgr = new Mock<ICredentialManager>();
_promptManager = new Mock<IPromptManager>();
_store = new Mock<IConfigurationStore>();
_extnMgr = new Mock<IExtensionManager>();
_rsaKeyManager = new Mock<IRSAKeyManager>();
_machineGroupServer = new Mock<IDeploymentGroupServer>();
_netFrameworkUtil = new Mock<INetFrameworkUtil>();
#if OS_WINDOWS
_serviceControlManager = new Mock<IWindowsServiceControlManager>();
#endif
#if !OS_WINDOWS
_serviceControlManager = new Mock<ILinuxServiceControlManager>();
#endif
#if !OS_WINDOWS
string eulaFile = Path.Combine(IOUtil.GetExternalsPath(), Constants.Path.TeeDirectory, "license.html");
Directory.CreateDirectory(IOUtil.GetExternalsPath());
Directory.CreateDirectory(Path.Combine(IOUtil.GetExternalsPath(), Constants.Path.TeeDirectory));
File.WriteAllText(eulaFile, "testeulafile");
#endif
_capabilitiesManager = new CapabilitiesManager();
var expectedAgent = new TaskAgent(_expectedAgentName) { Id = 1 };
var expectedDeploymentMachine = new DeploymentMachine() { Agent = expectedAgent, Id = _expectedDeploymentMachineId };
expectedAgent.Authorization = new TaskAgentAuthorization
{
ClientId = Guid.NewGuid(),
AuthorizationUrl = new Uri("http://localhost:8080/tfs"),
};
_agentServer.Setup(x => x.ConnectAsync(It.IsAny<VssConnection>())).Returns(Task.FromResult<object>(null));
_machineGroupServer.Setup(x => x.ConnectAsync(It.IsAny<VssConnection>())).Returns(Task.FromResult<object>(null));
_machineGroupServer.Setup(x => x.UpdateDeploymentMachinesAsync(It.IsAny<Guid>(), It.IsAny<int>(), It.IsAny<List<DeploymentMachine>>()));
_machineGroupServer.Setup(x => x.AddDeploymentMachineAsync(It.IsAny<Guid>(), It.IsAny<int>(), It.IsAny<DeploymentMachine>())).Returns(Task.FromResult(expectedDeploymentMachine));
_machineGroupServer.Setup(x => x.ReplaceDeploymentMachineAsync(It.IsAny<Guid>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<DeploymentMachine>())).Returns(Task.FromResult(expectedDeploymentMachine));
_machineGroupServer.Setup(x => x.GetDeploymentMachinesAsync(It.IsAny<Guid>(), It.IsAny<int>(), It.IsAny<string>())).Returns(Task.FromResult(new List<DeploymentMachine>(){}));
_machineGroupServer.Setup(x => x.DeleteDeploymentMachineAsync(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>())).Returns(Task.FromResult<object>(null));
_netFrameworkUtil.Setup(x => x.Test(It.IsAny<Version>())).Returns(true);
_store.Setup(x => x.IsConfigured()).Returns(false);
_store.Setup(x => x.HasCredentials()).Returns(false);
_store.Setup(x => x.GetSettings()).Returns(() => _configMgrAgentSettings);
_store.Setup(x => x.SaveSettings(It.IsAny<AgentSettings>()))
.Callback((AgentSettings settings) =>
{
_configMgrAgentSettings = settings;
});
_credMgr.Setup(x => x.GetCredentialProvider(It.IsAny<string>())).Returns(new TestAgentCredential());
#if !OS_WINDOWS
_serviceControlManager.Setup(x => x.GenerateScripts(It.IsAny<AgentSettings>()));
#endif
var expectedPools = new List<TaskAgentPool>() { new TaskAgentPool(_expectedPoolName) { Id = _expectedPoolId } };
_agentServer.Setup(x => x.GetAgentPoolsAsync(It.IsAny<string>())).Returns(Task.FromResult(expectedPools));
var expectedAgents = new List<TaskAgent>();
_agentServer.Setup(x => x.GetAgentsAsync(It.IsAny<int>(), It.IsAny<string>())).Returns(Task.FromResult(expectedAgents));
_agentServer.Setup(x => x.AddAgentAsync(It.IsAny<int>(), It.IsAny<TaskAgent>())).Returns(Task.FromResult(expectedAgent));
_agentServer.Setup(x => x.UpdateAgentAsync(It.IsAny<int>(), It.IsAny<TaskAgent>())).Returns(Task.FromResult(expectedAgent));
rsa = RSA.Create();
rsa.KeySize = 2048;
_rsaKeyManager.Setup(x => x.CreateKey()).Returns(rsa);
}
private TestHostContext CreateTestContext([CallerMemberName] String testName = "")
{
TestHostContext tc = new TestHostContext(this, testName);
tc.SetSingleton<ICredentialManager>(_credMgr.Object);
tc.SetSingleton<IPromptManager>(_promptManager.Object);
tc.SetSingleton<IConfigurationStore>(_store.Object);
tc.SetSingleton<IExtensionManager>(_extnMgr.Object);
tc.SetSingleton<IAgentServer>(_agentServer.Object);
tc.SetSingleton<IDeploymentGroupServer>(_machineGroupServer.Object);
tc.SetSingleton<INetFrameworkUtil>(_netFrameworkUtil.Object);
tc.SetSingleton<ICapabilitiesManager>(_capabilitiesManager);
#if OS_WINDOWS
tc.SetSingleton<IWindowsServiceControlManager>(_serviceControlManager.Object);
#else
tc.SetSingleton<ILinuxServiceControlManager>(_serviceControlManager.Object);
#endif
tc.SetSingleton<IRSAKeyManager>(_rsaKeyManager.Object);
tc.EnqueueInstance<IAgentServer>(_agentServer.Object);
tc.EnqueueInstance<IDeploymentGroupServer>(_machineGroupServer.Object);
return tc;
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "ConfigurationManagement")]
public async Task CanEnsureConfigure()
{
using (TestHostContext tc = CreateTestContext())
{
Tracing trace = tc.GetTrace();
trace.Info("Creating config manager");
IConfigurationManager configManager = new ConfigurationManager();
configManager.Initialize(tc);
trace.Info("Preparing command line arguments");
var command = new CommandSettings(
tc,
new[]
{
"configure",
#if !OS_WINDOWS
"--acceptteeeula",
#endif
"--url", _expectedServerUrl,
"--agent", _expectedAgentName,
"--pool", _expectedPoolName,
"--work", _expectedWorkFolder,
"--auth", _expectedAuthType,
"--token", _expectedToken
});
trace.Info("Constructed.");
_store.Setup(x => x.IsConfigured()).Returns(false);
_configMgrAgentSettings = null;
_extnMgr.Setup(x => x.GetExtensions<IConfigurationProvider>()).Returns(GetConfigurationProviderList(tc));
trace.Info("Ensuring all the required parameters are available in the command line parameter");
await configManager.ConfigureAsync(command);
_store.Setup(x => x.IsConfigured()).Returns(true);
trace.Info("Configured, verifying all the parameter value");
var s = configManager.LoadSettings();
Assert.NotNull(s);
Assert.True(s.ServerUrl.Equals(_expectedServerUrl));
Assert.True(s.AgentName.Equals(_expectedAgentName));
Assert.True(s.PoolId.Equals(_expectedPoolId));
Assert.True(s.WorkFolder.Equals(_expectedWorkFolder));
// For build and release agent, tags logic should not get trigger
_machineGroupServer.Verify(x =>
x.UpdateDeploymentMachinesAsync(It.IsAny<Guid>(), It.IsAny<int>(), It.IsAny<List<DeploymentMachine>>()), Times.Never);
}
}
/*
* Agent configuartion as deployment agent against VSTS account
* Collectioion name is not required
*/
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "ConfigurationManagement")]
public async Task CanEnsureMachineGroupAgentConfigureVSTSScenario()
{
using (TestHostContext tc = CreateTestContext())
{
Tracing trace = tc.GetTrace();
trace.Info("Creating config manager");
IConfigurationManager configManager = new ConfigurationManager();
configManager.Initialize(tc);
trace.Info("Preparing command line arguments for vsts scenario");
var command = new CommandSettings(
tc,
new[]
{
"configure",
#if !OS_WINDOWS
"--acceptteeeula",
#endif
"--machinegroup",
"--url", _expectedVSTSServerUrl,
"--agent", _expectedAgentName,
"--projectname", _expectedProjectName,
"--machinegroupname", _expectedMachineGroupName,
"--work", _expectedWorkFolder,
"--auth", _expectedAuthType,
"--token", _expectedToken
});
trace.Info("Constructed.");
_store.Setup(x => x.IsConfigured()).Returns(false);
_configMgrAgentSettings = null;
_extnMgr.Setup(x => x.GetExtensions<IConfigurationProvider>()).Returns(GetConfigurationProviderList(tc));
_machineGroupServer.Setup(x => x.GetDeploymentGroupsAsync(It.IsAny<string>(),It.IsAny<string>())).Returns(Task.FromResult(GetDeploymentGroups(18,27)));
trace.Info("Ensuring all the required parameters are available in the command line parameter");
await configManager.ConfigureAsync(command);
_store.Setup(x => x.IsConfigured()).Returns(true);
trace.Info("Configured, verifying all the parameter value");
var s = configManager.LoadSettings();
Assert.NotNull(s);
Assert.True(s.ServerUrl.Equals(_expectedVSTSServerUrl,StringComparison.CurrentCultureIgnoreCase));
Assert.True(s.AgentName.Equals(_expectedAgentName));
Assert.True(s.PoolId.Equals(27));
Assert.True(s.WorkFolder.Equals(_expectedWorkFolder));
Assert.True(s.MachineGroupId.Equals(0));
Assert.True(s.DeploymentGroupId.Equals(18));
Assert.Null(s.ProjectName);
Assert.True(s.ProjectId.Equals(_expectedProjectId));
// Tags logic should not get trigger
_machineGroupServer.Verify(x =>
x.UpdateDeploymentMachinesAsync(It.IsAny<Guid>(), It.IsAny<int>(), It.IsAny<List<DeploymentMachine>>()), Times.Never);
}
}
/*
* Agent configuartion as deployment agent against on prem tfs
* Collectioion name is required
*/
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "ConfigurationManagement")]
public async Task CanEnsureMachineGroupAgentConfigureOnPremScenario()
{
using (TestHostContext tc = CreateTestContext())
{
Tracing trace = tc.GetTrace();
trace.Info("Creating config manager");
IConfigurationManager configManager = new ConfigurationManager();
configManager.Initialize(tc);
var onPremTfsUrl = "http://localtfs:8080/tfs";
trace.Info("Preparing command line arguments for vsts scenario");
var command = new CommandSettings(
tc,
new[]
{
"configure",
#if !OS_WINDOWS
"--acceptteeeula",
#endif
"--deploymentgroup",
"--url", onPremTfsUrl,
"--agent", _expectedAgentName,
"--collectionname", _expectedCollectionName,
"--projectname", _expectedProjectName,
"--deploymentgroupname", _expectedMachineGroupName,
"--work", _expectedWorkFolder,
"--auth", _expectedAuthType,
"--token", _expectedToken
});
trace.Info("Constructed.");
_store.Setup(x => x.IsConfigured()).Returns(false);
_configMgrAgentSettings = null;
_extnMgr.Setup(x => x.GetExtensions<IConfigurationProvider>()).Returns(GetConfigurationProviderList(tc));
_machineGroupServer.Setup(x => x.GetDeploymentGroupsAsync(It.IsAny<string>(), It.IsAny<string>())).Returns(Task.FromResult(GetDeploymentGroups(3, 7)));
trace.Info("Ensuring all the required parameters are available in the command line parameter");
await configManager.ConfigureAsync(command);
_store.Setup(x => x.IsConfigured()).Returns(true);
trace.Info("Configured, verifying all the parameter value");
var s = configManager.LoadSettings();
Assert.NotNull(s);
Assert.True(s.ServerUrl.Equals(onPremTfsUrl));
Assert.True(s.AgentName.Equals(_expectedAgentName));
Assert.True(s.PoolId.Equals(7));
Assert.True(s.WorkFolder.Equals(_expectedWorkFolder));
Assert.True(s.MachineGroupId.Equals(0));
Assert.True(s.DeploymentGroupId.Equals(3));
Assert.Null(s.ProjectName);
Assert.True(s.ProjectId.Equals(_expectedProjectId));
// Tags logic should not get trigger
_machineGroupServer.Verify(x =>
x.UpdateDeploymentMachinesAsync(It.IsAny<Guid>(), It.IsAny<int>(), It.IsAny<List<DeploymentMachine>>()), Times.Never);
}
}
/*
* Agent configuartion as deployment agent against VSTS account
* Collectioion name is not required
*/
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "ConfigurationManagement")]
public async Task CanEnsureMachineGroupAgentConfigureVSTSScenarioWithTags()
{
Guid receivedProjectId;
string expectedProcessedTags = string.Empty;
string tags = "Tag3, ,, Tag4 , , , Tag1, , tag3 ";
string expectedTags = "Tag3,Tag4,Tag1";
int receivedMachineId = -1;
int expectedDeploymentGroupId = 7;
int receivedDeploymentGroupId = -1;
_machineGroupServer.Setup(x =>
x.UpdateDeploymentMachinesAsync(It.IsAny<Guid>(), It.IsAny<int>(),
It.IsAny<List<DeploymentMachine>>())).Callback((Guid project, int deploymentGroupId, List<DeploymentMachine> deploymentMachine) =>
{
receivedProjectId = project;
expectedProcessedTags = string.Join(",",deploymentMachine.FirstOrDefault().Tags.ToArray());
receivedMachineId = deploymentMachine.FirstOrDefault().Id;
receivedDeploymentGroupId = deploymentGroupId;
}
);
using (TestHostContext tc = CreateTestContext())
{
Tracing trace = tc.GetTrace();
trace.Info("Creating config manager");
IConfigurationManager configManager = new ConfigurationManager();
configManager.Initialize(tc);
trace.Info("Preparing command line arguments for vsts scenario");
var command = new CommandSettings(
tc,
new[]
{
"configure",
#if !OS_WINDOWS
"--acceptteeeula",
#endif
"--machinegroup",
"--adddeploymentgrouptags",
"--url", _expectedVSTSServerUrl,
"--agent", _expectedAgentName,
"--projectname", _expectedProjectName,
"--deploymentgroupname", _expectedMachineGroupName,
"--work", _expectedWorkFolder,
"--auth", _expectedAuthType,
"--token", _expectedToken,
"--deploymentgrouptags", tags
});
trace.Info("Constructed.");
_store.Setup(x => x.IsConfigured()).Returns(false);
_configMgrAgentSettings = null;
_extnMgr.Setup(x => x.GetExtensions<IConfigurationProvider>()).Returns(GetConfigurationProviderList(tc));
_machineGroupServer.Setup(x => x.GetDeploymentGroupsAsync(It.IsAny<string>(), It.IsAny<string>())).Returns(Task.FromResult(GetDeploymentGroups(expectedDeploymentGroupId, 3)));
trace.Info("Ensuring all the required parameters are available in the command line parameter");
await configManager.ConfigureAsync(command);
_store.Setup(x => x.IsConfigured()).Returns(true);
trace.Info("Configured, verifying all the parameter value");
var s = configManager.LoadSettings();
Assert.NotNull(s);
Assert.True(s.ServerUrl.Equals(_expectedVSTSServerUrl, StringComparison.CurrentCultureIgnoreCase));
Assert.True(s.AgentName.Equals(_expectedAgentName));
Assert.True(s.PoolId.Equals(3));
Assert.True(s.DeploymentGroupId.Equals(7));
Assert.True(s.WorkFolder.Equals(_expectedWorkFolder));
Assert.True(s.MachineGroupId.Equals(0));
Assert.Null(s.ProjectName);
Assert.True(s.ProjectId.Equals(_expectedProjectId));
Assert.True(receivedProjectId.Equals(new Guid(_expectedProjectId)), "UpdateDeploymentMachinesGroupAsync should get call with correct project name");
Assert.True(expectedTags.Equals(expectedProcessedTags),"Before applying the tags, should get processed ( Trim, Remove duplicate)");
Assert.True(receivedMachineId.Equals(_expectedDeploymentMachineId), "UpdateDeploymentMachinesGroupAsync should get call with correct machine id");
Assert.True(receivedDeploymentGroupId.Equals(expectedDeploymentGroupId), "UpdateDeploymentMachinesGroupAsync should get call with correct deployment group id");
// Tags logic should get trigger
_machineGroupServer.Verify(x =>
x.UpdateDeploymentMachinesAsync(It.IsAny<Guid>(), It.IsAny<int>(),
It.IsAny<List<DeploymentMachine>>()), Times.Once);
}
}
private List<DeploymentGroup> GetDeploymentGroups(int dgId, int poolId)
{
var dgJson = "{'id':" + dgId.ToString() + ",'project':{'id':'" + _expectedProjectId + "','name':'Test-Project1'},'name':'ch-test','pool':{'id':" + poolId.ToString() + ",'scope':'0efb4611-d565-4cd1-9a64-7d6cb6d7d5f0'}}";
var deploymentGroup = JsonConvert.DeserializeObject<DeploymentGroup>(dgJson);
return new List<DeploymentGroup>() { deploymentGroup };
}
// Init the Agent Config Provider
private List<IConfigurationProvider> GetConfigurationProviderList(TestHostContext tc)
{
IConfigurationProvider buildReleasesAgentConfigProvider = new BuildReleasesAgentConfigProvider();
buildReleasesAgentConfigProvider.Initialize(tc);
_deploymentGroupAgentConfigProvider = new DeploymentGroupAgentConfigProvider();
_deploymentGroupAgentConfigProvider.Initialize(tc);
return new List<IConfigurationProvider> { buildReleasesAgentConfigProvider, _deploymentGroupAgentConfigProvider };
}
// TODO Unit Test for IsConfigured - Rename config file and make sure it returns false
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
namespace System.Reflection.Emit
{
using System;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Diagnostics.Contracts;
internal sealed class MethodOnTypeBuilderInstantiation : MethodInfo
{
#region Private Static Members
internal static MethodInfo GetMethod(MethodInfo method, TypeBuilderInstantiation type)
{
return new MethodOnTypeBuilderInstantiation(method, type);
}
#endregion
#region Private Data Mebers
internal MethodInfo m_method;
private TypeBuilderInstantiation m_type;
#endregion
#region Constructor
internal MethodOnTypeBuilderInstantiation(MethodInfo method, TypeBuilderInstantiation type)
{
Contract.Assert(method is MethodBuilder || method is RuntimeMethodInfo);
m_method = method;
m_type = type;
}
#endregion
internal override Type[] GetParameterTypes()
{
return m_method.GetParameterTypes();
}
#region MemberInfo Overrides
public override MemberTypes MemberType { get { return m_method.MemberType; } }
public override String Name { get { return m_method.Name; } }
public override Type DeclaringType { get { return m_type; } }
public override Type ReflectedType { get { return m_type; } }
public override Object[] GetCustomAttributes(bool inherit) { return m_method.GetCustomAttributes(inherit); }
public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { return m_method.GetCustomAttributes(attributeType, inherit); }
public override bool IsDefined(Type attributeType, bool inherit) { return m_method.IsDefined(attributeType, inherit); }
internal int MetadataTokenInternal
{
get
{
MethodBuilder mb = m_method as MethodBuilder;
if (mb != null)
return mb.MetadataTokenInternal;
else
{
Contract.Assert(m_method is RuntimeMethodInfo);
return m_method.MetadataToken;
}
}
}
public override Module Module { get { return m_method.Module; } }
public new Type GetType() { return base.GetType(); }
#endregion
#region MethodBase Members
[Pure]
public override ParameterInfo[] GetParameters() { return m_method.GetParameters(); }
public override MethodImplAttributes GetMethodImplementationFlags() { return m_method.GetMethodImplementationFlags(); }
public override RuntimeMethodHandle MethodHandle { get { return m_method.MethodHandle; } }
public override MethodAttributes Attributes { get { return m_method.Attributes; } }
public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
{
throw new NotSupportedException();
}
public override CallingConventions CallingConvention { get { return m_method.CallingConvention; } }
public override Type [] GetGenericArguments() { return m_method.GetGenericArguments(); }
public override MethodInfo GetGenericMethodDefinition() { return m_method; }
public override bool IsGenericMethodDefinition { get { return m_method.IsGenericMethodDefinition; } }
public override bool ContainsGenericParameters { get { return m_method.ContainsGenericParameters; } }
public override MethodInfo MakeGenericMethod(params Type[] typeArgs)
{
if (!IsGenericMethodDefinition)
throw new InvalidOperationException(Environment.GetResourceString("Arg_NotGenericMethodDefinition"));
Contract.EndContractBlock();
return MethodBuilderInstantiation.MakeGenericMethod(this, typeArgs);
}
public override bool IsGenericMethod { get { return m_method.IsGenericMethod; } }
#endregion
#region Public Abstract\Virtual Members
public override Type ReturnType { get { return m_method.ReturnType; } }
public override ParameterInfo ReturnParameter { get { throw new NotSupportedException(); } }
public override ICustomAttributeProvider ReturnTypeCustomAttributes { get { throw new NotSupportedException(); } }
public override MethodInfo GetBaseDefinition() { throw new NotSupportedException(); }
#endregion
}
internal sealed class ConstructorOnTypeBuilderInstantiation : ConstructorInfo
{
#region Private Static Members
internal static ConstructorInfo GetConstructor(ConstructorInfo Constructor, TypeBuilderInstantiation type)
{
return new ConstructorOnTypeBuilderInstantiation(Constructor, type);
}
#endregion
#region Private Data Mebers
internal ConstructorInfo m_ctor;
private TypeBuilderInstantiation m_type;
#endregion
#region Constructor
internal ConstructorOnTypeBuilderInstantiation(ConstructorInfo constructor, TypeBuilderInstantiation type)
{
Contract.Assert(constructor is ConstructorBuilder || constructor is RuntimeConstructorInfo);
m_ctor = constructor;
m_type = type;
}
#endregion
internal override Type[] GetParameterTypes()
{
return m_ctor.GetParameterTypes();
}
internal override Type GetReturnType()
{
return DeclaringType;
}
#region MemberInfo Overrides
public override MemberTypes MemberType { get { return m_ctor.MemberType; } }
public override String Name { get { return m_ctor.Name; } }
public override Type DeclaringType { get { return m_type; } }
public override Type ReflectedType { get { return m_type; } }
public override Object[] GetCustomAttributes(bool inherit) { return m_ctor.GetCustomAttributes(inherit); }
public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { return m_ctor.GetCustomAttributes(attributeType, inherit); }
public override bool IsDefined(Type attributeType, bool inherit) { return m_ctor.IsDefined(attributeType, inherit); }
internal int MetadataTokenInternal
{
get
{
ConstructorBuilder cb = m_ctor as ConstructorBuilder;
if (cb != null)
return cb.MetadataTokenInternal;
else
{
Contract.Assert(m_ctor is RuntimeConstructorInfo);
return m_ctor.MetadataToken;
}
}
}
public override Module Module { get { return m_ctor.Module; } }
public new Type GetType() { return base.GetType(); }
#endregion
#region MethodBase Members
[Pure]
public override ParameterInfo[] GetParameters() { return m_ctor.GetParameters(); }
public override MethodImplAttributes GetMethodImplementationFlags() { return m_ctor.GetMethodImplementationFlags(); }
public override RuntimeMethodHandle MethodHandle { get { return m_ctor.MethodHandle; } }
public override MethodAttributes Attributes { get { return m_ctor.Attributes; } }
public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
{
throw new NotSupportedException();
}
public override CallingConventions CallingConvention { get { return m_ctor.CallingConvention; } }
public override Type[] GetGenericArguments() { return m_ctor.GetGenericArguments(); }
public override bool IsGenericMethodDefinition { get { return false; } }
public override bool ContainsGenericParameters { get { return false; } }
public override bool IsGenericMethod { get { return false; } }
#endregion
#region ConstructorInfo Members
public override Object Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
{
throw new InvalidOperationException();
}
#endregion
}
internal sealed class FieldOnTypeBuilderInstantiation : FieldInfo
{
#region Private Static Members
internal static FieldInfo GetField(FieldInfo Field, TypeBuilderInstantiation type)
{
FieldInfo m = null;
// This ifdef was introduced when non-generic collections were pulled from
// silverlight. See code:Dictionary#DictionaryVersusHashtableThreadSafety
// for information about this change.
//
// There is a pre-existing race condition in this code with the side effect
// that the second thread's value clobbers the first in the hashtable. This is
// an acceptable race condition since we make no guarantees that this will return the
// same object.
//
// We're not entirely sure if this cache helps any specific scenarios, so
// long-term, one could investigate whether it's needed. In any case, this
// method isn't expected to be on any critical paths for performance.
if (type.m_hashtable.Contains(Field)) {
m = type.m_hashtable[Field] as FieldInfo;
}
else {
m = new FieldOnTypeBuilderInstantiation(Field, type);
type.m_hashtable[Field] = m;
}
return m;
}
#endregion
#region Private Data Members
private FieldInfo m_field;
private TypeBuilderInstantiation m_type;
#endregion
#region Constructor
internal FieldOnTypeBuilderInstantiation(FieldInfo field, TypeBuilderInstantiation type)
{
Contract.Assert(field is FieldBuilder || field is RuntimeFieldInfo);
m_field = field;
m_type = type;
}
#endregion
internal FieldInfo FieldInfo { get { return m_field; } }
#region MemberInfo Overrides
public override MemberTypes MemberType { get { return System.Reflection.MemberTypes.Field; } }
public override String Name { get { return m_field.Name; } }
public override Type DeclaringType { get { return m_type; } }
public override Type ReflectedType { get { return m_type; } }
public override Object[] GetCustomAttributes(bool inherit) { return m_field.GetCustomAttributes(inherit); }
public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { return m_field.GetCustomAttributes(attributeType, inherit); }
public override bool IsDefined(Type attributeType, bool inherit) { return m_field.IsDefined(attributeType, inherit); }
internal int MetadataTokenInternal
{
get
{
FieldBuilder fb = m_field as FieldBuilder;
if (fb != null)
return fb.MetadataTokenInternal;
else
{
Contract.Assert(m_field is RuntimeFieldInfo);
return m_field.MetadataToken;
}
}
}
public override Module Module { get { return m_field.Module; } }
public new Type GetType() { return base.GetType(); }
#endregion
#region Public Abstract\Virtual Members
public override Type[] GetRequiredCustomModifiers() { return m_field.GetRequiredCustomModifiers(); }
public override Type[] GetOptionalCustomModifiers() { return m_field.GetOptionalCustomModifiers(); }
public override void SetValueDirect(TypedReference obj, Object value)
{
throw new NotImplementedException();
}
public override Object GetValueDirect(TypedReference obj)
{
throw new NotImplementedException();
}
public override RuntimeFieldHandle FieldHandle
{
get { throw new NotImplementedException(); }
}
public override Type FieldType { get { throw new NotImplementedException(); } }
public override Object GetValue(Object obj) { throw new InvalidOperationException(); }
public override void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture) { throw new InvalidOperationException(); }
public override FieldAttributes Attributes { get { return m_field.Attributes; } }
#endregion
}
}
| |
#region License
/*
* Copyright (C) 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
#region Imports
using System;
using System.Collections.Generic;
#endregion
namespace BitCoinSharp.Collections.Generic
{
/// <summary>
/// This class provides skeletal implementations for some of <see cref="IQueue{T}"/>
/// operations.
/// </summary>
/// <remarks>
/// <para>
/// The methods <see cref="Add"/>, <see cref="Remove"/>, and
/// <see cref="Element()"/> are based on the <see cref="Offer"/>,
/// <see cref="Poll"/>, and <see cref="Peek"/> methods respectively but
/// throw exceptions instead of indicating failure via
/// <see langword="false"/> returns.
/// </para>
/// </remarks>
/// <author>Doug Lea</author>
/// <author>Griffin Caprio (.NET)</author>
/// <author>Kenneth Xu</author>
[Serializable]
internal abstract class AbstractQueue<T> : AbstractCollection<T>, IQueue<T> //JDK_1_6
{
/// <summary>
/// Returns the remaining capacity of this queue.
/// </summary>
public abstract int RemainingCapacity { get; }
#region IQueue<T> Members
/// <summary>
/// Inserts the specified element into this queue if it is possible to
/// do so immediately without violating capacity restrictions.
/// </summary>
/// <remarks>
/// When using a capacity-restricted queue, this method is generally
/// preferable to <see cref="Add"/>, which can fail to
/// insert an element only by throwing an exception.
/// </remarks>
/// <param name="element">The element to add.</param>
/// <returns>
/// <c>true</c> if the element was added to this queue. Otherwise
/// <c>false</c>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// If the <paramref name="element"/> is <c>null</c> and the queue
/// implementation doesn't allow <c>null</c>.
/// </exception>
/// <exception cref="ArgumentException">
/// If some property of the supplied <paramref name="element"/>
/// prevents it from being added to this queue.
/// </exception>
public abstract bool Offer(T element);
/// <summary>
/// Retrieves, but does not remove, the head of this queue.
/// </summary>
/// <remarks>
/// <para>
/// This method differs from <see cref="Peek(out T)"/> in that it throws an
/// exception if this queue is empty.
/// </para>
/// <para>
/// this implementation returns the result of <see cref="Peek"/>
/// unless the queue is empty.
/// </para>
/// </remarks>
/// <returns>The head of this queue.</returns>
/// <exception cref="InvalidOperationException">
/// If this queue is empty.
/// </exception>
public virtual T Element()
{
T element;
if (Peek(out element))
{
return element;
}
else
{
throw new InvalidOperationException("Queue is empty.");
}
}
/// <summary>
/// Retrieves, but does not remove, the head of this queue into out
/// parameter <paramref name="element"/>.
/// </summary>
/// <param name="element">
/// The head of this queue. <c>default(T)</c> if queue is empty.
/// </param>
/// <returns>
/// <c>false</c> is the queue is empty. Otherwise <c>true</c>.
/// </returns>
public abstract bool Peek(out T element);
/// <summary>
/// Retrieves and removes the head of this queue.
/// </summary>
/// <returns>The head of this queue</returns>
/// <exception cref="InvalidOperationException">
/// If this queue is empty.
/// </exception>
public virtual T Remove()
{
T element;
if (Poll(out element))
{
return element;
}
else
{
throw new InvalidOperationException("Queue is empty.");
}
}
/// <summary>
/// Retrieves and removes the head of this queue into out parameter
/// <paramref name="element"/>.
/// </summary>
/// <param name="element">
/// Set to the head of this queue. <c>default(T)</c> if queue is empty.
/// </param>
/// <returns>
/// <c>false</c> if the queue is empty. Otherwise <c>true</c>.
/// </returns>
public abstract bool Poll(out T element);
#endregion
#region ICollection<T> Members
/// <summary>
/// Inserts the specified <paramref name="element"/> into this queue
/// if it is possible to do so immediately without violating capacity
/// restrictions. Throws an <see cref="InvalidOperationException"/>
/// if no space is currently available.
/// </summary>
/// <param name="element">The element to add.</param>
/// <exception cref="InvalidOperationException">
/// If the <paramref name="element"/> cannot be added at this time due
/// to capacity restrictions.
/// </exception>
public override void Add(T element)
{
if (!Offer(element))
{
throw new InvalidOperationException("Queue full.");
}
}
/// <summary>
/// Removes all items from the queue.
/// </summary>
/// <remarks>
/// This implementation repeatedly calls the <see cref="Poll"/> moethod
/// until it returns <c>false</c>.
/// </remarks>
public override void Clear()
{
T element;
while (Poll(out element))
{
}
}
#endregion
#region IQueue Members
/// <summary>
/// Returns <see langword="true"/> if there are no elements in the
/// <see cref="IQueue{T}"/>, <see langword="false"/> otherwise.
/// </summary>
public virtual bool IsEmpty
{
get { return Count == 0; }
}
/// <summary>
/// Returns the current capacity of this queue.
/// </summary>
public abstract int Capacity { get; }
/// <summary>
/// Gets a value indicating whether the <see cref="ICollection{T}"/> is read-only.
/// This implementation always return true;
/// </summary>
///
/// <returns>
/// true if the <see cref="ICollection{T}"/> is read-only; otherwise, false.
/// This implementation always return false as typically a queue should not
/// be read only.
/// </returns>
///
public override bool IsReadOnly
{
get { return false; }
}
#endregion
/// <summary>
/// Removes all available elements from this queue and invoke the given
/// <paramref name="action"/> on each element in order.
/// </summary>
/// <remarks>
/// This operation may be more efficient than repeatedly polling this
/// queue. A failure encountered while attempting to invoke the
/// <paramref name="action"/> on the elements may result in elements
/// being neither, either or both in the queue or processed when the
/// associated exception is thrown.
/// <example> Drain to a non-generic list.
/// <code language="c#">
/// IList c = ...;
/// int count = Drain(delegate(T e) {c.Add(e);});
/// </code>
/// </example>
/// </remarks>
/// <param name="action">The action to performe on each element.</param>
/// <returns>The number of elements processed.</returns>
/// <exception cref="System.InvalidOperationException">
/// If the queue cannot be drained at this time.
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// If the specified action is <see langword="null"/>.
/// </exception>
/// <seealso cref="IQueue{T}.Drain(Action{T}, int)"/>
public virtual int Drain(Action<T> action)
{
return Drain(action, null);
}
/// <summary>
/// Removes all elements that pass the given <paramref name="criteria"/>
/// from this queue and invoke the given <paramref name="action"/> on
/// each element in order.
/// </summary>
/// <remarks>
/// This operation may be more efficient than repeatedly polling this
/// queue. A failure encountered while attempting to invoke the
/// <paramref name="action"/> on the elements may result in elements
/// being neither, either or both in the queue or processed when the
/// associated exception is thrown.
/// <example> Drain to a non-generic list.
/// <code language="c#">
/// IList c = ...;
/// int count = Drain(delegate(T e) {c.Add(e);});
/// </code>
/// </example>
/// </remarks>
/// <param name="action">The action to performe on each element.</param>
/// <param name="criteria">
/// The criteria to select the elements. <c>null</c> selects any element.
/// </param>
/// <returns>The number of elements processed.</returns>
/// <exception cref="System.InvalidOperationException">
/// If the queue cannot be drained at this time.
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// If the specified action is <see langword="null"/>.
/// </exception>
/// <seealso cref="IQueue{T}.Drain(Action{T}, int)"/>
public virtual int Drain(Action<T> action, Predicate<T> criteria)
{
if (action == null) throw new ArgumentNullException("action");
return DoDrain(action, criteria);
}
/// <summary>
/// Removes at most the given number of available elements from this
/// queue and invoke the given <paramref name="action"/> on each
/// element in order.
/// </summary>
/// <remarks>
/// This operation may be more efficient than repeatedly polling this
/// queue. A failure encountered while attempting to invoke the
/// <paramref name="action"/> on the elements may result in elements
/// being neither, either or both in the queue or processed when the
/// associated exception is thrown.
/// </remarks>
/// <param name="action">The action to performe on each element.</param>
/// <param name="maxElements">the maximum number of elements to transfer</param>
/// <returns>The number of elements processed.</returns>
/// <exception cref="System.InvalidOperationException">
/// If the queue cannot be drained at this time.
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// If the specified action is <see langword="null"/>.
/// </exception>
/// <seealso cref="IQueue{T}.Drain(System.Action{T})"/>
public virtual int Drain(Action<T> action, int maxElements)
{
return Drain(action, maxElements, null);
}
/// <summary>
/// Removes at most the given number of elements that pass the given
/// <paramref name="criteria"/>from this queue and invoke the given
/// <paramref name="action"/> on each element in order.
/// </summary>
/// <remarks>
/// This operation may be more efficient than repeatedly polling this
/// queue. A failure encountered while attempting to invoke the
/// <paramref name="action"/> on the elements may result in elements
/// being neither, either or both in the queue or processed when the
/// associated exception is thrown.
/// </remarks>
/// <param name="action">The action to performe on each element.</param>
/// <param name="maxElements">the maximum number of elements to transfer</param>
/// <param name="criteria">
/// The criteria to select the elements. <c>null</c> selects any element.
/// </param>
/// <returns>The number of elements processed.</returns>
/// <exception cref="System.InvalidOperationException">
/// If the queue cannot be drained at this time.
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// If the specified action is <see langword="null"/>.
/// </exception>
/// <seealso cref="IQueue{T}.Drain(System.Action{T})"/>
public virtual int Drain(Action<T> action, int maxElements, Predicate<T> criteria)
{
if (action == null) throw new ArgumentNullException("action");
if (maxElements <= 0) return 0;
return DoDrain(action, maxElements, criteria);
}
/// <summary>
/// Does the real work for all drain methods. Caller must
/// guarantee the <paramref name="action"/> is not <c>null</c> and
/// <paramref name="maxElements"/> is greater then zero (0).
/// </summary>
/// <seealso cref="IQueue{T}.Drain(System.Action{T})"/>
/// <seealso cref="IQueue{T}.Drain(System.Action{T}, int)"/>
/// <seealso cref="IQueue{T}.Drain(System.Action{T}, Predicate{T})"/>
/// <seealso cref="IQueue{T}.Drain(System.Action{T}, int, Predicate{T})"/>
protected internal abstract int DoDrain(Action<T> action, int maxElements, Predicate<T> criteria);
/// <summary>
/// Does the real work for the <see cref="AbstractQueue{T}.Drain(System.Action{T})"/>
/// and <see cref="AbstractQueue{T}.Drain(System.Action{T},Predicate{T})"/>.
/// </summary>
protected internal virtual int DoDrain(Action<T> action, Predicate<T> criteria)
{
return DoDrain(action, int.MaxValue, criteria);
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Cloud.Iam.V1
{
/// <summary>Settings for <see cref="IAMPolicyClient"/> instances.</summary>
public sealed partial class IAMPolicySettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="IAMPolicySettings"/>.</summary>
/// <returns>A new instance of the default <see cref="IAMPolicySettings"/>.</returns>
public static IAMPolicySettings GetDefault() => new IAMPolicySettings();
/// <summary>Constructs a new <see cref="IAMPolicySettings"/> object with default settings.</summary>
public IAMPolicySettings()
{
}
private IAMPolicySettings(IAMPolicySettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
SetIamPolicySettings = existing.SetIamPolicySettings;
GetIamPolicySettings = existing.GetIamPolicySettings;
TestIamPermissionsSettings = existing.TestIamPermissionsSettings;
OnCopy(existing);
}
partial void OnCopy(IAMPolicySettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>IAMPolicyClient.SetIamPolicy</c> and <c>IAMPolicyClient.SetIamPolicyAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>No timeout is applied.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings SetIamPolicySettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>IAMPolicyClient.GetIamPolicy</c> and <c>IAMPolicyClient.GetIamPolicyAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>No timeout is applied.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetIamPolicySettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>IAMPolicyClient.TestIamPermissions</c> and <c>IAMPolicyClient.TestIamPermissionsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>No timeout is applied.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings TestIamPermissionsSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None);
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="IAMPolicySettings"/> object.</returns>
public IAMPolicySettings Clone() => new IAMPolicySettings(this);
}
/// <summary>
/// Builder class for <see cref="IAMPolicyClient"/> to provide simple configuration of credentials, endpoint etc.
/// </summary>
public sealed partial class IAMPolicyClientBuilder : gaxgrpc::ClientBuilderBase<IAMPolicyClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public IAMPolicySettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public IAMPolicyClientBuilder()
{
UseJwtAccessWithScopes = IAMPolicyClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref IAMPolicyClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<IAMPolicyClient> task);
/// <summary>Builds the resulting client.</summary>
public override IAMPolicyClient Build()
{
IAMPolicyClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<IAMPolicyClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<IAMPolicyClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private IAMPolicyClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return IAMPolicyClient.Create(callInvoker, Settings);
}
private async stt::Task<IAMPolicyClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return IAMPolicyClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => IAMPolicyClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => IAMPolicyClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => IAMPolicyClient.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>IAMPolicy client wrapper, for convenient use.</summary>
/// <remarks>
/// ## API Overview
///
/// Manages Identity and Access Management (IAM) policies.
///
/// Any implementation of an API that offers access control features
/// implements the google.iam.v1.IAMPolicy interface.
///
/// ## Data model
///
/// Access control is applied when a principal (user or service account), takes
/// some action on a resource exposed by a service. Resources, identified by
/// URI-like names, are the unit of access control specification. Service
/// implementations can choose the granularity of access control and the
/// supported permissions for their resources.
/// For example one database service may allow access control to be
/// specified only at the Table level, whereas another might allow access control
/// to also be specified at the Column level.
///
/// ## Policy Structure
///
/// See google.iam.v1.Policy
///
/// This is intentionally not a CRUD style API because access control policies
/// are created and deleted implicitly with the resources to which they are
/// attached.
/// </remarks>
public abstract partial class IAMPolicyClient
{
/// <summary>
/// The default endpoint for the IAMPolicy service, which is a host of "iam-meta-api.googleapis.com" and a port
/// of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "iam-meta-api.googleapis.com:443";
/// <summary>The default IAMPolicy scopes.</summary>
/// <remarks>The default IAMPolicy scopes are:<list type="bullet"></list></remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { });
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="IAMPolicyClient"/> using the default credentials, endpoint and settings.
/// To specify custom credentials or other settings, use <see cref="IAMPolicyClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="IAMPolicyClient"/>.</returns>
public static stt::Task<IAMPolicyClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new IAMPolicyClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="IAMPolicyClient"/> using the default credentials, endpoint and settings.
/// To specify custom credentials or other settings, use <see cref="IAMPolicyClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="IAMPolicyClient"/>.</returns>
public static IAMPolicyClient Create() => new IAMPolicyClientBuilder().Build();
/// <summary>
/// Creates a <see cref="IAMPolicyClient"/> 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="IAMPolicySettings"/>.</param>
/// <returns>The created <see cref="IAMPolicyClient"/>.</returns>
internal static IAMPolicyClient Create(grpccore::CallInvoker callInvoker, IAMPolicySettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
IAMPolicy.IAMPolicyClient grpcClient = new IAMPolicy.IAMPolicyClient(callInvoker);
return new IAMPolicyClientImpl(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 IAMPolicy client</summary>
public virtual IAMPolicy.IAMPolicyClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Sets the access control policy on the specified resource. Replaces any
/// existing policy.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Policy SetIamPolicy(SetIamPolicyRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Sets the access control policy on the specified resource. Replaces any
/// existing policy.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Policy> SetIamPolicyAsync(SetIamPolicyRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Sets the access control policy on the specified resource. Replaces any
/// existing policy.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Policy> SetIamPolicyAsync(SetIamPolicyRequest request, st::CancellationToken cancellationToken) =>
SetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Gets the access control policy for a resource.
/// Returns an empty policy if the resource exists and does not have a policy
/// set.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Policy GetIamPolicy(GetIamPolicyRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Gets the access control policy for a resource.
/// Returns an empty policy if the resource exists and does not have a policy
/// set.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Policy> GetIamPolicyAsync(GetIamPolicyRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Gets the access control policy for a resource.
/// Returns an empty policy if the resource exists and does not have a policy
/// set.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Policy> GetIamPolicyAsync(GetIamPolicyRequest request, st::CancellationToken cancellationToken) =>
GetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns permissions that a caller has on the specified resource.
/// If the resource does not exist, this will return an empty set of
/// permissions, not a NOT_FOUND error.
///
/// Note: This operation is designed to be used for building permission-aware
/// UIs and command-line tools, not for authorization checking. This operation
/// may "fail open" without warning.
/// </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 TestIamPermissionsResponse TestIamPermissions(TestIamPermissionsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns permissions that a caller has on the specified resource.
/// If the resource does not exist, this will return an empty set of
/// permissions, not a NOT_FOUND error.
///
/// Note: This operation is designed to be used for building permission-aware
/// UIs and command-line tools, not for authorization checking. This operation
/// may "fail open" without warning.
/// </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<TestIamPermissionsResponse> TestIamPermissionsAsync(TestIamPermissionsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns permissions that a caller has on the specified resource.
/// If the resource does not exist, this will return an empty set of
/// permissions, not a NOT_FOUND error.
///
/// Note: This operation is designed to be used for building permission-aware
/// UIs and command-line tools, not for authorization checking. This operation
/// may "fail open" without warning.
/// </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<TestIamPermissionsResponse> TestIamPermissionsAsync(TestIamPermissionsRequest request, st::CancellationToken cancellationToken) =>
TestIamPermissionsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>IAMPolicy client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// ## API Overview
///
/// Manages Identity and Access Management (IAM) policies.
///
/// Any implementation of an API that offers access control features
/// implements the google.iam.v1.IAMPolicy interface.
///
/// ## Data model
///
/// Access control is applied when a principal (user or service account), takes
/// some action on a resource exposed by a service. Resources, identified by
/// URI-like names, are the unit of access control specification. Service
/// implementations can choose the granularity of access control and the
/// supported permissions for their resources.
/// For example one database service may allow access control to be
/// specified only at the Table level, whereas another might allow access control
/// to also be specified at the Column level.
///
/// ## Policy Structure
///
/// See google.iam.v1.Policy
///
/// This is intentionally not a CRUD style API because access control policies
/// are created and deleted implicitly with the resources to which they are
/// attached.
/// </remarks>
public sealed partial class IAMPolicyClientImpl : IAMPolicyClient
{
private readonly gaxgrpc::ApiCall<SetIamPolicyRequest, Policy> _callSetIamPolicy;
private readonly gaxgrpc::ApiCall<GetIamPolicyRequest, Policy> _callGetIamPolicy;
private readonly gaxgrpc::ApiCall<TestIamPermissionsRequest, TestIamPermissionsResponse> _callTestIamPermissions;
/// <summary>
/// Constructs a client wrapper for the IAMPolicy service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="IAMPolicySettings"/> used within this client.</param>
public IAMPolicyClientImpl(IAMPolicy.IAMPolicyClient grpcClient, IAMPolicySettings settings)
{
GrpcClient = grpcClient;
IAMPolicySettings effectiveSettings = settings ?? IAMPolicySettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callSetIamPolicy = clientHelper.BuildApiCall<SetIamPolicyRequest, Policy>(grpcClient.SetIamPolicyAsync, grpcClient.SetIamPolicy, effectiveSettings.SetIamPolicySettings).WithGoogleRequestParam("resource", request => request.Resource);
Modify_ApiCall(ref _callSetIamPolicy);
Modify_SetIamPolicyApiCall(ref _callSetIamPolicy);
_callGetIamPolicy = clientHelper.BuildApiCall<GetIamPolicyRequest, Policy>(grpcClient.GetIamPolicyAsync, grpcClient.GetIamPolicy, effectiveSettings.GetIamPolicySettings).WithGoogleRequestParam("resource", request => request.Resource);
Modify_ApiCall(ref _callGetIamPolicy);
Modify_GetIamPolicyApiCall(ref _callGetIamPolicy);
_callTestIamPermissions = clientHelper.BuildApiCall<TestIamPermissionsRequest, TestIamPermissionsResponse>(grpcClient.TestIamPermissionsAsync, grpcClient.TestIamPermissions, effectiveSettings.TestIamPermissionsSettings).WithGoogleRequestParam("resource", request => request.Resource);
Modify_ApiCall(ref _callTestIamPermissions);
Modify_TestIamPermissionsApiCall(ref _callTestIamPermissions);
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_SetIamPolicyApiCall(ref gaxgrpc::ApiCall<SetIamPolicyRequest, Policy> call);
partial void Modify_GetIamPolicyApiCall(ref gaxgrpc::ApiCall<GetIamPolicyRequest, Policy> call);
partial void Modify_TestIamPermissionsApiCall(ref gaxgrpc::ApiCall<TestIamPermissionsRequest, TestIamPermissionsResponse> call);
partial void OnConstruction(IAMPolicy.IAMPolicyClient grpcClient, IAMPolicySettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC IAMPolicy client</summary>
public override IAMPolicy.IAMPolicyClient GrpcClient { get; }
partial void Modify_SetIamPolicyRequest(ref SetIamPolicyRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_GetIamPolicyRequest(ref GetIamPolicyRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_TestIamPermissionsRequest(ref TestIamPermissionsRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Sets the access control policy on the specified resource. Replaces any
/// existing policy.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override Policy SetIamPolicy(SetIamPolicyRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_SetIamPolicyRequest(ref request, ref callSettings);
return _callSetIamPolicy.Sync(request, callSettings);
}
/// <summary>
/// Sets the access control policy on the specified resource. Replaces any
/// existing policy.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<Policy> SetIamPolicyAsync(SetIamPolicyRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_SetIamPolicyRequest(ref request, ref callSettings);
return _callSetIamPolicy.Async(request, callSettings);
}
/// <summary>
/// Gets the access control policy for a resource.
/// Returns an empty policy if the resource exists and does not have a policy
/// set.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override Policy GetIamPolicy(GetIamPolicyRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetIamPolicyRequest(ref request, ref callSettings);
return _callGetIamPolicy.Sync(request, callSettings);
}
/// <summary>
/// Gets the access control policy for a resource.
/// Returns an empty policy if the resource exists and does not have a policy
/// set.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<Policy> GetIamPolicyAsync(GetIamPolicyRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetIamPolicyRequest(ref request, ref callSettings);
return _callGetIamPolicy.Async(request, callSettings);
}
/// <summary>
/// Returns permissions that a caller has on the specified resource.
/// If the resource does not exist, this will return an empty set of
/// permissions, not a NOT_FOUND error.
///
/// Note: This operation is designed to be used for building permission-aware
/// UIs and command-line tools, not for authorization checking. This operation
/// may "fail open" without warning.
/// </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 TestIamPermissionsResponse TestIamPermissions(TestIamPermissionsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_TestIamPermissionsRequest(ref request, ref callSettings);
return _callTestIamPermissions.Sync(request, callSettings);
}
/// <summary>
/// Returns permissions that a caller has on the specified resource.
/// If the resource does not exist, this will return an empty set of
/// permissions, not a NOT_FOUND error.
///
/// Note: This operation is designed to be used for building permission-aware
/// UIs and command-line tools, not for authorization checking. This operation
/// may "fail open" without warning.
/// </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<TestIamPermissionsResponse> TestIamPermissionsAsync(TestIamPermissionsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_TestIamPermissionsRequest(ref request, ref callSettings);
return _callTestIamPermissions.Async(request, callSettings);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace ComparedQueryable.NativeQueryable
{
internal class EnumerableRewriter : ExpressionVisitor
{
// We must ensure that if a LabelTarget is rewritten that it is always rewritten to the same new target
// or otherwise expressions using it won't match correctly.
private Dictionary<LabelTarget, LabelTarget> _targetCache;
// Finding equivalent types can be relatively expensive, and hitting with the same types repeatedly is quite likely.
private Dictionary<Type, Type> _equivalentTypeCache;
protected override Expression VisitMethodCall(MethodCallExpression m)
{
Expression obj = Visit(m.Object);
ReadOnlyCollection<Expression> args = Visit(m.Arguments);
// check for args changed
if (obj != m.Object || args != m.Arguments)
{
MethodInfo mInfo = m.Method;
Type[] typeArgs = (mInfo.IsGenericMethod) ? mInfo.GetGenericArguments() : null;
if ((mInfo.IsStatic || mInfo.DeclaringType.IsAssignableFrom(obj.Type))
&& ArgsMatch(mInfo, args, typeArgs))
{
// current method is still valid
return Expression.Call(obj, mInfo, args);
}
else if (mInfo.DeclaringType == typeof(Queryable))
{
// convert Queryable method to Enumerable method
MethodInfo seqMethod = FindEnumerableMethod(mInfo.Name, args, typeArgs);
args = FixupQuotedArgs(seqMethod, args);
return Expression.Call(obj, seqMethod, args);
}
else
{
// rebind to new method
MethodInfo method = FindMethod(mInfo.DeclaringType, mInfo.Name, args, typeArgs);
args = FixupQuotedArgs(method, args);
return Expression.Call(obj, method, args);
}
}
return m;
}
protected virtual ReadOnlyCollection<Expression> FixupQuotedArgs(MethodInfo mi, ReadOnlyCollection<Expression> argList)
{
ParameterInfo[] pis = mi.GetParameters();
if (pis.Length > 0)
{
List<Expression> newArgs = null;
// Since mi may have more parameters than are passed into the set of args (such as in the case of a
// custom comparer passed to the OrderBy method), we should iterate the values found in the arglist
// rather than in the method info parameters to avoid index out of range exceptions.
for (int i = 0, n = argList.Count; i < n; i++)
{
Expression arg = argList[i];
ParameterInfo pi = pis[i];
arg = FixupQuotedExpression(pi.ParameterType, arg);
if (newArgs == null && arg != argList[i])
{
newArgs = new List<Expression>(argList.Count);
for (int j = 0; j < i; j++)
{
newArgs.Add(argList[j]);
}
}
newArgs?.Add(arg);
}
if (newArgs != null)
argList = newArgs.AsReadOnly();
}
return argList;
}
private Expression FixupQuotedExpression(Type type, Expression expression)
{
Expression expr = expression;
while (true)
{
if (type.IsAssignableFrom(expr.Type))
return expr;
if (expr.NodeType != ExpressionType.Quote)
break;
expr = ((UnaryExpression)expr).Operand;
}
if (!type.IsAssignableFrom(expr.Type) && type.IsArray && expr.NodeType == ExpressionType.NewArrayInit)
{
Type strippedType = StripExpression(expr.Type);
if (type.IsAssignableFrom(strippedType))
{
Type elementType = type.GetElementType();
NewArrayExpression na = (NewArrayExpression)expr;
List<Expression> exprs = new List<Expression>(na.Expressions.Count);
for (int i = 0, n = na.Expressions.Count; i < n; i++)
{
exprs.Add(FixupQuotedExpression(elementType, na.Expressions[i]));
}
expression = Expression.NewArrayInit(elementType, exprs);
}
}
return expression;
}
protected override Expression VisitLambda<T>(Expression<T> node) => node;
private static Type GetPublicType(Type t)
{
// If we create a constant explicitly typed to be a private nested type,
// such as Lookup<,>.Grouping or a compiler-generated iterator class, then
// we cannot use the expression tree in a context which has only execution
// permissions. We should endeavour to translate constants into
// new constants which have public types.
if (t.IsGenericType && t.GetGenericTypeDefinition().GetInterfaces().Contains(typeof(IGrouping<,>)))
return typeof(IGrouping<,>).MakeGenericType(t.GetGenericArguments());
if (!t.IsNestedPrivate)
return t;
foreach (Type iType in t.GetInterfaces())
{
if (iType.IsGenericType && iType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
return iType;
}
if (typeof(IEnumerable).IsAssignableFrom(t))
return typeof(IEnumerable);
return t;
}
private Type GetEquivalentType(Type type)
{
Type equiv;
if (_equivalentTypeCache == null)
{
// Pre-loading with the non-generic IQueryable and IEnumerable not only covers this case
// without any reflection-based introspection, but also means the slightly different
// code needed to catch this case can be omitted safely.
_equivalentTypeCache = new Dictionary<Type, Type>
{
{ typeof(IQueryable), typeof(IEnumerable) },
{ typeof(IEnumerable), typeof(IEnumerable) }
};
}
if (!_equivalentTypeCache.TryGetValue(type, out equiv))
{
Type pubType = GetPublicType(type);
if (pubType.IsInterface && pubType.IsGenericType)
{
Type genericType = pubType.GetGenericTypeDefinition();
if (genericType == typeof(IOrderedEnumerable<>))
equiv = pubType;
else if (genericType == typeof(IOrderedQueryable<>))
equiv = typeof(IOrderedEnumerable<>).MakeGenericType(pubType.GenericTypeArguments[0]);
else if (genericType == typeof(IEnumerable<>))
equiv = pubType;
else if (genericType == typeof(IQueryable<>))
equiv = typeof(IEnumerable<>).MakeGenericType(pubType.GenericTypeArguments[0]);
}
if (equiv == null)
{
var interfacesWithInfo = pubType.GetInterfaces().Select(IntrospectionExtensions.GetTypeInfo).ToArray();
var singleTypeGenInterfacesWithGetType = interfacesWithInfo
.Where(i => i.IsGenericType && i.GenericTypeArguments.Length == 1)
.Select(i => new {Info = i, GenType = i.GetGenericTypeDefinition() })
.ToArray();
Type typeArg = singleTypeGenInterfacesWithGetType
.Where(i => i.GenType == typeof(IOrderedQueryable<>) || i.GenType == typeof(IOrderedEnumerable<>))
.Select(i => i.Info.GenericTypeArguments[0])
.Distinct()
.SingleOrDefault();
if (typeArg != null)
equiv = typeof(IOrderedEnumerable<>).MakeGenericType(typeArg);
else
{
typeArg = singleTypeGenInterfacesWithGetType
.Where(i => i.GenType == typeof(IQueryable<>) || i.GenType == typeof(IEnumerable<>))
.Select(i => i.Info.GenericTypeArguments[0])
.Distinct()
.Single();
equiv = typeof(IEnumerable<>).MakeGenericType(typeArg);
}
}
_equivalentTypeCache.Add(type, equiv);
}
return equiv;
}
protected override Expression VisitConstant(ConstantExpression c)
{
EnumerableQuery sq = c.Value as EnumerableQuery;
if (sq != null)
{
if (sq.Enumerable != null)
{
Type t = GetPublicType(sq.Enumerable.GetType());
return Expression.Constant(sq.Enumerable, t);
}
Expression exp = sq.Expression;
if (exp != c)
return Visit(exp);
}
return c;
}
private static ILookup<string, MethodInfo> s_seqMethods;
private MethodInfo FindEnumerableMethod(string name, ReadOnlyCollection<Expression> args, params Type[] typeArgs)
{
if (s_seqMethods == null)
{
s_seqMethods = typeof(Enumerable).GetStaticMethods().ToLookup(m => m.Name);
}
MethodInfo mi = s_seqMethods[name].FirstOrDefault(m => ArgsMatch(m, args, typeArgs));
Debug.Assert(mi != null, "All static methods with arguments on Queryable have equivalents on Enumerable.");
if (typeArgs != null)
return GetGenericMethod(typeArgs, mi, s_seqMethods[name]);
return mi;
}
protected virtual MethodInfo GetGenericMethod(Type[] typeArgs,
MethodInfo matchingMethodInfo,
IEnumerable<MethodInfo> potentialMethodMatches)
{
return matchingMethodInfo.MakeGenericMethod(typeArgs);
}
private static MethodInfo FindMethod(Type type, string name, ReadOnlyCollection<Expression> args, Type[] typeArgs)
{
using (IEnumerator<MethodInfo> en = type.GetStaticMethods().Where(m => m.Name == name).GetEnumerator())
{
if (!en.MoveNext())
throw Error.NoMethodOnType(name, type);
do
{
MethodInfo mi = en.Current;
if (ArgsMatch(mi, args, typeArgs))
return (typeArgs != null) ? mi.MakeGenericMethod(typeArgs) : mi;
} while (en.MoveNext());
}
throw Error.NoMethodOnTypeMatchingArguments(name, type);
}
private static bool ArgsMatch(MethodInfo m, ReadOnlyCollection<Expression> args, Type[] typeArgs)
{
ParameterInfo[] mParams = m.GetParameters();
if (mParams.Length != args.Count)
return false;
if (!m.IsGenericMethod && typeArgs != null && typeArgs.Length > 0)
{
return false;
}
if (!m.IsGenericMethodDefinition && m.IsGenericMethod && m.ContainsGenericParameters)
{
m = m.GetGenericMethodDefinition();
}
if (m.IsGenericMethodDefinition)
{
if (typeArgs == null || typeArgs.Length == 0)
return false;
if (m.GetGenericArguments().Length != typeArgs.Length)
return false;
m = m.MakeGenericMethod(typeArgs);
mParams = m.GetParameters();
}
for (int i = 0, n = args.Count; i < n; i++)
{
Type parameterType = mParams[i].ParameterType;
if (parameterType == null)
return false;
if (parameterType.IsByRef)
parameterType = parameterType.GetElementType();
Expression arg = args[i];
if (!parameterType.IsAssignableFrom(arg.Type))
{
if (arg.NodeType == ExpressionType.Quote)
{
arg = ((UnaryExpression)arg).Operand;
}
if (!parameterType.IsAssignableFrom(arg.Type) &&
!parameterType.IsAssignableFrom(StripExpression(arg.Type)))
{
return false;
}
}
}
return true;
}
private static Type StripExpression(Type type)
{
bool isArray = type.IsArray;
Type tmp = isArray ? type.GetElementType() : type;
Type eType = TypeHelper.FindGenericType(typeof(Expression<>), tmp);
if (eType != null)
tmp = eType.GetGenericArguments()[0];
if (isArray)
{
int rank = type.GetArrayRank();
return (rank == 1) ? tmp.MakeArrayType() : tmp.MakeArrayType(rank);
}
return type;
}
protected override Expression VisitConditional(ConditionalExpression c)
{
Type type = c.Type;
if (!typeof(IQueryable).IsAssignableFrom(type))
return base.VisitConditional(c);
Expression test = Visit(c.Test);
Expression ifTrue = Visit(c.IfTrue);
Expression ifFalse = Visit(c.IfFalse);
Type trueType = ifTrue.Type;
Type falseType = ifFalse.Type;
if (trueType.IsAssignableFrom(falseType))
return Expression.Condition(test, ifTrue, ifFalse, trueType);
if (falseType.IsAssignableFrom(trueType))
return Expression.Condition(test, ifTrue, ifFalse, falseType);
return Expression.Condition(test, ifTrue, ifFalse, GetEquivalentType(type));
}
protected override Expression VisitBlock(BlockExpression node)
{
Type type = node.Type;
if (!typeof(IQueryable).IsAssignableFrom(type))
return base.VisitBlock(node);
ReadOnlyCollection<Expression> nodes = Visit(node.Expressions);
ReadOnlyCollection<ParameterExpression> variables = VisitAndConvert(node.Variables, "EnumerableRewriter.VisitBlock");
if (type == node.Expressions.Last().Type)
return Expression.Block(variables, nodes);
return Expression.Block(GetEquivalentType(type), variables, nodes);
}
protected override Expression VisitGoto(GotoExpression node)
{
Type type = node.Value.Type;
if (!typeof(IQueryable).IsAssignableFrom(type))
return base.VisitGoto(node);
LabelTarget target = VisitLabelTarget(node.Target);
Expression value = Visit(node.Value);
return Expression.MakeGoto(node.Kind, target, value, GetEquivalentType(typeof(EnumerableQuery).IsAssignableFrom(type) ? value.Type : type));
}
protected override LabelTarget VisitLabelTarget(LabelTarget node)
{
LabelTarget newTarget;
if (_targetCache == null)
_targetCache = new Dictionary<LabelTarget, LabelTarget>();
else if (_targetCache.TryGetValue(node, out newTarget))
return newTarget;
Type type = node.Type;
if (!typeof(IQueryable).IsAssignableFrom(type))
newTarget = base.VisitLabelTarget(node);
else
newTarget = Expression.Label(GetEquivalentType(type), node.Name);
_targetCache.Add(node, newTarget);
return newTarget;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Abp.Authorization;
using Abp.Runtime.Session;
using Abp.UI;
using Helios.Authorization;
using Helios.Editions;
using Helios.Editions.Dto;
using Helios.MultiTenancy.Dto;
using Helios.MultiTenancy.Payments.Cache;
using Helios.MultiTenancy.Payments.Dto;
using Abp.Application.Services.Dto;
using Microsoft.EntityFrameworkCore;
using System.Linq.Dynamic.Core;
using Abp.Domain.Repositories;
using Abp.Linq.Extensions;
namespace Helios.MultiTenancy.Payments
{
public class PaymentAppService : HeliosZeroAppServiceBase, IPaymentAppService
{
private readonly ISubscriptionPaymentRepository _subscriptionPaymentRepository;
private readonly EditionManager _editionManager;
private readonly IPaymentGatewayManagerFactory _paymentGatewayManagerFactory;
private readonly IPaymentCache _paymentCache;
public PaymentAppService(
ISubscriptionPaymentRepository subscriptionPaymentRepository,
EditionManager editionManager,
IPaymentGatewayManagerFactory paymentGatewayManagerFactory, IPaymentCache paymentCache)
{
_subscriptionPaymentRepository = subscriptionPaymentRepository;
_editionManager = editionManager;
_paymentGatewayManagerFactory = paymentGatewayManagerFactory;
_paymentCache = paymentCache;
}
[AbpAuthorize(AppPermissions.Pages_Administration_Tenant_SubscriptionManagement)]
public async Task<PaymentInfoDto> GetPaymentInfo(PaymentInfoInput input)
{
var tenant = await TenantManager.GetByIdAsync(AbpSession.GetTenantId());
if (tenant.EditionId == null)
{
throw new UserFriendlyException(L("TenantEditionIsNotAssigned"));
}
var currentEdition = (SubscribableEdition)await _editionManager.GetByIdAsync(tenant.EditionId.Value);
var targetEdition = input.UpgradeEditionId == null ? currentEdition : (SubscribableEdition)await _editionManager.GetByIdAsync(input.UpgradeEditionId.Value);
decimal additionalPrice = 0;
if (input.UpgradeEditionId.HasValue)
{
var remainingDaysCount = tenant.CalculateRemainingDayCount();
if (remainingDaysCount > 0)
{
additionalPrice = TenantManager
.GetUpgradePrice(
currentEdition,
targetEdition,
remainingDaysCount
);
}
}
var edition = ObjectMapper.Map<EditionSelectDto>(input.UpgradeEditionId == null ? currentEdition : targetEdition);
await SetAdditionalDataForPaymentGateways(edition);
return new PaymentInfoDto
{
Edition = edition,
AdditionalPrice = additionalPrice
};
}
private async Task SetAdditionalDataForPaymentGateways(EditionSelectDto edition)
{
foreach (var paymentGateway in Enum.GetValues(typeof(SubscriptionPaymentGatewayType)).Cast<SubscriptionPaymentGatewayType>())
{
using (var paymentGatewayManager = _paymentGatewayManagerFactory.Create(paymentGateway))
{
var additionalData = await paymentGatewayManager.Object.GetAdditionalPaymentData(ObjectMapper.Map<SubscribableEdition>(edition));
edition.AdditionalData.Add(paymentGateway, additionalData);
}
}
}
public async Task<CreatePaymentResponse> CreatePayment(CreatePaymentDto input)
{
var targetEdition = (SubscribableEdition)await _editionManager.GetByIdAsync(input.EditionId);
var tenant = AbpSession.TenantId == null ? null : await TenantManager.GetByIdAsync(AbpSession.GetTenantId());
var amount = await CalculateAmountForPaymentAsync(targetEdition, input.PaymentPeriodType, input.EditionPaymentType, tenant);
using (var paymentGatewayManager = _paymentGatewayManagerFactory.Create(input.SubscriptionPaymentGatewayType))
{
var createPaymentResult = await paymentGatewayManager.Object.CreatePaymentAsync(CalculatePaymentDescription(input, targetEdition), amount);
await _subscriptionPaymentRepository.InsertAsync(
new SubscriptionPayment
{
PaymentPeriodType = input.PaymentPeriodType,
EditionId = input.EditionId,
TenantId = tenant == null ? 0 : tenant.Id,
Gateway = input.SubscriptionPaymentGatewayType,
Amount = amount,
DayCount = input.PaymentPeriodType.HasValue ? (int)input.PaymentPeriodType.Value : 0,
PaymentId = createPaymentResult.GetId(),
Status = SubscriptionPaymentStatus.Processing
}
);
return createPaymentResult;
}
}
public async Task<ExecutePaymentResponse> ExecutePayment(ExecutePaymentDto input)
{
using (var paymentGatewayManager = _paymentGatewayManagerFactory.Create(input.Gateway))
{
var executePaymentResponse = await paymentGatewayManager.Object.ExecutePaymentAsync(input.AdditionalData);
await _subscriptionPaymentRepository.UpdateByGatewayAndPaymentIdAsync(
input.Gateway,
executePaymentResponse.GetId(),
AbpSession.TenantId,
SubscriptionPaymentStatus.Completed
);
var paymentId = executePaymentResponse.GetId();
_paymentCache.AddCacheItem(new PaymentCacheItem(input.Gateway, input.PaymentPeriodType, paymentId));
if (AbpSession.TenantId.HasValue)
{
await TenantManager.UpdateTenantAsync(
AbpSession.GetTenantId(),
true,
false,
input.PaymentPeriodType,
input.EditionId,
input.EditionPaymentType
);
}
return executePaymentResponse;
}
}
public async Task<PagedResultDto<SubscriptionPaymentListDto>> GetPaymentHistory(GetPaymentHistoryInput input)
{
var query = _subscriptionPaymentRepository.GetAll()
.Include(sp => sp.Edition)
.Where(sp => sp.TenantId == AbpSession.GetTenantId())
.OrderBy(input.Sorting);
var payments = await query.OrderBy(input.Sorting).PageBy(input).ToListAsync();
var paymentsCount = query.Count();
return new PagedResultDto<SubscriptionPaymentListDto>(paymentsCount, ObjectMapper.Map<List<SubscriptionPaymentListDto>>(payments));
}
private async Task<decimal> CalculateAmountForPaymentAsync(SubscribableEdition targetEdition, PaymentPeriodType? periodType, EditionPaymentType editionPaymentType, Tenant tenant)
{
if (editionPaymentType != EditionPaymentType.Upgrade)
{
return targetEdition.GetPaymentAmount(periodType);
}
if (tenant.EditionId == null)
{
throw new UserFriendlyException(L("CanNotUpgradeSubscriptionSinceTenantHasNoEditionAssigned"));
}
var remainingDaysCount = tenant.CalculateRemainingDayCount();
if (remainingDaysCount <= 0)
{
return targetEdition.GetPaymentAmount(periodType);
}
Debug.Assert(tenant.EditionId != null, "tenant.EditionId != null");
var currentEdition = (SubscribableEdition)await _editionManager.GetByIdAsync(tenant.EditionId.Value);
return TenantManager.GetUpgradePrice(currentEdition, targetEdition, remainingDaysCount);
}
private string CalculatePaymentDescription(CreatePaymentDto input, SubscribableEdition targetEdition)
{
switch (input.EditionPaymentType)
{
case EditionPaymentType.NewRegistration:
case EditionPaymentType.BuyNow:
return L("Purchase");
case EditionPaymentType.Upgrade:
return L("UpgradedTo", targetEdition.DisplayName);
case EditionPaymentType.Extend:
return L("ExtendedEdition", targetEdition.DisplayName);
default:
throw new ArgumentException(nameof(input.EditionPaymentType));
}
}
}
}
| |
// 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.IO;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Threading;
using Windows.Foundation;
using Windows.Storage.Streams;
namespace System.IO
{
/// <summary>Depending on the concrete type of the stream managed by a <c>NetFxToWinRtStreamAdapter</c>,
/// we want the <c>ReadAsync</c> / <c>WriteAsync</c> / <c>FlushAsync</c> / etc. operation to be implemented
/// differently. This is for best performance as we can take advantage of the specifics of particular stream
/// types. For instance, <c>ReadAsync</c> currently has a special implementation for memory streams.
/// Moreover, knowledge about the actual runtime type of the <c>IBuffer</c> can also help choosing the optimal
/// implementation. This type provides static methods that encapsulate the performance logic and can be used
/// by <c>NetFxToWinRtStreamAdapter</c>.</summary>
internal static class StreamOperationsImplementation
{
#region ReadAsync implementations
internal static IAsyncOperationWithProgress<IBuffer, uint> ReadAsync_MemoryStream(Stream stream, IBuffer buffer, uint count)
{
Debug.Assert(stream != null);
Debug.Assert(stream is MemoryStream);
Debug.Assert(stream.CanRead);
Debug.Assert(stream.CanSeek);
Debug.Assert(buffer != null);
Debug.Assert(buffer is IBufferByteAccess);
Debug.Assert(0 <= count);
Debug.Assert(count <= int.MaxValue);
Debug.Assert(count <= buffer.Capacity);
// We will return a different buffer to the user backed directly by the memory stream (avoids memory copy).
// This is permitted by the WinRT stream contract.
// The user specified buffer will not have any data put into it:
buffer.Length = 0;
MemoryStream memStream = stream as MemoryStream;
Debug.Assert(memStream != null);
try
{
IBuffer dataBuffer = memStream.GetWindowsRuntimeBuffer((int)memStream.Position, (int)count);
if (dataBuffer.Length > 0)
memStream.Seek(dataBuffer.Length, SeekOrigin.Current);
return AsyncInfo.CreateCompletedOperation<IBuffer, uint>(dataBuffer);
}
catch (Exception ex)
{
return AsyncInfo.CreateFaultedOperation<IBuffer, uint>(ex);
}
} // ReadAsync_MemoryStream
internal static IAsyncOperationWithProgress<IBuffer, uint> ReadAsync_AbstractStream(Stream stream, IBuffer buffer, uint count,
InputStreamOptions options)
{
Debug.Assert(stream != null);
Debug.Assert(stream.CanRead);
Debug.Assert(buffer != null);
Debug.Assert(buffer is IBufferByteAccess);
Debug.Assert(0 <= count);
Debug.Assert(count <= int.MaxValue);
Debug.Assert(count <= buffer.Capacity);
Debug.Assert(options == InputStreamOptions.None || options == InputStreamOptions.Partial || options == InputStreamOptions.ReadAhead);
int bytesRequested = (int)count;
// Check if the buffer is our implementation.
// IF YES: In that case, we can read directly into its data array.
// IF NO: The buffer is of unknown implementation. It's not backed by a managed array, but the wrapped stream can only
// read into a managed array. If we used the user-supplied buffer we would need to copy data into it after every read.
// The spec allows to return a buffer instance that is not the same as passed by the user. So, we will create an own
// buffer instance, read data *directly* into the array backing it and then return it to the user.
// Note: the allocation costs we are paying for the new buffer are unavoidable anyway, as we would need to create
// an array to read into either way.
IBuffer dataBuffer = buffer as WindowsRuntimeBuffer;
if (dataBuffer == null)
dataBuffer = WindowsRuntimeBuffer.Create((int)Math.Min((uint)int.MaxValue, buffer.Capacity));
// This operation delegate will we run inside of the returned IAsyncOperationWithProgress:
Func<CancellationToken, IProgress<uint>, Task<IBuffer>> readOperation = async (cancelToken, progressListener) =>
{
// No bytes read yet:
dataBuffer.Length = 0;
// Get the buffer backing array:
byte[] data;
int offset;
bool managedBufferAssert = dataBuffer.TryGetUnderlyingData(out data, out offset);
Debug.Assert(managedBufferAssert);
// Init tracking values:
bool done = cancelToken.IsCancellationRequested;
int bytesCompleted = 0;
// Loop until EOS, cancelled or read enough data according to options:
while (!done)
{
int bytesRead = 0;
try
{
// Read asynchronously:
bytesRead = await stream.ReadAsync(data, offset + bytesCompleted, bytesRequested - bytesCompleted, cancelToken)
.ConfigureAwait(continueOnCapturedContext: false);
// We will continue here on a different thread when read async completed:
bytesCompleted += bytesRead;
// We will handle a cancelation exception and re-throw all others:
}
catch (OperationCanceledException)
{
// We assume that cancelToken.IsCancellationRequested is has been set and simply proceed.
// (we check cancelToken.IsCancellationRequested later)
Debug.Assert(cancelToken.IsCancellationRequested);
// This is because if the cancellation came after we read some bytes we want to return the results we got instead
// of an empty cancelled task, so if we have not yet read anything at all, then we can throw cancellation:
if (bytesCompleted == 0 && bytesRead == 0)
throw;
}
// Update target buffer:
dataBuffer.Length = (uint)bytesCompleted;
Debug.Assert(bytesCompleted <= bytesRequested);
// Check if we are done:
done = options == InputStreamOptions.Partial // If no complete read was requested, any amount of data is OK
|| bytesRead == 0 // this implies EndOfStream
|| bytesCompleted == bytesRequested // read all requested bytes
|| cancelToken.IsCancellationRequested; // operation was cancelled
// Call user Progress handler:
if (progressListener != null)
progressListener.Report(dataBuffer.Length);
} // while (!done)
// If we got here, then no error was detected. Return the results buffer:
return dataBuffer;
}; // readOperation
return AsyncInfo.Run<IBuffer, uint>(readOperation);
} // ReadAsync_AbstractStream
#endregion ReadAsync implementations
#region WriteAsync implementations
internal static IAsyncOperationWithProgress<uint, uint> WriteAsync_AbstractStream(Stream stream, IBuffer buffer)
{
Debug.Assert(stream != null);
Debug.Assert(stream.CanWrite);
Debug.Assert(buffer != null);
// Choose the optimal writing strategy for the kind of buffer supplied:
Func<CancellationToken, IProgress<uint>, Task<uint>> writeOperation;
byte[] data;
int offset;
// If buffer is backed by a managed array:
if (buffer.TryGetUnderlyingData(out data, out offset))
{
writeOperation = async (cancelToken, progressListener) =>
{
if (cancelToken.IsCancellationRequested) // CancellationToken is non-nullable
return 0;
Debug.Assert(buffer.Length <= int.MaxValue);
int bytesToWrite = (int)buffer.Length;
await stream.WriteAsync(data, offset, bytesToWrite, cancelToken).ConfigureAwait(continueOnCapturedContext: false);
if (progressListener != null)
progressListener.Report((uint)bytesToWrite);
return (uint)bytesToWrite;
};
// Otherwise buffer is of an unknown implementation:
}
else
{
writeOperation = async (cancelToken, progressListener) =>
{
if (cancelToken.IsCancellationRequested) // CancellationToken is non-nullable
return 0;
uint bytesToWrite = buffer.Length;
Stream dataStream = buffer.AsStream();
int buffSize = 0x4000;
if (bytesToWrite < buffSize)
buffSize = (int)bytesToWrite;
await dataStream.CopyToAsync(stream, buffSize, cancelToken).ConfigureAwait(continueOnCapturedContext: false);
if (progressListener != null)
progressListener.Report((uint)bytesToWrite);
return (uint)bytesToWrite;
};
} // if-else
// Construct and run the async operation:
return AsyncInfo.Run<uint, uint>(writeOperation);
} // WriteAsync_AbstractStream
#endregion WriteAsync implementations
#region FlushAsync implementations
internal static IAsyncOperation<bool> FlushAsync_AbstractStream(Stream stream)
{
Debug.Assert(stream != null);
Debug.Assert(stream.CanWrite);
Func<CancellationToken, Task<bool>> flushOperation = async (cancelToken) =>
{
if (cancelToken.IsCancellationRequested) // CancellationToken is non-nullable
return false;
await stream.FlushAsync(cancelToken).ConfigureAwait(continueOnCapturedContext: false);
return true;
};
// Construct and run the async operation:
return AsyncInfo.Run<bool>(flushOperation);
}
#endregion FlushAsync implementations
} // class StreamOperationsImplementation
} // namespace
| |
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Diagnostics;
using System.Linq;
namespace Svg
{
/// <summary>
/// The class that all SVG elements should derive from when they are to be rendered.
/// </summary>
public abstract partial class SvgVisualElement : SvgElement, ISvgBoundable, ISvgStylable, ISvgClipable
{
private bool? _requiresSmoothRendering;
private Region _previousClip;
/// <summary>
/// Gets the <see cref="GraphicsPath"/> for this element.
/// </summary>
public abstract GraphicsPath Path(ISvgRenderer renderer);
PointF ISvgBoundable.Location
{
get
{
return Bounds.Location;
}
}
SizeF ISvgBoundable.Size
{
get
{
return Bounds.Size;
}
}
/// <summary>
/// Gets the bounds of the element.
/// </summary>
/// <value>The bounds.</value>
public abstract RectangleF Bounds { get; }
/// <summary>
/// Gets the associated <see cref="SvgClipPath"/> if one has been specified.
/// </summary>
[SvgAttribute("clip")]
public virtual string Clip
{
get { return this.Attributes.GetInheritedAttribute<string>("clip"); }
set { this.Attributes["clip"] = value; }
}
/// <summary>
/// Gets the associated <see cref="SvgClipPath"/> if one has been specified.
/// </summary>
[SvgAttribute("clip-path")]
public virtual Uri ClipPath
{
get { return this.Attributes.GetAttribute<Uri>("clip-path"); }
set { this.Attributes["clip-path"] = value; }
}
/// <summary>
/// Gets or sets the algorithm which is to be used to determine the clipping region.
/// </summary>
[SvgAttribute("clip-rule")]
public SvgClipRule ClipRule
{
get { return this.Attributes.GetAttribute<SvgClipRule>("clip-rule", SvgClipRule.NonZero); }
set { this.Attributes["clip-rule"] = value; }
}
/// <summary>
/// Gets the associated <see cref="SvgClipPath"/> if one has been specified.
/// </summary>
[SvgAttribute("filter")]
public virtual Uri Filter
{
get { return this.Attributes.GetInheritedAttribute<Uri>("filter"); }
set { this.Attributes["filter"] = value; }
}
/// <summary>
/// Gets or sets a value to determine if anti-aliasing should occur when the element is being rendered.
/// </summary>
protected virtual bool RequiresSmoothRendering
{
get
{
if (_requiresSmoothRendering == null)
_requiresSmoothRendering = ConvertShapeRendering2AntiAlias(ShapeRendering);
return _requiresSmoothRendering.Value;
}
}
private bool ConvertShapeRendering2AntiAlias(SvgShapeRendering shapeRendering)
{
switch (shapeRendering)
{
case SvgShapeRendering.OptimizeSpeed:
case SvgShapeRendering.CrispEdges:
case SvgShapeRendering.GeometricPrecision:
return false;
default:
// SvgShapeRendering.Auto
// SvgShapeRendering.Inherit
return true;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="SvgVisualElement"/> class.
/// </summary>
public SvgVisualElement()
{
this.IsPathDirty = true;
}
protected virtual bool Renderable { get { return true; } }
/// <summary>
/// Renders the <see cref="SvgElement"/> and contents to the specified <see cref="Graphics"/> object.
/// </summary>
/// <param name="renderer">The <see cref="ISvgRenderer"/> object to render to.</param>
protected override void Render(ISvgRenderer renderer)
{
this.Render(renderer, true);
}
private void Render(ISvgRenderer renderer, bool renderFilter)
{
if (this.Visible && this.Displayable && this.PushTransforms(renderer) &&
(!Renderable || this.Path(renderer) != null))
{
bool renderNormal = true;
if (renderFilter && this.Filter != null)
{
var filterPath = this.Filter;
if (filterPath.ToString().StartsWith("url("))
{
filterPath = new Uri(filterPath.ToString().Substring(4, filterPath.ToString().Length - 5), UriKind.RelativeOrAbsolute);
}
var filter = this.OwnerDocument.IdManager.GetElementById(filterPath) as FilterEffects.SvgFilter;
if (filter != null)
{
this.PopTransforms(renderer);
try
{
filter.ApplyFilter(this, renderer, (r) => this.Render(r, false));
}
catch (Exception ex) { Debug.Print(ex.ToString()); }
renderNormal = false;
}
}
if (renderNormal)
{
this.SetClip(renderer);
if (Renderable)
{
// If this element needs smoothing enabled turn anti-aliasing on
if (this.RequiresSmoothRendering)
{
renderer.SmoothingMode = SmoothingMode.AntiAlias;
}
this.RenderFill(renderer);
this.RenderStroke(renderer);
// Reset the smoothing mode
if (this.RequiresSmoothRendering && renderer.SmoothingMode == SmoothingMode.AntiAlias)
{
renderer.SmoothingMode = SmoothingMode.Default;
}
}
else
{
base.RenderChildren(renderer);
}
this.ResetClip(renderer);
this.PopTransforms(renderer);
}
}
}
/// <summary>
/// Renders the fill of the <see cref="SvgVisualElement"/> to the specified <see cref="ISvgRenderer"/>
/// </summary>
/// <param name="renderer">The <see cref="ISvgRenderer"/> object to render to.</param>
protected internal virtual void RenderFill(ISvgRenderer renderer)
{
if (this.Fill != null)
{
using (var brush = this.Fill.GetBrush(this, renderer, Math.Min(Math.Max(this.FillOpacity * this.Opacity, 0), 1)))
{
if (brush != null)
{
this.Path(renderer).FillMode = this.FillRule == SvgFillRule.NonZero ? FillMode.Winding : FillMode.Alternate;
renderer.FillPath(brush, this.Path(renderer));
}
}
}
}
/// <summary>
/// Renders the stroke of the <see cref="SvgVisualElement"/> to the specified <see cref="ISvgRenderer"/>
/// </summary>
/// <param name="renderer">The <see cref="ISvgRenderer"/> object to render to.</param>
protected internal virtual bool RenderStroke(ISvgRenderer renderer)
{
if (this.Stroke != null && this.Stroke != SvgColourServer.None && this.StrokeWidth > 0)
{
float strokeWidth = this.StrokeWidth.ToDeviceValue(renderer, UnitRenderingType.Other, this);
using (var brush = this.Stroke.GetBrush(this, renderer, Math.Min(Math.Max(this.StrokeOpacity * this.Opacity, 0), 1), true))
{
if (brush != null)
{
var path = this.Path(renderer);
var bounds = path.GetBounds();
if (path.PointCount < 1) return false;
if (bounds.Width <= 0 && bounds.Height <= 0)
{
switch (this.StrokeLineCap)
{
case SvgStrokeLineCap.Round:
using (var capPath = new GraphicsPath())
{
capPath.AddEllipse(path.PathPoints[0].X - strokeWidth / 2, path.PathPoints[0].Y - strokeWidth / 2, strokeWidth, strokeWidth);
renderer.FillPath(brush, capPath);
}
break;
case SvgStrokeLineCap.Square:
using (var capPath = new GraphicsPath())
{
capPath.AddRectangle(new RectangleF(path.PathPoints[0].X - strokeWidth / 2, path.PathPoints[0].Y - strokeWidth / 2, strokeWidth, strokeWidth));
renderer.FillPath(brush, capPath);
}
break;
}
}
else
{
using (var pen = new Pen(brush, strokeWidth))
{
if (this.StrokeDashArray != null && this.StrokeDashArray.Count > 0)
{
if (this.StrokeDashArray.Count % 2 != 0)
{
// handle odd dash arrays by repeating them once
this.StrokeDashArray.AddRange(this.StrokeDashArray);
}
/* divide by stroke width - GDI behaviour that I don't quite understand yet.*/
pen.DashPattern = this.StrokeDashArray.ConvertAll(u => ((u.ToDeviceValue(renderer, UnitRenderingType.Other, this) <= 0) ? 1 : u.ToDeviceValue(renderer, UnitRenderingType.Other, this)) /
((strokeWidth <= 0) ? 1 : strokeWidth)).ToArray();
if (this.StrokeLineCap == SvgStrokeLineCap.Round)
{
// to handle round caps, we have to adapt the dash pattern
// by increasing the dash length by the stroke width - GDI draws the rounded
// edge inside the dash line, SVG draws it outside the line
var pattern = new float[pen.DashPattern.Length];
int offset = 1; // the values are already normalized to dash width
for ( int i = 0; i < pen.DashPattern.Length; i++)
{
pattern[i] = pen.DashPattern[i] + offset;
offset *= -1; // increase dash length, decrease spaces
}
pen.DashPattern = pattern;
pen.DashCap = DashCap.Round;
}
if (this.StrokeDashOffset != null && this.StrokeDashOffset.Value != 0)
{
pen.DashOffset = ((this.StrokeDashOffset.ToDeviceValue(renderer, UnitRenderingType.Other, this) <= 0) ? 1 : this.StrokeDashOffset.ToDeviceValue(renderer, UnitRenderingType.Other, this)) /
((strokeWidth <= 0) ? 1 : strokeWidth);
}
}
switch (this.StrokeLineJoin)
{
case SvgStrokeLineJoin.Bevel:
pen.LineJoin = LineJoin.Bevel;
break;
case SvgStrokeLineJoin.Round:
pen.LineJoin = LineJoin.Round;
break;
default:
pen.LineJoin = LineJoin.Miter;
break;
}
pen.MiterLimit = this.StrokeMiterLimit;
switch (this.StrokeLineCap)
{
case SvgStrokeLineCap.Round:
pen.StartCap = LineCap.Round;
pen.EndCap = LineCap.Round;
break;
case SvgStrokeLineCap.Square:
pen.StartCap = LineCap.Square;
pen.EndCap = LineCap.Square;
break;
}
renderer.DrawPath(pen, path);
return true;
}
}
}
}
}
return false;
}
/// <summary>
/// Sets the clipping region of the specified <see cref="ISvgRenderer"/>.
/// </summary>
/// <param name="renderer">The <see cref="ISvgRenderer"/> to have its clipping region set.</param>
protected internal virtual void SetClip(ISvgRenderer renderer)
{
if (this.ClipPath != null || !string.IsNullOrEmpty(this.Clip))
{
this._previousClip = renderer.GetClip();
if (this.ClipPath != null)
{
SvgClipPath clipPath = this.OwnerDocument.GetElementById<SvgClipPath>(this.ClipPath.ToString());
if (clipPath != null) renderer.SetClip(clipPath.GetClipRegion(this), CombineMode.Intersect);
}
var clip = this.Clip;
if (!string.IsNullOrEmpty(clip) && clip.StartsWith("rect("))
{
clip = clip.Trim();
var offsets = (from o in clip.Substring(5, clip.Length - 6).Split(',')
select float.Parse(o.Trim())).ToList();
var bounds = this.Bounds;
var clipRect = new RectangleF(bounds.Left + offsets[3], bounds.Top + offsets[0],
bounds.Width - (offsets[3] + offsets[1]),
bounds.Height - (offsets[2] + offsets[0]));
renderer.SetClip(new Region(clipRect), CombineMode.Intersect);
}
}
}
/// <summary>
/// Resets the clipping region of the specified <see cref="ISvgRenderer"/> back to where it was before the <see cref="SetClip"/> method was called.
/// </summary>
/// <param name="renderer">The <see cref="ISvgRenderer"/> to have its clipping region reset.</param>
protected internal virtual void ResetClip(ISvgRenderer renderer)
{
if (this._previousClip != null)
{
renderer.SetClip(this._previousClip);
this._previousClip = null;
}
}
/// <summary>
/// Sets the clipping region of the specified <see cref="ISvgRenderer"/>.
/// </summary>
/// <param name="renderer">The <see cref="ISvgRenderer"/> to have its clipping region set.</param>
void ISvgClipable.SetClip(ISvgRenderer renderer)
{
this.SetClip(renderer);
}
/// <summary>
/// Resets the clipping region of the specified <see cref="ISvgRenderer"/> back to where it was before the <see cref="SetClip"/> method was called.
/// </summary>
/// <param name="renderer">The <see cref="ISvgRenderer"/> to have its clipping region reset.</param>
void ISvgClipable.ResetClip(ISvgRenderer renderer)
{
this.ResetClip(renderer);
}
public override SvgElement DeepCopy<T>()
{
var newObj = base.DeepCopy<T>() as SvgVisualElement;
newObj.ClipPath = this.ClipPath;
newObj.ClipRule = this.ClipRule;
newObj.Filter = this.Filter;
newObj.Visible = this.Visible;
if (this.Fill != null)
newObj.Fill = this.Fill;
if (this.Stroke != null)
newObj.Stroke = this.Stroke;
newObj.FillRule = this.FillRule;
newObj.FillOpacity = this.FillOpacity;
newObj.StrokeWidth = this.StrokeWidth;
newObj.StrokeLineCap = this.StrokeLineCap;
newObj.StrokeLineJoin = this.StrokeLineJoin;
newObj.StrokeMiterLimit = this.StrokeMiterLimit;
newObj.StrokeDashArray = this.StrokeDashArray;
newObj.StrokeDashOffset = this.StrokeDashOffset;
newObj.StrokeOpacity = this.StrokeOpacity;
newObj.Opacity = this.Opacity;
return newObj;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics.CodeAnalysis;
using Microsoft.Modeling;
namespace Microsoft.Protocol.TestSuites.Smb
{
/// <summary>
/// Parameter.
/// All the overall variables definition will be defined here, except the portion variable.
/// </summary>
public static class Parameter
{
#region Parameters used for test environment setup
/// <summary>
/// Define client platform.
/// </summary>
/// Disable warning CA2211 because model need to change this variable according to Test Case design.
[SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")]
public static Platform clientPlatform = Platform.WinVista;
/// <summary>
/// Define System Under Test (the SUT) platform.
/// </summary>
/// Disable warning CA2211 because model need to change this variable according to Test Case design.
[SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")]
public static Platform sutPlatform = Platform.Win2K8;
/// <summary>
/// Define share This is used to represent the name of the resource.
/// </summary>
/// Disable warning CA2211 because model need to change this variable according to Test Case design.
[SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")]
public static Sequence<string> shareFileNames = new Sequence<string>("Share1", "Share2", "DFSShare", "QuotaShare");
/// <summary>
/// Define share printer name.
/// </summary>
/// Disable warning CA2211 because model need to change this variable according to Test Case design.
[SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")]
public static Sequence<string> sharePrinterNames = new Sequence<string>("PrinterShare1");
/// <summary>
/// Define share pipe name.
/// </summary>
/// Disable warning CA2211 because model need to change this variable according to Test Case design.
[SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")]
public static Sequence<string> sharePipeNames = new Sequence<string>("IPC$");
/// <summary>
/// Define share devide name.
/// </summary>
/// Disable warning CA2211 because model need to change this variable according to Test Case design.
[SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")]
public static Sequence<string> shareDeviceNames = new Sequence<string>(string.Empty);
/// <summary>
/// File names to use.
/// </summary>
/// Disable warning CA2211 because model need to change this variable according to Test Case design.
[SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")]
public static SequenceContainer<string> fileNames = new SequenceContainer<string>(
"Test1.txt",
"Test2.txt",
"ExistTest.txt",
@"Dir1\Test1.txt");
/// <summary>
/// Dir names to use.
/// </summary>
/// Disable warning CA2211 because model need to change this variable according to Test Case design.
[SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")]
public static SequenceContainer<string> dirNames = new SequenceContainer<string>(string.Empty, "Dir1", "Dir2");
/// <summary>
/// Namedpipe names to use.
/// </summary>
/// Disable warning CA2211 because model need to change this variable according to Test Case design.
[SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")]
public static SequenceContainer<string> pipeNames = new SequenceContainer<string>("Pipe1");
/// <summary>
/// Mailslot names to use.
/// </summary>
/// Disable warning CA2211 because model need to change this variable according to Test Case design.
[SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")]
public static SequenceContainer<string> mailslotNames = new SequenceContainer<string>("Mailslot1");
#endregion.
#region Parameters used to maintain the SUT configuration
/// <summary>
/// Set supportStream to false.
/// </summary>
/// Disable warning CA2211 because model need to change this variable according to Test Case design.
[SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")]
public static bool isSupportStream;
/// <summary>
/// Set SupportInfoLevelPassThrough to false.
/// </summary>
/// Disable warning CA2211 because model need to change this variable according to Test Case design.
[SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")]
public static bool isSupportInfoLevelPassThrough;
/// <summary>
/// Set supportDFS to false.
/// </summary>
/// Disable warning CA2211 because model need to change this variable according to Test Case design.
[SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")]
public static bool isSupportDfs;
/// <summary>
/// Set RAP the SUT status.
/// </summary>
/// Disable warning CA2211 because model need to change this variable according to Test Case design.
[SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")]
public static bool isRapServerActive = true;
/// <summary>
/// Set supportQuota to false.
/// </summary>
/// Disable warning CA2211 because model need to change this variable according to Test Case design.
[SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")]
public static bool isSupportQuota;
/// <summary>
/// It indicates whether the SUT support unique file ID values.
/// </summary>
/// Disable warning CA2211 because model need to change this variable according to Test Case design.
[SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")]
public static bool isSupportUniqueFileId;
/// <summary>
/// Set supportPreviousVersion to false.
/// </summary>
/// Disable warning CA2211 because model need to change this variable according to Test Case design.
[SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")]
public static bool isSupportPreviousVersion;
/// <summary>
/// Set supportResumeKey to false.
/// </summary>
/// Disable warning CA2211 because model need to change this variable according to Test Case design.
[SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")]
public static bool isSupportResumeKey;
/// <summary>
/// Set supportCopyChunk to false.
/// </summary>
/// Disable warning CA2211 because model need to change this variable according to Test Case design.
[SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")]
public static bool isSupportCopyChunk;
/// <summary>
/// Whether the SUT support NT SMBs.
/// </summary>
/// Disable warning CA2211 because model need to change this variable according to Test Case design.
[SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")]
public static bool isSupportNtSmb;
/// <summary>
/// Define FS Type.
/// </summary>
/// Disable warning CA2211 because model need to change this variable according to Test Case design.
[SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")]
public static FileSystemType fsType = FileSystemType.Ntfs;
/// <summary>
/// the SUT Message Signing Policy.
/// </summary>
/// Disable warning CA2211 because model need to change this variable according to Test Case design.
[SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")]
public static SignState sutSignState = SignState.Disabled;
/// <summary>
/// The mode of created name pipe.
/// </summary>
/// Disable warning CA2211 because model need to change this variable according to Test Case design.
[SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")]
public static bool isMessageModePipe;
/// <summary>
/// Whether testing Set_Quota Status_Access_Denied.
/// </summary>
/// Disable warning CA2211 because model need to change this variable according to Test Case design.
[SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")]
public static bool isSetQuotaAccessDenied;
#endregion
#region Parameters used to maintain the client state
/// <summary>
/// The total bytes can be written to a file.
/// </summary>
/// Disable warning CA2211 because model need to change this variable according to Test Case design.
[SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")]
public static int totalBytesWritten;
#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.Diagnostics;
using System.Runtime.CompilerServices;
#if !netstandard10
using System.Numerics;
#endif
namespace System
{
internal static partial class SpanHelpers
{
public static int IndexOf(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength)
{
Debug.Assert(searchSpaceLength >= 0);
Debug.Assert(valueLength >= 0);
if (valueLength == 0)
return 0; // A zero-length sequence is always treated as "found" at the start of the search space.
byte valueHead = value;
ref byte valueTail = ref Unsafe.Add(ref value, 1);
int valueTailLength = valueLength - 1;
int index = 0;
for (;;)
{
Debug.Assert(0 <= index && index <= searchSpaceLength); // Ensures no deceptive underflows in the computation of "remainingSearchSpaceLength".
int remainingSearchSpaceLength = searchSpaceLength - index - valueTailLength;
if (remainingSearchSpaceLength <= 0)
break; // The unsearched portion is now shorter than the sequence we're looking for. So it can't be there.
// Do a quick search for the first element of "value".
int relativeIndex = IndexOf(ref Unsafe.Add(ref searchSpace, index), valueHead, remainingSearchSpaceLength);
if (relativeIndex == -1)
break;
index += relativeIndex;
// Found the first element of "value". See if the tail matches.
if (SequenceEqual(ref Unsafe.Add(ref searchSpace, index + 1), ref valueTail, valueTailLength))
return index; // The tail matched. Return a successful find.
index++;
}
return -1;
}
public static int IndexOfAny(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength)
{
Debug.Assert(searchSpaceLength >= 0);
Debug.Assert(valueLength >= 0);
if (valueLength == 0)
return 0; // A zero-length sequence is always treated as "found" at the start of the search space.
int index = -1;
for (int i = 0; i < valueLength; i++)
{
var tempIndex = IndexOf(ref searchSpace, Unsafe.Add(ref value, i), searchSpaceLength);
if (tempIndex != -1)
{
index = (index == -1 || index > tempIndex) ? tempIndex : index;
}
}
return index;
}
public static unsafe int IndexOf(ref byte searchSpace, byte value, int length)
{
Debug.Assert(length >= 0);
uint uValue = value; // Use uint for comparisons to avoid unnecessary 8->32 extensions
IntPtr index = (IntPtr)0; // Use UIntPtr for arithmetic to avoid unnecessary 64->32->64 truncations
IntPtr nLength = (IntPtr)(uint)length;
#if !netstandard10
if (Vector.IsHardwareAccelerated && length >= Vector<byte>.Count * 2)
{
unchecked
{
int unaligned = (int)(byte*)Unsafe.AsPointer(ref searchSpace) & (Vector<byte>.Count - 1);
nLength = (IntPtr)(uint)((Vector<byte>.Count - unaligned) & (Vector<byte>.Count - 1));
}
}
SequentialScan:
#endif
while ((byte*)nLength >= (byte*)8)
{
nLength -= 8;
if (uValue == Unsafe.Add(ref searchSpace, index))
goto Found;
if (uValue == Unsafe.Add(ref searchSpace, index + 1))
goto Found1;
if (uValue == Unsafe.Add(ref searchSpace, index + 2))
goto Found2;
if (uValue == Unsafe.Add(ref searchSpace, index + 3))
goto Found3;
if (uValue == Unsafe.Add(ref searchSpace, index + 4))
goto Found4;
if (uValue == Unsafe.Add(ref searchSpace, index + 5))
goto Found5;
if (uValue == Unsafe.Add(ref searchSpace, index + 6))
goto Found6;
if (uValue == Unsafe.Add(ref searchSpace, index + 7))
goto Found7;
index += 8;
}
if ((byte*)nLength >= (byte*)4)
{
nLength -= 4;
if (uValue == Unsafe.Add(ref searchSpace, index))
goto Found;
if (uValue == Unsafe.Add(ref searchSpace, index + 1))
goto Found1;
if (uValue == Unsafe.Add(ref searchSpace, index + 2))
goto Found2;
if (uValue == Unsafe.Add(ref searchSpace, index + 3))
goto Found3;
index += 4;
}
while ((byte*)nLength > (byte*)0)
{
nLength -= 1;
if (uValue == Unsafe.Add(ref searchSpace, index))
goto Found;
index += 1;
}
#if !netstandard10
if (Vector.IsHardwareAccelerated && ((int)(byte*)index < length))
{
nLength = (IntPtr)(uint)((length - (uint)index) & ~(Vector<byte>.Count - 1));
// Get comparison Vector
Vector<byte> vComparison = GetVector(value);
while ((byte*)nLength > (byte*)index)
{
var vMatches = Vector.Equals(vComparison, Unsafe.ReadUnaligned<Vector<byte>>(ref Unsafe.AddByteOffset(ref searchSpace, index)));
if (Vector<byte>.Zero.Equals(vMatches))
{
index += Vector<byte>.Count;
continue;
}
// Find offset of first match
return (int)(byte*)index + LocateFirstFoundByte(vMatches);
}
if ((int)(byte*)index < length)
{
unchecked
{
nLength = (IntPtr)(length - (int)(byte*)index);
}
goto SequentialScan;
}
}
#endif
return -1;
Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549
return (int)(byte*)index;
Found1:
return (int)(byte*)(index + 1);
Found2:
return (int)(byte*)(index + 2);
Found3:
return (int)(byte*)(index + 3);
Found4:
return (int)(byte*)(index + 4);
Found5:
return (int)(byte*)(index + 5);
Found6:
return (int)(byte*)(index + 6);
Found7:
return (int)(byte*)(index + 7);
}
public static unsafe int IndexOfAny(ref byte searchSpace, byte value0, byte value1, int length)
{
Debug.Assert(length >= 0);
uint uValue0 = value0; // Use uint for comparisons to avoid unnecessary 8->32 extensions
uint uValue1 = value1; // Use uint for comparisons to avoid unnecessary 8->32 extensions
IntPtr index = (IntPtr)0; // Use UIntPtr for arithmetic to avoid unnecessary 64->32->64 truncations
IntPtr nLength = (IntPtr)(uint)length;
#if !netstandard10
if (Vector.IsHardwareAccelerated && length >= Vector<byte>.Count * 2)
{
unchecked
{
int unaligned = (int)(byte*)Unsafe.AsPointer(ref searchSpace) & (Vector<byte>.Count - 1);
nLength = (IntPtr)(uint)((Vector<byte>.Count - unaligned) & (Vector<byte>.Count - 1));
}
}
SequentialScan:
#endif
uint lookUp;
while ((byte*)nLength >= (byte*)8)
{
nLength -= 8;
lookUp = Unsafe.Add(ref searchSpace, index);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found;
lookUp = Unsafe.Add(ref searchSpace, index + 1);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found1;
lookUp = Unsafe.Add(ref searchSpace, index + 2);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found2;
lookUp = Unsafe.Add(ref searchSpace, index + 3);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found3;
lookUp = Unsafe.Add(ref searchSpace, index + 4);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found4;
lookUp = Unsafe.Add(ref searchSpace, index + 5);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found5;
lookUp = Unsafe.Add(ref searchSpace, index + 6);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found6;
lookUp = Unsafe.Add(ref searchSpace, index + 7);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found7;
index += 8;
}
if ((byte*)nLength >= (byte*)4)
{
nLength -= 4;
lookUp = Unsafe.Add(ref searchSpace, index);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found;
lookUp = Unsafe.Add(ref searchSpace, index + 1);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found1;
lookUp = Unsafe.Add(ref searchSpace, index + 2);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found2;
lookUp = Unsafe.Add(ref searchSpace, index + 3);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found3;
index += 4;
}
while ((byte*)nLength > (byte*)0)
{
nLength -= 1;
lookUp = Unsafe.Add(ref searchSpace, index);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found;
index += 1;
}
#if !netstandard10
if (Vector.IsHardwareAccelerated && ((int)(byte*)index < length))
{
nLength = (IntPtr)(uint)((length - (uint)index) & ~(Vector<byte>.Count - 1));
// Get comparison Vector
Vector<byte> values0 = GetVector(value0);
Vector<byte> values1 = GetVector(value1);
while ((byte*)nLength > (byte*)index)
{
var vData = Unsafe.ReadUnaligned<Vector<byte>>(ref Unsafe.AddByteOffset(ref searchSpace, index));
var vMatches = Vector.BitwiseOr(
Vector.Equals(vData, values0),
Vector.Equals(vData, values1));
if (Vector<byte>.Zero.Equals(vMatches))
{
index += Vector<byte>.Count;
continue;
}
// Find offset of first match
return (int)(byte*)index + LocateFirstFoundByte(vMatches);
}
if ((int)(byte*)index < length)
{
unchecked
{
nLength = (IntPtr)(length - (int)(byte*)index);
}
goto SequentialScan;
}
}
#endif
return -1;
Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549
return (int)(byte*)index;
Found1:
return (int)(byte*)(index + 1);
Found2:
return (int)(byte*)(index + 2);
Found3:
return (int)(byte*)(index + 3);
Found4:
return (int)(byte*)(index + 4);
Found5:
return (int)(byte*)(index + 5);
Found6:
return (int)(byte*)(index + 6);
Found7:
return (int)(byte*)(index + 7);
}
public static unsafe int IndexOfAny(ref byte searchSpace, byte value0, byte value1, byte value2, int length)
{
Debug.Assert(length >= 0);
uint uValue0 = value0; // Use uint for comparisons to avoid unnecessary 8->32 extensions
uint uValue1 = value1; // Use uint for comparisons to avoid unnecessary 8->32 extensions
uint uValue2 = value2; // Use uint for comparisons to avoid unnecessary 8->32 extensions
IntPtr index = (IntPtr)0; // Use UIntPtr for arithmetic to avoid unnecessary 64->32->64 truncations
IntPtr nLength = (IntPtr)(uint)length;
#if !netstandard10
if (Vector.IsHardwareAccelerated && length >= Vector<byte>.Count * 2)
{
unchecked
{
int unaligned = (int)(byte*)Unsafe.AsPointer(ref searchSpace) & (Vector<byte>.Count - 1);
nLength = (IntPtr)(uint)((Vector<byte>.Count - unaligned) & (Vector<byte>.Count - 1));
}
}
SequentialScan:
#endif
uint lookUp;
while ((byte*)nLength >= (byte*)8)
{
nLength -= 8;
lookUp = Unsafe.Add(ref searchSpace, index);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found;
lookUp = Unsafe.Add(ref searchSpace, index + 1);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found1;
lookUp = Unsafe.Add(ref searchSpace, index + 2);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found2;
lookUp = Unsafe.Add(ref searchSpace, index + 3);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found3;
lookUp = Unsafe.Add(ref searchSpace, index + 4);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found4;
lookUp = Unsafe.Add(ref searchSpace, index + 5);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found5;
lookUp = Unsafe.Add(ref searchSpace, index + 6);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found6;
lookUp = Unsafe.Add(ref searchSpace, index + 7);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found7;
index += 8;
}
if ((byte*)nLength >= (byte*)4)
{
nLength -= 4;
lookUp = Unsafe.Add(ref searchSpace, index);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found;
lookUp = Unsafe.Add(ref searchSpace, index + 1);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found1;
lookUp = Unsafe.Add(ref searchSpace, index + 2);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found2;
lookUp = Unsafe.Add(ref searchSpace, index + 3);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found3;
index += 4;
}
while ((byte*)nLength > (byte*)0)
{
nLength -= 1;
lookUp = Unsafe.Add(ref searchSpace, index);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found;
index += 1;
}
#if !netstandard10
if (Vector.IsHardwareAccelerated && ((int)(byte*)index < length))
{
nLength = (IntPtr)(uint)((length - (uint)index) & ~(Vector<byte>.Count - 1));
// Get comparison Vector
Vector<byte> values0 = GetVector(value0);
Vector<byte> values1 = GetVector(value1);
Vector<byte> values2 = GetVector(value2);
while ((byte*)nLength > (byte*)index)
{
var vData = Unsafe.ReadUnaligned<Vector<byte>>(ref Unsafe.AddByteOffset(ref searchSpace, index));
var vMatches = Vector.BitwiseOr(
Vector.BitwiseOr(
Vector.Equals(vData, values0),
Vector.Equals(vData, values1)),
Vector.Equals(vData, values2));
if (Vector<byte>.Zero.Equals(vMatches))
{
index += Vector<byte>.Count;
continue;
}
// Find offset of first match
return (int)(byte*)index + LocateFirstFoundByte(vMatches);
}
if ((int)(byte*)index < length)
{
unchecked
{
nLength = (IntPtr)(length - (int)(byte*)index);
}
goto SequentialScan;
}
}
#endif
return -1;
Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549
return (int)(byte*)index;
Found1:
return (int)(byte*)(index + 1);
Found2:
return (int)(byte*)(index + 2);
Found3:
return (int)(byte*)(index + 3);
Found4:
return (int)(byte*)(index + 4);
Found5:
return (int)(byte*)(index + 5);
Found6:
return (int)(byte*)(index + 6);
Found7:
return (int)(byte*)(index + 7);
}
public static unsafe bool SequenceEqual(ref byte first, ref byte second, int length)
{
Debug.Assert(length >= 0);
if (Unsafe.AreSame(ref first, ref second))
goto Equal;
IntPtr i = (IntPtr)0; // Use IntPtr and byte* for arithmetic to avoid unnecessary 64->32->64 truncations
IntPtr n = (IntPtr)length;
#if !netstandard10
if (Vector.IsHardwareAccelerated && (byte*)n >= (byte*)Vector<byte>.Count)
{
n -= Vector<byte>.Count;
while ((byte*)n > (byte*)i)
{
if (Unsafe.ReadUnaligned<Vector<byte>>(ref Unsafe.AddByteOffset(ref first, i)) !=
Unsafe.ReadUnaligned<Vector<byte>>(ref Unsafe.AddByteOffset(ref second, i)))
{
goto NotEqual;
}
i += Vector<byte>.Count;
}
return Unsafe.ReadUnaligned<Vector<byte>>(ref Unsafe.AddByteOffset(ref first, n)) ==
Unsafe.ReadUnaligned<Vector<byte>>(ref Unsafe.AddByteOffset(ref second, n));
}
#endif
if ((byte*)n >= (byte*)sizeof(UIntPtr))
{
n -= sizeof(UIntPtr);
while ((byte*)n > (byte*)i)
{
if (Unsafe.ReadUnaligned<UIntPtr>(ref Unsafe.AddByteOffset(ref first, i)) !=
Unsafe.ReadUnaligned<UIntPtr>(ref Unsafe.AddByteOffset(ref second, i)))
{
goto NotEqual;
}
i += sizeof(UIntPtr);
}
return Unsafe.ReadUnaligned<UIntPtr>(ref Unsafe.AddByteOffset(ref first, n)) ==
Unsafe.ReadUnaligned<UIntPtr>(ref Unsafe.AddByteOffset(ref second, n));
}
while ((byte*)n > (byte*)i)
{
if (Unsafe.AddByteOffset(ref first, i) != Unsafe.AddByteOffset(ref second, i))
goto NotEqual;
i += 1;
}
Equal:
return true;
NotEqual: // Workaround for https://github.com/dotnet/coreclr/issues/13549
return false;
}
#if !netstandard10
// Vector sub-search adapted from https://github.com/aspnet/KestrelHttpServer/pull/1138
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int LocateFirstFoundByte(Vector<byte> match)
{
var vector64 = Vector.AsVectorUInt64(match);
ulong candidate = 0;
int i = 0;
// Pattern unrolled by jit https://github.com/dotnet/coreclr/pull/8001
for (; i < Vector<ulong>.Count; i++)
{
candidate = vector64[i];
if (candidate != 0)
{
break;
}
}
// Single LEA instruction with jitted const (using function result)
return i * 8 + LocateFirstFoundByte(candidate);
}
#endif
#if !netstandard10
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int LocateFirstFoundByte(ulong match)
{
unchecked
{
// Flag least significant power of two bit
var powerOfTwoFlag = match ^ (match - 1);
// Shift all powers of two into the high byte and extract
return (int)((powerOfTwoFlag * xorPowerOfTwoToHighByte) >> 57);
}
}
#endif
#if !netstandard10
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static Vector<byte> GetVector(byte vectorByte)
{
#if !netcoreapp
// Vector<byte> .ctor doesn't become an intrinsic due to detection issue
// However this does cause it to become an intrinsic (with additional multiply and reg->reg copy)
// https://github.com/dotnet/coreclr/issues/7459#issuecomment-253965670
return Vector.AsVectorByte(new Vector<uint>(vectorByte * 0x01010101u));
#else
return new Vector<byte>(vectorByte);
#endif
}
#endif
#if !netstandard10
private const ulong xorPowerOfTwoToHighByte = (0x07ul |
0x06ul << 8 |
0x05ul << 16 |
0x04ul << 24 |
0x03ul << 32 |
0x02ul << 40 |
0x01ul << 48) + 1;
#endif
}
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using Palaso.WritingSystems;
namespace Palaso.UI.WindowsForms.WritingSystems.WSTree
{
public class WritingSystemTreeItem
{
protected readonly Action<WritingSystemTreeItem> ClickAction;
protected static Font kLabelFont=new Font(SystemFonts.MessageBoxFont.Name, 8);
protected static Font kHeaderFont=new Font(SystemFonts.MessageBoxFont.Name, 8);
public WritingSystemTreeItem(string text, Action<WritingSystemTreeItem> clickAction)
{
Children = new List<WritingSystemTreeItem>();
ClickAction = clickAction;
Text=text;
}
public bool Selected { get; set; }
public string Text { get; set; }
public List<WritingSystemTreeItem> Children { get; set; }
public TreeNode MakeTreeNode()
{
var node = new TreeNode(Text, Children.Select(n => n.MakeTreeNode()).ToArray());
node.Tag=this;
node.ForeColor = ForeColor;
node.NodeFont = this.Font;
return node;
}
protected virtual Color ForeColor
{
get { return System.Drawing.Color.Black; }
}
protected virtual Font Font
{
get { return kHeaderFont; }
}
public virtual bool CanSelect
{
get { return false; }
}
public virtual void Clicked()
{
if (ClickAction != null)
{
ClickAction(this);
}
}
}
public class NullTreeItem : WritingSystemTreeItem
{
public NullTreeItem()
: base(string.Empty, new Action<WritingSystemTreeItem>(x => { }))
{
}
}
/// <summary>
/// this is used when it would be confusing to make one of the WS's primary above the others.
/// related to http://projects.palaso.org/issues/show/482
/// </summary>
public class GroupTreeItem : WritingSystemTreeItem
{
protected static Font kFont = new Font(SystemFonts.MessageBoxFont.Name, 11);
public GroupTreeItem(string name)
: base(name, new Action<WritingSystemTreeItem>(x => { }))
{
}
protected override Font Font
{
get
{
return kFont;
}
}
protected override Color ForeColor
{
get
{
return Color.DarkGray;
}
}
}
public class WritingSystemDefinitionTreeItem : WritingSystemTreeItem
{
public IWritingSystemDefinition Definition { get; set; }
protected static Font kExistingItemFont = new Font(SystemFonts.MessageBoxFont.Name, 11);
public WritingSystemDefinitionTreeItem(IWritingSystemDefinition definition, Action<WritingSystemTreeItem> clickAction)
: base(definition.ListLabel, clickAction)
{
Definition = definition;
}
protected WritingSystemDefinitionTreeItem(Action<WritingSystemTreeItem> clickAction)
: base("label", clickAction)
{
}
protected override Font Font
{
get { return kExistingItemFont; }
}
public override bool CanSelect
{
get { return true; }
}
}
public class WritingSystemCreationTreeItem : WritingSystemDefinitionTreeItem
{
private readonly IWritingSystemDefinitionSuggestion _suggestion;
public WritingSystemCreationTreeItem(IWritingSystemDefinitionSuggestion suggestion, Action<WritingSystemTreeItem> clickAction)
: base(clickAction)
{
_suggestion = suggestion;
Text = "Add " + suggestion.Label;
}
protected override Color ForeColor
{
get { return System.Drawing.Color.DarkBlue; }
}
public override bool CanSelect
{
get { return true; }
}
protected override Font Font
{
get { return kLabelFont; }
}
public WritingSystemDefinition ShowDialogIfNeededAndGetDefinition()
{
return _suggestion.ShowDialogIfNeededAndGetDefinition();
}
}
public class WritingSystemCreateUnknownTreeItem : WritingSystemTreeItem
{
public WritingSystemCreateUnknownTreeItem(Action<WritingSystemTreeItem> clickAction)
: base("Add Language", clickAction)
{
}
protected override Color ForeColor
{
get { return System.Drawing.Color.DarkBlue; }
}
protected override Font Font
{
get { return kLabelFont; }
}
public override bool CanSelect
{
get { return true; }
}
}
public class WritingSystemRenameUnlistedLanguageTreeItem : WritingSystemTreeItem
{
public WritingSystemRenameUnlistedLanguageTreeItem(Action<WritingSystemTreeItem> clickAction)
: base("Change to Listed Language", clickAction)
{
}
protected override Color ForeColor
{
get { return System.Drawing.Color.DarkBlue; }
}
protected override Font Font
{
get { return kLabelFont; }
}
public override bool CanSelect
{
get { return true; }
}
}
}
| |
// 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.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.CSharp.LanguageServices
{
internal partial class CSharpSymbolDisplayService
{
protected class SymbolDescriptionBuilder : AbstractSymbolDescriptionBuilder
{
private static readonly SymbolDisplayFormat s_minimallyQualifiedFormat = SymbolDisplayFormat.MinimallyQualifiedFormat
.AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName)
.RemoveParameterOptions(SymbolDisplayParameterOptions.IncludeDefaultValue)
.WithKindOptions(SymbolDisplayKindOptions.None);
private static readonly SymbolDisplayFormat s_minimallyQualifiedFormatWithConstants = s_minimallyQualifiedFormat
.AddLocalOptions(SymbolDisplayLocalOptions.IncludeConstantValue)
.AddMemberOptions(SymbolDisplayMemberOptions.IncludeConstantValue)
.AddParameterOptions(SymbolDisplayParameterOptions.IncludeDefaultValue);
private static readonly SymbolDisplayFormat s_propertySignatureDisplayFormat =
new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeTypeConstraints,
memberOptions:
SymbolDisplayMemberOptions.IncludeAccessibility |
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeContainingType,
kindOptions:
SymbolDisplayKindOptions.IncludeMemberKeyword,
propertyStyle:
SymbolDisplayPropertyStyle.ShowReadWriteDescriptor,
parameterOptions:
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeParamsRefOut |
SymbolDisplayParameterOptions.IncludeExtensionThis |
SymbolDisplayParameterOptions.IncludeDefaultValue |
SymbolDisplayParameterOptions.IncludeOptionalBrackets,
localOptions: SymbolDisplayLocalOptions.IncludeType,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes |
SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName);
public SymbolDescriptionBuilder(
ISymbolDisplayService displayService,
SemanticModel semanticModel,
int position,
Workspace workspace,
IAnonymousTypeDisplayService anonymousTypeDisplayService,
CancellationToken cancellationToken)
: base(displayService, semanticModel, position, workspace, anonymousTypeDisplayService, cancellationToken)
{
}
protected override void AddDeprecatedPrefix()
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
Punctuation("["),
PlainText(CSharpFeaturesResources.deprecated),
Punctuation("]"),
Space());
}
protected override void AddExtensionPrefix()
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
Punctuation("("),
PlainText(CSharpFeaturesResources.extension),
Punctuation(")"),
Space());
}
protected override void AddAwaitablePrefix()
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
Punctuation("("),
PlainText(CSharpFeaturesResources.awaitable),
Punctuation(")"),
Space());
}
protected override void AddAwaitableExtensionPrefix()
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
Punctuation("("),
PlainText(CSharpFeaturesResources.awaitable_extension),
Punctuation(")"),
Space());
}
protected override void AddDescriptionForProperty(IPropertySymbol symbol)
{
if (symbol.ContainingType?.TypeKind == TypeKind.Interface)
{
base.AddDescriptionForProperty(symbol);
}
else
{
var fullParts = ToMinimalDisplayParts(symbol, s_propertySignatureDisplayFormat);
var neededParts = fullParts.SkipWhile(p => p.Symbol == null);
AddToGroup(SymbolDescriptionGroups.MainDescription, neededParts);
}
}
protected override Task<IEnumerable<SymbolDisplayPart>> GetInitializerSourcePartsAsync(
ISymbol symbol)
{
// Actually check for C# symbol types here.
if (symbol is IParameterSymbol)
{
return GetInitializerSourcePartsAsync((IParameterSymbol)symbol);
}
else if (symbol is ILocalSymbol)
{
return GetInitializerSourcePartsAsync((ILocalSymbol)symbol);
}
else if (symbol is IFieldSymbol)
{
return GetInitializerSourcePartsAsync((IFieldSymbol)symbol);
}
return SpecializedTasks.Default<IEnumerable<SymbolDisplayPart>>();
}
private async Task<IEnumerable<SymbolDisplayPart>> GetInitializerSourcePartsAsync(
IFieldSymbol symbol)
{
EqualsValueClauseSyntax initializer = null;
var variableDeclarator = await this.GetFirstDeclaration<VariableDeclaratorSyntax>(symbol).ConfigureAwait(false);
if (variableDeclarator != null)
{
initializer = variableDeclarator.Initializer;
}
if (initializer == null)
{
var enumMemberDeclaration = await this.GetFirstDeclaration<EnumMemberDeclarationSyntax>(symbol).ConfigureAwait(false);
if (enumMemberDeclaration != null)
{
initializer = enumMemberDeclaration.EqualsValue;
}
}
if (initializer != null)
{
return await GetInitializerSourcePartsAsync(initializer).ConfigureAwait(false);
}
return null;
}
private async Task<IEnumerable<SymbolDisplayPart>> GetInitializerSourcePartsAsync(
ILocalSymbol symbol)
{
var syntax = await this.GetFirstDeclaration<VariableDeclaratorSyntax>(symbol).ConfigureAwait(false);
if (syntax != null)
{
return await GetInitializerSourcePartsAsync(syntax.Initializer).ConfigureAwait(false);
}
return null;
}
private async Task<IEnumerable<SymbolDisplayPart>> GetInitializerSourcePartsAsync(
IParameterSymbol symbol)
{
var syntax = await this.GetFirstDeclaration<ParameterSyntax>(symbol).ConfigureAwait(false);
if (syntax != null)
{
return await GetInitializerSourcePartsAsync(syntax.Default).ConfigureAwait(false);
}
return null;
}
private async Task<T> GetFirstDeclaration<T>(ISymbol symbol) where T : SyntaxNode
{
foreach (var syntaxRef in symbol.DeclaringSyntaxReferences)
{
var syntax = await syntaxRef.GetSyntaxAsync(this.CancellationToken).ConfigureAwait(false);
if (syntax is T)
{
return (T)syntax;
}
}
return null;
}
private async Task<IEnumerable<SymbolDisplayPart>> GetInitializerSourcePartsAsync(
EqualsValueClauseSyntax equalsValue)
{
if (equalsValue != null && equalsValue.Value != null)
{
var semanticModel = GetSemanticModel(equalsValue.SyntaxTree);
if (semanticModel != null)
{
return await Classifier.GetClassifiedSymbolDisplayPartsAsync(
semanticModel, equalsValue.Value.Span,
this.Workspace, this.CancellationToken).ConfigureAwait(false);
}
}
return null;
}
protected override void AddAwaitableUsageText(IMethodSymbol method, SemanticModel semanticModel, int position)
{
AddToGroup(SymbolDescriptionGroups.AwaitableUsageText,
method.ToAwaitableParts(SyntaxFacts.GetText(SyntaxKind.AwaitKeyword), "x", semanticModel, position));
}
protected override SymbolDisplayFormat MinimallyQualifiedFormat
{
get { return s_minimallyQualifiedFormat; }
}
protected override SymbolDisplayFormat MinimallyQualifiedFormatWithConstants
{
get { return s_minimallyQualifiedFormatWithConstants; }
}
}
}
}
| |
// 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.Data;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Internal;
namespace Microsoft.Extensions.Caching.SqlServer
{
internal class DatabaseOperations : IDatabaseOperations
{
/// <summary>
/// Since there is no specific exception type representing a 'duplicate key' error, we are relying on
/// the following message number which represents the following text in Microsoft SQL Server database.
/// "Violation of %ls constraint '%.*ls'. Cannot insert duplicate key in object '%.*ls'.
/// The duplicate key value is %ls."
/// You can find the list of system messages by executing the following query:
/// "SELECT * FROM sys.messages WHERE [text] LIKE '%duplicate%'"
/// </summary>
private const int DuplicateKeyErrorId = 2627;
protected const string GetTableSchemaErrorText =
"Could not retrieve information of table with schema '{0}' and " +
"name '{1}'. Make sure you have the table setup and try again. " +
"Connection string: {2}";
public DatabaseOperations(
string connectionString, string schemaName, string tableName, ISystemClock systemClock)
{
ConnectionString = connectionString;
SchemaName = schemaName;
TableName = tableName;
SystemClock = systemClock;
SqlQueries = new SqlQueries(schemaName, tableName);
}
protected SqlQueries SqlQueries { get; }
protected string ConnectionString { get; }
protected string SchemaName { get; }
protected string TableName { get; }
protected ISystemClock SystemClock { get; }
public void DeleteCacheItem(string key)
{
using (var connection = new SqlConnection(ConnectionString))
using (var command = new SqlCommand(SqlQueries.DeleteCacheItem, connection))
{
command.Parameters.AddCacheItemId(key);
connection.Open();
command.ExecuteNonQuery();
}
}
public async Task DeleteCacheItemAsync(string key, CancellationToken token = default(CancellationToken))
{
token.ThrowIfCancellationRequested();
using (var connection = new SqlConnection(ConnectionString))
using (var command = new SqlCommand(SqlQueries.DeleteCacheItem, connection))
{
command.Parameters.AddCacheItemId(key);
await connection.OpenAsync(token).ConfigureAwait(false);
await command.ExecuteNonQueryAsync(token).ConfigureAwait(false);
}
}
public virtual byte[] GetCacheItem(string key)
{
return GetCacheItem(key, includeValue: true);
}
public virtual async Task<byte[]> GetCacheItemAsync(string key, CancellationToken token = default(CancellationToken))
{
token.ThrowIfCancellationRequested();
return await GetCacheItemAsync(key, includeValue: true, token: token).ConfigureAwait(false);
}
public void RefreshCacheItem(string key)
{
GetCacheItem(key, includeValue: false);
}
public async Task RefreshCacheItemAsync(string key, CancellationToken token = default(CancellationToken))
{
token.ThrowIfCancellationRequested();
await GetCacheItemAsync(key, includeValue: false, token:token).ConfigureAwait(false);
}
public virtual void DeleteExpiredCacheItems()
{
var utcNow = SystemClock.UtcNow;
using (var connection = new SqlConnection(ConnectionString))
using (var command = new SqlCommand(SqlQueries.DeleteExpiredCacheItems, connection))
{
command.Parameters.AddWithValue("UtcNow", SqlDbType.DateTimeOffset, utcNow);
connection.Open();
var effectedRowCount = command.ExecuteNonQuery();
}
}
public virtual void SetCacheItem(string key, byte[] value, DistributedCacheEntryOptions options)
{
var utcNow = SystemClock.UtcNow;
var absoluteExpiration = GetAbsoluteExpiration(utcNow, options);
ValidateOptions(options.SlidingExpiration, absoluteExpiration);
using (var connection = new SqlConnection(ConnectionString))
using (var upsertCommand = new SqlCommand(SqlQueries.SetCacheItem, connection))
{
upsertCommand.Parameters
.AddCacheItemId(key)
.AddCacheItemValue(value)
.AddSlidingExpirationInSeconds(options.SlidingExpiration)
.AddAbsoluteExpiration(absoluteExpiration)
.AddWithValue("UtcNow", SqlDbType.DateTimeOffset, utcNow);
connection.Open();
try
{
upsertCommand.ExecuteNonQuery();
}
catch (SqlException ex)
{
if (IsDuplicateKeyException(ex))
{
// There is a possibility that multiple requests can try to add the same item to the cache, in
// which case we receive a 'duplicate key' exception on the primary key column.
}
else
{
throw;
}
}
}
}
public virtual async Task SetCacheItemAsync(string key, byte[] value, DistributedCacheEntryOptions options, CancellationToken token = default(CancellationToken))
{
token.ThrowIfCancellationRequested();
var utcNow = SystemClock.UtcNow;
var absoluteExpiration = GetAbsoluteExpiration(utcNow, options);
ValidateOptions(options.SlidingExpiration, absoluteExpiration);
using (var connection = new SqlConnection(ConnectionString))
using(var upsertCommand = new SqlCommand(SqlQueries.SetCacheItem, connection))
{
upsertCommand.Parameters
.AddCacheItemId(key)
.AddCacheItemValue(value)
.AddSlidingExpirationInSeconds(options.SlidingExpiration)
.AddAbsoluteExpiration(absoluteExpiration)
.AddWithValue("UtcNow", SqlDbType.DateTimeOffset, utcNow);
await connection.OpenAsync(token).ConfigureAwait(false);
try
{
await upsertCommand.ExecuteNonQueryAsync(token).ConfigureAwait(false);
}
catch (SqlException ex)
{
if (IsDuplicateKeyException(ex))
{
// There is a possibility that multiple requests can try to add the same item to the cache, in
// which case we receive a 'duplicate key' exception on the primary key column.
}
else
{
throw;
}
}
}
}
protected virtual byte[] GetCacheItem(string key, bool includeValue)
{
var utcNow = SystemClock.UtcNow;
string query;
if (includeValue)
{
query = SqlQueries.GetCacheItem;
}
else
{
query = SqlQueries.GetCacheItemWithoutValue;
}
byte[] value = null;
using (var connection = new SqlConnection(ConnectionString))
using (var command = new SqlCommand(query, connection))
{
command.Parameters
.AddCacheItemId(key)
.AddWithValue("UtcNow", SqlDbType.DateTimeOffset, utcNow);
connection.Open();
using (var reader = command.ExecuteReader(
CommandBehavior.SequentialAccess | CommandBehavior.SingleRow | CommandBehavior.SingleResult))
{
if (reader.Read())
{
if (includeValue)
{
value = reader.GetFieldValue<byte[]>(Columns.Indexes.CacheItemValueIndex);
}
}
else
{
return null;
}
}
}
return value;
}
protected virtual async Task<byte[]> GetCacheItemAsync(string key, bool includeValue, CancellationToken token = default(CancellationToken))
{
token.ThrowIfCancellationRequested();
var utcNow = SystemClock.UtcNow;
string query;
if (includeValue)
{
query = SqlQueries.GetCacheItem;
}
else
{
query = SqlQueries.GetCacheItemWithoutValue;
}
byte[] value = null;
using (var connection = new SqlConnection(ConnectionString))
using (var command = new SqlCommand(query, connection))
{
command.Parameters
.AddCacheItemId(key)
.AddWithValue("UtcNow", SqlDbType.DateTimeOffset, utcNow);
await connection.OpenAsync(token).ConfigureAwait(false);
using (var reader = await command.ExecuteReaderAsync(
CommandBehavior.SequentialAccess | CommandBehavior.SingleRow | CommandBehavior.SingleResult,
token).ConfigureAwait(false))
{
if (await reader.ReadAsync(token).ConfigureAwait(false))
{
if (includeValue)
{
value = await reader.GetFieldValueAsync<byte[]>(Columns.Indexes.CacheItemValueIndex, token).ConfigureAwait(false);
}
}
else
{
return null;
}
}
}
return value;
}
protected bool IsDuplicateKeyException(SqlException ex)
{
if (ex.Errors != null)
{
return ex.Errors.Cast<SqlError>().Any(error => error.Number == DuplicateKeyErrorId);
}
return false;
}
protected DateTimeOffset? GetAbsoluteExpiration(DateTimeOffset utcNow, DistributedCacheEntryOptions options)
{
// calculate absolute expiration
DateTimeOffset? absoluteExpiration = null;
if (options.AbsoluteExpirationRelativeToNow.HasValue)
{
absoluteExpiration = utcNow.Add(options.AbsoluteExpirationRelativeToNow.Value);
}
else if (options.AbsoluteExpiration.HasValue)
{
if (options.AbsoluteExpiration.Value <= utcNow)
{
throw new InvalidOperationException("The absolute expiration value must be in the future.");
}
absoluteExpiration = options.AbsoluteExpiration.Value;
}
return absoluteExpiration;
}
protected void ValidateOptions(TimeSpan? slidingExpiration, DateTimeOffset? absoluteExpiration)
{
if (!slidingExpiration.HasValue && !absoluteExpiration.HasValue)
{
throw new InvalidOperationException("Either absolute or sliding expiration needs " +
"to be provided.");
}
}
}
}
| |
namespace KabMan.Forms
{
partial class VTPortManagerForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(VTPortManagerForm));
this.repositoryItemLookUpEdit7 = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit();
this.repositoryItemLookUpEdit8 = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit();
this.repositoryItemLookUpEdit3 = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit();
this.repositoryItemLookUpEdit4 = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit();
this.repositoryItemLookUpEdit5 = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit();
this.repositoryItemLookUpEdit1 = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit();
this.repositoryItemLookUpEdit2 = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit();
this.CBarManager = new DevExpress.XtraBars.BarManager(this.components);
this.CStatusBar = new DevExpress.XtraBars.Bar();
this.itemCount = new DevExpress.XtraBars.BarStaticItem();
this.bar1 = new DevExpress.XtraBars.Bar();
this.itemNew = new DevExpress.XtraBars.BarButtonItem();
this.itemDelete = new DevExpress.XtraBars.BarButtonItem();
this.itemDetails = new DevExpress.XtraBars.BarButtonItem();
this.itemExit = new DevExpress.XtraBars.BarButtonItem();
this.barDockControlTop = new DevExpress.XtraBars.BarDockControl();
this.barDockControlBottom = new DevExpress.XtraBars.BarDockControl();
this.barDockControlLeft = new DevExpress.XtraBars.BarDockControl();
this.barDockControlRight = new DevExpress.XtraBars.BarDockControl();
this.layoutControl1 = new DevExpress.XtraLayout.LayoutControl();
this.CGridControl = new DevExpress.XtraGrid.GridControl();
this.CGridView = new DevExpress.XtraGrid.Views.Grid.GridView();
this.gridColumn1 = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridColumn2 = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridColumn3 = new DevExpress.XtraGrid.Columns.GridColumn();
this.CSan = new KabMan.Controls.C_LookUpControl();
this.CSanGroup = new KabMan.Controls.C_LookUpControl();
this.CCoordinate = new KabMan.Controls.C_LookUpControl();
this.CDataCenter = new KabMan.Controls.C_LookUpControl();
this.CLocation = new KabMan.Controls.C_LookUpControl();
this.CSerial = new DevExpress.XtraEditors.TextEdit();
this.CDevice = new KabMan.Controls.C_LookUpControl();
this.CBlechType = new KabMan.Controls.C_LookUpControl();
this.layoutControlGroup1 = new DevExpress.XtraLayout.LayoutControlGroup();
this.layoutControlItem9 = new DevExpress.XtraLayout.LayoutControlItem();
((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit7)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit8)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit3)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit4)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit5)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.CBarManager)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).BeginInit();
this.layoutControl1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.CGridControl)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.CGridView)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.CSan.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.CSanGroup.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.CCoordinate.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.CDataCenter.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.CLocation.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.CSerial.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.CDevice.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.CBlechType.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem9)).BeginInit();
this.SuspendLayout();
//
// repositoryItemLookUpEdit7
//
this.repositoryItemLookUpEdit7.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo),
new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo),
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Plus, "", -1, false, true, false, DevExpress.XtraEditors.ImageLocation.MiddleCenter, null, new DevExpress.Utils.KeyShortcut(System.Windows.Forms.Keys.None), "", "Add")});
this.repositoryItemLookUpEdit7.Name = "repositoryItemLookUpEdit7";
this.repositoryItemLookUpEdit7.NullText = "Select SAN!";
//
// repositoryItemLookUpEdit8
//
this.repositoryItemLookUpEdit8.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo),
new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo),
new DevExpress.XtraEditors.Controls.EditorButton("Add", DevExpress.XtraEditors.Controls.ButtonPredefines.Plus)});
this.repositoryItemLookUpEdit8.Name = "repositoryItemLookUpEdit8";
this.repositoryItemLookUpEdit8.NullText = "Select SAN Group!";
//
// repositoryItemLookUpEdit3
//
this.repositoryItemLookUpEdit3.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo),
new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo),
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Plus, "", -1, false, true, false, DevExpress.XtraEditors.ImageLocation.MiddleCenter, null, new DevExpress.Utils.KeyShortcut(System.Windows.Forms.Keys.None), "", "Add")});
this.repositoryItemLookUpEdit3.Name = "repositoryItemLookUpEdit3";
this.repositoryItemLookUpEdit3.NullText = "Select Coordinate!";
//
// repositoryItemLookUpEdit4
//
this.repositoryItemLookUpEdit4.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo),
new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo),
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Plus, "", -1, false, true, false, DevExpress.XtraEditors.ImageLocation.MiddleCenter, null, new DevExpress.Utils.KeyShortcut(System.Windows.Forms.Keys.None), "", "Add")});
this.repositoryItemLookUpEdit4.Name = "repositoryItemLookUpEdit4";
this.repositoryItemLookUpEdit4.NullText = "Select Data Center!";
//
// repositoryItemLookUpEdit5
//
this.repositoryItemLookUpEdit5.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo),
new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo),
new DevExpress.XtraEditors.Controls.EditorButton("Add", DevExpress.XtraEditors.Controls.ButtonPredefines.Plus)});
this.repositoryItemLookUpEdit5.Name = "repositoryItemLookUpEdit5";
this.repositoryItemLookUpEdit5.NullText = "Select Location!";
//
// repositoryItemLookUpEdit1
//
this.repositoryItemLookUpEdit1.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo),
new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo),
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Plus, "", -1, false, true, false, DevExpress.XtraEditors.ImageLocation.MiddleCenter, null, new DevExpress.Utils.KeyShortcut(System.Windows.Forms.Keys.None), "", "Add")});
this.repositoryItemLookUpEdit1.Name = "repositoryItemLookUpEdit1";
//
// repositoryItemLookUpEdit2
//
this.repositoryItemLookUpEdit2.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo),
new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo),
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Plus, "", -1, false, true, false, DevExpress.XtraEditors.ImageLocation.MiddleCenter, null, new DevExpress.Utils.KeyShortcut(System.Windows.Forms.Keys.None), "", "Add")});
this.repositoryItemLookUpEdit2.Name = "repositoryItemLookUpEdit2";
//
// CBarManager
//
this.CBarManager.AllowCustomization = false;
this.CBarManager.AllowQuickCustomization = false;
this.CBarManager.AllowShowToolbarsPopup = false;
this.CBarManager.Bars.AddRange(new DevExpress.XtraBars.Bar[] {
this.CStatusBar,
this.bar1});
this.CBarManager.DockControls.Add(this.barDockControlTop);
this.CBarManager.DockControls.Add(this.barDockControlBottom);
this.CBarManager.DockControls.Add(this.barDockControlLeft);
this.CBarManager.DockControls.Add(this.barDockControlRight);
this.CBarManager.Form = this;
this.CBarManager.Items.AddRange(new DevExpress.XtraBars.BarItem[] {
this.itemCount,
this.itemNew,
this.itemDelete,
this.itemDetails,
this.itemExit});
this.CBarManager.MaxItemId = 9;
this.CBarManager.StatusBar = this.CStatusBar;
//
// CStatusBar
//
this.CStatusBar.BarName = "Status Bar";
this.CStatusBar.CanDockStyle = DevExpress.XtraBars.BarCanDockStyle.Bottom;
this.CStatusBar.DockCol = 0;
this.CStatusBar.DockRow = 0;
this.CStatusBar.DockStyle = DevExpress.XtraBars.BarDockStyle.Bottom;
this.CStatusBar.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] {
new DevExpress.XtraBars.LinkPersistInfo(this.itemCount)});
this.CStatusBar.OptionsBar.AllowQuickCustomization = false;
this.CStatusBar.OptionsBar.DrawDragBorder = false;
this.CStatusBar.OptionsBar.UseWholeRow = true;
this.CStatusBar.Text = "Status Bar";
//
// itemCount
//
this.itemCount.Alignment = DevExpress.XtraBars.BarItemLinkAlignment.Right;
this.itemCount.Caption = "0";
this.itemCount.Id = 4;
this.itemCount.Name = "itemCount";
this.itemCount.TextAlignment = System.Drawing.StringAlignment.Near;
//
// bar1
//
this.bar1.BarName = "Custom 4";
this.bar1.DockCol = 0;
this.bar1.DockRow = 0;
this.bar1.DockStyle = DevExpress.XtraBars.BarDockStyle.Top;
this.bar1.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] {
new DevExpress.XtraBars.LinkPersistInfo(this.itemNew),
new DevExpress.XtraBars.LinkPersistInfo(this.itemDelete),
new DevExpress.XtraBars.LinkPersistInfo(this.itemDetails, true),
new DevExpress.XtraBars.LinkPersistInfo(this.itemExit, true)});
this.bar1.OptionsBar.AllowQuickCustomization = false;
this.bar1.OptionsBar.DrawDragBorder = false;
this.bar1.OptionsBar.UseWholeRow = true;
this.bar1.Text = "Custom 4";
//
// itemNew
//
this.itemNew.Caption = "New";
this.itemNew.Id = 5;
this.itemNew.Name = "itemNew";
this.itemNew.PaintStyle = DevExpress.XtraBars.BarItemPaintStyle.CaptionGlyph;
this.itemNew.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.itemNew_ItemClick);
//
// itemDelete
//
this.itemDelete.Caption = "Delete";
this.itemDelete.Id = 6;
this.itemDelete.Name = "itemDelete";
this.itemDelete.PaintStyle = DevExpress.XtraBars.BarItemPaintStyle.CaptionGlyph;
//
// itemDetails
//
this.itemDetails.Caption = "View Details";
this.itemDetails.Id = 7;
this.itemDetails.Name = "itemDetails";
this.itemDetails.PaintStyle = DevExpress.XtraBars.BarItemPaintStyle.CaptionGlyph;
this.itemDetails.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.itemDetails_ItemClick);
//
// itemExit
//
this.itemExit.Caption = "Exit";
this.itemExit.Id = 8;
this.itemExit.Name = "itemExit";
this.itemExit.PaintStyle = DevExpress.XtraBars.BarItemPaintStyle.CaptionGlyph;
this.itemExit.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.itemExit_ItemClick);
//
// layoutControl1
//
this.layoutControl1.Appearance.DisabledLayoutGroupCaption.ForeColor = System.Drawing.SystemColors.GrayText;
this.layoutControl1.Appearance.DisabledLayoutGroupCaption.Options.UseForeColor = true;
this.layoutControl1.Appearance.DisabledLayoutItem.ForeColor = System.Drawing.SystemColors.GrayText;
this.layoutControl1.Appearance.DisabledLayoutItem.Options.UseForeColor = true;
this.layoutControl1.Controls.Add(this.CGridControl);
this.layoutControl1.Controls.Add(this.CSan);
this.layoutControl1.Controls.Add(this.CSanGroup);
this.layoutControl1.Controls.Add(this.CCoordinate);
this.layoutControl1.Controls.Add(this.CDataCenter);
this.layoutControl1.Controls.Add(this.CLocation);
this.layoutControl1.Controls.Add(this.CSerial);
this.layoutControl1.Controls.Add(this.CDevice);
this.layoutControl1.Controls.Add(this.CBlechType);
this.layoutControl1.Dock = System.Windows.Forms.DockStyle.Fill;
this.layoutControl1.Location = new System.Drawing.Point(0, 24);
this.layoutControl1.Name = "layoutControl1";
this.layoutControl1.Root = this.layoutControlGroup1;
this.layoutControl1.Size = new System.Drawing.Size(596, 415);
this.layoutControl1.TabIndex = 4;
this.layoutControl1.Text = "layoutControl1";
//
// CGridControl
//
this.CGridControl.Location = new System.Drawing.Point(7, 7);
this.CGridControl.MainView = this.CGridView;
this.CGridControl.Name = "CGridControl";
this.CGridControl.Size = new System.Drawing.Size(583, 402);
this.CGridControl.TabIndex = 12;
this.CGridControl.ViewCollection.AddRange(new DevExpress.XtraGrid.Views.Base.BaseView[] {
this.CGridView});
this.CGridControl.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.CGridControl_MouseDoubleClick);
//
// CGridView
//
this.CGridView.Appearance.ColumnFilterButton.BackColor = System.Drawing.Color.Silver;
this.CGridView.Appearance.ColumnFilterButton.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(212)))), ((int)(((byte)(212)))));
this.CGridView.Appearance.ColumnFilterButton.BorderColor = System.Drawing.Color.Silver;
this.CGridView.Appearance.ColumnFilterButton.ForeColor = System.Drawing.Color.Gray;
this.CGridView.Appearance.ColumnFilterButton.Options.UseBackColor = true;
this.CGridView.Appearance.ColumnFilterButton.Options.UseBorderColor = true;
this.CGridView.Appearance.ColumnFilterButton.Options.UseForeColor = true;
this.CGridView.Appearance.ColumnFilterButtonActive.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(212)))), ((int)(((byte)(212)))));
this.CGridView.Appearance.ColumnFilterButtonActive.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(223)))), ((int)(((byte)(223)))), ((int)(((byte)(223)))));
this.CGridView.Appearance.ColumnFilterButtonActive.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(212)))), ((int)(((byte)(212)))));
this.CGridView.Appearance.ColumnFilterButtonActive.ForeColor = System.Drawing.Color.Blue;
this.CGridView.Appearance.ColumnFilterButtonActive.Options.UseBackColor = true;
this.CGridView.Appearance.ColumnFilterButtonActive.Options.UseBorderColor = true;
this.CGridView.Appearance.ColumnFilterButtonActive.Options.UseForeColor = true;
this.CGridView.Appearance.Empty.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(243)))), ((int)(((byte)(243)))), ((int)(((byte)(243)))));
this.CGridView.Appearance.Empty.Options.UseBackColor = true;
this.CGridView.Appearance.EvenRow.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(223)))), ((int)(((byte)(223)))), ((int)(((byte)(223)))));
this.CGridView.Appearance.EvenRow.BackColor2 = System.Drawing.Color.GhostWhite;
this.CGridView.Appearance.EvenRow.ForeColor = System.Drawing.Color.Black;
this.CGridView.Appearance.EvenRow.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.CGridView.Appearance.EvenRow.Options.UseBackColor = true;
this.CGridView.Appearance.EvenRow.Options.UseForeColor = true;
this.CGridView.Appearance.FilterCloseButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200)))));
this.CGridView.Appearance.FilterCloseButton.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(118)))), ((int)(((byte)(170)))), ((int)(((byte)(225)))));
this.CGridView.Appearance.FilterCloseButton.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200)))));
this.CGridView.Appearance.FilterCloseButton.ForeColor = System.Drawing.Color.Black;
this.CGridView.Appearance.FilterCloseButton.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.CGridView.Appearance.FilterCloseButton.Options.UseBackColor = true;
this.CGridView.Appearance.FilterCloseButton.Options.UseBorderColor = true;
this.CGridView.Appearance.FilterCloseButton.Options.UseForeColor = true;
this.CGridView.Appearance.FilterPanel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(28)))), ((int)(((byte)(80)))), ((int)(((byte)(135)))));
this.CGridView.Appearance.FilterPanel.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200)))));
this.CGridView.Appearance.FilterPanel.ForeColor = System.Drawing.Color.White;
this.CGridView.Appearance.FilterPanel.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.CGridView.Appearance.FilterPanel.Options.UseBackColor = true;
this.CGridView.Appearance.FilterPanel.Options.UseForeColor = true;
this.CGridView.Appearance.FixedLine.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(58)))), ((int)(((byte)(58)))), ((int)(((byte)(58)))));
this.CGridView.Appearance.FixedLine.Options.UseBackColor = true;
this.CGridView.Appearance.FocusedCell.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(225)))));
this.CGridView.Appearance.FocusedCell.ForeColor = System.Drawing.Color.Black;
this.CGridView.Appearance.FocusedCell.Options.UseBackColor = true;
this.CGridView.Appearance.FocusedCell.Options.UseForeColor = true;
this.CGridView.Appearance.FocusedRow.BackColor = System.Drawing.Color.Navy;
this.CGridView.Appearance.FocusedRow.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(50)))), ((int)(((byte)(50)))), ((int)(((byte)(178)))));
this.CGridView.Appearance.FocusedRow.ForeColor = System.Drawing.Color.White;
this.CGridView.Appearance.FocusedRow.Options.UseBackColor = true;
this.CGridView.Appearance.FocusedRow.Options.UseForeColor = true;
this.CGridView.Appearance.FooterPanel.BackColor = System.Drawing.Color.Silver;
this.CGridView.Appearance.FooterPanel.BorderColor = System.Drawing.Color.Silver;
this.CGridView.Appearance.FooterPanel.ForeColor = System.Drawing.Color.Black;
this.CGridView.Appearance.FooterPanel.Options.UseBackColor = true;
this.CGridView.Appearance.FooterPanel.Options.UseBorderColor = true;
this.CGridView.Appearance.FooterPanel.Options.UseForeColor = true;
this.CGridView.Appearance.GroupButton.BackColor = System.Drawing.Color.Silver;
this.CGridView.Appearance.GroupButton.BorderColor = System.Drawing.Color.Silver;
this.CGridView.Appearance.GroupButton.ForeColor = System.Drawing.Color.Black;
this.CGridView.Appearance.GroupButton.Options.UseBackColor = true;
this.CGridView.Appearance.GroupButton.Options.UseBorderColor = true;
this.CGridView.Appearance.GroupButton.Options.UseForeColor = true;
this.CGridView.Appearance.GroupFooter.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(202)))), ((int)(((byte)(202)))), ((int)(((byte)(202)))));
this.CGridView.Appearance.GroupFooter.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(202)))), ((int)(((byte)(202)))), ((int)(((byte)(202)))));
this.CGridView.Appearance.GroupFooter.ForeColor = System.Drawing.Color.Black;
this.CGridView.Appearance.GroupFooter.Options.UseBackColor = true;
this.CGridView.Appearance.GroupFooter.Options.UseBorderColor = true;
this.CGridView.Appearance.GroupFooter.Options.UseForeColor = true;
this.CGridView.Appearance.GroupPanel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(58)))), ((int)(((byte)(110)))), ((int)(((byte)(165)))));
this.CGridView.Appearance.GroupPanel.BackColor2 = System.Drawing.Color.White;
this.CGridView.Appearance.GroupPanel.Font = new System.Drawing.Font("Tahoma", 8F, System.Drawing.FontStyle.Bold);
this.CGridView.Appearance.GroupPanel.ForeColor = System.Drawing.Color.White;
this.CGridView.Appearance.GroupPanel.Options.UseBackColor = true;
this.CGridView.Appearance.GroupPanel.Options.UseFont = true;
this.CGridView.Appearance.GroupPanel.Options.UseForeColor = true;
this.CGridView.Appearance.GroupRow.BackColor = System.Drawing.Color.Gray;
this.CGridView.Appearance.GroupRow.ForeColor = System.Drawing.Color.Silver;
this.CGridView.Appearance.GroupRow.Options.UseBackColor = true;
this.CGridView.Appearance.GroupRow.Options.UseForeColor = true;
this.CGridView.Appearance.HeaderPanel.BackColor = System.Drawing.Color.Silver;
this.CGridView.Appearance.HeaderPanel.BorderColor = System.Drawing.Color.Silver;
this.CGridView.Appearance.HeaderPanel.Font = new System.Drawing.Font("Tahoma", 8F, System.Drawing.FontStyle.Bold);
this.CGridView.Appearance.HeaderPanel.ForeColor = System.Drawing.Color.Black;
this.CGridView.Appearance.HeaderPanel.Options.UseBackColor = true;
this.CGridView.Appearance.HeaderPanel.Options.UseBorderColor = true;
this.CGridView.Appearance.HeaderPanel.Options.UseFont = true;
this.CGridView.Appearance.HeaderPanel.Options.UseForeColor = true;
this.CGridView.Appearance.HideSelectionRow.BackColor = System.Drawing.Color.Gray;
this.CGridView.Appearance.HideSelectionRow.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200)))));
this.CGridView.Appearance.HideSelectionRow.Options.UseBackColor = true;
this.CGridView.Appearance.HideSelectionRow.Options.UseForeColor = true;
this.CGridView.Appearance.HorzLine.BackColor = System.Drawing.Color.Silver;
this.CGridView.Appearance.HorzLine.Options.UseBackColor = true;
this.CGridView.Appearance.OddRow.BackColor = System.Drawing.Color.White;
this.CGridView.Appearance.OddRow.BackColor2 = System.Drawing.Color.White;
this.CGridView.Appearance.OddRow.ForeColor = System.Drawing.Color.Black;
this.CGridView.Appearance.OddRow.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.BackwardDiagonal;
this.CGridView.Appearance.OddRow.Options.UseBackColor = true;
this.CGridView.Appearance.OddRow.Options.UseForeColor = true;
this.CGridView.Appearance.Preview.BackColor = System.Drawing.Color.White;
this.CGridView.Appearance.Preview.ForeColor = System.Drawing.Color.Navy;
this.CGridView.Appearance.Preview.Options.UseBackColor = true;
this.CGridView.Appearance.Preview.Options.UseForeColor = true;
this.CGridView.Appearance.Row.BackColor = System.Drawing.Color.White;
this.CGridView.Appearance.Row.ForeColor = System.Drawing.Color.Black;
this.CGridView.Appearance.Row.Options.UseBackColor = true;
this.CGridView.Appearance.Row.Options.UseForeColor = true;
this.CGridView.Appearance.RowSeparator.BackColor = System.Drawing.Color.White;
this.CGridView.Appearance.RowSeparator.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(243)))), ((int)(((byte)(243)))), ((int)(((byte)(243)))));
this.CGridView.Appearance.RowSeparator.Options.UseBackColor = true;
this.CGridView.Appearance.SelectedRow.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(10)))), ((int)(((byte)(10)))), ((int)(((byte)(138)))));
this.CGridView.Appearance.SelectedRow.ForeColor = System.Drawing.Color.White;
this.CGridView.Appearance.SelectedRow.Options.UseBackColor = true;
this.CGridView.Appearance.SelectedRow.Options.UseForeColor = true;
this.CGridView.Appearance.VertLine.BackColor = System.Drawing.Color.Silver;
this.CGridView.Appearance.VertLine.Options.UseBackColor = true;
this.CGridView.Columns.AddRange(new DevExpress.XtraGrid.Columns.GridColumn[] {
this.gridColumn1,
this.gridColumn2,
this.gridColumn3});
this.CGridView.GridControl = this.CGridControl;
this.CGridView.Name = "CGridView";
this.CGridView.OptionsBehavior.AllowIncrementalSearch = true;
this.CGridView.OptionsBehavior.Editable = false;
this.CGridView.OptionsView.EnableAppearanceEvenRow = true;
this.CGridView.OptionsView.EnableAppearanceOddRow = true;
this.CGridView.OptionsView.ShowAutoFilterRow = true;
this.CGridView.OptionsView.ShowGroupPanel = false;
this.CGridView.OptionsView.ShowIndicator = false;
//
// gridColumn1
//
this.gridColumn1.Caption = "Name";
this.gridColumn1.FieldName = "Name";
this.gridColumn1.Name = "gridColumn1";
this.gridColumn1.Visible = true;
this.gridColumn1.VisibleIndex = 0;
//
// gridColumn2
//
this.gridColumn2.Caption = "Location ";
this.gridColumn2.FieldName = "LocationName";
this.gridColumn2.Name = "gridColumn2";
this.gridColumn2.Visible = true;
this.gridColumn2.VisibleIndex = 1;
//
// gridColumn3
//
this.gridColumn3.Caption = "Data Center";
this.gridColumn3.FieldName = "DataCenterName";
this.gridColumn3.Name = "gridColumn3";
this.gridColumn3.Visible = true;
this.gridColumn3.VisibleIndex = 2;
//
// CSan
//
this.CSan.Columns = this.repositoryItemLookUpEdit7.Columns;
this.CSan.DisplayMember = null;
this.CSan.FormParameters = ((System.Collections.Generic.List<object>)(resources.GetObject("CSan.FormParameters")));
this.CSan.Location = new System.Drawing.Point(67, 59);
this.CSan.Name = "CSan";
this.CSan.NullText = "Select SAN!";
this.CSan.Parameters = new KabMan.Controls.NameValuePair[0];
this.CSan.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo),
new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo),
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Plus, "", -1, false, true, false, DevExpress.XtraEditors.ImageLocation.MiddleCenter, null, new DevExpress.Utils.KeyShortcut(System.Windows.Forms.Keys.None), "", "Add")});
this.CSan.Properties.NullText = "Select SAN!";
this.CSan.RefreshButtonVisible = true;
this.CSan.Size = new System.Drawing.Size(545, 20);
this.CSan.StoredProcedure = null;
this.CSan.StyleController = this.layoutControl1;
this.CSan.TabIndex = 11;
this.CSan.TriggerControl = null;
this.CSan.ValueMember = null;
//
// CSanGroup
//
this.CSanGroup.AddButtonEnabled = true;
this.CSanGroup.Columns = this.repositoryItemLookUpEdit8.Columns;
this.CSanGroup.DisplayMember = null;
this.CSanGroup.FormParameters = ((System.Collections.Generic.List<object>)(resources.GetObject("CSanGroup.FormParameters")));
this.CSanGroup.Location = new System.Drawing.Point(67, 28);
this.CSanGroup.Name = "CSanGroup";
this.CSanGroup.NullText = "Select SAN Group!";
this.CSanGroup.Parameters = new KabMan.Controls.NameValuePair[0];
this.CSanGroup.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo),
new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo),
new DevExpress.XtraEditors.Controls.EditorButton("Add", DevExpress.XtraEditors.Controls.ButtonPredefines.Plus)});
this.CSanGroup.Properties.NullText = "Select SAN Group!";
this.CSanGroup.RefreshButtonVisible = true;
this.CSanGroup.Size = new System.Drawing.Size(545, 20);
this.CSanGroup.StoredProcedure = null;
this.CSanGroup.StyleController = this.layoutControl1;
this.CSanGroup.TabIndex = 10;
this.CSanGroup.TriggerControl = null;
this.CSanGroup.ValueMember = null;
//
// CCoordinate
//
this.CCoordinate.Columns = this.repositoryItemLookUpEdit3.Columns;
this.CCoordinate.DisplayMember = null;
this.CCoordinate.FormParameters = ((System.Collections.Generic.List<object>)(resources.GetObject("CCoordinate.FormParameters")));
this.CCoordinate.Location = new System.Drawing.Point(74, 90);
this.CCoordinate.Name = "CCoordinate";
this.CCoordinate.NullText = "Select Coordinate!";
this.CCoordinate.Parameters = new KabMan.Controls.NameValuePair[0];
this.CCoordinate.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo),
new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo),
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Plus, "", -1, false, true, false, DevExpress.XtraEditors.ImageLocation.MiddleCenter, null, new DevExpress.Utils.KeyShortcut(System.Windows.Forms.Keys.None), "", "Add")});
this.CCoordinate.Properties.NullText = "Select Coordinate!";
this.CCoordinate.RefreshButtonVisible = true;
this.CCoordinate.Size = new System.Drawing.Size(538, 20);
this.CCoordinate.StoredProcedure = null;
this.CCoordinate.StyleController = this.layoutControl1;
this.CCoordinate.TabIndex = 9;
this.CCoordinate.TriggerControl = null;
this.CCoordinate.ValueMember = null;
//
// CDataCenter
//
this.CDataCenter.Columns = this.repositoryItemLookUpEdit4.Columns;
this.CDataCenter.DisplayMember = null;
this.CDataCenter.FormParameters = ((System.Collections.Generic.List<object>)(resources.GetObject("CDataCenter.FormParameters")));
this.CDataCenter.Location = new System.Drawing.Point(74, 59);
this.CDataCenter.Name = "CDataCenter";
this.CDataCenter.NullText = "Select Data Center!";
this.CDataCenter.Parameters = new KabMan.Controls.NameValuePair[0];
this.CDataCenter.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo),
new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo),
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Plus, "", -1, false, true, false, DevExpress.XtraEditors.ImageLocation.MiddleCenter, null, new DevExpress.Utils.KeyShortcut(System.Windows.Forms.Keys.None), "", "Add")});
this.CDataCenter.Properties.NullText = "Select Data Center!";
this.CDataCenter.RefreshButtonVisible = true;
this.CDataCenter.Size = new System.Drawing.Size(538, 20);
this.CDataCenter.StoredProcedure = null;
this.CDataCenter.StyleController = this.layoutControl1;
this.CDataCenter.TabIndex = 8;
this.CDataCenter.TriggerControl = null;
this.CDataCenter.ValueMember = null;
//
// CLocation
//
this.CLocation.AddButtonEnabled = true;
this.CLocation.Columns = this.repositoryItemLookUpEdit5.Columns;
this.CLocation.DisplayMember = null;
this.CLocation.FormParameters = ((System.Collections.Generic.List<object>)(resources.GetObject("CLocation.FormParameters")));
this.CLocation.Location = new System.Drawing.Point(74, 28);
this.CLocation.Name = "CLocation";
this.CLocation.NullText = "Select Location!";
this.CLocation.Parameters = new KabMan.Controls.NameValuePair[0];
this.CLocation.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo),
new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo),
new DevExpress.XtraEditors.Controls.EditorButton("Add", DevExpress.XtraEditors.Controls.ButtonPredefines.Plus)});
this.CLocation.Properties.NullText = "Select Location!";
this.CLocation.RefreshButtonVisible = true;
this.CLocation.Size = new System.Drawing.Size(538, 20);
this.CLocation.StoredProcedure = null;
this.CLocation.StyleController = this.layoutControl1;
this.CLocation.TabIndex = 7;
this.CLocation.TriggerControl = null;
this.CLocation.ValueMember = null;
//
// CSerial
//
this.CSerial.Location = new System.Drawing.Point(74, 90);
this.CSerial.Name = "CSerial";
this.CSerial.Size = new System.Drawing.Size(538, 20);
this.CSerial.StyleController = this.layoutControl1;
this.CSerial.TabIndex = 6;
//
// CDevice
//
this.CDevice.AddButtonEnabled = true;
this.CDevice.Columns = this.repositoryItemLookUpEdit1.Columns;
this.CDevice.FormParameters = ((System.Collections.Generic.List<object>)(resources.GetObject("CDevice.FormParameters")));
this.CDevice.Location = new System.Drawing.Point(74, 59);
this.CDevice.Name = "CDevice";
this.CDevice.NullText = "Select Device to use Blech with!";
this.CDevice.Parameters = new KabMan.Controls.NameValuePair[0];
this.CDevice.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo),
new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo),
new DevExpress.XtraEditors.Controls.EditorButton("Add", DevExpress.XtraEditors.Controls.ButtonPredefines.Plus)});
this.CDevice.Properties.NullText = "Select Device to use Blech with!";
this.CDevice.RefreshButtonVisible = true;
this.CDevice.Size = new System.Drawing.Size(538, 20);
this.CDevice.StoredProcedure = null;
this.CDevice.StyleController = this.layoutControl1;
this.CDevice.TabIndex = 5;
this.CDevice.TriggerControl = null;
//
// CBlechType
//
this.CBlechType.AddButtonEnabled = true;
this.CBlechType.Columns = this.repositoryItemLookUpEdit2.Columns;
this.CBlechType.FormParameters = ((System.Collections.Generic.List<object>)(resources.GetObject("CBlechType.FormParameters")));
this.CBlechType.Location = new System.Drawing.Point(74, 28);
this.CBlechType.Name = "CBlechType";
this.CBlechType.NullText = "Select Blech Type!";
this.CBlechType.Parameters = new KabMan.Controls.NameValuePair[0];
this.CBlechType.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo),
new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo),
new DevExpress.XtraEditors.Controls.EditorButton("Add", DevExpress.XtraEditors.Controls.ButtonPredefines.Plus)});
this.CBlechType.Properties.NullText = "Select Blech Type!";
this.CBlechType.RefreshButtonVisible = true;
this.CBlechType.Size = new System.Drawing.Size(538, 20);
this.CBlechType.StoredProcedure = null;
this.CBlechType.StyleController = this.layoutControl1;
this.CBlechType.TabIndex = 4;
this.CBlechType.TriggerControl = null;
//
// layoutControlGroup1
//
this.layoutControlGroup1.CustomizationFormText = "layoutControlGroup1";
this.layoutControlGroup1.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] {
this.layoutControlItem9});
this.layoutControlGroup1.Location = new System.Drawing.Point(0, 0);
this.layoutControlGroup1.Name = "layoutControlGroup1";
this.layoutControlGroup1.Size = new System.Drawing.Size(596, 415);
this.layoutControlGroup1.Spacing = new DevExpress.XtraLayout.Utils.Padding(0, 0, 0, 0);
this.layoutControlGroup1.Text = "layoutControlGroup1";
this.layoutControlGroup1.TextVisible = false;
//
// layoutControlItem9
//
this.layoutControlItem9.Control = this.CGridControl;
this.layoutControlItem9.CustomizationFormText = "layoutControlItem9";
this.layoutControlItem9.Location = new System.Drawing.Point(0, 0);
this.layoutControlItem9.Name = "layoutControlItem9";
this.layoutControlItem9.Size = new System.Drawing.Size(594, 413);
this.layoutControlItem9.Text = "layoutControlItem9";
this.layoutControlItem9.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem9.TextSize = new System.Drawing.Size(0, 0);
this.layoutControlItem9.TextToControlDistance = 0;
this.layoutControlItem9.TextVisible = false;
//
// VTPortManagerForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(596, 464);
this.Controls.Add(this.layoutControl1);
this.Controls.Add(this.barDockControlLeft);
this.Controls.Add(this.barDockControlRight);
this.Controls.Add(this.barDockControlBottom);
this.Controls.Add(this.barDockControlTop);
this.MinimumSize = new System.Drawing.Size(420, 500);
this.Name = "VTPortManagerForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "VTPort Manager";
this.Load += new System.EventHandler(this.VTPortManagerForm_Load);
((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit7)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit8)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit3)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit4)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit5)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.CBarManager)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).EndInit();
this.layoutControl1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.CGridControl)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.CGridView)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.CSan.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.CSanGroup.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.CCoordinate.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.CDataCenter.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.CLocation.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.CSerial.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.CDevice.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.CBlechType.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem9)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DevExpress.XtraBars.BarManager CBarManager;
private DevExpress.XtraBars.Bar CStatusBar;
private DevExpress.XtraBars.BarDockControl barDockControlTop;
private DevExpress.XtraBars.BarDockControl barDockControlBottom;
private DevExpress.XtraBars.BarDockControl barDockControlLeft;
private DevExpress.XtraBars.BarDockControl barDockControlRight;
private DevExpress.XtraBars.BarStaticItem itemCount;
private DevExpress.XtraLayout.LayoutControl layoutControl1;
private DevExpress.XtraLayout.LayoutControlGroup layoutControlGroup1;
private DevExpress.XtraEditors.TextEdit CSerial;
private KabMan.Controls.C_LookUpControl CDevice;
private KabMan.Controls.C_LookUpControl CBlechType;
private KabMan.Controls.C_LookUpControl CSan;
private KabMan.Controls.C_LookUpControl CSanGroup;
private KabMan.Controls.C_LookUpControl CCoordinate;
private KabMan.Controls.C_LookUpControl CDataCenter;
private KabMan.Controls.C_LookUpControl CLocation;
private DevExpress.XtraGrid.GridControl CGridControl;
private DevExpress.XtraGrid.Views.Grid.GridView CGridView;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem9;
private DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repositoryItemLookUpEdit1;
private DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repositoryItemLookUpEdit2;
private DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repositoryItemLookUpEdit7;
private DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repositoryItemLookUpEdit8;
private DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repositoryItemLookUpEdit3;
private DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repositoryItemLookUpEdit4;
private DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repositoryItemLookUpEdit5;
private DevExpress.XtraBars.Bar bar1;
private DevExpress.XtraBars.BarButtonItem itemNew;
private DevExpress.XtraBars.BarButtonItem itemDelete;
private DevExpress.XtraBars.BarButtonItem itemDetails;
private DevExpress.XtraBars.BarButtonItem itemExit;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn1;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn2;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn3;
}
}
| |
namespace Selenium.WebDriver.Extensions.Tests
{
using System;
using System.Diagnostics.CodeAnalysis;
using AutoFixture;
using AutoFixture.Xunit2;
using FluentAssertions;
using OpenQA.Selenium;
using Xunit;
using static System.String;
using static By;
using static Shared.Trait;
using static Softlr.Suppress;
[Trait(CATEGORY, UNIT)]
[ExcludeFromCodeCoverage]
[SuppressMessage(SONARQUBE, S3900)]
public class JQuerySelectorTests
{
private static readonly Fixture _fixture = new();
public static TheoryData<Action> SelectorArgumentExceptionTests =>
new()
{
() => JQuerySelector(_fixture.Create<string>()).AddBack(Empty),
() => JQuerySelector(_fixture.Create<string>()).Children(Empty),
() => JQuerySelector(_fixture.Create<string>()).Next(Empty),
() => JQuerySelector(_fixture.Create<string>()).NextAll(Empty),
() => JQuerySelector(_fixture.Create<string>()).NextUntil(Empty, _fixture.Create<string>()),
() => JQuerySelector(_fixture.Create<string>()).NextUntil(_fixture.Create<string>(), Empty),
() => JQuerySelector(_fixture.Create<string>()).NextUntil(null, Empty),
() => JQuerySelector(_fixture.Create<string>()).Prev(Empty),
() => JQuerySelector(_fixture.Create<string>()).PrevAll(Empty),
() => JQuerySelector(_fixture.Create<string>()).PrevUntil(Empty, _fixture.Create<string>()),
() => JQuerySelector(_fixture.Create<string>()).PrevUntil(_fixture.Create<string>(), Empty),
() => JQuerySelector(_fixture.Create<string>()).PrevUntil(null, Empty),
() => JQuerySelector(_fixture.Create<string>()).Parent(Empty),
() => JQuerySelector(_fixture.Create<string>()).Parents(Empty),
() => JQuerySelector(_fixture.Create<string>()).ParentsUntil(Empty, _fixture.Create<string>()),
() => JQuerySelector(_fixture.Create<string>()).ParentsUntil(_fixture.Create<string>(), Empty),
() => JQuerySelector(_fixture.Create<string>()).ParentsUntil(null, Empty),
() => JQuerySelector(_fixture.Create<string>()).Siblings(Empty),
};
[SuppressMessage(FXCOP, CA1806)]
public static TheoryData<Action> SelectorNullArgumentExceptionTests =>
new()
{
() => JQuerySelector(_fixture.Create<string>()).Add(_fixture.Create<string>(), null),
() => JQuerySelector(_fixture.Create<string>()).Add(Empty),
() => JQuerySelector(_fixture.Create<string>()).Add(Empty, JQuerySelector(_fixture.Create<string>())),
() => JQuerySelector(_fixture.Create<string>()).Add(null),
() => JQuerySelector(_fixture.Create<string>()).Add(null, JQuerySelector(_fixture.Create<string>())),
() => JQuerySelector(_fixture.Create<string>()).Closest(_fixture.Create<string>(), null),
() => JQuerySelector(_fixture.Create<string>()).Closest(Empty),
() => JQuerySelector(_fixture.Create<string>())
.Closest(Empty, JQuerySelector(_fixture.Create<string>())),
() => JQuerySelector(_fixture.Create<string>()).Closest(null),
() => JQuerySelector(_fixture.Create<string>())
.Closest(null, JQuerySelector(_fixture.Create<string>())),
() => JQuerySelector(_fixture.Create<string>()).Filter(Empty),
() => JQuerySelector(_fixture.Create<string>()).Filter(null),
() => JQuerySelector(_fixture.Create<string>()).Find(Empty),
() => JQuerySelector(_fixture.Create<string>()).Find(null),
() => JQuerySelector(_fixture.Create<string>()).Has(Empty),
() => JQuerySelector(_fixture.Create<string>()).Has(null),
() => JQuerySelector(_fixture.Create<string>()).Is(Empty),
() => JQuerySelector(_fixture.Create<string>()).Is(null),
() => JQuerySelector(_fixture.Create<string>()).Not(Empty),
() => JQuerySelector(_fixture.Create<string>()).Not(null),
() => new JQuerySelector(_fixture.Create<string>(), null, _fixture.Create<string>(), null)
};
public static TheoryData<JQuerySelector, string> SelectorsTests
{
get
{
var tag = _fixture.Create<string>();
var parentTag = _fixture.Create<string>();
var variable = _fixture.Create<string>();
var chain = _fixture.Create<string>();
var attrName = _fixture.Create<string>();
var attrValue = _fixture.Create<string>();
var innerTag = _fixture.Create<string>();
var selector = _fixture.Create<string>();
var index1 = _fixture.Create<int>();
var index2 = _fixture.Create<int>();
var filter = _fixture.Create<string>();
return new TheoryData<JQuerySelector, string>
{
// simple selector
{ JQuerySelector(tag), $"jQuery('{tag}')" },
// constructor
{ new JQuerySelector(tag), $"jQuery('{tag}')" },
{
new JQuerySelector(tag, new JQuerySelector(parentTag), variable, chain),
$"{variable}('{tag}', jQuery('{parentTag}')){chain}"
},
// escaping
{ JQuerySelector($"[{attrName}=\"{attrValue}\"]"), $"jQuery('[{attrName}=\"{attrValue}\"]')" },
{ JQuerySelector($"[{attrName}='{attrValue}']"), $"jQuery('[{attrName}=\"{attrValue}\"]')" },
{
JQuerySelector(tag).Add($"[{attrName}=\"{attrValue}\"]"),
$"jQuery('{tag}').add('[{attrName}=\"{attrValue}\"]')"
},
{
JQuerySelector(tag).Add($"[{attrName}='{attrValue}']"),
$"jQuery('{tag}').add('[{attrName}=\"{attrValue}\"]')"
},
// chained methods
{ JQuerySelector(tag).Add(innerTag), $"jQuery('{tag}').add('{innerTag}')" },
{
JQuerySelector(tag).Add(innerTag, JQuerySelector(selector)),
$"jQuery('{tag}').add('{innerTag}', jQuery('{selector}'))"
},
{ JQuerySelector(tag).AddBack(), $"jQuery('{tag}').addBack()" },
{ JQuerySelector(tag).AddBack(innerTag), $"jQuery('{tag}').addBack('{innerTag}')" },
{ JQuerySelector(tag).AndSelf(), $"jQuery('{tag}').andSelf()" },
{ JQuerySelector(tag).Children(), $"jQuery('{tag}').children()" },
{ JQuerySelector(tag).Children(innerTag), $"jQuery('{tag}').children('{innerTag}')" },
{ JQuerySelector(tag).Closest(innerTag), $"jQuery('{tag}').closest('{innerTag}')" },
{
JQuerySelector(tag).Closest(innerTag, JQuerySelector(selector)),
$"jQuery('{tag}').closest('{innerTag}', jQuery('{selector}'))"
},
{ JQuerySelector(tag).Contents(), $"jQuery('{tag}').contents()" },
{ JQuerySelector(tag).End(), $"jQuery('{tag}').end()" },
{ JQuerySelector(tag).Eq(index1), $"jQuery('{tag}').eq({index1})" },
{ JQuerySelector(tag).Even(), $"jQuery('{tag}').even()" },
{ JQuerySelector(tag).Filter(selector), $"jQuery('{tag}').filter('{selector}')" },
{ JQuerySelector(tag).Find(selector), $"jQuery('{tag}').find('{selector}')" },
{ JQuerySelector(tag).First(), $"jQuery('{tag}').first()" },
{ JQuerySelector(tag).Has(selector), $"jQuery('{tag}').has('{selector}')" },
{ JQuerySelector(tag).Is(selector), $"jQuery('{tag}').is('{selector}')" },
{ JQuerySelector(tag).Last(), $"jQuery('{tag}').last()" },
{ JQuerySelector(tag).Next(), $"jQuery('{tag}').next()" },
{ JQuerySelector(tag).Next(selector), $"jQuery('{tag}').next('{selector}')" },
{ JQuerySelector(tag).NextAll(), $"jQuery('{tag}').nextAll()" },
{ JQuerySelector(tag).NextAll(selector), $"jQuery('{tag}').nextAll('{selector}')" },
{ JQuerySelector(tag).NextUntil(), $"jQuery('{tag}').nextUntil()" },
{ JQuerySelector(tag).NextUntil(null, filter), $"jQuery('{tag}').nextUntil('', '{filter}')" },
{ JQuerySelector(tag).NextUntil(selector), $"jQuery('{tag}').nextUntil('{selector}')" },
{
JQuerySelector(tag).NextUntil(selector, filter),
$"jQuery('{tag}').nextUntil('{selector}', '{filter}')"
},
{ JQuerySelector(tag).Not(selector), $"jQuery('{tag}').not('{selector}')" },
{ JQuerySelector(tag).Odd(), $"jQuery('{tag}').odd()" },
{ JQuerySelector(tag).OffsetParent(), $"jQuery('{tag}').offsetParent()" },
{ JQuerySelector(tag).Parent(), $"jQuery('{tag}').parent()" },
{ JQuerySelector(tag).Parent(selector), $"jQuery('{tag}').parent('{selector}')" },
{ JQuerySelector(tag).Parents(), $"jQuery('{tag}').parents()" },
{ JQuerySelector(tag).Parents(selector), $"jQuery('{tag}').parents('{selector}')" },
{ JQuerySelector(tag).ParentsUntil(), $"jQuery('{tag}').parentsUntil()" },
{
JQuerySelector(tag).ParentsUntil(null, filter),
$"jQuery('{tag}').parentsUntil('', '{filter}')"
},
{ JQuerySelector(tag).ParentsUntil(selector), $"jQuery('{tag}').parentsUntil('{selector}')" },
{
JQuerySelector(tag).ParentsUntil(selector, filter),
$"jQuery('{tag}').parentsUntil('{selector}', '{filter}')"
},
{ JQuerySelector(tag).Prev(), $"jQuery('{tag}').prev()" },
{ JQuerySelector(tag).Prev(selector), $"jQuery('{tag}').prev('{selector}')" },
{ JQuerySelector(tag).PrevAll(), $"jQuery('{tag}').prevAll()" },
{ JQuerySelector(tag).PrevAll(selector), $"jQuery('{tag}').prevAll('{selector}')" },
{ JQuerySelector(tag).PrevUntil(), $"jQuery('{tag}').prevUntil()" },
{ JQuerySelector(tag).PrevUntil(null, filter), $"jQuery('{tag}').prevUntil('', '{filter}')" },
{ JQuerySelector(tag).PrevUntil(selector), $"jQuery('{tag}').prevUntil('{selector}')" },
{
JQuerySelector(tag).PrevUntil(selector, filter),
$"jQuery('{tag}').prevUntil('{selector}', '{filter}')"
},
{ JQuerySelector(tag).Siblings(), $"jQuery('{tag}').siblings()" },
{ JQuerySelector(tag).Siblings(selector), $"jQuery('{tag}').siblings('{selector}')" },
{ JQuerySelector(tag).Slice(index1), $"jQuery('{tag}').slice({index1})" },
{ JQuerySelector(tag).Slice(index1, index2), $"jQuery('{tag}').slice({index1}, {index2})" },
// chained methods with context
{
JQuerySelector(tag, JQuerySelector(selector)).Children().First(),
$"jQuery('{tag}', jQuery('{selector}')).children().first()"
}
};
}
}
[Theory]
[MemberData(nameof(SelectorsTests))]
[SuppressMessage(SONARQUBE, S3242)]
public void ShouldCreateCorrectSelector(JQuerySelector sut, string expectedSelector) =>
sut.Selector.Should().Be(expectedSelector);
[Theory]
[AutoData]
public void ShouldCreateJQuerySelector(string rawSelector)
{
var sut = JQuerySelector(rawSelector);
sut.Should().NotBeNull();
sut.RawSelector.Should().Be(rawSelector);
}
[Theory]
[AutoData]
public void ShouldCreateJQuerySelectorWithContext(string contextRawSelector, string rawSelector)
{
var sut = JQuerySelector(rawSelector, JQuerySelector(contextRawSelector));
sut.Should().NotBeNull();
sut.RawSelector.Should().Be(rawSelector);
sut.Context.RawSelector.Should().Be(contextRawSelector);
}
[Theory]
[AutoData]
public void ShouldCreateJQuerySelectorWithJQueryVariable(string rawSelector, string variable)
{
var sut = JQuerySelector(rawSelector, variable: variable);
sut.Should().NotBeNull();
sut.RawSelector.Should().Be(rawSelector);
sut.Variable.Should().Be(variable);
}
[Theory]
[AutoData]
public void ShouldFindElementByJQuerySelector(string rawSelector)
{
var driver = new WebDriverBuilder().WithJQueryLoaded().WithElementLocatedByJQuery(rawSelector).Build();
var selector = JQuerySelector(rawSelector);
var sut = selector.FindElement(driver);
sut.Should().NotBeNull();
}
[Theory]
[AutoData]
public void ShouldFindElementsByJQuerySelector(string rawSelector)
{
var driver = new WebDriverBuilder().WithJQueryLoaded().WithElementsLocatedByJQuery(rawSelector).Build();
var selector = JQuerySelector(rawSelector);
var sut = selector.FindElements(driver);
sut.Should().NotBeNull().And.HaveCount(2);
}
[Theory]
[AutoData]
public void ShouldFindElementWithNestedJQuerySelector(string rawSelector)
{
var driver = new WebDriverBuilder().WithJQueryLoaded().WithElementLocatedByJQuery(rawSelector)
.WithElementLocatedByJQuery($"body > {rawSelector}").WithPathToElement(rawSelector).Build();
var element = new SearchContextBuilder().AsWebElement().WithWrappedDriver(driver).Build();
var selector = JQuerySelector(rawSelector);
var sut = selector.FindElement(element);
sut.Should().NotBeNull();
}
[Theory]
[AutoData]
public void ShouldReturnEmptyResultWhenNoElementsAreFoundWithJQuerySelector(string rawSelector)
{
var driver = new WebDriverBuilder().WithJQueryLoaded().WithNoElementLocatedByJQuery(rawSelector).Build();
var selector = JQuerySelector(rawSelector);
var sut = selector.FindElements(driver);
sut.Should().NotBeNull().And.HaveCount(0);
}
[Theory]
[MemberData(nameof(SelectorArgumentExceptionTests))]
public void ShouldThrowExceptionForInvalidArguments(Action sut) =>
FluentActions.Invoking(sut).Should().Throw<ArgumentException>();
[Theory]
[MemberData(nameof(SelectorNullArgumentExceptionTests))]
public void ShouldThrowExceptionForNullArguments(Action sut) =>
FluentActions.Invoking(sut).Should().Throw<ArgumentNullException>();
[Fact]
public void ShouldThrowExceptionWhenCreatingJQuerySelectorWithEmptyValue() =>
FluentActions.Invoking(() => JQuerySelector(Empty)).Should().Throw<ArgumentException>().And.ParamName
.Should().Be("selector");
[Theory]
[AutoData]
public void ShouldThrowExceptionWhenCreatingJQuerySelectorWithEmptyVariableValue(string rawSelector) =>
FluentActions.Invoking(() => JQuerySelector(rawSelector, variable: Empty)).Should()
.Throw<ArgumentException>().And.ParamName.Should().Be("variable");
[Fact]
public void ShouldThrowExceptionWhenCreatingJQuerySelectorWithNullValue() =>
FluentActions.Invoking(() => JQuerySelector(null)).Should().Throw<ArgumentNullException>().And.ParamName
.Should().Be("selector");
[Theory]
[AutoData]
public void ShouldThrowExceptionWhenCreatingJQuerySelectorWithNullVariableValue(string rawSelector) =>
FluentActions.Invoking(() => JQuerySelector(rawSelector, variable: null)).Should()
.Throw<ArgumentNullException>().And.ParamName.Should().Be("variable");
[Fact]
public void ShouldThrowExceptionWhenCreatingJQuerySelectorWithWhiteSpaceOnlyValue() =>
FluentActions.Invoking(() => JQuerySelector(" ")).Should().Throw<ArgumentException>().And.ParamName
.Should().Be("selector");
[Theory]
[AutoData]
public void ShouldThrowExceptionWhenCreatingJQuerySelectorWithWhiteSpaceOnlyVariableValue(
string rawSelector) =>
FluentActions.Invoking(() => JQuerySelector(rawSelector, variable: " ")).Should()
.Throw<ArgumentException>().And.ParamName.Should().Be("variable");
[Theory]
[AutoData]
public void ShouldThrowExceptionWhenElementIsNotFoundWithJQuerySelector(string rawSelector)
{
var driver = new WebDriverBuilder().WithJQueryLoaded().WithNoElementLocatedByJQuery(rawSelector).Build();
var sut = JQuerySelector(rawSelector);
FluentActions.Invoking(() => sut.FindElement(driver)).Should().Throw<NoSuchElementException>();
}
[Theory]
[AutoData]
public void ShouldThrowExceptionWhenSearchContextDoesNotWrapDriver(string rawSelector)
{
var element = new SearchContextBuilder().AsWebElement().Build();
var sut = JQuerySelector(rawSelector);
FluentActions.Invoking(() => sut.FindElement(element)).Should().Throw<InvalidCastException>();
}
[Theory]
[AutoData]
public void ShouldThrowExceptionWhenSearchContextIsNotWebElement(string rawSelector)
{
var driver = new WebDriverBuilder().WithJQueryLoaded().WithElementLocatedByJQuery(rawSelector)
.WithElementLocatedByJQuery($"body > {rawSelector}").WithPathToElement(rawSelector).Build();
var element = new SearchContextBuilder().WithWrappedDriver(driver).Build();
var sut = JQuerySelector(rawSelector);
FluentActions.Invoking(() => sut.FindElement(element)).Should().Throw<NotSupportedException>();
}
}
}
| |
// 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.Data.Common;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
namespace System.Data.Odbc
{
internal sealed class OdbcConnectionHandle : OdbcHandle
{
private HandleState _handleState;
private enum HandleState
{
Allocated = 0,
Connected = 1,
Transacted = 2,
TransactionInProgress = 3,
}
internal OdbcConnectionHandle(OdbcConnection connection, OdbcConnectionString constr, OdbcEnvironmentHandle environmentHandle) : base(ODBC32.SQL_HANDLE.DBC, environmentHandle)
{
if (null == connection)
{
throw ADP.ArgumentNull(nameof(connection));
}
if (null == constr)
{
throw ADP.ArgumentNull(nameof(constr));
}
ODBC32.RetCode retcode;
//Set connection timeout (only before open).
//Note: We use login timeout since its odbc 1.0 option, instead of using
//connectiontimeout (which affects other things besides just login) and its
//a odbc 3.0 feature. The ConnectionTimeout on the managed providers represents
//the login timeout, nothing more.
int connectionTimeout = connection.ConnectionTimeout;
retcode = SetConnectionAttribute2(ODBC32.SQL_ATTR.LOGIN_TIMEOUT, (IntPtr)connectionTimeout, (int)ODBC32.SQL_IS.UINTEGER);
string connectionString = constr.UsersConnectionString(false);
// Connect to the driver. (Using the connection string supplied)
//Note: The driver doesn't filter out the password in the returned connection string
//so their is no need for us to obtain the returned connection string
// Prepare to handle a ThreadAbort Exception between SQLDriverConnectW and update of the state variables
retcode = Connect(connectionString);
connection.HandleError(this, retcode);
}
private ODBC32.RetCode AutoCommitOff()
{
ODBC32.RetCode retcode;
Debug.Assert(HandleState.Connected <= _handleState, "AutoCommitOff while in wrong state?");
// Avoid runtime injected errors in the following block.
// must call SQLSetConnectAttrW and set _handleState
RuntimeHelpers.PrepareConstrainedRegions();
try { }
finally
{
retcode = Interop.Odbc.SQLSetConnectAttrW(this, ODBC32.SQL_ATTR.AUTOCOMMIT, ODBC32.SQL_AUTOCOMMIT_OFF, (int)ODBC32.SQL_IS.UINTEGER);
switch (retcode)
{
case ODBC32.RetCode.SUCCESS:
case ODBC32.RetCode.SUCCESS_WITH_INFO:
_handleState = HandleState.Transacted;
break;
}
}
ODBC.TraceODBC(3, "SQLSetConnectAttrW", retcode);
return retcode;
}
internal ODBC32.RetCode BeginTransaction(ref IsolationLevel isolevel)
{
ODBC32.RetCode retcode = ODBC32.RetCode.SUCCESS;
ODBC32.SQL_ATTR isolationAttribute;
if (IsolationLevel.Unspecified != isolevel)
{
ODBC32.SQL_TRANSACTION sql_iso;
switch (isolevel)
{
case IsolationLevel.ReadUncommitted:
sql_iso = ODBC32.SQL_TRANSACTION.READ_UNCOMMITTED;
isolationAttribute = ODBC32.SQL_ATTR.TXN_ISOLATION;
break;
case IsolationLevel.ReadCommitted:
sql_iso = ODBC32.SQL_TRANSACTION.READ_COMMITTED;
isolationAttribute = ODBC32.SQL_ATTR.TXN_ISOLATION;
break;
case IsolationLevel.RepeatableRead:
sql_iso = ODBC32.SQL_TRANSACTION.REPEATABLE_READ;
isolationAttribute = ODBC32.SQL_ATTR.TXN_ISOLATION;
break;
case IsolationLevel.Serializable:
sql_iso = ODBC32.SQL_TRANSACTION.SERIALIZABLE;
isolationAttribute = ODBC32.SQL_ATTR.TXN_ISOLATION;
break;
case IsolationLevel.Snapshot:
sql_iso = ODBC32.SQL_TRANSACTION.SNAPSHOT;
// VSDD 414121: Snapshot isolation level must be set through SQL_COPT_SS_TXN_ISOLATION (https://docs.microsoft.com/en-us/sql/relational-databases/native-client-odbc-api/sqlsetconnectattr#sqlcoptsstxnisolation)
isolationAttribute = ODBC32.SQL_ATTR.SQL_COPT_SS_TXN_ISOLATION;
break;
case IsolationLevel.Chaos:
throw ODBC.NotSupportedIsolationLevel(isolevel);
default:
throw ADP.InvalidIsolationLevel(isolevel);
}
//Set the isolation level (unless its unspecified)
retcode = SetConnectionAttribute2(isolationAttribute, (IntPtr)sql_iso, (int)ODBC32.SQL_IS.INTEGER);
//Note: The Driver can return success_with_info to indicate it "rolled" the
//isolevel to the next higher value. If this is the case, we need to requery
//the value if th euser asks for it...
//We also still propagate the info, since it could be other info as well...
if (ODBC32.RetCode.SUCCESS_WITH_INFO == retcode)
{
isolevel = IsolationLevel.Unspecified;
}
}
switch (retcode)
{
case ODBC32.RetCode.SUCCESS:
case ODBC32.RetCode.SUCCESS_WITH_INFO:
//Turn off auto-commit (which basically starts the transaction)
retcode = AutoCommitOff();
_handleState = HandleState.TransactionInProgress;
break;
}
return retcode;
}
internal ODBC32.RetCode CompleteTransaction(short transactionOperation)
{
bool mustRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
DangerousAddRef(ref mustRelease);
ODBC32.RetCode retcode = CompleteTransaction(transactionOperation, base.handle);
return retcode;
}
finally
{
if (mustRelease)
{
DangerousRelease();
}
}
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
private ODBC32.RetCode CompleteTransaction(short transactionOperation, IntPtr handle)
{
// must only call this code from ReleaseHandle or DangerousAddRef region
ODBC32.RetCode retcode = ODBC32.RetCode.SUCCESS;
// using ConstrainedRegions to make the native ODBC call and change the _handleState
RuntimeHelpers.PrepareConstrainedRegions();
try { }
finally
{
if (HandleState.TransactionInProgress == _handleState)
{
retcode = Interop.Odbc.SQLEndTran(HandleType, handle, transactionOperation);
if ((ODBC32.RetCode.SUCCESS == retcode) || (ODBC32.RetCode.SUCCESS_WITH_INFO == retcode))
{
_handleState = HandleState.Transacted;
}
}
if (HandleState.Transacted == _handleState)
{ // AutoCommitOn
retcode = Interop.Odbc.SQLSetConnectAttrW(handle, ODBC32.SQL_ATTR.AUTOCOMMIT, ODBC32.SQL_AUTOCOMMIT_ON, (int)ODBC32.SQL_IS.UINTEGER);
_handleState = HandleState.Connected;
}
}
//Overactive assert which fires if handle was allocated - but failed to connect to the server
//it can more legitmately fire if transaction failed to rollback - but there isn't much we can do in that situation
//Debug.Assert((HandleState.Connected == _handleState) || (HandleState.TransactionInProgress == _handleState), "not expected HandleState.Connected");
return retcode;
}
private ODBC32.RetCode Connect(string connectionString)
{
Debug.Assert(HandleState.Allocated == _handleState, "SQLDriverConnect while in wrong state?");
ODBC32.RetCode retcode;
// Avoid runtime injected errors in the following block.
RuntimeHelpers.PrepareConstrainedRegions();
try { }
finally
{
short cbActualSize;
retcode = Interop.Odbc.SQLDriverConnectW(this, ADP.PtrZero, connectionString, ODBC32.SQL_NTS, ADP.PtrZero, 0, out cbActualSize, (short)ODBC32.SQL_DRIVER.NOPROMPT);
switch (retcode)
{
case ODBC32.RetCode.SUCCESS:
case ODBC32.RetCode.SUCCESS_WITH_INFO:
_handleState = HandleState.Connected;
break;
}
}
ODBC.TraceODBC(3, "SQLDriverConnectW", retcode);
return retcode;
}
protected override bool ReleaseHandle()
{
// NOTE: The SafeHandle class guarantees this will be called exactly once and is non-interrutible.
ODBC32.RetCode retcode;
// must call complete the transaction rollback, change handle state, and disconnect the connection
retcode = CompleteTransaction(ODBC32.SQL_ROLLBACK, handle);
if ((HandleState.Connected == _handleState) || (HandleState.TransactionInProgress == _handleState))
{
retcode = Interop.Odbc.SQLDisconnect(handle);
_handleState = HandleState.Allocated;
}
Debug.Assert(HandleState.Allocated == _handleState, "not expected HandleState.Allocated");
return base.ReleaseHandle();
}
internal ODBC32.RetCode GetConnectionAttribute(ODBC32.SQL_ATTR attribute, byte[] buffer, out int cbActual)
{
ODBC32.RetCode retcode = Interop.Odbc.SQLGetConnectAttrW(this, attribute, buffer, buffer.Length, out cbActual);
return retcode;
}
internal ODBC32.RetCode GetFunctions(ODBC32.SQL_API fFunction, out short fExists)
{
ODBC32.RetCode retcode = Interop.Odbc.SQLGetFunctions(this, fFunction, out fExists);
ODBC.TraceODBC(3, "SQLGetFunctions", retcode);
return retcode;
}
internal ODBC32.RetCode GetInfo2(ODBC32.SQL_INFO info, byte[] buffer, out short cbActual)
{
ODBC32.RetCode retcode = Interop.Odbc.SQLGetInfoW(this, info, buffer, checked((short)buffer.Length), out cbActual);
return retcode;
}
internal ODBC32.RetCode GetInfo1(ODBC32.SQL_INFO info, byte[] buffer)
{
ODBC32.RetCode retcode = Interop.Odbc.SQLGetInfoW(this, info, buffer, checked((short)buffer.Length), ADP.PtrZero);
return retcode;
}
internal ODBC32.RetCode SetConnectionAttribute2(ODBC32.SQL_ATTR attribute, IntPtr value, int length)
{
ODBC32.RetCode retcode = Interop.Odbc.SQLSetConnectAttrW(this, attribute, value, length);
ODBC.TraceODBC(3, "SQLSetConnectAttrW", retcode);
return retcode;
}
internal ODBC32.RetCode SetConnectionAttribute3(ODBC32.SQL_ATTR attribute, string buffer, int length)
{
ODBC32.RetCode retcode = Interop.Odbc.SQLSetConnectAttrW(this, attribute, buffer, length);
return retcode;
}
internal ODBC32.RetCode SetConnectionAttribute4(ODBC32.SQL_ATTR attribute, System.Transactions.IDtcTransaction transaction, int length)
{
ODBC32.RetCode retcode = Interop.Odbc.SQLSetConnectAttrW(this, attribute, transaction, length);
ODBC.TraceODBC(3, "SQLSetConnectAttrW", retcode);
return retcode;
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System.Collections;
using System.Diagnostics;
namespace OpenLiveWriter.ApplicationFramework
{
/// <summary>
/// Enumeration of the allowable command context values.
/// </summary>
public enum CommandContext
{
/// <summary>
/// A command that is added to the CommandManager at all times.
/// </summary>
Normal,
/// <summary>
/// A command that is added to the CommandManager when active.
/// </summary>
Activated,
/// <summary>
/// A command that is added to the CommandManager when entered.
/// </summary>
Entered
}
/// <summary>
/// Provides services for managing commands.
/// </summary>
public class CommandContextManager
{
/// <summary>
/// The CommandManager.
/// </summary>
private CommandManager commandManager;
/// <summary>
/// A value which indicates whether this CommandContextManager is "Activated".
/// </summary>
private bool activated = false;
/// <summary>
/// A value which indicates whether this CommandContextManager is "Entered".
/// </summary>
private bool entered = false;
/// <summary>
/// The command context table.
/// </summary>
private Hashtable commandContextTable = new Hashtable();
/// <summary>
/// Collection of commands that are added to the CommandManager at all times.
/// </summary>
private CommandCollection normalCommandCollection = new CommandCollection();
/// <summary>
/// Collection of commands that are added to the CommandManager when the user of this
/// CommandContextManager is "Activated".
/// </summary>
private CommandCollection activatedCommandCollection = new CommandCollection();
/// <summary>
/// Collection of commands that are added to the CommandManager when the user of this
/// CommandContextManager is "Entered".
/// </summary>
private CommandCollection enteredCommandCollection = new CommandCollection();
/// <summary>
/// Initializes a new instance of the CommandContextManager class.
/// </summary>
public CommandContextManager(CommandManager commandManager)
{
this.commandManager = commandManager;
}
/// <summary>
/// Begins update to CommandContextManager allowing multiple change events to be batched.
/// </summary>
public void BeginUpdate()
{
commandManager.BeginUpdate();
}
/// <summary>
/// Ends update to CommandContextManager allowing multiple change events to be batched.
/// </summary>
public void EndUpdate()
{
commandManager.EndUpdate();
}
/// <summary>
/// Closes the CommandContextManager, ensuring that all commands have been removed from
/// the CommandManager.
/// </summary>
public void Close()
{
// Begin the batch update.
BeginUpdate();
// If entered, leave.
if (entered)
Leave();
// If activated, deactivate.
if (activated)
Deactivate();
// Remove normal commands.
commandManager.Remove(normalCommandCollection);
// End the batch update.
EndUpdate();
// Clear our internal tables.
normalCommandCollection.Clear();
activatedCommandCollection.Clear();
enteredCommandCollection.Clear();
commandContextTable.Clear();
}
/// <summary>
/// Adds a command to the CommandContextManager.
/// </summary>
/// <param name="command">The Command to add.</param>
/// <param name="commandContext">The context in which the command is added to the CommandManager.</param>
public void AddCommand(Command command, CommandContext commandContext)
{
// Ensure that the command is not null.
Debug.Assert(command != null, "Command cannot be null");
if (command == null)
return;
// Ensure the the command has not already been added.
if (commandContextTable.Contains(command))
{
Debug.Fail("Command " + command.Identifier + " was already added.");
return;
}
// Handle the command, adding it to the appropriate command collection.
switch (commandContext)
{
// Normal commands.
case CommandContext.Normal:
normalCommandCollection.Add(command);
commandManager.Add(command);
break;
// Activated commands.
case CommandContext.Activated:
activatedCommandCollection.Add(command);
if (activated)
commandManager.Add(command);
break;
// Entered commands.
case CommandContext.Entered:
enteredCommandCollection.Add(command);
if (entered)
commandManager.Add(command);
break;
// Can't happen.
default:
Debug.Fail("Unknown CommandContext");
return;
}
// Add the command to the command context table.
commandContextTable[command] = commandContext;
}
/// <summary>
/// Removes a command from the CommandContextManager.
/// </summary>
/// <param name="command">The Command to remove.</param>
/// <param name="commandContext">The context in which the command is added to the CommandManager.</param>
public void RemoveCommand(Command command)
{
// Ensure that the command is not null.
Debug.Assert(command != null, "Command cannot be null");
if (command == null)
return;
// Ensure the the command has been added.
if (!commandContextTable.Contains(command))
{
Debug.Fail("Command " + command.Identifier + " was not added.");
return;
}
// Handle the command, removing it from the appropriate command collection.
switch ((CommandContext)commandContextTable[command])
{
// Normal commands.
case CommandContext.Normal:
normalCommandCollection.Remove(command);
commandManager.Remove(command);
break;
// Activated commands.
case CommandContext.Activated:
activatedCommandCollection.Remove(command);
if (activated)
commandManager.Remove(command);
break;
// Entered commands.
case CommandContext.Entered:
enteredCommandCollection.Remove(command);
if (entered)
commandManager.Remove(command);
break;
// Can't happen.
default:
Debug.Fail("Unknown CommandContext");
return;
}
// Remove the command from the command context table.
commandContextTable.Remove(command);
}
public bool Activated
{
get
{
return activated;
}
}
/// <summary>
/// Set the "Activated" state of the CommandContextManager.
/// </summary>
public void Activate()
{
Debug.Assert(!activated, "CommandContextManager already activated.");
if (!activated)
{
commandManager.Add(activatedCommandCollection);
activated = true;
}
}
/// <summary>
/// Clears the "Activated" state of the CommandContextManager.
/// </summary>
public void Deactivate()
{
Debug.Assert(activated, "CommandContextManager not activated.");
if (activated)
{
commandManager.Remove(activatedCommandCollection);
activated = false;
}
}
public bool Entered
{
get
{
return entered;
}
}
/// <summary>
/// Set the "Entered" state of the CommandContextManager.
/// </summary>
public void Enter()
{
//Debug.Assert(!entered, "CommandContextManager already entered.");
if (!entered)
{
commandManager.Add(enteredCommandCollection);
entered = true;
}
}
/// <summary>
/// Clears the "Entered" state of the CommandContextManager.
/// </summary>
public void Leave()
{
//Debug.Assert(entered, "CommandContextManager not entered.");
if (entered)
{
commandManager.Remove(enteredCommandCollection);
entered = false;
}
}
}
}
| |
using System;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Data;
namespace MahApps.Metro.Controls
{
/// <summary>
/// A Button that allows the user to toggle between two states.
/// </summary>
[TemplatePart(Name = PART_BackgroundTranslate, Type = typeof(TranslateTransform))]
[TemplatePart(Name = PART_DraggingThumb, Type = typeof(Thumb))]
[TemplatePart(Name = PART_SwitchTrack, Type = typeof(Grid))]
[TemplatePart(Name = PART_ThumbIndicator, Type = typeof(FrameworkElement))]
[TemplatePart(Name = PART_ThumbTranslate, Type = typeof(TranslateTransform))]
public class ToggleSwitchButton : ToggleButton
{
private const string PART_BackgroundTranslate = "PART_BackgroundTranslate";
private const string PART_DraggingThumb = "PART_DraggingThumb";
private const string PART_SwitchTrack = "PART_SwitchTrack";
private const string PART_ThumbIndicator = "PART_ThumbIndicator";
private const string PART_ThumbTranslate = "PART_ThumbTranslate";
private TranslateTransform _BackgroundTranslate;
private Thumb _DraggingThumb;
private Grid _SwitchTrack;
private FrameworkElement _ThumbIndicator;
private TranslateTransform _ThumbTranslate;
private readonly PropertyChangeNotifier isCheckedPropertyChangeNotifier;
[Obsolete(@"This property will be deleted in the next release. You should use OnSwitchBrush and OffSwitchBrush to change the switch's brushes.")]
public static readonly DependencyProperty SwitchForegroundProperty = DependencyProperty.Register("SwitchForeground", typeof(Brush), typeof(ToggleSwitchButton), new PropertyMetadata(null, (o, e) => ((ToggleSwitchButton)o).OnSwitchBrush = e.NewValue as Brush));
public static readonly DependencyProperty OnSwitchBrushProperty = DependencyProperty.Register("OnSwitchBrush", typeof(Brush), typeof(ToggleSwitchButton), null);
public static readonly DependencyProperty OffSwitchBrushProperty = DependencyProperty.Register("OffSwitchBrush", typeof(Brush), typeof(ToggleSwitchButton), null);
public static readonly DependencyProperty ThumbIndicatorBrushProperty = DependencyProperty.Register("ThumbIndicatorBrush", typeof(Brush), typeof(ToggleSwitchButton), null);
public static readonly DependencyProperty ThumbIndicatorDisabledBrushProperty = DependencyProperty.Register("ThumbIndicatorDisabledBrush", typeof(Brush), typeof(ToggleSwitchButton), null);
public static readonly DependencyProperty ThumbIndicatorWidthProperty = DependencyProperty.Register("ThumbIndicatorWidth", typeof(double), typeof(ToggleSwitchButton), new PropertyMetadata(13d));
/// <summary>
/// Gets/sets the brush used for the control's foreground.
/// </summary>
[Obsolete(@"This property will be deleted in the next release. You should use OnSwitchBrush and OffSwitchBrush to change the switch's brushes.")]
public Brush SwitchForeground
{
get { return (Brush)GetValue(SwitchForegroundProperty); }
set { SetValue(SwitchForegroundProperty, value); }
}
/// <summary>
/// Gets/sets the brush used for the on-switch's foreground.
/// </summary>
public Brush OnSwitchBrush
{
get { return (Brush)GetValue(OnSwitchBrushProperty); }
set { SetValue(OnSwitchBrushProperty, value); }
}
/// <summary>
/// Gets/sets the brush used for the off-switch's foreground.
/// </summary>
public Brush OffSwitchBrush
{
get { return (Brush)GetValue(OffSwitchBrushProperty); }
set { SetValue(OffSwitchBrushProperty, value); }
}
/// <summary>
/// Gets/sets the brush used for the thumb indicator.
/// </summary>
public Brush ThumbIndicatorBrush
{
get { return (Brush)GetValue(ThumbIndicatorBrushProperty); }
set { SetValue(ThumbIndicatorBrushProperty, value); }
}
/// <summary>
/// Gets/sets the brush used for the thumb indicator.
/// </summary>
public Brush ThumbIndicatorDisabledBrush
{
get { return (Brush)GetValue(ThumbIndicatorDisabledBrushProperty); }
set { SetValue(ThumbIndicatorDisabledBrushProperty, value); }
}
/// <summary>
/// Gets/sets the width of the thumb indicator.
/// </summary>
public double ThumbIndicatorWidth
{
get { return (double)GetValue(ThumbIndicatorWidthProperty); }
set { SetValue(ThumbIndicatorWidthProperty, value); }
}
static ToggleSwitchButton()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(ToggleSwitchButton), new FrameworkPropertyMetadata(typeof(ToggleSwitchButton)));
}
public ToggleSwitchButton()
{
isCheckedPropertyChangeNotifier = new PropertyChangeNotifier(this, ToggleSwitchButton.IsCheckedProperty);
isCheckedPropertyChangeNotifier.ValueChanged += IsCheckedPropertyChangeNotifierValueChanged;
}
private void IsCheckedPropertyChangeNotifierValueChanged(object sender, EventArgs e)
{
UpdateThumb();
}
DoubleAnimation _thumbAnimation;
private void UpdateThumb()
{
if (_ThumbTranslate != null && _SwitchTrack != null && _ThumbIndicator != null)
{
double destination = IsChecked.GetValueOrDefault() ? ActualWidth - (_SwitchTrack.Margin.Left + _SwitchTrack.Margin.Right + _ThumbIndicator.ActualWidth + _ThumbIndicator.Margin.Left + _ThumbIndicator.Margin.Right) : 0;
_thumbAnimation = new DoubleAnimation();
_thumbAnimation.To = destination;
_thumbAnimation.Duration = TimeSpan.FromMilliseconds(500);
_thumbAnimation.EasingFunction = new ExponentialEase() { Exponent = 9 };
_thumbAnimation.FillBehavior = FillBehavior.Stop;
AnimationTimeline currentAnimation = _thumbAnimation;
_thumbAnimation.Completed += (sender, e) => {
if (_thumbAnimation != null && currentAnimation == _thumbAnimation)
{
_ThumbTranslate.X = destination;
_thumbAnimation = null;
}
};
_ThumbTranslate.BeginAnimation(TranslateTransform.XProperty, _thumbAnimation);
}
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
_BackgroundTranslate = GetTemplateChild(PART_BackgroundTranslate) as TranslateTransform;
_DraggingThumb = GetTemplateChild(PART_DraggingThumb) as Thumb;
_SwitchTrack = GetTemplateChild(PART_SwitchTrack) as Grid;
_ThumbIndicator = GetTemplateChild(PART_ThumbIndicator) as FrameworkElement;
_ThumbTranslate = GetTemplateChild(PART_ThumbTranslate) as TranslateTransform;
if (_ThumbIndicator != null && _ThumbTranslate != null && _BackgroundTranslate != null)
{
Binding translationBinding;
translationBinding = new System.Windows.Data.Binding("X");
translationBinding.Source = _ThumbTranslate;
BindingOperations.SetBinding(_BackgroundTranslate, TranslateTransform.XProperty, translationBinding);
}
if (_DraggingThumb != null && _ThumbIndicator != null && _ThumbTranslate != null)
{
_DraggingThumb.DragStarted -= _DraggingThumb_DragStarted;
_DraggingThumb.DragDelta -= _DraggingThumb_DragDelta;
_DraggingThumb.DragCompleted -= _DraggingThumb_DragCompleted;
_DraggingThumb.DragStarted += _DraggingThumb_DragStarted;
_DraggingThumb.DragDelta += _DraggingThumb_DragDelta;
_DraggingThumb.DragCompleted += _DraggingThumb_DragCompleted;
if (_SwitchTrack != null)
{
_SwitchTrack.SizeChanged -= _SwitchTrack_SizeChanged;
_SwitchTrack.SizeChanged += _SwitchTrack_SizeChanged;
}
}
}
private void SetIsPressed(bool pressed)
{
// we can't use readonly IsPressedProperty
typeof(ToggleButton).GetMethod("set_IsPressed", BindingFlags.Instance | BindingFlags.NonPublic)
.Invoke(this, new object[] { pressed });
}
private double? _lastDragPosition;
private bool _isDragging;
void _DraggingThumb_DragStarted(object sender, DragStartedEventArgs e)
{
if (Mouse.LeftButton == MouseButtonState.Pressed)
{
if (!IsPressed)
{
SetIsPressed(true);
}
}
if (_ThumbTranslate != null)
{
_ThumbTranslate.BeginAnimation(TranslateTransform.XProperty, null);
double destination = IsChecked.GetValueOrDefault() ? ActualWidth - (_SwitchTrack.Margin.Left + _SwitchTrack.Margin.Right + _ThumbIndicator.ActualWidth + _ThumbIndicator.Margin.Left + _ThumbIndicator.Margin.Right) : 0;
_ThumbTranslate.X = destination;
_thumbAnimation = null;
}
_lastDragPosition = _ThumbTranslate.X;
_isDragging = false;
}
void _DraggingThumb_DragDelta(object sender, DragDeltaEventArgs e)
{
if (_lastDragPosition.HasValue)
{
if (Math.Abs(e.HorizontalChange) > 3)
_isDragging = true;
if (_SwitchTrack != null && _ThumbIndicator != null)
{
double lastDragPosition = _lastDragPosition.Value;
_ThumbTranslate.X = Math.Min(ActualWidth - (_SwitchTrack.Margin.Left + _SwitchTrack.Margin.Right + _ThumbIndicator.ActualWidth + _ThumbIndicator.Margin.Left + _ThumbIndicator.Margin.Right), Math.Max(0, lastDragPosition + e.HorizontalChange));
}
}
}
void _DraggingThumb_DragCompleted(object sender, DragCompletedEventArgs e)
{
SetIsPressed(false);
_lastDragPosition = null;
if (!_isDragging)
{
OnClick();
}
else if (_ThumbTranslate != null && _SwitchTrack != null)
{
if (!IsChecked.GetValueOrDefault() && _ThumbTranslate.X + 6.5 >= _SwitchTrack.ActualWidth / 2)
{
OnClick();
}
else if (IsChecked.GetValueOrDefault() && _ThumbTranslate.X + 6.5 <= _SwitchTrack.ActualWidth / 2)
{
OnClick();
}
else
{
UpdateThumb();
}
}
}
void _SwitchTrack_SizeChanged(object sender, SizeChangedEventArgs e)
{
if (_ThumbTranslate != null && _SwitchTrack != null && _ThumbIndicator != null)
{
double destination = IsChecked.GetValueOrDefault() ? ActualWidth - (_SwitchTrack.Margin.Left + _SwitchTrack.Margin.Right + _ThumbIndicator.ActualWidth + _ThumbIndicator.Margin.Left + _ThumbIndicator.Margin.Right) : 0;
_ThumbTranslate.X = destination;
}
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[System.Serializable]
[AddComponentMenu("NGUI/NData/PopupList Binding")]
public class NguiPopupListSourceBinding : NguiItemsSourceBinding
{
/*
private UIPopupList _uiPopupList = null;
public override void Awake()
{
base.Awake();
_uiPopupList = GetComponent<UIPopupList>();
if (_uiPopupList != null)
{
_uiPopupList.onChange.Add(new EventDelegate(OnSelectionChange));
}
}
protected override void Bind()
{
base.Bind();
if (_uiPopupList == null)
return;
OnItemsClear();
if (_collection == null)
return;
for (var i = 0; i < _collection.ItemsCount; ++i)
{
_uiPopupList.items.Add(GetItemDisplayValue(i));
}
_uiPopupList.value = GetItemDisplayValue(_collection.SelectedIndex);
}
protected override void OnItemInsert(int position, EZData.Context item)
{
base.OnItemInsert(position, item);
_uiPopupList.items.Insert(position, GetDisplayValueProperty(item).GetValue());
_uiPopupList.value = GetItemDisplayValue(_collection.SelectedIndex);
}
protected override void OnItemRemove(int position)
{
if (_collection == null || _uiPopupList == null)
return;
_displayValuesCache.Remove(_collection.GetBaseItem(position));
base.OnItemRemove(position);
_uiPopupList.items.RemoveAt(position);
if (_uiPopupList.items.Count == 0)
_uiPopupList.value = string.Empty;
else
_uiPopupList.value = GetItemDisplayValue(_collection.SelectedIndex);
}
protected override void OnItemsClear()
{
_displayValuesCache.Clear();
_uiPopupList.items.Clear();
_uiPopupList.value = string.Empty;
}
private EZData.Property<string> GetDisplayValueProperty(EZData.Context item)
{
if (item == null)
return null;
EZData.Property<string> property = null;
if (_displayValuesCache.TryGetValue(item, out property))
return property;
property = item.FindProperty<string>(DisplayValuePath, this);
if (property != null)
_displayValuesCache.Add(item, property);
return property;
}
private string GetItemDisplayValue(int index)
{
if (_collection == null)
return string.Empty;
var property = GetDisplayValueProperty(_collection.GetBaseItem(index));
if (property == null)
return string.Empty;
return property.GetValue();
}
public void OnSelectionChange()
{
var selectedItem = _uiPopupList.value;
if (_collection != null && !_isCollectionSelecting)
{
_isCollectionSelecting = true;
for (var i = 0; i < _collection.ItemsCount; ++i)
{
if (GetItemDisplayValue(i) == selectedItem)
{
_collection.SelectItem(i);
break;
}
}
_isCollectionSelecting = false;
}
}
protected override void OnCollectionSelectionChange()
{
if (_uiPopupList == null || _collection == null)
return;
var selectedValue = GetItemDisplayValue(_collection.SelectedIndex);
_uiPopupList.value = selectedValue;
}
*/
public string DisplayValuePath;
private readonly Dictionary<EZData.Context, EZData.Property<string>> _displayValuesCache = new Dictionary<EZData.Context, EZData.Property<string>>();
private UIPopupList _uiPopupList = null;
#if NGUI_2
private GameObject _nativeEventReceiver;
private string _nativeFunctionName;
#endif
private void AssignValue(string value)
{
#if NGUI_2
_uiPopupList.selection = value;
#else
_uiPopupList.value = value;
#endif
}
public override void Awake()
{
base.Awake();
_uiPopupList = GetComponent<UIPopupList>();
if (_uiPopupList != null)
{
#if NGUI_2
_nativeEventReceiver = _uiPopupList.eventReceiver;
_nativeFunctionName = _uiPopupList.functionName;
_uiPopupList.eventReceiver = gameObject;
_uiPopupList.functionName = "OnSelectionChange";
#else
_uiPopupList.onChange.Add(new EventDelegate(OnSelectionChange));
#endif
}
}
protected override void Bind()
{
base.Bind();
if (_uiPopupList == null)
return;
OnItemsClear();
if (_collection == null)
return;
for (var i = 0; i < _collection.ItemsCount; ++i)
{
_uiPopupList.items.Add(GetItemDisplayValue(i));
}
AssignValue(GetItemDisplayValue(_collection.SelectedIndex));
}
protected override void OnItemInsert(int position, EZData.Context item)
{
base.OnItemInsert(position, item);
_uiPopupList.items.Insert(position, GetDisplayValueProperty(item).GetValue());
AssignValue(GetItemDisplayValue(_collection.SelectedIndex));
}
protected override void OnItemRemove(int position)
{
if (_collection == null || _uiPopupList == null)
return;
_displayValuesCache.Remove(_collection.GetBaseItem(position));
base.OnItemRemove(position);
_uiPopupList.items.RemoveAt(position);
if (_uiPopupList.items.Count == 0)
AssignValue(string.Empty);
else
AssignValue(GetItemDisplayValue(_collection.SelectedIndex));
}
protected override void OnItemsClear()
{
_displayValuesCache.Clear();
_uiPopupList.items.Clear();
AssignValue(string.Empty);
}
private EZData.Property<string> GetDisplayValueProperty(EZData.Context item)
{
if (item == null)
return null;
EZData.Property<string> property = null;
if (_displayValuesCache.TryGetValue(item, out property))
return property;
property = item.FindProperty<string>(DisplayValuePath, this);
if (property != null)
_displayValuesCache.Add(item, property);
return property;
}
private string GetItemDisplayValue(int index)
{
if (_collection == null)
return string.Empty;
var property = GetDisplayValueProperty(_collection.GetBaseItem(index));
if (property == null)
return string.Empty;
return property.GetValue();
}
#if !NGUI_2
public void OnSelectionChange()
{
OnSelectionChange(_uiPopupList.value);
}
#endif
public void OnSelectionChange(string selectedItem)
{
if (_collection != null && !_isCollectionSelecting)
{
_isCollectionSelecting = true;
for (var i = 0; i < _collection.ItemsCount; ++i)
{
if (GetItemDisplayValue(i) == selectedItem)
{
_collection.SelectItem(i);
break;
}
}
_isCollectionSelecting = false;
}
#if NGUI_2
if (_nativeEventReceiver != null)
{
if (_nativeEventReceiver != gameObject || _nativeFunctionName != "OnSelectionChange")
{
_nativeEventReceiver.SendMessage(_nativeFunctionName, selectedItem, SendMessageOptions.DontRequireReceiver);
}
}
#endif
}
protected override void OnCollectionSelectionChange()
{
if (_uiPopupList == null || _collection == null)
return;
var selectedValue = GetItemDisplayValue(_collection.SelectedIndex);
AssignValue(selectedValue);
}
}
| |
using System;
namespace Godot
{
public struct Color : IEquatable<Color>
{
public float r;
public float g;
public float b;
public float a;
public int r8
{
get
{
return (int)(r * 255.0f);
}
}
public int g8
{
get
{
return (int)(g * 255.0f);
}
}
public int b8
{
get
{
return (int)(b * 255.0f);
}
}
public int a8
{
get
{
return (int)(a * 255.0f);
}
}
public float h
{
get
{
float max = Mathf.max(r, Mathf.max(g, b));
float min = Mathf.min(r, Mathf.min(g, b));
float delta = max - min;
if (delta == 0)
return 0;
float h;
if (r == max)
h = (g - b) / delta; // Between yellow & magenta
else if (g == max)
h = 2 + (b - r) / delta; // Between cyan & yellow
else
h = 4 + (r - g) / delta; // Between magenta & cyan
h /= 6.0f;
if (h < 0)
h += 1.0f;
return h;
}
set
{
this = from_hsv(value, s, v);
}
}
public float s
{
get
{
float max = Mathf.max(r, Mathf.max(g, b));
float min = Mathf.min(r, Mathf.min(g, b));
float delta = max - min;
return max != 0 ? delta / max : 0;
}
set
{
this = from_hsv(h, value, v);
}
}
public float v
{
get
{
return Mathf.max(r, Mathf.max(g, b));
}
set
{
this = from_hsv(h, s, value);
}
}
private static readonly Color black = new Color(0f, 0f, 0f, 1.0f);
public Color Black
{
get
{
return black;
}
}
public float this [int index]
{
get
{
switch (index)
{
case 0:
return r;
case 1:
return g;
case 2:
return b;
case 3:
return a;
default:
throw new IndexOutOfRangeException();
}
}
set
{
switch (index)
{
case 0:
r = value;
return;
case 1:
g = value;
return;
case 2:
b = value;
return;
case 3:
a = value;
return;
default:
throw new IndexOutOfRangeException();
}
}
}
public static void to_hsv(Color color, out float hue, out float saturation, out float value)
{
int max = Mathf.max(color.r8, Mathf.max(color.g8, color.b8));
int min = Mathf.min(color.r8, Mathf.min(color.g8, color.b8));
float delta = max - min;
if (delta == 0)
{
hue = 0;
}
else
{
if (color.r == max)
hue = (color.g - color.b) / delta; // Between yellow & magenta
else if (color.g == max)
hue = 2 + (color.b - color.r) / delta; // Between cyan & yellow
else
hue = 4 + (color.r - color.g) / delta; // Between magenta & cyan
hue /= 6.0f;
if (hue < 0)
hue += 1.0f;
}
saturation = (max == 0) ? 0 : 1f - (1f * min / max);
value = max / 255f;
}
public static Color from_hsv(float hue, float saturation, float value, float alpha = 1.0f)
{
if (saturation == 0)
{
// acp_hromatic (grey)
return new Color(value, value, value, alpha);
}
int i;
float f, p, q, t;
hue *= 6.0f;
hue %= 6f;
i = (int)hue;
f = hue - i;
p = value * (1 - saturation);
q = value * (1 - saturation * f);
t = value * (1 - saturation * (1 - f));
switch (i)
{
case 0: // Red is the dominant color
return new Color(value, t, p, alpha);
case 1: // Green is the dominant color
return new Color(q, value, p, alpha);
case 2:
return new Color(p, value, t, alpha);
case 3: // Blue is the dominant color
return new Color(p, q, value, alpha);
case 4:
return new Color(t, p, value, alpha);
default: // (5) Red is the dominant color
return new Color(value, p, q, alpha);
}
}
public Color blend(Color over)
{
Color res;
float sa = 1.0f - over.a;
res.a = a * sa + over.a;
if (res.a == 0)
{
return new Color(0, 0, 0, 0);
}
else
{
res.r = (r * a * sa + over.r * over.a) / res.a;
res.g = (g * a * sa + over.g * over.a) / res.a;
res.b = (b * a * sa + over.b * over.a) / res.a;
}
return res;
}
public Color contrasted()
{
return new Color(
(r + 0.5f) % 1.0f,
(g + 0.5f) % 1.0f,
(b + 0.5f) % 1.0f
);
}
public float gray()
{
return (r + g + b) / 3.0f;
}
public Color inverted()
{
return new Color(
1.0f - r,
1.0f - g,
1.0f - b
);
}
public Color linear_interpolate(Color b, float t)
{
Color res = this;
res.r += (t * (b.r - this.r));
res.g += (t * (b.g - this.g));
res.b += (t * (b.b - this.b));
res.a += (t * (b.a - this.a));
return res;
}
public int to_32()
{
int c = (byte)(a * 255);
c <<= 8;
c |= (byte)(r * 255);
c <<= 8;
c |= (byte)(g * 255);
c <<= 8;
c |= (byte)(b * 255);
return c;
}
public int to_ARGB32()
{
int c = (byte)(a * 255);
c <<= 8;
c |= (byte)(r * 255);
c <<= 8;
c |= (byte)(g * 255);
c <<= 8;
c |= (byte)(b * 255);
return c;
}
public string to_html(bool include_alpha = true)
{
String txt = string.Empty;
txt += _to_hex(r);
txt += _to_hex(g);
txt += _to_hex(b);
if (include_alpha)
txt = _to_hex(a) + txt;
return txt;
}
public Color(float r, float g, float b, float a = 1.0f)
{
this.r = r;
this.g = g;
this.b = b;
this.a = a;
}
public Color(int rgba)
{
this.a = (rgba & 0xFF) / 255.0f;
rgba >>= 8;
this.b = (rgba & 0xFF) / 255.0f;
rgba >>= 8;
this.g = (rgba & 0xFF) / 255.0f;
rgba >>= 8;
this.r = (rgba & 0xFF) / 255.0f;
}
private static float _parse_col(string str, int ofs)
{
int ig = 0;
for (int i = 0; i < 2; i++)
{
int c = str[i + ofs];
int v = 0;
if (c >= '0' && c <= '9')
{
v = c - '0';
}
else if (c >= 'a' && c <= 'f')
{
v = c - 'a';
v += 10;
}
else if (c >= 'A' && c <= 'F')
{
v = c - 'A';
v += 10;
}
else
{
return -1;
}
if (i == 0)
ig += v * 16;
else
ig += v;
}
return ig;
}
private String _to_hex(float val)
{
int v = (int)Mathf.clamp(val * 255.0f, 0, 255);
string ret = string.Empty;
for (int i = 0; i < 2; i++)
{
char[] c = { (char)0, (char)0 };
int lv = v & 0xF;
if (lv < 10)
c[0] = (char)('0' + lv);
else
c[0] = (char)('a' + lv - 10);
v >>= 4;
ret = c + ret;
}
return ret;
}
internal static bool html_is_valid(string color)
{
if (color.Length == 0)
return false;
if (color[0] == '#')
color = color.Substring(1, color.Length - 1);
bool alpha = false;
if (color.Length == 8)
alpha = true;
else if (color.Length == 6)
alpha = false;
else
return false;
if (alpha)
{
if ((int)_parse_col(color, 0) < 0)
return false;
}
int from = alpha ? 2 : 0;
if ((int)_parse_col(color, from + 0) < 0)
return false;
if ((int)_parse_col(color, from + 2) < 0)
return false;
if ((int)_parse_col(color, from + 4) < 0)
return false;
return true;
}
public static Color Color8(byte r8, byte g8, byte b8, byte a8)
{
return new Color((float)r8 / 255f, (float)g8 / 255f, (float)b8 / 255f, (float)a8 / 255f);
}
public Color(string rgba)
{
if (rgba.Length == 0)
{
r = 0f;
g = 0f;
b = 0f;
a = 1.0f;
return;
}
if (rgba[0] == '#')
rgba = rgba.Substring(1);
bool alpha = false;
if (rgba.Length == 8)
{
alpha = true;
}
else if (rgba.Length == 6)
{
alpha = false;
}
else
{
throw new ArgumentOutOfRangeException("Invalid color code. Length is " + rgba.Length + " but a length of 6 or 8 is expected: " + rgba);
}
if (alpha)
{
a = _parse_col(rgba, 0);
if (a < 0)
throw new ArgumentOutOfRangeException("Invalid color code. Alpha is " + a + " but zero or greater is expected: " + rgba);
}
else
{
a = 1.0f;
}
int from = alpha ? 2 : 0;
r = _parse_col(rgba, from + 0);
if (r < 0)
throw new ArgumentOutOfRangeException("Invalid color code. Red is " + r + " but zero or greater is expected: " + rgba);
g = _parse_col(rgba, from + 2);
if (g < 0)
throw new ArgumentOutOfRangeException("Invalid color code. Green is " + g + " but zero or greater is expected: " + rgba);
b = _parse_col(rgba, from + 4);
if (b < 0)
throw new ArgumentOutOfRangeException("Invalid color code. Blue is " + b + " but zero or greater is expected: " + rgba);
}
public static bool operator ==(Color left, Color right)
{
return left.Equals(right);
}
public static bool operator !=(Color left, Color right)
{
return !left.Equals(right);
}
public static bool operator <(Color left, Color right)
{
if (left.r == right.r)
{
if (left.g == right.g)
{
if (left.b == right.b)
return (left.a < right.a);
else
return (left.b < right.b);
}
else
{
return left.g < right.g;
}
}
return left.r < right.r;
}
public static bool operator >(Color left, Color right)
{
if (left.r == right.r)
{
if (left.g == right.g)
{
if (left.b == right.b)
return (left.a > right.a);
else
return (left.b > right.b);
}
else
{
return left.g > right.g;
}
}
return left.r > right.r;
}
public override bool Equals(object obj)
{
if (obj is Color)
{
return Equals((Color)obj);
}
return false;
}
public bool Equals(Color other)
{
return r == other.r && g == other.g && b == other.b && a == other.a;
}
public override int GetHashCode()
{
return r.GetHashCode() ^ g.GetHashCode() ^ b.GetHashCode() ^ a.GetHashCode();
}
public override string ToString()
{
return String.Format("{0},{1},{2},{3}", new object[]
{
this.r.ToString(),
this.g.ToString(),
this.b.ToString(),
this.a.ToString()
});
}
public string ToString(string format)
{
return String.Format("{0},{1},{2},{3}", new object[]
{
this.r.ToString(format),
this.g.ToString(format),
this.b.ToString(format),
this.a.ToString(format)
});
}
}
}
| |
using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class FAtlasElement
{
public string name;
public int indexInAtlas;
public FAtlas atlas;
public int atlasIndex;
public Rect uvRect;
public Vector2 uvTopLeft;
public Vector2 uvTopRight;
public Vector2 uvBottomRight;
public Vector2 uvBottomLeft;
public Rect sourceRect;
public Vector2 sourceSize;
public Vector2 sourcePixelSize;
public bool isTrimmed;
//public bool isRotated;
public FAtlasElement Clone()
{
FAtlasElement element = new FAtlasElement();
element.name = name;
element.indexInAtlas = indexInAtlas;
element.atlas = atlas;
element.atlasIndex = atlasIndex;
element.uvRect = uvRect;
element.uvTopLeft = uvTopLeft;
element.uvTopRight = uvTopRight;
element.uvBottomRight = uvBottomRight;
element.uvBottomLeft = uvBottomLeft;
element.sourceRect = sourceRect;
element.sourceSize = sourceSize;
element.isTrimmed = isTrimmed;
return element;
}
}
public class FAtlas
{
private string _name;
private string _imagePath;
private string _dataPath;
private int _index;
private List<FAtlasElement> _elements = new List<FAtlasElement>();
private Dictionary<string, FAtlasElement> _elementsByName = new Dictionary<string, FAtlasElement>();
private Texture _texture;
private Vector2 _textureSize;
private bool _isSingleImage;
private bool _isTextureAnAsset = false;
//TODO: allow users to pass a dictionary of pre-built atlas data if they want
public FAtlas (string name, Texture texture, int index) //single image
{
_name = name;
_imagePath = "";
_dataPath = "";
_index = index;
_texture = texture;
_textureSize = new Vector2(_texture.width,_texture.height);
CreateAtlasFromSingleImage();
}
public FAtlas (string name, string dataPath, Texture texture, int index) //atlas with data path
{
_name = name;
_imagePath = "";
_dataPath = dataPath;
_index = index;
_texture = texture;
_textureSize = new Vector2(_texture.width,_texture.height);
_isSingleImage = false;
LoadAtlasData();
}
public FAtlas (string name, string imagePath, string dataPath, int index, bool shouldLoadAsSingleImage)
{
_name = name;
_imagePath = imagePath;
_dataPath = dataPath;
_index = index;
LoadTexture();
if(shouldLoadAsSingleImage)
{
_isSingleImage = true;
CreateAtlasFromSingleImage();
}
else
{
_isSingleImage = false;
LoadAtlasData();
}
}
private void LoadTexture()
{
_texture = Resources.Load (_imagePath, typeof(Texture)) as Texture;
if(_texture == null)
{
throw new FutileException("Couldn't load the atlas texture from: " + _imagePath);
}
_isTextureAnAsset = true;
_textureSize = new Vector2(_texture.width,_texture.height);
}
private void LoadAtlasData()
{
TextAsset dataAsset = Resources.Load (_dataPath, typeof(TextAsset)) as TextAsset;
if(dataAsset == null)
{
throw new FutileException("Couldn't load the atlas data from: " + _dataPath);
}
Dictionary<string,object> dict = dataAsset.text.dictionaryFromJson();
if(dict == null)
{
throw new FutileException("The atlas at " + _dataPath + " was not a proper JSON file. Make sure to select \"Unity3D\" in TexturePacker.");
}
Dictionary<string,object> frames = (Dictionary<string,object>) dict["frames"];
float scaleInverse = Futile.resourceScaleInverse;
int index = 0;
foreach(KeyValuePair<string,object> item in frames)
{
FAtlasElement element = new FAtlasElement();
element.indexInAtlas = index++;
string name = (string) item.Key;
if(Futile.shouldRemoveAtlasElementFileExtensions)
{
int extensionPosition = name.LastIndexOf(".");
if (extensionPosition >= 0) name = name.Substring(0, extensionPosition);
}
element.name = name;
IDictionary itemDict = (IDictionary)item.Value;
element.isTrimmed = (bool)itemDict["trimmed"];
if((bool)itemDict["rotated"])
{
throw new NotSupportedException("Futile no longer supports TexturePacker's \"rotated\" flag. Please disable it when creating the "+_dataPath+" atlas.");
}
//the uv coordinate rectangle within the atlas
IDictionary frame = (IDictionary)itemDict["frame"];
float frameX = float.Parse(frame["x"].ToString());
float frameY = float.Parse(frame["y"].ToString());
float frameW = float.Parse(frame["w"].ToString());
float frameH = float.Parse(frame["h"].ToString());
Rect uvRect = new Rect
(
frameX/_textureSize.x,
((_textureSize.y - frameY - frameH)/_textureSize.y),
frameW/_textureSize.x,
frameH/_textureSize.y
);
element.uvRect = uvRect;
element.uvTopLeft.Set(uvRect.xMin,uvRect.yMax);
element.uvTopRight.Set(uvRect.xMax,uvRect.yMax);
element.uvBottomRight.Set(uvRect.xMax,uvRect.yMin);
element.uvBottomLeft.Set(uvRect.xMin,uvRect.yMin);
//the source size is the untrimmed size
IDictionary sourcePixelSize = (IDictionary)itemDict["sourceSize"];
element.sourcePixelSize.x = float.Parse(sourcePixelSize["w"].ToString());
element.sourcePixelSize.y = float.Parse(sourcePixelSize["h"].ToString());
element.sourceSize.x = element.sourcePixelSize.x * scaleInverse;
element.sourceSize.y = element.sourcePixelSize.y * scaleInverse;
//this rect is the trimmed size and position relative to the untrimmed rect
IDictionary sourceRect = (IDictionary)itemDict["spriteSourceSize"];
float rectX = float.Parse(sourceRect["x"].ToString()) * scaleInverse;
float rectY = float.Parse(sourceRect["y"].ToString()) * scaleInverse;
float rectW = float.Parse(sourceRect["w"].ToString()) * scaleInverse;
float rectH = float.Parse(sourceRect["h"].ToString()) * scaleInverse;
element.sourceRect = new Rect(rectX,rectY,rectW,rectH);
_elements.Add (element);
_elementsByName.Add(element.name, element);
}
Resources.UnloadAsset(dataAsset);
}
private void CreateAtlasFromSingleImage()
{
FAtlasElement element = new FAtlasElement();
element.name = _name;
element.indexInAtlas = 0;
//TODO: may have to offset the rect slightly
float scaleInverse = Futile.resourceScaleInverse;
Rect uvRect = new Rect(0.0f,0.0f,1.0f,1.0f);
element.uvRect = uvRect;
element.uvTopLeft.Set(uvRect.xMin,uvRect.yMax);
element.uvTopRight.Set(uvRect.xMax,uvRect.yMax);
element.uvBottomRight.Set(uvRect.xMax,uvRect.yMin);
element.uvBottomLeft.Set(uvRect.xMin,uvRect.yMin);
element.sourceSize = new Vector2(_textureSize.x*scaleInverse,_textureSize.y*scaleInverse);
element.sourcePixelSize = new Vector2(_textureSize.x,_textureSize.y);
element.sourceRect = new Rect(0,0,_textureSize.x*scaleInverse,_textureSize.y*scaleInverse);
element.isTrimmed = false;
_elements.Add (element);
_elementsByName.Add (element.name, element);
}
public void Unload ()
{
if(_isTextureAnAsset)
{
Resources.UnloadAsset(_texture);
}
}
public List<FAtlasElement> elements
{
get {return _elements;}
}
public int index
{
get {return _index;}
}
public Texture texture
{
get {return _texture;}
}
public Vector2 textureSize
{
get {return _textureSize;}
}
public string name
{
get {return _name;}
}
public string imagePath
{
get {return _imagePath;}
}
public string dataPath
{
get {return _dataPath;}
}
public bool isSingleImage
{
get {return _isSingleImage;}
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// 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 DiscUtils.Internal;
using DiscUtils.Streams;
namespace DiscUtils.Vmdk
{
/// <summary>
/// Represents a single VMDK file.
/// </summary>
public sealed class DiskImageFile : VirtualDiskLayer
{
private static readonly Random _rng = new Random();
private readonly FileAccess _access;
private SparseStream _contentStream;
private DescriptorFile _descriptor;
private readonly FileLocator _fileLocator;
/// <summary>
/// The stream containing the VMDK disk, if this is a monolithic disk.
/// </summary>
private Stream _monolithicStream;
/// <summary>
/// Indicates if this instance controls lifetime of _monolithicStream.
/// </summary>
private readonly Ownership _ownsMonolithicStream;
/// <summary>
/// Initializes a new instance of the DiskImageFile class.
/// </summary>
/// <param name="path">The path to the disk.</param>
/// <param name="access">The desired access to the disk.</param>
public DiskImageFile(string path, FileAccess access)
{
_access = access;
FileAccess fileAccess = FileAccess.Read;
FileShare fileShare = FileShare.Read;
if (_access != FileAccess.Read)
{
fileAccess = FileAccess.ReadWrite;
fileShare = FileShare.None;
}
Stream fileStream = null;
_fileLocator = new LocalFileLocator(Path.GetDirectoryName(path));
try
{
fileStream = _fileLocator.Open(Path.GetFileName(path), FileMode.Open, fileAccess, fileShare);
LoadDescriptor(fileStream);
// For monolithic disks, keep hold of the stream - we won't try to use the file name
// from the embedded descriptor because the file may have been renamed, making the
// descriptor out of date.
if (_descriptor.CreateType == DiskCreateType.StreamOptimized ||
_descriptor.CreateType == DiskCreateType.MonolithicSparse)
{
_monolithicStream = fileStream;
_ownsMonolithicStream = Ownership.Dispose;
fileStream = null;
}
}
finally
{
if (fileStream != null)
{
fileStream.Dispose();
}
}
}
/// <summary>
/// Initializes a new instance of the DiskImageFile class.
/// </summary>
/// <param name="stream">The stream containing a monolithic disk.</param>
/// <param name="ownsStream">Indicates if the created instance should own the stream.</param>
public DiskImageFile(Stream stream, Ownership ownsStream)
{
_access = stream.CanWrite ? FileAccess.ReadWrite : FileAccess.Read;
LoadDescriptor(stream);
bool createTypeIsSparse =
_descriptor.CreateType == DiskCreateType.MonolithicSparse
|| _descriptor.CreateType == DiskCreateType.StreamOptimized;
if (!createTypeIsSparse || _descriptor.Extents.Count != 1
|| _descriptor.Extents[0].Type != ExtentType.Sparse || _descriptor.ParentContentId != uint.MaxValue)
{
throw new ArgumentException(
"Only Monolithic Sparse and Streaming Optimized disks can be accessed via a stream", nameof(stream));
}
_monolithicStream = stream;
_ownsMonolithicStream = ownsStream;
}
/// <summary>
/// Initializes a new instance of the DiskImageFile class.
/// </summary>
/// <param name="fileLocator">An object to open the file and any extents.</param>
/// <param name="file">The file name.</param>
/// <param name="access">The type of access desired.</param>
internal DiskImageFile(FileLocator fileLocator, string file, FileAccess access)
{
_access = access;
FileAccess fileAccess = FileAccess.Read;
FileShare fileShare = FileShare.Read;
if (_access != FileAccess.Read)
{
fileAccess = FileAccess.ReadWrite;
fileShare = FileShare.None;
}
Stream fileStream = null;
try
{
fileStream = fileLocator.Open(file, FileMode.Open, fileAccess, fileShare);
LoadDescriptor(fileStream);
// For monolithic disks, keep hold of the stream - we won't try to use the file name
// from the embedded descriptor because the file may have been renamed, making the
// descriptor out of date.
if (_descriptor.CreateType == DiskCreateType.StreamOptimized ||
_descriptor.CreateType == DiskCreateType.MonolithicSparse)
{
_monolithicStream = fileStream;
_ownsMonolithicStream = Ownership.Dispose;
fileStream = null;
}
}
finally
{
if (fileStream != null)
{
fileStream.Dispose();
}
}
_fileLocator = fileLocator.GetRelativeLocator(fileLocator.GetDirectoryFromPath(file));
}
/// <summary>
/// Gets the IDE/SCSI adapter type of the disk.
/// </summary>
internal DiskAdapterType AdapterType
{
get { return _descriptor.AdapterType; }
}
/// <summary>
/// Gets the BIOS geometry of this disk.
/// </summary>
internal Geometry BiosGeometry
{
get { return _descriptor.BiosGeometry; }
}
/// <summary>
/// Gets the capacity of this disk (in bytes).
/// </summary>
internal override long Capacity
{
get
{
long result = 0;
foreach (ExtentDescriptor extent in _descriptor.Extents)
{
result += extent.SizeInSectors * Sizes.Sector;
}
return result;
}
}
internal uint ContentId
{
get { return _descriptor.ContentId; }
}
/// <summary>
/// Gets the 'CreateType' of this disk.
/// </summary>
internal DiskCreateType CreateType
{
get { return _descriptor.CreateType; }
}
/// <summary>
/// Gets the relative paths to all of the disk's extents.
/// </summary>
public IEnumerable<string> ExtentPaths
{
get
{
foreach (ExtentDescriptor path in _descriptor.Extents)
{
yield return path.FileName;
}
}
}
/// <summary>
/// Gets the extents that comprise this file.
/// </summary>
public override IList<VirtualDiskExtent> Extents
{
get
{
List<VirtualDiskExtent> extents = new List<VirtualDiskExtent>(_descriptor.Extents.Count);
if (_monolithicStream != null)
{
extents.Add(new DiskExtent(_descriptor.Extents[0], 0, _monolithicStream));
}
else
{
long pos = 0;
foreach (ExtentDescriptor record in _descriptor.Extents)
{
extents.Add(new DiskExtent(record, pos, _fileLocator, _access));
pos += record.SizeInSectors * Sizes.Sector;
}
}
return extents;
}
}
/// <summary>
/// Gets the Geometry of this disk.
/// </summary>
public override Geometry Geometry
{
get { return _descriptor.DiskGeometry; }
}
/// <summary>
/// Gets an indication as to whether the disk file is sparse.
/// </summary>
public override bool IsSparse
{
get
{
return _descriptor.CreateType == DiskCreateType.MonolithicSparse
|| _descriptor.CreateType == DiskCreateType.TwoGbMaxExtentSparse
|| _descriptor.CreateType == DiskCreateType.VmfsSparse;
}
}
/// <summary>
/// Gets a value indicating whether this disk is a linked differencing disk.
/// </summary>
public override bool NeedsParent
{
get { return _descriptor.ParentContentId != uint.MaxValue; }
}
/// <summary>
/// Gets a <c>FileLocator</c> that can resolve relative paths, or <c>null</c>.
/// </summary>
/// <remarks>
/// Typically used to locate parent disks.
/// </remarks>
internal override FileLocator RelativeFileLocator
{
get { return _fileLocator; }
}
/// <summary>
/// Creates a new virtual disk at the specified path.
/// </summary>
/// <param name="path">The name of the VMDK to create.</param>
/// <param name="parameters">The desired parameters for the new disk.</param>
/// <returns>The newly created disk image.</returns>
public static DiskImageFile Initialize(string path, DiskParameters parameters)
{
FileLocator locator = new LocalFileLocator(Path.GetDirectoryName(path));
return Initialize(locator, Path.GetFileName(path), parameters);
}
/// <summary>
/// Creates a new virtual disk at the specified path.
/// </summary>
/// <param name="fileSystem">The file system to create the disk on.</param>
/// <param name="path">The name of the VMDK to create.</param>
/// <param name="parameters">The desired parameters for the new disk.</param>
/// <returns>The newly created disk image.</returns>
public static DiskImageFile Initialize(DiscFileSystem fileSystem, string path, DiskParameters parameters)
{
FileLocator locator = new DiscFileLocator(fileSystem, Utilities.GetDirectoryFromPath(path));
return Initialize(locator, Utilities.GetFileFromPath(path), parameters);
}
/// <summary>
/// Creates a new virtual disk at the specified path.
/// </summary>
/// <param name="path">The name of the VMDK to create.</param>
/// <param name="capacity">The desired capacity of the new disk.</param>
/// <param name="type">The type of virtual disk to create.</param>
/// <returns>The newly created disk image.</returns>
public static DiskImageFile Initialize(string path, long capacity, DiskCreateType type)
{
DiskParameters diskParams = new DiskParameters();
diskParams.Capacity = capacity;
diskParams.CreateType = type;
return Initialize(path, diskParams);
}
/// <summary>
/// Creates a new virtual disk at the specified path.
/// </summary>
/// <param name="path">The name of the VMDK to create.</param>
/// <param name="capacity">The desired capacity of the new disk.</param>
/// <param name="geometry">The desired geometry of the new disk, or <c>null</c> for default.</param>
/// <param name="createType">The type of virtual disk to create.</param>
/// <returns>The newly created disk image.</returns>
public static DiskImageFile Initialize(string path, long capacity, Geometry geometry, DiskCreateType createType)
{
DiskParameters diskParams = new DiskParameters();
diskParams.Capacity = capacity;
diskParams.Geometry = geometry;
diskParams.CreateType = createType;
return Initialize(path, diskParams);
}
/// <summary>
/// Creates a new virtual disk at the specified path.
/// </summary>
/// <param name="path">The name of the VMDK to create.</param>
/// <param name="capacity">The desired capacity of the new disk.</param>
/// <param name="geometry">The desired geometry of the new disk, or <c>null</c> for default.</param>
/// <param name="createType">The type of virtual disk to create.</param>
/// <param name="adapterType">The type of disk adapter used with the disk.</param>
/// <returns>The newly created disk image.</returns>
public static DiskImageFile Initialize(string path, long capacity, Geometry geometry, DiskCreateType createType,
DiskAdapterType adapterType)
{
DiskParameters diskParams = new DiskParameters();
diskParams.Capacity = capacity;
diskParams.Geometry = geometry;
diskParams.CreateType = createType;
diskParams.AdapterType = adapterType;
return Initialize(path, diskParams);
}
/// <summary>
/// Creates a new virtual disk at the specified path.
/// </summary>
/// <param name="fileSystem">The file system to create the VMDK on.</param>
/// <param name="path">The name of the VMDK to create.</param>
/// <param name="capacity">The desired capacity of the new disk.</param>
/// <param name="createType">The type of virtual disk to create.</param>
/// <returns>The newly created disk image.</returns>
public static DiskImageFile Initialize(DiscFileSystem fileSystem, string path, long capacity,
DiskCreateType createType)
{
DiskParameters diskParams = new DiskParameters();
diskParams.Capacity = capacity;
diskParams.CreateType = createType;
return Initialize(fileSystem, path, diskParams);
}
/// <summary>
/// Creates a new virtual disk at the specified path.
/// </summary>
/// <param name="fileSystem">The file system to create the VMDK on.</param>
/// <param name="path">The name of the VMDK to create.</param>
/// <param name="capacity">The desired capacity of the new disk.</param>
/// <param name="createType">The type of virtual disk to create.</param>
/// <param name="adapterType">The type of disk adapter used with the disk.</param>
/// <returns>The newly created disk image.</returns>
public static DiskImageFile Initialize(DiscFileSystem fileSystem, string path, long capacity,
DiskCreateType createType, DiskAdapterType adapterType)
{
DiskParameters diskParams = new DiskParameters();
diskParams.Capacity = capacity;
diskParams.CreateType = createType;
diskParams.AdapterType = adapterType;
return Initialize(fileSystem, path, diskParams);
}
/// <summary>
/// Creates a new virtual disk that is a linked clone of an existing disk.
/// </summary>
/// <param name="path">The path to the new disk.</param>
/// <param name="type">The type of the new disk.</param>
/// <param name="parent">The disk to clone.</param>
/// <returns>The new virtual disk.</returns>
public static DiskImageFile InitializeDifferencing(string path, DiskCreateType type, string parent)
{
if (type != DiskCreateType.MonolithicSparse && type != DiskCreateType.TwoGbMaxExtentSparse &&
type != DiskCreateType.VmfsSparse)
{
throw new ArgumentException("Differencing disks must be sparse", nameof(type));
}
using (DiskImageFile parentFile = new DiskImageFile(parent, FileAccess.Read))
{
DescriptorFile baseDescriptor = CreateDifferencingDiskDescriptor(type, parentFile, parent);
FileLocator locator = new LocalFileLocator(Path.GetDirectoryName(path));
return DoInitialize(locator, Path.GetFileName(path), parentFile.Capacity, type, baseDescriptor);
}
}
/// <summary>
/// Creates a new virtual disk that is a linked clone of an existing disk.
/// </summary>
/// <param name="fileSystem">The file system to create the VMDK on.</param>
/// <param name="path">The path to the new disk.</param>
/// <param name="type">The type of the new disk.</param>
/// <param name="parent">The disk to clone.</param>
/// <returns>The new virtual disk.</returns>
public static DiskImageFile InitializeDifferencing(DiscFileSystem fileSystem, string path, DiskCreateType type,
string parent)
{
if (type != DiskCreateType.MonolithicSparse && type != DiskCreateType.TwoGbMaxExtentSparse &&
type != DiskCreateType.VmfsSparse)
{
throw new ArgumentException("Differencing disks must be sparse", nameof(type));
}
string basePath = Utilities.GetDirectoryFromPath(path);
FileLocator locator = new DiscFileLocator(fileSystem, basePath);
FileLocator parentLocator = locator.GetRelativeLocator(Utilities.GetDirectoryFromPath(parent));
using (
DiskImageFile parentFile = new DiskImageFile(parentLocator, Utilities.GetFileFromPath(parent),
FileAccess.Read))
{
DescriptorFile baseDescriptor = CreateDifferencingDiskDescriptor(type, parentFile, parent);
return DoInitialize(locator, Utilities.GetFileFromPath(path), parentFile.Capacity, type, baseDescriptor);
}
}
/// <summary>
/// Gets the contents of this disk as a stream.
/// </summary>
/// <param name="parent">The content of the parent disk (needed if this is a differencing disk).</param>
/// <param name="ownsParent">A value indicating whether ownership of the parent stream is transfered.</param>
/// <returns>The stream containing the disk contents.</returns>
public override SparseStream OpenContent(SparseStream parent, Ownership ownsParent)
{
if (_descriptor.ParentContentId == uint.MaxValue)
{
if (parent != null && ownsParent == Ownership.Dispose)
{
parent.Dispose();
}
parent = null;
}
if (parent == null)
{
parent = new ZeroStream(Capacity);
ownsParent = Ownership.Dispose;
}
if (_descriptor.Extents.Count == 1)
{
if (_monolithicStream != null)
{
return new HostedSparseExtentStream(
_monolithicStream,
Ownership.None,
0,
parent,
ownsParent);
}
return OpenExtent(_descriptor.Extents[0], 0, parent, ownsParent);
}
long extentStart = 0;
SparseStream[] streams = new SparseStream[_descriptor.Extents.Count];
for (int i = 0; i < streams.Length; ++i)
{
streams[i] = OpenExtent(_descriptor.Extents[i], extentStart, parent,
i == streams.Length - 1 ? ownsParent : Ownership.None);
extentStart += _descriptor.Extents[i].SizeInSectors * Sizes.Sector;
}
return new ConcatStream(Ownership.Dispose, streams);
}
/// <summary>
/// Gets the location of the parent.
/// </summary>
/// <returns>The parent locations as an array.</returns>
public override string[] GetParentLocations()
{
return new[] { _descriptor.ParentFileNameHint };
}
/// <summary>
/// Creates a new virtual disk at the specified path.
/// </summary>
/// <param name="fileLocator">The object used to locate / create the component files.</param>
/// <param name="path">The name of the VMDK to create.</param>
/// <param name="parameters">The desired parameters for the new disk.</param>
/// <returns>The newly created disk image.</returns>
internal static DiskImageFile Initialize(FileLocator fileLocator, string path, DiskParameters parameters)
{
if (parameters.Capacity <= 0)
{
throw new ArgumentException("Capacity must be greater than zero", nameof(parameters));
}
Geometry geometry = parameters.Geometry ?? DefaultGeometry(parameters.Capacity);
Geometry biosGeometry;
if (parameters.BiosGeometry != null)
{
biosGeometry = parameters.BiosGeometry;
}
else
{
biosGeometry = Geometry.MakeBiosSafe(geometry, parameters.Capacity);
}
DiskAdapterType adapterType = parameters.AdapterType == DiskAdapterType.None
? DiskAdapterType.LsiLogicScsi
: parameters.AdapterType;
DiskCreateType createType = parameters.CreateType == DiskCreateType.None
? DiskCreateType.MonolithicSparse
: parameters.CreateType;
DescriptorFile baseDescriptor = CreateSimpleDiskDescriptor(geometry, biosGeometry, createType, adapterType);
return DoInitialize(fileLocator, path, parameters.Capacity, createType, baseDescriptor);
}
internal static Geometry DefaultGeometry(long diskSize)
{
int heads;
int sectors;
if (diskSize < Sizes.OneGiB)
{
heads = 64;
sectors = 32;
}
else if (diskSize < 2 * Sizes.OneGiB)
{
heads = 128;
sectors = 32;
}
else
{
heads = 255;
sectors = 63;
}
int cylinders = (int)(diskSize / (heads * sectors * Sizes.Sector));
return new Geometry(cylinders, heads, sectors);
}
internal static DescriptorFile CreateSimpleDiskDescriptor(Geometry geometry, Geometry biosGeometery,
DiskCreateType createType, DiskAdapterType adapterType)
{
DescriptorFile baseDescriptor = new DescriptorFile();
baseDescriptor.DiskGeometry = geometry;
baseDescriptor.BiosGeometry = biosGeometery;
baseDescriptor.ContentId = (uint)_rng.Next();
baseDescriptor.CreateType = createType;
baseDescriptor.UniqueId = Guid.NewGuid();
baseDescriptor.HardwareVersion = "4";
baseDescriptor.AdapterType = adapterType;
return baseDescriptor;
}
internal static ServerSparseExtentHeader CreateServerSparseExtentHeader(long size)
{
uint numSectors = (uint)MathUtilities.Ceil(size, Sizes.Sector);
uint numGDEntries = (uint)MathUtilities.Ceil(numSectors * (long)Sizes.Sector, 2 * Sizes.OneMiB);
ServerSparseExtentHeader header = new ServerSparseExtentHeader();
header.Capacity = numSectors;
header.GrainSize = 1;
header.GdOffset = 4;
header.NumGdEntries = numGDEntries;
header.FreeSector = (uint)(header.GdOffset + MathUtilities.Ceil(numGDEntries * 4, Sizes.Sector));
return header;
}
/// <summary>
/// Disposes of this instance.
/// </summary>
/// <param name="disposing"><c>true</c> if disposing, <c>false</c> if in destructor.</param>
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
{
if (_contentStream != null)
{
_contentStream.Dispose();
_contentStream = null;
}
if (_ownsMonolithicStream == Ownership.Dispose && _monolithicStream != null)
{
_monolithicStream.Dispose();
_monolithicStream = null;
}
}
}
finally
{
base.Dispose(disposing);
}
}
private static DiskImageFile DoInitialize(FileLocator fileLocator, string file, long capacity,
DiskCreateType type, DescriptorFile baseDescriptor)
{
if (type == DiskCreateType.MonolithicSparse)
{
// MonolithicSparse is a special case, the descriptor is embedded in the file itself...
using (Stream fs = fileLocator.Open(file, FileMode.Create, FileAccess.ReadWrite, FileShare.None))
{
long descriptorStart;
CreateExtent(fs, capacity, ExtentType.Sparse, 10 * Sizes.OneKiB, out descriptorStart);
ExtentDescriptor extent = new ExtentDescriptor(ExtentAccess.ReadWrite, capacity / Sizes.Sector,
ExtentType.Sparse, file, 0);
fs.Position = descriptorStart * Sizes.Sector;
baseDescriptor.Extents.Add(extent);
baseDescriptor.Write(fs);
}
}
else
{
ExtentType extentType = CreateTypeToExtentType(type);
long totalSize = 0;
List<ExtentDescriptor> extents = new List<ExtentDescriptor>();
if (type == DiskCreateType.MonolithicFlat || type == DiskCreateType.VmfsSparse ||
type == DiskCreateType.Vmfs)
{
string adornment = "flat";
if (type == DiskCreateType.VmfsSparse)
{
adornment = string.IsNullOrEmpty(baseDescriptor.ParentFileNameHint) ? "sparse" : "delta";
}
string fileName = AdornFileName(file, adornment);
using (Stream fs = fileLocator.Open(fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.None)
)
{
CreateExtent(fs, capacity, extentType);
extents.Add(new ExtentDescriptor(ExtentAccess.ReadWrite, capacity / Sizes.Sector, extentType,
fileName, 0));
totalSize = capacity;
}
}
else if (type == DiskCreateType.TwoGbMaxExtentFlat || type == DiskCreateType.TwoGbMaxExtentSparse)
{
int i = 1;
while (totalSize < capacity)
{
string adornment;
if (type == DiskCreateType.TwoGbMaxExtentSparse)
{
adornment = string.Format(CultureInfo.InvariantCulture, "s{0:x3}", i);
}
else
{
adornment = string.Format(CultureInfo.InvariantCulture, "{0:x6}", i);
}
string fileName = AdornFileName(file, adornment);
using (
Stream fs = fileLocator.Open(fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.None)
)
{
long extentSize = Math.Min(2 * Sizes.OneGiB - Sizes.OneMiB, capacity - totalSize);
CreateExtent(fs, extentSize, extentType);
extents.Add(new ExtentDescriptor(ExtentAccess.ReadWrite, extentSize / Sizes.Sector, extentType,
fileName, 0));
totalSize += extentSize;
}
++i;
}
}
else
{
throw new NotSupportedException("Creating disks of this type is not supported");
}
using (Stream fs = fileLocator.Open(file, FileMode.Create, FileAccess.ReadWrite, FileShare.None))
{
baseDescriptor.Extents.AddRange(extents);
baseDescriptor.Write(fs);
}
}
return new DiskImageFile(fileLocator, file, FileAccess.ReadWrite);
}
private static void CreateSparseExtent(Stream extentStream, long size, long descriptorLength,
out long descriptorStart)
{
// Figure out grain size and number of grain tables, and adjust actual extent size to be a multiple
// of grain size
const int GtesPerGt = 512;
long grainSize = 128;
int numGrainTables = (int)MathUtilities.Ceil(size, grainSize * GtesPerGt * Sizes.Sector);
descriptorLength = MathUtilities.RoundUp(descriptorLength, Sizes.Sector);
descriptorStart = 0;
if (descriptorLength != 0)
{
descriptorStart = 1;
}
long redundantGrainDirStart = Math.Max(descriptorStart, 1) + MathUtilities.Ceil(descriptorLength, Sizes.Sector);
long redundantGrainDirLength = numGrainTables * 4;
long redundantGrainTablesStart = redundantGrainDirStart +
MathUtilities.Ceil(redundantGrainDirLength, Sizes.Sector);
long redundantGrainTablesLength = numGrainTables * MathUtilities.RoundUp(GtesPerGt * 4, Sizes.Sector);
long grainDirStart = redundantGrainTablesStart + MathUtilities.Ceil(redundantGrainTablesLength, Sizes.Sector);
long grainDirLength = numGrainTables * 4;
long grainTablesStart = grainDirStart + MathUtilities.Ceil(grainDirLength, Sizes.Sector);
long grainTablesLength = numGrainTables * MathUtilities.RoundUp(GtesPerGt * 4, Sizes.Sector);
long dataStart = MathUtilities.RoundUp(grainTablesStart + MathUtilities.Ceil(grainTablesLength, Sizes.Sector),
grainSize);
// Generate the header, and write it
HostedSparseExtentHeader header = new HostedSparseExtentHeader();
header.Flags = HostedSparseExtentFlags.ValidLineDetectionTest | HostedSparseExtentFlags.RedundantGrainTable;
header.Capacity = MathUtilities.RoundUp(size, grainSize * Sizes.Sector) / Sizes.Sector;
header.GrainSize = grainSize;
header.DescriptorOffset = descriptorStart;
header.DescriptorSize = descriptorLength / Sizes.Sector;
header.NumGTEsPerGT = GtesPerGt;
header.RgdOffset = redundantGrainDirStart;
header.GdOffset = grainDirStart;
header.Overhead = dataStart;
extentStream.Position = 0;
extentStream.Write(header.GetBytes(), 0, Sizes.Sector);
// Zero-out the descriptor space
if (descriptorLength > 0)
{
byte[] descriptor = new byte[descriptorLength];
extentStream.Position = descriptorStart * Sizes.Sector;
extentStream.Write(descriptor, 0, descriptor.Length);
}
// Generate the redundant grain dir, and write it
byte[] grainDir = new byte[numGrainTables * 4];
for (int i = 0; i < numGrainTables; ++i)
{
EndianUtilities.WriteBytesLittleEndian(
(uint)(redundantGrainTablesStart + i * MathUtilities.Ceil(GtesPerGt * 4, Sizes.Sector)), grainDir, i * 4);
}
extentStream.Position = redundantGrainDirStart * Sizes.Sector;
extentStream.Write(grainDir, 0, grainDir.Length);
// Write out the blank grain tables
byte[] grainTable = new byte[GtesPerGt * 4];
for (int i = 0; i < numGrainTables; ++i)
{
extentStream.Position = redundantGrainTablesStart * Sizes.Sector +
i * MathUtilities.RoundUp(GtesPerGt * 4, Sizes.Sector);
extentStream.Write(grainTable, 0, grainTable.Length);
}
// Generate the main grain dir, and write it
for (int i = 0; i < numGrainTables; ++i)
{
EndianUtilities.WriteBytesLittleEndian(
(uint)(grainTablesStart + i * MathUtilities.Ceil(GtesPerGt * 4, Sizes.Sector)), grainDir, i * 4);
}
extentStream.Position = grainDirStart * Sizes.Sector;
extentStream.Write(grainDir, 0, grainDir.Length);
// Write out the blank grain tables
for (int i = 0; i < numGrainTables; ++i)
{
extentStream.Position = grainTablesStart * Sizes.Sector +
i * MathUtilities.RoundUp(GtesPerGt * 4, Sizes.Sector);
extentStream.Write(grainTable, 0, grainTable.Length);
}
// Make sure stream is correct length
if (extentStream.Length != dataStart * Sizes.Sector)
{
extentStream.SetLength(dataStart * Sizes.Sector);
}
}
private static void CreateExtent(Stream extentStream, long size, ExtentType type)
{
long descriptorStart;
CreateExtent(extentStream, size, type, 0, out descriptorStart);
}
private static void CreateExtent(Stream extentStream, long size, ExtentType type, long descriptorLength,
out long descriptorStart)
{
if (type == ExtentType.Flat || type == ExtentType.Vmfs)
{
extentStream.SetLength(size);
descriptorStart = 0;
return;
}
if (type == ExtentType.Sparse)
{
CreateSparseExtent(extentStream, size, descriptorLength, out descriptorStart);
}
else if (type == ExtentType.VmfsSparse)
{
ServerSparseExtentHeader header = CreateServerSparseExtentHeader(size);
extentStream.Position = 0;
extentStream.Write(header.GetBytes(), 0, 4 * Sizes.Sector);
byte[] blankGlobalDirectory = new byte[header.NumGdEntries * 4];
extentStream.Write(blankGlobalDirectory, 0, blankGlobalDirectory.Length);
descriptorStart = 0;
}
else
{
throw new NotImplementedException("Extent type not implemented");
}
}
private static string AdornFileName(string name, string adornment)
{
if (!name.EndsWith(".vmdk", StringComparison.OrdinalIgnoreCase))
{
throw new ArgumentException("name must end in .vmdk to be adorned");
}
return name.Substring(0, name.Length - 5) + "-" + adornment + ".vmdk";
}
private static ExtentType CreateTypeToExtentType(DiskCreateType type)
{
switch (type)
{
case DiskCreateType.FullDevice:
case DiskCreateType.MonolithicFlat:
case DiskCreateType.PartitionedDevice:
case DiskCreateType.TwoGbMaxExtentFlat:
return ExtentType.Flat;
case DiskCreateType.MonolithicSparse:
case DiskCreateType.StreamOptimized:
case DiskCreateType.TwoGbMaxExtentSparse:
return ExtentType.Sparse;
case DiskCreateType.Vmfs:
return ExtentType.Vmfs;
case DiskCreateType.VmfsPassthroughRawDeviceMap:
return ExtentType.VmfsRdm;
case DiskCreateType.VmfsRaw:
case DiskCreateType.VmfsRawDeviceMap:
return ExtentType.VmfsRaw;
case DiskCreateType.VmfsSparse:
return ExtentType.VmfsSparse;
default:
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Unable to convert {0}",
type));
}
}
private static DescriptorFile CreateDifferencingDiskDescriptor(DiskCreateType type, DiskImageFile parent,
string parentPath)
{
DescriptorFile baseDescriptor = new DescriptorFile();
baseDescriptor.ContentId = (uint)_rng.Next();
baseDescriptor.ParentContentId = parent.ContentId;
baseDescriptor.ParentFileNameHint = parentPath;
baseDescriptor.CreateType = type;
return baseDescriptor;
}
private SparseStream OpenExtent(ExtentDescriptor extent, long extentStart, SparseStream parent,
Ownership ownsParent)
{
FileAccess access = FileAccess.Read;
FileShare share = FileShare.Read;
if (extent.Access == ExtentAccess.ReadWrite && _access != FileAccess.Read)
{
access = FileAccess.ReadWrite;
share = FileShare.None;
}
if (extent.Type != ExtentType.Sparse && extent.Type != ExtentType.VmfsSparse)
{
if (ownsParent == Ownership.Dispose && parent != null)
{
parent.Dispose();
}
}
switch (extent.Type)
{
case ExtentType.Flat:
case ExtentType.Vmfs:
return SparseStream.FromStream(
_fileLocator.Open(extent.FileName, FileMode.Open, access, share),
Ownership.Dispose);
case ExtentType.Zero:
return new ZeroStream(extent.SizeInSectors * Sizes.Sector);
case ExtentType.Sparse:
return new HostedSparseExtentStream(
_fileLocator.Open(extent.FileName, FileMode.Open, access, share),
Ownership.Dispose,
extentStart,
parent,
ownsParent);
case ExtentType.VmfsSparse:
return new ServerSparseExtentStream(
_fileLocator.Open(extent.FileName, FileMode.Open, access, share),
Ownership.Dispose,
extentStart,
parent,
ownsParent);
default:
throw new NotSupportedException();
}
}
private void LoadDescriptor(Stream s)
{
s.Position = 0;
byte[] header = StreamUtilities.ReadExact(s, (int)Math.Min(Sizes.Sector, s.Length));
if (header.Length < Sizes.Sector ||
EndianUtilities.ToUInt32LittleEndian(header, 0) != HostedSparseExtentHeader.VmdkMagicNumber)
{
s.Position = 0;
_descriptor = new DescriptorFile(s);
if (_access != FileAccess.Read)
{
_descriptor.ContentId = (uint)_rng.Next();
s.Position = 0;
_descriptor.Write(s);
s.SetLength(s.Position);
}
}
else
{
// This is a sparse disk extent, hopefully with embedded descriptor...
HostedSparseExtentHeader hdr = HostedSparseExtentHeader.Read(header, 0);
if (hdr.DescriptorOffset != 0)
{
Stream descriptorStream = new SubStream(s, hdr.DescriptorOffset * Sizes.Sector,
hdr.DescriptorSize * Sizes.Sector);
_descriptor = new DescriptorFile(descriptorStream);
if (_access != FileAccess.Read)
{
_descriptor.ContentId = (uint)_rng.Next();
descriptorStream.Position = 0;
_descriptor.Write(descriptorStream);
byte[] blank = new byte[descriptorStream.Length - descriptorStream.Position];
descriptorStream.Write(blank, 0, blank.Length);
}
}
}
}
}
}
| |
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
using System;
using System.Globalization;
using Lucene.Net.Util;
namespace Lucene.Net.Support
{
/// <summary>
/// Mimics Java's Character class.
/// </summary>
public class Character
{
private const char charNull = '\0';
private const char charZero = '0';
private const char charA = 'a';
public const int MAX_RADIX = 36;
public const int MIN_RADIX = 2;
public const int MAX_CODE_POINT = 0x10FFFF;
public const int MIN_CODE_POINT = 0x000000;
public const char MAX_SURROGATE = '\uDFFF';
public const char MIN_SURROGATE = '\uD800';
public const char MIN_LOW_SURROGATE = '\uDC00';
public const char MAX_LOW_SURROGATE = '\uDFFF';
public const char MIN_HIGH_SURROGATE = '\uD800';
public const char MAX_HIGH_SURROGATE = '\uDBFF';
public const int MIN_SUPPLEMENTARY_CODE_POINT = 0x010000;
private static readonly string digitKeys = "0Aa\u0660\u06f0\u0966\u09e6\u0a66\u0ae6\u0b66\u0be7\u0c66\u0ce6\u0d66\u0e50\u0ed0\u0f20\u1040\u1369\u17e0\u1810\uff10\uff21\uff41";
private static readonly char[] digitValues = "90Z7zW\u0669\u0660\u06f9\u06f0\u096f\u0966\u09ef\u09e6\u0a6f\u0a66\u0aef\u0ae6\u0b6f\u0b66\u0bef\u0be6\u0c6f\u0c66\u0cef\u0ce6\u0d6f\u0d66\u0e59\u0e50\u0ed9\u0ed0\u0f29\u0f20\u1049\u1040\u1371\u1368\u17e9\u17e0\u1819\u1810\uff19\uff10\uff3a\uff17\uff5a\uff37"
.ToCharArray();
/// <summary>
/// Convenience method to determine the value of the specified character
/// <paramref name="c"/> in the supplied radix. The value of <paramref name="radix"/> must be
/// between <see cref="MIN_RADIX"/> and <see cref="MAX_RADIX"/>.
/// </summary>
/// <param name="c">The character to determine the value of.</param>
/// <param name="radix">The radix.</param>
/// <returns>
/// The value of <paramref name="c"/> in <paramref name="radix"/> if <paramref name="radix"/> lies
/// between <see cref="MIN_RADIX"/> and <see cref="MAX_RADIX"/>; -1 otherwise.
/// </returns>
public static int Digit(char c, int radix)
{
int result = -1;
if (radix >= MIN_RADIX && radix <= MAX_RADIX)
{
if (c < 128)
{
// Optimized for ASCII
if ('0' <= c && c <= '9')
{
result = c - '0';
}
else if ('a' <= c && c <= 'z')
{
result = c - ('a' - 10);
}
else if ('A' <= c && c <= 'Z')
{
result = c - ('A' - 10);
}
return result < radix ? result : -1;
}
result = BinarySearchRange(digitKeys, c);
if (result >= 0 && c <= digitValues[result * 2])
{
int value = (char)(c - digitValues[result * 2 + 1]);
if (value >= radix)
{
return -1;
}
return value;
}
}
return -1;
}
/// <summary>
/// Search the sorted characters in the string and return the nearest index.
/// </summary>
/// <param name="data">The String to search.</param>
/// <param name="c">The character to search for.</param>
/// <returns>The nearest index.</returns>
private static int BinarySearchRange(string data, char c)
{
char value = (char)0;
int low = 0, mid = -1, high = data.Length - 1;
while (low <= high)
{
mid = (low + high) >> 1;
value = data[mid];
if (c > value)
low = mid + 1;
else if (c == value)
return mid;
else
high = mid - 1;
}
return mid - (c < value ? 1 : 0);
}
/// <summary>
///
/// </summary>
/// <param name="digit"></param>
/// <param name="radix"></param>
/// <returns></returns>
public static char ForDigit(int digit, int radix)
{
// if radix or digit is out of range,
// return the null character.
if (radix < Character.MIN_RADIX)
return charNull;
if (radix > Character.MAX_RADIX)
return charNull;
if (digit < 0)
return charNull;
if (digit >= radix)
return charNull;
// if digit is less than 10,
// return '0' plus digit
if (digit < 10)
return (char)((int)charZero + digit);
// otherwise, return 'a' plus digit.
return (char)((int)charA + digit - 10);
}
public static int ToChars(int codePoint, char[] dst, int dstIndex)
{
var converted = UnicodeUtil.ToCharArray(new[] {codePoint}, 0, 1);
Array.Copy(converted, 0, dst, dstIndex, converted.Length);
return converted.Length;
}
public static char[] ToChars(int codePoint)
{
return UnicodeUtil.ToCharArray(new[] {codePoint}, 0, 1);
}
public static int ToCodePoint(char high, char low)
{
// Optimized form of:
// return ((high - MIN_HIGH_SURROGATE) << 10)
// + (low - MIN_LOW_SURROGATE)
// + MIN_SUPPLEMENTARY_CODE_POINT;
return ((high << 10) + low) + (MIN_SUPPLEMENTARY_CODE_POINT
- (MIN_HIGH_SURROGATE << 10)
- MIN_LOW_SURROGATE);
}
public static int ToLower(int codePoint)
{
var str = UnicodeUtil.NewString(new[] {codePoint}, 0, 1);
str = str.ToLowerInvariant();
return CodePointAt(str, 0);
}
public static int ToUpper(int codePoint)
{
var str = UnicodeUtil.NewString(new[] { codePoint }, 0, 1);
str = str.ToUpperInvariant();
return CodePointAt(str, 0);
}
public static int CharCount(int codePoint)
{
// A given codepoint can be represented in .NET either by 1 char (up to UTF16),
// or by if it's a UTF32 codepoint, in which case the current char will be a surrogate
return codePoint >= MIN_SUPPLEMENTARY_CODE_POINT ? 2 : 1;
}
/// <summary>
/// Returns the number of Unicode code points in the text range of the specified char sequence.
/// The text range begins at the specified <paramref name="beginIndex"/> and extends to the char at index <c>endIndex - 1</c>.
/// Thus the length (in <see cref="char"/>s) of the text range is <c>endIndex-beginIndex</c>.
/// Unpaired surrogates within the text range count as one code point each.
/// </summary>
/// <param name="seq">the char sequence</param>
/// <param name="beginIndex">the index to the first char of the text range.</param>
/// <param name="endIndex">the index after the last char of the text range.</param>
/// <returns>the number of Unicode code points in the specified text range</returns>
/// <exception cref="IndexOutOfRangeException">
/// if the <paramref name="beginIndex"/> is negative, or <paramref name="endIndex"/>
/// is larger than the length of the given sequence, or <paramref name="beginIndex"/>
/// is larger than <paramref name="endIndex"/>.
/// </exception>
public static int CodePointCount(string seq, int beginIndex, int endIndex)
{
int length = seq.Length;
if (beginIndex < 0 || endIndex > length || beginIndex > endIndex)
{
throw new IndexOutOfRangeException();
}
int n = endIndex - beginIndex;
for (int i = beginIndex; i < endIndex;)
{
if (char.IsHighSurrogate(seq[i++]) && i < endIndex &&
char.IsLowSurrogate(seq[i]))
{
n--;
i++;
}
}
return n;
}
public static int CodePointCount(char[] a, int offset, int count)
{
if (count > a.Length - offset || offset < 0 || count < 0)
{
throw new IndexOutOfRangeException();
}
return CodePointCountImpl(a, offset, count);
}
internal static int CodePointCountImpl(char[] a, int offset, int count)
{
int endIndex = offset + count;
int n = count;
for (int i = offset; i < endIndex;)
{
if (char.IsHighSurrogate(a[i++]) && i < endIndex
&& char.IsLowSurrogate(a[i]))
{
n--;
i++;
}
}
return n;
}
public static int CodePointAt(string seq, int index)
{
char c1 = seq[index++];
if (char.IsHighSurrogate(c1))
{
if (index < seq.Length)
{
char c2 = seq[index];
if (char.IsLowSurrogate(c2))
{
return ToCodePoint(c1, c2);
}
}
}
return c1;
}
public static int CodePointAt(char high, char low)
{
return ((high << 10) + low) + (MIN_SUPPLEMENTARY_CODE_POINT
- (MIN_HIGH_SURROGATE << 10)
- MIN_LOW_SURROGATE);
}
public static int CodePointAt(ICharSequence seq, int index)
{
char c1 = seq[index++];
if (char.IsHighSurrogate(c1))
{
if (index < seq.Length)
{
char c2 = seq[index];
if (char.IsLowSurrogate(c2))
{
return ToCodePoint(c1, c2);
}
}
}
return c1;
}
public static int CodePointAt(char[] a, int index, int limit)
{
if (index >= limit || limit < 0 || limit > a.Length)
{
throw new IndexOutOfRangeException();
}
return CodePointAtImpl(a, index, limit);
}
// throws ArrayIndexOutofBoundsException if index out of bounds
static int CodePointAtImpl(char[] a, int index, int limit)
{
char c1 = a[index++];
if (char.IsHighSurrogate(c1))
{
if (index < limit)
{
char c2 = a[index];
if (char.IsLowSurrogate(c2))
{
return ToCodePoint(c1, c2);
}
}
}
return c1;
}
/// <summary>
/// Copy of the implementation from Character class in Java
///
/// http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b27/java/lang/Character.java
/// </summary>
public static int OffsetByCodePoints(string seq, int index,
int codePointOffset)
{
int length = seq.Length;
if (index < 0 || index > length)
{
throw new IndexOutOfRangeException();
}
int x = index;
if (codePointOffset >= 0)
{
int i;
for (i = 0; x < length && i < codePointOffset; i++)
{
if (char.IsHighSurrogate(seq[x++]))
{
if (x < length && char.IsLowSurrogate(seq[x]))
{
x++;
}
}
}
if (i < codePointOffset)
{
throw new IndexOutOfRangeException();
}
}
else
{
int i;
for (i = codePointOffset; x > 0 && i < 0; i++)
{
if (char.IsLowSurrogate(seq[--x]))
{
if (x > 0 && char.IsHighSurrogate(seq[x - 1]))
{
x--;
}
}
}
if (i < 0)
{
throw new IndexOutOfRangeException();
}
}
return x;
}
/// <summary>
/// Copy of the implementation from Character class in Java
///
/// http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b27/java/lang/Character.java
/// </summary>
public static int OffsetByCodePoints(char[] a, int start, int count,
int index, int codePointOffset)
{
if (count > a.Length - start || start < 0 || count < 0
|| index < start || index > start + count)
{
throw new IndexOutOfRangeException();
}
return OffsetByCodePointsImpl(a, start, count, index, codePointOffset);
}
static int OffsetByCodePointsImpl(char[] a, int start, int count,
int index, int codePointOffset)
{
int x = index;
if (codePointOffset >= 0)
{
int limit = start + count;
int i;
for (i = 0; x < limit && i < codePointOffset; i++)
{
if (Char.IsHighSurrogate(a[x++]) && x < limit && Char.IsLowSurrogate(a[x]))
{
x++;
}
}
if (i < codePointOffset)
{
throw new IndexOutOfRangeException();
}
}
else
{
int i;
for (i = codePointOffset; x > start && i < 0; i++)
{
if (Char.IsLowSurrogate(a[--x]) && x > start &&
Char.IsHighSurrogate(a[x - 1]))
{
x--;
}
}
if (i < 0)
{
throw new IndexOutOfRangeException();
}
}
return x;
}
public static bool IsLetter(int c)
{
var unicodeCategory = CharUnicodeInfo.GetUnicodeCategory((char)c);
return unicodeCategory == UnicodeCategory.LowercaseLetter ||
unicodeCategory == UnicodeCategory.UppercaseLetter ||
unicodeCategory == UnicodeCategory.TitlecaseLetter ||
unicodeCategory == UnicodeCategory.ModifierLetter ||
unicodeCategory == UnicodeCategory.OtherLetter;
}
/// <summary>
/// LUCENENET safe way to get unicode category. The .NET <see cref="char.ConvertFromUtf32(int)"/>
/// method should be used first to be safe for surrogate pairs. However, if the value falls between
/// 0x00d800 and 0x00dfff, that method throws an exception. So this is a wrapper that converts the
/// codepoint to a char in those cases.
///
/// This mimics the behavior of the Java Character.GetType class, but returns the .NET UnicodeCategory
/// enumeration for easy consumption.
/// </summary>
/// <param name="codePoint"></param>
/// <returns> A <see cref="UnicodeCategory"/> representing the <paramref name="codePoint"/>. </returns>
public static UnicodeCategory GetType(int codePoint)
{
if ((codePoint >= 0x00d800) && (codePoint <= 0x00dfff))
return CharUnicodeInfo.GetUnicodeCategory((char)codePoint);
else
return CharUnicodeInfo.GetUnicodeCategory(char.ConvertFromUtf32(codePoint), 0);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Resources;
using Encoding = System.Text.Encoding;
#if ES_BUILD_STANDALONE
using Environment = Microsoft.Diagnostics.Tracing.Internal.Environment;
namespace Microsoft.Diagnostics.Tracing
#else
namespace System.Diagnostics.Tracing
#endif
{
/// <summary>
/// TraceLogging: Contains the information needed to generate tracelogging
/// metadata for an event field.
/// </summary>
internal class FieldMetadata
{
/// <summary>
/// Name of the field
/// </summary>
private readonly string name;
/// <summary>
/// The number of bytes in the UTF8 Encoding of 'name' INCLUDING a null terminator.
/// </summary>
private readonly int nameSize;
private readonly EventFieldTags tags;
private readonly byte[]? custom;
/// <summary>
/// ETW supports fixed sized arrays. If inType has the InTypeFixedCountFlag then this is the
/// statically known count for the array. It is also used to encode the number of bytes of
/// custom meta-data if InTypeCustomCountFlag set.
/// </summary>
private readonly ushort fixedCount;
private byte inType;
private byte outType;
/// <summary>
/// Scalar or variable-length array.
/// </summary>
public FieldMetadata(
string name,
TraceLoggingDataType type,
EventFieldTags tags,
bool variableCount)
: this(
name,
type,
tags,
variableCount ? Statics.InTypeVariableCountFlag : (byte)0,
0,
null)
{
}
/// <summary>
/// Fixed-length array.
/// </summary>
public FieldMetadata(
string name,
TraceLoggingDataType type,
EventFieldTags tags,
ushort fixedCount)
: this(
name,
type,
tags,
Statics.InTypeFixedCountFlag,
fixedCount,
null)
{
}
/// <summary>
/// Custom serializer
/// </summary>
public FieldMetadata(
string name,
TraceLoggingDataType type,
EventFieldTags tags,
byte[]? custom)
: this(
name,
type,
tags,
Statics.InTypeCustomCountFlag,
checked((ushort)(custom == null ? 0 : custom.Length)),
custom)
{
}
private FieldMetadata(
string name,
TraceLoggingDataType dataType,
EventFieldTags tags,
byte countFlags,
ushort fixedCount = 0,
byte[]? custom = null)
{
if (name == null)
{
throw new ArgumentNullException(
nameof(name),
"This usually means that the object passed to Write is of a type that"
+ " does not support being used as the top-level object in an event,"
+ " e.g. a primitive or built-in type.");
}
Statics.CheckName(name);
var coreType = (int)dataType & Statics.InTypeMask;
this.name = name;
this.nameSize = Encoding.UTF8.GetByteCount(this.name) + 1;
this.inType = (byte)(coreType | countFlags);
this.outType = (byte)(((int)dataType >> 8) & Statics.OutTypeMask);
this.tags = tags;
this.fixedCount = fixedCount;
this.custom = custom;
if (countFlags != 0)
{
if (coreType == (int)TraceLoggingDataType.Nil)
{
throw new NotSupportedException(SR.EventSource_NotSupportedArrayOfNil);
}
if (coreType == (int)TraceLoggingDataType.Binary)
{
throw new NotSupportedException(SR.EventSource_NotSupportedArrayOfBinary);
}
if (coreType == (int)TraceLoggingDataType.Utf16String ||
coreType == (int)TraceLoggingDataType.MbcsString)
{
throw new NotSupportedException(SR.EventSource_NotSupportedArrayOfNullTerminatedString);
}
}
if (((int)this.tags & 0xfffffff) != 0)
{
this.outType |= Statics.OutTypeChainFlag;
}
if (this.outType != 0)
{
this.inType |= Statics.InTypeChainFlag;
}
}
public void IncrementStructFieldCount()
{
this.inType |= Statics.InTypeChainFlag;
this.outType++;
if ((this.outType & Statics.OutTypeMask) == 0)
{
throw new NotSupportedException(SR.EventSource_TooManyFields);
}
}
/// <summary>
/// This is the main routine for FieldMetaData. Basically it will serialize the data in
/// this structure as TraceLogging style meta-data into the array 'metaArray' starting at
/// 'pos' (pos is updated to reflect the bytes written).
///
/// Note that 'metaData' can be null, in which case it only updates 'pos'. This is useful
/// for a 'two pass' approach where you figure out how big to make the array, and then you
/// fill it in.
/// </summary>
public void Encode(ref int pos, byte[]? metadata)
{
// Write out the null terminated UTF8 encoded name
if (metadata != null)
{
Encoding.UTF8.GetBytes(this.name, 0, this.name.Length, metadata, pos);
}
pos += this.nameSize;
// Write 1 byte for inType
if (metadata != null)
{
metadata[pos] = this.inType;
}
pos += 1;
// If InTypeChainFlag set, then write out the outType
if (0 != (this.inType & Statics.InTypeChainFlag))
{
if (metadata != null)
{
metadata[pos] = this.outType;
}
pos += 1;
// If OutTypeChainFlag set, then write out tags
if (0 != (this.outType & Statics.OutTypeChainFlag))
{
Statics.EncodeTags((int)this.tags, ref pos, metadata);
}
}
// If InTypeFixedCountFlag set, write out the fixedCount (2 bytes little endian)
if (0 != (this.inType & Statics.InTypeFixedCountFlag))
{
if (metadata != null)
{
metadata[pos + 0] = unchecked((byte)this.fixedCount);
metadata[pos + 1] = (byte)(this.fixedCount >> 8);
}
pos += 2;
// If InTypeCustomCountFlag set, write out the blob of custom meta-data.
if (Statics.InTypeCustomCountFlag == (this.inType & Statics.InTypeCountMask) &&
this.fixedCount != 0)
{
if (metadata != null)
{
Debug.Assert(custom != null);
Buffer.BlockCopy(custom, 0, metadata, pos, this.fixedCount);
}
pos += this.fixedCount;
}
}
}
}
}
| |
// Copyright (c) 2012, Event Store LLP
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// Neither the name of the Event Store LLP nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
using System;
using System.Collections.Generic;
using System.Security.Principal;
using EventStore.Core.Bus;
using EventStore.Core.Data;
using EventStore.Core.Helpers;
using EventStore.Core.Messages;
using EventStore.Core.Services.TimerService;
using EventStore.Projections.Core.Messages;
namespace EventStore.Projections.Core.Services.Processing
{
public class ExternallyFedByStreamEventReader : EventReader,
IHandle<ReaderSubscriptionManagement.SpoolStreamReading>,
IHandle<ReaderSubscriptionManagement.CompleteSpooledStreamReading>
{
private readonly IODispatcher _ioDispatcher;
private long? _limitingCommitPosition;
private readonly ITimeProvider _timeProvider;
private readonly bool _resolveLinkTos;
private int _maxReadCount = 111;
private int _deliveredEvents;
private string _dataStreamName;
private int _dataNextSequenceNumber;
private readonly Queue<Tuple<string, int>> _pendingStreams = new Queue<Tuple<string, int>>();
private Guid _dataReadRequestId;
private bool _catalogEof;
private int _catalogCurrentSequenceNumber;
private readonly HashSet<Guid> _readLengthRequests = new HashSet<Guid>();
public ExternallyFedByStreamEventReader(
IPublisher publisher, Guid eventReaderCorrelationId, IPrincipal readAs, IODispatcher ioDispatcher,
long? limitingCommitPosition, ITimeProvider timeProvider, bool resolveLinkTos)
: base(ioDispatcher, publisher, eventReaderCorrelationId, readAs, true, stopAfterNEvents: null)
{
_ioDispatcher = ioDispatcher;
_limitingCommitPosition = limitingCommitPosition;
_timeProvider = timeProvider;
_resolveLinkTos = resolveLinkTos;
_catalogCurrentSequenceNumber = -1;
}
protected override bool AreEventsRequested()
{
return _dataReadRequestId != Guid.Empty;
}
private bool CheckEnough()
{
if (_stopAfterNEvents != null && _deliveredEvents >= _stopAfterNEvents)
{
_publisher.Publish(
new ReaderSubscriptionMessage.EventReaderEof(EventReaderCorrelationId, maxEventsReached: true));
Dispose();
return true;
}
return false;
}
protected override void RequestEvents()
{
if (_disposed) throw new InvalidOperationException("Disposed");
if (AreEventsRequested())
throw new InvalidOperationException("Read operation is already in progress");
if (PauseRequested || Paused)
throw new InvalidOperationException("Paused or pause requested");
TakeNextStreamIfRequired();
if (!_disposed && _dataStreamName != null)
{
_dataReadRequestId = _ioDispatcher.ReadForward(
_dataStreamName, _dataNextSequenceNumber, _maxReadCount, _resolveLinkTos, ReadAs,
ReadDataStreamCompleted);
}
}
private void TakeNextStreamIfRequired()
{
if (_dataNextSequenceNumber == int.MaxValue || _dataStreamName == null)
{
if (_dataStreamName != null)
SendPartitionEof(
_dataStreamName,
CheckpointTag.FromByStreamPosition(
0, "", _catalogCurrentSequenceNumber, _dataStreamName, int.MaxValue,
_limitingCommitPosition.Value));
_dataStreamName = null;
if (_catalogEof && _pendingStreams.Count == 0)
{
SendEof();
return;
}
if (_pendingStreams.Count == 0)
{
SendIdle();
return;
}
var nextDataStream = _pendingStreams.Dequeue();
_dataStreamName = nextDataStream.Item1;
_catalogCurrentSequenceNumber = nextDataStream.Item2;
_dataNextSequenceNumber = 0;
}
}
private void SendIdle()
{
_publisher.Publish(
new ReaderSubscriptionMessage.EventReaderIdle(EventReaderCorrelationId, _timeProvider.Now));
}
private void ReadDataStreamCompleted(ClientMessage.ReadStreamEventsForwardCompleted completed)
{
_dataReadRequestId = Guid.Empty;
if (Paused)
throw new InvalidOperationException("Paused");
switch (completed.Result)
{
case ReadStreamResult.AccessDenied:
SendNotAuthorized();
return;
case ReadStreamResult.NoStream:
_dataNextSequenceNumber = int.MaxValue;
if (completed.LastEventNumber >= 0)
SendPartitionDeleted(_dataStreamName, -1, null, null, null, null);
PauseOrContinueProcessing();
break;
case ReadStreamResult.StreamDeleted:
_dataNextSequenceNumber = int.MaxValue;
SendPartitionDeleted(_dataStreamName, -1, null, null, null, null);
PauseOrContinueProcessing();
break;
case ReadStreamResult.Success:
foreach (var e in completed.Events)
{
DeliverEvent(e, 17.7f);
if (CheckEnough())
return;
}
if (completed.IsEndOfStream)
_dataNextSequenceNumber = int.MaxValue;
else
_dataNextSequenceNumber = completed.NextEventNumber;
PauseOrContinueProcessing();
break;
default:
throw new NotSupportedException();
}
}
private void EnqueueStreamForProcessing(string streamId, int catalogSequenceNumber)
{
_pendingStreams.Enqueue(Tuple.Create(streamId, catalogSequenceNumber));
if (!AreEventsRequested() && !PauseRequested && !Paused)
RequestEvents();
}
private void CompleteStreamProcessing()
{
_catalogEof = true;
}
private void DeliverEvent(EventStore.Core.Data.ResolvedEvent pair, float progress)
{
_deliveredEvents++;
EventRecord positionEvent = pair.OriginalEvent;
if (positionEvent.LogPosition > _limitingCommitPosition)
return;
var resolvedEvent = new ResolvedEvent(pair, null);
if (resolvedEvent.IsLinkToDeletedStream || resolvedEvent.IsStreamDeletedEvent)
return;
_publisher.Publish(
//TODO: publish both link and event data
new ReaderSubscriptionMessage.CommittedEventDistributed(
EventReaderCorrelationId, resolvedEvent,
_stopOnEof ? (long?) null : positionEvent.LogPosition, progress, source: GetType(),
preTagged:
CheckpointTag.FromByStreamPosition(
0, "", _catalogCurrentSequenceNumber, positionEvent.EventStreamId, positionEvent.EventNumber,
_limitingCommitPosition.Value)));
//TODO: consider passing phase from outside instead of using 0 (above)
}
public void Handle(ReaderSubscriptionManagement.SpoolStreamReading message)
{
EnsureLimitingCommitPositionSet(message.LimitingCommitPosition);
BeginReadStreamLength(message.StreamId);
EnqueueStreamForProcessing(message.StreamId, message.CatalogSequenceNumber);
}
private void BeginReadStreamLength(string streamId)
{
var requestId = _ioDispatcher.ReadBackward(
streamId, -1, 1, false, ReadAs, completed =>
{
_readLengthRequests.Remove(_dataReadRequestId);
switch (completed.Result)
{
case ReadStreamResult.AccessDenied:
SendNotAuthorized();
break;
case ReadStreamResult.NoStream:
DeliverStreamLength(streamId, 0);
break;
case ReadStreamResult.StreamDeleted:
DeliverStreamLength(streamId, 0);
break;
case ReadStreamResult.Success:
DeliverStreamLength(streamId, completed.LastEventNumber);
break;
default:
throw new NotSupportedException();
}
});
if (requestId != Guid.Empty)
_readLengthRequests.Add(requestId);
}
private void DeliverStreamLength(string streamId, int length)
{
_publisher.Publish(
//TODO: publish both link and event data
new ReaderSubscriptionMessage.EventReaderPartitionMeasured(EventReaderCorrelationId, streamId, length));
}
private void EnsureLimitingCommitPositionSet(long limitingCommitPosition)
{
if (_limitingCommitPosition != null && _limitingCommitPosition.GetValueOrDefault() != limitingCommitPosition)
throw new InvalidOperationException(
string.Format(
"ExternallyFedByStreamEventReader cannot be used with different limiting commit positions. "
+ "Currently set: {0}. New: {1}", _limitingCommitPosition, limitingCommitPosition));
_limitingCommitPosition = limitingCommitPosition;
}
public void Handle(ReaderSubscriptionManagement.CompleteSpooledStreamReading message)
{
CompleteStreamProcessing();
}
}
}
| |
// 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.Text;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.X509Certificates;
using X509IssuerSerial = System.Security.Cryptography.Xml.X509IssuerSerial;
namespace Internal.Cryptography
{
internal static class Helpers
{
public static byte[] CloneByteArray(this byte[] a)
{
return (byte[])(a.Clone());
}
/// <summary>
/// This is not just a convenience wrapper for Array.Resize(). In DEBUG builds, it forces the array to move in memory even if no resize is needed. This should be used by
/// helper methods that do anything of the form "call a native api once to get the estimated size, call it again to get the data and return the data in a byte[] array."
/// Sometimes, that data consist of a native data structure containing pointers to other parts of the block. Using such a helper to retrieve such a block results in an intermittent
/// AV. By using this helper, you make that AV repro every time.
/// </summary>
public static byte[] Resize(this byte[] a, int size)
{
Array.Resize(ref a, size);
#if DEBUG
a = a.CloneByteArray();
#endif
return a;
}
public static CmsRecipientCollection DeepCopy(this CmsRecipientCollection recipients)
{
CmsRecipientCollection recipientsCopy = new CmsRecipientCollection();
foreach (CmsRecipient recipient in recipients)
{
X509Certificate2 originalCert = recipient.Certificate;
X509Certificate2 certCopy = new X509Certificate2(originalCert.Handle);
CmsRecipient recipientCopy = new CmsRecipient(recipient.RecipientIdentifierType, certCopy);
recipientsCopy.Add(recipientCopy);
GC.KeepAlive(originalCert);
}
return recipientsCopy;
}
public static byte[] UnicodeToOctetString(this string s)
{
byte[] octets = new byte[2 * (s.Length + 1)];
Encoding.Unicode.GetBytes(s, 0, s.Length, octets, 0);
return octets;
}
public static string OctetStringToUnicode(this byte[] octets)
{
if (octets.Length < 2)
return string.Empty; // Desktop compat: 0-length byte array maps to string.empty. 1-length byte array gets passed to Marshal.PtrToStringUni() with who knows what outcome.
string s = Encoding.Unicode.GetString(octets, 0, octets.Length - 2);
return s;
}
public static X509Certificate2Collection GetStoreCertificates(StoreName storeName, StoreLocation storeLocation, bool openExistingOnly)
{
using (X509Store store = new X509Store())
{
OpenFlags flags = OpenFlags.ReadOnly | OpenFlags.IncludeArchived;
if (openExistingOnly)
flags |= OpenFlags.OpenExistingOnly;
store.Open(flags);
X509Certificate2Collection certificates = store.Certificates;
return certificates;
}
}
/// <summary>
/// Desktop compat: We do not complain about multiple matches. Just take the first one and ignore the rest.
/// </summary>
public static X509Certificate2 TryFindMatchingCertificate(this X509Certificate2Collection certs, SubjectIdentifier recipientIdentifier)
{
//
// Note: SubjectIdentifier has no public constructor so the only one that can construct this type is this assembly.
// Therefore, we trust that the string-ized byte array (serial or ski) in it is correct and canonicalized.
//
SubjectIdentifierType recipientIdentifierType = recipientIdentifier.Type;
switch (recipientIdentifierType)
{
case SubjectIdentifierType.IssuerAndSerialNumber:
{
X509IssuerSerial issuerSerial = (X509IssuerSerial)(recipientIdentifier.Value);
byte[] serialNumber = issuerSerial.SerialNumber.ToSerialBytes();
string issuer = issuerSerial.IssuerName;
foreach (X509Certificate2 candidate in certs)
{
byte[] candidateSerialNumber = candidate.GetSerialNumber();
if (AreByteArraysEqual(candidateSerialNumber, serialNumber) && candidate.Issuer == issuer)
return candidate;
}
}
break;
case SubjectIdentifierType.SubjectKeyIdentifier:
{
string skiString = (string)(recipientIdentifier.Value);
byte[] ski = skiString.ToSkiBytes();
foreach (X509Certificate2 cert in certs)
{
byte[] candidateSki = PkcsPal.Instance.GetSubjectKeyIdentifier(cert);
if (AreByteArraysEqual(ski, candidateSki))
return cert;
}
}
break;
default:
// RecipientInfo's can only be created by this package so if this an invalid type, it's the package's fault.
Debug.Fail($"Invalid recipientIdentifier type: {recipientIdentifierType}");
throw new CryptographicException();
}
return null;
}
private static bool AreByteArraysEqual(byte[] ba1, byte[] ba2)
{
if (ba1.Length != ba2.Length)
return false;
for (int i = 0; i < ba1.Length; i++)
{
if (ba1[i] != ba2[i])
return false;
}
return true;
}
/// <summary>
/// Asserts on bad or non-canonicalized input. Input must come from trusted sources.
///
/// Subject Key Identifier is string-ized as an upper case hex string. This format is part of the public api behavior and cannot be changed.
/// </summary>
private static byte[] ToSkiBytes(this string skiString)
{
return skiString.UpperHexStringToByteArray();
}
public static string ToSkiString(this byte[] skiBytes)
{
return skiBytes.ToUpperHexString();
}
/// <summary>
/// Asserts on bad or non-canonicalized input. Input must come from trusted sources.
///
/// Serial number is string-ized as a reversed upper case hex string. This format is part of the public api behavior and cannot be changed.
/// </summary>
private static byte[] ToSerialBytes(this string serialString)
{
byte[] ba = serialString.UpperHexStringToByteArray();
Array.Reverse(ba);
return ba;
}
public static string ToSerialString(this byte[] serialBytes)
{
serialBytes = serialBytes.CloneByteArray();
Array.Reverse(serialBytes);
return serialBytes.ToUpperHexString();
}
private static string ToUpperHexString(this byte[] ba)
{
StringBuilder sb = new StringBuilder(ba.Length * 2);
foreach (byte b in ba)
{
sb.Append(b.ToString("X2"));
}
return sb.ToString();
}
/// <summary>
/// Asserts on bad input. Input must come from trusted sources.
/// </summary>
private static byte[] UpperHexStringToByteArray(this string normalizedString)
{
Debug.Assert((normalizedString.Length & 0x1) == 0);
byte[] ba = new byte[normalizedString.Length / 2];
for (int i = 0; i < ba.Length; i++)
{
char c = normalizedString[i * 2];
byte b = (byte)(UpperHexCharToNybble(c) << 4);
c = normalizedString[i * 2 + 1];
b |= UpperHexCharToNybble(c);
ba[i] = b;
}
return ba;
}
/// <summary>
/// Asserts on bad input. Input must come from trusted sources.
/// </summary>
private static byte UpperHexCharToNybble(char c)
{
if (c >= '0' && c <= '9')
return (byte)(c - '0');
if (c >= 'A' && c <= 'F')
return (byte)(c - 'A' + 10);
Debug.Fail($"Invalid hex character: {c}");
throw new CryptographicException(); // This just keeps the compiler happy. We don't expect to reach this.
}
/// <summary>
/// Useful helper for "upgrading" well-known CMS attributes to type-specific objects such as Pkcs9DocumentName, Pkcs9DocumentDescription, etc.
/// </summary>
public static Pkcs9AttributeObject CreateBestPkcs9AttributeObjectAvailable(Oid oid, byte[] encodedAttribute)
{
Pkcs9AttributeObject attributeObject = new Pkcs9AttributeObject(oid, encodedAttribute);
switch (oid.Value)
{
case Oids.DocumentName:
attributeObject = Upgrade<Pkcs9DocumentName>(attributeObject);
break;
case Oids.DocumentDescription:
attributeObject = Upgrade<Pkcs9DocumentDescription>(attributeObject);
break;
case Oids.SigningTime:
attributeObject = Upgrade<Pkcs9SigningTime>(attributeObject);
break;
case Oids.ContentType:
attributeObject = Upgrade<Pkcs9ContentType>(attributeObject);
break;
case Oids.MessageDigest:
attributeObject = Upgrade<Pkcs9MessageDigest>(attributeObject);
break;
default:
break;
}
return attributeObject;
}
private static T Upgrade<T>(Pkcs9AttributeObject basicAttribute) where T : Pkcs9AttributeObject, new()
{
T enhancedAttribute = new T();
enhancedAttribute.CopyFrom(basicAttribute);
return enhancedAttribute;
}
}
}
| |
//
// Copyright (c) 2004-2017 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using System.Collections.Generic;
using NLog.Config;
using NLog.Internal;
using NLog.Layouts;
using NLog.Targets;
using System.Runtime.CompilerServices;
namespace NLog.UnitTests.LayoutRenderers
{
using System;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
public class CallSiteTests : NLogTestBase
{
#if !NETSTANDARD
[Fact]
public void HiddenAssemblyTest()
{
const string code = @"
namespace Foo
{
public class HiddenAssemblyLogger
{
public void LogDebug(NLog.Logger logger)
{
logger.Debug(""msg"");
}
}
}
";
var provider = new Microsoft.CSharp.CSharpCodeProvider();
var parameters = new System.CodeDom.Compiler.CompilerParameters();
// reference the NLog dll
parameters.ReferencedAssemblies.Add("NLog.dll");
// the assembly should be generated in memory
parameters.GenerateInMemory = true;
// generate a dll instead of an executable
parameters.GenerateExecutable = false;
// compile code and generate assembly
System.CodeDom.Compiler.CompilerResults results = provider.CompileAssemblyFromSource(parameters, code);
Assert.False(results.Errors.HasErrors, "Compiler errors: " + string.Join(";", results.Errors));
// create nlog configuration
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${callsite} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
// create logger
Logger logger = LogManager.GetLogger("A");
// load HiddenAssemblyLogger type
Assembly compiledAssembly = results.CompiledAssembly;
Type hiddenAssemblyLoggerType = compiledAssembly.GetType("Foo.HiddenAssemblyLogger");
Assert.NotNull(hiddenAssemblyLoggerType);
// load methodinfo
MethodInfo logDebugMethod = hiddenAssemblyLoggerType.GetMethod("LogDebug");
Assert.NotNull(logDebugMethod);
// instantiate the HiddenAssemblyLogger from previously generated assembly
object instance = Activator.CreateInstance(hiddenAssemblyLoggerType);
// Add the previously generated assembly to the "blacklist"
LogManager.AddHiddenAssembly(compiledAssembly);
// call the log method
logDebugMethod.Invoke(instance, new object[] { logger });
MethodBase currentMethod = MethodBase.GetCurrentMethod();
AssertDebugLastMessage("debug", currentMethod.DeclaringType.FullName + "." + currentMethod.Name + " msg");
}
#endif
#if !DEBUG
[Fact(Skip = "RELEASE not working, only DEBUG")]
#else
[Fact]
#endif
public void LineNumberTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${callsite:filename=true} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
#if !NET4_5 && !MONO
#line 100000
#endif
logger.Debug("msg");
var linenumber = GetPrevLineNumber();
string lastMessage = GetDebugLastMessage("debug");
// There's a difference in handling line numbers between .NET and Mono
// We're just interested in checking if it's above 100000
Assert.True(lastMessage.IndexOf("callsitetests.cs:" + linenumber, StringComparison.OrdinalIgnoreCase) >= 0, "Invalid line number. Expected prefix of 10000, got: " + lastMessage);
#if !NET4_5 && !MONO
#line default
#endif
}
[Fact]
public void MethodNameTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${callsite} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("msg");
MethodBase currentMethod = MethodBase.GetCurrentMethod();
AssertDebugLastMessage("debug", currentMethod.DeclaringType.FullName + "." + currentMethod.Name + " msg");
}
[Fact]
public void MethodNameInChainTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='debug' type='Debug' layout='${message}' />
<target name='debug2' type='Debug' layout='${callsite} ${message}' />
</targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug,debug2' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("msg2");
MethodBase currentMethod = MethodBase.GetCurrentMethod();
AssertDebugLastMessage("debug2", currentMethod.DeclaringType.FullName + "." + currentMethod.Name + " msg2");
}
[Fact]
public void ClassNameTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=false} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("msg");
AssertDebugLastMessage("debug", "NLog.UnitTests.LayoutRenderers.CallSiteTests msg");
}
[Fact]
public void ClassNameTestWithoutNamespace()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=false:includeNamespace=false} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("msg");
AssertDebugLastMessage("debug", "CallSiteTests msg");
}
[Fact]
public void ClassNameWithPaddingTestPadLeftAlignLeftTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=false:padding=3:fixedlength=true} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("msg");
MethodBase currentMethod = MethodBase.GetCurrentMethod();
AssertDebugLastMessage("debug", currentMethod.DeclaringType.FullName.Substring(0, 3) + " msg");
}
[Fact]
public void ClassNameWithPaddingTestPadLeftAlignRightTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=false:padding=3:fixedlength=true:alignmentOnTruncation=right} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("msg");
MethodBase currentMethod = MethodBase.GetCurrentMethod();
var typeName = currentMethod.DeclaringType.FullName;
AssertDebugLastMessage("debug", typeName.Substring(typeName.Length - 3) + " msg");
}
[Fact]
public void ClassNameWithPaddingTestPadRightAlignLeftTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=false:padding=-3:fixedlength=true:alignmentOnTruncation=left} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("msg");
MethodBase currentMethod = MethodBase.GetCurrentMethod();
AssertDebugLastMessage("debug", currentMethod.DeclaringType.FullName.Substring(0, 3) + " msg");
}
[Fact]
public void ClassNameWithPaddingTestPadRightAlignRightTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=false:padding=-3:fixedlength=true:alignmentOnTruncation=right} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("msg");
MethodBase currentMethod = MethodBase.GetCurrentMethod();
var typeName = currentMethod.DeclaringType.FullName;
AssertDebugLastMessage("debug", typeName.Substring(typeName.Length - 3) + " msg");
}
[Fact]
public void MethodNameWithPaddingTestPadLeftAlignLeftTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${callsite:classname=false:methodname=true:padding=16:fixedlength=true} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("msg");
AssertDebugLastMessage("debug", "MethodNameWithPa msg");
}
[Fact]
public void MethodNameWithPaddingTestPadLeftAlignRightTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${callsite:classname=false:methodname=true:padding=16:fixedlength=true:alignmentOnTruncation=right} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("msg");
AssertDebugLastMessage("debug", "ftAlignRightTest msg");
}
[Fact]
public void MethodNameWithPaddingTestPadRightAlignLeftTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${callsite:classname=false:methodname=true:padding=-16:fixedlength=true:alignmentOnTruncation=left} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("msg");
AssertDebugLastMessage("debug", "MethodNameWithPa msg");
}
[Fact]
public void MethodNameWithPaddingTestPadRightAlignRightTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${callsite:classname=false:methodname=true:padding=-16:fixedlength=true:alignmentOnTruncation=right} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("msg");
AssertDebugLastMessage("debug", "htAlignRightTest msg");
}
[Fact]
public void GivenSkipFrameNotDefined_WhenLogging_ThenLogFirstUserStackFrame()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${callsite} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("msg");
AssertDebugLastMessage("debug", "NLog.UnitTests.LayoutRenderers.CallSiteTests.GivenSkipFrameNotDefined_WhenLogging_ThenLogFirstUserStackFrame msg");
}
#if !DEBUG
[Fact(Skip = "RELEASE not working, only DEBUG")]
#else
[Fact]
#endif
public void GivenOneSkipFrameDefined_WhenLogging_ShouldSkipOneUserStackFrame()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${callsite:skipframes=1} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
Action action = () => logger.Debug("msg");
action.Invoke();
AssertDebugLastMessage("debug", "NLog.UnitTests.LayoutRenderers.CallSiteTests.GivenOneSkipFrameDefined_WhenLogging_ShouldSkipOneUserStackFrame msg");
}
#if MONO
[Fact(Skip = "Not working under MONO - not sure if unit test is wrong, or the code")]
#else
[Fact]
#endif
public void CleanMethodNamesOfAnonymousDelegatesTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${callsite:ClassName=false:CleanNamesOfAnonymousDelegates=true}' /></targets>
<rules>
<logger name='*' levels='Fatal' writeTo='debug' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
bool done = false;
ThreadPool.QueueUserWorkItem(
state =>
{
logger.Fatal("message");
done = true;
},
null);
while (done == false)
{
Thread.Sleep(10);
}
if (done == true)
{
AssertDebugLastMessage("debug", "CleanMethodNamesOfAnonymousDelegatesTest");
}
}
#if MONO
[Fact(Skip = "Not working under MONO - not sure if unit test is wrong, or the code")]
#else
[Fact]
#endif
public void DontCleanMethodNamesOfAnonymousDelegatesTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${callsite:ClassName=false:CleanNamesOfAnonymousDelegates=false}' /></targets>
<rules>
<logger name='*' levels='Fatal' writeTo='debug' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
bool done = false;
ThreadPool.QueueUserWorkItem(
state =>
{
logger.Fatal("message");
done = true;
},
null);
while (done == false)
{
Thread.Sleep(10);
}
if (done == true)
{
string lastMessage = GetDebugLastMessage("debug");
Assert.StartsWith("<DontCleanMethodNamesOfAnonymousDelegatesTest>", lastMessage);
}
}
#if MONO
[Fact(Skip = "Not working under MONO - not sure if unit test is wrong, or the code")]
#else
[Fact]
#endif
public void CleanClassNamesOfAnonymousDelegatesTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${callsite:ClassName=true:MethodName=false:CleanNamesOfAnonymousDelegates=true}' /></targets>
<rules>
<logger name='*' levels='Fatal' writeTo='debug' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
bool done = false;
ThreadPool.QueueUserWorkItem(
state =>
{
logger.Fatal("message");
done = true;
},
null);
while (done == false)
{
Thread.Sleep(10);
}
if (done == true)
{
AssertDebugLastMessage("debug", "NLog.UnitTests.LayoutRenderers.CallSiteTests");
}
}
#if MONO
[Fact(Skip = "Not working under MONO - not sure if unit test is wrong, or the code")]
#else
[Fact]
#endif
public void DontCleanClassNamesOfAnonymousDelegatesTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${callsite:ClassName=true:MethodName=false:CleanNamesOfAnonymousDelegates=false}' /></targets>
<rules>
<logger name='*' levels='Fatal' writeTo='debug' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
bool done = false;
ThreadPool.QueueUserWorkItem(
state =>
{
logger.Fatal("message");
done = true;
},
null);
while (done == false)
{
Thread.Sleep(10);
}
if (done == true)
{
string lastMessage = GetDebugLastMessage("debug");
Assert.Contains("+<>", lastMessage);
}
}
[Fact]
public void When_Wrapped_Ignore_Wrapper_Methods_In_Callstack()
{
//namespace en name of current method
const string currentMethodFullName = "NLog.UnitTests.LayoutRenderers.CallSiteTests.When_Wrapped_Ignore_Wrapper_Methods_In_Callstack";
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${callsite}|${message}' /></targets>
<rules>
<logger name='*' levels='Warn' writeTo='debug' />
</rules>
</nlog>");
var logger = LogManager.GetLogger("A");
logger.Warn("direct");
AssertDebugLastMessage("debug", $"{currentMethodFullName}|direct");
LoggerTests.BaseWrapper wrappedLogger = new LoggerTests.MyWrapper();
wrappedLogger.Log("wrapped");
AssertDebugLastMessage("debug", $"{currentMethodFullName}|wrapped");
}
[Fact]
public void CheckStackTraceUsageForTwoRules()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='debug' type='Debug' layout='${message}' />
<target name='debug2' type='Debug' layout='${callsite} ${message}' />
</targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
<logger name='*' minlevel='Debug' writeTo='debug2' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("msg");
AssertDebugLastMessage("debug2", "NLog.UnitTests.LayoutRenderers.CallSiteTests.CheckStackTraceUsageForTwoRules msg");
}
[Fact]
public void CheckStackTraceUsageForTwoRules_chained()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='debug' type='Debug' layout='${message}' />
<target name='debug2' type='Debug' layout='${callsite} ${message}' />
</targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
<logger name='*' minlevel='Debug' writeTo='debug,debug2' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("msg");
AssertDebugLastMessage("debug2", "NLog.UnitTests.LayoutRenderers.CallSiteTests.CheckStackTraceUsageForTwoRules_chained msg");
}
[Fact]
public void CheckStackTraceUsageForMultipleRules()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='debug' type='Debug' layout='${message}' />
<target name='debug2' type='Debug' layout='${callsite} ${message}' />
</targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
<logger name='*' minlevel='Debug' writeTo='debug' />
<logger name='*' minlevel='Debug' writeTo='debug,debug2' />
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("msg");
AssertDebugLastMessage("debug2", "NLog.UnitTests.LayoutRenderers.CallSiteTests.CheckStackTraceUsageForMultipleRules msg");
}
#region Compositio unit test
[Fact]
public void When_WrappedInCompsition_Ignore_Wrapper_Methods_In_Callstack()
{
//namespace en name of current method
const string currentMethodFullName = "NLog.UnitTests.LayoutRenderers.CallSiteTests.When_WrappedInCompsition_Ignore_Wrapper_Methods_In_Callstack";
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${callsite}|${message}' /></targets>
<rules>
<logger name='*' levels='Warn' writeTo='debug' />
</rules>
</nlog>");
var logger = LogManager.GetLogger("A");
logger.Warn("direct");
AssertDebugLastMessage("debug", $"{currentMethodFullName}|direct");
CompositeWrapper wrappedLogger = new CompositeWrapper();
wrappedLogger.Log("wrapped");
AssertDebugLastMessage("debug", $"{currentMethodFullName}|wrapped");
}
#if NET3_5 || NET4_0
[Fact(Skip = "NET3_5 + NET4_0 not supporting async callstack")]
#else
[Fact]
#endif
public void Show_correct_method_with_async()
{
//namespace en name of current method
const string currentMethodFullName = "NLog.UnitTests.LayoutRenderers.CallSiteTests.AsyncMethod";
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${callsite}|${message}' /></targets>
<rules>
<logger name='*' levels='Warn' writeTo='debug' />
</rules>
</nlog>");
AsyncMethod().Wait();
AssertDebugLastMessage("debug", $"{currentMethodFullName}|direct");
}
private async Task AsyncMethod()
{
var logger = LogManager.GetCurrentClassLogger();
logger.Warn("direct");
var reader = new StreamReader(new MemoryStream(new byte[0]));
await reader.ReadLineAsync();
}
#if NET3_5 || NET4_0
[Fact(Skip = "NET3_5 + NET4_0 not supporting async callstack")]
#else
[Fact]
#endif
public void Show_correct_method_with_async2()
{
//namespace en name of current method
const string currentMethodFullName = "NLog.UnitTests.LayoutRenderers.CallSiteTests.AsyncMethod2b";
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${callsite}|${message}' /></targets>
<rules>
<logger name='*' levels='Warn' writeTo='debug' />
</rules>
</nlog>");
AsyncMethod2a().Wait();
AssertDebugLastMessage("debug", $"{currentMethodFullName}|direct");
}
private async Task AsyncMethod2a()
{
await AsyncMethod2b();
}
private async Task AsyncMethod2b()
{
var logger = LogManager.GetCurrentClassLogger();
logger.Warn("direct");
var reader = new StreamReader(new MemoryStream(new byte[0]));
await reader.ReadLineAsync();
}
#if NET3_5
[Fact(Skip = "NET3_5 not supporting async callstack")]
#elif !DEBUG
[Fact(Skip = "RELEASE not working, only DEBUG")]
#else
[Fact]
#endif
public void Show_correct_method_with_async3()
{
//namespace en name of current method
const string currentMethodFullName = "NLog.UnitTests.LayoutRenderers.CallSiteTests.AsyncMethod3b";
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${callsite}|${message}' /></targets>
<rules>
<logger name='*' levels='Warn' writeTo='debug' />
</rules>
</nlog>");
AsyncMethod3a().Wait();
AssertDebugLastMessage("debug", $"{currentMethodFullName}|direct");
}
private async Task AsyncMethod3a()
{
var reader = new StreamReader(new MemoryStream(new byte[0]));
await reader.ReadLineAsync();
AsyncMethod3b();
}
private void AsyncMethod3b()
{
var logger = LogManager.GetCurrentClassLogger();
logger.Warn("direct");
}
public async Task<IEnumerable<string>> AsyncMethod4()
{
NLog.Logger logger = NLog.LogManager.GetLogger("AnnonTest");
logger.Info("Direct, async method");
return await Task.FromResult(new string[] { "value1", "value2" });
}
#if NET3_5 || NET4_0
[Fact(Skip = "NET3_5 + NET4_0 not supporting async callstack")]
#elif MONO
[Fact(Skip = "Not working under MONO - not sure if unit test is wrong, or the code")]
#else
[Fact]
#endif
public void Show_correct_method_with_async4()
{
//namespace en name of current method
const string currentMethodFullName = "NLog.UnitTests.LayoutRenderers.CallSiteTests.AsyncMethod4";
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${callsite}|${message}' /></targets>
<rules>
<logger name='*' levels='Info' writeTo='debug' />
</rules>
</nlog>");
AsyncMethod4().Wait();
AssertDebugLastMessage("debug", $"{currentMethodFullName}|Direct, async method");
}
#if NET3_5 || NET4_0
[Fact(Skip = "NET3_5 + NET4_0 not supporting async callstack")]
#elif MONO
[Fact(Skip = "Not working under MONO - not sure if unit test is wrong, or the code")]
#else
[Fact]
#endif
public void CallSiteShouldWorkForAsyncMethodsWithReturnValue()
{
var callSite = GetAsyncCallSite().GetAwaiter().GetResult();
Assert.Equal("NLog.UnitTests.LayoutRenderers.CallSiteTests.GetAsyncCallSite", callSite);
}
public async Task<string> GetAsyncCallSite()
{
Type loggerType = typeof(Logger);
var stacktrace = StackTraceUsageUtils.GetWriteStackTrace(loggerType);
var index = LoggerImpl.FindCallingMethodOnStackTrace(stacktrace, loggerType);
var logEvent = new LogEventInfo(LogLevel.Error, "logger1", "message1");
logEvent.SetStackTrace(stacktrace, index);
await Task.Delay(0);
Layout l = "${callsite}";
var callSite = l.Render(logEvent);
return callSite;
}
#if !DEBUG
[Fact(Skip = "RELEASE not working, only DEBUG")]
#else
[Fact]
#endif
public void Show_correct_method_for_moveNext()
{
//namespace en name of current method
const string currentMethodFullName = "NLog.UnitTests.LayoutRenderers.CallSiteTests.MoveNext";
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${callsite}|${message}' /></targets>
<rules>
<logger name='*' levels='Warn' writeTo='debug' />
</rules>
</nlog>");
MoveNext();
AssertDebugLastMessage("debug", $"{currentMethodFullName}|direct");
}
private void MoveNext()
{
var logger = LogManager.GetCurrentClassLogger();
logger.Warn("direct");
}
public class CompositeWrapper
{
private readonly MyWrapper wrappedLogger;
public CompositeWrapper()
{
wrappedLogger = new MyWrapper();
}
[MethodImpl(MethodImplOptions.NoInlining)]
public void Log(string what)
{
wrappedLogger.Log(typeof(CompositeWrapper), what);
}
}
public abstract class BaseWrapper
{
public void Log(string what)
{
InternalLog(typeof(BaseWrapper), what);
}
public void Log(Type type, string what) //overloaded with type for composition
{
InternalLog(type, what);
}
protected abstract void InternalLog(Type type, string what);
}
public class MyWrapper : BaseWrapper
{
private readonly ILogger wrapperLogger;
public MyWrapper()
{
wrapperLogger = LogManager.GetLogger("WrappedLogger");
}
protected override void InternalLog(Type type, string what) //added type for composition
{
LogEventInfo info = new LogEventInfo(LogLevel.Warn, wrapperLogger.Name, what);
// Provide BaseWrapper as wrapper type.
// Expected: UserStackFrame should point to the method that calls a
// method of BaseWrapper.
wrapperLogger.Log(type, info);
}
}
#endregion
private class MyLogger : Logger
{
}
[Fact]
public void CallsiteBySubclass_interface()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=true} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("mylogger", typeof(MyLogger));
Assert.True(logger is MyLogger, "logger isn't MyLogger");
logger.Debug("msg");
AssertDebugLastMessage("debug", "NLog.UnitTests.LayoutRenderers.CallSiteTests.CallsiteBySubclass_interface msg");
}
[Fact]
public void CallsiteBySubclass_mylogger()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=true} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
MyLogger logger = LogManager.GetLogger("mylogger", typeof(MyLogger)) as MyLogger;
Assert.NotNull(logger);
logger.Debug("msg");
AssertDebugLastMessage("debug", "NLog.UnitTests.LayoutRenderers.CallSiteTests.CallsiteBySubclass_mylogger msg");
}
[Fact]
public void CallsiteBySubclass_logger()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=true} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
Logger logger = LogManager.GetLogger("mylogger", typeof(MyLogger)) as Logger;
Assert.NotNull(logger);
logger.Debug("msg");
AssertDebugLastMessage("debug", "NLog.UnitTests.LayoutRenderers.CallSiteTests.CallsiteBySubclass_logger msg");
}
[Fact]
public void Should_preserve_correct_callsite_information()
{
// Step 1. Create configuration object
var config = new LoggingConfiguration();
// Step 2. Create targets and add them to the configuration
var target = new MemoryTarget();
var wrapper = new NLog.Targets.Wrappers.AsyncTargetWrapper(target) { TimeToSleepBetweenBatches = 0 };
config.AddTarget("target", wrapper);
// Step 3. Set target properties
target.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}";
// Step 4. Define rules
var rule = new LoggingRule("*", LogLevel.Debug, wrapper);
config.LoggingRules.Add(rule);
LogManager.Configuration = config;
var factory = new NLogFactory(config);
var logger = factory.Create("MyLoggerName");
WriteLogMessage(logger);
LogManager.Flush();
var logMessage = target.Logs[0];
Assert.Contains("MyLoggerName", logMessage);
// See that LogManager.ReconfigExistingLoggers() is able to upgrade the Logger
target.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${callsite} ${message}";
LogManager.ReconfigExistingLoggers();
WriteLogMessage(logger);
LogManager.Flush();
logMessage = target.Logs[1];
Assert.Contains("CallSiteTests.WriteLogMessage", logMessage);
// See that LogManager.ReconfigExistingLoggers() is able to upgrade the Logger
target.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${callsite} ${message} ThreadId=${threadid}";
LogManager.ReconfigExistingLoggers();
WriteLogMessage(logger);
LogManager.Flush();
logMessage = target.Logs[2];
Assert.Contains("ThreadId=" + Thread.CurrentThread.ManagedThreadId.ToString(), logMessage);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void WriteLogMessage(NLogLogger logger)
{
logger.Debug("something");
}
/// <summary>
///
/// </summary>
public class NLogFactory
{
internal const string defaultConfigFileName = "nlog.config";
/// <summary>
/// Initializes a new instance of the <see cref="NLogFactory" /> class.
/// </summary>
/// <param name="loggingConfiguration"> The NLog Configuration </param>
public NLogFactory(LoggingConfiguration loggingConfiguration)
{
LogManager.Configuration = loggingConfiguration;
}
/// <summary>
/// Creates a logger with specified <paramref name="name" />.
/// </summary>
/// <param name="name"> The name. </param>
/// <returns> </returns>
public NLogLogger Create(string name)
{
var log = LogManager.GetLogger(name);
return new NLogLogger(log);
}
}
/// <summary>
/// If some calls got inlined, we can't find LoggerType anymore. We should fallback if loggerType can be found
///
/// Example of those stacktraces:
/// at NLog.LoggerImpl.Write(Type loggerType, TargetWithFilterChain targets, LogEventInfo logEvent, LogFactory factory) in c:\temp\NLog\src\NLog\LoggerImpl.cs:line 68
/// at NLog.UnitTests.LayoutRenderers.NLogLogger.ErrorWithoutLoggerTypeArg(String message) in c:\temp\NLog\tests\NLog.UnitTests\LayoutRenderers\CallSiteTests.cs:line 989
/// at NLog.UnitTests.LayoutRenderers.CallSiteTests.TestCallsiteWhileCallsGotInlined() in c:\temp\NLog\tests\NLog.UnitTests\LayoutRenderers\CallSiteTests.cs:line 893
///
/// </summary>
[Fact]
public void CallSiteShouldWorkEvenInlined()
{
Type loggerType = typeof(Logger);
var stacktrace = StackTraceUsageUtils.GetWriteStackTrace(loggerType);
var index = LoggerImpl.FindCallingMethodOnStackTrace(stacktrace, loggerType);
var logEvent = new LogEventInfo(LogLevel.Error, "logger1", "message1");
logEvent.SetStackTrace(stacktrace, index);
Layout l = "${callsite}";
var callSite = l.Render(logEvent);
Assert.Equal("NLog.UnitTests.LayoutRenderers.CallSiteTests.CallSiteShouldWorkEvenInlined", callSite);
}
[Fact]
public void LogAfterAwait_CleanNamesOfAsyncContinuationsIsTrue_ShouldCleanMethodName()
{
// name of the logging method
const string callsiteMethodName = "AsyncMethod5";
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${callsite:classname=false:cleannamesofasynccontinuations=true}' /></targets>
<rules>
<logger name='*' levels='Debug' writeTo='debug' />
</rules>
</nlog>");
AsyncMethod5().GetAwaiter().GetResult();
AssertDebugLastMessage("debug", callsiteMethodName);
}
[Fact]
public void LogAfterAwait_CleanNamesOfAsyncContinuationsIsTrue_ShouldCleanClassName()
{
// full name of the logging method
const string callsiteMethodFullName = "NLog.UnitTests.LayoutRenderers.CallSiteTests.AsyncMethod5";
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${callsite:classname=true:includenamespace=true:cleannamesofasynccontinuations=true}' /></targets>
<rules>
<logger name='*' levels='Debug' writeTo='debug' />
</rules>
</nlog>");
AsyncMethod5().GetAwaiter().GetResult();
AssertDebugLastMessage("debug", callsiteMethodFullName);
}
[Fact]
public void LogAfterAwait_CleanNamesOfAsyncContinuationsIsFalse_ShouldNotCleanNames()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${callsite:includenamespace=true:cleannamesofasynccontinuations=false}' /></targets>
<rules>
<logger name='*' levels='Debug' writeTo='debug' />
</rules>
</nlog>");
AsyncMethod5().GetAwaiter().GetResult();
if (IsTravis())
{
Console.WriteLine("[SKIP] LogAfterAwait_CleanNamesOfAsyncContinuationsIsFalse_ShouldNotCleanNames - test is unstable on Travis");
return;
}
AssertDebugLastMessageContains("debug", "NLog.UnitTests.LayoutRenderers.CallSiteTests");
AssertDebugLastMessageContains("debug", "MoveNext");
AssertDebugLastMessageContains("debug", "d__");
}
private async Task AsyncMethod5()
{
await AMinimalAsyncMethod();
var logger = LogManager.GetCurrentClassLogger();
logger.Debug("dude");
}
private async Task AMinimalAsyncMethod()
{
await Task.Run(() => { });
}
/// <summary>
/// Implementation of <see cref="ILogger" /> for NLog.
/// </summary>
public class NLogLogger
{
/// <summary>
/// Initializes a new instance of the <see cref="NLogLogger" /> class.
/// </summary>
/// <param name="logger"> The logger. </param>
public NLogLogger(Logger logger)
{
Logger = logger;
}
/// <summary>
/// Gets or sets the logger.
/// </summary>
/// <value> The logger. </value>
protected internal Logger Logger { get; set; }
/// <summary>
/// Returns a <see cref="string" /> that represents this instance.
/// </summary>
/// <returns> A <see cref="string" /> that represents this instance. </returns>
public override string ToString()
{
return Logger.ToString();
}
/// <summary>
/// Logs a debug message.
/// </summary>
/// <param name="message"> The message to log </param>
public void Debug(string message)
{
Log(LogLevel.Debug, message);
}
public void Log(LogLevel logLevel, string message)
{
Logger.Log(typeof(NLogLogger), new LogEventInfo(logLevel, Logger.Name, message));
}
}
}
}
| |
/* ====================================================================
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.
==================================================================== */
namespace NPOI.SS.Formula.Functions
{
using System;
using NPOI.SS.Formula.Eval;
using System.Diagnostics;
/**
* Implementation for the Excel function INDEX
*
* Syntax : <br/>
* INDEX ( reference, row_num[, column_num [, area_num]])<br/>
* INDEX ( array, row_num[, column_num])
* <table border="0" cellpAdding="1" cellspacing="0" summary="Parameter descriptions">
* <tr><th>reference</th><td>typically an area reference, possibly a union of areas</td></tr>
* <tr><th>array</th><td>a literal array value (currently not supported)</td></tr>
* <tr><th>row_num</th><td>selects the row within the array or area reference</td></tr>
* <tr><th>column_num</th><td>selects column within the array or area reference. default Is 1</td></tr>
* <tr><th>area_num</th><td>used when reference Is a union of areas</td></tr>
* </table>
*
* @author Josh Micich
*/
internal class Index : Function2Arg, Function3Arg, Function4Arg
{
public ValueEval Evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0, ValueEval arg1)
{
//AreaEval reference = ConvertFirstArg(arg0);
//bool colArgWasPassed = false;
//int columnIx = 0;
//try
//{
// int rowIx = ResolveIndexArg(arg1, srcRowIndex, srcColumnIndex);
// return GetValueFromArea(reference, rowIx, columnIx, colArgWasPassed, srcRowIndex, srcColumnIndex);
//}
//catch (EvaluationException e)
//{
// return e.GetErrorEval();
//}
TwoDEval reference = ConvertFirstArg(arg0);
int columnIx = 0;
try
{
int rowIx = ResolveIndexArg(arg1, srcRowIndex, srcColumnIndex);
if (!reference.IsColumn)
{
if (!reference.IsRow)
{
// always an error with 2-D area refs
// Note - the type of error changes if the pRowArg is negative
return ErrorEval.REF_INVALID;
}
// When the two-arg version of INDEX() has been invoked and the reference
// is a single column ref, the row arg seems to get used as the column index
columnIx = rowIx;
rowIx = 0;
}
return GetValueFromArea(reference, rowIx, columnIx);
}
catch (EvaluationException e)
{
return e.GetErrorEval();
}
}
public ValueEval Evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0, ValueEval arg1,
ValueEval arg2)
{
//AreaEval reference = ConvertFirstArg(arg0);
//bool colArgWasPassed = true;
//try
//{
// int columnIx = ResolveIndexArg(arg2, srcRowIndex, srcColumnIndex);
// int rowIx = ResolveIndexArg(arg1, srcRowIndex, srcColumnIndex);
// return GetValueFromArea(reference, rowIx, columnIx, colArgWasPassed, srcRowIndex, srcColumnIndex);
//}
//catch (EvaluationException e)
//{
// return e.GetErrorEval();
//}
TwoDEval reference = ConvertFirstArg(arg0);
try
{
int columnIx = ResolveIndexArg(arg2, srcRowIndex, srcColumnIndex);
int rowIx = ResolveIndexArg(arg1, srcRowIndex, srcColumnIndex);
return GetValueFromArea(reference, rowIx, columnIx);
}
catch (EvaluationException e)
{
return e.GetErrorEval();
}
}
public ValueEval Evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0, ValueEval arg1,
ValueEval arg2, ValueEval arg3)
{
throw new Exception("Incomplete code"
+ " - don't know how to support the 'area_num' parameter yet)");
// Excel expression might look like thIs "INDEX( (A1:B4, C3:D6, D2:E5 ), 1, 2, 3)
// In thIs example, the 3rd area would be used i.e. D2:E5, and the overall result would be E2
// Token array might be encoded like thIs: MemAreaPtg, AreaPtg, AreaPtg, UnionPtg, UnionPtg, ParenthesesPtg
// The formula parser doesn't seem to support thIs yet. Not sure if the evaluator does either
}
private static TwoDEval ConvertFirstArg(ValueEval arg0)
{
ValueEval firstArg = arg0;
if (firstArg is RefEval)
{
// Convert to area ref for simpler code in getValueFromArea()
return ((RefEval)firstArg).Offset(0, 0, 0, 0);
}
if ((firstArg is TwoDEval))
{
return (TwoDEval)firstArg;
}
// else the other variation of thIs function takes an array as the first argument
// it seems like interface 'ArrayEval' does not even exIst yet
throw new Exception("Incomplete code - cannot handle first arg of type ("
+ firstArg.GetType().Name + ")");
}
public ValueEval Evaluate(ValueEval[] args, int srcRowIndex, int srcColumnIndex)
{
switch (args.Length)
{
case 2:
return Evaluate(srcRowIndex, srcColumnIndex, args[0], args[1]);
case 3:
return Evaluate(srcRowIndex, srcColumnIndex, args[0], args[1], args[2]);
case 4:
return Evaluate(srcRowIndex, srcColumnIndex, args[0], args[1], args[2], args[3]);
}
return ErrorEval.VALUE_INVALID;
}
private static ValueEval GetValueFromArea(TwoDEval ae, int pRowIx, int pColumnIx)
{
Debug.Assert(pRowIx >= 0);
Debug.Assert(pColumnIx >= 0);
TwoDEval result = ae;
if (pRowIx != 0)
{
// Slightly irregular logic for bounds checking errors
if (pRowIx > ae.Height)
{
// high bounds check fail gives #REF! if arg was explicitly passed
throw new EvaluationException(ErrorEval.REF_INVALID);
}
result = result.GetRow(pRowIx - 1);
}
if (pColumnIx != 0)
{
// Slightly irregular logic for bounds checking errors
if (pColumnIx > ae.Width)
{
// high bounds check fail gives #REF! if arg was explicitly passed
throw new EvaluationException(ErrorEval.REF_INVALID);
}
result = result.GetColumn(pColumnIx - 1);
}
return result;
}
/**
* @param colArgWasPassed <c>false</c> if the INDEX argument lIst had just 2 items
* (exactly 1 comma). If anything Is passed for the <c>column_num</c> argument
* (including {@link BlankEval} or {@link MIssingArgEval}) this parameter will be
* <c>true</c>. ThIs parameter is needed because error codes are slightly
* different when only 2 args are passed.
*/
[Obsolete]
private static ValueEval GetValueFromArea(AreaEval ae, int pRowIx, int pColumnIx,
bool colArgWasPassed, int srcRowIx, int srcColIx)
{
bool rowArgWasEmpty = pRowIx == 0;
bool colArgWasEmpty = pColumnIx == 0;
int rowIx;
int columnIx;
// when the area ref Is a single row or a single column,
// there are special rules for conversion of rowIx and columnIx
if (ae.IsRow)
{
if (ae.IsColumn)
{
// single cell ref
rowIx = rowArgWasEmpty ? 0 : pRowIx - 1;
columnIx = colArgWasEmpty ? 0 : pColumnIx - 1;
}
else
{
if (colArgWasPassed)
{
rowIx = rowArgWasEmpty ? 0 : pRowIx - 1;
columnIx = pColumnIx - 1;
}
else
{
// special case - row arg seems to Get used as the column index
rowIx = 0;
// transfer both the index value and the empty flag from 'row' to 'column':
columnIx = pRowIx - 1;
colArgWasEmpty = rowArgWasEmpty;
}
}
}
else if (ae.IsColumn)
{
if (rowArgWasEmpty)
{
rowIx = srcRowIx - ae.FirstRow;
}
else
{
rowIx = pRowIx - 1;
}
if (colArgWasEmpty)
{
columnIx = 0;
}
else
{
columnIx = colArgWasEmpty ? 0 : pColumnIx - 1;
}
}
else
{
// ae Is an area (not single row or column)
if (!colArgWasPassed)
{
// always an error with 2-D area refs
// Note - the type of error Changes if the pRowArg is negative
throw new EvaluationException(pRowIx < 0 ? ErrorEval.VALUE_INVALID : ErrorEval.REF_INVALID);
}
// Normal case - area ref Is 2-D, and both index args were provided
// if either arg Is missing (or blank) the logic is similar to OperandResolver.getSingleValue()
if (rowArgWasEmpty)
{
rowIx = srcRowIx - ae.FirstRow;
}
else
{
rowIx = pRowIx - 1;
}
if (colArgWasEmpty)
{
columnIx = srcColIx - ae.FirstColumn;
}
else
{
columnIx = pColumnIx - 1;
}
}
int width = ae.Width;
int height = ae.Height;
// Slightly irregular logic for bounds checking errors
if (!rowArgWasEmpty && rowIx >= height || !colArgWasEmpty && columnIx >= width)
{
// high bounds check fail gives #REF! if arg was explicitly passed
throw new EvaluationException(ErrorEval.REF_INVALID);
}
if (rowIx < 0 || columnIx < 0 || rowIx >= height || columnIx >= width)
{
throw new EvaluationException(ErrorEval.VALUE_INVALID);
}
return ae.GetRelativeValue(rowIx, columnIx);
}
/**
* @param arg a 1-based index.
* @return the Resolved 1-based index. Zero if the arg was missing or blank
* @throws EvaluationException if the arg Is an error value evaluates to a negative numeric value
*/
private static int ResolveIndexArg(ValueEval arg, int srcCellRow, int srcCellCol)
{
ValueEval ev = OperandResolver.GetSingleValue(arg, srcCellRow, srcCellCol);
if (ev == MissingArgEval.instance)
{
return 0;
}
if (ev == BlankEval.instance)
{
return 0;
}
int result = OperandResolver.CoerceValueToInt(ev);
if (result < 0)
{
throw new EvaluationException(ErrorEval.VALUE_INVALID);
}
return result;
}
}
}
| |
//----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------------------
namespace System.ServiceModel.ComIntegration
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.AccessControl;
using System.Security.Permissions;
using System.Security.Principal;
using System.ServiceModel;
using System.ServiceModel.Diagnostics;
using SafeCloseHandle = System.IdentityModel.SafeCloseHandle;
using SafeHGlobalHandle = System.IdentityModel.SafeHGlobalHandle;
static class SecurityUtils
{
static WindowsIdentity anonymousIdentity;
static WindowsIdentity processIdentity;
static object lockObject = new object();
[Fx.Tag.SecurityNote(Critical = "Uses critical type SafeHGlobalHandle.",
Safe = "Performs a Demand for full trust.")]
[SecuritySafeCritical]
[SecurityPermission(SecurityAction.Demand, Unrestricted = true)]
public static SafeHandle GetTokenInformation(SafeCloseHandle token, TOKEN_INFORMATION_CLASS infoClass)
{
uint length;
if (!SafeNativeMethods.GetTokenInformation(token, infoClass, SafeHGlobalHandle.InvalidHandle, 0, out length))
{
int error = Marshal.GetLastWin32Error();
if (error != (int)Win32Error.ERROR_INSUFFICIENT_BUFFER)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error, SR.GetString(SR.GetTokenInfoFailed, error)));
}
}
SafeHandle buffer = SafeHGlobalHandle.AllocHGlobal(length);
try
{
if (!SafeNativeMethods.GetTokenInformation(token, infoClass, buffer, length, out length))
{
int error = Marshal.GetLastWin32Error();
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error, SR.GetString(SR.GetTokenInfoFailed, error)));
}
}
catch
{
buffer.Dispose();
throw;
}
return buffer;
}
internal static bool IsAtleastImpersonationToken(SafeCloseHandle token)
{
using (SafeHandle buffer =
GetTokenInformation(token, TOKEN_INFORMATION_CLASS.TokenImpersonationLevel))
{
int level = Marshal.ReadInt32(buffer.DangerousGetHandle());
if (level < (int)SecurityImpersonationLevel.Impersonation)
return false;
else
return true;
}
}
internal static bool IsPrimaryToken(SafeCloseHandle token)
{
using (SafeHandle buffer =
GetTokenInformation(token, TOKEN_INFORMATION_CLASS.TokenType))
{
int level = Marshal.ReadInt32(buffer.DangerousGetHandle());
return (level == (int)TokenType.TokenPrimary);
}
}
internal static LUID GetModifiedIDLUID(SafeCloseHandle token)
{
using (SafeHandle buffer =
GetTokenInformation(token, TOKEN_INFORMATION_CLASS.TokenStatistics))
{
TOKEN_STATISTICS tokenStats = (TOKEN_STATISTICS)
Marshal.PtrToStructure(buffer.DangerousGetHandle(), typeof(TOKEN_STATISTICS));
return tokenStats.ModifiedId;
}
}
public static WindowsIdentity GetAnonymousIdentity()
{
SafeCloseHandle tokenHandle = null;
bool isImpersonating = false;
lock (lockObject)
{
if (anonymousIdentity == null)
{
try
{
try
{
if (!SafeNativeMethods.ImpersonateAnonymousUserOnCurrentThread(SafeNativeMethods.GetCurrentThread()))
{
int error = Marshal.GetLastWin32Error();
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error, SR.GetString(SR.ImpersonateAnonymousTokenFailed, error)));
}
isImpersonating = true;
bool revertSuccess;
bool isSuccess = SafeNativeMethods.OpenCurrentThreadToken(SafeNativeMethods.GetCurrentThread(), TokenAccessLevels.Query, true, out tokenHandle);
if (!isSuccess)
{
int error = Marshal.GetLastWin32Error();
revertSuccess = SafeNativeMethods.RevertToSelf();
if (false == revertSuccess)
{
error = Marshal.GetLastWin32Error();
//this requires a failfast since failure to revert impersonation compromises security
DiagnosticUtility.FailFast("RevertToSelf() failed with " + error);
}
isImpersonating = false;
Utility.CloseInvalidOutSafeHandle(tokenHandle);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error, SR.GetString(SR.OpenThreadTokenFailed, error)));
}
revertSuccess = SafeNativeMethods.RevertToSelf();
if (false == revertSuccess)
{
int error = Marshal.GetLastWin32Error();
//this requires a failfast since failure to revert impersonation compromises security
DiagnosticUtility.FailFast("RevertToSelf() failed with " + error);
}
isImpersonating = false;
using (tokenHandle)
{
anonymousIdentity = new WindowsIdentity(tokenHandle.DangerousGetHandle());
}
}
finally
{
if (isImpersonating)
{
bool revertSuccess = SafeNativeMethods.RevertToSelf();
if (false == revertSuccess)
{
int error = Marshal.GetLastWin32Error();
//this requires a failfast since failure to revert impersonation compromises security
DiagnosticUtility.FailFast("RevertToSelf() failed with " + error);
}
}
}
}
catch
{
// Force the finally to run before leaving the method.
throw;
}
}
}
return anonymousIdentity;
}
public static WindowsIdentity GetProcessIdentity()
{
SafeCloseHandle tokenHandle = null;
lock (lockObject)
{
try
{
bool isSuccess = SafeNativeMethods.GetCurrentProcessToken(SafeNativeMethods.GetCurrentProcess(), TokenAccessLevels.Query, out tokenHandle);
if (!isSuccess)
{
int error = Marshal.GetLastWin32Error();
Utility.CloseInvalidOutSafeHandle(tokenHandle);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error, SR.GetString(SR.OpenProcessTokenFailed, error)));
}
processIdentity = new WindowsIdentity(tokenHandle.DangerousGetHandle());
}
finally
{
if (tokenHandle != null)
tokenHandle.Dispose();
}
}
return processIdentity;
}
}
internal sealed class ComPlusAuthorization
{
string[] serviceRoleMembers = null;
string[] contractRoleMembers = null;
string[] operationRoleMembers = null;
CommonSecurityDescriptor securityDescriptor = null;
static SecurityIdentifier sidAdministrators = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
Dictionary<LUID, bool> accessCheckCache = new Dictionary<LUID, bool>();
public ComPlusAuthorization(string[] serviceRoleMembers, string[] contractRoleMembers, string[] operationRoleMembers)
{
this.serviceRoleMembers = serviceRoleMembers;
this.contractRoleMembers = contractRoleMembers;
this.operationRoleMembers = operationRoleMembers;
}
private void BuildSecurityDescriptor()
{
Fx.Assert((null == securityDescriptor), "SecurityDescriptor must be NULL");
NTAccount name;
SecurityIdentifier sid;
CommonAce ace;
RawAcl acl = new RawAcl(GenericAcl.AclRevision, 1);
int index = 0;
if (operationRoleMembers != null)
{
foreach (string userName in operationRoleMembers)
{
name = new NTAccount(userName);
sid = (SecurityIdentifier)name.Translate(typeof(SecurityIdentifier));
ace = new CommonAce(AceFlags.None, AceQualifier.AccessAllowed, (int)ComRights.EXECUTE, sid, false, null);
acl.InsertAce(index, ace);
index++;
}
}
if (contractRoleMembers != null)
{
foreach (string userName in contractRoleMembers)
{
name = new NTAccount(userName);
sid = (SecurityIdentifier)name.Translate(typeof(SecurityIdentifier));
ace = new CommonAce(AceFlags.None, AceQualifier.AccessAllowed, (int)ComRights.EXECUTE, sid, false, null);
acl.InsertAce(index, ace);
index++;
}
}
if (serviceRoleMembers != null)
{
foreach (string userName in serviceRoleMembers)
{
name = new NTAccount(userName);
sid = (SecurityIdentifier)name.Translate(typeof(SecurityIdentifier));
ace = new CommonAce(AceFlags.None, AceQualifier.AccessAllowed, (int)ComRights.EXECUTE, sid, false, null);
acl.InsertAce(index, ace);
index++;
}
}
DiscretionaryAcl dacl = new DiscretionaryAcl(true, false, acl);
securityDescriptor = new CommonSecurityDescriptor(true, false, ControlFlags.DiscretionaryAclPresent, sidAdministrators, sidAdministrators, null, dacl);
}
private bool IsAccessCached(LUID luidModifiedID, out bool isAccessAllowed)
{
if (null == accessCheckCache)
{
throw Fx.AssertAndThrowFatal("AcessCheckCache must not be NULL");
}
bool retValue = false;
lock (this)
{
retValue = accessCheckCache.TryGetValue(luidModifiedID, out isAccessAllowed);
}
return retValue;
}
private void CacheAccessCheck(LUID luidModifiedID, bool isAccessAllowed)
{
if (null == accessCheckCache)
{
throw Fx.AssertAndThrowFatal("AcessCheckCache must not be NULL");
}
lock (this)
{
accessCheckCache[luidModifiedID] = isAccessAllowed;
}
}
private void CheckAccess(WindowsIdentity clientIdentity, out bool IsAccessAllowed)
{
if (null == securityDescriptor)
{
throw Fx.AssertAndThrowFatal("Security Descriptor must not be NULL");
}
IsAccessAllowed = false;
byte[] BinaryForm = new byte[securityDescriptor.BinaryLength];
securityDescriptor.GetBinaryForm(BinaryForm, 0);
SafeCloseHandle ImpersonationToken = null;
SafeCloseHandle clientIdentityToken = new SafeCloseHandle(clientIdentity.Token, false);
try
{
if (SecurityUtils.IsPrimaryToken(clientIdentityToken))
{
if (!SafeNativeMethods.DuplicateTokenEx(clientIdentityToken,
TokenAccessLevels.Query,
IntPtr.Zero,
SecurityImpersonationLevel.Identification,
TokenType.TokenImpersonation,
out ImpersonationToken))
{
int error = Marshal.GetLastWin32Error();
Utility.CloseInvalidOutSafeHandle(ImpersonationToken);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error, SR.GetString(SR.DuplicateTokenExFailed, error)));
}
}
GENERIC_MAPPING GenericMapping = new GENERIC_MAPPING();
PRIVILEGE_SET PrivilegeSet = new PRIVILEGE_SET();
uint PrivilegeSetLength = (uint)Marshal.SizeOf(PrivilegeSet);
uint GrantedAccess = 0;
if (!SafeNativeMethods.AccessCheck(BinaryForm, (ImpersonationToken != null) ? ImpersonationToken : clientIdentityToken,
(int)ComRights.EXECUTE, GenericMapping, out PrivilegeSet,
ref PrivilegeSetLength, out GrantedAccess, out IsAccessAllowed))
{
int error = Marshal.GetLastWin32Error();
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error, SR.GetString(SR.AccessCheckFailed, error)));
}
}
finally
{
if (ImpersonationToken != null)
ImpersonationToken.Dispose();
}
}
public string[] ServiceRoleMembers
{
get
{
return serviceRoleMembers;
}
}
public string[] ContractRoleMembers
{
get
{
return contractRoleMembers;
}
}
public string[] OperationRoleMembers
{
get
{
return operationRoleMembers;
}
}
public CommonSecurityDescriptor SecurityDescriptor
{
get
{
return securityDescriptor;
}
}
public bool IsAuthorizedForOperation(WindowsIdentity clientIdentity)
{
bool IsAccessAllowed = false;
if (null == clientIdentity)
{
throw Fx.AssertAndThrow("NULL Identity");
}
if (IntPtr.Zero == clientIdentity.Token)
{
throw Fx.AssertAndThrow("Token handle cannot be zero");
}
lock (this)
{
if (securityDescriptor == null)
{
BuildSecurityDescriptor();
}
}
LUID luidModified = SecurityUtils.GetModifiedIDLUID(new SafeCloseHandle(clientIdentity.Token, false));
if (IsAccessCached(luidModified, out IsAccessAllowed))
return IsAccessAllowed;
CheckAccess(clientIdentity, out IsAccessAllowed);
CacheAccessCheck(luidModified, IsAccessAllowed);
return IsAccessAllowed;
}
}
internal sealed class ComPlusServerSecurity : IContextSecurityPerimeter, IServerSecurity, IDisposable
{
WindowsIdentity clientIdentity = null;
IntPtr oldSecurityObject = IntPtr.Zero;
WindowsImpersonationContext impersonateContext = null;
bool isImpersonating = false;
bool shouldUseCallContext = false;
const uint RPC_C_AUTHN_GSS_NEGOTIATE = 9;
const uint RPC_C_AUTHN_WINNT = 10;
const uint RPC_C_AUTHN_GSS_KERBEROS = 16;
const uint RPC_C_AUTHN_DEFAULT = unchecked((uint)0xFFFFFFFF);
const uint RPC_C_AUTHZ_NONE = 0;
const uint RPC_C_AUTHN_LEVEL_DEFAULT = 0;
const uint RPC_C_AUTHN_LEVEL_NONE = 1;
const uint RPC_C_AUTHN_LEVEL_CONNECT = 2;
const uint RPC_C_AUTHN_LEVEL_CALL = 3;
const uint RPC_C_AUTHN_LEVEL_PKT = 4;
const uint RPC_C_AUTHN_LEVEL_PKT_INTEGRITY = 5;
const uint RPC_C_AUTHN_LEVEL_PKT_PRIVACY = 6;
public ComPlusServerSecurity(WindowsIdentity clientIdentity, bool shouldUseCallContext)
{
if (null == clientIdentity)
{
throw Fx.AssertAndThrow("NULL Identity");
}
if (IntPtr.Zero == clientIdentity.Token)
{
throw Fx.AssertAndThrow("Token handle cannot be zero");
}
this.shouldUseCallContext = shouldUseCallContext;
this.clientIdentity = clientIdentity;
IntPtr secCtx = Marshal.GetIUnknownForObject(this);
try
{
oldSecurityObject = SafeNativeMethods.CoSwitchCallContext(secCtx);
}
catch
{
Marshal.Release(secCtx);
throw;
}
}
~ComPlusServerSecurity()
{
Dispose(false);
}
public bool GetPerimeterFlag()
{
return shouldUseCallContext;
}
public void SetPerimeterFlag(bool flag)
{
shouldUseCallContext = flag;
}
public void QueryBlanket
(
IntPtr authnSvc,
IntPtr authzSvc,
IntPtr serverPrincipalName,
IntPtr authnLevel,
IntPtr impLevel,
IntPtr clientPrincipalName,
IntPtr Capabilities
)
{
// Convert to RPC'isms.
if (authnSvc != IntPtr.Zero)
{
uint tempAuthnSvc = RPC_C_AUTHN_DEFAULT;
// Try to convert the clientIdentity.AuthenticationType to an RPC constant.
// This is a best case attempt.
string authenticationType = clientIdentity.AuthenticationType;
if (authenticationType.ToUpperInvariant() == "NTLM")
tempAuthnSvc = RPC_C_AUTHN_WINNT;
else if (authenticationType.ToUpperInvariant() == "KERBEROS")
tempAuthnSvc = RPC_C_AUTHN_GSS_KERBEROS;
else if (authenticationType.ToUpperInvariant() == "NEGOTIATE")
tempAuthnSvc = RPC_C_AUTHN_GSS_NEGOTIATE;
Marshal.WriteInt32(authnSvc, (int)tempAuthnSvc);
}
if (authzSvc != IntPtr.Zero)
{
Marshal.WriteInt32(authzSvc, (int)RPC_C_AUTHZ_NONE);
}
if (serverPrincipalName != IntPtr.Zero)
{
IntPtr str = Marshal.StringToCoTaskMemUni(SecurityUtils.GetProcessIdentity().Name);
Marshal.WriteIntPtr(serverPrincipalName, str);
}
// There is no equivalent for the RPC authn level. It can only be
// approximated, in the best case. Use default.
if (authnLevel != IntPtr.Zero)
{
Marshal.WriteInt32(authnLevel, (int)RPC_C_AUTHN_LEVEL_DEFAULT);
}
if (impLevel != IntPtr.Zero)
{
Marshal.WriteInt32(impLevel, 0);
}
if (clientPrincipalName != IntPtr.Zero)
{
IntPtr str = Marshal.StringToCoTaskMemUni(clientIdentity.Name);
Marshal.WriteIntPtr(clientPrincipalName, str);
}
if (Capabilities != IntPtr.Zero)
{
Marshal.WriteInt32(Capabilities, 0);
}
}
public int ImpersonateClient()
{
// We want to return known COM hresults here rather than random CLR-Exception mapped HRESULTS. Also,
// we don't want CLR to set the ErrorInfo object.
int hresult = HR.E_FAIL;
try
{
impersonateContext = WindowsIdentity.Impersonate(clientIdentity.Token);
isImpersonating = true;
hresult = HR.S_OK;
}
catch (SecurityException)
{
// Special case anonymous impersonation failure.
// Unmanaged callers to ImpersonateClient expect this hresult.
hresult = HR.RPC_NT_BINDING_HAS_NO_AUTH;
}
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
}
return hresult;
}
public int RevertToSelf()
{
// We want to return known COM hresults here rather than random CLR-Exception mapped HRESULTS. Also,
// we don't want CLR to set the ErrorInfo object.
int hresult = HR.E_FAIL;
if (isImpersonating)
{
try
{
impersonateContext.Undo();
isImpersonating = false;
hresult = HR.S_OK;
}
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
}
}
return hresult;
}
public bool IsImpersonating()
{
return isImpersonating;
}
void IDisposable.Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public void Dispose(bool disposing)
{
RevertToSelf();
IntPtr secCtx = SafeNativeMethods.CoSwitchCallContext(oldSecurityObject);
if (IntPtr.Zero == secCtx)
{
// this has to be a failfast since not having a security context can compromise security
DiagnosticUtility.FailFast("Security Context was should not be null");
}
if (Marshal.GetObjectForIUnknown(secCtx) != this)
{
// this has to be a failfast since being in the wrong security context can compromise security
DiagnosticUtility.FailFast("Security Context was modified from underneath us");
}
Marshal.Release(secCtx);
if (disposing)
{
clientIdentity = null;
if (impersonateContext != null)
impersonateContext.Dispose();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Fantabulous.Core.Entities;
namespace Fantabulous.Core.Repositories
{
/// <summary>
/// Extensions for cache repositories to perform cache miss resolution.
/// </summary>
public static class CacheExtensions
{
/// <summary>
/// Fetch an entity by its unique ID.
/// </summary>
/// <param name="id">
/// A unique id
/// </param>
/// <param name="resolver">
/// A function which can resolve a cache miss
/// </param>
/// <returns>
/// The entity, or null if not found
/// </returns>
public async static Task<T> GetAsync<T>(
this IIdCacheCommon<T> cache,
long id,
Func<long,Task<T>> resolver)
where T: HasId
{
var entity = await cache.GetAsync(id);
if (entity == null)
{
entity = await resolver(id);
if (entity != null) cache.SetInBackground(entity);
}
return entity;
}
/// <summary>
/// Fetch some entities by their unique IDs.
/// </summary>
/// <param name="ids">
/// Some unique ids
/// </param>
/// <param name="resolver">
/// A function which can resolve cache misses
/// </param>
/// <returns>
/// The entities, empty if not found
/// </returns>
public async static Task<IEnumerable<T>> GetAsync<T>(
this IIdCacheCommon<T> cache,
IEnumerable<long> ids,
Func<IEnumerable<long>,Task<IEnumerable<T>>> resolver)
where T: HasId
{
var entityIds = ids.ToArray();
var entities = (await cache.GetAsync(entityIds)).ToArray();
var hits = new List<T>();
var misses = new List<long>();
for (int i = 0; i < entityIds.Length; i++)
{
if (entities[i] == null)
{
misses.Add(entityIds[i]);
}
else
{
hits.Add(entities[i]);
}
}
if (misses.Count > 0)
{
foreach (var entity in await resolver(misses))
{
hits.Add(entity);
cache.SetInBackground(entity);
}
}
return hits;
}
/// <summary>
/// Fetch an entity by its name.
/// </summary>
/// <param name="name">
/// An entity name
/// </param>
/// <param name="resolver">
/// A function which can resolve a cache miss
/// </param>
/// <returns>
/// The entity, or null if not found
/// </returns>
public async static Task<T> GetAsync<T>(
this IIdNameCache<T> cache,
string name,
Func<string,Task<T>> resolver)
where T: HasName
{
var entity = await cache.GetAsync(name);
if (entity == null)
{
entity = await resolver(name);
if (entity != null) cache.SetInBackground(entity);
}
return entity;
}
/// <summary>
/// Fetch a JSON representation of an entity by its unique ID.
/// </summary>
/// <param name="id">
/// A unique id
/// </param>
/// <param name="resolver">
/// A function which can resolve a cache miss
/// </param>
/// <returns>
/// The entity JSON, or null if not found
/// </returns>
public async static Task<string> GetJsonAsync<T>(
this IIdCacheCommon<T> cache,
long id,
Func<long,Task<T>> resolver)
where T: HasId
{
var json = await cache.GetJsonAsync(id);
if (json == null)
{
var entity = await resolver(id);
if (entity != null) json = cache.SetInBackground(entity);
}
return json;
}
/// <summary>
/// Fetch JSON representations of some entities by their IDs.
/// </summary>
/// <param name="ids">
/// Some unique ids
/// </param>
/// <param name="resolver">
/// A function which can resolve cache misses
/// </param>
/// <returns>
/// The entity JSONs, empty if not found
/// </returns>
public async static Task<IEnumerable<string>> GetJsonAsync<T>(
this IIdCacheCommon<T> cache,
IEnumerable<long> ids,
Func<IEnumerable<long>,Task<IEnumerable<T>>> resolver)
where T: HasId
{
var entityIds = ids.ToArray();
var jsons = (await cache.GetJsonAsync(entityIds)).ToArray();
var hits = new List<string>();
var misses = new List<long>();
for (int i = 0; i < entityIds.Length; i++)
{
if (jsons[i] == null)
{
misses.Add(entityIds[i]);
}
else
{
hits.Add(jsons[i]);
}
}
if (misses.Count > 0)
{
foreach (var entity in await resolver(misses))
{
hits.Add(cache.SetInBackground(entity));
}
}
return hits;
}
/// <summary>
/// Fetch a JSON representation of an entity by its name.
/// </summary>
/// <param name="name">
/// An entity name
/// </param>
/// <param name="resolver">
/// A function which can resolve a cache miss
/// </param>
/// <returns>
/// The entity JSON, or null if not found
/// </returns>
public async static Task<string> GetJsonAsync<T>(
this IIdNameCache<T> cache,
string name,
Func<string,Task<T>> resolver)
where T: HasName
{
var json = await cache.GetJsonAsync(name);
if (json == null)
{
var entity = await resolver(name);
if (entity != null) json = cache.SetInBackground(entity);
}
return json;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using FluentNHibernate.Mapping;
using FluentNHibernate.Mapping.Providers;
using FluentNHibernate.MappingModel;
using FluentNHibernate.MappingModel.ClassBased;
using FluentNHibernate.Utils;
namespace FluentNHibernate.Automapping
{
public class AutoMapping<T> : ClassMap<T>, IAutoClasslike, IPropertyIgnorer
{
readonly MappingProviderStore providers;
readonly IList<Member> mappedMembers;
public AutoMapping(IList<Member> mappedMembers)
: this(mappedMembers, new AttributeStore(), new MappingProviderStore())
{}
AutoMapping(IList<Member> mappedMembers, AttributeStore attributes, MappingProviderStore providers)
: base(attributes, providers)
{
this.mappedMembers = mappedMembers;
this.providers = providers;
}
void IAutoClasslike.DiscriminateSubClassesOnColumn(string column)
{
DiscriminateSubClassesOnColumn(column);
}
IEnumerable<Member> IMappingProvider.GetIgnoredProperties()
{
return mappedMembers;
}
void IAutoClasslike.AlterModel(ClassMappingBase mapping)
{
mapping.MergeAttributes(attributes.Clone());
if (mapping is ClassMapping)
{
var classMapping = (ClassMapping)mapping;
if (providers.Id != null)
classMapping.Set(x => x.Id, Layer.Defaults, providers.Id.GetIdentityMapping());
if (providers.NaturalId != null)
classMapping.Set(x => x.NaturalId, Layer.Defaults, providers.NaturalId.GetNaturalIdMapping());
if (providers.CompositeId != null)
classMapping.Set(x => x.Id, Layer.Defaults, providers.CompositeId.GetCompositeIdMapping());
if (providers.Version != null)
classMapping.Set(x => x.Version, Layer.Defaults, providers.Version.GetVersionMapping());
if (providers.Discriminator != null)
classMapping.Set(x => x.Discriminator, Layer.Defaults, providers.Discriminator.GetDiscriminatorMapping());
if (Cache.IsDirty)
classMapping.Set(x => x.Cache, Layer.Defaults, ((ICacheMappingProvider)Cache).GetCacheMapping());
foreach (var join in providers.Joins)
classMapping.AddJoin(join.GetJoinMapping());
classMapping.Set(x => x.Tuplizer, Layer.Defaults, providers.TuplizerMapping);
}
foreach (var property in providers.Properties)
mapping.AddOrReplaceProperty(property.GetPropertyMapping());
foreach (var collection in providers.Collections)
mapping.AddOrReplaceCollection(collection.GetCollectionMapping());
foreach (var component in providers.Components)
mapping.AddOrReplaceComponent(component.GetComponentMapping());
foreach (var oneToOne in providers.OneToOnes)
mapping.AddOrReplaceOneToOne(oneToOne.GetOneToOneMapping());
foreach (var reference in providers.References)
mapping.AddOrReplaceReference(reference.GetManyToOneMapping());
foreach (var any in providers.Anys)
mapping.AddOrReplaceAny(any.GetAnyMapping());
foreach (var storedProcedure in providers.StoredProcedures)
mapping.AddStoredProcedure(storedProcedure.GetStoredProcedureMapping());
foreach (var filter in providers.Filters)
mapping.AddOrReplaceFilter(filter.GetFilterMapping());
}
internal override void OnMemberMapped(Member member)
{
mappedMembers.Add(member);
}
public void IgnoreProperty(Expression<Func<T, object>> expression)
{
mappedMembers.Add(expression.ToMember());
}
IPropertyIgnorer IPropertyIgnorer.IgnoreProperty(string name)
{
((IPropertyIgnorer)this).IgnoreProperties(name);
return this;
}
IPropertyIgnorer IPropertyIgnorer.IgnoreProperties(string first, params string[] others)
{
var options = (others ?? new string[0]).Concat(new[] { first }).ToArray();
((IPropertyIgnorer)this).IgnoreProperties(x => x.Name.In(options));
return this;
}
IPropertyIgnorer IPropertyIgnorer.IgnoreProperties(Func<Member, bool> predicate)
{
typeof(T).GetProperties()
.Select(x => x.ToMember())
.Where(predicate)
.Each(mappedMembers.Add);
return this;
}
public AutoJoinedSubClassPart<TSubclass> JoinedSubClass<TSubclass>(string keyColumn, Action<AutoJoinedSubClassPart<TSubclass>> action)
where TSubclass : T
{
var genericType = typeof(AutoJoinedSubClassPart<>).MakeGenericType(typeof(TSubclass));
var joinedclass = (AutoJoinedSubClassPart<TSubclass>)Activator.CreateInstance(genericType, keyColumn);
if (action != null)
action(joinedclass);
providers.Subclasses[typeof(TSubclass)] = joinedclass;
return joinedclass;
}
public IAutoClasslike JoinedSubClass(Type type, string keyColumn)
{
var genericType = typeof (AutoJoinedSubClassPart<>).MakeGenericType(type);
var joinedclass = (ISubclassMappingProvider)Activator.CreateInstance(genericType, keyColumn);
// remove any mappings for the same type, then re-add
providers.Subclasses[type] = joinedclass;
return (IAutoClasslike)joinedclass;
}
public AutoJoinedSubClassPart<TSubclass> JoinedSubClass<TSubclass>(string keyColumn)
where TSubclass : T
{
return JoinedSubClass<TSubclass>(keyColumn, null);
}
public AutoSubClassPart<TSubclass> SubClass<TSubclass>(object discriminatorValue, Action<AutoSubClassPart<TSubclass>> action)
where TSubclass : T
{
var genericType = typeof(AutoSubClassPart<>).MakeGenericType(typeof(TSubclass));
var subclass = (AutoSubClassPart<TSubclass>)Activator.CreateInstance(genericType, null, discriminatorValue);
if (action != null)
action(subclass);
// remove any mappings for the same type, then re-add
providers.Subclasses[typeof(TSubclass)] = subclass;
return subclass;
}
public AutoSubClassPart<TSubclass> SubClass<TSubclass>(object discriminatorValue)
where TSubclass : T
{
return SubClass<TSubclass>(discriminatorValue, null);
}
public IAutoClasslike SubClass(Type type, string discriminatorValue)
{
var genericType = typeof(AutoSubClassPart<>).MakeGenericType(type);
var subclass = (ISubclassMappingProvider)Activator.CreateInstance(genericType, null, discriminatorValue);
// remove any mappings for the same type, then re-add
providers.Subclasses[type] = subclass;
return (IAutoClasslike)subclass;
}
// hide the base one D:
private new void Join(string table, Action<JoinPart<T>> action)
{ }
public void Join(string table, Action<AutoJoinPart<T>> action)
{
var join = new AutoJoinPart<T>(mappedMembers, table);
action(join);
providers.Joins.Add(join);
}
#pragma warning disable 809
// hide this - imports aren't supported in overrides
[Obsolete("Imports aren't supported in overrides.", true)]
public new ImportPart ImportType<TImport>()
{
return null;
}
#pragma warning restore 809
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the AprCentilesIMCEdadGestacional class.
/// </summary>
[Serializable]
public partial class AprCentilesIMCEdadGestacionalCollection : ActiveList<AprCentilesIMCEdadGestacional, AprCentilesIMCEdadGestacionalCollection>
{
public AprCentilesIMCEdadGestacionalCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>AprCentilesIMCEdadGestacionalCollection</returns>
public AprCentilesIMCEdadGestacionalCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
AprCentilesIMCEdadGestacional o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the APR_CentilesIMCEdadGestacional table.
/// </summary>
[Serializable]
public partial class AprCentilesIMCEdadGestacional : ActiveRecord<AprCentilesIMCEdadGestacional>, IActiveRecord
{
#region .ctors and Default Settings
public AprCentilesIMCEdadGestacional()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public AprCentilesIMCEdadGestacional(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public AprCentilesIMCEdadGestacional(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public AprCentilesIMCEdadGestacional(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("APR_CentilesIMCEdadGestacional", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarId = new TableSchema.TableColumn(schema);
colvarId.ColumnName = "id";
colvarId.DataType = DbType.Int32;
colvarId.MaxLength = 0;
colvarId.AutoIncrement = true;
colvarId.IsNullable = false;
colvarId.IsPrimaryKey = true;
colvarId.IsForeignKey = false;
colvarId.IsReadOnly = false;
colvarId.DefaultSetting = @"";
colvarId.ForeignKeyTableName = "";
schema.Columns.Add(colvarId);
TableSchema.TableColumn colvarSemanasGestacion = new TableSchema.TableColumn(schema);
colvarSemanasGestacion.ColumnName = "SemanasGestacion";
colvarSemanasGestacion.DataType = DbType.Decimal;
colvarSemanasGestacion.MaxLength = 0;
colvarSemanasGestacion.AutoIncrement = false;
colvarSemanasGestacion.IsNullable = false;
colvarSemanasGestacion.IsPrimaryKey = false;
colvarSemanasGestacion.IsForeignKey = false;
colvarSemanasGestacion.IsReadOnly = false;
colvarSemanasGestacion.DefaultSetting = @"";
colvarSemanasGestacion.ForeignKeyTableName = "";
schema.Columns.Add(colvarSemanasGestacion);
TableSchema.TableColumn colvarL = new TableSchema.TableColumn(schema);
colvarL.ColumnName = "L";
colvarL.DataType = DbType.Decimal;
colvarL.MaxLength = 0;
colvarL.AutoIncrement = false;
colvarL.IsNullable = false;
colvarL.IsPrimaryKey = false;
colvarL.IsForeignKey = false;
colvarL.IsReadOnly = false;
colvarL.DefaultSetting = @"";
colvarL.ForeignKeyTableName = "";
schema.Columns.Add(colvarL);
TableSchema.TableColumn colvarM = new TableSchema.TableColumn(schema);
colvarM.ColumnName = "M";
colvarM.DataType = DbType.Decimal;
colvarM.MaxLength = 0;
colvarM.AutoIncrement = false;
colvarM.IsNullable = false;
colvarM.IsPrimaryKey = false;
colvarM.IsForeignKey = false;
colvarM.IsReadOnly = false;
colvarM.DefaultSetting = @"";
colvarM.ForeignKeyTableName = "";
schema.Columns.Add(colvarM);
TableSchema.TableColumn colvarS = new TableSchema.TableColumn(schema);
colvarS.ColumnName = "S";
colvarS.DataType = DbType.Decimal;
colvarS.MaxLength = 0;
colvarS.AutoIncrement = false;
colvarS.IsNullable = false;
colvarS.IsPrimaryKey = false;
colvarS.IsForeignKey = false;
colvarS.IsReadOnly = false;
colvarS.DefaultSetting = @"";
colvarS.ForeignKeyTableName = "";
schema.Columns.Add(colvarS);
TableSchema.TableColumn colvarC3 = new TableSchema.TableColumn(schema);
colvarC3.ColumnName = "C3";
colvarC3.DataType = DbType.Decimal;
colvarC3.MaxLength = 0;
colvarC3.AutoIncrement = false;
colvarC3.IsNullable = false;
colvarC3.IsPrimaryKey = false;
colvarC3.IsForeignKey = false;
colvarC3.IsReadOnly = false;
colvarC3.DefaultSetting = @"";
colvarC3.ForeignKeyTableName = "";
schema.Columns.Add(colvarC3);
TableSchema.TableColumn colvarC10 = new TableSchema.TableColumn(schema);
colvarC10.ColumnName = "C10";
colvarC10.DataType = DbType.Decimal;
colvarC10.MaxLength = 0;
colvarC10.AutoIncrement = false;
colvarC10.IsNullable = false;
colvarC10.IsPrimaryKey = false;
colvarC10.IsForeignKey = false;
colvarC10.IsReadOnly = false;
colvarC10.DefaultSetting = @"";
colvarC10.ForeignKeyTableName = "";
schema.Columns.Add(colvarC10);
TableSchema.TableColumn colvarC50 = new TableSchema.TableColumn(schema);
colvarC50.ColumnName = "C50";
colvarC50.DataType = DbType.Decimal;
colvarC50.MaxLength = 0;
colvarC50.AutoIncrement = false;
colvarC50.IsNullable = false;
colvarC50.IsPrimaryKey = false;
colvarC50.IsForeignKey = false;
colvarC50.IsReadOnly = false;
colvarC50.DefaultSetting = @"";
colvarC50.ForeignKeyTableName = "";
schema.Columns.Add(colvarC50);
TableSchema.TableColumn colvarC90 = new TableSchema.TableColumn(schema);
colvarC90.ColumnName = "C90";
colvarC90.DataType = DbType.Decimal;
colvarC90.MaxLength = 0;
colvarC90.AutoIncrement = false;
colvarC90.IsNullable = false;
colvarC90.IsPrimaryKey = false;
colvarC90.IsForeignKey = false;
colvarC90.IsReadOnly = false;
colvarC90.DefaultSetting = @"";
colvarC90.ForeignKeyTableName = "";
schema.Columns.Add(colvarC90);
TableSchema.TableColumn colvarC97 = new TableSchema.TableColumn(schema);
colvarC97.ColumnName = "C97";
colvarC97.DataType = DbType.Decimal;
colvarC97.MaxLength = 0;
colvarC97.AutoIncrement = false;
colvarC97.IsNullable = false;
colvarC97.IsPrimaryKey = false;
colvarC97.IsForeignKey = false;
colvarC97.IsReadOnly = false;
colvarC97.DefaultSetting = @"";
colvarC97.ForeignKeyTableName = "";
schema.Columns.Add(colvarC97);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("APR_CentilesIMCEdadGestacional",schema);
}
}
#endregion
#region Props
[XmlAttribute("Id")]
[Bindable(true)]
public int Id
{
get { return GetColumnValue<int>(Columns.Id); }
set { SetColumnValue(Columns.Id, value); }
}
[XmlAttribute("SemanasGestacion")]
[Bindable(true)]
public decimal SemanasGestacion
{
get { return GetColumnValue<decimal>(Columns.SemanasGestacion); }
set { SetColumnValue(Columns.SemanasGestacion, value); }
}
[XmlAttribute("L")]
[Bindable(true)]
public decimal L
{
get { return GetColumnValue<decimal>(Columns.L); }
set { SetColumnValue(Columns.L, value); }
}
[XmlAttribute("M")]
[Bindable(true)]
public decimal M
{
get { return GetColumnValue<decimal>(Columns.M); }
set { SetColumnValue(Columns.M, value); }
}
[XmlAttribute("S")]
[Bindable(true)]
public decimal S
{
get { return GetColumnValue<decimal>(Columns.S); }
set { SetColumnValue(Columns.S, value); }
}
[XmlAttribute("C3")]
[Bindable(true)]
public decimal C3
{
get { return GetColumnValue<decimal>(Columns.C3); }
set { SetColumnValue(Columns.C3, value); }
}
[XmlAttribute("C10")]
[Bindable(true)]
public decimal C10
{
get { return GetColumnValue<decimal>(Columns.C10); }
set { SetColumnValue(Columns.C10, value); }
}
[XmlAttribute("C50")]
[Bindable(true)]
public decimal C50
{
get { return GetColumnValue<decimal>(Columns.C50); }
set { SetColumnValue(Columns.C50, value); }
}
[XmlAttribute("C90")]
[Bindable(true)]
public decimal C90
{
get { return GetColumnValue<decimal>(Columns.C90); }
set { SetColumnValue(Columns.C90, value); }
}
[XmlAttribute("C97")]
[Bindable(true)]
public decimal C97
{
get { return GetColumnValue<decimal>(Columns.C97); }
set { SetColumnValue(Columns.C97, value); }
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(decimal varSemanasGestacion,decimal varL,decimal varM,decimal varS,decimal varC3,decimal varC10,decimal varC50,decimal varC90,decimal varC97)
{
AprCentilesIMCEdadGestacional item = new AprCentilesIMCEdadGestacional();
item.SemanasGestacion = varSemanasGestacion;
item.L = varL;
item.M = varM;
item.S = varS;
item.C3 = varC3;
item.C10 = varC10;
item.C50 = varC50;
item.C90 = varC90;
item.C97 = varC97;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varId,decimal varSemanasGestacion,decimal varL,decimal varM,decimal varS,decimal varC3,decimal varC10,decimal varC50,decimal varC90,decimal varC97)
{
AprCentilesIMCEdadGestacional item = new AprCentilesIMCEdadGestacional();
item.Id = varId;
item.SemanasGestacion = varSemanasGestacion;
item.L = varL;
item.M = varM;
item.S = varS;
item.C3 = varC3;
item.C10 = varC10;
item.C50 = varC50;
item.C90 = varC90;
item.C97 = varC97;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn SemanasGestacionColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn LColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn MColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn SColumn
{
get { return Schema.Columns[4]; }
}
public static TableSchema.TableColumn C3Column
{
get { return Schema.Columns[5]; }
}
public static TableSchema.TableColumn C10Column
{
get { return Schema.Columns[6]; }
}
public static TableSchema.TableColumn C50Column
{
get { return Schema.Columns[7]; }
}
public static TableSchema.TableColumn C90Column
{
get { return Schema.Columns[8]; }
}
public static TableSchema.TableColumn C97Column
{
get { return Schema.Columns[9]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string Id = @"id";
public static string SemanasGestacion = @"SemanasGestacion";
public static string L = @"L";
public static string M = @"M";
public static string S = @"S";
public static string C3 = @"C3";
public static string C10 = @"C10";
public static string C50 = @"C50";
public static string C90 = @"C90";
public static string C97 = @"C97";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using GetSocialSdk.MiniJSON;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace GetSocialSdk.Core
{
public class GetSocialSettings : ScriptableObject
{
public const string UnityDemoAppAppId = "LuDPp7W0J4";
const string SettingsAssetName = "GetSocialSettings";
const string SettingsAssetPath = "Resources/";
static GetSocialSettings _instance;
[SerializeField]
string _appId = string.Empty;
[SerializeField]
bool _isAutoRegisrationForPushesEnabled = true;
[SerializeField]
bool _isForegroundNotificationsEnabled = false;
[SerializeField]
bool _autoInitEnabled = true;
[SerializeField]
bool _disableFacebookReferralCheck = false;
[SerializeField]
string _getSocialCustomConfigurationFilePath = string.Empty;
[SerializeField]
string _getSocialDefaultConfigurationFilePath = string.Empty;
[SerializeField]
string _iosPushEnvironment = string.Empty;
[SerializeField]
List<string> _deeplinkingDomains = new List<string>();
[SerializeField]
bool _isAndroidEnabled = false;
[SerializeField]
bool _isIosEnabled = false;
[SerializeField]
bool _isIosPushEnabled = false;
[SerializeField]
bool _isAndroidPushEnabled = false;
[SerializeField]
bool _isAppIdValid = true;
[SerializeField]
bool _isRichNotificationsEnabled = false;
[SerializeField]
bool _shouldWaitForListener = false;
[SerializeField]
string _extensionBundleId = string.Empty;
[SerializeField]
string _extensionProvisioningProfile = string.Empty;
#region initialization
public static GetSocialSettings Instance
{
get
{
if (_instance == null)
{
_instance = Resources.Load(SettingsAssetName) as GetSocialSettings;
if (_instance == null)
{
_instance = CreateInstance<GetSocialSettings>();
AppId = UnityDemoAppAppId;
SaveAsset(Path.Combine(GetPluginPath(), SettingsAssetPath), SettingsAssetName);
}
}
return _instance;
}
}
#endregion
#region public methods
public static string AppId
{
get { return Instance._appId; }
set
{
Instance._appId = value;
MarkAssetDirty();
}
}
public static bool IsAutoRegisrationForPushesEnabled
{
get { return Instance._isAutoRegisrationForPushesEnabled; }
set
{
Instance._isAutoRegisrationForPushesEnabled = value;
MarkAssetDirty();
}
}
public static bool IsForegroundNotificationsEnabled
{
get { return Instance._isForegroundNotificationsEnabled; }
set
{
Instance._isForegroundNotificationsEnabled = value;
MarkAssetDirty();
}
}
public static bool ShouldWaitForPushListener
{
get { return Instance._shouldWaitForListener; }
set
{
Instance._shouldWaitForListener = value;
MarkAssetDirty();
}
}
public static bool IsAutoInitEnabled
{
get { return Instance._autoInitEnabled; }
set
{
Instance._autoInitEnabled = value;
MarkAssetDirty();
}
}
public static bool IsFacebookReferralCheckDisabled
{
get { return Instance._disableFacebookReferralCheck; }
set
{
Instance._disableFacebookReferralCheck = value;
MarkAssetDirty();
}
}
public static string IosPushEnvironment
{
get { return Instance._iosPushEnvironment; }
set
{
Instance._iosPushEnvironment= value;
MarkAssetDirty();
}
}
public static List<string> DeeplinkingDomains
{
get { return Instance._deeplinkingDomains; }
set
{
Instance._deeplinkingDomains = value;
MarkAssetDirty();
}
}
public static bool IsAndroidEnabled
{
get { return Instance._isAndroidEnabled; }
set
{
Instance._isAndroidEnabled = value;
MarkAssetDirty();
}
}
public static bool IsIosEnabled
{
get { return Instance._isIosEnabled; }
set
{
Instance._isIosEnabled = value;
MarkAssetDirty();
}
}
public static string UiConfigurationCustomFilePath
{
get
{
if (string.IsNullOrEmpty(Instance._getSocialCustomConfigurationFilePath)
&& !string.IsNullOrEmpty(Instance._getSocialDefaultConfigurationFilePath))
{
Instance._getSocialCustomConfigurationFilePath = Instance._getSocialDefaultConfigurationFilePath;
Instance._getSocialDefaultConfigurationFilePath = string.Empty;
MarkAssetDirty();
}
return Instance._getSocialCustomConfigurationFilePath;
}
set
{
Instance._getSocialCustomConfigurationFilePath = value;
MarkAssetDirty();
}
}
public static bool IsIosPushEnabled
{
get { return Instance._isIosPushEnabled; }
set
{
Instance._isIosPushEnabled = value;
if (!value)
{
Instance._isRichNotificationsEnabled = false;
}
MarkAssetDirty();
}
}
public static bool IsAndroidPushEnabled
{
get { return Instance._isAndroidPushEnabled; }
set
{
Instance._isAndroidPushEnabled = value;
MarkAssetDirty();
}
}
public static bool IsAppIdValidated
{
get { return Instance._isAppIdValid; }
set
{
Instance._isAppIdValid = value;
MarkAssetDirty();
}
}
public static bool IsRichPushNotificationsEnabled
{
get { return Instance._isRichNotificationsEnabled; }
set
{
Instance._isRichNotificationsEnabled = value;
MarkAssetDirty();
}
}
public static string ExtensionBundleId
{
get { return Instance._extensionBundleId; }
set
{
Instance._extensionBundleId = value;
MarkAssetDirty();
}
}
public static string ExtensionProvisioningProfile
{
get { return Instance._extensionProvisioningProfile; }
set
{
Instance._extensionProvisioningProfile = value;
MarkAssetDirty();
}
}
public static string GetPluginPath()
{
// get GetSocial plugin path relative to Assets folder
return GetAbsolutePluginPath().Replace("\\", "/").Replace(Application.dataPath, "Assets");
}
public static string GetAbsolutePluginPath()
{
// get absolute path to GetSocial folder
return Path.GetDirectoryName(Path.GetDirectoryName( FindEditor(Application.dataPath)));
}
private static string FindEditor(string path)
{
foreach (var d in Directory.GetDirectories(path))
{
foreach (var f in Directory.GetFiles(d))
{
if (f.Contains("GetSocialSettingsEditor.cs"))
{
return f;
}
}
var rec = FindEditor(d);
if (rec != null)
{
return rec;
}
}
return null;
}
#endregion
#region private methods
static void SaveAsset(string directory, string name)
{
#if UNITY_EDITOR
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
AssetDatabase.CreateAsset(Instance, directory + name + ".asset");
AssetDatabase.Refresh();
#endif
}
static void MarkAssetDirty()
{
#if UNITY_EDITOR
EditorUtility.SetDirty(Instance);
UpdateConfigsFile();
#endif
}
public static void UpdateConfigsFile()
{
var pathToConfig = Path.Combine(Application.streamingAssetsPath, "getsocial.json");
var dictionary = File.Exists(pathToConfig)
? GSJson.Deserialize(File.ReadAllText(pathToConfig)) as Dictionary<string, object>
: new Dictionary<string, object>();
dictionary["runtime"] = new Dictionary<string, object>
{
{"name", "UNITY"},
{"version", Application.unityVersion},
{"wrapper", BuildConfig.UnitySdkVersion}
};
dictionary["appId"] = GetSocialSettings.AppId;
dictionary["autoInit"] = GetSocialSettings.IsAutoInitEnabled;
dictionary["disableFacebookReferralCheck"] = GetSocialSettings.IsFacebookReferralCheckDisabled;
dictionary["pushNotifications"] = new Dictionary<string, object>
{
{"autoRegister", GetSocialSettings.IsAutoRegisrationForPushesEnabled},
{"customListener", GetSocialSettings.ShouldWaitForPushListener},
{"foreground", GetSocialSettings.IsForegroundNotificationsEnabled}
};
var customPath = GetSocialSettings.UiConfigurationCustomFilePath;
dictionary["uiConfig"] = string.IsNullOrEmpty(customPath) ? null : customPath;
// add basic formatting, maybe lets add some pretty print in future
if (!Directory.Exists(Application.streamingAssetsPath))
{
Directory.CreateDirectory(Application.streamingAssetsPath);
}
File.WriteAllText(pathToConfig,
GSJson.Serialize(dictionary)
.Replace(",", "," + Environment.NewLine)
.Replace("}", Environment.NewLine + "}")
.Replace("{", Environment.NewLine + "{" + Environment.NewLine)
);
}
#endregion
}
}
| |
// ***********************************************************************
// Copyright (c) 2014 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using NUnit.Common;
using NUnit.ConsoleRunner.Utilities;
using NUnit.Engine;
using NUnit.Engine.Extensibility;
using System.Runtime.InteropServices;
namespace NUnit.ConsoleRunner
{
/// <summary>
/// ConsoleRunner provides the nunit3-console text-based
/// user interface, running the tests and reporting the results.
/// </summary>
public class ConsoleRunner
{
#region Console Runner Return Codes
public static readonly int OK = 0;
public static readonly int INVALID_ARG = -1;
public static readonly int INVALID_ASSEMBLY = -2;
//public static readonly int FIXTURE_NOT_FOUND = -3; //No longer in use
public static readonly int INVALID_TEST_FIXTURE = -4;
public static readonly int UNEXPECTED_ERROR = -100;
#endregion
#region Instance Fields
private ITestEngine _engine;
private ConsoleOptions _options;
private IResultService _resultService;
private ITestFilterService _filterService;
private IExtensionService _extensionService;
private ExtendedTextWriter _outWriter;
private TextWriter _errorWriter = Console.Error;
private string _workDirectory;
#endregion
#region Constructor
public ConsoleRunner(ITestEngine engine, ConsoleOptions options, ExtendedTextWriter writer)
{
_engine = engine;
_options = options;
_outWriter = writer;
_workDirectory = options.WorkDirectory;
if (_workDirectory == null)
_workDirectory = Environment.CurrentDirectory;
else if (!Directory.Exists(_workDirectory))
Directory.CreateDirectory(_workDirectory);
_resultService = _engine.Services.GetService<IResultService>();
_filterService = _engine.Services.GetService<ITestFilterService>();
_extensionService = _engine.Services.GetService<IExtensionService>();
// Enable TeamCityEventListener immediately, before the console is redirected
_extensionService.EnableExtension("NUnit.Engine.Listeners.TeamCityEventListener", _options.TeamCity);
}
#endregion
#region Execute Method
/// <summary>
/// Executes tests according to the provided commandline options.
/// </summary>
/// <returns></returns>
public int Execute()
{
if (!VerifyEngineSupport(_options))
return INVALID_ARG;
DisplayRuntimeEnvironment(_outWriter);
if (_options.ListExtensions)
DisplayExtensionList();
if (_options.InputFiles.Count == 0)
{
if (!_options.ListExtensions)
using (new ColorConsole(ColorStyle.Error))
Console.Error.WriteLine("Error: no inputs specified");
return ConsoleRunner.OK;
}
DisplayTestFiles();
TestPackage package = MakeTestPackage(_options);
// We display the filters at this point so that any exception message
// thrown by CreateTestFilter will be understandable.
DisplayTestFilters();
TestFilter filter = CreateTestFilter(_options);
if (_options.Explore)
return ExploreTests(package, filter);
else
return RunTests(package, filter);
}
private void DisplayTestFiles()
{
_outWriter.WriteLine(ColorStyle.SectionHeader, "Test Files");
foreach (string file in _options.InputFiles)
_outWriter.WriteLine(ColorStyle.Default, " " + file);
_outWriter.WriteLine();
}
#endregion
#region Helper Methods
private int ExploreTests(TestPackage package, TestFilter filter)
{
XmlNode result;
using (var runner = _engine.GetRunner(package))
result = runner.Explore(filter);
if (_options.ExploreOutputSpecifications.Count == 0)
{
_resultService.GetResultWriter("cases", null).WriteResultFile(result, Console.Out);
}
else
{
foreach (OutputSpecification spec in _options.ExploreOutputSpecifications)
{
_resultService.GetResultWriter(spec.Format, new object[] {spec.Transform}).WriteResultFile(result, spec.OutputPath);
_outWriter.WriteLine("Results ({0}) saved as {1}", spec.Format, spec.OutputPath);
}
}
return ConsoleRunner.OK;
}
private int RunTests(TestPackage package, TestFilter filter)
{
foreach (var spec in _options.ResultOutputSpecifications)
{
var outputPath = Path.Combine(_workDirectory, spec.OutputPath);
GetResultWriter(spec).CheckWritability(outputPath);
}
// TODO: Incorporate this in EventCollector?
RedirectErrorOutputAsRequested();
var labels = _options.DisplayTestLabels != null
? _options.DisplayTestLabels.ToUpperInvariant()
: "ON";
XmlNode result = null;
NUnitEngineException engineException = null;
try
{
using (new SaveConsoleOutput())
using (new ColorConsole(ColorStyle.Output))
using (ITestRunner runner = _engine.GetRunner(package))
using (var output = CreateOutputWriter())
{
var eventHandler = new TestEventHandler(output, labels);
result = runner.Run(eventHandler, filter);
}
}
catch (NUnitEngineException ex)
{
engineException = ex;
}
finally
{
RestoreErrorOutput();
}
var writer = new ColorConsoleWriter(!_options.NoColor);
if (result != null)
{
var reporter = new ResultReporter(result, writer, _options);
reporter.ReportResults();
foreach (var spec in _options.ResultOutputSpecifications)
{
var outputPath = Path.Combine(_workDirectory, spec.OutputPath);
GetResultWriter(spec).WriteResultFile(result, outputPath);
_outWriter.WriteLine("Results ({0}) saved as {1}", spec.Format, spec.OutputPath);
}
// Since we got a result, we display any engine exception as a warning
if (engineException != null)
writer.WriteLine(ColorStyle.Warning, Environment.NewLine + engineException.Message);
if (reporter.Summary.UnexpectedError)
return ConsoleRunner.UNEXPECTED_ERROR;
if (reporter.Summary.InvalidAssemblies > 0)
return ConsoleRunner.INVALID_ASSEMBLY;
return reporter.Summary.InvalidTestFixtures > 0
? ConsoleRunner.INVALID_TEST_FIXTURE
: reporter.Summary.FailureCount + reporter.Summary.ErrorCount + reporter.Summary.InvalidCount;
}
// If we got here, it's because we had an exception, but check anyway
if (engineException != null)
writer.WriteLine(ColorStyle.Error, engineException.Message);
return ConsoleRunner.UNEXPECTED_ERROR;
}
private void DisplayRuntimeEnvironment(ExtendedTextWriter OutWriter)
{
OutWriter.WriteLine(ColorStyle.SectionHeader, "Runtime Environment");
OutWriter.WriteLabelLine(" OS Version: ", GetOSVersion());
OutWriter.WriteLabelLine(" CLR Version: ", Environment.Version.ToString());
OutWriter.WriteLine();
}
private static string GetOSVersion()
{
OperatingSystem os = Environment.OSVersion;
string osString = os.ToString();
if (os.Platform == PlatformID.Unix)
{
IntPtr buf = Marshal.AllocHGlobal(8192);
if (uname(buf) == 0)
{
var unixVariant = Marshal.PtrToStringAnsi(buf);
if (unixVariant.Equals("Darwin"))
unixVariant = "MacOSX";
osString = string.Format("{0} {1} {2}", unixVariant, os.Version, os.ServicePack);
}
Marshal.FreeHGlobal(buf);
}
return osString;
}
[DllImport("libc")]
static extern int uname(IntPtr buf);
private void DisplayExtensionList()
{
_outWriter.WriteLine(ColorStyle.SectionHeader, "Installed Extensions");
foreach (var ep in _extensionService.ExtensionPoints)
{
_outWriter.WriteLabelLine(" Extension Point: ", ep.Path);
foreach (var node in ep.Extensions)
{
_outWriter.Write(" Extension: ");
_outWriter.Write(ColorStyle.Value, node.TypeName);
_outWriter.WriteLine(node.Enabled ? "" : " (Disabled)");
foreach (var prop in node.PropertyNames)
{
_outWriter.Write(" " + prop + ":");
foreach (var val in node.GetValues(prop))
_outWriter.Write(ColorStyle.Value, " " + val);
_outWriter.WriteLine();
}
}
}
_outWriter.WriteLine();
}
private void DisplayTestFilters()
{
if (_options.TestList.Count > 0 || _options.WhereClauseSpecified)
{
_outWriter.WriteLine(ColorStyle.SectionHeader, "Test Filters");
if (_options.TestList.Count > 0)
foreach (string testName in _options.TestList)
_outWriter.WriteLabelLine(" Test: ", testName);
if (_options.WhereClauseSpecified)
_outWriter.WriteLabelLine(" Where: ", _options.WhereClause.Trim());
_outWriter.WriteLine();
}
}
private void RedirectErrorOutputAsRequested()
{
if (_options.ErrFileSpecified)
{
var errorStreamWriter = new StreamWriter(Path.Combine(_workDirectory, _options.ErrFile));
errorStreamWriter.AutoFlush = true;
_errorWriter = errorStreamWriter;
}
}
private ExtendedTextWriter CreateOutputWriter()
{
if (_options.OutFileSpecified)
{
var outStreamWriter = new StreamWriter(Path.Combine(_workDirectory, _options.OutFile));
outStreamWriter.AutoFlush = true;
return new ExtendedTextWrapper(outStreamWriter);
}
return _outWriter;
}
private void RestoreErrorOutput()
{
_errorWriter.Flush();
if (_options.ErrFileSpecified)
_errorWriter.Close();
}
private IResultWriter GetResultWriter(OutputSpecification spec)
{
return _resultService.GetResultWriter(spec.Format, new object[] {spec.Transform});
}
// This is public static for ease of testing
public static TestPackage MakeTestPackage(ConsoleOptions options)
{
TestPackage package = new TestPackage(options.InputFiles);
if (options.ProcessModelSpecified)
package.AddSetting(PackageSettings.ProcessModel, options.ProcessModel);
if (options.DomainUsageSpecified)
package.AddSetting(PackageSettings.DomainUsage, options.DomainUsage);
if (options.FrameworkSpecified)
package.AddSetting(PackageSettings.RuntimeFramework, options.Framework);
if (options.RunAsX86)
package.AddSetting(PackageSettings.RunAsX86, true);
if (options.DisposeRunners)
package.AddSetting(PackageSettings.DisposeRunners, true);
if (options.ShadowCopyFiles)
package.AddSetting(PackageSettings.ShadowCopyFiles, true);
if (options.LoadUserProfile)
package.AddSetting(PackageSettings.LoadUserProfile, true);
if (options.DefaultTimeout >= 0)
package.AddSetting(PackageSettings.DefaultTimeout, options.DefaultTimeout);
if (options.InternalTraceLevelSpecified)
package.AddSetting(PackageSettings.InternalTraceLevel, options.InternalTraceLevel);
if (options.ActiveConfigSpecified)
package.AddSetting(PackageSettings.ActiveConfig, options.ActiveConfig);
// Always add work directory, in case current directory is changed
var workDirectory = options.WorkDirectory ?? Environment.CurrentDirectory;
package.AddSetting(PackageSettings.WorkDirectory, workDirectory);
if (options.StopOnError)
package.AddSetting(PackageSettings.StopOnError, true);
if (options.MaxAgentsSpecified)
package.AddSetting(PackageSettings.MaxAgents, options.MaxAgents);
if (options.NumberOfTestWorkersSpecified)
package.AddSetting(PackageSettings.NumberOfTestWorkers, options.NumberOfTestWorkers);
if (options.RandomSeedSpecified)
package.AddSetting(PackageSettings.RandomSeed, options.RandomSeed);
if (options.DebugTests)
{
package.AddSetting(PackageSettings.DebugTests, true);
if (!options.NumberOfTestWorkersSpecified)
package.AddSetting(PackageSettings.NumberOfTestWorkers, 0);
}
if (options.PauseBeforeRun)
package.AddSetting(PackageSettings.PauseBeforeRun, true);
#if DEBUG
if (options.DebugAgent)
package.AddSetting(PackageSettings.DebugAgent, true);
//foreach (KeyValuePair<string, object> entry in package.Settings)
// if (!(entry.Value is string || entry.Value is int || entry.Value is bool))
// throw new Exception(string.Format("Package setting {0} is not a valid type", entry.Key));
#endif
if (options.DefaultTestNamePattern != null)
package.AddSetting(PackageSettings.DefaultTestNamePattern, options.DefaultTestNamePattern);
if (options.TestParameters != null)
package.AddSetting(PackageSettings.TestParameters, options.TestParameters);
return package;
}
private TestFilter CreateTestFilter(ConsoleOptions options)
{
ITestFilterBuilder builder = _filterService.GetTestFilterBuilder();
foreach (string testName in options.TestList)
builder.AddTest(testName);
if (options.WhereClauseSpecified)
builder.SelectWhere(options.WhereClause);
return builder.GetFilter();
}
private bool VerifyEngineSupport(ConsoleOptions options)
{
foreach (var spec in options.ResultOutputSpecifications)
{
bool available = false;
foreach (var format in _resultService.Formats)
{
if (spec.Format == format)
{
available = true;
break;
}
}
if (!available)
{
Console.WriteLine("Unknown result format: {0}", spec.Format);
return false;
}
}
return true;
}
#endregion
}
}
| |
using DynamicData.Binding;
using MaterialDesignThemes.Wpf;
using System.Collections.ObjectModel;
using System.Text.RegularExpressions;
using System.Windows;
using System.Xml.Serialization;
using System.Linq;
using System.Data;
using System.Collections.Generic;
using System.Data.SqlClient;
using System;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Linq;
using System.Windows.Controls;
namespace RelatedRows.Domain
{
public enum eAutoFilter
{
Everything,
TablesWithPrimaryKey,
MatchingColumnNames
}
public enum eViewType
{
Datasets,
Tables,
Queries
}
public enum eViewMode
{
Data,
Schema
}
[XmlRoot("Configuration", Namespace="", IsNullable=false)]
public partial class CConfiguration: AbstractNotifyPropertyChanged {
public CConfiguration() {
Dataset = new ObservableCollection<CDataset>();
Datasource = new ObservableCollection<CDatasource>();
}
[XmlElement("Datasource")]
public ObservableCollection<CDatasource> Datasource { get; set; }
[XmlElement("Dataset")]
public ObservableCollection<CDataset> Dataset { get; set; }
[XmlAttribute()]
public string defaultDataset { get; set; }
[XmlAttribute()]
public string defaultDatasource { get; set; }
}
[XmlRoot(Namespace="", IsNullable=true)]
public partial class CDatasource: AbstractNotifyPropertyChanged, IXmlSerializable
{
private string _connectionString;
public string ConnectionString
{
get {
if (null == _selectedProvider) return _connectionString;
return string.Format(
_selectedProvider.GetConnectionStringFormat(isTrustedConnection),
_serverName, _databaseName, _userName, _password);
}
set {
_connectionString = value;
serverName = GetString(value, "server");
databaseName = GetString(value, "database");
userName = GetString(value, "userid");
password = GetString(value, "password");
var trusted = GetString(value, "trusted");
isTrustedConnection = bool.Parse(trusted.Length > 0 ? trusted : "false");
}
}
public CDatasource()
{
ConnectionString = @"Data Source=localhost;Initial Catalog=Chinook;Integrated Security=False;
User=sa;Password=1234;Connect Timeout=120;MultipleActiveResultSets=True;Asynchronous Processing=True;Enlist=false;";
}
[XmlAttribute()]
public string name { get; set; }
private string _providerName;
[XmlAttribute]
public string providerName {
get { return _providerName; }
set {
SetAndRaise(ref _providerName, value);
OnPropertyChanged("IsValid");
if(null != Providers)
SelectedProvider = Providers.FirstOrDefault(p => p.Name.Equals(value));
}
}
[XmlIgnore]
public IEnumerable<IDatasourceProvider> Providers { get; set; }
[XmlIgnore]
public IEnumerable<string> ProviderNames {
get { return Providers.Select(p => p.Name); }
}
private IDatasourceProvider _selectedProvider;
[XmlIgnore]
public IDatasourceProvider SelectedProvider
{
get { return _selectedProvider; }
set
{
SetAndRaise(ref _selectedProvider, value);
}
}
private string _serverName;
[XmlIgnore]
public string serverName
{
get { return _serverName; }
set
{
SetAndRaise(ref _serverName, value);
OnPropertyChanged("IsValid");
}
}
private string _databaseName;
[XmlIgnore]
public string databaseName
{
get { return _databaseName; }
set
{
SetAndRaise(ref _databaseName, value);
OnPropertyChanged("IsValid");
}
}
private string _userName;
[XmlIgnore]
public string userName
{
get { return _userName; }
set
{
SetAndRaise(ref _userName, value);
OnPropertyChanged("IsValid");
}
}
private string _password;
[XmlIgnore]
public string password
{
get { return _password; }
set
{
SetAndRaise(ref _password, value);
OnPropertyChanged("IsValid");
}
}
private bool _isTrustedConnection = false;
[XmlIgnore]
public bool isTrustedConnection
{
get { return _isTrustedConnection; }
set
{
SetAndRaise(ref _isTrustedConnection, value);
OnPropertyChanged("notIsTrustedConnection");
OnPropertyChanged("IsValid");
}
}
[XmlIgnore]
public bool notIsTrustedConnection
{
get { return !_isTrustedConnection; }
}
[XmlIgnore]
public bool IsValid
{
get {
return !string.IsNullOrEmpty(serverName)
&& !string.IsNullOrEmpty(databaseName)
&& (!string.IsNullOrEmpty(providerName) && ProviderNames.Contains(providerName))
&& (isTrustedConnection ? true : !string.IsNullOrEmpty(userName));
}
}
private string GetString(string value, string group)
{
var reg = new Regex(@"(?<source>data\ssource=(?<server>.*?));(?<catalog>initial\scatalog=(?<database>.*?));(?<security>(integrated\ssecurity=(?<trusted>true|false))|(?<user>(user\sid|user)=(?<userid>.*?))?;(?<pwd>password=(?<password>.*?))?);.*?", RegexOptions.IgnoreCase | RegexOptions.Multiline);
var match = reg.Match(value);
if(match != null && match.Success)
{
return match.Groups[group].Value;
}
return string.Empty;
}
public XmlSchema GetSchema()
{
return null;
}
public void ReadXml(XmlReader reader)
{
var elem = XElement.ReadFrom(reader) as XElement;
name = elem.Attribute("name").Value;
providerName = elem.Attribute("provider").Value;
ConnectionString = elem.Element("ConnectionString").Value.Deflated();
}
public void WriteXml(XmlWriter writer)
{
writer.WriteAttributeString("name", name);
writer.WriteAttributeString("provider", providerName);
writer.WriteElementString("ConnectionString", ConnectionString.Inflated());
}
}
[XmlRoot(Namespace="", IsNullable=true)]
public partial class CRelationship: AbstractNotifyPropertyChanged {
[XmlAttribute()]
public string name { get; set; }
[XmlAttribute()]
public string fromTable { get; set; }
[XmlAttribute()]
public string toTable { get; set; }
[XmlElement("ColumnRelationship")]
public ObservableCollection<CColumnRelationShip> ColumnRelationship { get; set; }
public CRelationship()
{
ColumnRelationship = new ObservableCollection<CColumnRelationShip>();
}
public string GetName()
{
return string.Format("{0}->{1}{2}", fromTable, toTable,
string.Join(",", ColumnRelationship.Select(cr => $"{ cr.fromColumn}:{cr.toColumn}")));
}
}
[XmlType(AnonymousType = true)]
public partial class CColumnRelationShip
{
[XmlAttribute()]
public string fromColumn { get; set; }
[XmlAttribute()]
public string toColumn { get; set; }
}
[XmlRoot(Namespace="", IsNullable=true)]
public partial class CColumn : AbstractNotifyPropertyChanged
{
[XmlAttribute()]
public int ordinal { get; set; }
[XmlAttribute()]
public string name { get; set; }
[XmlAttribute()]
public eDbType DbType { get; set; }
[XmlAttribute()]
public int maxLen { get; set; }
[XmlAttribute()]
public int precision { get; set; }
[XmlAttribute()]
public bool isPrimaryKey { get; set; }
[XmlAttribute()]
public bool isForeignKey { get; set; }
[XmlAttribute()]
public bool isIdentity { get; set; }
[XmlAttribute()]
public bool isNullable { get; set; }
[XmlAttribute()]
public string defaultValue { get; set; }
//[XmlIgnore()]
//public bool isSelected { get; set; }
}
[XmlRoot(Namespace = "", IsNullable = false)]
public enum eDbType
{
bigint,
binary,
bit,
@bool,
@char,
custom,
date,
datetime,
datetime2,
datetimeoffset,
@decimal,
@float,
geography,
geometry,
guid,
hierarchyid,
image,
@int,
@long,
money,
nchar,
ntext,
numeric,
nvarchar,
real,
smalldatetime,
smallint,
smallmoney,
sql_variant,
@string,
text,
time,
timestamp,
tinyint,
uniqueidentifier,
varbinary,
varchar,
xml,
}
[XmlRoot(Namespace="", IsNullable=true)]
public partial class CTable: AbstractNotifyPropertyChanged {
public CTable() {
Column = new ObservableCollection<CColumn>();
Children = new ObservableCollection<CTable>();
Relationship = new ObservableCollection<CRelationship>();
Pager = new CPager(1, 1);
}
[XmlIgnore]
public ObservableCollection<CTable> Children { get; set; }
[XmlIgnore]
public ObservableCollection<CRelationship> Relationship { get; set; }
[XmlElement("Column")]
public ObservableCollection<CColumn> Column { get; set; }
private ITabularSource _data;
[XmlIgnore]
public ITabularSource Data {
get
{
return _data;
}
set
{
SetAndRaise(ref _data, value);
}
}
private DataTable _dataTable;
[XmlIgnore]
public DataTable DataTable
{
get
{
return _dataTable;
}
set
{
SetAndRaise(ref _dataTable, value);
}
}
private CPager _pager;
[XmlIgnore]
public CPager Pager
{
get { return _pager; }
set
{
SetAndRaise(ref _pager, value);
}
}
[XmlAttribute()]
public string name { get; set; }
[XmlAttribute()]
public string catalog { get; set; }
[XmlAttribute()]
public string schemaName { get; set; }
[XmlAttribute()]
public long rows { get; set; }
[XmlIgnore]
public bool requiresPagination
{
get { return rows > 250; }
}
[XmlIgnore()]
public string iconName
{
get
{
return name.UnQuoteName().Substring(0, 1);
}
}
[XmlIgnore]
public bool isDefault { get; set; }
[XmlIgnore]
public Visibility DefaultVisibility
{
get { return isDefault ? Visibility.Visible : Visibility.Collapsed; }
}
[XmlIgnore]
public Visibility RelationshipVisibility
{
get { return Relationship.Any() ? Visibility.Visible : Visibility.Collapsed; }
}
public override string ToString()
{
return name
.Replace("[", "").Replace("]", "")
.Replace("\"", "");
}
#region clipboard handling
private DataRowView _selectedRow;
[XmlIgnore]
public DataRowView SelectedRow
{
get { return _selectedRow; }
set
{
SetAndRaise(ref _selectedRow, value);
}
}
private DataGridCellInfo _selectedViewCell;
[XmlIgnore]
public DataGridCellInfo SelectedViewCell
{
get { return _selectedViewCell; }
set
{
SetAndRaise(ref _selectedViewCell, value);
if (SelectedRow != null
&& SelectedViewCell != null
&& SelectedViewCell.Column != null
&& SelectedViewCell.Column.Header != null)
{
SelectedColumn = SelectedViewCell.Column.Header.ToString();
SelectedRow = SelectedViewCell.Item as DataRowView;
ColumnValue = SelectedRow[SelectedColumn].ToString();
CopyTooltip = this.GetQueryTooltip(SelectedColumn, SelectedRow.Row); //TODO: fix it using data source provider
}
}
}
private string _selectedColumn;
public string SelectedColumn
{
get { return _selectedColumn; }
set { SetAndRaise(ref _selectedColumn, value); }
}
private string _copyTooltip = string.Empty;
[XmlIgnore]
public string CopyTooltip
{
get { return _copyTooltip; }
set
{
SetAndRaise(ref _copyTooltip, value);
OnPropertyChanged("CopyTooltipShort");
}
}
[XmlIgnore]
public string CopyTooltipShort
{
get
{
return string.Join(Environment.NewLine,
_copyTooltip.Split(new string[] { Environment.NewLine }, StringSplitOptions.None)
.Select(s => s.Substring(0, Math.Min(50, s.Length))
+ (s.Length > 50 ? "..." : "")));
}
}
#endregion
#region column expressions
public string ColumnExpression
{
get
{
if (!string.IsNullOrEmpty(SelectedColumn) && !string.IsNullOrEmpty(SelectedOperator) && !string.IsNullOrEmpty(ColumnValue))
{
if (!SelectedOperator.Equals("[NONE]"))
{
var column = Column.FirstOrDefault(c => c.name.UnQuoteName().Equals(SelectedColumn.UnQuoteName()));
return $"{SelectedColumn.QuoteName("\"", "\"")} {SelectedOperator} {column.GetDefaultValue(SelectedOperator, ColumnValue)}";
}
}
return string.Empty;
}
}
private string _columnValue;
[XmlIgnore]
public string ColumnValue
{
get { return _columnValue; }
set { SetAndRaise(ref _columnValue, value); }
}
private IList<string> _operators;
[XmlIgnore]
public IList<string> Operators
{
get
{
if(_operators == null)
{
_operators = GetColumnOperators().ToList();
SelectedOperator = _operators.FirstOrDefault();
}
return _operators;
}
}
private string _selectedOperator;
[XmlIgnore]
public string SelectedOperator
{
get { return _selectedOperator; }
set
{
SetAndRaise(ref _selectedOperator, value);
}
}
private IEnumerable<string> GetColumnOperators()
{
var list = new List<string> { "[NONE]" };
foreach (var c in Column)
{
list.AddRange(GetColumnOperators(c));
}
return list.Distinct();
}
private IEnumerable<string> GetColumnOperators(CColumn column)
{
var list = new List<string>();
string opString = string.Empty;
switch (GetMappingType(column.DbType.ToString()).ToString())
{
case "System.DateTime":
case "System.Int16":
case "System.Int32":
case "System.Int64":
case "System.Double":
opString = "=,<>,>,>=,<,<=,IS,IS NOT";
break;
case "System.Boolean":
opString = "=,<>,IS,IS NOT";
break;
default:
opString = "=,<>,LIKE,IS,IS NOT";
break;
}
foreach (string op in opString.Split(new char[] { ',' }))
if (!list.Contains(op))
list.Add(op);
return list;
}
private Type GetMappingType(string colType)
{
string typeName = colType.ToLower().Split(new char[] { '(' })[0];
var types = new Dictionary<Type, List<string>>{
{typeof(System.Int32), new List<string> {"int", "smallint", "long", "tinyint"}}
,{typeof(System.Byte[]), new List<string> {"image", "blob", "binary", "sql_variant", "varbinary"}}
,{typeof(System.DateTime), new List<string> {"datetime", "datetime2", "date", "timestamp", "datetimeoffset", "smalldatetime", "time"}}
,{typeof(System.Double), new List<string> {"money", "real", "number", "bigint", "decimal", "float", "numeric"}}
,{typeof(System.Boolean), new List<string> {"bit"}}
};
var theType = from key in types.Keys
where types[key].Contains(colType)
select key;
if (null != theType && null != theType.FirstOrDefault())
return theType.FirstOrDefault();
return typeof(System.String);
}
#endregion
}
public partial class CPager: AbstractNotifyPropertyChanged
{
public long RowsCount { get; set; }
public long Page { get; set; }
public long Pages { get; set; }
public long RowsPerPage { get; set; }
public long Skip { get { return (Page-1) * RowsPerPage; } }
public bool CanGoFirst { get { return Page > 2; } }
public bool CanGoPrev { get { return Page > 1; } }
public bool CanGoNext { get { return Page < Pages; } }
public bool CanGoLast { get { return Page < Pages-1; } }
public CPager(long rows, long rowsPerPage)
{
Reset(rows, rowsPerPage);
}
public void Reset(long rows, long rowsPerPage)
{
RowsCount = rows;
RowsPerPage = rowsPerPage;
Page = 1;
Pages = (RowsCount / RowsPerPage) + (RowsCount % RowsPerPage > 0 ? 1 : 0);
OnPropertyChanged("NextTooltip");
OnPropertyChanged("PrevTooltip");
OnPropertyChanged("CanGoFirst");
OnPropertyChanged("CanGoNext");
OnPropertyChanged("CanGoPrev");
OnPropertyChanged("CanGoLast");
OnPropertyChanged("FirstTooltip");
OnPropertyChanged("LastTooltip");
OnPropertyChanged("Visible");
OnPropertyChanged("EdgesVisible");
}
public void Navigate(string direction)
{
switch (direction)
{
case "first":
First();
break;
case "next":
Next();
break;
case "prev":
Prev();
break;
case "last":
Last();
break;
}
Logger.Log.Verbose("Navigated to page {@page} of {@pages}", Page, Pages);
}
public void First()
{
Page = 1;
OnPropertyChanged("NextTooltip");
OnPropertyChanged("PrevTooltip");
OnPropertyChanged("CanGoFirst");
OnPropertyChanged("CanGoNext");
OnPropertyChanged("CanGoPrev");
OnPropertyChanged("CanGoLast");
OnPropertyChanged("Page");
}
public void Next()
{
if (++Page > Pages) Last();
OnPropertyChanged("NextTooltip");
OnPropertyChanged("PrevTooltip");
OnPropertyChanged("CanGoFirst");
OnPropertyChanged("CanGoNext");
OnPropertyChanged("CanGoPrev");
OnPropertyChanged("CanGoLast");
OnPropertyChanged("Page");
}
public void Prev()
{
if (--Page == 0) First();
OnPropertyChanged("NextTooltip");
OnPropertyChanged("PrevTooltip");
OnPropertyChanged("CanGoFirst");
OnPropertyChanged("CanGoNext");
OnPropertyChanged("CanGoPrev");
OnPropertyChanged("CanGoLast");
OnPropertyChanged("Page");
}
public void Last()
{
Page = Pages;
OnPropertyChanged("NextTooltip");
OnPropertyChanged("PrevTooltip");
OnPropertyChanged("CanGoFirst");
OnPropertyChanged("CanGoNext");
OnPropertyChanged("CanGoPrev");
OnPropertyChanged("CanGoLast");
OnPropertyChanged("Page");
}
public string FirstTooltip
{
get { return $"Page 1 of {Pages}"; }
}
public string NextTooltip
{
get { return $"Page {Page+1} of {Pages}"; }
}
public string PrevTooltip
{
get { return $"Page {Page-1} of {Pages}"; }
}
public string LastTooltip
{
get { return $"Page {Pages} of {Pages}"; }
}
public Visibility Visible
{
get { return Pages > 1 ? Visibility.Visible : Visibility.Collapsed; }
}
public Visibility EdgesVisible
{
get { return Pages > 2 ? Visibility.Visible : Visibility.Collapsed; }
}
}
[XmlType(AnonymousType = true)]
public partial class CQuery: AbstractNotifyPropertyChanged
{
public CQuery()
{
Parameter = new ObservableCollection<CParameter>();
Children = new ObservableCollection<DataTable>();
}
[XmlElement("Parameter")]
public ObservableCollection<CParameter> Parameter { get; set; }
[XmlText()]
public string Text { get; set; }
[XmlIgnore]
public string FriendlyText {
get { return Text.Replace("<![CDATA[", string.Empty).Replace("]]>", string.Empty); }
set { Text = value; }
}
[XmlAttribute()]
public string name { get; set; }
[XmlAttribute()]
public string catalog { get; set; }
[XmlAttribute()]
public string schemaName { get; set; }
[XmlAttribute()]
public bool isStoreProcedure { get; set; }
[XmlIgnore]
public bool isScript { get { return type == "Q"; } }
[XmlAttribute]
public string type { get; set; }
[XmlAttribute]
public string defaultValue { get; set; }
[XmlIgnore()]
public string iconName
{
get
{
return name.Replace("[", "").Replace("]", "").Substring(0, 1);
}
}
private DataTable _dataTable;
[XmlIgnore]
public DataTable DataTable
{
get
{
return _dataTable;
}
set
{
SetAndRaise(ref _dataTable, value);
}
}
public string[] GetQueries()
{
var list = new List<string>();
var text = Text;
foreach (var par in GetParameters())
text = text.Replace(par.ParameterName, par.Value.ToString());
return text.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
}
private ObservableCollection<DataTable> _children;
[XmlIgnore]
public ObservableCollection<DataTable> Children
{
get
{
return _children;
}
set
{
SetAndRaise(ref _children, value);
}
}
public IDbDataParameter[] GetParameters()
{
return Parameter.Select(p => new SqlParameter(p.name, GetParameterValue(p))).ToArray();
}
private object GetParameterValue(CParameter p)
{
p.defaultValue = CheckDefaultValue(p.type, p.defaultValue);
switch (p.type)
{
case eDbType.bigint:
case eDbType.@long:
return Convert.ToInt64(p.defaultValue);
case eDbType.binary:
case eDbType.image:
case eDbType.varbinary:
var i = 0;
var bytes = new byte[p.defaultValue.Length];
foreach (var c in p.defaultValue)
bytes[i++] = Convert.ToByte(c);
return bytes;
case eDbType.bit:
case eDbType.@bool:
return Convert.ToBoolean(p.defaultValue);
case eDbType.@char:
case eDbType.nchar:
return Convert.ToChar(p.defaultValue);
case eDbType.date:
case eDbType.datetime:
case eDbType.datetime2:
case eDbType.datetimeoffset:
case eDbType.smalldatetime:
case eDbType.time:
case eDbType.timestamp:
return Convert.ToDateTime(p.defaultValue);
case eDbType.@decimal:
case eDbType.@float:
case eDbType.money:
case eDbType.numeric:
case eDbType.real:
case eDbType.smallmoney:
return Convert.ToDecimal(p.defaultValue);
case eDbType.geography:
case eDbType.geometry:
case eDbType.hierarchyid:
return p.defaultValue;
case eDbType.@int:
return Convert.ToInt32(p.defaultValue);
case eDbType.guid:
case eDbType.uniqueidentifier:
case eDbType.ntext:
case eDbType.nvarchar:
case eDbType.@string:
case eDbType.text:
case eDbType.varchar:
case eDbType.sql_variant:
case eDbType.xml:
return Convert.ToString(p.defaultValue);
case eDbType.smallint:
case eDbType.tinyint:
return Convert.ToInt16(p.defaultValue);
}
return p.defaultValue;
}
private string CheckDefaultValue(eDbType type, string value)
{
if (!string.IsNullOrEmpty(value)) return value;
switch (type)
{
case eDbType.binary:
case eDbType.image:
case eDbType.varbinary:
return default(byte).ToString();
case eDbType.bit:
case eDbType.@bool:
return default(bool).ToString();
case eDbType.@char:
case eDbType.nchar:
case eDbType.ntext:
case eDbType.nvarchar:
case eDbType.@string:
case eDbType.text:
case eDbType.varchar:
case eDbType.sql_variant:
case eDbType.xml:
case eDbType.geography:
case eDbType.geometry:
case eDbType.hierarchyid:
return default(string);
case eDbType.date:
case eDbType.datetime:
case eDbType.datetime2:
case eDbType.datetimeoffset:
case eDbType.smalldatetime:
case eDbType.time:
case eDbType.timestamp:
return default(DateTime).ToString();
case eDbType.@decimal:
case eDbType.@float:
case eDbType.money:
case eDbType.numeric:
case eDbType.real:
case eDbType.smallmoney:
return default(float).ToString();
case eDbType.guid:
case eDbType.uniqueidentifier:
return default(Guid).ToString();
case eDbType.smallint:
case eDbType.tinyint:
return default(Int16).ToString();
case eDbType.@int:
return default(int).ToString();
case eDbType.bigint:
case eDbType.@long:
return default(long).ToString();
}
return default(string);
}
[XmlIgnore]
public string key
{
get
{
return string.Format("{0}-{1}", name,
string.Join(",", Parameter.Select(p => $"{p.name}:{p.defaultValue}")));
}
}
private IEnumerable<CParameter> _selectedParameters;
[XmlIgnore]
public IEnumerable<CParameter> SelectedParameters
{
get { return _selectedParameters; }
set
{
SetAndRaise(ref _selectedParameters, value);
}
}
public override string ToString()
{
return name
.Replace("[", "").Replace("]", "")
.Replace("\"", "");
}
public static CQuery Clone(CQuery other)
{
return new CQuery
{
name = other.name,
catalog = other.catalog,
schemaName = other.schemaName,
type = other.type,
Parameter = new ObservableCollection<CParameter>(
other.Parameter.Select(p => new CParameter
{
name = p.name,
type = p.type,
length = p.length,
defaultValue = p.defaultValue
}))
};
}
}
[XmlRoot()]
public partial class CParameter: AbstractNotifyPropertyChanged, IXmlSerializable
{
[XmlAttribute()]
public string name { get; set; }
[XmlAttribute()]
public eDbType type { get; set; }
[XmlAttribute()]
public string customType { get; set; }
[XmlAttribute()]
public int length { get; set; }
private string _defaultValue;
[XmlAttribute()]
public string defaultValue {
get { return _defaultValue; }
set { SetAndRaise(ref _defaultValue, value); }
}
public XmlSchema GetSchema()
{
return null;
}
public void ReadXml(XmlReader reader)
{
var elem = XElement.ReadFrom(reader) as XElement;
name = elem.Attribute("name").Value;
length = int.Parse(elem.Attribute("length").Value);
if (elem.Attribute("defaultValue") != null)
defaultValue = elem.Attribute("defaultValue").Value;
var attType = elem.Attribute("type").Value;
try
{
type = (eDbType)Enum.Parse(typeof(eDbType), attType);
}
catch(Exception)
{
type = eDbType.custom;
customType = attType;
}
}
public void WriteXml(XmlWriter writer)
{
writer.WriteAttributeString("name", name);
writer.WriteAttributeString("type", type.ToString());
writer.WriteAttributeString("length", length.ToString());
writer.WriteAttributeString("defaultValue", defaultValue);
writer.WriteAttributeString("customType", customType);
}
private IEnumerable<CComboTrick> _comboTricks;
[XmlIgnore]
public IEnumerable<CComboTrick> ComboTricks {
get
{
if(_comboTricks == null)
{
_comboTricks = new List<CComboTrick> {
new CComboTrick { owner = this, action = "Remove Parameter", icon = "MinusCircleOutline" },
new CComboTrick { owner = this, action = "Clone Parameter" , icon = "PlusCircleMultipleOutline" }
};
}
return _comboTricks;
}
}
}
public partial class CComboTrick : AbstractNotifyPropertyChanged
{
public CParameter owner { get; set; }
public string action { get; set; }
public string icon { get; set; }
}
[XmlRoot(Namespace = "", IsNullable = true)]
public partial class CDataset : AbstractNotifyPropertyChanged
{
public CDataset() {
Relationship = new ObservableCollection<CRelationship>();
Table = new ObservableCollection<CTable>();
Query = new ObservableCollection<CQuery>();
QueryHistory = new ObservableCollection<CQuery>();
}
[XmlElement("Table")]
public ObservableCollection<CTable> Table { get; set; }
[XmlElement("Query")]
public ObservableCollection<CQuery> Query { get; set; }
[XmlIgnore]
public ObservableCollection<CQuery> QueryHistory { get; set; }
[XmlElement("Relationship")]
public ObservableCollection<CRelationship> Relationship { get; set; }
[XmlAttribute()]
public string name { get; set; }
[XmlAttribute()]
public string dataSourceName { get; set; }
[XmlAttribute()]
public string defaultTable { get; set; }
[XmlAttribute()]
public bool isDisabled { get; set; }
private bool _isSelected;
[XmlIgnore]
public bool isSelected
{
get
{
return _isSelected;
}
set
{
_isSelected = value;
OnPropertyChanged();
OnPropertyChanged("SelectedVisibility");
OnPropertyChanged("ColorZone");
}
}
[XmlIgnore]
public ColorZoneMode ColorZone
{
get { return isSelected ? ColorZoneMode.Accent : ColorZoneMode.Standard; }
}
[XmlIgnore]
public Visibility SelectedVisibility
{
get { return isSelected ? Visibility.Visible : Visibility.Collapsed; }
}
private bool _isDefault;
[XmlIgnore]
public bool isDefault
{
get { return _isDefault; }
set
{
_isDefault = value;
OnPropertyChanged();
OnPropertyChanged("DefaultVisibility");
}
}
[XmlIgnore]
public Visibility DefaultVisibility
{
get { return isDefault ? Visibility.Visible : Visibility.Collapsed; }
}
}
}
| |
//
// 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 Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Management.Models;
namespace Microsoft.WindowsAzure.Management.Models
{
/// <summary>
/// The Get Subscription operation response.
/// </summary>
public partial class SubscriptionGetResponse : OperationResponse
{
private string _accountAdminLiveEmailId;
/// <summary>
/// Optional. The live ID of the account administrator.
/// </summary>
public string AccountAdminLiveEmailId
{
get { return this._accountAdminLiveEmailId; }
set { this._accountAdminLiveEmailId = value; }
}
private int _currentCoreCount;
/// <summary>
/// Optional. The number of currently allocated cores.
/// </summary>
public int CurrentCoreCount
{
get { return this._currentCoreCount; }
set { this._currentCoreCount = value; }
}
private int _currentDnsServers;
/// <summary>
/// Optional. The current number of DNS servers allocated on this
/// subscription.
/// </summary>
public int CurrentDnsServers
{
get { return this._currentDnsServers; }
set { this._currentDnsServers = value; }
}
private int _currentHostedServices;
/// <summary>
/// Optional. The number of currently allocated cloud services.
/// </summary>
public int CurrentHostedServices
{
get { return this._currentHostedServices; }
set { this._currentHostedServices = value; }
}
private int _currentLocalNetworkSites;
/// <summary>
/// Optional. The current number of local virtual network sites that
/// are allocated on this subscription.
/// </summary>
public int CurrentLocalNetworkSites
{
get { return this._currentLocalNetworkSites; }
set { this._currentLocalNetworkSites = value; }
}
private int _currentStorageAccounts;
/// <summary>
/// Optional. The number of currently allocated storage accounts.
/// </summary>
public int CurrentStorageAccounts
{
get { return this._currentStorageAccounts; }
set { this._currentStorageAccounts = value; }
}
private int _currentVirtualNetworkSites;
/// <summary>
/// Optional. The number of currently allocated virtual network sites.
/// </summary>
public int CurrentVirtualNetworkSites
{
get { return this._currentVirtualNetworkSites; }
set { this._currentVirtualNetworkSites = value; }
}
private int _maximumCoreCount;
/// <summary>
/// Optional. The maximum number of cores that can be allocated on this
/// subscription.
/// </summary>
public int MaximumCoreCount
{
get { return this._maximumCoreCount; }
set { this._maximumCoreCount = value; }
}
private int _maximumDnsServers;
/// <summary>
/// Optional. The maximum number of DNS servers that can be allocated
/// on this subscription.
/// </summary>
public int MaximumDnsServers
{
get { return this._maximumDnsServers; }
set { this._maximumDnsServers = value; }
}
private int _maximumHostedServices;
/// <summary>
/// Optional. The maximum number of cloud services that can be
/// allocated on this subscription.
/// </summary>
public int MaximumHostedServices
{
get { return this._maximumHostedServices; }
set { this._maximumHostedServices = value; }
}
private int _maximumLocalNetworkSites;
/// <summary>
/// Optional. The maximum number of local virtual network sites that
/// can be allocated on this subscription.
/// </summary>
public int MaximumLocalNetworkSites
{
get { return this._maximumLocalNetworkSites; }
set { this._maximumLocalNetworkSites = value; }
}
private int _maximumStorageAccounts;
/// <summary>
/// Optional. The maximum number of storage accounts that can be
/// allocated on this subscription.
/// </summary>
public int MaximumStorageAccounts
{
get { return this._maximumStorageAccounts; }
set { this._maximumStorageAccounts = value; }
}
private int _maximumVirtualNetworkSites;
/// <summary>
/// Optional. The maximum number of virtual network sites that can be
/// allocated on this subscription.
/// </summary>
public int MaximumVirtualNetworkSites
{
get { return this._maximumVirtualNetworkSites; }
set { this._maximumVirtualNetworkSites = value; }
}
private string _serviceAdminLiveEmailId;
/// <summary>
/// Optional. The live ID of the subscription administrator.
/// </summary>
public string ServiceAdminLiveEmailId
{
get { return this._serviceAdminLiveEmailId; }
set { this._serviceAdminLiveEmailId = value; }
}
private string _subscriptionID;
/// <summary>
/// Optional. The subscription ID that the operation was called on.
/// </summary>
public string SubscriptionID
{
get { return this._subscriptionID; }
set { this._subscriptionID = value; }
}
private string _subscriptionName;
/// <summary>
/// Optional. The user-supplied name for the subscription.
/// </summary>
public string SubscriptionName
{
get { return this._subscriptionName; }
set { this._subscriptionName = value; }
}
private SubscriptionStatus _subscriptionStatus;
/// <summary>
/// Optional. The subscription status.
/// </summary>
public SubscriptionStatus SubscriptionStatus
{
get { return this._subscriptionStatus; }
set { this._subscriptionStatus = value; }
}
/// <summary>
/// Initializes a new instance of the SubscriptionGetResponse class.
/// </summary>
public SubscriptionGetResponse()
{
}
}
}
| |
// <copyright file="Rfc6455Handler.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.
// </copyright>
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
namespace OpenQA.Selenium.Safari.Internal.Handlers
{
/// <summary>
/// Provides a handler for the RFC 6455 version of the WebSocket protocol.
/// </summary>
internal class Rfc6455Handler : RequestHandler
{
private const string WebSocketResponseGuid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
private WebSocketHttpRequest request;
private ReadState readState = new ReadState();
/// <summary>
/// Initializes a new instance of the <see cref="Rfc6455Handler"/> class.
/// </summary>
/// <param name="request">The <see cref="WebSocketHttpRequest"/> to handle.</param>
private Rfc6455Handler(WebSocketHttpRequest request)
{
this.request = request;
}
/// <summary>
/// Creates a new instance of the handler.
/// </summary>
/// <param name="request">The request to handle.</param>
/// <returns>A <see cref="IHandler"/> to perform handling of subsequent requests.</returns>
public static IHandler Create(WebSocketHttpRequest request)
{
return new Rfc6455Handler(request);
}
/// <summary>
/// Receives data from the protocol.
/// </summary>
protected override void ProcessReceivedData()
{
while (Data.Count >= 2)
{
var isFinal = (Data[0] & 128) != 0;
var reservedBits = Data[0] & 112;
var frameType = (FrameType)(Data[0] & 15);
var isMasked = (Data[1] & 128) != 0;
var length = Data[1] & 127;
if (!isMasked
|| !Enum.IsDefined(typeof(FrameType), frameType)
|| reservedBits != 0 // Must be zero per spec 5.2
|| (frameType == FrameType.Continuation && !this.readState.FrameType.HasValue))
{
throw new WebSocketException(WebSocketStatusCodes.ProtocolError);
}
var index = 2;
int payloadLength;
if (length == 127)
{
if (Data.Count < index + 8)
{
// Not complete
return;
}
payloadLength = Data.Skip(index).Take(8).ToArray().ToLittleEndianInt32();
index += 8;
}
else if (length == 126)
{
if (Data.Count < index + 2)
{
// Not complete
return;
}
payloadLength = Data.Skip(index).Take(2).ToArray().ToLittleEndianInt32();
index += 2;
}
else
{
payloadLength = length;
}
if (Data.Count < index + 4)
{
// Not complete
return;
}
var maskBytes = Data.Skip(index).Take(4).ToArray();
index += 4;
if (Data.Count < index + payloadLength)
{
// Not complete
return;
}
var payload = Data
.Skip(index)
.Take(payloadLength)
.Select((x, i) => (byte)(x ^ maskBytes[i % 4]));
this.readState.Data.AddRange(payload);
Data.RemoveRange(0, index + payloadLength);
if (frameType != FrameType.Continuation)
{
this.readState.FrameType = frameType;
}
if (isFinal && this.readState.FrameType.HasValue)
{
var stateData = this.readState.Data.ToArray();
var stateFrameType = this.readState.FrameType;
this.readState.Clear();
this.ProcessFrame(stateFrameType.Value, stateData);
}
}
}
/// <summary>
/// Prepares a text frame for the given text.
/// </summary>
/// <param name="text">The text for which to prepare the frame.</param>
/// <returns>A byte array representing the frame in the WebSocket protocol.</returns>
protected override byte[] GetTextFrame(string text)
{
return ConstructFrame(Encoding.UTF8.GetBytes(text), FrameType.Text);
}
/// <summary>
/// Prepares a close frame for the given connection.
/// </summary>
/// <param name="code">The code to use in closing the connection.</param>
/// <returns>A byte array representing the frame in the WebSocket protocol.</returns>
protected override byte[] GetCloseFrame(int code)
{
return ConstructFrame(Convert.ToUInt16(code).ToBigEndianByteArray(), FrameType.Close);
}
/// <summary>
/// Gets the handshake for WebSocket protocol.
/// </summary>
/// <returns>A byte array representing the handshake in the WebSocket protocol.</returns>
protected override byte[] GetHandshake()
{
var builder = new StringBuilder();
builder.Append("HTTP/1.1 101 Switching Protocols\r\n");
builder.Append("Upgrade: websocket\r\n");
builder.Append("Connection: Upgrade\r\n");
var responseKey = CreateResponseKey(this.request["Sec-WebSocket-Key"]);
builder.AppendFormat("Sec-WebSocket-Accept: {0}\r\n", responseKey);
builder.Append("\r\n");
return Encoding.ASCII.GetBytes(builder.ToString());
}
/// <summary>
/// Prepares a binary frame for the given binary data.
/// </summary>
/// <param name="frameData">The binary data for which to prepare the frame.</param>
/// <returns>A byte array representing the frame in the WebSocket protocol.</returns>
protected override byte[] GetBinaryFrame(byte[] frameData)
{
return ConstructFrame(frameData, FrameType.Binary);
}
private static byte[] ConstructFrame(byte[] payload, FrameType frameType)
{
byte[] frame = { 0 };
using (var memoryStream = new MemoryStream())
{
byte op = Convert.ToByte(Convert.ToByte(frameType, CultureInfo.InvariantCulture) + 128, CultureInfo.InvariantCulture);
memoryStream.WriteByte(op);
if (payload.Length > ushort.MaxValue)
{
memoryStream.WriteByte(127);
var lengthBytes = Convert.ToUInt64(payload.Length).ToBigEndianByteArray();
memoryStream.Write(lengthBytes, 0, lengthBytes.Length);
}
else if (payload.Length > 125)
{
memoryStream.WriteByte(126);
var lengthBytes = Convert.ToUInt16(payload.Length).ToBigEndianByteArray();
memoryStream.Write(lengthBytes, 0, lengthBytes.Length);
}
else
{
memoryStream.WriteByte(Convert.ToByte(payload.Length, CultureInfo.InvariantCulture));
}
memoryStream.Write(payload, 0, payload.Length);
frame = memoryStream.ToArray();
}
return frame;
}
private static string CreateResponseKey(string requestKey)
{
byte[] responseKeyBytes = { 0 };
var combined = requestKey + WebSocketResponseGuid;
using (SHA1 hashAlgorithm = SHA1.Create())
{
responseKeyBytes = hashAlgorithm.ComputeHash(Encoding.ASCII.GetBytes(combined));
}
return Convert.ToBase64String(responseKeyBytes);
}
private static string ReadUTF8PayloadData(byte[] bytes)
{
var encoding = new UTF8Encoding(false, true);
try
{
return encoding.GetString(bytes);
}
catch (ArgumentException)
{
throw new WebSocketException(WebSocketStatusCodes.InvalidFramePayloadData);
}
}
private void ProcessFrame(FrameType frameType, byte[] data)
{
switch (frameType)
{
case FrameType.Close:
if (data.Length == 1 || data.Length > 125)
{
throw new WebSocketException(WebSocketStatusCodes.ProtocolError);
}
if (data.Length >= 2)
{
var closeCode = Convert.ToUInt16(data.Take(2).ToArray().ToLittleEndianInt32(), CultureInfo.InvariantCulture);
if (!WebSocketStatusCodes.ValidCloseCodes.Contains(closeCode) && (closeCode < 3000 || closeCode > 4999))
{
throw new WebSocketException(WebSocketStatusCodes.ProtocolError);
}
}
if (data.Length > 2)
{
ReadUTF8PayloadData(data.Skip(2).ToArray());
}
this.OnCloseHandled(new EventArgs());
break;
case FrameType.Binary:
this.OnBinaryMessageHandled(new BinaryMessageHandledEventArgs(data));
break;
case FrameType.Text:
this.OnTextMessageHandled(new TextMessageHandledEventArgs(ReadUTF8PayloadData(data)));
break;
default:
break;
}
}
}
}
| |
//#define DEBUG
//#define RETX_DEBUG
using System;
using System.Collections.Generic;
using System.Text;
namespace ICSimulator
{
public class AFCBufferSlot : IComparable
{
Flit m_f;
public ulong inTimeStamp;
public Flit flit { get { return m_f; } set { m_f = value; } }
public AFCBufferSlot(Flit f)
{
m_f = f;
inTimeStamp = Simulator.CurrentRound;
}
public int CompareTo(object o)
{
if (o is AFCBufferSlot)
return Router_Flit_OldestFirst._rank(m_f, (o as AFCBufferSlot).m_f);
else
throw new ArgumentException("bad comparison");
}
public void getNewTimeStamp()
{
inTimeStamp = Simulator.CurrentRound;
}
}
public class AFCUtilAvg
{
double m_avg;
double m_window_sum;
double[] m_window;
int m_window_ptr;
public AFCUtilAvg()
{
m_window = new double[Config.afc_avg_window];
m_window_ptr = 0;
m_window_sum = 0;
m_avg = 0;
}
public void Add(double util)
{
// add new sample to window and update sum
m_window_sum -= m_window[m_window_ptr];
m_window[m_window_ptr] = util;
m_window_sum += util;
m_window_ptr = (m_window_ptr + 1) % Config.afc_avg_window;
// mix window-average into EWMA
m_avg = Config.afc_ewma_history * m_avg +
(1 - Config.afc_ewma_history) * (m_window_sum / Config.afc_avg_window);
}
public double Avg { get { return m_avg; } }
}
public class Router_AFC : Router
{
// injectSlot is from Node
protected Flit m_injectSlot;
// buffers, indexed by physical channel and virtual network
protected MinHeap<AFCBufferSlot>[,] m_buf;
int m_buf_occupancy;
// buffers active?
protected bool m_buffered;
public Router_AFC(Coord myCoord)
: base(myCoord)
{
m_injectSlot = null;
m_buf = new MinHeap<AFCBufferSlot>[5, Config.afc_vnets];
for (int pc = 0; pc < 5; pc++)
for (int i = 0; i < Config.afc_vnets; i++)
m_buf[pc, i] = new MinHeap<AFCBufferSlot>();
m_buffered = false;
m_buf_occupancy = 0;
}
protected Router_AFC getNeigh(int dir)
{
return neigh[dir] as Router_AFC;
}
// accept one ejected flit into rxbuf
protected void acceptFlit(Flit f)
{
statsEjectFlit(f);
if (f.packet.nrOfArrivedFlits + 1 == f.packet.nrOfFlits)
statsEjectPacket(f.packet);
m_n.receiveFlit(f);
}
Flit ejectLocal()
{
// eject locally-destined flit (highest-ranked, if multiple)
Flit ret = null;
int bestDir = -1;
for (int dir = 0; dir < 4; dir++)
if (linkIn[dir] != null && linkIn[dir].Out != null &&
linkIn[dir].Out.state != Flit.State.Placeholder &&
linkIn[dir].Out.dest.ID == ID &&
(ret == null || rank(linkIn[dir].Out, ret) < 0))
{
ret = linkIn[dir].Out;
bestDir = dir;
}
if (bestDir != -1) linkIn[bestDir].Out = null;
#if DEBUG
if (ret != null)
Console.WriteLine("ejecting flit {0}.{1} at node {2} cyc {3}", ret.packet.ID, ret.flitNr, coord, Simulator.CurrentRound);
#endif
return ret;
}
// keep these as member vars so we don't have to allocate on every step
// (why can't we have arrays on the stack like in C?)
Flit[] input = new Flit[4];
AFCBufferSlot[] requesters = new AFCBufferSlot[5];
int[] requester_dir = new int[5];
Queue<AFCBufferSlot> m_freeAFCSlots = new Queue<AFCBufferSlot>();
AFCBufferSlot getFreeBufferSlot(Flit f)
{
if (m_freeAFCSlots.Count > 0)
{
AFCBufferSlot s = m_freeAFCSlots.Dequeue();
s.flit = f;
s.getNewTimeStamp();
return s;
}
else
return new AFCBufferSlot(f);
}
void returnFreeBufferSlot(AFCBufferSlot s)
{
m_freeAFCSlots.Enqueue(s);
}
void switchBufferless()
{
m_buffered = false;
}
void switchBuffered()
{
m_buffered = true;
if (m_injectSlot != null)
{
InjectFlit(m_injectSlot);
m_injectSlot = null;
}
}
AFCUtilAvg m_util_avg = new AFCUtilAvg();
protected override void _doStep()
{
int flit_count = 0;
for (int dir = 0; dir < 4; dir++)
if (linkIn[dir] != null && linkIn[dir].Out != null)
flit_count++;
m_util_avg.Add((double)flit_count / neighbors);
Simulator.stats.afc_avg.Add(m_util_avg.Avg);
Simulator.stats.afc_avg_bysrc[ID].Add(m_util_avg.Avg);
bool old_status = m_buffered;
bool new_status = old_status;
bool gossip_induced = false;
if (Config.afc_force)
{
new_status = Config.afc_force_buffered;
}
else
{
if (!m_buffered &&
(m_util_avg.Avg > Config.afc_buf_threshold))
new_status = true;
if (m_buffered &&
(m_util_avg.Avg < Config.afc_bless_threshold) &&
m_buf_occupancy == 0)
new_status = false;
// check at least one free slot in downstream routers; if not, gossip-induced switch
for (int n = 0; n < 4; n++)
{
Router_AFC nr = getNeigh(n);
if (nr == null) continue;
int oppDir = (n + 2) % 4;
for (int vnet = 0; vnet < Config.afc_vnets; vnet++)
{
int occupancy = nr.m_buf[oppDir, vnet].Count;
if ((capacity(vnet) - occupancy) < 2)
{
gossip_induced = true;
break;
}
}
}
if (gossip_induced) new_status = true;
}
// perform switching and stats accumulation
if (old_status && !new_status)
{
switchBufferless();
Simulator.stats.afc_switch.Add();
Simulator.stats.afc_switch_bless.Add();
Simulator.stats.afc_switch_bysrc[ID].Add();
Simulator.stats.afc_switch_bless_bysrc[ID].Add();
}
if (!old_status && new_status)
{
switchBuffered();
Simulator.stats.afc_switch.Add();
Simulator.stats.afc_switch_buf.Add();
Simulator.stats.afc_switch_bysrc[ID].Add();
Simulator.stats.afc_switch_buf_bysrc[ID].Add();
}
if (m_buffered)
{
Simulator.stats.afc_buffered.Add();
Simulator.stats.afc_buffered_bysrc[ID].Add();
if (gossip_induced)
{
Simulator.stats.afc_gossip.Add();
Simulator.stats.afc_gossip_bysrc[ID].Add();
}
}
else
{
Simulator.stats.afc_bless.Add();
Simulator.stats.afc_bless_bysrc[ID].Add();
}
if (m_buffered)
{
Simulator.stats.afc_buf_enabled.Add();
Simulator.stats.afc_buf_enabled_bysrc[ID].Add();
Simulator.stats.afc_buf_occupancy.Add(m_buf_occupancy);
Simulator.stats.afc_buf_occupancy_bysrc[ID].Add(m_buf_occupancy);
// grab inputs into buffers
for (int dir = 0; dir < 4; dir++)
{
if (linkIn[dir] != null && linkIn[dir].Out != null)
{
Flit f = linkIn[dir].Out;
linkIn[dir].Out = null;
f.bufferInTime = Simulator.CurrentRound;
AFCBufferSlot slot = getFreeBufferSlot(f);
m_buf[dir, f.packet.getClass()].Enqueue(slot);
m_buf_occupancy++;
Simulator.stats.afc_buf_write.Add();
Simulator.stats.afc_buf_write_bysrc[ID].Add();
}
}
// perform arbitration: (i) collect heads of each virtual-net
// heap (which represents many VCs) to obtain a single requester
// per physical channel; (ii) request outputs among these
// requesters based on DOR; (iii) select a single winner
// per output
for (int i = 0; i < 5; i++)
{
requesters[i] = null;
requester_dir[i] = -1;
}
// find the highest-priority vnet head for each input PC
for (int pc = 0; pc < 5; pc++)
for (int vnet = 0; vnet < Config.afc_vnets; vnet++)
if (m_buf[pc, vnet].Count > 0)
{
AFCBufferSlot top = m_buf[pc, vnet].Peek();
PreferredDirection pd = determineDirection(top.flit, coord);
int outdir = (pd.xDir != Simulator.DIR_NONE) ?
pd.xDir : pd.yDir;
if (outdir == Simulator.DIR_NONE)
outdir = 4; // local ejection
// skip if (i) not local ejection and (ii)
// destination router is buffered and (iii)
// no credits left to destination router
if (outdir != 4)
{
Router_AFC nrouter = (Router_AFC)neigh[outdir];
int ndir = (outdir + 2) % 4;
if (nrouter.m_buf[ndir, vnet].Count >= capacity(vnet) &&
nrouter.m_buffered)
continue;
}
// otherwise, contend for top requester from this
// physical channel
if (requesters[pc] == null ||
top.CompareTo(requesters[pc]) < 0)
{
requesters[pc] = top;
requester_dir[pc] = outdir;
}
}
// find the highest-priority requester for each output, and pop
// it from its heap
for (int outdir = 0; outdir < 5; outdir++)
{
AFCBufferSlot top = null;
AFCBufferSlot top2 = null;
int top_indir = -1;
int top2_indir = -1;
int nrWantToEject = 0;
for (int req = 0; req < 5; req++)
if (requesters[req] != null &&
requester_dir[req] == outdir)
{
if (top == null ||
requesters[req].CompareTo(top) < 0)
{
top2 = top;
top2_indir = top_indir;
top = requesters[req];
top_indir = req;
nrWantToEject++;
}
}
if (outdir == 4)
switch (nrWantToEject)
{
case 0: Simulator.stats.eject_0.Add(); break;
case 1: Simulator.stats.eject_1.Add(); break;
case 2: Simulator.stats.eject_2.Add(); break;
case 3: Simulator.stats.eject_3.Add(); break;
case 4: Simulator.stats.eject_4.Add(); break;
default: throw new Exception("Ejection problem");
}
if (top_indir != -1)
{
m_buf[top_indir, top.flit.packet.getClass()].Dequeue();
if (top.inTimeStamp == Simulator.CurrentRound)
Simulator.stats.buffer_bypasses.Add();
Simulator.stats.buffer_comparisons.Add();
Simulator.stats.afc_buf_read.Add();
Simulator.stats.afc_buf_read_bysrc[ID].Add();
Simulator.stats.afc_xbar.Add();
Simulator.stats.afc_xbar_bysrc[ID].Add();
if (top_indir == 4)
statsInjectFlit(top.flit);
// propagate to next router (or eject)
if (outdir == 4)
acceptFlit(top.flit);
else
linkOut[outdir].In = top.flit;
returnFreeBufferSlot(top);
m_buf_occupancy--;
}
if (Config.ejectCount == 2 && outdir == 4 && top2_indir != -1)
{
m_buf[top2_indir, top2.flit.packet.getClass()].Dequeue();
if (top2 != null)
acceptFlit(top2.flit);
returnFreeBufferSlot(top2);
m_buf_occupancy--;
}
}
}
else
{
Flit[] eject = new Flit[4];
eject[0] = eject[1] = eject[2] = eject[3] = null;
int ejCount = 0;
for (int i = 0; i < Config.ejectCount; i++)
{
eject[ejCount] = ejectLocal();
ejCount++;
}
for (int i = 0; i < 4; i++) input[i] = null;
// grab inputs into a local array so we can sort
int c = 0;
for (int dir = 0; dir < 4; dir++)
if (linkIn[dir] != null && linkIn[dir].Out != null)
{
input[c++] = linkIn[dir].Out;
linkIn[dir].Out.inDir = dir;
linkIn[dir].Out = null;
}
// sometimes network-meddling such as flit-injection can put unexpected
// things in outlinks...
int outCount = 0;
for (int dir = 0; dir < 4; dir++)
if (linkOut[dir] != null && linkOut[dir].In != null)
outCount++;
bool wantToInject = m_injectSlot != null;
bool canInject = (c + outCount) < neighbors;
bool starved = wantToInject && !canInject;
if (starved)
{
Flit starvedFlit = m_injectSlot;
Simulator.controller.reportStarve(coord.ID);
statsStarve(starvedFlit);
}
if (canInject && wantToInject)
{
Flit inj = null;
if (m_injectSlot != null)
{
inj = m_injectSlot;
m_injectSlot = null;
}
else
throw new Exception("trying to inject a null flit");
input[c++] = inj;
#if DEBUG
Console.WriteLine("injecting flit {0}.{1} at node {2} cyc {3}",
m_injectSlot.packet.ID, m_injectSlot.flitNr, coord, Simulator.CurrentRound);
#endif
statsInjectFlit(inj);
}
for (int i = 0; i < Config.ejectCount; i++)
{
if (eject[i] != null)
acceptFlit(eject[i]);
}
// inline bubble sort is faster for this size than Array.Sort()
// sort input[] by descending priority. rank(a,b) < 0 iff a has higher priority.
for (int i = 0; i < 4; i++)
for (int j = i + 1; j < 4; j++)
if (input[j] != null &&
(input[i] == null ||
rank(input[j], input[i]) < 0))
{
Flit t = input[i];
input[i] = input[j];
input[j] = t;
}
// assign outputs
for (int i = 0; i < 4 && input[i] != null; i++)
{
PreferredDirection pd = determineDirection(input[i], coord);
int outDir = -1;
if (pd.xDir != Simulator.DIR_NONE && linkOut[pd.xDir].In == null)
{
linkOut[pd.xDir].In = input[i];
outDir = pd.xDir;
}
else if (pd.yDir != Simulator.DIR_NONE && linkOut[pd.yDir].In == null)
{
linkOut[pd.yDir].In = input[i];
outDir = pd.yDir;
}
// deflect!
else
{
input[i].Deflected = true;
int dir = 0;
if (Config.randomize_defl) dir = Simulator.rand.Next(4); // randomize deflection dir (so no bias)
for (int count = 0; count < 4; count++, dir = (dir + 1) % 4)
if (linkOut[dir] != null && linkOut[dir].In == null)
{
linkOut[dir].In = input[i];
outDir = dir;
break;
}
if (outDir == -1) throw new Exception(
String.Format("Ran out of outlinks in arbitration at node {0} on input {1} cycle {2} flit {3} c {4} neighbors {5} outcount {6}", coord, i, Simulator.CurrentRound, input[i], c, neighbors, outCount));
}
}
}
}
public override bool canInjectFlit(Flit f)
{
int cl = f.packet.getClass();
if (m_buffered)
return m_buf[4, cl].Count < capacity(cl);
else
return m_injectSlot == null;
}
public override void InjectFlit(Flit f)
{
Simulator.stats.afc_vnet[f.packet.getClass()].Add();
if (m_buffered)
{
//AFCBufferSlot slot = new AFCBufferSlot(f);
AFCBufferSlot slot = getFreeBufferSlot(f);
m_buf[4, f.packet.getClass()].Enqueue(slot);
m_buf_occupancy++;
Simulator.stats.afc_buf_write.Add();
Simulator.stats.afc_buf_write_bysrc[ID].Add();
}
else
{
if (m_injectSlot != null)
throw new Exception("Trying to inject twice in one cycle");
m_injectSlot = f;
}
}
int capacity(int cl)
{
// in the future, we might size each virtual network differently; for now,
// we use just one virtual network (since there is no receiver backpressure)
return Config.afc_buf_per_vnet;
}
public override void flush()
{
m_injectSlot = null;
}
protected virtual bool needFlush(Flit f) { return false; }
}
}
| |
// SharpMath - C# Mathematical Library
// Copyright (c) 2014 Morten Bakkedal
// This code is published under the MIT License.
using System;
using System.Collections.Generic;
using SharpMath.LinearAlgebra;
#pragma warning disable
namespace SharpMath.Statistics.Regressions
{
/// <summary>
/// Linear regression.
/// http://en.wikipedia.org/w/index.php?title=Linear_regression&oldid=595475658#Introduction_to_linear_regression
/// </summary>
[Serializable]
public class SimpleLinearRegression
{
private int p;
private SimpleLinearRegression(Vector y, Matrix x, double alpha, Vector beta, int p)
{
this.p = p;
Y = y;
X = x;
Alpha = alpha;
Beta = beta;
}
/// <summary>
/// 1-dimensional linear regression.
/// </summary>
public static SimpleLinearRegression Fit(Vector y, Vector x)
{
return Fit(y, (Matrix)x);
}
public static SimpleLinearRegression Fit(Vector y, Vector x, bool intercept)
{
return Fit(y, (Matrix)x, intercept);
}
public static SimpleLinearRegression Fit(Vector y, Matrix x)
{
return Fit(y, x, false);
}
public static SimpleLinearRegression Fit(Vector y, Matrix x, bool intercept)
{
if (y == null || x == null)
{
throw new ArgumentNullException();
}
// Number of fitting points for the linear regression.
int n = y.Length;
// And the dimension.
int p = x.Columns;
if (x.Rows != n)
{
throw new ArgumentException("Dimensions doesn't match.");
}
double alpha;
Vector beta;
throw new NotImplementedException();
/*if (intercept)
{
double[,] a = new double[n, p + 1];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < p; j++)
{
a[i, j] = x[i, j];
}
a[i, p] = 1.0;
}
Vector b = SingularValueDecomposition.PseudoInverse(new Matrix(a)) * y;
beta = b.GetVector(0, p);
alpha = b[p];
}
else
{
//beta = Matrix.Inverse(Matrix.Transpose(x) * x) * Matrix.Transpose(x) * y;
beta = SingularValueDecomposition.PseudoInverse(x) * y;
alpha = 0.0;
}
return new SimpleLinearRegression(y, x, alpha, beta, p);*/
}
public static SimpleLinearRegression Fit(IEnumerable<double> y, IEnumerable<Vector> x)
{
return Fit(new Vector(y), CreateX(new List<Vector>(x).ToArray()));
}
public static SimpleLinearRegression Fit(IEnumerable<double> y, IEnumerable<Vector> x, bool intercept)
{
return Fit(new Vector(y), CreateX(new List<Vector>(x).ToArray()), intercept);
}
private static Matrix CreateX(Vector[] x)
{
int n = x.Length;
int p = x[0].Length;
double[,] x2 = new double[n, p];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < p; j++)
{
if (x[i].Length != p)
{
throw new ArgumentException();
}
x2[i, j] = x[i][j];
}
}
return new Matrix(x2);
}
public double Value(double x)
{
if (p != 1)
{
throw new NotSupportedException("Only supported for the 1-dimensional case.");
}
return Value(new Vector(new double[] { x }));
}
public double Value(Vector x)
{
if (x == null)
{
throw new ArgumentNullException();
}
if (x.Length != p)
{
throw new ArgumentException("Dimensions doesn't match.");
}
// The actual independent variables are treated as a row-vector, just as in the estimation.
//return (Alpha + Matrix.Transpose(x) * Beta)[0];
return Value(Matrix.Transpose(x));
}
private double Value(Matrix x)
{
return (Alpha + x * Beta)[0];
}
public Vector Y
{
get;
private set;
}
public Matrix X
{
get;
private set;
}
public double Alpha
{
get;
private set;
}
public Vector Beta
{
get;
private set;
}
/*public Vector Epsilon
{
get;
private set;
}
public double Sigma0
{
get;
private set;
}
public Vector Sigma
{
get;
private set;
}*/
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.ComponentModel.Design.Serialization;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
namespace System.ComponentModel
{
/// <summary>
/// Converts the value of an object into a different data type.
/// </summary>
public class TypeConverter
{
/// <summary>
/// Gets a value indicating whether this converter can convert an object in the
/// given source type to the native type of the converter.
/// </summary>
public bool CanConvertFrom(Type sourceType) => CanConvertFrom(null, sourceType);
/// <summary>
/// Gets a value indicating whether this converter can convert an object in the given
/// source type to the native type of the converter using the context.
/// </summary>
public virtual bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
=> sourceType == typeof(InstanceDescriptor);
/// <summary>
/// Gets a value indicating whether this converter can convert an object to the given
/// destination type using the context.
/// </summary>
public bool CanConvertTo(Type destinationType) => CanConvertTo(null, destinationType);
/// <summary>
/// Gets a value indicating whether this converter can convert an object to the given
/// destination type using the context.
/// </summary>
public virtual bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return destinationType == typeof(string);
}
/// <summary>
/// Converts the given value to the converter's native type.
/// </summary>
public object ConvertFrom(object value) => ConvertFrom(null, CultureInfo.CurrentCulture, value);
/// <summary>
/// Converts the given object to the converter's native type.
/// </summary>
public virtual object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (value is InstanceDescriptor instanceDescriptor)
{
return instanceDescriptor.Invoke();
}
throw GetConvertFromException(value);
}
/// <summary>
/// Converts the given string to the converter's native type using the invariant culture.
/// </summary>
public object ConvertFromInvariantString(string text)
{
return ConvertFromString(null, CultureInfo.InvariantCulture, text);
}
/// <summary>
/// Converts the given string to the converter's native type using the invariant culture.
/// </summary>
public object ConvertFromInvariantString(ITypeDescriptorContext context, string text)
{
return ConvertFromString(context, CultureInfo.InvariantCulture, text);
}
/// <summary>
/// Converts the specified text into an object.
/// </summary>
public object ConvertFromString(string text) => ConvertFrom(null, null, text);
/// <summary>
/// Converts the specified text into an object.
/// </summary>
public object ConvertFromString(ITypeDescriptorContext context, string text)
{
return ConvertFrom(context, CultureInfo.CurrentCulture, text);
}
/// <summary>
/// Converts the specified text into an object.
/// </summary>
public object ConvertFromString(ITypeDescriptorContext context, CultureInfo culture, string text)
{
return ConvertFrom(context, culture, text);
}
/// <summary>
/// Converts the given
/// value object to the specified destination type using the arguments.
/// </summary>
public object ConvertTo(object value, Type destinationType)
{
return ConvertTo(null, null, value, destinationType);
}
/// <summary>
/// Converts the given value object to
/// the specified destination type using the specified context and arguments.
/// </summary>
public virtual object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (destinationType == null)
{
throw new ArgumentNullException(nameof(destinationType));
}
if (destinationType == typeof(string))
{
if (value == null)
{
return string.Empty;
}
if (culture != null && culture != CultureInfo.CurrentCulture)
{
if (value is IFormattable formattable)
{
return formattable.ToString(format: null, formatProvider: culture);
}
}
return value.ToString();
}
throw GetConvertToException(value, destinationType);
}
/// <summary>
/// Converts the specified value to a culture-invariant string representation.
/// </summary>
public string ConvertToInvariantString(object value)
{
return ConvertToString(null, CultureInfo.InvariantCulture, value);
}
/// <summary>
/// Converts the specified value to a culture-invariant string representation.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")]
public string ConvertToInvariantString(ITypeDescriptorContext context, object value)
{
return ConvertToString(context, CultureInfo.InvariantCulture, value);
}
/// <summary>
/// Converts the specified value to a string representation.
/// </summary>
public string ConvertToString(object value)
{
return (string)ConvertTo(null, CultureInfo.CurrentCulture, value, typeof(string));
}
/// <summary>
/// Converts the specified value to a string representation.
/// </summary>
public string ConvertToString(ITypeDescriptorContext context, object value)
{
return (string)ConvertTo(context, CultureInfo.CurrentCulture, value, typeof(string));
}
/// <summary>
/// Converts the specified value to a string representation.
/// </summary>
public string ConvertToString(ITypeDescriptorContext context, CultureInfo culture, object value)
{
return (string)ConvertTo(context, culture, value, typeof(string));
}
/// <summary>
/// Re-creates an <see cref='object'/> given a set of property values for the object.
/// </summary>
public object CreateInstance(IDictionary propertyValues)
{
return CreateInstance(null, propertyValues);
}
/// <summary>
/// Re-creates an <see cref='object'/> given a set of property values for the object.
/// </summary>
public virtual object CreateInstance(ITypeDescriptorContext context, IDictionary propertyValues) => null;
/// <summary>
/// Gets a suitable exception to throw when a conversion cannot be performed.
/// </summary>
protected Exception GetConvertFromException(object value)
{
string valueTypeName = value == null ? SR.Null : value.GetType().FullName;
throw new NotSupportedException(SR.Format(SR.ConvertFromException, GetType().Name, valueTypeName));
}
/// <summary>
/// Retrieves a suitable exception to throw when a conversion cannot
/// be performed.
/// </summary>
protected Exception GetConvertToException(object value, Type destinationType)
{
string valueTypeName = value == null ? SR.Null : value.GetType().FullName;
throw new NotSupportedException(SR.Format(SR.ConvertToException, GetType().Name, valueTypeName, destinationType.FullName));
}
/// <summary>
/// Gets a value indicating whether changing a value on this object requires a call to
/// <see cref='System.ComponentModel.TypeConverter.CreateInstance(IDictionary)'/> to create a new value.
/// </summary>
public bool GetCreateInstanceSupported() => GetCreateInstanceSupported(null);
/// <summary>
///
/// Gets a value indicating whether changing a value on this object requires a call to
/// <see cref='System.ComponentModel.TypeConverter.CreateInstance(IDictionary)'/> to create a new value,
/// using the specified context.
///
/// </summary>
public virtual bool GetCreateInstanceSupported(ITypeDescriptorContext context) => false;
/// <summary>
/// Gets a collection of properties for the type of array specified by the value parameter.
/// </summary>
public PropertyDescriptorCollection GetProperties(object value) => GetProperties(null, value);
/// <summary>
///
/// Gets a collection of properties for the type of array specified by the value parameter using
/// the specified context.
///
/// </summary>
public PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value)
{
return GetProperties(context, value, new Attribute[] { BrowsableAttribute.Yes });
}
/// <summary>
///
/// Gets a collection of properties for the type of array specified by the value parameter using
/// the specified context and attributes.
///
/// </summary>
public virtual PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes)
{
return null;
}
/// <summary>
/// Gets a value indicating whether this object supports properties.
/// </summary>
public bool GetPropertiesSupported() => GetPropertiesSupported(null);
/// <summary>
/// Gets a value indicating whether this object supports properties using the specified context.
/// </summary>
public virtual bool GetPropertiesSupported(ITypeDescriptorContext context) => false;
/// <summary>
/// Gets a collection of standard values for the data type this type converter is designed for.
/// </summary>
public ICollection GetStandardValues() => GetStandardValues(null);
/// <summary>
/// Gets a collection of standard values for the data type this type converter is designed for.
/// </summary>
public virtual StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) => null;
/// <summary>
/// Gets a value indicating whether the collection of standard values returned from
/// <see cref='System.ComponentModel.TypeConverter.GetStandardValues()'/> is an exclusive list.
/// </summary>
public bool GetStandardValuesExclusive() => GetStandardValuesExclusive(null);
/// <summary>
/// Gets a value indicating whether the collection of standard values returned from
/// <see cref='System.ComponentModel.TypeConverter.GetStandardValues()'/> is an exclusive
/// list of possible values, using the specified context.
/// </summary>
public virtual bool GetStandardValuesExclusive(ITypeDescriptorContext context) => false;
/// <summary>
/// Gets a value indicating whether this object supports a standard set of values
/// that can be picked from a list.
/// </summary>
public bool GetStandardValuesSupported() => GetStandardValuesSupported(null);
/// <summary>
/// Gets a value indicating whether this object supports a standard set of values that can be picked
/// from a list using the specified context.
/// </summary>
public virtual bool GetStandardValuesSupported(ITypeDescriptorContext context) => false;
/// <summary>
/// Gets a value indicating whether the given value object is valid for this type.
/// </summary>
public bool IsValid(object value) => IsValid(null, value);
/// <summary>
/// Gets a value indicating whether the given value object is valid for this type.
/// </summary>
public virtual bool IsValid(ITypeDescriptorContext context, object value)
{
bool isValid = true;
try
{
// Because null doesn't have a type, so we couldn't pass this to CanConvertFrom.
// Meanwhile, we couldn't silence null value here, such as type converter like
// NullableConverter would consider null value as a valid value.
if (value == null || CanConvertFrom(context, value.GetType()))
{
ConvertFrom(context, CultureInfo.InvariantCulture, value);
}
else
{
isValid = false;
}
}
catch
{
isValid = false;
}
return isValid;
}
/// <summary>
/// Sorts a collection of properties.
/// </summary>
protected PropertyDescriptorCollection SortProperties(PropertyDescriptorCollection props, string[] names)
{
props.Sort(names);
return props;
}
/// <summary>
/// An <see langword='abstract '/> class that provides properties for objects that do not have properties.
/// </summary>
protected abstract class SimplePropertyDescriptor : PropertyDescriptor
{
/// <summary>
/// Initializes a new instance of the <see cref='System.ComponentModel.TypeConverter.SimplePropertyDescriptor'/> class.
/// </summary>
protected SimplePropertyDescriptor(Type componentType, string name, Type propertyType) : this(componentType, name, propertyType, Array.Empty<Attribute>())
{
}
/// <summary>
/// Initializes a new instance of the <see cref='System.ComponentModel.TypeConverter.SimplePropertyDescriptor'/> class.
/// </summary>
protected SimplePropertyDescriptor(Type componentType, string name, Type propertyType, Attribute[] attributes) : base(name, attributes)
{
ComponentType = componentType;
PropertyType = propertyType;
}
/// <summary>
/// Gets the type of the component this property description is bound to.
/// </summary>
public override Type ComponentType { get; }
/// <summary>
/// Gets a value indicating whether this property is read-only.
/// </summary>
public override bool IsReadOnly => Attributes.Contains(ReadOnlyAttribute.Yes);
/// <summary>
/// Gets the type of the property.
/// </summary>
public override Type PropertyType { get; }
/// <summary>
/// Gets a value indicating whether resetting the component will change the value of the component.
/// </summary>
public override bool CanResetValue(object component)
{
DefaultValueAttribute attr = (DefaultValueAttribute)Attributes[typeof(DefaultValueAttribute)];
if (attr == null)
{
return false;
}
return attr.Value.Equals(GetValue(component));
}
/// <summary>
/// Resets the value for this property of the component.
/// </summary>
public override void ResetValue(object component)
{
DefaultValueAttribute attr = (DefaultValueAttribute)Attributes[typeof(DefaultValueAttribute)];
if (attr != null)
{
SetValue(component, attr.Value);
}
}
/// <summary>
/// Gets a value indicating whether the value of this property needs to be persisted.
/// </summary>
public override bool ShouldSerializeValue(object component) => false;
}
/// <summary>
/// Represents a collection of values.
/// </summary>
public class StandardValuesCollection : ICollection
{
private readonly ICollection _values;
private Array _valueArray;
/// <summary>
///
/// Initializes a new instance of the <see cref='System.ComponentModel.TypeConverter.StandardValuesCollection'/> class.
///
/// </summary>
public StandardValuesCollection(ICollection values)
{
if (values == null)
{
values = Array.Empty<object>();
}
if (values is Array a)
{
_valueArray = a;
}
_values = values;
}
/// <summary>
///
/// Gets the number of objects in the collection.
///
/// </summary>
public int Count
{
get
{
if (_valueArray != null)
{
return _valueArray.Length;
}
else
{
return _values.Count;
}
}
}
/// <summary>
/// Gets the object at the specified index number.
/// </summary>
public object this[int index]
{
get
{
if (_valueArray != null)
{
return _valueArray.GetValue(index);
}
if (_values is IList list)
{
return list[index];
}
// No other choice but to enumerate the collection.
//
_valueArray = new object[_values.Count];
_values.CopyTo(_valueArray, 0);
return _valueArray.GetValue(index);
}
}
/// <summary>
/// Copies the contents of this collection to an array.
/// </summary>
public void CopyTo(Array array, int index) => _values.CopyTo(array, index);
/// <summary>
/// Gets an enumerator for this collection.
/// </summary>
public IEnumerator GetEnumerator() => _values.GetEnumerator();
/// <summary>
/// Determines if this collection is synchronized. The ValidatorCollection is not synchronized for
/// speed. Also, since it is read-only, there is no need to synchronize it.
/// </summary>
bool ICollection.IsSynchronized => false;
/// <summary>
/// Retrieves the synchronization root for this collection. Because we are not synchronized,
/// this returns null.
/// </summary>
object ICollection.SyncRoot => null;
}
}
}
| |
// Copyright (c) 2015 SharpYaml - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// -------------------------------------------------------------------------------
// SharpYaml is a fork of YamlDotNet https://github.com/aaubry/YamlDotNet
// published with the following license:
// -------------------------------------------------------------------------------
//
// Copyright (c) 2008, 2009, 2010, 2011, 2012 Antoine Aubry
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace SharpYaml.Serialization.Descriptors
{
/// <summary>
/// Default implementation of a <see cref="ITypeDescriptor"/>.
/// </summary>
public class ObjectDescriptor : ITypeDescriptor
{
public static readonly Func<object, bool> ShouldSerializeDefault = o => true;
protected static readonly string SystemCollectionsNamespace = typeof(int).Namespace;
private readonly static object[] EmptyObjectArray = new object[0];
private readonly Type type;
private List<IMemberDescriptor> members;
private Dictionary<string, IMemberDescriptor> mapMembers;
private readonly bool emitDefaultValues;
private YamlStyle style;
private bool isSorted;
private readonly IMemberNamingConvention memberNamingConvention;
private HashSet<string> remapMembers;
private List<Attribute> attributes;
/// <summary>
/// Initializes a new instance of the <see cref="ObjectDescriptor" /> class.
/// </summary>
/// <param name="attributeRegistry">The attribute registry.</param>
/// <param name="type">The type.</param>
/// <param name="emitDefaultValues">if set to <c>true</c> [emit default values].</param>
/// <param name="namingConvention">The naming convention.</param>
/// <exception cref="System.ArgumentNullException">type</exception>
/// <exception cref="YamlException">type</exception>
public ObjectDescriptor(IAttributeRegistry attributeRegistry, Type type, bool emitDefaultValues, IMemberNamingConvention namingConvention)
{
if (attributeRegistry == null) throw new ArgumentNullException("attributeRegistry");
if (type == null) throw new ArgumentNullException("type");
if (namingConvention == null) throw new ArgumentNullException("namingConvention");
this.memberNamingConvention = namingConvention;
this.emitDefaultValues = emitDefaultValues;
this.AttributeRegistry = attributeRegistry;
this.type = type;
attributes = AttributeRegistry.GetAttributes(type);
this.style = YamlStyle.Any;
foreach (var attribute in attributes)
{
var styleAttribute = attribute as YamlStyleAttribute;
if (styleAttribute != null)
{
style = styleAttribute.Style;
continue;
}
if (attribute is CompilerGeneratedAttribute)
{
this.IsCompilerGenerated = true;
}
}
}
/// <summary>
/// Gets attributes attached to this type.
/// </summary>
public List<Attribute> Attributes
{
get { return attributes; }
}
/// <summary>
/// Gets the naming convention.
/// </summary>
/// <value>The naming convention.</value>
public IMemberNamingConvention NamingConvention
{
get { return memberNamingConvention; }
}
/// <summary>
/// Initializes this instance.
/// </summary>
/// <exception cref="YamlException">Failed to get ObjectDescriptor for type [{0}]. The member [{1}] cannot be registered as a member with the same name is already registered [{2}].DoFormat(type.FullName, member, existingMember)</exception>
public virtual void Initialize()
{
if (members != null)
{
return;
}
members = PrepareMembers();
// If no members found, we don't need to build a dictionary map
if (members.Count <= 0) return;
mapMembers = new Dictionary<string, IMemberDescriptor>((int)(members.Count * 1.2));
foreach (var member in members)
{
IMemberDescriptor existingMember;
if (mapMembers.TryGetValue(member.Name, out existingMember))
{
throw new YamlException("Failed to get ObjectDescriptor for type [{0}]. The member [{1}] cannot be registered as a member with the same name is already registered [{2}]".DoFormat(type.FullName, member, existingMember));
}
mapMembers.Add(member.Name, member);
// If there is any alternative names, register them
if (member.AlternativeNames != null)
{
foreach (var alternateName in member.AlternativeNames)
{
if (mapMembers.TryGetValue(alternateName, out existingMember))
{
throw new YamlException("Failed to get ObjectDescriptor for type [{0}]. The member [{1}] cannot be registered as a member with the same name [{2}] is already registered [{3}]".DoFormat(type.FullName, member, alternateName, existingMember));
}
else
{
if (remapMembers == null)
{
remapMembers = new HashSet<string>();
}
mapMembers[alternateName] = member;
remapMembers.Add(alternateName);
}
}
}
}
}
protected IAttributeRegistry AttributeRegistry { get; private set; }
public Type Type
{
get { return type; }
}
public IEnumerable<IMemberDescriptor> Members
{
get { return members; }
}
public int Count
{
get { return members == null ? 0 : members.Count; }
}
public virtual DescriptorCategory Category
{
get { return DescriptorCategory.Object; }
}
public bool HasMembers
{
get { return members.Count > 0; }
}
public YamlStyle Style
{
get { return style; }
}
/// <summary>
/// Sorts the members of this instance with the specified instance.
/// </summary>
/// <param name="keyComparer">The key comparer.</param>
public void SortMembers(IComparer<object> keyComparer)
{
if (keyComparer != null && !isSorted)
{
members.Sort(keyComparer.Compare);
isSorted = true;
}
}
public IMemberDescriptor this[string name]
{
get
{
if (mapMembers == null) throw new KeyNotFoundException(name);
IMemberDescriptor member;
mapMembers.TryGetValue(name, out member);
return member;
}
}
public bool IsMemberRemapped(string name)
{
return remapMembers != null && remapMembers.Contains(name);
}
public bool IsCompilerGenerated { get; private set; }
public bool Contains(string memberName)
{
return mapMembers != null && mapMembers.ContainsKey(memberName);
}
protected virtual List<IMemberDescriptor> PrepareMembers()
{
var bindingFlags = BindingFlags.Instance | BindingFlags.Public;
if (Category == DescriptorCategory.Object)
bindingFlags |= BindingFlags.NonPublic;
// Add all public properties with a readable get method
var memberList = (from propertyInfo in type.GetProperties(bindingFlags)
where
propertyInfo.CanRead && propertyInfo.GetIndexParameters().Length == 0
select new PropertyDescriptor(propertyInfo, NamingConvention.Comparer)
into member
where PrepareMember(member)
select member).Cast<IMemberDescriptor>().ToList();
// Add all public fields
memberList.AddRange((from fieldInfo in type.GetFields(bindingFlags)
select new FieldDescriptor(fieldInfo, NamingConvention.Comparer)
into member where PrepareMember(member) select member));
// Allow to add dynamic members per type
if (AttributeRegistry.PrepareMembersCallback != null)
{
AttributeRegistry.PrepareMembersCallback(this, memberList);
}
return memberList;
}
protected virtual bool PrepareMember(MemberDescriptorBase member)
{
var memberType = member.Type;
// Remove all SyncRoot from members
if (member is PropertyDescriptor && member.OriginalName == "SyncRoot" &&
(member.DeclaringType.Namespace ?? string.Empty).StartsWith(SystemCollectionsNamespace))
{
return false;
}
// Process all attributes just once instead of getting them one by one
var attributes = AttributeRegistry.GetAttributes(member.MemberInfo);
YamlStyleAttribute styleAttribute = null;
YamlMemberAttribute memberAttribute = null;
DefaultValueAttribute defaultValueAttribute = null;
foreach (var attribute in attributes)
{
// Member is not displayed if there is a YamlIgnore attribute on it
if (attribute is YamlIgnoreAttribute)
{
return false;
}
if (attribute is YamlMemberAttribute)
{
memberAttribute = (YamlMemberAttribute)attribute;
continue;
}
if (attribute is DefaultValueAttribute)
{
defaultValueAttribute = (DefaultValueAttribute) attribute;
continue;
}
if (attribute is YamlStyleAttribute)
{
styleAttribute = (YamlStyleAttribute) attribute;
continue;
}
var yamlRemap = attribute as YamlRemapAttribute;
if (yamlRemap != null)
{
if (member.AlternativeNames == null)
{
member.AlternativeNames = new List<string>();
}
if (!string.IsNullOrWhiteSpace(yamlRemap.Name))
{
member.AlternativeNames.Add(yamlRemap.Name);
}
}
}
// If the member has a set, this is a conventional assign method
if (member.HasSet)
{
member.SerializeMemberMode = SerializeMemberMode.Content;
}
else
{
// Else we cannot only assign its content if it is a class
member.SerializeMemberMode = (memberType != typeof(string) && memberType.IsClass) || memberType.IsInterface || type.IsAnonymous() ? SerializeMemberMode.Content : SerializeMemberMode.Never;
}
// If it's a private member, check it has a YamlMemberAttribute on it
if (!member.IsPublic)
{
if (memberAttribute == null)
return false;
}
// Gets the style
member.Style = styleAttribute != null ? styleAttribute.Style : YamlStyle.Any;
member.Mask = 1;
// Handle member attribute
if (memberAttribute != null)
{
member.Mask = memberAttribute.Mask;
if (!member.HasSet)
{
if (memberAttribute.SerializeMethod == SerializeMemberMode.Assign ||
(memberType.IsValueType && member.SerializeMemberMode == SerializeMemberMode.Content))
throw new ArgumentException("{0} {1} is not writeable by {2}.".DoFormat(memberType.FullName, member.OriginalName, memberAttribute.SerializeMethod.ToString()));
}
if (memberAttribute.SerializeMethod != SerializeMemberMode.Default)
{
member.SerializeMemberMode = memberAttribute.SerializeMethod;
}
member.Order = memberAttribute.Order;
}
if (member.SerializeMemberMode == SerializeMemberMode.Binary)
{
if (!memberType.IsArray)
throw new InvalidOperationException("{0} {1} of {2} is not an array. Can not be serialized as binary."
.DoFormat(memberType.FullName, member.OriginalName, type.FullName));
if (!memberType.GetElementType().IsPureValueType())
throw new InvalidOperationException("{0} is not a pure ValueType. {1} {2} of {3} can not serialize as binary.".DoFormat(memberType.GetElementType(), memberType.FullName, member.OriginalName, type.FullName));
}
// If this member cannot be serialized, remove it from the list
if (member.SerializeMemberMode == SerializeMemberMode.Never)
{
return false;
}
// ShouldSerialize
// YamlSerializeAttribute(Never) => false
// ShouldSerializeSomeProperty => call it
// DefaultValueAttribute(default) => compare to it
// otherwise => true
var shouldSerialize = type.GetMethod("ShouldSerialize" + member.OriginalName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
if (shouldSerialize != null && shouldSerialize.ReturnType == typeof(bool) && member.ShouldSerialize == null)
member.ShouldSerialize = obj => (bool)shouldSerialize.Invoke(obj, EmptyObjectArray);
if (defaultValueAttribute != null && member.ShouldSerialize == null && !emitDefaultValues)
{
object defaultValue = defaultValueAttribute.Value;
Type defaultType = defaultValue == null ? null : defaultValue.GetType();
if (defaultType.IsNumeric() && defaultType != memberType)
defaultValue = memberType.CastToNumericType(defaultValue);
member.ShouldSerialize = obj => !TypeExtensions.AreEqual(defaultValue, member.Get(obj));
}
if (member.ShouldSerialize == null)
member.ShouldSerialize = ShouldSerializeDefault;
if (memberAttribute != null && !string.IsNullOrEmpty(memberAttribute.Name))
{
member.Name = memberAttribute.Name;
}
else
{
member.Name = NamingConvention.Convert(member.OriginalName);
}
return true;
}
public override string ToString()
{
return type.ToString();
}
}
}
| |
#region License
//
// Copyright (c) 2007-2018, Sean Chambers <schambers80@gmail.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
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Linq;
using FirebirdSql.Data.FirebirdClient;
using FluentMigrator.Runner.Announcers;
using FluentMigrator.Runner.Generators.Postgres;
using FluentMigrator.Runner.Processors;
using FluentMigrator.Runner.Processors.MySql;
using FluentMigrator.Runner.Processors.Postgres;
using FluentMigrator.Runner.Processors.SQLite;
using FluentMigrator.Runner.Processors.SqlServer;
using FluentMigrator.Runner.Generators.SQLite;
using FluentMigrator.Runner.Generators.SqlServer;
using FluentMigrator.Runner.Generators.MySql;
using FluentMigrator.Runner.Processors.Firebird;
using FluentMigrator.Runner.Generators.Firebird;
using FluentMigrator.Runner.Generators.SqlAnywhere;
using FluentMigrator.Runner.Processors.SqlAnywhere;
using MySql.Data.MySqlClient;
using Npgsql;
using NUnit.Framework;
namespace FluentMigrator.Tests.Integration
{
[Obsolete]
public class ObsoleteIntegrationTestBase
{
private delegate void ExecuteTestDelegate(Action<IMigrationProcessor> test, bool tryRollback, IntegrationTestOptions.DatabaseServerOptions options);
private readonly List<(Type processorType, Func<IntegrationTestOptions.DatabaseServerOptions> getOptionsFunc, ExecuteTestDelegate executeTestDelegate)> _processors;
private bool _isFirstExecuteForFirebird = true;
private string _tempDataDirectory;
protected ObsoleteIntegrationTestBase()
{
_processors = new List<(Type, Func<IntegrationTestOptions.DatabaseServerOptions>, ExecuteTestDelegate)>
{
(typeof(SqlServerProcessor), () => IntegrationTestOptions.SqlServer2005, ExecuteWithSqlServer2005),
(typeof(SqlServerProcessor), () => IntegrationTestOptions.SqlServer2008, ExecuteWithSqlServer2008),
(typeof(SqlServerProcessor), () => IntegrationTestOptions.SqlServer2012, ExecuteWithSqlServer2012),
(typeof(SqlServerProcessor), () => IntegrationTestOptions.SqlServer2014, ExecuteWithSqlServer2014),
(typeof(SqlServerProcessor), () => IntegrationTestOptions.SqlServer2016, ExecuteWithSqlServer2016),
(typeof(SqlAnywhereProcessor), () => IntegrationTestOptions.SqlAnywhere16, ExecuteWithSqlAnywhere),
(typeof(SQLiteProcessor), () => IntegrationTestOptions.SQLite, ExecuteWithSqlite),
(typeof(FirebirdProcessor), () => IntegrationTestOptions.Firebird, ExecuteWithFirebird),
(typeof(PostgresProcessor), () => IntegrationTestOptions.Postgres, ExecuteWithPostgres),
(typeof(MySqlProcessor), () => IntegrationTestOptions.MySql, ExecuteWithMySql),
};
}
[SetUp]
public void SetUpFirebird()
{
_isFirstExecuteForFirebird = true;
}
[SetUp]
public void SetUpDataDirectory()
{
_tempDataDirectory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(_tempDataDirectory);
AppDomain.CurrentDomain.SetData("DataDirectory", _tempDataDirectory);
}
[TearDown]
public void TearDownDataDirectory()
{
if (!string.IsNullOrEmpty(_tempDataDirectory) && Directory.Exists(_tempDataDirectory))
{
Directory.Delete(_tempDataDirectory, true);
}
}
protected bool IsAnyServerEnabled(params Type[] exceptProcessors)
{
return IsAnyServerEnabled(procType => !exceptProcessors.Any(p => p.IsAssignableFrom(procType)));
}
protected bool IsAnyServerEnabled(Predicate<Type> isMatch)
{
foreach (var (processorType, getOptionsFunc, _) in _processors)
{
var opt = getOptionsFunc();
if (!opt.IsEnabled)
continue;
if (!isMatch(processorType))
continue;
return true;
}
return false;
}
public void ExecuteWithSupportedProcessors(Action<IMigrationProcessor> test)
{
ExecuteWithSupportedProcessors(test, true);
}
public void ExecuteWithSupportedProcessors(Action<IMigrationProcessor> test, bool tryRollback)
{
ExecuteWithSupportedProcessors(test, tryRollback, new Type[] { });
}
public void ExecuteWithSupportedProcessors(Action<IMigrationProcessor> test, bool tryRollback, params Type[] exceptProcessors)
{
ExecuteWithSupportedProcessors(
test,
tryRollback,
procType => !exceptProcessors.Any(p => p.IsAssignableFrom(procType)));
}
public void ExecuteWithSupportedProcessors(Action<IMigrationProcessor> test, bool tryRollback, Predicate<Type> isMatch)
{
if (!IsAnyServerEnabled())
{
Assert.Fail(
"No database processors are configured to run your migration tests. This message is provided to avoid false positives. To avoid this message enable one or more test runners in the {0} class.",
nameof(IntegrationTestOptions));
}
var executed = false;
foreach (var (processorType, getOptionsFunc, executeFunc) in _processors)
{
var opt = getOptionsFunc();
if (!opt.IsEnabled)
continue;
if (!isMatch(processorType))
continue;
executed = true;
executeFunc(test, tryRollback, opt);
}
if (!executed)
{
Assert.Ignore("No processor found for the given action.");
}
}
protected static void ExecuteWithSqlServer2016(Action<IMigrationProcessor> test, bool tryRollback, IntegrationTestOptions.DatabaseServerOptions serverOptions)
{
Debug.Assert(serverOptions.IsEnabled);
var announcer = new TextWriterAnnouncer(TestContext.Out);
announcer.Heading("Testing Migration against MS SQL Server 2016");
var generator = new SqlServer2016Generator();
ExecuteWithSqlServer(new[] { "SqlServer2016" }, serverOptions, announcer, generator, test, tryRollback);
}
protected static void ExecuteWithSqlServer2014(Action<IMigrationProcessor> test, bool tryRollback, IntegrationTestOptions.DatabaseServerOptions serverOptions)
{
Debug.Assert(serverOptions.IsEnabled);
var announcer = new TextWriterAnnouncer(TestContext.Out);
announcer.Heading("Testing Migration against MS SQL Server 2014");
var generator = new SqlServer2014Generator();
ExecuteWithSqlServer(new[] { "SqlServer2014" }, serverOptions, announcer, generator, test, tryRollback);
}
protected static void ExecuteWithSqlServer2012(Action<IMigrationProcessor> test, bool tryRollback, IntegrationTestOptions.DatabaseServerOptions serverOptions)
{
Debug.Assert(serverOptions.IsEnabled);
var announcer = new TextWriterAnnouncer(TestContext.Out);
announcer.Heading("Testing Migration against MS SQL Server 2012");
var generator = new SqlServer2012Generator();
ExecuteWithSqlServer(new[] { "SqlServer2012" }, serverOptions, announcer, generator, test, tryRollback);
}
protected static void ExecuteWithSqlServer2008(Action<IMigrationProcessor> test, bool tryRollback, IntegrationTestOptions.DatabaseServerOptions serverOptions)
{
Debug.Assert(serverOptions.IsEnabled);
var announcer = new TextWriterAnnouncer(TestContext.Out);
announcer.Heading("Testing Migration against MS SQL Server 2008");
var generator = new SqlServer2008Generator();
ExecuteWithSqlServer(new[] { "SqlServer2008" }, serverOptions, announcer, generator, test, tryRollback);
}
protected static void ExecuteWithSqlServer2005(Action<IMigrationProcessor> test, bool tryRollback, IntegrationTestOptions.DatabaseServerOptions serverOptions)
{
Debug.Assert(serverOptions.IsEnabled);
var announcer = new TextWriterAnnouncer(TestContext.Out);
announcer.Heading("Testing Migration against MS SQL Server 2005");
var generator = new SqlServer2005Generator();
ExecuteWithSqlServer(new[] { "SqlServer2005" }, serverOptions, announcer, generator, test, tryRollback);
}
private static void ExecuteWithSqlServer(IEnumerable<string> databaseTypes, IntegrationTestOptions.DatabaseServerOptions serverOptions, TextWriterAnnouncer announcer, SqlServer2005Generator generator, Action<IMigrationProcessor> test, bool tryRollback)
{
using (var connection = new SqlConnection(serverOptions.ConnectionString))
{
var processor = new SqlServerProcessor(databaseTypes, connection, generator, announcer, new ProcessorOptions(), new SqlServerDbFactory());
test(processor);
if (tryRollback && !processor.WasCommitted)
{
processor.RollbackTransaction();
}
}
}
protected static void ExecuteWithSqlite(Action<IMigrationProcessor> test, bool tryRollback, IntegrationTestOptions.DatabaseServerOptions serverOptions)
{
if (!serverOptions.IsEnabled)
return;
var announcer = new TextWriterAnnouncer(TestContext.Out);
announcer.Heading("Testing Migration against SQLite");
var factory = new SQLiteDbFactory(serviceProvider: null);
using (var connection = factory.Factory.CreateConnection())
{
Debug.Assert(connection != null, nameof(connection) + " != null");
connection.ConnectionString = serverOptions.ConnectionString;
connection.Open();
var processor = new SQLiteProcessor(connection, new SQLiteGenerator(), announcer, new ProcessorOptions(), factory);
test(processor);
if (tryRollback && !processor.WasCommitted)
{
processor.RollbackTransaction();
}
}
}
protected static void ExecuteWithSqlAnywhere(Action<IMigrationProcessor> test, bool tryRollback, IntegrationTestOptions.DatabaseServerOptions serverOptions)
{
if (!serverOptions.IsEnabled)
return;
var announcer = new TextWriterAnnouncer(TestContext.Out);
announcer.Heading("Testing Migration against Postgres");
var factory = new SqlAnywhereDbFactory();
using (var connection = factory.CreateConnection(serverOptions.ConnectionString))
{
var processor = new SqlAnywhereProcessor("SqlAnywhere16", connection, new SqlAnywhere16Generator(), new TextWriterAnnouncer(TestContext.Out), new ProcessorOptions(), factory);
test(processor);
if (tryRollback && !processor.WasCommitted)
{
processor.RollbackTransaction();
}
}
}
protected static void ExecuteWithPostgres(Action<IMigrationProcessor> test, bool tryRollback, IntegrationTestOptions.DatabaseServerOptions serverOptions)
{
if (!serverOptions.IsEnabled)
return;
var announcer = new TextWriterAnnouncer(TestContext.Out);
announcer.Heading("Testing Migration against Postgres");
using (var connection = new NpgsqlConnection(serverOptions.ConnectionString))
{
var pgOptions = new PostgresOptions();
var processor = new PostgresProcessor(
connection,
new PostgresGenerator(new PostgresQuoter(pgOptions)),
new TextWriterAnnouncer(TestContext.Out),
new ProcessorOptions(),
new PostgresDbFactory(serviceProvider: null),
pgOptions);
test(processor);
if (tryRollback && !processor.WasCommitted)
{
processor.RollbackTransaction();
}
}
}
protected static void ExecuteWithMySql(Action<IMigrationProcessor> test, bool tryRollback, IntegrationTestOptions.DatabaseServerOptions serverOptions)
{
if (!serverOptions.IsEnabled)
return;
var announcer = new TextWriterAnnouncer(TestContext.Out);
announcer.Heading("Testing Migration against MySQL Server");
using (var connection = new MySqlConnection(serverOptions.ConnectionString))
{
var processor = new MySqlProcessor(connection, new MySql4Generator(), announcer, new ProcessorOptions(), new MySqlDbFactory(serviceProvider: null));
test(processor);
if (tryRollback && !processor.WasCommitted)
{
processor.RollbackTransaction();
}
}
}
protected void ExecuteWithFirebird(Action<IMigrationProcessor> test, bool tryRollback, IntegrationTestOptions.DatabaseServerOptions serverOptions)
{
if (!serverOptions.IsEnabled)
return;
var announcer = new TextWriterAnnouncer(TestContext.Out);
announcer.ShowSql = true;
announcer.Heading("Testing Migration against Firebird Server");
if (_isFirstExecuteForFirebird)
{
_isFirstExecuteForFirebird = false;
FbConnection.CreateDatabase(serverOptions.ConnectionString, true);
}
using (var connection = new FbConnection(serverOptions.ConnectionString))
{
var options = FirebirdOptions.AutoCommitBehaviour();
var processor = new FirebirdProcessor(connection, new FirebirdGenerator(options), announcer, new ProcessorOptions(), new FirebirdDbFactory(serviceProvider: null), options);
try
{
test(processor);
}
catch (Exception)
{
if (tryRollback && !processor.WasCommitted)
processor.RollbackTransaction();
throw;
}
}
}
}
}
| |
/* Copyright (c) 2006-2008 Google 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.
*/
/* Change history
* Oct 13 2008 Joe Feser joseph.feser@gmail.com
* Converted ArrayLists and other .NET 1.1 collections to use Generics
* Combined IExtensionElement and IExtensionElementFactory interfaces
*
*/
#define USE_TRACING
using System;
using System.IO;
using System.Xml;
using System.Collections;
using System.Configuration;
using System.Net;
using System.Text;
using NUnit.Framework;
using Google.GData.Client;
using Google.GData.GoogleBase;
using System.Collections.Generic;
namespace Google.GData.GoogleBase.UnitTests
{
[TestFixture]
[Category("GoogleBase")]
public class GBaseFeedTest
{
private static readonly Uri FeedUri =
new Uri("http://www.google.com/base/feeds/snippets");
private const string SAMPLE_FEED =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<feed xmlns=\"http://www.w3.org/2005/Atom\"" +
" xmlns:g=\"http://base.google.com/ns/1.0\"" +
" xmlns:gm=\"http://base.google.com/ns-metadata/1.0\"" +
">" +
" <entry>" +
" <author>" +
" <name>Jane Doe</name>" +
" <email>JaneDoe@gmail.com</email>" +
" </author>" +
" <category scheme='http://www.google.com/categories/itemtypes' term='Recipes'/>" +
" <title type='text'>He Jingxian's chicken</title>" +
" <content type='xhtml'>" +
" <div xmlns='http://www.w3.org/1999/xhtml'>Delectable Sichuan speciality</div>" +
" </content>" +
" <link rel='alternate' type='text/html' href='http://www.host.com/123456jsh9'/>" +
" <g:label type='text'>kung pao chicken</g:label>" +
" <g:label type='text'>chinese cuisine</g:label>" +
" <g:label type='text'>recipes</g:label>" +
" <g:label type='text'>asian</g:label>" +
" <g:label type='text'>sichuan</g:label>" +
" <g:location type='location'>Mountain View, CA 94043</g:location>" +
" <g:item_type type='text'>Recipes</g:item_type>" +
" <g:cooking_time type='intUnit'>30 minutes</g:cooking_time>" +
" <g:main_ingredient type='text'>chicken</g:main_ingredient>" +
" <g:main_ingredient type='text'>chili peppers</g:main_ingredient>" +
" <g:main_ingredient type='text'>peanuts</g:main_ingredient>" +
" <g:serving_count type='number'>5</g:serving_count>" +
" <gm:stats><gm:impressions total='100'/></gm:stats>" +
" </entry>" +
"</feed>";
[Test]
public void ReadFeedFromXmlRegenerateAndReparse()
{
GBaseFeed feed = Parse(SAMPLE_FEED);
CheckParsedFeedEntries(feed);
}
private void CheckParsedFeedEntries(GBaseFeed feed)
{
GBaseEntry entry = feed.Entries[0] as GBaseEntry;
Assert.IsNotNull(entry, "entry");
GBaseAttributes attrs = entry.GBaseAttributes;
Assert.AreEqual("Recipes", attrs.ItemType, "item type");
Assert.AreEqual("Mountain View, CA 94043", attrs.Location, "location");
String[] labels = attrs.Labels;
Assert.AreEqual("kung pao chicken", labels[0], "label");
Assert.AreEqual("chinese cuisine", labels[1], "label");
Assert.AreEqual("recipes", labels[2], "label");
Assert.AreEqual("asian", labels[3], "label");
Assert.AreEqual("sichuan", labels[4], "label");
Assert.AreEqual(5f, attrs.GetNumberAttribute("serving count", 0f));
Assert.IsNotNull(entry.Stats, "gm:stats");
Assert.AreEqual(100, entry.Stats.Impressions.Total, "gm:impressions");
}
[Test]
public void ParseGenerateAndReparse()
{
GBaseFeed feed = Parse(SAMPLE_FEED);
StringWriter sw = new StringWriter();
XmlWriter xmlWriter = new XmlTextWriter(sw);
feed.SaveToXml(xmlWriter);
xmlWriter.Close();
Tracing.TraceMsg(sw.ToString());
GBaseFeed reparsed = Parse(sw.ToString());
CheckParsedFeedEntries(reparsed);
}
[Test]
public void ReadAttributesFeedFromXml()
{
string xml = "<?xml version='1.0' encoding='UTF-8'?>" +
"<feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:gm='http://base.google.com/ns-metadata/1.0'>" +
" <id>http://www.google.com/base/feeds/attributes</id>" +
" <updated>2006-08-24T14:26:45.558Z</updated>" +
" <title type='text'>Attribute histogram for query: </title>" +
" <link rel='alternate' type='text/html' href='http://www.google.com'/>" +
" <link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://www.google.com/base/feeds/attributes'/>" +
" <link rel='self' type='application/atom+xml' href='http://www.google.com/base/feeds/attributes?max-results=1&key=ABQIAAAA7VerLsOcLuBYXR7vZI2NjhTRERdeAiwZ9EeJWta3L_JZVS0bOBRIFbhTrQjhHE52fqjZvfabYYyn6A'/>" +
" <generator version='1.0' uri='http://www.google.com'>GoogleBase</generator>" +
" <openSearch:totalResults>1</openSearch:totalResults>" +
" <openSearch:itemsPerPage>1</openSearch:itemsPerPage>" +
" <entry>" +
" <id>http://www.google.com/base/feeds/attributes/label%28text%29N</id>" +
" <updated>2006-08-24T14:26:45.651Z</updated>" +
" <title type='text'>label(text)</title>" +
" <content type='text'>Attribute label of type text.</content>" +
" <link rel='self' type='application/atom+xml' href='http://www.google.com/base/feeds/attributes/label%28text%29N'/>" +
" <gm:attribute name='label' type='text' count='158778'>" +
" <gm:value count='47544'>housing</gm:value>" +
" <gm:value count='36954'>reviews</gm:value>" +
" </gm:attribute>" +
" </entry>" +
"</feed>";
GBaseFeed feed = Parse(xml);
GBaseEntry entry = feed.Entries[0] as GBaseEntry;
Assert.IsNotNull(entry, "entry");
AttributeHistogram hist = entry.AttributeHistogram;
Assert.AreEqual("label", hist.Name, "name");
Assert.AreEqual(GBaseAttributeType.Text, hist.Type, "type");
Assert.AreEqual(158778, hist.Count, "count");
List<HistogramValue> values = hist.Values;
Assert.AreEqual(2, values.Count, "values.Length");
Assert.AreEqual("housing", values[0].Content);
Assert.AreEqual(47544, values[0].Count);
Assert.AreEqual("reviews", values[1].Content);
Assert.AreEqual(36954, values[1].Count);
}
[Test]
public void ReadItemTypesFeedFromXml()
{
string xml = "<?xml version='1.0' encoding='UTF-8'?>\n" +
"<feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:gm='http://base.google.com/ns-metadata/1.0'>\n" +
" <id>http://www.google.com/base/feeds/itemtypes/en_US</id>\n" +
" <updated>2006-08-24T14:32:27.228Z</updated>\n" +
" <title type='text'>Item types for locale en_US</title>\n" +
" <link rel='alternate' type='text/html' href='http://www.google.com'/>\n" +
" <link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://www.google.com/base/feeds/itemtypes/en_US'/>\n" +
" <link rel='self' type='application/atom+xml' href='http://www.google.com/base/feeds/itemtypes/en_US?max-results=1&key=ABQIAAAAfW6XRFfnNGUiegdqIq0KExT2yXp_ZAY8_ufC3CFXhHIE1NvwkxS8MfEf7Ag6UI0Ony8Yq3gZHm6c9w'/>\n" +
" <author>\n" +
" <name>Google Inc.</name>\n" +
" <email>base@google.com</email>\n" +
" </author>\n" +
" <generator version='1.0' uri='http://www.google.com'>GoogleBase</generator>\n" +
" <openSearch:totalResults>1</openSearch:totalResults>\n" +
" <openSearch:itemsPerPage>1</openSearch:itemsPerPage>\n" +
" <entry>\n" +
" <id>http://www.google.com/base/feeds/itemtypes/en_US/products</id>\n" +
" <updated>2006-08-24T14:32:27.233Z</updated>\n" +
" <category scheme='http://www.google.com/categories/itemtypes' term='products'/>\n" +
" <title type='text'>products</title>\n" +
" <content type='text'>products</content>\n" +
" <gm:item_type>products</gm:item_type>\n" +
" <gm:attributes>\n" +
" <gm:attribute name='product type' type='text'/>\n" +
" <gm:attribute name='condition' type='text'/>\n" +
" <gm:attribute name='count' type='int'/>\n" +
" </gm:attributes>\n" +
" </entry>\n" +
"</feed>";
GBaseFeed feed = Parse(xml);
GBaseEntry entry = feed.Entries[0] as GBaseEntry;
Assert.IsNotNull(entry, "entry");
ItemTypeDefinition def = entry.ItemTypeDefinition;
Assert.IsNotNull(def, "ItemTypeDefinition");
Assert.AreEqual("products", def.ItemType);
Assert.AreEqual(3, def.Attributes.Count);
Assert.AreEqual("product type", def.Attributes[0].Name);
Assert.AreEqual(GBaseAttributeType.Text, def.Attributes[0].Type);
Assert.AreEqual("condition", def.Attributes[1].Name);
Assert.AreEqual(GBaseAttributeType.Text, def.Attributes[1].Type);
Assert.AreEqual("count", def.Attributes[2].Name);
Assert.AreEqual(GBaseAttributeType.Int, def.Attributes[2].Type);
}
private GBaseFeed Parse(String xml)
{
byte[] bytes = new UTF8Encoding().GetBytes(xml);
GBaseFeed feed = new GBaseFeed(FeedUri, new GBaseService("Test", "boguskey"));
feed.Parse(new MemoryStream(bytes), AlternativeFormat.Atom);
return feed;
}
}
}
| |
/* httpcontext-simulator
* a simulator used to simulate http context during integration testing
*
* Copyright (C) Phil Haack
* http://code.google.com/p/httpcontext-simulator/
*
* 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 HttpSimulator
{
#region
using System;
using System.Collections;
using System.Collections.Specialized;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Configuration;
using System.Web.Hosting;
using System.Web.SessionState;
#endregion
/// <summary>
/// The http verb.
/// </summary>
public enum HttpVerb
{
/// <summary>
/// The get.
/// </summary>
GET,
/// <summary>
/// The head.
/// </summary>
HEAD,
/// <summary>
/// The post.
/// </summary>
POST,
/// <summary>
/// The put.
/// </summary>
PUT,
/// <summary>
/// The delete.
/// </summary>
DELETE,
}
/// <summary>
/// Useful class for simulating the HttpContext. This does not actually make an HttpRequest, it merely simulates the state that your code would be in "as if" handling a request. Thus the HttpContext.Current property is populated.
/// </summary>
public class HttpSimulator : IDisposable
{
#region Constants and Fields
/// <summary>
/// The default physical app path.
/// </summary>
private const string DefaultPhysicalAppPath = @"c:\InetPub\wwwRoot\";
/// <summary>
/// The _form vars.
/// </summary>
private readonly NameValueCollection formVars = new NameValueCollection();
/// <summary>
/// The headers.
/// </summary>
private readonly NameValueCollection headers = new NameValueCollection();
/// <summary>
/// The referer.
/// </summary>
private Uri referer;
/// <summary>
/// The application path.
/// </summary>
private string applicationPath = "/";
/// <summary>
/// The builder.
/// </summary>
private StringBuilder builder;
/// <summary>
/// The physical application path.
/// </summary>
private string physicalApplicationPath = DefaultPhysicalAppPath;
#endregion
#region Constructors and Destructors
/// <summary>
/// Initializes a new instance of the <see cref="HttpSimulator"/> class.
/// </summary>
public HttpSimulator()
: this("/", DefaultPhysicalAppPath)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="HttpSimulator"/> class.
/// </summary>
/// <param name="applicationPath">
/// The application path.
/// </param>
public HttpSimulator(string applicationPath)
: this(applicationPath, DefaultPhysicalAppPath)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="HttpSimulator"/> class.
/// </summary>
/// <param name="applicationPath">
/// The application path.
/// </param>
/// <param name="physicalApplicationPath">
/// The physical application path.
/// </param>
public HttpSimulator(string applicationPath, string physicalApplicationPath)
{
this.ApplicationPath = applicationPath;
this.PhysicalApplicationPath = physicalApplicationPath;
}
#endregion
#region Public Properties
/// <summary>
/// Gets or sets The same thing as the IIS Virtual directory. It's what gets returned by Request.ApplicationPath.
/// </summary>
/// <value>
/// The application path.
/// </value>
public string ApplicationPath
{
get => this.applicationPath;
set
{
this.applicationPath = value ?? "/";
this.applicationPath = NormalizeSlashes(this.applicationPath);
}
}
/// <summary>
/// Gets Host.
/// </summary>
public string Host { get; private set; }
/// <summary>
/// Gets LocalPath.
/// </summary>
public string LocalPath { get; private set; }
/// <summary>
/// Gets the Portion of the URL after the application.
/// </summary>
public string Page { get; private set; }
/// <summary>
/// Gets or sets the Physical path to the application (used for simulation purposes).
/// </summary>
/// <value>
/// The physical application path.
/// </value>
public string PhysicalApplicationPath
{
get => this.physicalApplicationPath;
set
{
this.physicalApplicationPath = value ?? DefaultPhysicalAppPath;
// strip trailing backslashes.
this.physicalApplicationPath = StripTrailingBackSlashes(this.physicalApplicationPath) + @"\";
}
}
/// <summary>
/// Gets the Physical path to the requested file (used for simulation purposes).
/// </summary>
public string PhysicalPath { get; private set; } = DefaultPhysicalAppPath;
/// <summary>
/// Gets Port.
/// </summary>
public int Port { get; private set; }
/// <summary>
/// Returns the text from the response to the simulated request.
/// </summary>
public string ResponseText => (this.builder ?? new StringBuilder()).ToString();
/// <summary>
/// Gets or sets ResponseWriter.
/// </summary>
public TextWriter ResponseWriter { get; set; }
/// <summary>
/// Gets WorkerRequest.
/// </summary>
public SimulatedHttpRequest WorkerRequest { get; private set; }
#endregion
#region Public Methods and Operators
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
/// <filterpriority>2</filterpriority>
public void Dispose()
{
if (HttpContext.Current != null)
{
HttpContext.Current = null;
}
}
/// <summary>
/// Sets a form variable.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="value">The value.</param>
/// <returns></returns>
public HttpSimulator SetFormVariable(string name, string value)
{
// TODO: Change this ordering requirement.
if (this.WorkerRequest != null)
{
throw new InvalidOperationException("Cannot set form variables after calling Simulate().");
}
this.formVars.Add(name, value);
return this;
}
/// <summary>
/// Sets a header value.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="value">The value.</param>
/// <returns></returns>
public HttpSimulator SetHeader(string name, string value)
{
// TODO: Change this ordering requirement.
if (this.WorkerRequest != null)
{
throw new InvalidOperationException("Cannot set headers after calling Simulate().");
}
this.headers.Add(name, value);
return this;
}
/// <summary>
/// Sets the referer for the request. Uses a fluent interface.
/// </summary>
/// <param name="referer">
/// </param>
/// <returns>
/// </returns>
public HttpSimulator SetReferer(Uri referer)
{
this.WorkerRequest?.SetReferer(referer);
this.referer = referer;
return this;
}
/// <summary>
/// Sets up the HttpContext objects to simulate a GET request.
/// </summary>
/// <remarks>
/// Simulates a request to http://localhost/
/// </remarks>
public HttpSimulator SimulateRequest()
{
return this.SimulateRequest(new Uri("http://localhost/"));
}
/// <summary>
/// Sets up the HttpContext objects to simulate a GET request.
/// </summary>
/// <param name="url">
/// </param>
public HttpSimulator SimulateRequest(bool isMobileDevice)
{
return this.SimulateRequest(new Uri("http://localhost/"), isMobileDevice);
}
/// <summary>
/// Sets up the HttpContext objects to simulate a GET request.
/// </summary>
/// <param name="url">
/// </param>
public HttpSimulator SimulateRequest(Uri url, bool isMobileDevice = false)
{
return this.SimulateRequest(url, HttpVerb.GET, isMobileDevice);
}
/// <summary>
/// Sets up the HttpContext objects to simulate a request.
/// </summary>
/// <param name="url">The URL.</param>
/// <param name="httpVerb">The HTTP verb.</param>
/// <returns></returns>
public HttpSimulator SimulateRequest(Uri url, HttpVerb httpVerb, bool isMobileDevice = false)
{
return this.SimulateRequest(url, httpVerb, null, null, isMobileDevice);
}
/// <summary>
/// Sets up the HttpContext objects to simulate a POST request.
/// </summary>
/// <param name="url">The URL.</param>
/// <param name="formVariables">The form variables.</param>
/// <returns></returns>
public HttpSimulator SimulateRequest(Uri url, NameValueCollection formVariables)
{
return this.SimulateRequest(url, HttpVerb.POST, formVariables, null);
}
/// <summary>
/// Sets up the HttpContext objects to simulate a POST request.
/// </summary>
/// <param name="url">The URL.</param>
/// <param name="formVariables">The form variables.</param>
/// <param name="headers">The headers.</param>
/// <returns></returns>
public HttpSimulator SimulateRequest(Uri url, NameValueCollection formVariables, NameValueCollection headers)
{
return this.SimulateRequest(url, HttpVerb.POST, formVariables, headers);
}
/// <summary>
/// Sets up the HttpContext objects to simulate a request.
/// </summary>
/// <param name="url">The URL.</param>
/// <param name="httpVerb">The HTTP verb.</param>
/// <param name="headers">The headers.</param>
/// <returns></returns>
public HttpSimulator SimulateRequest(Uri url, HttpVerb httpVerb, NameValueCollection headers)
{
return this.SimulateRequest(url, httpVerb, null, headers);
}
#endregion
#region Methods
/// <summary>
/// The get hosting environment.
/// </summary>
/// <returns></returns>
protected static HostingEnvironment GetHostingEnvironment()
{
HostingEnvironment environment;
try
{
environment = new HostingEnvironment();
}
catch (InvalidOperationException)
{
// Shoot, we need to grab it via reflection.
environment = ReflectionHelper.GetStaticFieldValue<HostingEnvironment>(
"_theHostingEnvironment", typeof(HostingEnvironment));
}
return environment;
}
/// <summary>
/// The normalize slashes.
/// </summary>
/// <param name="s">
/// The s.
/// </param>
/// <returns>
/// The normalize slashes.
/// </returns>
protected static string NormalizeSlashes(string s)
{
if (string.IsNullOrEmpty(s) || s == "/")
{
return "/";
}
s = s.Replace(@"\", "/");
// Reduce multiple slashes in row to single.
var normalized = Regex.Replace(s, "(/)/+", "$1");
// Strip left.
normalized = StripPrecedingSlashes(normalized);
// Strip right.
normalized = StripTrailingSlashes(normalized);
return "/" + normalized;
}
/// <summary>
/// The strip preceding slashes.
/// </summary>
/// <param name="s">
/// The s.
/// </param>
/// <returns>
/// The strip preceding slashes.
/// </returns>
protected static string StripPrecedingSlashes(string s)
{
return Regex.Replace(s, "^/*(.*)", "$1");
}
/// <summary>
/// The strip trailing back slashes.
/// </summary>
/// <param name="s">
/// The s.
/// </param>
/// <returns>
/// The strip trailing back slashes.
/// </returns>
protected static string StripTrailingBackSlashes(string s)
{
if (string.IsNullOrEmpty(s))
{
return string.Empty;
}
return Regex.Replace(s, @"(.*)\\*$", "$1", RegexOptions.RightToLeft);
}
/// <summary>
/// The strip trailing slashes.
/// </summary>
/// <param name="s">
/// The s.
/// </param>
/// <returns>
/// The strip trailing slashes.
/// </returns>
protected static string StripTrailingSlashes(string s)
{
return Regex.Replace(s, "(.*)/*$", "$1", RegexOptions.RightToLeft);
}
/// <summary>
/// Sets up the HttpContext objects to simulate a request.
/// </summary>
/// <param name="url">
/// </param>
/// <param name="httpVerb">
/// </param>
/// <param name="formVariables">
/// </param>
/// <param name="headers">
/// </param>
protected virtual HttpSimulator SimulateRequest(
Uri url, HttpVerb httpVerb, NameValueCollection formVariables, NameValueCollection headers, bool isMobileDevice = false)
{
HttpContext.Current = null;
this.ParseRequestUrl(url);
if (this.ResponseWriter == null)
{
this.builder = new StringBuilder();
this.ResponseWriter = new StringWriter(this.builder);
}
this.SetHttpRuntimeInternals();
var query = ExtractQueryStringPart(url);
if (formVariables != null)
{
this.formVars.Add(formVariables);
}
if (this.formVars.Count > 0)
{
httpVerb = HttpVerb.POST; // Need to enforce this.
}
if (headers != null)
{
this.headers.Add(headers);
}
this.WorkerRequest = new SimulatedHttpRequest(
this.ApplicationPath,
this.PhysicalApplicationPath,
this.PhysicalPath,
this.Page,
query,
this.ResponseWriter,
this.Host,
this.Port,
httpVerb.ToString());
this.WorkerRequest.Form.Add(this.formVars);
this.WorkerRequest.Headers.Add(this.headers);
if (this.referer != null)
{
this.WorkerRequest.SetReferer(this.referer);
}
this.InitializeSession(isMobileDevice);
InitializeApplication();
Console.WriteLine("host: {0}", this.Host);
Console.WriteLine("virtualDir: {0}", this.applicationPath);
Console.WriteLine("page: {0}", this.LocalPath);
Console.WriteLine("pathPartAfterApplicationPart: {0}", this.Page);
Console.WriteLine("appPhysicalDir: {0}", this.physicalApplicationPath);
Console.WriteLine("Request.Url.LocalPath: {0}", HttpContext.Current.Request.Url.LocalPath);
Console.WriteLine("Request.Url.Host: {0}", HttpContext.Current.Request.Url.Host);
Console.WriteLine("Request.FilePath: {0}", HttpContext.Current.Request.FilePath);
Console.WriteLine("Request.Path: " + HttpContext.Current.Request.Path);
Console.WriteLine("Request.RawUrl: " + HttpContext.Current.Request.RawUrl);
Console.WriteLine("Request.Url: " + HttpContext.Current.Request.Url);
Console.WriteLine("Request.Url.Port: " + HttpContext.Current.Request.Url.Port);
Console.WriteLine("Request.ApplicationPath: " + HttpContext.Current.Request.ApplicationPath);
Console.WriteLine("Request.PhysicalPath: " + HttpContext.Current.Request.PhysicalPath);
Console.WriteLine("HttpRuntime.AppDomainAppPath: " + HttpRuntime.AppDomainAppPath);
Console.WriteLine("HttpRuntime.AppDomainAppVirtualPath: " + HttpRuntime.AppDomainAppVirtualPath);
Console.WriteLine(
"HostingEnvironment.ApplicationPhysicalPath: " + HostingEnvironment.ApplicationPhysicalPath);
Console.WriteLine("HostingEnvironment.ApplicationVirtualPath: " + HostingEnvironment.ApplicationVirtualPath);
return this;
}
/// <summary>
/// The extract query string part.
/// </summary>
/// <param name="url">
/// The url.
/// </param>
/// <returns>
/// The extract query string part.
/// </returns>
private static string ExtractQueryStringPart(Uri url)
{
var query = url.Query;
return query.StartsWith("?") ? query.Substring(1) : query;
}
/// <summary>
/// The initialize application.
/// </summary>
private static void InitializeApplication()
{
var appFactoryType =
Type.GetType(
"System.Web.HttpApplicationFactory, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
var appFactory = ReflectionHelper.GetStaticFieldValue<object>("_theApplicationFactory", appFactoryType);
ReflectionHelper.SetPrivateInstanceFieldValue("_state", appFactory, HttpContext.Current.Application);
}
/// <summary>
/// The right after.
/// </summary>
/// <param name="original">
/// The original.
/// </param>
/// <param name="search">
/// The search.
/// </param>
/// <returns>
/// The right after.
/// </returns>
private static string RightAfter(string original, string search)
{
if (search.Length > original.Length || search.Length == 0)
{
return original;
}
var searchIndex = original.IndexOf(search, 0, StringComparison.InvariantCultureIgnoreCase);
return searchIndex < 0 ? original : original.Substring(original.IndexOf(search) + search.Length);
}
/// <summary>
/// The initialize session.
/// </summary>
/// <param name="isMobileDevice">if set to <c>true</c> [is mobile device].</param>
private void InitializeSession(bool isMobileDevice = false)
{
HttpContext.Current = new HttpContext(this.WorkerRequest);
HttpContext.Current.Items.Clear();
var session =
(HttpSessionState)
ReflectionHelper.Instantiate(
typeof(HttpSessionState), new[] { typeof(IHttpSessionState) }, new FakeHttpSessionState());
var browserCaps = new HttpBrowserCapabilities();
var values = new Hashtable(20, StringComparer.OrdinalIgnoreCase) { ["ecmascriptversion"] = "3.0" };
if (isMobileDevice)
{
values["Type"] = "YAFMobile1";
values["Name"] = "YAFMobile";
values["IsMobileDevice"] = "True";
values["Platform"] = "yafiphone";
values["Is Win16"] = "False";
values["Is Win32"] = "False";
}
else
{
values["Type"] = "Chrome18";
values["Name"] = "Chrome";
values["IsMobileDevice"] = "False";
values["Platform"] = "WinNT";
values["Is Win16"] = "False";
values["Is Win32"] = "True";
}
values["Browser"] = "YAF";
values["Version"] = "3.0";
values["Major Version"] = "3";
values["Minor Version"] = "0";
values["Is Beta"] = "False";
values["Is Crawler"] = "False";
values["Is AOL"] = "False";
values["Supports Frames"] = "True";
values["Supports Tables"] = "True";
values["Supports Cookies"] = "True";
values["Supports VB Script"] = "False";
values["Supports JavaScript"] = "True";
values["Supports Java Applets"] = "True";
values["Supports ActiveX Controls"] = "False";
values["CDF"] = "False";
values["Crawler"] = "False";
browserCaps.Capabilities = values;
HttpContext.Current.Request.Browser = browserCaps;
HttpContext.Current.Items.Add("AspSession", session);
}
/// <summary>
/// The parse request url.
/// </summary>
/// <param name="url">
/// The url.
/// </param>
private void ParseRequestUrl(Uri url)
{
if (url == null)
{
return;
}
this.Host = url.Host;
this.Port = url.Port;
this.LocalPath = url.LocalPath;
this.Page = StripPrecedingSlashes(RightAfter(url.LocalPath, this.ApplicationPath));
this.PhysicalPath = Path.Combine(this.physicalApplicationPath, this.Page.Replace("/", @"\"));
}
/// <summary>
/// The set http runtime internals.
/// </summary>
private void SetHttpRuntimeInternals()
{
// We cheat by using reflection.
// get singleton property value
var runtime = ReflectionHelper.GetStaticFieldValue<HttpRuntime>("_theRuntime", typeof(HttpRuntime));
// set app path property value
ReflectionHelper.SetPrivateInstanceFieldValue("_appDomainAppPath", runtime, this.PhysicalApplicationPath);
// set app virtual path property value
const string vpathTypeName = "System.Web.VirtualPath, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";
var virtualPath = ReflectionHelper.Instantiate(
vpathTypeName, new[] { typeof(string) }, new object[] { this.ApplicationPath });
ReflectionHelper.SetPrivateInstanceFieldValue("_appDomainAppVPath", runtime, virtualPath);
// set codegen dir property value
ReflectionHelper.SetPrivateInstanceFieldValue("_codegenDir", runtime, this.PhysicalApplicationPath);
var environment = GetHostingEnvironment();
ReflectionHelper.SetPrivateInstanceFieldValue("_appPhysicalPath", environment, this.PhysicalApplicationPath);
ReflectionHelper.SetPrivateInstanceFieldValue("_appVirtualPath", environment, virtualPath);
ReflectionHelper.SetPrivateInstanceFieldValue("_configMapPath", environment, new ConfigMapPath(this));
}
#endregion
/// <summary>
/// The config map path.
/// </summary>
public class ConfigMapPath : IConfigMapPath
{
#region Constants and Fields
/// <summary>
/// The _request simulation.
/// </summary>
private readonly HttpSimulator _requestSimulation;
#endregion
#region Constructors and Destructors
/// <summary>
/// Initializes a new instance of the <see cref="ConfigMapPath"/> class.
/// </summary>
/// <param name="simulation">
/// The simulation.
/// </param>
public ConfigMapPath(HttpSimulator simulation)
{
this._requestSimulation = simulation;
}
#endregion
#region Public Methods and Operators
/// <summary>
/// The get app path for path.
/// </summary>
/// <param name="siteID">
/// The site id.
/// </param>
/// <param name="path">
/// The path.
/// </param>
/// <returns>
/// The get app path for path.
/// </returns>
public string GetAppPathForPath(string siteID, string path)
{
return this._requestSimulation.ApplicationPath;
}
/// <summary>
/// The get default site name and id.
/// </summary>
/// <param name="siteName">
/// The site name.
/// </param>
/// <param name="siteID">
/// The site id.
/// </param>
/// <exception cref="NotImplementedException">
/// </exception>
public void GetDefaultSiteNameAndID(out string siteName, out string siteID)
{
throw new NotImplementedException();
}
/// <summary>
/// The get machine config filename.
/// </summary>
/// <returns>
/// The get machine config filename.
/// </returns>
/// <exception cref="NotImplementedException">
/// </exception>
public string GetMachineConfigFilename()
{
throw new NotImplementedException();
}
/// <summary>
/// The get path config filename.
/// </summary>
/// <param name="siteID">
/// The site id.
/// </param>
/// <param name="path">
/// The path.
/// </param>
/// <param name="directory">
/// The directory.
/// </param>
/// <param name="baseName">
/// The base name.
/// </param>
/// <exception cref="NotImplementedException">
/// </exception>
public void GetPathConfigFilename(string siteID, string path, out string directory, out string baseName)
{
throw new NotImplementedException();
}
/// <summary>
/// The get root web config filename.
/// </summary>
/// <returns>
/// The get root web config filename.
/// </returns>
/// <exception cref="NotImplementedException">
/// </exception>
public string GetRootWebConfigFilename()
{
throw new NotImplementedException();
}
/// <summary>
/// The map path.
/// </summary>
/// <param name="siteID">
/// The site id.
/// </param>
/// <param name="path">
/// The path.
/// </param>
/// <returns>
/// The map path.
/// </returns>
public string MapPath(string siteID, string path)
{
var page = StripPrecedingSlashes(RightAfter(path, this._requestSimulation.ApplicationPath));
return Path.Combine(this._requestSimulation.PhysicalApplicationPath, page.Replace("/", @"\"));
}
/// <summary>
/// The resolve site argument.
/// </summary>
/// <param name="siteArgument">
/// The site argument.
/// </param>
/// <param name="siteName">
/// The site name.
/// </param>
/// <param name="siteID">
/// The site id.
/// </param>
/// <exception cref="NotImplementedException">
/// </exception>
public void ResolveSiteArgument(string siteArgument, out string siteName, out string siteID)
{
throw new NotImplementedException();
}
#endregion
}
/// <summary>
/// The fake http session state.
/// </summary>
public class FakeHttpSessionState : NameObjectCollectionBase, IHttpSessionState
{
#region Constants and Fields
#endregion
#region Public Properties
///<summary>
/// Gets or sets the code-page identifier for the current session.
///</summary>
///<returns> The code-page identifier for the current session. </returns>
public int CodePage { get; set; }
///<summary>
/// Gets a value that indicates whether the application is configured for cookieless sessions.
///</summary>
///<returns> One of the <see cref="T:System.Web.HttpCookieMode"></see> values that indicate whether the application is configured for cookieless sessions. The default is <see
/// cref="F:System.Web.HttpCookieMode.UseCookies"></see> . </returns>
public HttpCookieMode CookieMode => HttpCookieMode.UseCookies;
///<summary>
/// Gets a value indicating whether the session ID is embedded in the URL or stored in an HTTP cookie.
///</summary>
///<returns> true if the session is embedded in the URL; otherwise, false. </returns>
public bool IsCookieless => false;
///<summary>
/// Gets a value indicating whether the session was created with the current request.
///</summary>
///<returns> true if the session was created with the current request; otherwise, false. </returns>
public bool IsNewSession { get; } = true;
///<summary>
/// Gets a value indicating whether access to the collection of session-state values is synchronized (thread safe).
///</summary>
///<returns> true if access to the collection is synchronized (thread safe); otherwise, false. </returns>
public bool IsSynchronized => true;
///<summary>
/// Gets or sets the locale identifier (LCID) of the current session.
///</summary>
///<returns> A <see cref="T:System.Globalization.CultureInfo"></see> instance that specifies the culture of the current session. </returns>
public int LCID { get; set; }
///<summary>
/// Gets the current session-state mode.
///</summary>
///<returns> One of the <see cref="T:System.Web.SessionState.SessionStateMode"></see> values. </returns>
public SessionStateMode Mode => SessionStateMode.InProc;
///<summary>
/// Gets the unique session identifier for the session.
///</summary>
///<returns> The session ID. </returns>
public string SessionID { get; } = Guid.NewGuid().ToString().Remove(24);
///<summary>
/// Gets a collection of objects declared by <object Runat="Server" Scope="Session"/> tags within the ASP.NET application file Global.asax.
///</summary>
///<returns> An <see cref="T:System.Web.HttpStaticObjectsCollection"></see> containing objects declared in the Global.asax file. </returns>
public HttpStaticObjectsCollection StaticObjects { get; } = new HttpStaticObjectsCollection();
///<summary>
/// Gets an object that can be used to synchronize access to the collection of session-state values.
///</summary>
///<returns> An object that can be used to synchronize access to the collection. </returns>
public object SyncRoot { get; } = new object();
///<summary>
/// Gets and sets the time-out period (in minutes) allowed between requests before the session-state provider terminates the session.
///</summary>
///<returns> The time-out period, in minutes. </returns>
public int Timeout { get; set; } = 30;
#endregion
#region Explicit Interface Properties
///<summary>
/// Gets a value indicating whether the session is read-only.
///</summary>
///<returns> true if the session is read-only; otherwise, false. </returns>
bool IHttpSessionState.IsReadOnly => true;
#endregion
#region Public Indexers
///<summary>
/// Gets or sets a session-state item value by name.
///</summary>
///<returns> The session-state item value specified in the name parameter. </returns>
///<param name="name"> The key name of the session-state item value. </param>
public object this[string name]
{
get => this.BaseGet(name);
set => this.BaseSet(name, value);
}
///<summary>
/// Gets or sets a session-state item value by numerical index.
///</summary>
///<returns> The session-state item value specified in the index parameter. </returns>
///<param name="index"> The numerical index of the session-state item value. </param>
public object this[int index]
{
get => this.BaseGet(index);
set => this.BaseSet(index, value);
}
#endregion
#region Public Methods and Operators
/// <summary>
/// Ends the current session.
/// </summary>
public void Abandon()
{
this.BaseClear();
}
/// <summary>
/// Adds a new item to the session-state collection.
/// </summary>
/// <param name="name">
/// The name of the item to add to the session-state collection.
/// </param>
/// <param name="value">
/// The value of the item to add to the session-state collection.
/// </param>
public void Add(string name, object value)
{
this.BaseAdd(name, value);
}
/// <summary>
/// Clears all values from the session-state item collection.
/// </summary>
public void Clear()
{
this.BaseClear();
}
/// <summary>
/// Copies the collection of session-state item values to a one-dimensional array, starting at the specified index in the array.
/// </summary>
/// <param name="array">
/// The <see cref="T:System.Array"></see> that receives the session values.
/// </param>
/// <param name="index">
/// The index in array where copying starts.
/// </param>
public void CopyTo(Array array, int index)
{
throw new NotImplementedException();
}
/// <summary>
/// Deletes an item from the session-state item collection.
/// </summary>
/// <param name="name">
/// The name of the item to delete from the session-state item collection.
/// </param>
public void Remove(string name)
{
this.BaseRemove(name);
}
/// <summary>
/// Clears all values from the session-state item collection.
/// </summary>
public void RemoveAll()
{
this.BaseClear();
}
/// <summary>
/// Deletes an item at a specified index from the session-state item collection.
/// </summary>
/// <param name="index">
/// The index of the item to remove from the session-state collection.
/// </param>
public void RemoveAt(int index)
{
this.BaseRemoveAt(index);
}
#endregion
}
}
}
| |
using System;
using System.Diagnostics;
using System.Reflection;
using FluentAssertions.Common;
using FluentAssertions.Execution;
namespace FluentAssertions.Types
{
/// <summary>
/// Contains a number of methods to assert that a <see cref="PropertyInfo"/> is in the expected state.
/// </summary>
[DebuggerNonUserCode]
public class PropertyInfoAssertions :
MemberInfoAssertions<PropertyInfo, PropertyInfoAssertions>
{
public PropertyInfoAssertions(PropertyInfo propertyInfo)
{
Subject = propertyInfo;
}
/// <summary>
/// Asserts that the selected property is virtual.
/// </summary>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndConstraint<PropertyInfoAssertions> BeVirtual(
string because = "", params object[] becauseArgs)
{
string failureMessage = "Expected property " +
GetDescriptionFor(Subject) +
" to be virtual{reason}, but it is not.";
Execute.Assertion
.ForCondition(Subject.IsVirtual())
.BecauseOf(because, becauseArgs)
.FailWith(failureMessage);
return new AndConstraint<PropertyInfoAssertions>(this);
}
/// <summary>
/// Asserts that the selected property has a setter.
/// </summary>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndConstraint<PropertyInfoAssertions> BeWritable(
string because = "", params object[] becauseArgs)
{
Execute.Assertion
.ForCondition(Subject.CanWrite)
.BecauseOf(because, becauseArgs)
.FailWith(
"Expected {context:property} {0} to have a setter{reason}.",
Subject);
return new AndConstraint<PropertyInfoAssertions>(this);
}
/// <summary>
/// Asserts that the selected property has a setter with the specified C# access modifier.
/// </summary>
/// <param name="accessModifier">The expected C# access modifier.</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndConstraint<PropertyInfoAssertions> BeWritable(CSharpAccessModifier accessModifier, string because = "", params object[] becauseArgs)
{
Subject.Should().BeWritable(because, becauseArgs);
Subject.GetSetMethod(true).Should().HaveAccessModifier(accessModifier, because, becauseArgs);
return new AndConstraint<PropertyInfoAssertions>(this);
}
/// <summary>
/// Asserts that the selected property does not have a setter.
/// </summary>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndConstraint<PropertyInfoAssertions> NotBeWritable(
string because = "", params object[] becauseArgs)
{
Execute.Assertion
.ForCondition(!Subject.CanWrite)
.BecauseOf(because, becauseArgs)
.FailWith(
"Expected {context:property} {0} not to have a setter{reason}.",
Subject);
return new AndConstraint<PropertyInfoAssertions>(this);
}
/// <summary>
/// Asserts that the selected property has a getter.
/// </summary>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndConstraint<PropertyInfoAssertions> BeReadable(string because = "", params object[] becauseArgs)
{
Execute.Assertion.ForCondition(Subject.CanRead)
.BecauseOf(because, becauseArgs)
.FailWith("Expected property " + Subject.Name + " to have a getter{reason}, but it does not.");
return new AndConstraint<PropertyInfoAssertions>(this);
}
/// <summary>
/// Asserts that the selected property has a getter with the specified C# access modifier.
/// </summary>
/// <param name="accessModifier">The expected C# access modifier.</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndConstraint<PropertyInfoAssertions> BeReadable(CSharpAccessModifier accessModifier, string because = "", params object[] becauseArgs)
{
Subject.Should().BeReadable(because, becauseArgs);
Subject.GetGetMethod(true).Should().HaveAccessModifier(accessModifier, because, becauseArgs);
return new AndConstraint<PropertyInfoAssertions>(this);
}
/// <summary>
/// Asserts that the selected property does not have a getter.
/// </summary>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndConstraint<PropertyInfoAssertions> NotBeReadable(
string because = "", params object[] becauseArgs)
{
Execute.Assertion
.ForCondition(!Subject.CanRead)
.BecauseOf(because, becauseArgs)
.FailWith(
"Expected {context:property} {0} not to have a getter{reason}.",
Subject);
return new AndConstraint<PropertyInfoAssertions>(this);
}
/// <summary>
/// Asserts that the selected property returns a specified type.
/// </summary>
/// <param name="propertyType">The expected type of the property.</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndConstraint<PropertyInfoAssertions> Return(Type propertyType,
string because = "", params object[] becauseArgs)
{
Execute.Assertion.ForCondition(Subject.PropertyType == propertyType)
.BecauseOf(because, becauseArgs)
.FailWith("Expected Type of property " + Subject.Name + " to be {0}{reason}, but it is {1}.", propertyType, Subject.PropertyType);
return new AndConstraint<PropertyInfoAssertions>(this);
}
/// <summary>
/// Asserts that the selected PropertyInfo returns <typeparamref name="TReturn"/>.
/// </summary>
/// <typeparam name="TReturn">The expected return type.</typeparam>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndConstraint<PropertyInfoAssertions> Return<TReturn>(string because = "", params object[] becauseArgs)
{
return Return(typeof(TReturn), because, becauseArgs);
}
internal static string GetDescriptionFor(PropertyInfo property)
{
string propTypeName = property.PropertyType.Name;
return String.Format("{0} {1}.{2}", propTypeName,
property.DeclaringType, property.Name);
}
internal override string SubjectDescription
{
get { return GetDescriptionFor(Subject); }
}
/// <summary>
/// Returns the type of the subject the assertion applies on.
/// </summary>
protected override string Context
{
get { return "property"; }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.NetCore.Extensions;
namespace System.Tests
{
public class EnvironmentTests : RemoteExecutorTestBase
{
[Fact]
public void CurrentDirectory_Null_Path_Throws_ArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("value", () => Environment.CurrentDirectory = null);
}
[Fact]
public void CurrentDirectory_Empty_Path_Throws_ArgumentException()
{
AssertExtensions.Throws<ArgumentException>("value", null, () => Environment.CurrentDirectory = string.Empty);
}
[Fact]
public void CurrentDirectory_SetToNonExistentDirectory_ThrowsDirectoryNotFoundException()
{
Assert.Throws<DirectoryNotFoundException>(() => Environment.CurrentDirectory = GetTestFilePath());
}
[Fact]
public void CurrentDirectory_SetToValidOtherDirectory()
{
RemoteInvoke(() =>
{
Environment.CurrentDirectory = TestDirectory;
Assert.Equal(Directory.GetCurrentDirectory(), Environment.CurrentDirectory);
if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
// On OSX, the temp directory /tmp/ is a symlink to /private/tmp, so setting the current
// directory to a symlinked path will result in GetCurrentDirectory returning the absolute
// path that followed the symlink.
Assert.Equal(TestDirectory, Directory.GetCurrentDirectory());
}
return SuccessExitCode;
}).Dispose();
}
[Fact]
public void CurrentManagedThreadId_Idempotent()
{
Assert.Equal(Environment.CurrentManagedThreadId, Environment.CurrentManagedThreadId);
}
[Fact]
public void CurrentManagedThreadId_DifferentForActiveThreads()
{
var ids = new HashSet<int>();
Barrier b = new Barrier(10);
Task.WaitAll((from i in Enumerable.Range(0, b.ParticipantCount)
select Task.Factory.StartNew(() =>
{
b.SignalAndWait();
lock (ids) ids.Add(Environment.CurrentManagedThreadId);
b.SignalAndWait();
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default)).ToArray());
Assert.Equal(b.ParticipantCount, ids.Count);
}
[Fact]
public void HasShutdownStarted_FalseWhileExecuting()
{
Assert.False(Environment.HasShutdownStarted);
}
[Fact]
public void Is64BitProcess_MatchesIntPtrSize()
{
Assert.Equal(IntPtr.Size == 8, Environment.Is64BitProcess);
}
[Fact]
public void Is64BitOperatingSystem_TrueIf64BitProcess()
{
if (Environment.Is64BitProcess)
{
Assert.True(Environment.Is64BitOperatingSystem);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Tests OS-specific environment
public void Is64BitOperatingSystem_Unix_TrueIff64BitProcess()
{
Assert.Equal(Environment.Is64BitProcess, Environment.Is64BitOperatingSystem);
}
[Fact]
public void OSVersion_Idempotent()
{
Assert.Same(Environment.OSVersion, Environment.OSVersion);
}
[Fact]
public void OSVersion_MatchesPlatform()
{
PlatformID id = Environment.OSVersion.Platform;
Assert.Equal(
RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? PlatformID.Win32NT : PlatformID.Unix,
id);
}
[Fact]
public void OSVersion_ValidVersion()
{
Version version = Environment.OSVersion.Version;
string versionString = Environment.OSVersion.VersionString;
Assert.False(string.IsNullOrWhiteSpace(versionString), "Expected non-empty version string");
Assert.True(version.Major > 0);
Assert.Contains(version.ToString(2), versionString);
Assert.Contains(RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "Windows" : "Unix", versionString);
}
[Fact]
public void SystemPageSize_Valid()
{
int pageSize = Environment.SystemPageSize;
Assert.Equal(pageSize, Environment.SystemPageSize);
Assert.True(pageSize > 0, "Expected positive page size");
Assert.True((pageSize & (pageSize - 1)) == 0, "Expected power-of-2 page size");
}
[Fact]
public void UserInteractive_True()
{
Assert.True(Environment.UserInteractive);
}
[Fact]
public void UserName_Valid()
{
Assert.False(string.IsNullOrWhiteSpace(Environment.UserName));
}
[Fact]
public void UserDomainName_Valid()
{
Assert.False(string.IsNullOrWhiteSpace(Environment.UserDomainName));
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Tests OS-specific environment
public void UserDomainName_Unix_MatchesMachineName()
{
Assert.Equal(Environment.MachineName, Environment.UserDomainName);
}
[Fact]
public void Version_MatchesFixedVersion()
{
Assert.Equal(new Version(4, 0, 30319, 42000), Environment.Version);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap)] // Throws InvalidOperationException in Uap as NtQuerySystemInformation Pinvoke is not available
public void WorkingSet_Valid()
{
Assert.True(Environment.WorkingSet > 0, "Expected positive WorkingSet value");
}
[Fact]
[SkipOnTargetFramework(~TargetFrameworkMonikers.Uap)]
public void WorkingSet_Valid_Uap()
{
Assert.Throws<PlatformNotSupportedException>(() => Environment.WorkingSet);
}
[Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // fail fast crashes the process
[OuterLoop]
[Fact]
[ActiveIssue("https://github.com/dotnet/corefx/issues/21404", TargetFrameworkMonikers.Uap)]
public void FailFast_ExpectFailureExitCode()
{
using (Process p = RemoteInvoke(() => { Environment.FailFast("message"); return SuccessExitCode; }).Process)
{
p.WaitForExit();
Assert.NotEqual(SuccessExitCode, p.ExitCode);
}
using (Process p = RemoteInvoke(() => { Environment.FailFast("message", new Exception("uh oh")); return SuccessExitCode; }).Process)
{
p.WaitForExit();
Assert.NotEqual(SuccessExitCode, p.ExitCode);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Tests OS-specific environment
public void GetFolderPath_Unix_PersonalIsHomeAndUserProfile()
{
Assert.Equal(Environment.GetEnvironmentVariable("HOME"), Environment.GetFolderPath(Environment.SpecialFolder.Personal));
Assert.Equal(Environment.GetEnvironmentVariable("HOME"), Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
Assert.Equal(Environment.GetEnvironmentVariable("HOME"), Environment.GetFolderPath(Environment.SpecialFolder.UserProfile));
}
[Fact]
public void GetSystemDirectory()
{
if (PlatformDetection.IsWindowsNanoServer)
{
// https://github.com/dotnet/corefx/issues/19110
// On Windows Nano, ShGetKnownFolderPath currently doesn't give
// the correct result for SystemDirectory.
// Assert that it's wrong, so that if it's fixed, we don't forget to
// enable this test for Nano.
Assert.NotEqual(Environment.GetFolderPath(Environment.SpecialFolder.System), Environment.SystemDirectory);
return;
}
Assert.Equal(Environment.GetFolderPath(Environment.SpecialFolder.System), Environment.SystemDirectory);
}
[Theory]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Tests OS-specific environment
[InlineData(Environment.SpecialFolder.UserProfile, Environment.SpecialFolderOption.None)]
[InlineData(Environment.SpecialFolder.Personal, Environment.SpecialFolderOption.None)]
[InlineData(Environment.SpecialFolder.MyDocuments, Environment.SpecialFolderOption.None)]
[InlineData(Environment.SpecialFolder.CommonApplicationData, Environment.SpecialFolderOption.None)]
[InlineData(Environment.SpecialFolder.CommonTemplates, Environment.SpecialFolderOption.DoNotVerify)]
[InlineData(Environment.SpecialFolder.ApplicationData, Environment.SpecialFolderOption.DoNotVerify)]
[InlineData(Environment.SpecialFolder.LocalApplicationData, Environment.SpecialFolderOption.DoNotVerify)]
[InlineData(Environment.SpecialFolder.Desktop, Environment.SpecialFolderOption.DoNotVerify)]
[InlineData(Environment.SpecialFolder.DesktopDirectory, Environment.SpecialFolderOption.DoNotVerify)]
// Not set on Unix (amongst others)
//[InlineData(Environment.SpecialFolder.System, Environment.SpecialFolderOption.DoNotVerify)]
[InlineData(Environment.SpecialFolder.Templates, Environment.SpecialFolderOption.DoNotVerify)]
[InlineData(Environment.SpecialFolder.MyVideos, Environment.SpecialFolderOption.DoNotVerify)]
[InlineData(Environment.SpecialFolder.MyMusic, Environment.SpecialFolderOption.DoNotVerify)]
[InlineData(Environment.SpecialFolder.MyPictures, Environment.SpecialFolderOption.DoNotVerify)]
[InlineData(Environment.SpecialFolder.Fonts, Environment.SpecialFolderOption.DoNotVerify)]
public void GetFolderPath_Unix_NonEmptyFolderPaths(Environment.SpecialFolder folder, Environment.SpecialFolderOption option)
{
Assert.NotEmpty(Environment.GetFolderPath(folder, option));
if (option == Environment.SpecialFolderOption.None)
{
Assert.NotEmpty(Environment.GetFolderPath(folder));
}
}
[Theory]
[PlatformSpecific(TestPlatforms.OSX)] // Tests OS-specific environment
[InlineData(Environment.SpecialFolder.Favorites, Environment.SpecialFolderOption.DoNotVerify)]
[InlineData(Environment.SpecialFolder.InternetCache, Environment.SpecialFolderOption.DoNotVerify)]
[InlineData(Environment.SpecialFolder.ProgramFiles, Environment.SpecialFolderOption.None)]
[InlineData(Environment.SpecialFolder.System, Environment.SpecialFolderOption.None)]
public void GetFolderPath_OSX_NonEmptyFolderPaths(Environment.SpecialFolder folder, Environment.SpecialFolderOption option)
{
Assert.NotEmpty(Environment.GetFolderPath(folder, option));
if (option == Environment.SpecialFolderOption.None)
{
Assert.NotEmpty(Environment.GetFolderPath(folder));
}
}
// Requires recent RS3 builds
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsWindows10Version16251OrGreater))]
[SkipOnTargetFramework(~(TargetFrameworkMonikers.Uap | TargetFrameworkMonikers.UapAot))]
[InlineData(Environment.SpecialFolder.LocalApplicationData)]
[InlineData(Environment.SpecialFolder.Cookies)]
[InlineData(Environment.SpecialFolder.History)]
[InlineData(Environment.SpecialFolder.InternetCache)]
[InlineData(Environment.SpecialFolder.System)]
[InlineData(Environment.SpecialFolder.SystemX86)]
[InlineData(Environment.SpecialFolder.Windows)]
public void GetFolderPath_UapExistAndAccessible(Environment.SpecialFolder folder)
{
string knownFolder = Environment.GetFolderPath(folder);
Assert.NotEmpty(knownFolder);
AssertDirectoryExists(knownFolder);
}
// Requires recent RS3 builds
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsWindows10Version16251OrGreater))]
[SkipOnTargetFramework(~(TargetFrameworkMonikers.Uap | TargetFrameworkMonikers.UapAot))]
[InlineData(Environment.SpecialFolder.ApplicationData)]
[InlineData(Environment.SpecialFolder.MyMusic)]
[InlineData(Environment.SpecialFolder.MyPictures)]
[InlineData(Environment.SpecialFolder.MyVideos)]
[InlineData(Environment.SpecialFolder.Recent)]
[InlineData(Environment.SpecialFolder.Templates)]
[InlineData(Environment.SpecialFolder.DesktopDirectory)]
[InlineData(Environment.SpecialFolder.Personal)]
[InlineData(Environment.SpecialFolder.UserProfile)]
[InlineData(Environment.SpecialFolder.CommonDocuments)]
[InlineData(Environment.SpecialFolder.CommonMusic)]
[InlineData(Environment.SpecialFolder.CommonPictures)]
[InlineData(Environment.SpecialFolder.CommonDesktopDirectory)]
[InlineData(Environment.SpecialFolder.CommonVideos)]
// These are in the package folder
[InlineData(Environment.SpecialFolder.CommonApplicationData)]
[InlineData(Environment.SpecialFolder.Desktop)]
[InlineData(Environment.SpecialFolder.Favorites)]
public void GetFolderPath_UapNotEmpty(Environment.SpecialFolder folder)
{
// The majority of the paths here cannot be accessed from an appcontainer
string knownFolder = Environment.GetFolderPath(folder);
Assert.NotEmpty(knownFolder);
}
private void AssertDirectoryExists(string path)
{
// Directory.Exists won't tell us if access was denied, etc. Invoking directly
// to get diagnosable test results.
FileAttributes attributes = GetFileAttributesW(path);
if (attributes == (FileAttributes)(-1))
{
int error = Marshal.GetLastWin32Error();
Assert.False(true, $"error {error} getting attributes for {path}");
}
Assert.True((attributes & FileAttributes.Directory) == FileAttributes.Directory, $"not a directory: {path}");
}
// The commented out folders aren't set on all systems.
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))] // https://github.com/dotnet/corefx/issues/19110
[InlineData(Environment.SpecialFolder.ApplicationData)]
[InlineData(Environment.SpecialFolder.CommonApplicationData)]
[InlineData(Environment.SpecialFolder.LocalApplicationData)]
[InlineData(Environment.SpecialFolder.Cookies)]
[InlineData(Environment.SpecialFolder.Desktop)]
[InlineData(Environment.SpecialFolder.Favorites)]
[InlineData(Environment.SpecialFolder.History)]
[InlineData(Environment.SpecialFolder.InternetCache)]
[InlineData(Environment.SpecialFolder.Programs)]
// [InlineData(Environment.SpecialFolder.MyComputer)]
[InlineData(Environment.SpecialFolder.MyMusic)]
[InlineData(Environment.SpecialFolder.MyPictures)]
[InlineData(Environment.SpecialFolder.MyVideos)]
[InlineData(Environment.SpecialFolder.Recent)]
[InlineData(Environment.SpecialFolder.SendTo)]
[InlineData(Environment.SpecialFolder.StartMenu)]
[InlineData(Environment.SpecialFolder.Startup)]
[InlineData(Environment.SpecialFolder.System)]
[InlineData(Environment.SpecialFolder.Templates)]
[InlineData(Environment.SpecialFolder.DesktopDirectory)]
[InlineData(Environment.SpecialFolder.Personal)]
[InlineData(Environment.SpecialFolder.ProgramFiles)]
[InlineData(Environment.SpecialFolder.CommonProgramFiles)]
[InlineData(Environment.SpecialFolder.AdminTools)]
[InlineData(Environment.SpecialFolder.CDBurning)]
[InlineData(Environment.SpecialFolder.CommonAdminTools)]
[InlineData(Environment.SpecialFolder.CommonDocuments)]
[InlineData(Environment.SpecialFolder.CommonMusic)]
// [InlineData(Environment.SpecialFolder.CommonOemLinks)]
[InlineData(Environment.SpecialFolder.CommonPictures)]
[InlineData(Environment.SpecialFolder.CommonStartMenu)]
[InlineData(Environment.SpecialFolder.CommonPrograms)]
[InlineData(Environment.SpecialFolder.CommonStartup)]
[InlineData(Environment.SpecialFolder.CommonDesktopDirectory)]
[InlineData(Environment.SpecialFolder.CommonTemplates)]
[InlineData(Environment.SpecialFolder.CommonVideos)]
[InlineData(Environment.SpecialFolder.Fonts)]
[InlineData(Environment.SpecialFolder.NetworkShortcuts)]
// [InlineData(Environment.SpecialFolder.PrinterShortcuts)]
[InlineData(Environment.SpecialFolder.UserProfile)]
[InlineData(Environment.SpecialFolder.CommonProgramFilesX86)]
[InlineData(Environment.SpecialFolder.ProgramFilesX86)]
[InlineData(Environment.SpecialFolder.Resources)]
// [InlineData(Environment.SpecialFolder.LocalizedResources)]
[InlineData(Environment.SpecialFolder.SystemX86)]
[InlineData(Environment.SpecialFolder.Windows)]
[PlatformSpecific(TestPlatforms.Windows)] // Tests OS-specific environment
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap | TargetFrameworkMonikers.UapAot)] // Don't run on UAP
public unsafe void GetFolderPath_Windows(Environment.SpecialFolder folder)
{
string knownFolder = Environment.GetFolderPath(folder);
Assert.NotEmpty(knownFolder);
// Call the older folder API to compare our results.
char* buffer = stackalloc char[260];
SHGetFolderPathW(IntPtr.Zero, (int)folder, IntPtr.Zero, 0, buffer);
string folderPath = new string(buffer);
Assert.Equal(folderPath, knownFolder);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Uses P/Invokes
public void GetLogicalDrives_Unix_AtLeastOneIsRoot()
{
string[] drives = Environment.GetLogicalDrives();
Assert.NotNull(drives);
Assert.True(drives.Length > 0, "Expected at least one drive");
Assert.All(drives, d => Assert.NotNull(d));
Assert.Contains(drives, d => d == "/");
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes
public void GetLogicalDrives_Windows_MatchesExpectedLetters()
{
string[] drives = Environment.GetLogicalDrives();
uint mask = (uint)GetLogicalDrives();
var bits = new BitArray(new[] { (int)mask });
Assert.Equal(bits.Cast<bool>().Count(b => b), drives.Length);
for (int bit = 0, d = 0; bit < bits.Length; bit++)
{
if (bits[bit])
{
Assert.Contains((char)('A' + bit), drives[d++]);
}
}
}
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern int GetLogicalDrives();
[DllImport("shell32.dll", SetLastError = false, BestFitMapping = false, ExactSpelling = true)]
internal static extern unsafe int SHGetFolderPathW(
IntPtr hwndOwner,
int nFolder,
IntPtr hToken,
uint dwFlags,
char* pszPath);
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true)]
internal static extern FileAttributes GetFileAttributesW(string lpFileName);
public static IEnumerable<object[]> EnvironmentVariableTargets
{
get
{
yield return new object[] { EnvironmentVariableTarget.Process };
yield return new object[] { EnvironmentVariableTarget.User };
yield return new object[] { EnvironmentVariableTarget.Machine };
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsAzureBodyDuration
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// DurationOperations operations.
/// </summary>
internal partial class DurationOperations : IServiceOperations<AutoRestDurationTestService>, IDurationOperations
{
/// <summary>
/// Initializes a new instance of the DurationOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal DurationOperations(AutoRestDurationTestService client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestDurationTestService
/// </summary>
public AutoRestDurationTestService Client { get; private set; }
/// <summary>
/// Get null duration value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<TimeSpan?>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetNull", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/null").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<TimeSpan?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<TimeSpan?>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put a positive duration value
/// </summary>
/// <param name='durationBody'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PutPositiveDurationWithHttpMessagesAsync(TimeSpan durationBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("durationBody", durationBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutPositiveDuration", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/positiveduration").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(durationBody != null)
{
_requestContent = SafeJsonConvert.SerializeObject(durationBody, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get a positive duration value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<TimeSpan?>> GetPositiveDurationWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetPositiveDuration", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/positiveduration").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<TimeSpan?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<TimeSpan?>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get an invalid duration value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<TimeSpan?>> GetInvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetInvalid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/invalid").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<TimeSpan?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<TimeSpan?>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Management.Automation;
using System.Text;
using Microsoft.Management.Infrastructure;
using Microsoft.PowerShell.Cim;
using Dbg = System.Management.Automation.Diagnostics;
namespace Microsoft.PowerShell.Cmdletization.Cim
{
/// <summary>
/// CimQuery supports building of queries against CIM object model.
/// </summary>
internal class CimQuery : QueryBuilder, ISessionBoundQueryBuilder<CimSession>
{
private readonly StringBuilder _wqlCondition;
private CimInstance _associatedObject;
private string _associationName;
private string _resultRole;
private string _sourceRole;
internal readonly Dictionary<string, object> queryOptions = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
internal ClientSideQuery ClientSideQuery { get; private set; }
internal CimQuery()
{
_wqlCondition = new StringBuilder();
this.ClientSideQuery = new ClientSideQuery();
}
#region WQL processing
private void AddWqlCondition(string condition)
{
_wqlCondition.Append(_wqlCondition.Length != 0 ? " AND " : " WHERE ");
_wqlCondition.Append('(');
_wqlCondition.Append(condition);
_wqlCondition.Append(')');
}
private static string ObjectToWqlLiteral(object o)
{
if (LanguagePrimitives.IsNull(o))
{
return "null"; // based on an example at https://msdn.microsoft.com/library/aa394054(VS.85).aspx
}
o = CimValueConverter.ConvertFromDotNetToCim(o);
PSObject pso = PSObject.AsPSObject(o);
Type type = pso.BaseObject.GetType();
TypeCode typeCode = LanguagePrimitives.GetTypeCode(type);
if (typeCode == TypeCode.String)
{
string s = o.ToString();
s = s.Replace("\\", "\\\\");
s = s.Replace("'", "\\'");
return "'" + s + "'";
}
if (typeCode == TypeCode.Char)
{
return ObjectToWqlLiteral(LanguagePrimitives.ConvertTo(o, typeof(string), CultureInfo.InvariantCulture));
}
if (typeCode == TypeCode.DateTime)
{
var dateTime = (DateTime)LanguagePrimitives.ConvertTo(o, typeof(DateTime), CultureInfo.InvariantCulture);
string result = ClrFacade.ToDmtfDateTime(dateTime);
return "'" + result + "'";
}
if (type == typeof(TimeSpan))
{
// WMIv1 does not support using interval literals in a WQL query
return null;
}
if (LanguagePrimitives.IsNumeric(typeCode))
{
return (string)LanguagePrimitives.ConvertTo(o, typeof(string), CultureInfo.InvariantCulture);
}
if (LanguagePrimitives.IsBooleanType(type))
{
if ((bool)LanguagePrimitives.ConvertTo(o, typeof(bool), CultureInfo.InvariantCulture))
{
return "TRUE"; // based on https://msdn.microsoft.com/library/aa394054(VS.85).aspx
}
return "FALSE"; // based on https://msdn.microsoft.com/library/aa394054(VS.85).aspx
}
throw CimValueConverter.GetInvalidCastException(
null, /* inner exception */
"InvalidCimQueryCast",
o,
CmdletizationResources.CimConversion_WqlQuery);
}
private static string WildcardToWqlLikeOperand(WildcardPattern wildcardPattern, out bool needsClientSideFiltering)
{
string nakedOperand = WildcardPatternToCimQueryParser.Parse(wildcardPattern, out needsClientSideFiltering);
return ObjectToWqlLiteral(nakedOperand);
}
#endregion
private static string GetMatchConditionForEqualityOperator(string propertyName, object propertyValue)
{
string condition;
// comparison of 'char' is case-sensitive in WQL (comparison of 'string' is case-insensitive)
if (propertyValue is char)
{
char c = (char)propertyValue;
char lowerCase = char.ToLowerInvariant(c);
char upperCase = char.ToUpperInvariant(c);
string lowerCaseLiteral = CimQuery.ObjectToWqlLiteral(lowerCase);
string upperCaseLiteral = CimQuery.ObjectToWqlLiteral(upperCase);
Dbg.Assert(!string.IsNullOrWhiteSpace(lowerCaseLiteral), "All characters are assumed to have valid WQL literals (lower)");
Dbg.Assert(!string.IsNullOrWhiteSpace(upperCaseLiteral), "All characters are assumed to have valid WQL literals (upper)");
condition = string.Format(
CultureInfo.InvariantCulture,
"(({0} = {1}) OR ({0} = {2}))",
propertyName,
lowerCaseLiteral,
upperCaseLiteral);
return condition;
}
string wqlLiteral = CimQuery.ObjectToWqlLiteral(propertyValue);
if (string.IsNullOrWhiteSpace(wqlLiteral))
{
return null;
}
condition = string.Format(
CultureInfo.InvariantCulture,
"({0} = {1})",
propertyName,
wqlLiteral);
return condition;
}
private static string GetMatchConditionForLikeOperator(string propertyName, object propertyValue)
{
var expectedPropertyValueAsString = (string)LanguagePrimitives.ConvertTo(propertyValue, typeof(string), CultureInfo.InvariantCulture);
var expectedPropertyValueAsPowerShellWildcard = WildcardPattern.Get(expectedPropertyValueAsString, WildcardOptions.IgnoreCase);
bool needsClientSideFiltering; // not used because for simplicity all results go through post-filtering
var expectedPropertyValueAsWqlWildcard = CimQuery.WildcardToWqlLikeOperand(expectedPropertyValueAsPowerShellWildcard, out needsClientSideFiltering);
string condition = string.Format(
CultureInfo.InvariantCulture,
"({0} LIKE {1})",
propertyName,
expectedPropertyValueAsWqlWildcard);
return condition;
}
private static string GetMatchCondition(string propertyName, IEnumerable propertyValues, bool wildcardsEnabled)
{
List<string> individualConditions = propertyValues
.Cast<object>()
.Select(propertyValue => wildcardsEnabled
? GetMatchConditionForLikeOperator(propertyName, propertyValue)
: GetMatchConditionForEqualityOperator(propertyName, propertyValue))
.Where(individualCondition => !string.IsNullOrWhiteSpace(individualCondition))
.ToList();
if (individualConditions.Count == 0)
{
return null;
}
string result = string.Join(" OR ", individualConditions);
return result;
}
#region Public inputs from cmdletization
/// <summary>
/// Modifies the query, so that it only returns objects with a given property value.
/// </summary>
/// <param name="propertyName">Property name to query on.</param>
/// <param name="allowedPropertyValues">Property values to accept in the query.</param>
/// <param name="wildcardsEnabled">
/// <c>true</c> if <paramref name="allowedPropertyValues"/> should be treated as a <see cref="System.String"/> containing a wildcard pattern;
/// <c>false otherwise</c>
/// </param>
/// <param name="behaviorOnNoMatch">
/// Describes how to handle filters that didn't match any objects
/// </param>
public override void FilterByProperty(string propertyName, IEnumerable allowedPropertyValues, bool wildcardsEnabled, BehaviorOnNoMatch behaviorOnNoMatch)
{
this.ClientSideQuery.FilterByProperty(propertyName, allowedPropertyValues, wildcardsEnabled, behaviorOnNoMatch);
string matchCondition = CimQuery.GetMatchCondition(propertyName, allowedPropertyValues, wildcardsEnabled);
if (!string.IsNullOrWhiteSpace(matchCondition))
{
this.AddWqlCondition(matchCondition);
}
}
/// <summary>
/// Modifies the query, so that it does not return objects with a given property value.
/// </summary>
/// <param name="propertyName">Property name to query on.</param>
/// <param name="excludedPropertyValues">Property values to reject in the query.</param>
/// <param name="wildcardsEnabled">
/// <c>true</c> if <paramref name="excludedPropertyValues"/> should be treated as a <see cref="System.String"/> containing a wildcard pattern;
/// <c>false otherwise</c>
/// </param>
/// <param name="behaviorOnNoMatch">
/// Describes how to handle filters that didn't match any objects
/// </param>
public override void ExcludeByProperty(string propertyName, IEnumerable excludedPropertyValues, bool wildcardsEnabled, BehaviorOnNoMatch behaviorOnNoMatch)
{
this.ClientSideQuery.ExcludeByProperty(propertyName, excludedPropertyValues, wildcardsEnabled, behaviorOnNoMatch);
string positiveWqlCondition = CimQuery.GetMatchCondition(propertyName, excludedPropertyValues, wildcardsEnabled);
if (!string.IsNullOrWhiteSpace(positiveWqlCondition))
{
string condition = string.Format(
CultureInfo.InvariantCulture,
"NOT ({0})",
positiveWqlCondition);
this.AddWqlCondition(condition);
}
}
/// <summary>
/// Modifies the query, so that it returns only objects that have a property value greater than or equal to a <paramref name="minPropertyValue"/> threshold.
/// </summary>
/// <param name="propertyName">Property name to query on.</param>
/// <param name="minPropertyValue">Minimum property value.</param>
/// <param name="behaviorOnNoMatch">
/// Describes how to handle filters that didn't match any objects
/// </param>
public override void FilterByMinPropertyValue(string propertyName, object minPropertyValue, BehaviorOnNoMatch behaviorOnNoMatch)
{
this.ClientSideQuery.FilterByMinPropertyValue(propertyName, minPropertyValue, behaviorOnNoMatch);
string wqlLiteral = CimQuery.ObjectToWqlLiteral(minPropertyValue);
if (!string.IsNullOrWhiteSpace(wqlLiteral))
{
string condition = string.Format(
CultureInfo.InvariantCulture,
"{0} >= {1}",
propertyName,
wqlLiteral);
this.AddWqlCondition(condition);
}
}
/// <summary>
/// Modifies the query, so that it returns only objects that have a property value less than or equal to a <paramref name="maxPropertyValue"/> threshold.
/// </summary>
/// <param name="propertyName">Property name to query on.</param>
/// <param name="maxPropertyValue">Maximum property value.</param>
/// <param name="behaviorOnNoMatch">
/// Describes how to handle filters that didn't match any objects
/// </param>
public override void FilterByMaxPropertyValue(string propertyName, object maxPropertyValue, BehaviorOnNoMatch behaviorOnNoMatch)
{
this.ClientSideQuery.FilterByMaxPropertyValue(propertyName, maxPropertyValue, behaviorOnNoMatch);
string wqlLiteral = CimQuery.ObjectToWqlLiteral(maxPropertyValue);
if (!string.IsNullOrWhiteSpace(wqlLiteral))
{
string condition = string.Format(
CultureInfo.InvariantCulture,
"{0} <= {1}",
propertyName,
CimQuery.ObjectToWqlLiteral(maxPropertyValue));
this.AddWqlCondition(condition);
}
}
/// <summary>
/// Modifies the query, so that it returns only objects associated with <paramref name="associatedInstance"/>
/// </summary>
/// <param name="associatedInstance">Object that query results have to be associated with.</param>
/// <param name="associationName">Name of the association.</param>
/// <param name="resultRole">Name of the role that <paramref name="associatedInstance"/> has in the association.</param>
/// <param name="sourceRole">Name of the role that query results have in the association.</param>
/// <param name="behaviorOnNoMatch">
/// Describes how to handle filters that didn't match any objects
/// </param>
public override void FilterByAssociatedInstance(object associatedInstance, string associationName, string sourceRole, string resultRole, BehaviorOnNoMatch behaviorOnNoMatch)
{
this.ClientSideQuery.FilterByAssociatedInstance(associatedInstance, associationName, sourceRole, resultRole, behaviorOnNoMatch);
_associatedObject = associatedInstance as CimInstance;
_associationName = associationName;
_resultRole = resultRole;
_sourceRole = sourceRole;
}
/// <summary>
/// Sets a query option.
/// </summary>
/// <param name="optionName"></param>
/// <param name="optionValue"></param>
public override void AddQueryOption(string optionName, object optionValue)
{
if (string.IsNullOrEmpty(optionName))
{
throw new ArgumentNullException("optionName");
}
if (optionValue == null)
{
throw new ArgumentNullException("optionValue");
}
this.queryOptions[optionName] = optionValue;
}
#endregion Cmdletization inputs
#region Outputs for doing the query
internal StartableJob GetQueryJob(CimJobContext jobContext)
{
if (_associationName == null)
{
return new QueryInstancesJob(jobContext, this, _wqlCondition.ToString());
}
else
{
return new EnumerateAssociatedInstancesJob(jobContext, this, _associatedObject, _associationName, _resultRole, _sourceRole);
}
}
internal bool IsMatchingResult(CimInstance result)
{
Dbg.Assert(result != null, "Caller should verify result != null");
return this.ClientSideQuery.IsResultMatchingClientSideQuery(result);
}
internal IEnumerable<ClientSideQuery.NotFoundError> GenerateNotFoundErrors()
{
return this.ClientSideQuery.GenerateNotFoundErrors();
}
#endregion
CimSession ISessionBoundQueryBuilder<CimSession>.GetTargetSession()
{
if (_associatedObject != null)
{
return CimCmdletAdapter.GetSessionOfOriginFromCimInstance(_associatedObject);
}
return null;
}
/// <summary>
/// Returns a string that represents the current CIM query.
/// </summary>
/// <returns>A string that represents the current CIM query.</returns>
public override string ToString()
{
return _wqlCondition.ToString();
}
}
}
| |
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Game.Graphics.Sprites;
namespace osu.Game.Graphics
{
public class TextAwesome : OsuSpriteText
{
//public override FontFace FontFace => (int)Icon < 0xf000 ? FontFace.OsuFont : FontFace.FontAwesome;
private FontAwesome icon;
public FontAwesome Icon
{
get
{
return icon;
}
set
{
if (icon == value) return;
icon = value;
Text = ((char)icon).ToString();
}
}
}
public enum FontAwesome
{
fa_500px = 0xf26e,
fa_address_book = 0xf2b9,
fa_address_book_o = 0xf2ba,
fa_address_card = 0xf2bb,
fa_address_card_o = 0xf2bc,
fa_adjust = 0xf042,
fa_adn = 0xf170,
fa_align_center = 0xf037,
fa_align_justify = 0xf039,
fa_align_left = 0xf036,
fa_align_right = 0xf038,
fa_amazon = 0xf270,
fa_ambulance = 0xf0f9,
fa_american_sign_language_interpreting = 0xf2a3,
fa_anchor = 0xf13d,
fa_android = 0xf17b,
fa_angellist = 0xf209,
fa_angle_double_down = 0xf103,
fa_angle_double_left = 0xf100,
fa_angle_double_right = 0xf101,
fa_angle_double_up = 0xf102,
fa_angle_down = 0xf107,
fa_angle_left = 0xf104,
fa_angle_right = 0xf105,
fa_angle_up = 0xf106,
fa_apple = 0xf179,
fa_archive = 0xf187,
fa_area_chart = 0xf1fe,
fa_arrow_circle_down = 0xf0ab,
fa_arrow_circle_left = 0xf0a8,
fa_arrow_circle_o_down = 0xf01a,
fa_arrow_circle_o_left = 0xf190,
fa_arrow_circle_o_right = 0xf18e,
fa_arrow_circle_o_up = 0xf01b,
fa_arrow_circle_right = 0xf0a9,
fa_arrow_circle_up = 0xf0aa,
fa_arrow_down = 0xf063,
fa_arrow_left = 0xf060,
fa_arrow_right = 0xf061,
fa_arrow_up = 0xf062,
fa_arrows = 0xf047,
fa_arrows_alt = 0xf0b2,
fa_arrows_h = 0xf07e,
fa_arrows_v = 0xf07d,
fa_asl_interpreting = 0xf2a3,
fa_assistive_listening_systems = 0xf2a2,
fa_asterisk = 0xf069,
fa_at = 0xf1fa,
fa_audio_description = 0xf29e,
fa_automobile = 0xf1b9,
fa_backward = 0xf04a,
fa_balance_scale = 0xf24e,
fa_ban = 0xf05e,
fa_bandcamp = 0xf2d5,
fa_bank = 0xf19c,
fa_bar_chart = 0xf080,
fa_bar_chart_o = 0xf080,
fa_barcode = 0xf02a,
fa_bars = 0xf0c9,
fa_bath = 0xf2cd,
fa_bathtub = 0xf2cd,
fa_battery = 0xf240,
fa_battery_0 = 0xf244,
fa_battery_1 = 0xf243,
fa_battery_2 = 0xf242,
fa_battery_3 = 0xf241,
fa_battery_4 = 0xf240,
fa_battery_empty = 0xf244,
fa_battery_full = 0xf240,
fa_battery_half = 0xf242,
fa_battery_quarter = 0xf243,
fa_battery_three_quarters = 0xf241,
fa_bed = 0xf236,
fa_beer = 0xf0fc,
fa_behance = 0xf1b4,
fa_behance_square = 0xf1b5,
fa_bell = 0xf0f3,
fa_bell_o = 0xf0a2,
fa_bell_slash = 0xf1f6,
fa_bell_slash_o = 0xf1f7,
fa_bicycle = 0xf206,
fa_binoculars = 0xf1e5,
fa_birthday_cake = 0xf1fd,
fa_bitbucket = 0xf171,
fa_bitbucket_square = 0xf172,
fa_bitcoin = 0xf15a,
fa_black_tie = 0xf27e,
fa_blind = 0xf29d,
fa_bluetooth = 0xf293,
fa_bluetooth_b = 0xf294,
fa_bold = 0xf032,
fa_bolt = 0xf0e7,
fa_bomb = 0xf1e2,
fa_book = 0xf02d,
fa_bookmark = 0xf02e,
fa_bookmark_o = 0xf097,
fa_braille = 0xf2a1,
fa_briefcase = 0xf0b1,
fa_btc = 0xf15a,
fa_bug = 0xf188,
fa_building = 0xf1ad,
fa_building_o = 0xf0f7,
fa_bullhorn = 0xf0a1,
fa_bullseye = 0xf140,
fa_bus = 0xf207,
fa_buysellads = 0xf20d,
fa_cab = 0xf1ba,
fa_calculator = 0xf1ec,
fa_calendar = 0xf073,
fa_calendar_check_o = 0xf274,
fa_calendar_minus_o = 0xf272,
fa_calendar_o = 0xf133,
fa_calendar_plus_o = 0xf271,
fa_calendar_times_o = 0xf273,
fa_camera = 0xf030,
fa_camera_retro = 0xf083,
fa_car = 0xf1b9,
fa_caret_down = 0xf0d7,
fa_caret_left = 0xf0d9,
fa_caret_right = 0xf0da,
fa_caret_square_o_down = 0xf150,
fa_caret_square_o_left = 0xf191,
fa_caret_square_o_right = 0xf152,
fa_caret_square_o_up = 0xf151,
fa_caret_up = 0xf0d8,
fa_cart_arrow_down = 0xf218,
fa_cart_plus = 0xf217,
fa_cc = 0xf20a,
fa_cc_amex = 0xf1f3,
fa_cc_diners_club = 0xf24c,
fa_cc_discover = 0xf1f2,
fa_cc_jcb = 0xf24b,
fa_cc_mastercard = 0xf1f1,
fa_cc_paypal = 0xf1f4,
fa_cc_stripe = 0xf1f5,
fa_cc_visa = 0xf1f0,
fa_certificate = 0xf0a3,
fa_chain = 0xf0c1,
fa_chain_broken = 0xf127,
fa_check = 0xf00c,
fa_check_circle = 0xf058,
fa_check_circle_o = 0xf05d,
fa_check_square = 0xf14a,
fa_check_square_o = 0xf046,
fa_chevron_circle_down = 0xf13a,
fa_chevron_circle_left = 0xf137,
fa_chevron_circle_right = 0xf138,
fa_chevron_circle_up = 0xf139,
fa_chevron_down = 0xf078,
fa_chevron_left = 0xf053,
fa_chevron_right = 0xf054,
fa_chevron_up = 0xf077,
fa_child = 0xf1ae,
fa_chrome = 0xf268,
fa_circle = 0xf111,
fa_circle_o = 0xf10c,
fa_circle_o_notch = 0xf1ce,
fa_circle_thin = 0xf1db,
fa_clipboard = 0xf0ea,
fa_clock_o = 0xf017,
fa_clone = 0xf24d,
fa_close = 0xf00d,
fa_cloud = 0xf0c2,
fa_cloud_download = 0xf0ed,
fa_cloud_upload = 0xf0ee,
fa_cny = 0xf157,
fa_code = 0xf121,
fa_code_fork = 0xf126,
fa_codepen = 0xf1cb,
fa_codiepie = 0xf284,
fa_coffee = 0xf0f4,
fa_cog = 0xf013,
fa_cogs = 0xf085,
fa_columns = 0xf0db,
fa_comment = 0xf075,
fa_comment_o = 0xf0e5,
fa_commenting = 0xf27a,
fa_commenting_o = 0xf27b,
fa_comments = 0xf086,
fa_comments_o = 0xf0e6,
fa_compass = 0xf14e,
fa_compress = 0xf066,
fa_connectdevelop = 0xf20e,
fa_contao = 0xf26d,
fa_copy = 0xf0c5,
fa_copyright = 0xf1f9,
fa_creative_commons = 0xf25e,
fa_credit_card = 0xf09d,
fa_credit_card_alt = 0xf283,
fa_crop = 0xf125,
fa_crosshairs = 0xf05b,
fa_css3 = 0xf13c,
fa_cube = 0xf1b2,
fa_cubes = 0xf1b3,
fa_cut = 0xf0c4,
fa_cutlery = 0xf0f5,
fa_dashboard = 0xf0e4,
fa_dashcube = 0xf210,
fa_database = 0xf1c0,
fa_deaf = 0xf2a4,
fa_deafness = 0xf2a4,
fa_dedent = 0xf03b,
fa_delicious = 0xf1a5,
fa_desktop = 0xf108,
fa_deviantart = 0xf1bd,
fa_diamond = 0xf219,
fa_digg = 0xf1a6,
fa_dollar = 0xf155,
fa_dot_circle_o = 0xf192,
fa_download = 0xf019,
fa_dribbble = 0xf17d,
fa_drivers_license = 0xf2c2,
fa_drivers_license_o = 0xf2c3,
fa_dropbox = 0xf16b,
fa_drupal = 0xf1a9,
fa_edge = 0xf282,
fa_edit = 0xf044,
fa_eercast = 0xf2da,
fa_eject = 0xf052,
fa_ellipsis_h = 0xf141,
fa_ellipsis_v = 0xf142,
fa_empire = 0xf1d1,
fa_envelope = 0xf0e0,
fa_envelope_o = 0xf003,
fa_envelope_open = 0xf2b6,
fa_envelope_open_o = 0xf2b7,
fa_envelope_square = 0xf199,
fa_envira = 0xf299,
fa_eraser = 0xf12d,
fa_etsy = 0xf2d7,
fa_eur = 0xf153,
fa_euro = 0xf153,
fa_exchange = 0xf0ec,
fa_exclamation = 0xf12a,
fa_exclamation_circle = 0xf06a,
fa_exclamation_triangle = 0xf071,
fa_expand = 0xf065,
fa_expeditedssl = 0xf23e,
fa_external_link = 0xf08e,
fa_external_link_square = 0xf14c,
fa_eye = 0xf06e,
fa_eye_slash = 0xf070,
fa_eyedropper = 0xf1fb,
fa_fa = 0xf2b4,
fa_facebook = 0xf09a,
fa_facebook_f = 0xf09a,
fa_facebook_official = 0xf230,
fa_facebook_square = 0xf082,
fa_fast_backward = 0xf049,
fa_fast_forward = 0xf050,
fa_fax = 0xf1ac,
fa_feed = 0xf09e,
fa_female = 0xf182,
fa_fighter_jet = 0xf0fb,
fa_file = 0xf15b,
fa_file_archive_o = 0xf1c6,
fa_file_audio_o = 0xf1c7,
fa_file_code_o = 0xf1c9,
fa_file_excel_o = 0xf1c3,
fa_file_image_o = 0xf1c5,
fa_file_movie_o = 0xf1c8,
fa_file_o = 0xf016,
fa_file_pdf_o = 0xf1c1,
fa_file_photo_o = 0xf1c5,
fa_file_picture_o = 0xf1c5,
fa_file_powerpoint_o = 0xf1c4,
fa_file_sound_o = 0xf1c7,
fa_file_text = 0xf15c,
fa_file_text_o = 0xf0f6,
fa_file_video_o = 0xf1c8,
fa_file_word_o = 0xf1c2,
fa_file_zip_o = 0xf1c6,
fa_files_o = 0xf0c5,
fa_film = 0xf008,
fa_filter = 0xf0b0,
fa_fire = 0xf06d,
fa_fire_extinguisher = 0xf134,
fa_firefox = 0xf269,
fa_first_order = 0xf2b0,
fa_flag = 0xf024,
fa_flag_checkered = 0xf11e,
fa_flag_o = 0xf11d,
fa_flash = 0xf0e7,
fa_flask = 0xf0c3,
fa_flickr = 0xf16e,
fa_floppy_o = 0xf0c7,
fa_folder = 0xf07b,
fa_folder_o = 0xf114,
fa_folder_open = 0xf07c,
fa_folder_open_o = 0xf115,
fa_font = 0xf031,
fa_font_awesome = 0xf2b4,
fa_fonticons = 0xf280,
fa_fort_awesome = 0xf286,
fa_forumbee = 0xf211,
fa_forward = 0xf04e,
fa_foursquare = 0xf180,
fa_free_code_camp = 0xf2c5,
fa_frown_o = 0xf119,
fa_futbol_o = 0xf1e3,
fa_gamepad = 0xf11b,
fa_gavel = 0xf0e3,
fa_gbp = 0xf154,
fa_ge = 0xf1d1,
fa_gear = 0xf013,
fa_gears = 0xf085,
fa_genderless = 0xf22d,
fa_get_pocket = 0xf265,
fa_gg = 0xf260,
fa_gg_circle = 0xf261,
fa_gift = 0xf06b,
fa_git = 0xf1d3,
fa_git_square = 0xf1d2,
fa_github = 0xf09b,
fa_github_alt = 0xf113,
fa_github_square = 0xf092,
fa_gitlab = 0xf296,
fa_gittip = 0xf184,
fa_glass = 0xf000,
fa_glide = 0xf2a5,
fa_glide_g = 0xf2a6,
fa_globe = 0xf0ac,
fa_google = 0xf1a0,
fa_google_plus = 0xf0d5,
fa_google_plus_circle = 0xf2b3,
fa_google_plus_official = 0xf2b3,
fa_google_plus_square = 0xf0d4,
fa_google_wallet = 0xf1ee,
fa_graduation_cap = 0xf19d,
fa_gratipay = 0xf184,
fa_grav = 0xf2d6,
fa_group = 0xf0c0,
fa_h_square = 0xf0fd,
fa_hacker_news = 0xf1d4,
fa_hand_grab_o = 0xf255,
fa_hand_lizard_o = 0xf258,
fa_hand_o_down = 0xf0a7,
fa_hand_o_left = 0xf0a5,
fa_hand_o_right = 0xf0a4,
fa_hand_o_up = 0xf0a6,
fa_hand_paper_o = 0xf256,
fa_hand_peace_o = 0xf25b,
fa_hand_pointer_o = 0xf25a,
fa_hand_rock_o = 0xf255,
fa_hand_scissors_o = 0xf257,
fa_hand_spock_o = 0xf259,
fa_hand_stop_o = 0xf256,
fa_handshake_o = 0xf2b5,
fa_hard_of_hearing = 0xf2a4,
fa_hashtag = 0xf292,
fa_hdd_o = 0xf0a0,
fa_header = 0xf1dc,
fa_headphones = 0xf025,
fa_heart = 0xf004,
fa_heart_o = 0xf08a,
fa_heartbeat = 0xf21e,
fa_history = 0xf1da,
fa_home = 0xf015,
fa_hospital_o = 0xf0f8,
fa_hotel = 0xf236,
fa_hourglass = 0xf254,
fa_hourglass_1 = 0xf251,
fa_hourglass_2 = 0xf252,
fa_hourglass_3 = 0xf253,
fa_hourglass_end = 0xf253,
fa_hourglass_half = 0xf252,
fa_hourglass_o = 0xf250,
fa_hourglass_start = 0xf251,
fa_houzz = 0xf27c,
fa_html5 = 0xf13b,
fa_i_cursor = 0xf246,
fa_id_badge = 0xf2c1,
fa_id_card = 0xf2c2,
fa_id_card_o = 0xf2c3,
fa_ils = 0xf20b,
fa_image = 0xf03e,
fa_imdb = 0xf2d8,
fa_inbox = 0xf01c,
fa_indent = 0xf03c,
fa_industry = 0xf275,
fa_info = 0xf129,
fa_info_circle = 0xf05a,
fa_inr = 0xf156,
fa_instagram = 0xf16d,
fa_institution = 0xf19c,
fa_internet_explorer = 0xf26b,
fa_intersex = 0xf224,
fa_ioxhost = 0xf208,
fa_italic = 0xf033,
fa_joomla = 0xf1aa,
fa_jpy = 0xf157,
fa_jsfiddle = 0xf1cc,
fa_key = 0xf084,
fa_keyboard_o = 0xf11c,
fa_krw = 0xf159,
fa_language = 0xf1ab,
fa_laptop = 0xf109,
fa_lastfm = 0xf202,
fa_lastfm_square = 0xf203,
fa_leaf = 0xf06c,
fa_leanpub = 0xf212,
fa_legal = 0xf0e3,
fa_lemon_o = 0xf094,
fa_level_down = 0xf149,
fa_level_up = 0xf148,
fa_life_bouy = 0xf1cd,
fa_life_buoy = 0xf1cd,
fa_life_ring = 0xf1cd,
fa_life_saver = 0xf1cd,
fa_lightbulb_o = 0xf0eb,
fa_line_chart = 0xf201,
fa_link = 0xf0c1,
fa_linkedin = 0xf0e1,
fa_linkedin_square = 0xf08c,
fa_linode = 0xf2b8,
fa_linux = 0xf17c,
fa_list = 0xf03a,
fa_list_alt = 0xf022,
fa_list_ol = 0xf0cb,
fa_list_ul = 0xf0ca,
fa_location_arrow = 0xf124,
fa_lock = 0xf023,
fa_long_arrow_down = 0xf175,
fa_long_arrow_left = 0xf177,
fa_long_arrow_right = 0xf178,
fa_long_arrow_up = 0xf176,
fa_low_vision = 0xf2a8,
fa_magic = 0xf0d0,
fa_magnet = 0xf076,
fa_mail_forward = 0xf064,
fa_mail_reply = 0xf112,
fa_mail_reply_all = 0xf122,
fa_male = 0xf183,
fa_map = 0xf279,
fa_map_marker = 0xf041,
fa_map_o = 0xf278,
fa_map_pin = 0xf276,
fa_map_signs = 0xf277,
fa_mars = 0xf222,
fa_mars_double = 0xf227,
fa_mars_stroke = 0xf229,
fa_mars_stroke_h = 0xf22b,
fa_mars_stroke_v = 0xf22a,
fa_maxcdn = 0xf136,
fa_meanpath = 0xf20c,
fa_medium = 0xf23a,
fa_medkit = 0xf0fa,
fa_meetup = 0xf2e0,
fa_meh_o = 0xf11a,
fa_mercury = 0xf223,
fa_microchip = 0xf2db,
fa_microphone = 0xf130,
fa_microphone_slash = 0xf131,
fa_minus = 0xf068,
fa_minus_circle = 0xf056,
fa_minus_square = 0xf146,
fa_minus_square_o = 0xf147,
fa_mixcloud = 0xf289,
fa_mobile = 0xf10b,
fa_mobile_phone = 0xf10b,
fa_modx = 0xf285,
fa_money = 0xf0d6,
fa_moon_o = 0xf186,
fa_mortar_board = 0xf19d,
fa_motorcycle = 0xf21c,
fa_mouse_pointer = 0xf245,
fa_music = 0xf001,
fa_navicon = 0xf0c9,
fa_neuter = 0xf22c,
fa_newspaper_o = 0xf1ea,
fa_object_group = 0xf247,
fa_object_ungroup = 0xf248,
fa_odnoklassniki = 0xf263,
fa_odnoklassniki_square = 0xf264,
fa_opencart = 0xf23d,
fa_openid = 0xf19b,
fa_opera = 0xf26a,
fa_optin_monster = 0xf23c,
fa_outdent = 0xf03b,
fa_pagelines = 0xf18c,
fa_paint_brush = 0xf1fc,
fa_paper_plane = 0xf1d8,
fa_paper_plane_o = 0xf1d9,
fa_paperclip = 0xf0c6,
fa_paragraph = 0xf1dd,
fa_paste = 0xf0ea,
fa_pause = 0xf04c,
fa_pause_circle = 0xf28b,
fa_pause_circle_o = 0xf28c,
fa_paw = 0xf1b0,
fa_paypal = 0xf1ed,
fa_pencil = 0xf040,
fa_pencil_square = 0xf14b,
fa_pencil_square_o = 0xf044,
fa_percent = 0xf295,
fa_phone = 0xf095,
fa_phone_square = 0xf098,
fa_photo = 0xf03e,
fa_picture_o = 0xf03e,
fa_pie_chart = 0xf200,
fa_pied_piper = 0xf2ae,
fa_pied_piper_alt = 0xf1a8,
fa_pied_piper_pp = 0xf1a7,
fa_pinterest = 0xf0d2,
fa_pinterest_p = 0xf231,
fa_pinterest_square = 0xf0d3,
fa_plane = 0xf072,
fa_play = 0xf04b,
fa_play_circle = 0xf144,
fa_play_circle_o = 0xf01d,
fa_plug = 0xf1e6,
fa_plus = 0xf067,
fa_plus_circle = 0xf055,
fa_plus_square = 0xf0fe,
fa_plus_square_o = 0xf196,
fa_podcast = 0xf2ce,
fa_power_off = 0xf011,
fa_print = 0xf02f,
fa_product_hunt = 0xf288,
fa_puzzle_piece = 0xf12e,
fa_qq = 0xf1d6,
fa_qrcode = 0xf029,
fa_question = 0xf128,
fa_question_circle = 0xf059,
fa_question_circle_o = 0xf29c,
fa_quora = 0xf2c4,
fa_quote_left = 0xf10d,
fa_quote_right = 0xf10e,
fa_ra = 0xf1d0,
fa_random = 0xf074,
fa_ravelry = 0xf2d9,
fa_rebel = 0xf1d0,
fa_recycle = 0xf1b8,
fa_reddit = 0xf1a1,
fa_reddit_alien = 0xf281,
fa_reddit_square = 0xf1a2,
fa_refresh = 0xf021,
fa_registered = 0xf25d,
fa_remove = 0xf00d,
fa_renren = 0xf18b,
fa_reorder = 0xf0c9,
fa_repeat = 0xf01e,
fa_reply = 0xf112,
fa_reply_all = 0xf122,
fa_resistance = 0xf1d0,
fa_retweet = 0xf079,
fa_rmb = 0xf157,
fa_road = 0xf018,
fa_rocket = 0xf135,
fa_rotate_left = 0xf0e2,
fa_rotate_right = 0xf01e,
fa_rouble = 0xf158,
fa_rss = 0xf09e,
fa_rss_square = 0xf143,
fa_rub = 0xf158,
fa_ruble = 0xf158,
fa_rupee = 0xf156,
fa_s15 = 0xf2cd,
fa_safari = 0xf267,
fa_save = 0xf0c7,
fa_scissors = 0xf0c4,
fa_scribd = 0xf28a,
fa_search = 0xf002,
fa_search_minus = 0xf010,
fa_search_plus = 0xf00e,
fa_sellsy = 0xf213,
fa_send = 0xf1d8,
fa_send_o = 0xf1d9,
fa_server = 0xf233,
fa_share = 0xf064,
fa_share_alt = 0xf1e0,
fa_share_alt_square = 0xf1e1,
fa_share_square = 0xf14d,
fa_share_square_o = 0xf045,
fa_shekel = 0xf20b,
fa_sheqel = 0xf20b,
fa_shield = 0xf132,
fa_ship = 0xf21a,
fa_shirtsinbulk = 0xf214,
fa_shopping_bag = 0xf290,
fa_shopping_basket = 0xf291,
fa_shopping_cart = 0xf07a,
fa_shower = 0xf2cc,
fa_sign_in = 0xf090,
fa_sign_language = 0xf2a7,
fa_sign_out = 0xf08b,
fa_signal = 0xf012,
fa_signing = 0xf2a7,
fa_simplybuilt = 0xf215,
fa_sitemap = 0xf0e8,
fa_skyatlas = 0xf216,
fa_skype = 0xf17e,
fa_slack = 0xf198,
fa_sliders = 0xf1de,
fa_slideshare = 0xf1e7,
fa_smile_o = 0xf118,
fa_snapchat = 0xf2ab,
fa_snapchat_ghost = 0xf2ac,
fa_snapchat_square = 0xf2ad,
fa_snowflake_o = 0xf2dc,
fa_soccer_ball_o = 0xf1e3,
fa_sort = 0xf0dc,
fa_sort_alpha_asc = 0xf15d,
fa_sort_alpha_desc = 0xf15e,
fa_sort_amount_asc = 0xf160,
fa_sort_amount_desc = 0xf161,
fa_sort_asc = 0xf0de,
fa_sort_desc = 0xf0dd,
fa_sort_down = 0xf0dd,
fa_sort_numeric_asc = 0xf162,
fa_sort_numeric_desc = 0xf163,
fa_sort_up = 0xf0de,
fa_soundcloud = 0xf1be,
fa_space_shuttle = 0xf197,
fa_spinner = 0xf110,
fa_spoon = 0xf1b1,
fa_spotify = 0xf1bc,
fa_square = 0xf0c8,
fa_square_o = 0xf096,
fa_stack_exchange = 0xf18d,
fa_stack_overflow = 0xf16c,
fa_star = 0xf005,
fa_star_half = 0xf089,
fa_star_half_empty = 0xf123,
fa_star_half_full = 0xf123,
fa_star_half_o = 0xf123,
fa_star_o = 0xf006,
fa_steam = 0xf1b6,
fa_steam_square = 0xf1b7,
fa_step_backward = 0xf048,
fa_step_forward = 0xf051,
fa_stethoscope = 0xf0f1,
fa_sticky_note = 0xf249,
fa_sticky_note_o = 0xf24a,
fa_stop = 0xf04d,
fa_stop_circle = 0xf28d,
fa_stop_circle_o = 0xf28e,
fa_street_view = 0xf21d,
fa_strikethrough = 0xf0cc,
fa_stumbleupon = 0xf1a4,
fa_stumbleupon_circle = 0xf1a3,
fa_subscript = 0xf12c,
fa_subway = 0xf239,
fa_suitcase = 0xf0f2,
fa_sun_o = 0xf185,
fa_superpowers = 0xf2dd,
fa_superscript = 0xf12b,
fa_support = 0xf1cd,
fa_table = 0xf0ce,
fa_tablet = 0xf10a,
fa_tachometer = 0xf0e4,
fa_tag = 0xf02b,
fa_tags = 0xf02c,
fa_tasks = 0xf0ae,
fa_taxi = 0xf1ba,
fa_telegram = 0xf2c6,
fa_television = 0xf26c,
fa_tencent_weibo = 0xf1d5,
fa_terminal = 0xf120,
fa_text_height = 0xf034,
fa_text_width = 0xf035,
fa_th = 0xf00a,
fa_th_large = 0xf009,
fa_th_list = 0xf00b,
fa_themeisle = 0xf2b2,
fa_thermometer = 0xf2c7,
fa_thermometer_0 = 0xf2cb,
fa_thermometer_1 = 0xf2ca,
fa_thermometer_2 = 0xf2c9,
fa_thermometer_3 = 0xf2c8,
fa_thermometer_4 = 0xf2c7,
fa_thermometer_empty = 0xf2cb,
fa_thermometer_full = 0xf2c7,
fa_thermometer_half = 0xf2c9,
fa_thermometer_quarter = 0xf2ca,
fa_thermometer_three_quarters = 0xf2c8,
fa_thumb_tack = 0xf08d,
fa_thumbs_down = 0xf165,
fa_thumbs_o_down = 0xf088,
fa_thumbs_o_up = 0xf087,
fa_thumbs_up = 0xf164,
fa_ticket = 0xf145,
fa_times = 0xf00d,
fa_times_circle = 0xf057,
fa_times_circle_o = 0xf05c,
fa_times_rectangle = 0xf2d3,
fa_times_rectangle_o = 0xf2d4,
fa_tint = 0xf043,
fa_toggle_down = 0xf150,
fa_toggle_left = 0xf191,
fa_toggle_off = 0xf204,
fa_toggle_on = 0xf205,
fa_toggle_right = 0xf152,
fa_toggle_up = 0xf151,
fa_trademark = 0xf25c,
fa_train = 0xf238,
fa_transgender = 0xf224,
fa_transgender_alt = 0xf225,
fa_trash = 0xf1f8,
fa_trash_o = 0xf014,
fa_tree = 0xf1bb,
fa_trello = 0xf181,
fa_tripadvisor = 0xf262,
fa_trophy = 0xf091,
fa_truck = 0xf0d1,
fa_try = 0xf195,
fa_tty = 0xf1e4,
fa_tumblr = 0xf173,
fa_tumblr_square = 0xf174,
fa_turkish_lira = 0xf195,
fa_tv = 0xf26c,
fa_twitch = 0xf1e8,
fa_twitter = 0xf099,
fa_twitter_square = 0xf081,
fa_umbrella = 0xf0e9,
fa_underline = 0xf0cd,
fa_undo = 0xf0e2,
fa_universal_access = 0xf29a,
fa_university = 0xf19c,
fa_unlink = 0xf127,
fa_unlock = 0xf09c,
fa_unlock_alt = 0xf13e,
fa_unsorted = 0xf0dc,
fa_upload = 0xf093,
fa_usb = 0xf287,
fa_usd = 0xf155,
fa_user = 0xf007,
fa_user_circle = 0xf2bd,
fa_user_circle_o = 0xf2be,
fa_user_md = 0xf0f0,
fa_user_o = 0xf2c0,
fa_user_plus = 0xf234,
fa_user_secret = 0xf21b,
fa_user_times = 0xf235,
fa_users = 0xf0c0,
fa_vcard = 0xf2bb,
fa_vcard_o = 0xf2bc,
fa_venus = 0xf221,
fa_venus_double = 0xf226,
fa_venus_mars = 0xf228,
fa_viacoin = 0xf237,
fa_viadeo = 0xf2a9,
fa_viadeo_square = 0xf2aa,
fa_video_camera = 0xf03d,
fa_vimeo = 0xf27d,
fa_vimeo_square = 0xf194,
fa_vine = 0xf1ca,
fa_vk = 0xf189,
fa_volume_control_phone = 0xf2a0,
fa_volume_down = 0xf027,
fa_volume_off = 0xf026,
fa_volume_up = 0xf028,
fa_warning = 0xf071,
fa_wechat = 0xf1d7,
fa_weibo = 0xf18a,
fa_weixin = 0xf1d7,
fa_whatsapp = 0xf232,
fa_wheelchair = 0xf193,
fa_wheelchair_alt = 0xf29b,
fa_wifi = 0xf1eb,
fa_wikipedia_w = 0xf266,
fa_window_close = 0xf2d3,
fa_window_close_o = 0xf2d4,
fa_window_maximize = 0xf2d0,
fa_window_minimize = 0xf2d1,
fa_window_restore = 0xf2d2,
fa_windows = 0xf17a,
fa_won = 0xf159,
fa_wordpress = 0xf19a,
fa_wpbeginner = 0xf297,
fa_wpexplorer = 0xf2de,
fa_wpforms = 0xf298,
fa_wrench = 0xf0ad,
fa_xing = 0xf168,
fa_xing_square = 0xf169,
fa_y_combinator = 0xf23b,
fa_y_combinator_square = 0xf1d4,
fa_yahoo = 0xf19e,
fa_yc = 0xf23b,
fa_yc_square = 0xf1d4,
fa_yelp = 0xf1e9,
fa_yen = 0xf157,
fa_yoast = 0xf2b1,
fa_youtube = 0xf167,
fa_youtube_play = 0xf16a,
fa_youtube_square = 0xf166,
// ruleset icons in circles
fa_osu_osu_o = 0xe000,
fa_osu_mania_o = 0xe001,
fa_osu_fruits_o = 0xe002,
fa_osu_taiko_o = 0xe003,
// ruleset icons without circles
fa_osu_filled_circle = 0xe004,
fa_osu_cross_o = 0xe005,
fa_osu_logo = 0xe006,
fa_osu_chevron_down_o = 0xe007,
fa_osu_edit_o = 0xe033,
fa_osu_left_o = 0xe034,
fa_osu_right_o = 0xe035,
fa_osu_charts = 0xe036,
fa_osu_solo = 0xe037,
fa_osu_multi = 0xe038,
fa_osu_gear = 0xe039,
// misc icons
fa_osu_bat = 0xe008,
fa_osu_bubble = 0xe009,
fa_osu_bubble_pop = 0xe02e,
fa_osu_dice = 0xe011,
fa_osu_heart1 = 0xe02f,
fa_osu_heart1_break = 0xe030,
fa_osu_hot = 0xe031,
fa_osu_list_search = 0xe032,
//osu! playstyles
fa_osu_playstyle_tablet = 0xe02a,
fa_osu_playstyle_mouse = 0xe029,
fa_osu_playstyle_keyboard = 0xe02b,
fa_osu_playstyle_touch = 0xe02c,
// osu! difficulties
fa_osu_easy_osu = 0xe015,
fa_osu_normal_osu = 0xe016,
fa_osu_hard_osu = 0xe017,
fa_osu_insane_osu = 0xe018,
fa_osu_expert_osu = 0xe019,
// taiko difficulties
fa_osu_easy_taiko = 0xe01a,
fa_osu_normal_taiko = 0xe01b,
fa_osu_hard_taiko = 0xe01c,
fa_osu_insane_taiko = 0xe01d,
fa_osu_expert_taiko = 0xe01e,
// fruits difficulties
fa_osu_easy_fruits = 0xe01f,
fa_osu_normal_fruits = 0xe020,
fa_osu_hard_fruits = 0xe021,
fa_osu_insane_fruits = 0xe022,
fa_osu_expert_fruits = 0xe023,
// mania difficulties
fa_osu_easy_mania = 0xe024,
fa_osu_normal_mania = 0xe025,
fa_osu_hard_mania = 0xe026,
fa_osu_insane_mania = 0xe027,
fa_osu_expert_mania = 0xe028,
// mod icons
fa_osu_mod_perfect = 0xe02d,
fa_osu_mod_autopilot = 0xe03a,
fa_osu_mod_auto = 0xe03b,
fa_osu_mod_cinema = 0xe03c,
fa_osu_mod_doubletime = 0xe03d,
fa_osu_mod_easy = 0xe03e,
fa_osu_mod_flashlight = 0xe03f,
fa_osu_mod_halftime = 0xe040,
fa_osu_mod_hardrock = 0xe041,
fa_osu_mod_hidden = 0xe042,
fa_osu_mod_nightcore = 0xe043,
fa_osu_mod_nofail = 0xe044,
fa_osu_mod_relax = 0xe045,
fa_osu_mod_spunout = 0xe046,
fa_osu_mod_suddendeath = 0xe047,
fa_osu_mod_target = 0xe048,
fa_osu_mod_bg = 0xe04a,
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public class tk2dSpritePickerPopup : EditorWindow
{
class PresentationParams
{
public int border = 12;
public int tileSep = 8;
public int labelHeight = 15;
public int labelOffset = 4;
public int scrollbarWidth = 16;
public int tileSizeMin = 32;
public int tileSizeMax = 512;
public int numTilesPerRow = 0;
public int tileHeight = 0;
public int tileWidth = 0;
public int numRows = 0;
int tileSizeInt = 128;
public Vector2 rectDims;
public void Update(int numTiles) {
tileSizeInt = TileSize;
int w = Screen.width - scrollbarWidth - border * 2;
numTilesPerRow = Mathf.Max((w + tileSep) / (tileSizeInt + tileSep), 1);
numRows = (numTiles + numTilesPerRow - 1) / numTilesPerRow;
tileWidth = tileSizeInt + tileSep;
tileHeight = tileSizeInt + tileSep + labelOffset + labelHeight;
rectDims = new Vector2(w, numRows * tileHeight + border * 2);
}
public int TileSize
{
get { return tk2dPreferences.inst.spriteThumbnailSize; }
set { tk2dPreferences.inst.spriteThumbnailSize = Mathf.Clamp(value, tileSizeMin, tileSizeMax); }
}
public int GetYForIndex(int index)
{
int tileSep = 8;
int labelHeight = 15;
int tileHeight = tileSizeInt + tileSep + labelOffset + labelHeight;
return tileHeight * (index / numTilesPerRow);
}
}
PresentationParams presentParams = new PresentationParams();
tk2dSpriteGuiUtility.SpriteChangedCallback callback = null;
object callbackData = null;
tk2dSpriteCollectionData spriteCollection = null;
List<tk2dSpriteDefinition> selectedDefinitions = new List<tk2dSpriteDefinition>();
string searchFilter = "";
int selectedIndex = -1;
bool makeSelectionVisible = false;
Vector2 scroll = Vector2.zero;
tk2dSpriteThumbnailCache spriteThumbnailRenderer = null;
tk2dSpriteDefinition SelectedDefinition
{
get {
for (int i = 0; i < selectedDefinitions.Count; ++i)
if (i == selectedIndex) return selectedDefinitions[i];
return null;
}
}
void OnEnable()
{
UpdateFilter();
}
void OnDestroy()
{
if (spriteThumbnailRenderer != null)
{
spriteThumbnailRenderer.Destroy();
spriteThumbnailRenderer = null;
}
tk2dEditorSkin.Done();
tk2dGrid.Done();
}
void PerformSelection()
{
tk2dSpriteDefinition def = SelectedDefinition;
if (def != null)
{
int spriteIndex = -1;
for (int i = 0; i < spriteCollection.inst.spriteDefinitions.Length; ++i)
if (spriteCollection.inst.spriteDefinitions[i] == def)
spriteIndex = i;
if (spriteIndex != -1 && callback != null)
callback( spriteCollection, spriteIndex, callbackData );
}
}
void UpdateFilter()
{
if (spriteCollection == null)
{
selectedDefinitions.Clear();
}
else
{
tk2dSpriteDefinition selectedSprite = SelectedDefinition;
string s = searchFilter.ToLower();
if (s != "") {
selectedDefinitions = (from d in spriteCollection.inst.spriteDefinitions where d.Valid && d.name.ToLower().IndexOf(s) != -1 select d)
.OrderBy( d => d.name, new tk2dEditor.Shared.NaturalComparer() )
.ToList();
}
else {
selectedDefinitions = (from d in spriteCollection.inst.spriteDefinitions where d.Valid select d)
.OrderBy( d => d.name, new tk2dEditor.Shared.NaturalComparer() )
.ToList();
}
selectedIndex = -1;
for (int i = 0; i < selectedDefinitions.Count; ++i)
{
if (selectedSprite == selectedDefinitions[i])
{
selectedIndex = i;
break;
}
}
}
}
void HandleKeyboardShortcuts() {
Event ev = Event.current;
int numTilesPerRow = presentParams.numTilesPerRow;
int newSelectedIndex = selectedIndex;
if (ev.type == EventType.KeyDown)
{
switch (ev.keyCode)
{
case KeyCode.Escape:
if (searchFilter.Length > 0)
{
searchFilter = "";
UpdateFilter();
newSelectedIndex = selectedIndex; // avoid it doing any processing later
}
else
{
Close();
}
ev.Use();
break;
case KeyCode.Return:
{
PerformSelection();
ev.Use();
Close();
break;
}
case KeyCode.RightArrow: newSelectedIndex++;break;
case KeyCode.LeftArrow: newSelectedIndex--; break;
case KeyCode.DownArrow: if (newSelectedIndex + numTilesPerRow < selectedDefinitions.Count) newSelectedIndex += numTilesPerRow; break;
case KeyCode.UpArrow: if (newSelectedIndex - numTilesPerRow >= 0) newSelectedIndex -= numTilesPerRow; break;
case KeyCode.Home: newSelectedIndex = 0; break;
case KeyCode.End: newSelectedIndex = selectedDefinitions.Count - 1; break;
default:
return; // unused key
}
newSelectedIndex = Mathf.Clamp(newSelectedIndex, 0, selectedDefinitions.Count - 1);
if (newSelectedIndex != selectedIndex)
{
selectedIndex = newSelectedIndex;
ev.Use();
makeSelectionVisible = true;
}
}
}
void OnGUI()
{
HandleKeyboardShortcuts();
presentParams.Update(selectedDefinitions.Count);
if (makeSelectionVisible) {
scroll.y = presentParams.GetYForIndex(selectedIndex);
makeSelectionVisible = false;
}
GUILayout.BeginArea(new Rect(0, 0, Screen.width, Screen.height));
GUILayout.BeginHorizontal(EditorStyles.toolbar, GUILayout.ExpandWidth(true));
GUILayout.Label("Collection: ");
tk2dSpriteCollectionData newSpriteCollection = tk2dSpriteGuiUtility.SpriteCollectionList(spriteCollection);
if (newSpriteCollection != spriteCollection)
{
spriteCollection = newSpriteCollection;
searchFilter = "";
UpdateFilter();
}
GUILayout.Space(8);
string searchControlName = "tk2dSpritePickerSearch";
GUI.SetNextControlName(searchControlName);
string newSearchFilter = GUILayout.TextField(searchFilter, tk2dEditorSkin.ToolbarSearch, GUILayout.Width(140));
if (GUIUtility.keyboardControl == 0) {
GUI.FocusControl(searchControlName);
}
if (newSearchFilter != searchFilter)
{
searchFilter = newSearchFilter;
UpdateFilter();
}
if (searchFilter.Length > 0)
{
if (GUILayout.Button("", tk2dEditorSkin.ToolbarSearchClear, GUILayout.ExpandWidth(false)))
{
searchFilter = "";
UpdateFilter();
}
}
else
{
GUILayout.Label("", tk2dEditorSkin.ToolbarSearchRightCap);
}
GUILayout.FlexibleSpace();
presentParams.TileSize = (int)EditorGUILayout.Slider(presentParams.TileSize, presentParams.tileSizeMin, presentParams.tileSizeMax, GUILayout.Width(120));
GUILayout.EndHorizontal();
if (selectedIndex < 0 || selectedIndex >= selectedDefinitions.Count)
{
if (selectedDefinitions.Count == 0) selectedIndex = -1;
else selectedIndex = 0;
}
if (spriteCollection != null)
DrawSpriteCollection(spriteCollection);
GUILayout.EndArea();
}
void DrawSpriteCollection(tk2dSpriteCollectionData spriteCollection)
{
Event ev = Event.current;
int tileSize = presentParams.TileSize;
scroll = GUILayout.BeginScrollView(scroll);
Rect r = GUILayoutUtility.GetRect(presentParams.rectDims.x, presentParams.rectDims.y);
if (ev.type == EventType.MouseDown && ev.button == 0 && r.Contains(ev.mousePosition))
{
int selX = ((int)ev.mousePosition.x - presentParams.border) / presentParams.tileWidth;
int selY = ((int)ev.mousePosition.y - presentParams.border) / presentParams.tileHeight;
int selId = selY * presentParams.numTilesPerRow + selX;
if (selX < presentParams.numTilesPerRow && selY < presentParams.numRows) {
selectedIndex = Mathf.Clamp(selId, 0, selectedDefinitions.Count - 1);
Repaint();
}
if (ev.clickCount == 2)
{
PerformSelection();
Close();
}
ev.Use();
}
r.x += presentParams.border;
r.y += presentParams.border;
if (spriteThumbnailRenderer == null)
spriteThumbnailRenderer = new tk2dSpriteThumbnailCache();
int ix = 0;
float x = r.x;
float y = r.y;
int index = 0;
foreach (tk2dSpriteDefinition def in selectedDefinitions)
{
Rect spriteRect = new Rect(x, y, tileSize, tileSize);
tk2dGrid.Draw(spriteRect, Vector2.zero);
spriteThumbnailRenderer.DrawSpriteTextureInRect(spriteRect, def, Color.white);
Rect labelRect = new Rect(x, y + tileSize + presentParams.labelOffset, tileSize, presentParams.labelHeight);
if (selectedIndex == index)
{
GUI.Label(labelRect, "", tk2dEditorSkin.Selection);
}
GUI.Label(labelRect, def.name, EditorStyles.miniLabel);
if (++ix >= presentParams.numTilesPerRow)
{
ix = 0;
x = r.x;
y += presentParams.tileHeight;
}
else
{
x += presentParams.tileWidth;
}
index++;
}
GUILayout.EndScrollView();
}
void InitForSpriteInCollection(tk2dSpriteCollectionData sc, int spriteId)
{
spriteCollection = sc;
searchFilter = "";
UpdateFilter();
tk2dSpriteDefinition def = (spriteId >= 0 && spriteId < sc.Count) ? sc.inst.spriteDefinitions[spriteId] : null;
selectedIndex = -1;
for (int i = 0; i < selectedDefinitions.Count; ++i) {
if (selectedDefinitions[i] == def) {
selectedIndex = i;
break;
}
}
if (selectedIndex != -1) {
makeSelectionVisible = true;
}
}
public static void DoPickSprite(tk2dSpriteCollectionData spriteCollection, int spriteId, string title, tk2dSpriteGuiUtility.SpriteChangedCallback callback, object callbackData)
{
tk2dSpritePickerPopup popup = EditorWindow.GetWindow(typeof(tk2dSpritePickerPopup), true, title, true) as tk2dSpritePickerPopup;
popup.InitForSpriteInCollection(spriteCollection, spriteId);
popup.callback = callback;
popup.callbackData = callbackData;
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Surface;
using Microsoft.Surface.Core;
using XenGameBase;
using Xen2D;
namespace GarageDemo
{
public class SurfaceGameBase : GameBase
{
public static ContactTarget ContactTarget;
protected UserOrientation currentOrientation = UserOrientation.Bottom;
protected bool applicationLoadCompleteSignalled;
protected Matrix screenTransform = Matrix.Identity;
// application state: Activated, Previewed, Deactivated,
// start in Activated state
protected bool isApplicationActivated = true;
protected bool isApplicationPreviewed;
public SurfaceGameBase()
{
BackgroundColor = new Color( 81, 81, 81 );
}
/// <summary>
/// Allows the app to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
InitializeSurfaceInput();
// Set the application's orientation based on the current launcher orientation
currentOrientation = ApplicationLauncher.Orientation;
// Subscribe to surface application activation events
ApplicationLauncher.ApplicationActivated += OnApplicationActivated;
ApplicationLauncher.ApplicationPreviewed += OnApplicationPreviewed;
ApplicationLauncher.ApplicationDeactivated += OnApplicationDeactivated;
// Setup the UI to transform if the UI is rotated.
if( currentOrientation == UserOrientation.Top )
{
// Create a rotation matrix to orient the screen so it is viewed correctly when the user orientation is 180 degress different.
Matrix rotation = Matrix.CreateRotationZ( MathHelper.ToRadians( 180 ) );
Matrix translation = Matrix.CreateTranslation( GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, 0 );
screenTransform = rotation * translation;
}
base.Initialize();
SetWindowOnSurface();
}
/// <summary>
/// Moves and sizes the window to cover the input surface.
/// </summary>
private void SetWindowOnSurface()
{
System.Diagnostics.Debug.Assert( Window.Handle != System.IntPtr.Zero,
"Window initialization must be complete before SetWindowOnSurface is called" );
if( Window.Handle == System.IntPtr.Zero )
return;
// We don't want to run in full-screen mode because we need
// overlapped windows, so instead run in windowed mode
// and resize to take up the whole surface with no border.
// Make sure the graphics device has the correct back buffer size.
InteractiveSurface interactiveSurface = InteractiveSurface.DefaultInteractiveSurface;
if( interactiveSurface != null )
{
Globals.Graphics.PreferredBackBufferWidth = interactiveSurface.Width;
Globals.Graphics.PreferredBackBufferHeight = interactiveSurface.Height;
Globals.Graphics.ApplyChanges();
// Remove the border and position the window.
Program.RemoveBorder( Window.Handle );
Program.PositionWindow( Window );
}
}
/// <summary>
/// Initializes the surface input system. This should be called after any window
/// initialization is done, and should only be called once.
/// </summary>
private void InitializeSurfaceInput()
{
System.Diagnostics.Debug.Assert( Window.Handle != System.IntPtr.Zero,
"Window initialization must be complete before InitializeSurfaceInput is called" );
if( Window.Handle == System.IntPtr.Zero )
return;
System.Diagnostics.Debug.Assert( ContactTarget == null,
"Surface input already initialized" );
if( ContactTarget != null )
return;
// Create a target for surface input.
ContactTarget = new ContactTarget( Window.Handle, EventThreadChoice.OnBackgroundThread );
ContactTarget.EnableInput();
}
/// <summary>
/// This is called when the app should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw( GameTime gameTime )
{
if( !applicationLoadCompleteSignalled )
{
// Dismiss the loading screen now that we are starting to draw
ApplicationLauncher.SignalApplicationLoadComplete();
applicationLoadCompleteSignalled = true;
}
//TODO: Rotate the UI based on the value of screenTransform here if desired
//TODO: Add your drawing code here
//TODO: Avoid any expensive logic if application is neither active nor previewed
base.Draw( gameTime );
}
/// <summary>
/// This is called when application has been activated.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected virtual void OnApplicationActivated( object sender, EventArgs e )
{
// update application state
isApplicationActivated = true;
isApplicationPreviewed = false;
//TODO: Enable audio, animations here
//TODO: Optionally enable raw image here
}
/// <summary>
/// This is called when application is in preview mode.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected virtual void OnApplicationPreviewed( object sender, EventArgs e )
{
// update application state
isApplicationActivated = false;
isApplicationPreviewed = true;
//TODO: Disable audio here if it is enabled
//TODO: Optionally enable animations here
}
/// <summary>
/// This is called when application has been deactivated.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected virtual void OnApplicationDeactivated( object sender, EventArgs e )
{
// update application state
isApplicationActivated = false;
isApplicationPreviewed = false;
//TODO: Disable audio, animations here
//TODO: Disable raw image if it's enabled
}
#region IDisposable
protected override void Dispose( bool disposing )
{
try
{
if( disposing )
{
IDisposable graphicsDispose = Globals.Graphics as IDisposable;
if( graphicsDispose != null )
{
graphicsDispose.Dispose();
graphicsDispose = null;
}
if( ContactTarget != null )
{
ContactTarget.Dispose();
ContactTarget = null;
}
}
}
finally
{
base.Dispose( disposing );
}
}
#endregion
}
}
| |
// Copyright 2007-2015 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// 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 MassTransit.Tests.Saga
{
using System;
using System.Threading.Tasks;
using GreenPipes;
using GreenPipes.Introspection;
using MassTransit.Saga;
using MassTransit.Testing;
using Messages;
using NUnit.Framework;
using Shouldly;
using TestFramework;
[TestFixture]
public class When_an_initiating_message_for_a_saga_arrives :
InMemoryTestFixture
{
[Test, Explicit]
public void Should_return_a_wonderful_breakdown_of_the_guts_inside_it()
{
ProbeResult result = Bus.GetProbeResult();
Console.WriteLine(result.ToJsonString());
}
[Test]
public async Task The_saga_should_be_created_when_an_initiating_message_is_received()
{
var message = new InitiateSimpleSaga(_sagaId);
await InputQueueSendEndpoint.Send(message);
Guid? sagaId = await _repository.ShouldContainSaga(_sagaId, TestTimeout);
sagaId.HasValue.ShouldBe(true);
}
public When_an_initiating_message_for_a_saga_arrives()
{
_repository = new InMemorySagaRepository<SimpleSaga>();
}
[OneTimeSetUp]
public void Setup()
{
_sagaId = Guid.NewGuid();
}
protected override void ConfigureInMemoryBus(IInMemoryBusFactoryConfigurator configurator)
{
base.ConfigureInMemoryBus(configurator);
configurator.UseRetry(x => x.None());
}
protected override void ConfigureInMemoryReceiveEndpoint(IInMemoryReceiveEndpointConfigurator configurator)
{
configurator.UseRetry(x => x.Immediate(2));
configurator.Saga(_repository);
}
Guid _sagaId;
InMemorySagaRepository<SimpleSaga> _repository;
}
[TestFixture]
public class When_an_initiating_message_for_an_existing_saga_arrives :
InMemoryTestFixture
{
[Test]
public async Task The_message_should_fault()
{
Task<ConsumeContext<Fault<InitiateSimpleSaga>>> faulted = ConnectPublishHandler<Fault<InitiateSimpleSaga>>();
var message = new InitiateSimpleSaga(_sagaId);
await InputQueueSendEndpoint.Send(message);
Guid? sagaId = await _repository.ShouldContainSaga(_sagaId, TestTimeout);
sagaId.HasValue.ShouldBe(true);
await InputQueueSendEndpoint.Send(message);
await faulted;
}
public When_an_initiating_message_for_an_existing_saga_arrives()
{
_repository = new InMemorySagaRepository<SimpleSaga>();
}
[OneTimeSetUp]
public void Setup()
{
_sagaId = Guid.NewGuid();
}
protected override void ConfigureInMemoryReceiveEndpoint(IInMemoryReceiveEndpointConfigurator configurator)
{
configurator.Saga(_repository);
}
Guid _sagaId;
InMemorySagaRepository<SimpleSaga> _repository;
}
[TestFixture]
public class When_an_initiating_and_orchestrated_message_for_a_saga_arrives :
InMemoryTestFixture
{
[Test]
public async Task The_saga_should_be_loaded()
{
await InputQueueSendEndpoint.Send(new InitiateSimpleSaga(_sagaId));
Guid? sagaId = await _repository.ShouldContainSaga(x => x.Initiated, TestTimeout);
await InputQueueSendEndpoint.Send(new CompleteSimpleSaga(_sagaId));
sagaId = await _repository.ShouldContainSaga(x => x.Completed, TestTimeout);
sagaId.HasValue.ShouldBe(true);
}
public When_an_initiating_and_orchestrated_message_for_a_saga_arrives()
{
_repository = new InMemorySagaRepository<SimpleSaga>();
}
[OneTimeSetUp]
public void Setup()
{
_sagaId = Guid.NewGuid();
}
protected override void ConfigureInMemoryReceiveEndpoint(IInMemoryReceiveEndpointConfigurator configurator)
{
configurator.Saga(_repository);
}
Guid _sagaId;
InMemorySagaRepository<SimpleSaga> _repository;
}
[TestFixture]
public class When_an_initiating_and_observed_message_for_a_saga_arrives :
InMemoryTestFixture
{
[Test]
public async Task The_saga_should_be_loaded()
{
await InputQueueSendEndpoint.Send(new InitiateSimpleSaga(_sagaId) {Name = "Chris"});
Guid? sagaId = await _repository.ShouldContainSaga(x => x.Initiated, TestTimeout);
await InputQueueSendEndpoint.Send(new ObservableSagaMessage {Name = "Chris"});
sagaId = await _repository.ShouldContainSaga(x => x.Observed, TestTimeout);
sagaId.HasValue.ShouldBe(true);
}
public When_an_initiating_and_observed_message_for_a_saga_arrives()
{
_repository = new InMemorySagaRepository<SimpleSaga>();
}
[OneTimeSetUp]
public void Setup()
{
_sagaId = Guid.NewGuid();
}
protected override void ConfigureInMemoryReceiveEndpoint(IInMemoryReceiveEndpointConfigurator configurator)
{
configurator.Saga(_repository);
}
Guid _sagaId;
InMemorySagaRepository<SimpleSaga> _repository;
}
[TestFixture]
public class When_an_existing_saga_receives_an_initiating_message :
InMemoryTestFixture
{
[Test]
public async Task An_exception_should_be_thrown()
{
var message = new InitiateSimpleSaga(_sagaId);
await BusSendEndpoint.Send(message);
try
{
await BusSendEndpoint.Send(message);
}
catch (SagaException sex)
{
Assert.AreEqual(sex.MessageType, typeof(InitiateSimpleSaga));
}
}
[OneTimeSetUp]
public void SetUp()
{
_sagaId = Guid.NewGuid();
_repository = new InMemorySagaRepository<SimpleSaga>();
Bus.ConnectSaga(_repository);
}
Guid _sagaId;
InMemorySagaRepository<SimpleSaga> _repository;
}
}
| |
/* ====================================================================
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.
==================================================================== */
namespace NPOI.SS.Formula.Function
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using NPOI.SS.Formula.PTG;
using System.Globalization;
using System.Text;
/**
* Converts the text meta-data file into a <c>FunctionMetadataRegistry</c>
*
* @author Josh Micich
*/
class FunctionMetadataReader
{
#if NETSTANDARD2_0
private const String METADATA_FILE_NAME = "NPOI.Resources.functionMetadata.txt";
#else
private const String METADATA_FILE_NAME = "functionMetadata.txt";
#endif
/** plain ASCII text metadata file uses three dots for ellipsis */
private const string ELLIPSIS = "...";
private const string TAB_DELIM_PATTERN = @"\t";
private const string SPACE_DELIM_PATTERN = @"\s";
private static readonly byte[] EMPTY_BYTE_ARRAY = { };
private static readonly string[] DIGIT_ENDING_FUNCTION_NAMES = {
// Digits at the end of a function might be due to a left-over footnote marker.
// except in these cases
"LOG10", "ATAN2", "DAYS360", "SUMXMY2", "SUMX2MY2", "SUMX2PY2",
};
private static List<string> DIGIT_ENDING_FUNCTION_NAMES_Set = new List<string> (DIGIT_ENDING_FUNCTION_NAMES);
public static FunctionMetadataRegistry CreateRegistry()
{
using (StreamReader br = new StreamReader (typeof (FunctionMetadataReader).Assembly.GetManifestResourceStream (METADATA_FILE_NAME)))
{
FunctionDataBuilder fdb = new FunctionDataBuilder(400);
try
{
while (true)
{
String line = br.ReadLine();
if (line == null)
{
break;
}
if (line.Length < 1 || line[0] == '#')
{
continue;
}
String TrimLine = line.Trim();
if (TrimLine.Length < 1)
{
continue;
}
ProcessLine(fdb, line);
}
}
catch (IOException)
{
throw;
}
return fdb.Build();
}
}
private static void ProcessLine(FunctionDataBuilder fdb, String line)
{
Regex regex = new Regex(TAB_DELIM_PATTERN);
String[] parts = regex.Split(line);
if (parts.Length != 8)
{
throw new Exception("Bad line format '" + line + "' - expected 8 data fields");
}
int functionIndex = ParseInt(parts[0]);
String functionName = parts[1];
int minParams = ParseInt(parts[2]);
int maxParams = ParseInt(parts[3]);
byte returnClassCode = ParseReturnTypeCode(parts[4]);
byte[] parameterClassCodes = ParseOperandTypeCodes(parts[5]);
// 6 IsVolatile
bool hasNote = parts[7].Length > 0;
ValidateFunctionName(functionName);
// TODO - make POI use IsVolatile
fdb.Add(functionIndex, functionName, minParams, maxParams,
returnClassCode, parameterClassCodes, hasNote);
}
private static byte ParseReturnTypeCode(String code)
{
if (code.Length == 0)
{
return Ptg.CLASS_REF; // happens for GetPIVOTDATA
}
return ParseOperandTypeCode(code);
}
private static byte[] ParseOperandTypeCodes(String codes)
{
if (codes.Length < 1)
{
return EMPTY_BYTE_ARRAY; // happens for GetPIVOTDATA
}
if (IsDash(codes))
{
// '-' means empty:
return EMPTY_BYTE_ARRAY;
}
Regex regex = new Regex(SPACE_DELIM_PATTERN);
String[] array = regex.Split(codes);
int nItems = array.Length;
if (ELLIPSIS.Equals(array[nItems - 1]))
{
// ellipsis is optional, and ignored
// (all Unspecified params are assumed to be the same as the last)
nItems--;
}
byte[] result = new byte[nItems];
for (int i = 0; i < nItems; i++)
{
result[i] = ParseOperandTypeCode(array[i]);
}
return result;
}
private static bool IsDash(String codes)
{
if (codes.Length == 1)
{
switch (codes[0])
{
case '-':
return true;
}
}
return false;
}
private static byte ParseOperandTypeCode(String code)
{
if (code.Length != 1)
{
throw new Exception("Bad operand type code format '" + code + "' expected single char");
}
switch (code[0])
{
case 'V': return Ptg.CLASS_VALUE;
case 'R': return Ptg.CLASS_REF;
case 'A': return Ptg.CLASS_ARRAY;
}
throw new ArgumentException("Unexpected operand type code '" + code + "' (" + (int)code[0] + ")");
}
/**
* Makes sure that footnote digits from the original OOO document have not been accidentally
* left behind
*/
private static void ValidateFunctionName(String functionName)
{
int len = functionName.Length;
int ix = len - 1;
if (!Char.IsDigit(functionName[ix]))
{
return;
}
while (ix >= 0)
{
if (!Char.IsDigit(functionName[ix]))
{
break;
}
ix--;
}
if (DIGIT_ENDING_FUNCTION_NAMES_Set.Contains(functionName))
{
return;
}
throw new Exception("Invalid function name '" + functionName
+ "' (is footnote number incorrectly Appended)");
}
private static int ParseInt(String valStr)
{
return int.Parse(valStr, CultureInfo.InvariantCulture);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Commencement.Core.Domain;
using Commencement.Tests.Core;
using Commencement.Tests.Core.Extensions;
using Commencement.Tests.Core.Helpers;
using FluentNHibernate.Testing;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using UCDArch.Core.PersistanceSupport;
using UCDArch.Data.NHibernate;
namespace Commencement.Tests.Repositories
{
/// <summary>
/// Entity Name: vUser
/// LookupFieldName: LoginId
/// </summary>
[TestClass]
// ReSharper disable InconsistentNaming
public class vUserRepositoryTests : AbstractRepositoryTests<vUser, int, vUserMap>
{
/// <summary>
/// Gets or sets the vUser repository.
/// </summary>
/// <value>The vUser repository.</value>
public IRepository<vUser> vUserRepository { get; set; }
// ReSharper restore InconsistentNaming
#region Init and Overrides
/// <summary>
/// Initializes a new instance of the <see cref="vUserRepositoryTests"/> class.
/// </summary>
public vUserRepositoryTests()
{
vUserRepository = new Repository<vUser>();
}
/// <summary>
/// Gets the valid entity of type T
/// </summary>
/// <param name="counter">The counter.</param>
/// <returns>A valid entity of type T</returns>
protected override vUser GetValid(int? counter)
{
return CreateValidEntities.vUser(counter);
}
/// <summary>
/// A Query which will return a single record
/// </summary>
/// <param name="numberAtEnd"></param>
/// <returns></returns>
protected override IQueryable<vUser> GetQuery(int numberAtEnd)
{
return vUserRepository.Queryable.Where(a => a.LoginId.EndsWith(numberAtEnd.ToString()));
}
/// <summary>
/// A way to compare the entities that were read.
/// For example, this would have the assert.AreEqual("Comment" + counter, entity.Comment);
/// </summary>
/// <param name="entity"></param>
/// <param name="counter"></param>
protected override void FoundEntityComparison(vUser entity, int counter)
{
Assert.AreEqual("LoginId" + counter, entity.LoginId);
}
/// <summary>
/// Updates , compares, restores.
/// </summary>
/// <param name="entity">The entity.</param>
/// <param name="action">The action.</param>
protected override void UpdateUtility(vUser entity, ARTAction action)
{
const string updateValue = "Updated";
switch (action)
{
case ARTAction.Compare:
Assert.AreEqual(updateValue, entity.LoginId);
break;
case ARTAction.Restore:
entity.LoginId = RestoreValue;
break;
case ARTAction.Update:
RestoreValue = entity.LoginId;
entity.LoginId = updateValue;
break;
}
}
[TestMethod]
[ExpectedException(typeof(NHibernate.HibernateException))]
public override void CanDeleteEntity()
{
try
{
base.CanDeleteEntity();
}
catch (Exception ex)
{
Assert.IsNotNull(ex);
Assert.AreEqual("Attempted to delete an object of immutable class: [Commencement.Core.Domain.vUser]", ex.Message);
throw;
}
}
public override void CanUpdateEntity()
{
CanUpdateEntity(false);
}
/// <summary>
/// Loads the data.
/// </summary>
protected override void LoadData()
{
vUserRepository.DbContext.BeginTransaction();
LoadRecords(5);
vUserRepository.DbContext.CommitTransaction();
}
#endregion Init and Overrides
#region LoginId Tests
#region Valid Tests
/// <summary>
/// Tests the LoginId with null value saves.
/// </summary>
[TestMethod]
public void TestLoginIdWithNullValueSaves()
{
#region Arrange
var vUser = GetValid(9);
vUser.LoginId = null;
#endregion Arrange
#region Act
vUserRepository.DbContext.BeginTransaction();
vUserRepository.EnsurePersistent(vUser);
vUserRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsFalse(vUser.IsTransient());
Assert.IsTrue(vUser.IsValid());
#endregion Assert
}
/// <summary>
/// Tests the LoginId with empty string saves.
/// </summary>
[TestMethod]
public void TestLoginIdWithEmptyStringSaves()
{
#region Arrange
var vUser = GetValid(9);
vUser.LoginId = string.Empty;
#endregion Arrange
#region Act
vUserRepository.DbContext.BeginTransaction();
vUserRepository.EnsurePersistent(vUser);
vUserRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsFalse(vUser.IsTransient());
Assert.IsTrue(vUser.IsValid());
#endregion Assert
}
/// <summary>
/// Tests the LoginId with one space saves.
/// </summary>
[TestMethod]
public void TestLoginIdWithOneSpaceSaves()
{
#region Arrange
var vUser = GetValid(9);
vUser.LoginId = " ";
#endregion Arrange
#region Act
vUserRepository.DbContext.BeginTransaction();
vUserRepository.EnsurePersistent(vUser);
vUserRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsFalse(vUser.IsTransient());
Assert.IsTrue(vUser.IsValid());
#endregion Assert
}
/// <summary>
/// Tests the LoginId with one character saves.
/// </summary>
[TestMethod]
public void TestLoginIdWithOneCharacterSaves()
{
#region Arrange
var vUser = GetValid(9);
vUser.LoginId = "x";
#endregion Arrange
#region Act
vUserRepository.DbContext.BeginTransaction();
vUserRepository.EnsurePersistent(vUser);
vUserRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsFalse(vUser.IsTransient());
Assert.IsTrue(vUser.IsValid());
#endregion Assert
}
/// <summary>
/// Tests the LoginId with long value saves.
/// </summary>
[TestMethod]
public void TestLoginIdWithLongValueSaves()
{
#region Arrange
var vUser = GetValid(9);
vUser.LoginId = "x".RepeatTimes(999);
#endregion Arrange
#region Act
vUserRepository.DbContext.BeginTransaction();
vUserRepository.EnsurePersistent(vUser);
vUserRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.AreEqual(999, vUser.LoginId.Length);
Assert.IsFalse(vUser.IsTransient());
Assert.IsTrue(vUser.IsValid());
#endregion Assert
}
#endregion Valid Tests
#endregion LoginId Tests
#region FirstName Tests
#region Valid Tests
/// <summary>
/// Tests the FirstName with null value saves.
/// </summary>
[TestMethod]
public void TestFirstNameWithNullValueSaves()
{
#region Arrange
var vUser = GetValid(9);
vUser.FirstName = null;
#endregion Arrange
#region Act
vUserRepository.DbContext.BeginTransaction();
vUserRepository.EnsurePersistent(vUser);
vUserRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsFalse(vUser.IsTransient());
Assert.IsTrue(vUser.IsValid());
#endregion Assert
}
/// <summary>
/// Tests the FirstName with empty string saves.
/// </summary>
[TestMethod]
public void TestFirstNameWithEmptyStringSaves()
{
#region Arrange
var vUser = GetValid(9);
vUser.FirstName = string.Empty;
#endregion Arrange
#region Act
vUserRepository.DbContext.BeginTransaction();
vUserRepository.EnsurePersistent(vUser);
vUserRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsFalse(vUser.IsTransient());
Assert.IsTrue(vUser.IsValid());
#endregion Assert
}
/// <summary>
/// Tests the FirstName with one space saves.
/// </summary>
[TestMethod]
public void TestFirstNameWithOneSpaceSaves()
{
#region Arrange
var vUser = GetValid(9);
vUser.FirstName = " ";
#endregion Arrange
#region Act
vUserRepository.DbContext.BeginTransaction();
vUserRepository.EnsurePersistent(vUser);
vUserRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsFalse(vUser.IsTransient());
Assert.IsTrue(vUser.IsValid());
#endregion Assert
}
/// <summary>
/// Tests the FirstName with one character saves.
/// </summary>
[TestMethod]
public void TestFirstNameWithOneCharacterSaves()
{
#region Arrange
var vUser = GetValid(9);
vUser.FirstName = "x";
#endregion Arrange
#region Act
vUserRepository.DbContext.BeginTransaction();
vUserRepository.EnsurePersistent(vUser);
vUserRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsFalse(vUser.IsTransient());
Assert.IsTrue(vUser.IsValid());
#endregion Assert
}
/// <summary>
/// Tests the FirstName with long value saves.
/// </summary>
[TestMethod]
public void TestFirstNameWithLongValueSaves()
{
#region Arrange
var vUser = GetValid(9);
vUser.FirstName = "x".RepeatTimes(999);
#endregion Arrange
#region Act
vUserRepository.DbContext.BeginTransaction();
vUserRepository.EnsurePersistent(vUser);
vUserRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.AreEqual(999, vUser.FirstName.Length);
Assert.IsFalse(vUser.IsTransient());
Assert.IsTrue(vUser.IsValid());
#endregion Assert
}
#endregion Valid Tests
#endregion FirstName Tests
#region LastName Tests
#region Valid Tests
/// <summary>
/// Tests the LastName with null value saves.
/// </summary>
[TestMethod]
public void TestLastNameWithNullValueSaves()
{
#region Arrange
var vUser = GetValid(9);
vUser.LastName = null;
#endregion Arrange
#region Act
vUserRepository.DbContext.BeginTransaction();
vUserRepository.EnsurePersistent(vUser);
vUserRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsFalse(vUser.IsTransient());
Assert.IsTrue(vUser.IsValid());
#endregion Assert
}
/// <summary>
/// Tests the LastName with empty string saves.
/// </summary>
[TestMethod]
public void TestLastNameWithEmptyStringSaves()
{
#region Arrange
var vUser = GetValid(9);
vUser.LastName = string.Empty;
#endregion Arrange
#region Act
vUserRepository.DbContext.BeginTransaction();
vUserRepository.EnsurePersistent(vUser);
vUserRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsFalse(vUser.IsTransient());
Assert.IsTrue(vUser.IsValid());
#endregion Assert
}
/// <summary>
/// Tests the LastName with one space saves.
/// </summary>
[TestMethod]
public void TestLastNameWithOneSpaceSaves()
{
#region Arrange
var vUser = GetValid(9);
vUser.LastName = " ";
#endregion Arrange
#region Act
vUserRepository.DbContext.BeginTransaction();
vUserRepository.EnsurePersistent(vUser);
vUserRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsFalse(vUser.IsTransient());
Assert.IsTrue(vUser.IsValid());
#endregion Assert
}
/// <summary>
/// Tests the LastName with one character saves.
/// </summary>
[TestMethod]
public void TestLastNameWithOneCharacterSaves()
{
#region Arrange
var vUser = GetValid(9);
vUser.LastName = "x";
#endregion Arrange
#region Act
vUserRepository.DbContext.BeginTransaction();
vUserRepository.EnsurePersistent(vUser);
vUserRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsFalse(vUser.IsTransient());
Assert.IsTrue(vUser.IsValid());
#endregion Assert
}
/// <summary>
/// Tests the LastName with long value saves.
/// </summary>
[TestMethod]
public void TestLastNameWithLongValueSaves()
{
#region Arrange
var vUser = GetValid(9);
vUser.LastName = "x".RepeatTimes(999);
#endregion Arrange
#region Act
vUserRepository.DbContext.BeginTransaction();
vUserRepository.EnsurePersistent(vUser);
vUserRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.AreEqual(999, vUser.LastName.Length);
Assert.IsFalse(vUser.IsTransient());
Assert.IsTrue(vUser.IsValid());
#endregion Assert
}
#endregion Valid Tests
#endregion LastName Tests
#region Email Tests
#region Valid Tests
/// <summary>
/// Tests the Email with null value saves.
/// </summary>
[TestMethod]
public void TestEmailWithNullValueSaves()
{
#region Arrange
var vUser = GetValid(9);
vUser.Email = null;
#endregion Arrange
#region Act
vUserRepository.DbContext.BeginTransaction();
vUserRepository.EnsurePersistent(vUser);
vUserRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsFalse(vUser.IsTransient());
Assert.IsTrue(vUser.IsValid());
#endregion Assert
}
/// <summary>
/// Tests the Email with empty string saves.
/// </summary>
[TestMethod]
public void TestEmailWithEmptyStringSaves()
{
#region Arrange
var vUser = GetValid(9);
vUser.Email = string.Empty;
#endregion Arrange
#region Act
vUserRepository.DbContext.BeginTransaction();
vUserRepository.EnsurePersistent(vUser);
vUserRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsFalse(vUser.IsTransient());
Assert.IsTrue(vUser.IsValid());
#endregion Assert
}
/// <summary>
/// Tests the Email with one space saves.
/// </summary>
[TestMethod]
public void TestEmailWithOneSpaceSaves()
{
#region Arrange
var vUser = GetValid(9);
vUser.Email = " ";
#endregion Arrange
#region Act
vUserRepository.DbContext.BeginTransaction();
vUserRepository.EnsurePersistent(vUser);
vUserRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsFalse(vUser.IsTransient());
Assert.IsTrue(vUser.IsValid());
#endregion Assert
}
/// <summary>
/// Tests the Email with one character saves.
/// </summary>
[TestMethod]
public void TestEmailWithOneCharacterSaves()
{
#region Arrange
var vUser = GetValid(9);
vUser.Email = "x";
#endregion Arrange
#region Act
vUserRepository.DbContext.BeginTransaction();
vUserRepository.EnsurePersistent(vUser);
vUserRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsFalse(vUser.IsTransient());
Assert.IsTrue(vUser.IsValid());
#endregion Assert
}
/// <summary>
/// Tests the Email with long value saves.
/// </summary>
[TestMethod]
public void TestEmailWithLongValueSaves()
{
#region Arrange
var vUser = GetValid(9);
vUser.Email = "x".RepeatTimes(999);
#endregion Arrange
#region Act
vUserRepository.DbContext.BeginTransaction();
vUserRepository.EnsurePersistent(vUser);
vUserRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.AreEqual(999, vUser.Email.Length);
Assert.IsFalse(vUser.IsTransient());
Assert.IsTrue(vUser.IsValid());
#endregion Assert
}
#endregion Valid Tests
#endregion Email Tests
#region FullName Tests
[TestMethod]
public void TestFullNameReturnsExpectedResult()
{
#region Arrange
var record = CreateValidEntities.vUser(1);
#endregion Arrange
#region Assert
Assert.AreEqual("FirstName1 LastName1", record.FullName);
#endregion Assert
}
#endregion FullName Tests
#region Fluent Mapping Tests
[TestMethod]
public void TestCanCorrectlyMapvUser()
{
#region Arrange
var id = vUserRepository.Queryable.Max(a => a.Id) + 1;
var session = NHibernateSessionManager.Instance.GetSession();
#endregion Arrange
#region Act/Assert
new PersistenceSpecification<vUser>(session)
.CheckProperty(c => c.Id, id)
.CheckProperty(c => c.LoginId, "Login")
.CheckProperty(c => c.FirstName, "FirstName")
.CheckProperty(c => c.LastName, "LastName")
.CheckProperty(c => c.Email, "Email")
.VerifyTheMappings();
#endregion Act/Assert
}
#endregion Fluent Mapping Tests
#region Reflection of Database.
/// <summary>
/// Tests all fields in the database have been tested.
/// If this fails and no other tests, it means that a field has been added which has not been tested above.
/// </summary>
[TestMethod]
public void TestAllFieldsInTheDatabaseHaveBeenTested()
{
#region Arrange
var expectedFields = new List<NameAndType>();
expectedFields.Add(new NameAndType("Email", "System.String", new List<string>()));
expectedFields.Add(new NameAndType("FirstName", "System.String", new List<string>()));
expectedFields.Add(new NameAndType("FullName", "System.String", new List<string>()));
expectedFields.Add(new NameAndType("Id", "System.Int32", new List<string>
{
"[Newtonsoft.Json.JsonPropertyAttribute()]",
"[System.Xml.Serialization.XmlIgnoreAttribute()]"
}));
expectedFields.Add(new NameAndType("LastName", "System.String", new List<string>()));
expectedFields.Add(new NameAndType("LoginId", "System.String", new List<string>()));
#endregion Arrange
AttributeAndFieldValidation.ValidateFieldsAndAttributes(expectedFields, typeof(vUser));
}
#endregion Reflection of Database.
}
}
| |
//
// Copyright 2012-2016, 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.Threading.Tasks;
using System.Net;
using System.Collections.Generic;
using System.Text;
using Xamarin.Utilities;
#if ! AZURE_MOBILE_SERVICES
namespace Xamarin.Auth
#else
namespace Xamarin.Auth._MobileServices
#endif
{
/// <summary>
/// Type of method used to fetch the username of an account
/// after it has been successfully authenticated.
/// </summary>
#if XAMARIN_AUTH_INTERNAL
internal delegate Task<string> GetUsernameAsyncFunc (IDictionary<string, string> accountProperties);
#else
public delegate Task<string> GetUsernameAsyncFunc(IDictionary<string, string> accountProperties);
#endif
/// <summary>
/// OAuth 1.0 authenticator.
/// </summary>
#if XAMARIN_AUTH_INTERNAL
internal class OAuth1Authenticator
:
//WebAuthenticator
WebRedirectAuthenticator //mc++ changed in 1.5.0.4 on 2017-09-15
// OAuth2Authenticator inherits from WebRedirectAuthenticator
#else
public class OAuth1Authenticator
:
//WebAuthenticator
WebRedirectAuthenticator //mc++ changed in 1.5.0.4 on 2017-09-15
// OAuth2Authenticator inherits from WebRedirectAuthenticator
#endif
{
string consumerKey;
string consumerSecret;
Uri requestTokenUrl;
Uri authorizeUrl;
Uri accessTokenUrl;
Uri callbackUrl;
GetUsernameAsyncFunc getUsernameAsync;
string token;
string tokenSecret;
string verifier;
/// <summary>
/// Initializes a new instance of the <see cref="Xamarin.Auth.OAuth1Authenticator"/> class.
/// </summary>
/// <param name='consumerKey'>
/// Consumer key.
/// </param>
/// <param name='consumerSecret'>
/// Consumer secret.
/// </param>
/// <param name='requestTokenUrl'>
/// Request token URL.
/// </param>
/// <param name='authorizeUrl'>
/// Authorize URL.
/// </param>
/// <param name='accessTokenUrl'>
/// Access token URL.
/// </param>
/// <param name='callbackUrl'>
/// Callback URL.
/// </param>
/// <param name='getUsernameAsync'>
/// Method used to fetch the username of an account
/// after it has been successfully authenticated.
/// </param>
public OAuth1Authenticator
(
string consumerKey,
string consumerSecret,
Uri requestTokenUrl,
Uri authorizeUrl,
Uri accessTokenUrl,
Uri callbackUrl,
GetUsernameAsyncFunc getUsernameAsync = null,
bool isUsingNativeUI = false
)
: base(authorizeUrl, callbackUrl)
{
this.is_using_native_ui = isUsingNativeUI;
if (string.IsNullOrEmpty(consumerKey))
{
throw new ArgumentException("consumerKey must be provided", "consumerKey");
}
this.consumerKey = consumerKey;
if (string.IsNullOrEmpty(consumerSecret))
{
throw new ArgumentException("consumerSecret must be provided", "consumerSecret");
}
this.consumerSecret = consumerSecret;
if (requestTokenUrl == null)
{
throw new ArgumentNullException("requestTokenUrl");
}
this.requestTokenUrl = requestTokenUrl;
if (authorizeUrl == null)
{
throw new ArgumentNullException("authorizeUrl");
}
this.authorizeUrl = authorizeUrl;
if (accessTokenUrl == null)
{
throw new ArgumentNullException("accessTokenUrl");
}
this.accessTokenUrl = accessTokenUrl;
if (callbackUrl == null)
{
throw new ArgumentNullException("callbackUrl");
}
this.callbackUrl = callbackUrl;
this.getUsernameAsync = getUsernameAsync;
this.HttpWebClientFrameworkType = Auth.HttpWebClientFrameworkType.WebRequest;
#if DEBUG
StringBuilder sb = new StringBuilder();
sb.AppendLine($"OAuth1Authenticator ");
sb.AppendLine($" IsUsingNativeUI = {IsUsingNativeUI}");
sb.AppendLine($" callbackUrl = {callbackUrl}");
System.Diagnostics.Debug.WriteLine(sb.ToString());
#endif
return;
}
/// <summary>
/// Method that returns the initial URL to be displayed in the web browser.
/// </summary>
/// <returns>
/// A task that will return the initial URL.
/// </returns>
public override Task<Uri> GetInitialUrlAsync(Dictionary<string, string> query_parameters = null)
{
/*
mc++
OriginalString property of the Uri object should be used instead of AbsoluteUri
otherwise trailing slash is added.
string[] uris = new string[]
{
"http://xamarin.com/",
"http://xamarin.com",
};
foreach (string u in uris)
{
uri = new Uri(u);
Console.WriteLine("uri.AbsoluteUri = " + uri.AbsoluteUri);
Console.WriteLine("uri.OriginalString = " + uri.OriginalString);
}
The problem is whether to send original string to be compared with registered
redirect_url on the authorization server od "correct" url (AblsoluteUrl) with
slash
*/
//string oauth_callback_uri_absolute = callbackUrl.AbsoluteUri;
string oauth_callback_uri_original = callbackUrl.OriginalString;
//System.Diagnostics.Debug.WriteLine("GetInitialUrlAsync callbackUrl.AbsoluteUri = " + oauth_callback_uri_absolute);
System.Diagnostics.Debug.WriteLine("GetInitialUrlAsync callbackUrl.OriginalString = " + oauth_callback_uri_original);
string oauth_callback_uri = oauth_callback_uri_original;
var req = OAuth1.CreateRequest
(
"GET",
requestTokenUrl,
new Dictionary<string, string>()
{
{ "oauth_callback", oauth_callback_uri },
},
consumerKey,
consumerSecret,
""
);
if (this.HttpWebClientFrameworkType == HttpWebClientFrameworkType.WebRequest)
{
return req.GetResponseAsync()
.ContinueWith
(
respTask =>
{
var content = respTask.Result.GetResponseText();
var r = WebEx.FormDecode(content);
token = r["oauth_token"];
tokenSecret = r["oauth_token_secret"];
string paramType = authorizeUrl.AbsoluteUri.IndexOf("?") >= 0 ? "&" : "?";
var url = authorizeUrl.AbsoluteUri + paramType + "oauth_token=" + Uri.EscapeDataString(token);
return new Uri(url);
}
);
}
else if (this.HttpWebClientFrameworkType == HttpWebClientFrameworkType.HttpClient)
{
throw new NotImplementedException("HttpClient implementation!");
}
return null;
}
/// <summary>
/// Event handler that watches for the callback URL to be loaded.
/// </summary>
/// <param name='url'>
/// The URL of the loaded page.
/// </param>
public override void OnPageLoaded(Uri url)
{
if (
url.Authority == callbackUrl.Authority
//url.Host == callbackUrl.Host
&&
url.AbsolutePath == callbackUrl.AbsolutePath
)
{
var query = url.Query;
var r = WebEx.FormDecode(query);
r.TryGetValue("oauth_verifier", out verifier);
#if DEBUG
StringBuilder sb = new StringBuilder();
sb.AppendLine($"OAuth1Authenticator.OnPageLoaded ");
sb.AppendLine($" url = {url.AbsoluteUri}");
sb.AppendLine($" oauth_verifier = {verifier}");
System.Diagnostics.Debug.WriteLine(sb.ToString());
#endif
GetAccessTokenAsync().ContinueWith(getTokenTask =>
{
if (getTokenTask.IsCanceled)
{
OnCancelled();
}
else if (getTokenTask.IsFaulted)
{
OnError(getTokenTask.Exception);
}
}, TaskContinuationOptions.NotOnRanToCompletion);
}
else
{
// http[s]://www.xamarin.com != http[s]://xamarin.com
#if DEBUG
StringBuilder sb = new StringBuilder();
sb.AppendLine($"OAuth1Authenticator.OnPageLoaded ");
sb.AppendLine($" mc++ fix");
sb.AppendLine($" url = {url.AbsoluteUri}");
sb.AppendLine($" callbackUrl = {callbackUrl.OriginalString}");
sb.AppendLine($" oauth_verifier = {verifier}");
System.Diagnostics.Debug.WriteLine(sb.ToString());
#endif
}
return;
}
Task GetAccessTokenAsync()
{
#if DEBUG
StringBuilder sb = new StringBuilder();
sb.AppendLine($"OAuth1Authenticator.GetAccessTokenAsync ");
sb.AppendLine($" token = {token}");
System.Diagnostics.Debug.WriteLine(sb.ToString());
#endif
RequestParameters = new Dictionary<string, string>
{
{ "oauth_token", token }
};
if (verifier != null)
{
RequestParameters["oauth_verifier"] = verifier;
System.Diagnostics.Debug.WriteLine($" verifier = {verifier}");
}
// WebRequest Replaced with HttpRequest for .net Standard 1.1
HttpWebRequest req = OAuth1.CreateRequest
(
"GET",
accessTokenUrl,
request_parameters,
consumerKey,
consumerSecret,
tokenSecret
);
if (this.HttpWebClientFrameworkType == HttpWebClientFrameworkType.WebRequest)
{
WebResponse response = req.GetResponseAsync().Result;
return req.GetResponseAsync().ContinueWith
(
respTask =>
{
var content = respTask.Result.GetResponseText();
var accountProperties = WebEx.FormDecode(content);
accountProperties["oauth_consumer_key"] = consumerKey;
accountProperties["oauth_consumer_secret"] = consumerSecret;
if (getUsernameAsync != null)
{
getUsernameAsync(accountProperties).ContinueWith(uTask =>
{
if (uTask.IsFaulted)
{
OnError(uTask.Exception);
}
else
{
OnSucceeded(uTask.Result, accountProperties);
}
});
}
else
{
OnSucceeded("", accountProperties);
}
}
);
}
else if (this.HttpWebClientFrameworkType == HttpWebClientFrameworkType.HttpClient)
{
throw new NotImplementedException("HttpClient implementation!");
}
return null;
}
public HttpWebClientFrameworkType HttpWebClientFrameworkType
{
get;
set;
}
public override string ToString()
{
/*
string msg = string.Format
(
"[OAuth1Authenticator: HttpWebClientFrameworkType={0}]",
HttpWebClientFrameworkType
);
*/
System.Text.StringBuilder sb = new System.Text.StringBuilder(base.ToString());
sb.AppendLine().AppendLine(this.GetType().ToString());
classlevel_depth++;
string prefix = new string('\t', classlevel_depth);
sb.Append(prefix).AppendLine($"Query = {Query}");
sb.Append(prefix).AppendLine($"Fragment = {Fragment}");
sb.Append(prefix).AppendLine($"IsLoadableRedirectUri = {IsLoadableRedirectUri}");
sb.Append(prefix).AppendLine($"ShouldEncounterOnPageLoading = {ShouldEncounterOnPageLoading}");
sb.Append(prefix).AppendLine($"ShouldEncounterOnPageLoaded = {ShouldEncounterOnPageLoaded}");
return sb.ToString();
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.Compute.Fluent
{
using Microsoft.Azure.Management.Compute.Fluent.Models;
using Microsoft.Azure.Management.Compute.Fluent.VirtualMachineCustomImage.CustomImageDataDisk.Definition;
using Microsoft.Azure.Management.Compute.Fluent.VirtualMachineCustomImage.Definition;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
internal partial class VirtualMachineCustomImageImpl
{
/// <summary>
/// Gets data disk images in this image, indexed by the disk LUN.
/// </summary>
System.Collections.Generic.IReadOnlyDictionary<int, Models.ImageDataDisk> Microsoft.Azure.Management.Compute.Fluent.IVirtualMachineCustomImage.DataDiskImages
{
get
{
return this.DataDiskImages();
}
}
/// <summary>
/// Gets true if this image was created by capturing a virtual machine.
/// </summary>
bool Microsoft.Azure.Management.Compute.Fluent.IVirtualMachineCustomImage.IsCreatedFromVirtualMachine
{
get
{
return this.IsCreatedFromVirtualMachine();
}
}
/// <summary>
/// Gets operating system disk image in this image.
/// </summary>
Models.ImageOSDisk Microsoft.Azure.Management.Compute.Fluent.IVirtualMachineCustomImage.OSDiskImage
{
get
{
return this.OSDiskImage();
}
}
/// <summary>
/// Gets ID of the virtual machine if this image was created by capturing that virtual machine.
/// </summary>
string Microsoft.Azure.Management.Compute.Fluent.IVirtualMachineCustomImage.SourceVirtualMachineId
{
get
{
return this.SourceVirtualMachineId();
}
}
/// <summary>
/// Begins the definition of a new data disk image to add to the image.
/// </summary>
/// <return>The first stage of the new data disk image definition.</return>
VirtualMachineCustomImage.CustomImageDataDisk.Definition.IBlank<VirtualMachineCustomImage.Definition.IWithCreateAndDataDiskImageOSDiskSettings> VirtualMachineCustomImage.Definition.IWithDataDiskImage.DefineDataDiskImage()
{
return this.DefineDataDiskImage();
}
/// <summary>
/// Uses the virtual machine's OS disk and data disks as the source for OS disk image and
/// data disk images of this image.
/// </summary>
/// <param name="virtualMachineId">Source virtual machine resource ID.</param>
/// <return>The next stage of the definition.</return>
VirtualMachineCustomImage.Definition.IWithCreate VirtualMachineCustomImage.Definition.IWithSourceVirtualMachine.FromVirtualMachine(string virtualMachineId)
{
return this.FromVirtualMachine(virtualMachineId);
}
/// <summary>
/// Uses the virtual machine's OS and data disks as the sources for OS disk image and data
/// disk images of this image.
/// </summary>
/// <param name="virtualMachine">Source virtual machine.</param>
/// <return>The next stage of the definition.</return>
VirtualMachineCustomImage.Definition.IWithCreate VirtualMachineCustomImage.Definition.IWithSourceVirtualMachine.FromVirtualMachine(IVirtualMachine virtualMachine)
{
return this.FromVirtualMachine(virtualMachine);
}
/// <summary>
/// Adds a data disk image with an existing managed disk as the source.
/// </summary>
/// <param name="sourceManagedDiskId">Source managed disk resource ID.</param>
/// <return>The next stage of the definition.</return>
VirtualMachineCustomImage.Definition.IWithCreateAndDataDiskImageOSDiskSettings VirtualMachineCustomImage.Definition.IWithDataDiskImage.WithDataDiskImageFromManagedDisk(string sourceManagedDiskId)
{
return this.WithDataDiskImageFromManagedDisk(sourceManagedDiskId);
}
/// <summary>
/// Adds a data disk image with an existing snapshot as the source.
/// </summary>
/// <param name="sourceSnapshotId">Source snapshot resource ID.</param>
/// <return>The next stage of the definition.</return>
VirtualMachineCustomImage.Definition.IWithCreateAndDataDiskImageOSDiskSettings VirtualMachineCustomImage.Definition.IWithDataDiskImage.WithDataDiskImageFromSnapshot(string sourceSnapshotId)
{
return this.WithDataDiskImageFromSnapshot(sourceSnapshotId);
}
/// <summary>
/// Adds a data disk image with a virtual hard disk as the source.
/// </summary>
/// <param name="sourceVhdUrl">Source virtual hard disk URL.</param>
/// <return>The next stage of the definition.</return>
VirtualMachineCustomImage.Definition.IWithCreateAndDataDiskImageOSDiskSettings VirtualMachineCustomImage.Definition.IWithDataDiskImage.WithDataDiskImageFromVhd(string sourceVhdUrl)
{
return this.WithDataDiskImageFromVhd(sourceVhdUrl);
}
/// <summary>
/// Specifies the Linux source managed disk for the OS disk image.
/// </summary>
/// <param name="sourceManagedDiskId">Source managed disk resource ID.</param>
/// <param name="osState">Operating system state.</param>
/// <return>The next stage of the definition.</return>
VirtualMachineCustomImage.Definition.IWithCreateAndDataDiskImageOSDiskSettings VirtualMachineCustomImage.Definition.IWithOSDiskImageSource.WithLinuxFromDisk(string sourceManagedDiskId, OperatingSystemStateTypes osState)
{
return this.WithLinuxFromDisk(sourceManagedDiskId, osState);
}
/// <summary>
/// Specifies the Linux source managed disk for the OS disk image.
/// </summary>
/// <param name="sourceManagedDisk">Source managed disk.</param>
/// <param name="osState">Operating system state.</param>
/// <return>The next stage of the definition.</return>
VirtualMachineCustomImage.Definition.IWithCreateAndDataDiskImageOSDiskSettings VirtualMachineCustomImage.Definition.IWithOSDiskImageSource.WithLinuxFromDisk(IDisk sourceManagedDisk, OperatingSystemStateTypes osState)
{
return this.WithLinuxFromDisk(sourceManagedDisk, osState);
}
/// <summary>
/// Specifies the Linux source snapshot for the OS disk image.
/// </summary>
/// <param name="sourceSnapshotId">Source snapshot resource ID.</param>
/// <param name="osState">Operating system state.</param>
/// <return>The next stage of the definition.</return>
VirtualMachineCustomImage.Definition.IWithCreateAndDataDiskImageOSDiskSettings VirtualMachineCustomImage.Definition.IWithOSDiskImageSource.WithLinuxFromSnapshot(string sourceSnapshotId, OperatingSystemStateTypes osState)
{
return this.WithLinuxFromSnapshot(sourceSnapshotId, osState);
}
/// <summary>
/// Specifies the Linux source snapshot for the OS disk image.
/// </summary>
/// <param name="sourceSnapshot">Source snapshot resource.</param>
/// <param name="osState">Operating system state.</param>
/// <return>The next stage of the definition.</return>
VirtualMachineCustomImage.Definition.IWithCreateAndDataDiskImageOSDiskSettings VirtualMachineCustomImage.Definition.IWithOSDiskImageSource.WithLinuxFromSnapshot(ISnapshot sourceSnapshot, OperatingSystemStateTypes osState)
{
return this.WithLinuxFromSnapshot(sourceSnapshot, osState);
}
/// <summary>
/// Specifies the Linux source native VHD for the OS disk image.
/// </summary>
/// <param name="sourceVhdUrl">Source Linux virtual hard disk URL.</param>
/// <param name="osState">Operating system state.</param>
/// <return>The next stage of the definition.</return>
VirtualMachineCustomImage.Definition.IWithCreateAndDataDiskImageOSDiskSettings VirtualMachineCustomImage.Definition.IWithOSDiskImageSource.WithLinuxFromVhd(string sourceVhdUrl, OperatingSystemStateTypes osState)
{
return this.WithLinuxFromVhd(sourceVhdUrl, osState);
}
/// <summary>
/// Specifies the caching type for OS disk.
/// </summary>
/// <param name="cachingType">The disk caching type.</param>
/// <return>The next stage of the definition.</return>
VirtualMachineCustomImage.Definition.IWithCreateAndDataDiskImageOSDiskSettings VirtualMachineCustomImage.Definition.IWithOSDiskSettings.WithOSDiskCaching(CachingTypes cachingType)
{
return this.WithOSDiskCaching(cachingType);
}
/// <summary>
/// Specifies the size in GB for OS disk.
/// </summary>
/// <param name="diskSizeGB">The disk size in GB.</param>
/// <return>The next stage of the definition.</return>
VirtualMachineCustomImage.Definition.IWithCreateAndDataDiskImageOSDiskSettings VirtualMachineCustomImage.Definition.IWithOSDiskSettings.WithOSDiskSizeInGB(int diskSizeGB)
{
return this.WithOSDiskSizeInGB(diskSizeGB);
}
/// <summary>
/// Specifies the Windows source managed disk for the OS disk image.
/// </summary>
/// <param name="sourceManagedDiskId">Source managed disk resource ID.</param>
/// <param name="osState">Operating system state.</param>
/// <return>The next stage of the definition.</return>
VirtualMachineCustomImage.Definition.IWithCreateAndDataDiskImageOSDiskSettings VirtualMachineCustomImage.Definition.IWithOSDiskImageSource.WithWindowsFromDisk(string sourceManagedDiskId, OperatingSystemStateTypes osState)
{
return this.WithWindowsFromDisk(sourceManagedDiskId, osState);
}
/// <summary>
/// Specifies the Windows source managed disk for the OS disk image.
/// </summary>
/// <param name="sourceManagedDisk">Source managed disk.</param>
/// <param name="osState">Operating system state.</param>
/// <return>The next stage of the definition.</return>
VirtualMachineCustomImage.Definition.IWithCreateAndDataDiskImageOSDiskSettings VirtualMachineCustomImage.Definition.IWithOSDiskImageSource.WithWindowsFromDisk(IDisk sourceManagedDisk, OperatingSystemStateTypes osState)
{
return this.WithWindowsFromDisk(sourceManagedDisk, osState);
}
/// <summary>
/// Specifies the Windows source snapshot for the OS disk image.
/// </summary>
/// <param name="sourceSnapshotId">Source snapshot resource ID.</param>
/// <param name="osState">Operating system state.</param>
/// <return>The next stage of the definition.</return>
VirtualMachineCustomImage.Definition.IWithCreateAndDataDiskImageOSDiskSettings VirtualMachineCustomImage.Definition.IWithOSDiskImageSource.WithWindowsFromSnapshot(string sourceSnapshotId, OperatingSystemStateTypes osState)
{
return this.WithWindowsFromSnapshot(sourceSnapshotId, osState);
}
/// <summary>
/// Specifies the Windows source snapshot for the OS disk image.
/// </summary>
/// <param name="sourceSnapshot">Source snapshot resource.</param>
/// <param name="osState">Operating system state.</param>
/// <return>The next stage of the definition.</return>
VirtualMachineCustomImage.Definition.IWithCreateAndDataDiskImageOSDiskSettings VirtualMachineCustomImage.Definition.IWithOSDiskImageSource.WithWindowsFromSnapshot(ISnapshot sourceSnapshot, OperatingSystemStateTypes osState)
{
return this.WithWindowsFromSnapshot(sourceSnapshot, osState);
}
/// <summary>
/// Specifies the Windows source native VHD for the OS disk image.
/// </summary>
/// <param name="sourceVhdUrl">Source Windows virtual hard disk URL.</param>
/// <param name="osState">Operating system state.</param>
/// <return>The next stage of the definition.</return>
VirtualMachineCustomImage.Definition.IWithCreateAndDataDiskImageOSDiskSettings VirtualMachineCustomImage.Definition.IWithOSDiskImageSource.WithWindowsFromVhd(string sourceVhdUrl, OperatingSystemStateTypes osState)
{
return this.WithWindowsFromVhd(sourceVhdUrl, osState);
}
/// <summary>
/// Specifies that zone resiliency should be enabled for the image.
/// </summary>
/// <return>The next stage of the definition.</return>
VirtualMachineCustomImage.Definition.IWithCreate VirtualMachineCustomImage.Definition.IWithZoneResilient.WithZoneResilient()
{
return this.WithZoneResilient();
}
}
}
| |
using System;
using System.Collections;
using System.IO;
using System.Xml;
using System.Reflection;
using NUnit.Framework;
using CookComputing.XmlRpc;
// TODO: parse array
// TODO: parse struct
// TODO: parse XmlRpcStruct
// TODO: parse XmlRpcStruct derived
// TODO: array of base64
namespace ntest
{
[TestFixture]
public class ParseTest
{
struct Struct2
{
public int mi;
public string ms;
public bool mb;
public double md;
public DateTime mdt;
public byte[] mb64;
public int[] ma;
public XmlRpcInt xi;
public XmlRpcBoolean xb;
public XmlRpcDouble xd;
public XmlRpcDateTime xdt;
public XmlRpcStruct xstr;
}
//---------------------- int -------------------------------------------//
[Test]
public void Int_NullType()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?><value><int>12345</int></value>";
object obj = Utils.Parse(xml, null, MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.AreEqual(12345, (int)obj);
}
[Test]
public void Int_IntType()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?><value><int>12345</int></value>";
object obj = Utils.Parse(xml, typeof(int), MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.AreEqual(12345, (int)obj);
}
[Test]
public void Int_ObjectType()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?><value><int>12345</int></value>";
object obj = Utils.Parse(xml, typeof(object), MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.AreEqual(12345, (int)obj);
}
//---------------------- Int64 -------------------------------------------//
[Test]
[ExpectedException(typeof(XmlRpcInvalidXmlRpcException))]
public void Int_TooLarge()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?><value><int>123456789012</int></value>";
object obj = Utils.Parse(xml, typeof(int), MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.AreEqual(12345, (int)obj);
}
[Test]
public void Int64_NullType()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?><value><i8>123456789012</i8></value>";
object obj = Utils.Parse(xml, null, MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.AreEqual(123456789012, (long)obj);
}
[Test]
public void Int64_IntType()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?><value><i8>123456789012</i8></value>";
object obj = Utils.Parse(xml, typeof(long), MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.AreEqual(123456789012, (long)obj);
}
[Test]
public void Int64_ObjectType()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?><value><i8>123456789012</i8></value>";
object obj = Utils.Parse(xml, typeof(object), MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.AreEqual(123456789012, (long)obj);
}
//---------------------- string ----------------------------------------//
[Test]
public void String_NullType()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value><string>astring</string></value>";
object obj = Utils.Parse(xml, null, MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.AreEqual("astring", (string)obj);
}
[Test]
public void DefaultString_NullType()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value>astring</value>";
object obj = Utils.Parse(xml, null, MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.AreEqual("astring", (string)obj);
}
[Test]
public void String_StringType()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value><string>astring</string></value>";
object obj = Utils.Parse(xml, typeof(string), MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.AreEqual("astring", (string)obj);
}
[Test]
public void String_ObjectType()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value><string>astring</string></value>";
object obj = Utils.Parse(xml, typeof(object), MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.AreEqual("astring", (string)obj);
}
[Test]
public void DefaultString_StringType()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value>astring</value>";
object obj = Utils.Parse(xml, typeof(string), MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.AreEqual("astring", (string)obj);
}
[Test]
public void Empty1String_StringType()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value><string></string></value>";
object obj = Utils.Parse(xml, typeof(string), MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.AreEqual("", (string)obj);
}
[Test]
public void Empty2String_StringType()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value><string/></value>";
object obj = Utils.Parse(xml, typeof(string), MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.AreEqual("", (string)obj);
}
[Test]
public void Default1EmptyString_StringType()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value></value>";
object obj = Utils.Parse(xml, typeof(string), MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.AreEqual("", (string)obj);
}
[Test]
public void Default2EmptyString_StringType()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value/>";
object obj = Utils.Parse(xml, typeof(string), MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.AreEqual("", (string)obj);
}
//---------------------- boolean ---------------------------------------//
[Test]
public void Boolean_NullType()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value><boolean>1</boolean></value>";
object obj = Utils.Parse(xml, null, MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.AreEqual(true, (bool)obj);
}
[Test]
public void Boolean_BooleanType()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value><boolean>1</boolean></value>";
object obj = Utils.Parse(xml, typeof(bool), MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.AreEqual(true, (bool)obj);
}
[Test]
public void Boolean_ObjectType()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value><boolean>1</boolean></value>";
object obj = Utils.Parse(xml, typeof(object), MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.AreEqual(true, (bool)obj);
}
//---------------------- double ----------------------------------------//
[Test]
public void Double_NullType()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value><double>543.21</double></value>";
object obj = Utils.Parse(xml, null, MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.AreEqual(543.21, (double)obj);
}
[Test]
public void Double_DoubleType()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value><double>543.21</double></value>";
object obj = Utils.Parse(xml, typeof(double), MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.AreEqual(543.21, (double)obj);
}
[Test]
public void Double_ObjectType()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value><double>543.21</double></value>";
object obj = Utils.Parse(xml, typeof(double), MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.AreEqual(543.21, (double)obj);
}
//---------------------- dateTime ------------------------------------//
[Test]
public void DateTime_NullType()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value><dateTime.iso8601>20020706T11:25:37</dateTime.iso8601></value>";
object obj = Utils.Parse(xml, null, MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.AreEqual(new DateTime(2002, 7, 6, 11, 25, 37),
(DateTime)obj);
}
[Test]
public void DateTime_DateTimeType()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value><dateTime.iso8601>20020706T11:25:37</dateTime.iso8601></value>";
object obj = Utils.Parse(xml, typeof(DateTime), MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.AreEqual(new DateTime(2002, 7, 6, 11, 25, 37),
(DateTime)obj);
}
[Test]
public void DateTime_ObjectTimeType()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value><dateTime.iso8601>20020706T11:25:37</dateTime.iso8601></value>";
object obj = Utils.Parse(xml, typeof(object), MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.AreEqual(new DateTime(2002, 7, 6, 11, 25, 37),
(DateTime)obj);
}
[Test]
public void DateTime_ROCA()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value><dateTime.iso8601>2002-07-06T11:25:37</dateTime.iso8601></value>";
XmlRpcSerializer serializer = new XmlRpcSerializer();
serializer.NonStandard = XmlRpcNonStandard.AllowNonStandardDateTime;
object obj = Utils.Parse(xml, typeof(DateTime), MappingAction.Error, serializer,
out parsedType, out parsedArrayType);
Assert.AreEqual(new DateTime(2002, 7, 6, 11, 25, 37),
(DateTime)obj);
}
[Test]
public void DateTime_WordPress()
{
// yyyyMMddThh:mm:ssZ
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value><dateTime.iso8601>20020706T11:25:37Z</dateTime.iso8601></value>";
XmlRpcSerializer serializer = new XmlRpcSerializer();
serializer.NonStandard = XmlRpcNonStandard.AllowNonStandardDateTime;
object obj = Utils.Parse(xml, typeof(DateTime), MappingAction.Error,
serializer, out parsedType, out parsedArrayType);
Assert.AreEqual(new DateTime(2002, 7, 6, 11, 25, 37),
(DateTime)obj);
}
[Test]
public void DateTime_TypePad()
{
// yyyy-MM-ddThh:mm:ssZ
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value><dateTime.iso8601>2002-07-06T11:25:37Z</dateTime.iso8601></value>";
XmlRpcSerializer serializer = new XmlRpcSerializer();
serializer.NonStandard = XmlRpcNonStandard.AllowNonStandardDateTime;
object obj = Utils.Parse(xml, typeof(DateTime), MappingAction.Error,
serializer, out parsedType, out parsedArrayType);
Assert.AreEqual(new DateTime(2002, 7, 6, 11, 25, 37),
(DateTime)obj);
}
[Test]
public void DateTime_TZPlus01()
{
// yyyyMMddThh:mm:ssZ+00
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value><dateTime.iso8601>20020706T12:25:37+01</dateTime.iso8601></value>";
XmlRpcSerializer serializer = new XmlRpcSerializer();
serializer.NonStandard = XmlRpcNonStandard.AllowNonStandardDateTime;
object obj = Utils.Parse(xml, typeof(DateTime), MappingAction.Error,
serializer, out parsedType, out parsedArrayType);
Assert.AreEqual(new DateTime(2002, 7, 6, 11, 25, 37),
(DateTime)obj);
}
[Test]
public void DateTime_TZPlus0130()
{
// yyyyMMddThh:mm:ssZ+00
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value><dateTime.iso8601>20020706T12:55:37+0130</dateTime.iso8601></value>";
XmlRpcSerializer serializer = new XmlRpcSerializer();
serializer.NonStandard = XmlRpcNonStandard.AllowNonStandardDateTime;
object obj = Utils.Parse(xml, typeof(DateTime), MappingAction.Error,
serializer, out parsedType, out parsedArrayType);
Assert.AreEqual(new DateTime(2002, 7, 6, 11, 25, 37),
(DateTime)obj);
}
[Test]
public void DateTime_TZPlus01Colon30()
{
// yyyyMMddThh:mm:ssZ+00
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value><dateTime.iso8601>20020706T12:55:37+01:30</dateTime.iso8601></value>";
XmlRpcSerializer serializer = new XmlRpcSerializer();
serializer.NonStandard = XmlRpcNonStandard.AllowNonStandardDateTime;
object obj = Utils.Parse(xml, typeof(DateTime), MappingAction.Error,
serializer, out parsedType, out parsedArrayType);
Assert.AreEqual(new DateTime(2002, 7, 6, 11, 25, 37),
(DateTime)obj);
}
[Test]
public void DateTime_TZPlus00()
{
// yyyyMMddThh:mm:ssZ+00
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value><dateTime.iso8601>20020706T11:25:37+00</dateTime.iso8601></value>";
XmlRpcSerializer serializer = new XmlRpcSerializer();
serializer.NonStandard = XmlRpcNonStandard.AllowNonStandardDateTime;
object obj = Utils.Parse(xml, typeof(DateTime), MappingAction.Error,
serializer, out parsedType, out parsedArrayType);
Assert.AreEqual(new DateTime(2002, 7, 6, 11, 25, 37),
(DateTime)obj);
}
[Test]
public void DateTime_TZPlus0000()
{
// yyyyMMddThh:mm:ssZ+00
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value><dateTime.iso8601>20020706T11:25:37+0000</dateTime.iso8601></value>";
XmlRpcSerializer serializer = new XmlRpcSerializer();
serializer.NonStandard = XmlRpcNonStandard.AllowNonStandardDateTime;
object obj = Utils.Parse(xml, typeof(DateTime), MappingAction.Error,
serializer, out parsedType, out parsedArrayType);
Assert.AreEqual(new DateTime(2002, 7, 6, 11, 25, 37),
(DateTime)obj);
}
[Test]
public void DateTime_TZMinus01()
{
// yyyyMMddThh:mm:ssZ+00
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value><dateTime.iso8601>20020706T10:25:37-01</dateTime.iso8601></value>";
XmlRpcSerializer serializer = new XmlRpcSerializer();
serializer.NonStandard = XmlRpcNonStandard.AllowNonStandardDateTime;
object obj = Utils.Parse(xml, typeof(DateTime), MappingAction.Error,
serializer, out parsedType, out parsedArrayType);
Assert.AreEqual(new DateTime(2002, 7, 6, 11, 25, 37),
(DateTime)obj);
}
[Test]
public void DateTime_TZMinus0130()
{
// yyyyMMddThh:mm:ssZ+00
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value><dateTime.iso8601>20020706T09:55:37-0130</dateTime.iso8601></value>";
XmlRpcSerializer serializer = new XmlRpcSerializer();
serializer.NonStandard = XmlRpcNonStandard.AllowNonStandardDateTime;
object obj = Utils.Parse(xml, typeof(DateTime), MappingAction.Error,
serializer, out parsedType, out parsedArrayType);
Assert.AreEqual(new DateTime(2002, 7, 6, 11, 25, 37),
(DateTime)obj);
}
[Test]
public void DateTime_TZMinus01Colon30()
{
// yyyyMMddThh:mm:ssZ+00
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value><dateTime.iso8601>20020706T09:55:37-01:30</dateTime.iso8601></value>";
XmlRpcSerializer serializer = new XmlRpcSerializer();
serializer.NonStandard = XmlRpcNonStandard.AllowNonStandardDateTime;
object obj = Utils.Parse(xml, typeof(DateTime), MappingAction.Error,
serializer, out parsedType, out parsedArrayType);
Assert.AreEqual(new DateTime(2002, 7, 6, 11, 25, 37),
(DateTime)obj);
}
[Test]
public void DateTime_TZMinus00()
{
// yyyyMMddThh:mm:ssZ+00
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value><dateTime.iso8601>20020706T11:25:37-00</dateTime.iso8601></value>";
XmlRpcSerializer serializer = new XmlRpcSerializer();
serializer.NonStandard = XmlRpcNonStandard.AllowNonStandardDateTime;
object obj = Utils.Parse(xml, typeof(DateTime), MappingAction.Error,
serializer, out parsedType, out parsedArrayType);
Assert.AreEqual(new DateTime(2002, 7, 6, 11, 25, 37),
(DateTime)obj);
}
[Test]
public void DateTime_TZMinus0000()
{
// yyyyMMddThh:mm:ssZ+00
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value><dateTime.iso8601>20020706T11:25:37-0000</dateTime.iso8601></value>";
XmlRpcSerializer serializer = new XmlRpcSerializer();
serializer.NonStandard = XmlRpcNonStandard.AllowNonStandardDateTime;
object obj = Utils.Parse(xml, typeof(DateTime), MappingAction.Error,
serializer, out parsedType, out parsedArrayType);
Assert.AreEqual(new DateTime(2002, 7, 6, 11, 25, 37),
(DateTime)obj);
}
[Test]
public void DateTime_allZeros1()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value><dateTime.iso8601>0000-00-00T00:00:00</dateTime.iso8601></value>";
XmlRpcSerializer serializer = new XmlRpcSerializer();
serializer.NonStandard = XmlRpcNonStandard.MapZerosDateTimeToMinValue;
object obj = Utils.Parse(xml, typeof(DateTime), MappingAction.Error, serializer,
out parsedType, out parsedArrayType);
Assert.AreEqual(DateTime.MinValue, (DateTime)obj);
}
[Test]
public void DateTime_allZeros2()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value><dateTime.iso8601>0000-00-00T00:00:00Z</dateTime.iso8601></value>";
XmlRpcSerializer serializer = new XmlRpcSerializer();
serializer.NonStandard = XmlRpcNonStandard.MapZerosDateTimeToMinValue;
object obj = Utils.Parse(xml, typeof(DateTime), MappingAction.Error, serializer,
out parsedType, out parsedArrayType);
Assert.AreEqual(DateTime.MinValue, (DateTime)obj);
}
[Test]
public void DateTime_allZeros3()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value><dateTime.iso8601>00000000T00:00:00Z</dateTime.iso8601></value>";
XmlRpcSerializer serializer = new XmlRpcSerializer();
serializer.NonStandard = XmlRpcNonStandard.MapZerosDateTimeToMinValue;
object obj = Utils.Parse(xml, typeof(DateTime), MappingAction.Error, serializer,
out parsedType, out parsedArrayType);
Assert.AreEqual(DateTime.MinValue, (DateTime)obj);
}
[Test]
public void DateTime_allZeros4()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value><dateTime.iso8601>0000-00-00T00:00:00</dateTime.iso8601></value>";
XmlRpcSerializer serializer = new XmlRpcSerializer();
serializer.NonStandard = XmlRpcNonStandard.MapZerosDateTimeToMinValue;
object obj = Utils.Parse(xml, typeof(DateTime), MappingAction.Error, serializer,
out parsedType, out parsedArrayType);
Assert.AreEqual(DateTime.MinValue, (DateTime)obj);
}
[Test]
public void DateTime_Empty_Standard()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value><dateTime.iso8601></dateTime.iso8601></value>";
XmlRpcSerializer serializer = new XmlRpcSerializer();
serializer.NonStandard = XmlRpcNonStandard.MapEmptyDateTimeToMinValue;
object obj = Utils.Parse(xml, typeof(DateTime), MappingAction.Error, serializer,
out parsedType, out parsedArrayType);
Assert.AreEqual(DateTime.MinValue, (DateTime)obj);
}
[Test]
[ExpectedException(typeof(XmlRpcInvalidXmlRpcException))]
public void DateTime_Empty_NonStandard()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value><dateTime.iso8601></dateTime.iso8601></value>";
XmlRpcSerializer serializer = new XmlRpcSerializer();
object obj = Utils.Parse(xml, typeof(DateTime), MappingAction.Error, serializer,
out parsedType, out parsedArrayType);
}
[Test]
public void Issue72()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value><dateTime.iso8601>20090209T22:20:01+01:00</dateTime.iso8601></value>";
XmlRpcSerializer serializer = new XmlRpcSerializer();
serializer.NonStandard = XmlRpcNonStandard.AllowNonStandardDateTime;
object obj = Utils.Parse(xml, typeof(DateTime), MappingAction.Error,
serializer, out parsedType, out parsedArrayType);
Assert.AreEqual(new DateTime(2009, 2, 9, 21, 20, 01),
(DateTime)obj);
}
//---------------------- base64 ----------------------------------------//
byte[] testb = new Byte[]
{
121, 111, 117, 32, 99, 97, 110, 39, 116, 32, 114, 101, 97, 100,
32, 116, 104, 105, 115, 33 };
[Test]
public void Base64_NullType()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value><base64>eW91IGNhbid0IHJlYWQgdGhpcyE=</base64></value>";
object obj = Utils.Parse(xml, null, MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.IsTrue(obj is byte[], "result is array of byte");
byte[] ret = obj as byte[];
Assert.IsTrue(ret.Length == testb.Length);
for (int i = 0; i < testb.Length; i++)
Assert.IsTrue(testb[i] == ret[i]);
}
[Test]
public void Base64_Base64Type()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value><base64>eW91IGNhbid0IHJlYWQgdGhpcyE=</base64></value>";
object obj = Utils.Parse(xml, typeof(byte[]), MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.IsTrue(obj is byte[], "result is array of byte");
byte[] ret = obj as byte[];
Assert.IsTrue(ret.Length == testb.Length);
for (int i = 0; i < testb.Length; i++)
Assert.IsTrue(testb[i] == ret[i]);
}
[Test]
public void Base64_ObjectType()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value><base64>eW91IGNhbid0IHJlYWQgdGhpcyE=</base64></value>";
object obj = Utils.Parse(xml, typeof(object), MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.IsTrue(obj is byte[], "result is array of byte");
byte[] ret = obj as byte[];
Assert.IsTrue(ret.Length == testb.Length);
for (int i = 0; i < testb.Length; i++)
Assert.IsTrue(testb[i] == ret[i]);
}
//---------------------- array -----------------------------------------//
[Test]
public void MixedArray_NullType()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value>
<array>
<data>
<value><i4>12</i4></value>
<value><string>Egypt</string></value>
<value><boolean>0</boolean></value>
</data>
</array>
</value>";
object obj = Utils.Parse(xml, null, MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.IsTrue(obj is object[], "result is array of object");
object[] ret = obj as object[];
Assert.AreEqual(12, ret[0]);
Assert.AreEqual("Egypt", ret[1]);
Assert.AreEqual(false, ret[2]);
}
[Test]
public void MixedArray_ObjectArrayType()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value>
<array>
<data>
<value><i4>12</i4></value>
<value><string>Egypt</string></value>
<value><boolean>0</boolean></value>
</data>
</array>
</value>";
object obj = Utils.Parse(xml, typeof(object[]), MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.IsTrue(obj is object[], "result is array of object");
object[] ret = obj as object[];
Assert.AreEqual(12, ret[0]);
Assert.AreEqual("Egypt", ret[1]);
Assert.AreEqual(false, ret[2]);
}
[Test]
public void MixedArray_ObjectType()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value>
<array>
<data>
<value><i4>12</i4></value>
<value><string>Egypt</string></value>
<value><boolean>0</boolean></value>
</data>
</array>
</value>";
object obj = Utils.Parse(xml, typeof(object), MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.IsTrue(obj is object[], "result is array of object");
object[] ret = obj as object[];
Assert.AreEqual(12, ret[0]);
Assert.AreEqual("Egypt", ret[1]);
Assert.AreEqual(false, ret[2]);
}
[Test]
public void HomogArray_NullType()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value>
<array>
<data>
<value><i4>12</i4></value>
<value><i4>13</i4></value>
<value><i4>14</i4></value>
</data>
</array>
</value>";
object obj = Utils.Parse(xml, null, MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.IsTrue(obj is int[], "result is array of int");
int[] ret = obj as int[];
Assert.AreEqual(12, ret[0]);
Assert.AreEqual(13, ret[1]);
Assert.AreEqual(14, ret[2]);
}
[Test]
public void HomogArray_IntArrayType()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value>
<array>
<data>
<value><i4>12</i4></value>
<value><i4>13</i4></value>
<value><i4>14</i4></value>
</data>
</array>
</value>";
object obj = Utils.Parse(xml, typeof(int[]), MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.IsTrue(obj is int[], "result is array of int");
int[] ret = obj as int[];
Assert.AreEqual(12, ret[0]);
Assert.AreEqual(13, ret[1]);
Assert.AreEqual(14, ret[2]);
}
[Test]
public void HomogArray_ObjectArrayType()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value>
<array>
<data>
<value><i4>12</i4></value>
<value><i4>13</i4></value>
<value><i4>14</i4></value>
</data>
</array>
</value>";
object obj = Utils.Parse(xml, typeof(object[]), MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.IsTrue(obj is object[], "result is array of object");
object[] ret = obj as object[];
Assert.AreEqual(12, ret[0]);
Assert.AreEqual(13, ret[1]);
Assert.AreEqual(14, ret[2]);
}
[Test]
public void HomogArray_ObjectType()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value>
<array>
<data>
<value><i4>12</i4></value>
<value><i4>13</i4></value>
<value><i4>14</i4></value>
</data>
</array>
</value>";
object obj = Utils.Parse(xml, typeof(object), MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.IsTrue(obj is int[], "result is array of int");
int[] ret = obj as int[];
Assert.AreEqual(12, ret[0]);
Assert.AreEqual(13, ret[1]);
Assert.AreEqual(14, ret[2]);
}
//---------------------- XmlRpcInt -------------------------------------//
[Test]
public void XmlRpcInt_XmlRpcIntType()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?><value><int>12345</int></value>";
object obj = Utils.Parse(xml, typeof(XmlRpcInt), MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.IsInstanceOfType(typeof(XmlRpcInt), obj);
Assert.AreEqual(12345, (XmlRpcInt)obj);
}
//---------------------- XmlRpcBoolean ---------------------------------//
[Test]
public void XmlRpcBoolean_XmlRpcBooleanType()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value><boolean>1</boolean></value>";
object obj = Utils.Parse(xml, typeof(XmlRpcBoolean), MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.AreEqual(new XmlRpcBoolean(true), (XmlRpcBoolean)obj);
}
//---------------------- XmlRpcDouble ----------------------------------//
[Test]
public void XmlRpcDouble_XmlRpcDoubleType()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value><double>543.21</double></value>";
object obj = Utils.Parse(xml, typeof(XmlRpcDouble), MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.AreEqual(new XmlRpcDouble(543.21), (XmlRpcDouble)obj);
}
//---------------------- XmlRpcDateTime --------------------------------//
[Test]
public void XmlRpcDateTime_XmlRpcDateTimeType()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value><dateTime.iso8601>20020706T11:25:37</dateTime.iso8601></value>";
object obj = Utils.Parse(xml, typeof(XmlRpcDateTime), MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.AreEqual(
new XmlRpcDateTime(new DateTime(2002, 7, 6, 11, 25, 37)),
(XmlRpcDateTime)obj);
}
#if !FX1_0
//---------------------- int? -------------------------------------//
[Test]
public void nullableIntType()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?><value><int>12345</int></value>";
object obj = Utils.Parse(xml, typeof(int?), MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.IsInstanceOfType(typeof(int?), obj);
Assert.AreEqual(12345, obj);
}
//---------------------- bool? ---------------------------------//
[Test]
public void nullableBoolType()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value><boolean>1</boolean></value>";
object obj = Utils.Parse(xml, typeof(bool?), MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.AreEqual(true, obj);
}
//---------------------- double? ----------------------------------//
[Test]
public void nullableDoubleType()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value><double>543.21</double></value>";
object obj = Utils.Parse(xml, typeof(double?), MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.AreEqual(543.21, obj);
}
//---------------------- DateTime? --------------------------------//
[Test]
public void nullableDateTimeType()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value><dateTime.iso8601>20020706T11:25:37</dateTime.iso8601></value>";
object obj = Utils.Parse(xml, typeof(DateTime?), MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.AreEqual(new DateTime(2002, 7, 6, 11, 25, 37), obj);
}
#endif
//---------------------- XmlRpcStruct array ----------------------------//
[Test]
public void XmlRpcStructArray()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value>
<array>
<data>
<value>
<struct>
<member>
<name>mi</name>
<value><i4>18</i4></value>
</member>
</struct>
</value>
<value>
<struct>
<member>
<name>mi</name>
<value><i4>28</i4></value>
</member>
</struct>
</value>
</data>
</array>
</value>";
object obj = Utils.Parse(xml, null, MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.AreEqual(obj.GetType(), typeof(object[]));
object[] objarray = (object[])obj;
Assert.AreEqual(objarray[0].GetType(), typeof(XmlRpcStruct));
Assert.AreEqual(objarray[1].GetType(), typeof(XmlRpcStruct));
XmlRpcStruct xstruct1 = objarray[0] as XmlRpcStruct;
XmlRpcStruct xstruct2 = objarray[1] as XmlRpcStruct;
Assert.AreEqual(xstruct1["mi"], 18);
Assert.AreEqual(xstruct2["mi"], 28);
}
//---------------------- struct ------------------------------------------//
[Test]
[ExpectedException(typeof(XmlRpcInvalidXmlRpcException))]
public void NameEmptyString()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value>
<struct>
<member>
<name/>
<value><i4>18</i4></value>
</member>
</struct>
</value>";
object obj = Utils.Parse(xml, null, MappingAction.Error,
out parsedType, out parsedArrayType);
}
//------------------------------------------------------------------------//
struct Struct3
{
[XmlRpcMember("IntField")]
public int intOne;
[XmlRpcMember("IntProperty")]
public int intTwo { get { return _intTwo; } set { _intTwo = value; } }
private int _intTwo;
}
[Test]
public void PropertyXmlRpcName()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value>
<struct>
<member>
<name>IntField</name>
<value><i4>18</i4></value>
</member>
<member>
<name>IntProperty</name>
<value><i4>18</i4></value>
</member>
</struct>
</value>";
object obj = Utils.Parse(xml, typeof(Struct3), MappingAction.Error,
out parsedType, out parsedArrayType);
}
struct Struct4
{
[NonSerialized]
public int x;
public int y;
}
[Test]
public void IgnoreNonSerialized()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value>
<struct>
<member>
<name>y</name>
<value><i4>18</i4></value>
</member>
</struct>
</value>";
object obj = Utils.Parse(xml, typeof(Struct4), MappingAction.Error,
out parsedType, out parsedArrayType);
}
[Test]
[ExpectedException(typeof(XmlRpcNonSerializedMember))]
public void NonSerializedInStruct()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value>
<struct>
<member>
<name>x</name>
<value><i4>12</i4></value>
</member>
<member>
<name>y</name>
<value><i4>18</i4></value>
</member>
</struct>
</value>";
object obj = Utils.Parse(xml, typeof(Struct4), MappingAction.Error,
out parsedType, out parsedArrayType);
Struct4 ret = (Struct4)obj;
Assert.AreEqual(0, ret.x);
Assert.AreEqual(18, ret.y);
}
struct Struct5
{
public int x;
}
[Test]
public void UnexpectedMember()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value>
<struct>
<member>
<name>x</name>
<value><i4>12</i4></value>
</member>
<member>
<name>y</name>
<value><i4>18</i4></value>
</member>
</struct>
</value>";
object obj = Utils.Parse(xml, typeof(Struct5), MappingAction.Error,
out parsedType, out parsedArrayType);
}
struct Struct6
{
[NonSerialized]
public decimal x;
public int y;
}
[Test]
public void NonSerializedNonXmlRpcType()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value>
<struct>
<member>
<name>y</name>
<value><i4>18</i4></value>
</member>
</struct>
</value>";
object obj = Utils.Parse(xml, typeof(Struct4), MappingAction.Error,
out parsedType, out parsedArrayType);
Struct4 ret = (Struct4)obj;
Assert.AreEqual(0, ret.x);
Assert.AreEqual(18, ret.y);
}
[Test]
public void XmlRpcStructOrder()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value>
<struct>
<member>
<name>a</name>
<value><i4>1</i4></value>
</member>
<member>
<name>c</name>
<value><i4>3</i4></value>
</member>
<member>
<name>b</name>
<value><i4>2</i4></value>
</member>
</struct>
</value>";
object obj = Utils.Parse(xml, typeof(XmlRpcStruct), MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.IsInstanceOfType(typeof(XmlRpcStruct), obj);
XmlRpcStruct strct = obj as XmlRpcStruct;
IDictionaryEnumerator denumerator = strct.GetEnumerator();
denumerator.MoveNext();
Assert.AreEqual("a", denumerator.Key);
Assert.AreEqual(1, denumerator.Value);
denumerator.MoveNext();
Assert.AreEqual("c", denumerator.Key);
Assert.AreEqual(3, denumerator.Value);
denumerator.MoveNext();
Assert.AreEqual("b", denumerator.Key);
Assert.AreEqual(2, denumerator.Value);
}
class RecursiveMember
{
public string Level;
[XmlRpcMissingMapping(MappingAction.Ignore)]
public RecursiveMember childExample;
}
[Test]
public void RecursiveMemberTest()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value>
<struct>
<member>
<name>Level</name>
<value>1</value>
</member>
<member>
<name>childExample</name>
<value>
<struct>
<member>
<name>Level</name>
<value>2</value>
</member>
<member>
<name>childExample</name>
<value>
<struct>
<member>
<name>Level</name>
<value>3</value>
</member>
</struct>
</value>
</member>
</struct>
</value>
</member>
</struct>
</value>";
object obj = Utils.Parse(xml, typeof(RecursiveMember), MappingAction.Error,
out parsedType, out parsedArrayType);
RecursiveMember ret = (RecursiveMember)obj;
}
class RecursiveArrayMember
{
public string Level;
public RecursiveArrayMember[] childExamples;
}
[Test]
public void RecursiveArrayMemberTest()
{
Type parsedType, parsedArrayType;
string xml = @"<?xml version=""1.0"" ?>
<value>
<struct>
<member>
<name>Level</name>
<value>1</value>
</member>
<member>
<name>childExamples</name>
<value>
<array>
<data>
<value>
<struct>
<member>
<name>Level</name>
<value>1-1</value>
</member>
<member>
<name>childExamples</name>
<value>
<array>
<data>
<value>
<struct>
<member>
<name>Level</name>
<value>1-1-1</value>
</member>
<member>
<name>childExamples</name>
<value>
<array>
<data>
</data>
</array>
</value>
</member>
</struct>
</value>
<value>
<struct>
<member>
<name>Level</name>
<value>1-1-2</value>
</member>
<member>
<name>childExamples</name>
<value>
<array>
<data>
</data>
</array>
</value>
</member>
</struct>
</value>
</data>
</array>
</value>
</member>
</struct>
</value>
<value>
<struct>
<member>
<name>Level</name>
<value>1-2</value>
</member>
<member>
<name>childExamples</name>
<value>
<array>
<data>
<value>
<struct>
<member>
<name>Level</name>
<value>1-2-1</value>
</member>
<member>
<name>childExamples</name>
<value>
<array>
<data>
</data>
</array>
</value>
</member>
</struct>
</value>
<value>
<struct>
<member>
<name>Level</name>
<value>1-2-2</value>
</member>
<member>
<name>childExamples</name>
<value>
<array>
<data>
</data>
</array>
</value>
</member>
</struct>
</value>
</data>
</array>
</value>
</member>
</struct>
</value>
</data>
</array>
</value>
</member>
</struct>
</value>";
object obj = Utils.Parse(xml, typeof(RecursiveArrayMember), MappingAction.Error,
out parsedType, out parsedArrayType);
RecursiveArrayMember ret = (RecursiveArrayMember)obj;
}
}
}
| |
// 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 Test.Cryptography;
using Xunit;
namespace System.Security.Cryptography.X509Certificates.Tests
{
public static class X500DistinguishedNameTests
{
[Fact]
public static void PrintInvalidEncoding()
{
// One byte has been removed from the payload here. Since DER is length-prepended
// this will run out of data too soon, and report as invalid.
byte[] encoded = "3017311530130603550403130C436F6D6D6F6E204E616D65".HexToByteArray();
X500DistinguishedName dn = new X500DistinguishedName(encoded);
Assert.Equal("", dn.Decode(X500DistinguishedNameFlags.None));
}
[Fact]
[ActiveIssue(3892, TestPlatforms.AnyUnix)]
public static void PrintMultiComponentRdn()
{
byte[] encoded = (
"30223120300C060355040313054A616D65733010060355040A13094D6963726F" +
"736F6674").HexToByteArray();
const string expected = "CN=James + O=Microsoft";
X500DistinguishedName dn = new X500DistinguishedName(encoded);
Assert.Equal(expected, dn.Decode(X500DistinguishedNameFlags.None));
// It should not change ordering when reversed, since the two are one unit.
Assert.Equal(expected, dn.Decode(X500DistinguishedNameFlags.Reversed));
}
[Fact]
public static void PrintUnknownOidRdn()
{
byte[] encoded = (
"30183116301406052901020203130B496E76616C6964204F6964").HexToByteArray();
X500DistinguishedName dn = new X500DistinguishedName(encoded);
Assert.Equal("OID.1.1.1.2.2.3=Invalid Oid", dn.Decode(X500DistinguishedNameFlags.None));
}
[Theory]
[MemberData(nameof(WhitespaceBeforeCases))]
public static void QuoteWhitespaceBefore(string expected, string hexEncoded)
{
byte[] encoded = hexEncoded.HexToByteArray();
X500DistinguishedName dn = new X500DistinguishedName(encoded);
Assert.Equal(expected, dn.Decode(X500DistinguishedNameFlags.None));
}
[Theory]
[MemberData(nameof(WhitespaceBeforeCases))]
public static void NoQuoteWhitespaceBefore(string expectedQuoted, string hexEncoded)
{
string expected = expectedQuoted.Replace("\"", "");
byte[] encoded = hexEncoded.HexToByteArray();
X500DistinguishedName dn = new X500DistinguishedName(encoded);
Assert.Equal(expected, dn.Decode(X500DistinguishedNameFlags.DoNotUseQuotes));
}
[Theory]
[MemberData(nameof(WhitespaceAfterCases))]
public static void QuoteWhitespaceAfter(string expected, string hexEncoded)
{
byte[] encoded = hexEncoded.HexToByteArray();
X500DistinguishedName dn = new X500DistinguishedName(encoded);
Assert.Equal(expected, dn.Decode(X500DistinguishedNameFlags.None));
}
[Theory]
[MemberData(nameof(WhitespaceAfterCases))]
public static void NoQuoteWhitespaceAfter(string expectedQuoted, string hexEncoded)
{
string expected = expectedQuoted.Replace("\"", "");
byte[] encoded = hexEncoded.HexToByteArray();
X500DistinguishedName dn = new X500DistinguishedName(encoded);
Assert.Equal(expected, dn.Decode(X500DistinguishedNameFlags.DoNotUseQuotes));
}
[Theory]
[MemberData(nameof(QuotedContentsCases))]
public static void QuoteByContents(string expected, string hexEncoded)
{
byte[] encoded = hexEncoded.HexToByteArray();
X500DistinguishedName dn = new X500DistinguishedName(encoded);
Assert.Equal(expected, dn.Decode(X500DistinguishedNameFlags.None));
}
[Theory]
[MemberData(nameof(QuotedContentsCases))]
public static void NoQuoteByContents(string expectedQuoted, string hexEncoded)
{
string expected = expectedQuoted.Replace("\"", "");
byte[] encoded = hexEncoded.HexToByteArray();
X500DistinguishedName dn = new X500DistinguishedName(encoded);
Assert.Equal(expected, dn.Decode(X500DistinguishedNameFlags.DoNotUseQuotes));
}
[Theory]
[MemberData(nameof(InternallyQuotedRDNs))]
public static void QuotedWithQuotes(string quoted, string notQuoted, string hexEncoded)
{
byte[] encoded = hexEncoded.HexToByteArray();
X500DistinguishedName dn = new X500DistinguishedName(encoded);
Assert.Equal(quoted, dn.Decode(X500DistinguishedNameFlags.None));
}
[Theory]
[MemberData(nameof(InternallyQuotedRDNs))]
public static void NotQuotedWithQuotes(string quoted, string notQuoted, string hexEncoded)
{
byte[] encoded = hexEncoded.HexToByteArray();
X500DistinguishedName dn = new X500DistinguishedName(encoded);
Assert.Equal(notQuoted, dn.Decode(X500DistinguishedNameFlags.DoNotUseQuotes));
}
[Fact]
public static void PrintComplexReversed()
{
byte[] encoded = MicrosoftDotComSubject.HexToByteArray();
X500DistinguishedName dn = new X500DistinguishedName(encoded);
const string expected =
"CN=www.microsoft.com, OU=MSCOM, O=Microsoft Corporation, STREET=1 Microsoft Way, " +
"L=Redmond, S=Washington, PostalCode=98052, C=US, SERIALNUMBER=600413485, ";
// Windows 8.1 would continue the string with some unknown OIDs, but OpenSSL 1.0.1 can decode
// at least businessCategory (2.5.4.15), and other Windows versions may do so in the future.
// "OID.2.5.4.15=Private Organization, OID.1.3.6.1.4.1.311.60.2.1.2=Washington, " +
// "OID.1.3.6.1.4.1.311.60.2.1.3=US";
Assert.StartsWith(expected, dn.Decode(X500DistinguishedNameFlags.Reversed), StringComparison.Ordinal);
}
[Fact]
public static void PrintComplexForwards()
{
byte[] encoded = MicrosoftDotComSubject.HexToByteArray();
X500DistinguishedName dn = new X500DistinguishedName(encoded);
const string expected =
", SERIALNUMBER=600413485, C=US, PostalCode=98052, S=Washington, L=Redmond, " +
"STREET=1 Microsoft Way, O=Microsoft Corporation, OU=MSCOM, CN=www.microsoft.com";
Assert.EndsWith(expected, dn.Decode(X500DistinguishedNameFlags.None), StringComparison.Ordinal);
}
public static readonly object[][] WhitespaceBeforeCases =
{
// Regular space.
new object[]
{
"CN=\" Common Name\"",
"3017311530130603550403130C20436F6D6D6F6E204E616D65"
},
// Tab
new object[]
{
"CN=\"\tCommon Name\"",
"30233121301F06035504031E1800090043006F006D006D006F006E0020004E00" +
"61006D0065"
},
// Newline
new object[]
{
"CN=\"\nCommon Name\"",
"30233121301F06035504031E18000A0043006F006D006D006F006E0020004E00" +
"61006D0065"
},
// xUnit doesn't like \v in Assert.Equals, reports it as an invalid character.
//new object[]
//{
// "CN=\"\vCommon Name\"",
// "30233121301F06035504031E18000B0043006F006D006D006F006E0020004E00" +
// "61006D0065"
//},
// xUnit doesn't like FormFeed in Assert.Equals, reports it as an invalid character.
//new object[]
//{
// "CN=\"\u000cCommon Name\"",
// "30233121301F06035504031E18000C0043006F006D006D006F006E0020004E00" +
// "61006D0065"
//},
// Carriage return
new object[]
{
"CN=\"\rCommon Name\"",
"30233121301F06035504031E18000D0043006F006D006D006F006E0020004E00" +
"61006D0065"
},
// em quad. This is char.IsWhitespace, but is not quoted.
new object[]
{
"CN=\u2002Common Name",
"30233121301F06035504031E1820020043006F006D006D006F006E0020004E00" +
"61006D0065"
},
};
public static readonly object[][] WhitespaceAfterCases =
{
// Regular space.
new object[]
{
"CN=\"Common Name \"",
"3017311530130603550403130C436F6D6D6F6E204E616D6520"
},
// Newline
new object[]
{
"CN=\"Common Name\t\"",
"30233121301F06035504031E180043006F006D006D006F006E0020004E006100" +
"6D00650009"
},
// Newline
new object[]
{
"CN=\"Common Name\n\"",
"30233121301F06035504031E180043006F006D006D006F006E0020004E006100" +
"6D0065000A"
},
// xUnit doesn't like \v in Assert.Equals, reports it as an invalid character.
//new object[]
//{
// "CN=\"Common Name\v\"",
// "30233121301F06035504031E180043006F006D006D006F006E0020004E006100" +
// "6D0065000B"
//},
// xUnit doesn't like FormFeed in Assert.Equals, reports it as an invalid character.
//new object[]
//{
// "CN=\"Common Name\u000c\"",
// "30233121301F06035504031E180043006F006D006D006F006E0020004E006100" +
// "6D0065000C"
//},
// Carriage return
new object[]
{
"CN=\"Common Name\r\"",
"30233121301F06035504031E180043006F006D006D006F006E0020004E006100" +
"6D0065000D"
},
// em quad. This is char.IsWhitespace, but is not quoted.
new object[]
{
"CN=Common Name\u2002",
"30233121301F06035504031E180043006F006D006D006F006E0020004E006100" +
"6D00652002"
},
};
public static readonly object[][] QuotedContentsCases =
{
// Empty value
new object[]
{
"CN=\"\"",
"300B3109300706035504031300"
},
// Comma (RDN separator)
new object[]
{
"CN=\"Common,Name\"",
"3016311430120603550403130B436F6D6D6F6E2C4E616D65"
},
// Plus (RDN component separator)
new object[]
{
"CN=\"Common+Name\"",
"3016311430120603550403130B436F6D6D6F6E2B4E616D65"
},
// Equal (Key/Value separator)
new object[]
{
"CN=\"Common=Name\"",
"3016311430120603550403130B436F6D6D6F6E3D4E616D65"
},
// Note: Double Quote has been removed from this set, it's a dedicated test suite.
// Newline
new object[]
{
"CN=\"Common\nName\"",
"3021311F301D06035504031E160043006F006D006D006F006E000A004E006100" +
"6D0065"
},
// Carriage return is NOT quoted.
new object[]
{
"CN=Common\rName",
"3021311F301D06035504031E160043006F006D006D006F006E000D004E006100" +
"6D0065"
},
// Less-than
new object[]
{
"CN=\"Common<Name\"",
"3021311F301D06035504031E160043006F006D006D006F006E003C004E006100" +
"6D0065"
},
// Greater-than
new object[]
{
"CN=\"Common>Name\"",
"3021311F301D06035504031E160043006F006D006D006F006E003E004E006100" +
"6D0065"
},
// Octothorpe (Number Sign, Pound, Hash, whatever)
new object[]
{
"CN=\"Common#Name\"",
"3021311F301D06035504031E160043006F006D006D006F006E0023004E006100" +
"6D0065"
},
// Semi-colon
new object[]
{
"CN=\"Common;Name\"",
"3021311F301D06035504031E160043006F006D006D006F006E003B004E006100" +
"6D0065"
},
};
public static readonly object[][] InternallyQuotedRDNs =
{
// Interior Double Quote
new object[]
{
"CN=\"Common\"\"Name\"", // Quoted
"CN=Common\"Name", // Not-Quoted
"3021311F301D06035504031E160043006F006D006D006F006E0022004E006100" +
"6D0065"
},
// Starts with a double quote
new object[]
{
"CN=\"\"\"Common Name\"", // Quoted
"CN=\"Common Name", // Not-Quoted
"30233121301F06035504031E1800220043006F006D006D006F006E0020004E00" +
"61006D0065"
},
// Ends with a double quote
new object[]
{
"CN=\"Common Name\"\"\"", // Quoted
"CN=Common Name\"", // Not-Quoted
"30233121301F06035504031E180043006F006D006D006F006E0020004E006100" +
"6D00650022"
},
};
private const string MicrosoftDotComSubject =
"3082010F31133011060B2B0601040182373C02010313025553311B3019060B2B" +
"0601040182373C0201020C0A57617368696E67746F6E311D301B060355040F13" +
"1450726976617465204F7267616E697A6174696F6E3112301006035504051309" +
"363030343133343835310B3009060355040613025553310E300C06035504110C" +
"0539383035323113301106035504080C0A57617368696E67746F6E3110300E06" +
"035504070C075265646D6F6E643118301606035504090C0F31204D6963726F73" +
"6F667420576179311E301C060355040A0C154D6963726F736F667420436F7270" +
"6F726174696F6E310E300C060355040B0C054D53434F4D311A30180603550403" +
"0C117777772E6D6963726F736F66742E636F6D";
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
namespace System.Collections.ObjectModel
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime;
[Serializable]
[System.Runtime.InteropServices.ComVisible(false)]
[DebuggerTypeProxy(typeof(Mscorlib_CollectionDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
public class ReadOnlyCollection<T>: IList<T>, IList, IReadOnlyList<T>
{
IList<T> list;
[NonSerialized]
private Object _syncRoot;
public ReadOnlyCollection(IList<T> list) {
if (list == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.list);
}
this.list = list;
}
public int Count {
get { return list.Count; }
}
public T this[int index] {
get { return list[index]; }
}
public bool Contains(T value) {
return list.Contains(value);
}
public void CopyTo(T[] array, int index) {
list.CopyTo(array, index);
}
public IEnumerator<T> GetEnumerator() {
return list.GetEnumerator();
}
public int IndexOf(T value) {
return list.IndexOf(value);
}
protected IList<T> Items {
get {
return list;
}
}
bool ICollection<T>.IsReadOnly {
get { return true; }
}
T IList<T>.this[int index] {
get { return list[index]; }
set {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
}
void ICollection<T>.Add(T value) {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
void ICollection<T>.Clear() {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
void IList<T>.Insert(int index, T value) {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
bool ICollection<T>.Remove(T value) {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
return false;
}
void IList<T>.RemoveAt(int index) {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
IEnumerator IEnumerable.GetEnumerator() {
return ((IEnumerable)list).GetEnumerator();
}
bool ICollection.IsSynchronized {
get { return false; }
}
object ICollection.SyncRoot {
get {
if( _syncRoot == null) {
ICollection c = list as ICollection;
if( c != null) {
_syncRoot = c.SyncRoot;
}
else {
System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
}
return _syncRoot;
}
}
void ICollection.CopyTo(Array array, int index) {
if (array==null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (array.Rank != 1) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
}
if( array.GetLowerBound(0) != 0 ) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound);
}
if (index < 0) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.arrayIndex, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
if (array.Length - index < Count) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
T[] items = array as T[];
if (items != null) {
list.CopyTo(items, index);
}
else {
//
// Catch the obvious case assignment will fail.
// We can found all possible problems by doing the check though.
// For example, if the element type of the Array is derived from T,
// we can't figure out if we can successfully copy the element beforehand.
//
Type targetType = array.GetType().GetElementType();
Type sourceType = typeof(T);
if(!(targetType.IsAssignableFrom(sourceType) || sourceType.IsAssignableFrom(targetType))) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType);
}
//
// We can't cast array of value type to object[], so we don't support
// widening of primitive types here.
//
object[] objects = array as object[];
if( objects == null) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType);
}
int count = list.Count;
try {
for (int i = 0; i < count; i++) {
objects[index++] = list[i];
}
}
catch(ArrayTypeMismatchException) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType);
}
}
}
bool IList.IsFixedSize {
get { return true; }
}
bool IList.IsReadOnly {
get { return true; }
}
object IList.this[int index] {
get { return list[index]; }
set {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
}
int IList.Add(object value) {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
return -1;
}
void IList.Clear() {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
private static bool IsCompatibleObject(object value) {
// Non-null values are fine. Only accept nulls if T is a class or Nullable<U>.
// Note that default(T) is not equal to null for value types except when T is Nullable<U>.
return ((value is T) || (value == null && default(T) == null));
}
bool IList.Contains(object value) {
if(IsCompatibleObject(value)) {
return Contains((T) value);
}
return false;
}
int IList.IndexOf(object value) {
if(IsCompatibleObject(value)) {
return IndexOf((T)value);
}
return -1;
}
void IList.Insert(int index, object value) {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
void IList.Remove(object value) {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
void IList.RemoveAt(int index) {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
}
}
| |
/*
* Author Luke Campbell <LCampbell@asascience.com>
* com.asascience.netcdf4.NcException
*/
namespace ASA.NetCDF4.exceptions {
public class NcException : System.Exception{
public NcException() : base() {
}
public NcException(string message) : base(message) {
}
public NcException(string message, System.Exception inner) : base(message, inner) {
}
protected NcException(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcBadId : NcException {
public NcBadId() : base() {
}
public NcBadId(string message) : base(message) {
}
public NcBadId(string message, System.Exception inner) : base(message, inner) {
}
protected NcBadId(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcNFile : NcException {
public NcNFile() : base() {
}
public NcNFile(string message) : base(message) {
}
public NcNFile(string message, System.Exception inner) : base(message, inner) {
}
protected NcNFile(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcExist : NcException {
public NcExist() : base() {
}
public NcExist(string message) : base(message) {
}
public NcExist(string message, System.Exception inner) : base(message, inner) {
}
protected NcExist(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcInvalidArg : NcException {
public NcInvalidArg() : base() {
}
public NcInvalidArg(string message) : base(message) {
}
public NcInvalidArg(string message, System.Exception inner) : base(message, inner) {
}
protected NcInvalidArg(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcInvalidWrite : NcException {
public NcInvalidWrite() : base() {
}
public NcInvalidWrite(string message) : base(message) {
}
public NcInvalidWrite(string message, System.Exception inner) : base(message, inner) {
}
protected NcInvalidWrite(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcNotInDefineMode : NcException {
public NcNotInDefineMode() : base() {
}
public NcNotInDefineMode(string message) : base(message) {
}
public NcNotInDefineMode(string message, System.Exception inner) : base(message, inner) {
}
protected NcNotInDefineMode(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcInDefineMode : NcException {
public NcInDefineMode() : base() {
}
public NcInDefineMode(string message) : base(message) {
}
public NcInDefineMode(string message, System.Exception inner) : base(message, inner) {
}
protected NcInDefineMode(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcInvalidCoords : NcException {
public NcInvalidCoords() : base() {
}
public NcInvalidCoords(string message) : base(message) {
}
public NcInvalidCoords(string message, System.Exception inner) : base(message, inner) {
}
protected NcInvalidCoords(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcMaxDims : NcException {
public NcMaxDims() : base() {
}
public NcMaxDims(string message) : base(message) {
}
public NcMaxDims(string message, System.Exception inner) : base(message, inner) {
}
protected NcMaxDims(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcNameInUse : NcException {
public NcNameInUse() : base() {
}
public NcNameInUse(string message) : base(message) {
}
public NcNameInUse(string message, System.Exception inner) : base(message, inner) {
}
protected NcNameInUse(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcNotAtt : NcException {
public NcNotAtt() : base() {
}
public NcNotAtt(string message) : base(message) {
}
public NcNotAtt(string message, System.Exception inner) : base(message, inner) {
}
protected NcNotAtt(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcMaxAtts : NcException {
public NcMaxAtts() : base() {
}
public NcMaxAtts(string message) : base(message) {
}
public NcMaxAtts(string message, System.Exception inner) : base(message, inner) {
}
protected NcMaxAtts(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcBadType : NcException {
public NcBadType() : base() {
}
public NcBadType(string message) : base(message) {
}
public NcBadType(string message, System.Exception inner) : base(message, inner) {
}
protected NcBadType(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcBadDim : NcException {
public NcBadDim() : base() {
}
public NcBadDim(string message) : base(message) {
}
public NcBadDim(string message, System.Exception inner) : base(message, inner) {
}
protected NcBadDim(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcUnlimPos : NcException {
public NcUnlimPos() : base() {
}
public NcUnlimPos(string message) : base(message) {
}
public NcUnlimPos(string message, System.Exception inner) : base(message, inner) {
}
protected NcUnlimPos(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcMaxVars : NcException {
public NcMaxVars() : base() {
}
public NcMaxVars(string message) : base(message) {
}
public NcMaxVars(string message, System.Exception inner) : base(message, inner) {
}
protected NcMaxVars(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcNotVar : NcException {
public NcNotVar() : base() {
}
public NcNotVar(string message) : base(message) {
}
public NcNotVar(string message, System.Exception inner) : base(message, inner) {
}
protected NcNotVar(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcGlobal : NcException {
public NcGlobal() : base() {
}
public NcGlobal(string message) : base(message) {
}
public NcGlobal(string message, System.Exception inner) : base(message, inner) {
}
protected NcGlobal(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcNotNCF : NcException {
public NcNotNCF() : base() {
}
public NcNotNCF(string message) : base(message) {
}
public NcNotNCF(string message, System.Exception inner) : base(message, inner) {
}
protected NcNotNCF(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcSts : NcException {
public NcSts() : base() {
}
public NcSts(string message) : base(message) {
}
public NcSts(string message, System.Exception inner) : base(message, inner) {
}
protected NcSts(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcMaxName : NcException {
public NcMaxName() : base() {
}
public NcMaxName(string message) : base(message) {
}
public NcMaxName(string message, System.Exception inner) : base(message, inner) {
}
protected NcMaxName(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcUnlimit : NcException {
public NcUnlimit() : base() {
}
public NcUnlimit(string message) : base(message) {
}
public NcUnlimit(string message, System.Exception inner) : base(message, inner) {
}
protected NcUnlimit(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcNoRecVars : NcException {
public NcNoRecVars() : base() {
}
public NcNoRecVars(string message) : base(message) {
}
public NcNoRecVars(string message, System.Exception inner) : base(message, inner) {
}
protected NcNoRecVars(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcChar : NcException {
public NcChar() : base() {
}
public NcChar(string message) : base(message) {
}
public NcChar(string message, System.Exception inner) : base(message, inner) {
}
protected NcChar(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcEdge : NcException {
public NcEdge() : base() {
}
public NcEdge(string message) : base(message) {
}
public NcEdge(string message, System.Exception inner) : base(message, inner) {
}
protected NcEdge(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcStride : NcException {
public NcStride() : base() {
}
public NcStride(string message) : base(message) {
}
public NcStride(string message, System.Exception inner) : base(message, inner) {
}
protected NcStride(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcBadName : NcException {
public NcBadName() : base() {
}
public NcBadName(string message) : base(message) {
}
public NcBadName(string message, System.Exception inner) : base(message, inner) {
}
protected NcBadName(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcRange : NcException {
public NcRange() : base() {
}
public NcRange(string message) : base(message) {
}
public NcRange(string message, System.Exception inner) : base(message, inner) {
}
protected NcRange(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcNoMem : NcException {
public NcNoMem() : base() {
}
public NcNoMem(string message) : base(message) {
}
public NcNoMem(string message, System.Exception inner) : base(message, inner) {
}
protected NcNoMem(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcVarSize : NcException {
public NcVarSize() : base() {
}
public NcVarSize(string message) : base(message) {
}
public NcVarSize(string message, System.Exception inner) : base(message, inner) {
}
protected NcVarSize(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcDimSize : NcException {
public NcDimSize() : base() {
}
public NcDimSize(string message) : base(message) {
}
public NcDimSize(string message, System.Exception inner) : base(message, inner) {
}
protected NcDimSize(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcTrunc : NcException {
public NcTrunc() : base() {
}
public NcTrunc(string message) : base(message) {
}
public NcTrunc(string message, System.Exception inner) : base(message, inner) {
}
protected NcTrunc(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcHdfErr : NcException {
public NcHdfErr() : base() {
}
public NcHdfErr(string message) : base(message) {
}
public NcHdfErr(string message, System.Exception inner) : base(message, inner) {
}
protected NcHdfErr(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcCantRead : NcException {
public NcCantRead() : base() {
}
public NcCantRead(string message) : base(message) {
}
public NcCantRead(string message, System.Exception inner) : base(message, inner) {
}
protected NcCantRead(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcCantWrite : NcException {
public NcCantWrite() : base() {
}
public NcCantWrite(string message) : base(message) {
}
public NcCantWrite(string message, System.Exception inner) : base(message, inner) {
}
protected NcCantWrite(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcCantCreate : NcException {
public NcCantCreate() : base() {
}
public NcCantCreate(string message) : base(message) {
}
public NcCantCreate(string message, System.Exception inner) : base(message, inner) {
}
protected NcCantCreate(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcFileMeta : NcException {
public NcFileMeta() : base() {
}
public NcFileMeta(string message) : base(message) {
}
public NcFileMeta(string message, System.Exception inner) : base(message, inner) {
}
protected NcFileMeta(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcDimMeta : NcException {
public NcDimMeta() : base() {
}
public NcDimMeta(string message) : base(message) {
}
public NcDimMeta(string message, System.Exception inner) : base(message, inner) {
}
protected NcDimMeta(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcAttMeta : NcException {
public NcAttMeta() : base() {
}
public NcAttMeta(string message) : base(message) {
}
public NcAttMeta(string message, System.Exception inner) : base(message, inner) {
}
protected NcAttMeta(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcVarMeta : NcException {
public NcVarMeta() : base() {
}
public NcVarMeta(string message) : base(message) {
}
public NcVarMeta(string message, System.Exception inner) : base(message, inner) {
}
protected NcVarMeta(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcNoCompound : NcException {
public NcNoCompound() : base() {
}
public NcNoCompound(string message) : base(message) {
}
public NcNoCompound(string message, System.Exception inner) : base(message, inner) {
}
protected NcNoCompound(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcAttExists : NcException {
public NcAttExists() : base() {
}
public NcAttExists(string message) : base(message) {
}
public NcAttExists(string message, System.Exception inner) : base(message, inner) {
}
protected NcAttExists(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcNotNc4 : NcException {
public NcNotNc4() : base() {
}
public NcNotNc4(string message) : base(message) {
}
public NcNotNc4(string message, System.Exception inner) : base(message, inner) {
}
protected NcNotNc4(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcStrictNc3 : NcException {
public NcStrictNc3() : base() {
}
public NcStrictNc3(string message) : base(message) {
}
public NcStrictNc3(string message, System.Exception inner) : base(message, inner) {
}
protected NcStrictNc3(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcBadGroupId : NcException {
public NcBadGroupId() : base() {
}
public NcBadGroupId(string message) : base(message) {
}
public NcBadGroupId(string message, System.Exception inner) : base(message, inner) {
}
protected NcBadGroupId(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcBadTypeId : NcException {
public NcBadTypeId() : base() {
}
public NcBadTypeId(string message) : base(message) {
}
public NcBadTypeId(string message, System.Exception inner) : base(message, inner) {
}
protected NcBadTypeId(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcBadFieldId : NcException {
public NcBadFieldId() : base() {
}
public NcBadFieldId(string message) : base(message) {
}
public NcBadFieldId(string message, System.Exception inner) : base(message, inner) {
}
protected NcBadFieldId(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcUnknownName : NcException {
public NcUnknownName() : base() {
}
public NcUnknownName(string message) : base(message) {
}
public NcUnknownName(string message, System.Exception inner) : base(message, inner) {
}
protected NcUnknownName(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcEnoGrp : NcException {
public NcEnoGrp() : base() {
}
public NcEnoGrp(string message) : base(message) {
}
public NcEnoGrp(string message, System.Exception inner) : base(message, inner) {
}
protected NcEnoGrp(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcNullGrp : NcException {
public NcNullGrp() : base() {
}
public NcNullGrp(string message) : base(message) {
}
public NcNullGrp(string message, System.Exception inner) : base(message, inner) {
}
protected NcNullGrp(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcNullType : NcException {
public NcNullType() : base() {
}
public NcNullType(string message) : base(message) {
}
public NcNullType(string message, System.Exception inner) : base(message, inner) {
}
protected NcNullType(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcNullDim : NcException {
public NcNullDim() : base() {
}
public NcNullDim(string message) : base(message) {
}
public NcNullDim(string message, System.Exception inner) : base(message, inner) {
}
protected NcNullDim(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcNullVar : NcException {
public NcNullVar() : base() {
}
public NcNullVar(string message) : base(message) {
}
public NcNullVar(string message, System.Exception inner) : base(message, inner) {
}
protected NcNullVar(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcNullAtt : NcException {
public NcNullAtt() : base() {
}
public NcNullAtt(string message) : base(message) {
}
public NcNullAtt(string message, System.Exception inner) : base(message, inner) {
}
protected NcNullAtt(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcElateDef : NcException {
public NcElateDef() : base() {
}
public NcElateDef(string message) : base(message) {
}
public NcElateDef(string message, System.Exception inner) : base(message, inner) {
}
protected NcElateDef(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcBufferOverflow : NcException {
public NcBufferOverflow() : base() {
}
public NcBufferOverflow(string message) : base(message) {
}
public NcBufferOverflow(string message, System.Exception inner) : base(message, inner) {
}
protected NcBufferOverflow(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
public class NcDimUnlimited : NcException {
public NcDimUnlimited() : base() {
}
public NcDimUnlimited(string message) : base(message) {
}
public NcDimUnlimited(string message, System.Exception inner) : base(message, inner) {
}
protected NcDimUnlimited(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {
}
}
}
| |
/*
Copyright (c) 2014, RMIT Training
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of CounterCompliance nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#region
using System;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
#endregion
namespace RMIT.Counter.Libraries.Library.Common
{
/// <summary>
/// Helper class for Ad-hoc database communication
/// </summary>
public class SqlHelper : IDisposable
{
//Command TimeOut Default value is 20 second
public int CommandTimeout = 30;
#region Properties and construtors
/// <summary>
/// The connection instance
/// </summary>
public SqlConnection Connection { get; private set; }
/// <summary>
/// Gets the transaction.
/// </summary>
/// <value>
/// The transaction.
/// </value>
public SqlTransaction Transaction { get; private set; }
#endregion
#region Object Life cycle
/// <summary>
/// Initializes a new instance of the <see cref="SqlHelper" /> class.
/// </summary>
/// <param name="connectionString">The connection string.</param>
public SqlHelper(string connectionString)
{
Connection = new SqlConnection(connectionString);
Connection.Open();
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
if (Transaction != null)
Transaction.Dispose();
if (Connection == null)
return;
if (Connection.State == ConnectionState.Open)
Connection.Close();
Connection.Dispose();
Connection = null;
}
#endregion
#region Transactions
/// <summary>
/// Begins the transaction.
/// </summary>
public void BeginTransaction()
{
Transaction = Connection.BeginTransaction();
}
/// <summary>
/// Rollbacks this instance.
/// </summary>
public void Rollback()
{
Transaction.Rollback();
}
/// <summary>
/// Commits this instance.
/// </summary>
public void Commit()
{
Transaction.Commit();
}
#endregion
#region Methods
/// <summary>
/// Executes the data set.
/// </summary>
/// <param name="commandText">The command text.</param>
/// <param name="commandType">Type of the command.</param>
/// <param name="parameters">The parameters.</param>
/// <returns></returns>
public DataSet ExecuteDataSet(string commandText, CommandType commandType = CommandType.Text,
params SqlParameter[] parameters)
{
var ds = new DataSet();
using (var adapter = new SqlDataAdapter(commandText, Connection))
{
adapter.SelectCommand.Transaction = Transaction;
adapter.SelectCommand.CommandType = commandType;
adapter.SelectCommand.Parameters.AddRange(parameters);
adapter.SelectCommand.CommandTimeout = CommandTimeout;
adapter.Fill(ds);
}
return ds;
}
/// <summary>
/// Executes the non query.
/// </summary>
/// <param name="commandText">The command text.</param>
/// <param name="commandType">Type of the command.</param>
/// <param name="parameters">The parameters.</param>
/// <returns></returns>
public int ExecuteNonQuery(string commandText, CommandType commandType = CommandType.Text,
params SqlParameter[] parameters)
{
using (var command = new SqlCommand(commandText, Connection, Transaction) {CommandType = commandType})
{
command.Parameters.AddRange(parameters);
command.CommandTimeout = CommandTimeout;
return command.ExecuteNonQuery();
}
}
/// <summary>
/// Executes the scalar.
/// </summary>
/// <param name="commandText">The command text.</param>
/// <param name="commandType">Type of the command.</param>
/// <param name="parameters">The parameters.</param>
/// <returns></returns>
public object ExecuteScalar(string commandText, CommandType commandType = CommandType.Text,
params SqlParameter[] parameters)
{
using (var command = new SqlCommand(commandText, Connection, Transaction) {CommandType = commandType})
{
command.Parameters.AddRange(parameters);
command.CommandTimeout = CommandTimeout;
return command.ExecuteScalar();
}
}
/// <summary>
/// Executes the reader.
/// </summary>
/// <param name="commandType">Type of the command.</param>
/// <param name="commandText">The command text.</param>
/// <param name="parameters">The parameters.</param>
/// <returns></returns>
/// <remarks>You have to close connection yourself</remarks>
public SqlDataReader ExecuteReader(string commandText, CommandType commandType = CommandType.Text,
params SqlParameter[] parameters)
{
var command = new SqlCommand(commandText, Connection, Transaction)
{
CommandType = commandType,
CommandTimeout = CommandTimeout
};
command.Parameters.AddRange(parameters);
return command.ExecuteReader();
}
#endregion
#region Helpers
/// <summary>
/// Values the specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <returns></returns>
public static object Value(string value)
{
return string.IsNullOrEmpty(value) ? DBNull.Value : (object) value;
}
public static bool ToBoolean(object o, bool defaultValue = false)
{
return o is bool ? (bool) o : defaultValue;
}
/// <summary>
/// Bulk inserts data.
/// </summary>
/// <param name="bulkDataLoadTimeout">The bulk data load timeout.</param>
/// <param name="dataTable">The data table.</param>
/// <param name="bulkCopyOption">The bulk copy option.</param>
/// <returns></returns>
public bool BulkInsert(int bulkDataLoadTimeout, DataTable dataTable,
SqlBulkCopyOptions bulkCopyOption = SqlBulkCopyOptions.Default)
{
var watch = Stopwatch.StartNew();
try
{
//Do this in a transaction
BeginTransaction();
using (var s = new SqlBulkCopy(Connection, bulkCopyOption, Transaction))
{
s.DestinationTableName = dataTable.TableName;
s.BulkCopyTimeout = bulkDataLoadTimeout;
foreach (var column in dataTable.Columns)
s.ColumnMappings.Add(column.ToString(), column.ToString());
s.WriteToServer(dataTable);
}
Commit();
}
catch (Exception ex)
{
Trace.TraceError(ex.Message);
Trace.TraceError(ex.StackTrace);
Rollback();
throw;
}
watch.Stop();
Trace.TraceInformation("Took {0} to bulk load data of {1} records to table {2}", watch.Elapsed,
dataTable.Rows.Count, dataTable.TableName);
return true;
}
#endregion
}
}
| |
/*
MIT License
Copyright (c) 2017 Saied Zarrinmehr
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SpatialAnalysis.Optimization;
using System.CodeDom.Compiler;
using SpatialAnalysis.Interoperability;
namespace SpatialAnalysis.Data
{
/// <summary>
/// Enum AgentParameters
/// </summary>
public enum AgentParameters
{
/// <summary>
/// The isovist external depth
/// </summary>
OPT_IsovistExternalDepth = 0,
/// <summary>
/// The number of destinations
/// </summary>
OPT_NumberOfDestinations = 1,
/// <summary>
/// The angle distribution lambda factor
/// </summary>
OPT_AngleDistributionLambdaFactor = 2,
/// <summary>
/// The desirability distribution lambda factor
/// </summary>
OPT_DesirabilityDistributionLambdaFactor = 3,
/// <summary>
/// The decision making period lambda factor
/// </summary>
OPT_DecisionMakingPeriodLambdaFactor = 4,
/// <summary>
/// The velocity magnitude
/// </summary>
GEN_VelocityMagnitude = 5,
/// <summary>
/// The angular velocity
/// </summary>
GEN_AngularVelocity = 6,
/// <summary>
/// The body size
/// </summary>
GEN_BodySize = 7,
/// <summary>
/// The visibility angle
/// </summary>
GEN_VisibilityAngle = 8,
/// <summary>
/// The barrier repulsion range
/// </summary>
GEN_BarrierRepulsionRange = 9,
/// <summary>
/// The maximum repulsion
/// </summary>
GEN_MaximumRepulsion = 10,
/// <summary>
/// The acceleration magnitude
/// </summary>
GEN_AccelerationMagnitude = 11,
/// <summary>
/// The barrier friction
/// </summary>
GEN_BarrierFriction = 12,
/// <summary>
/// The agent body elasticity
/// </summary>
GEN_AgentBodyElasticity = 13,
/// <summary>
/// The angular deviation cost
/// </summary>
MAN_AngularDeviationCost = 14,
//MAN_GAUSSIANNEIGHBORHOODSIZE = 15,
/// <summary>
/// The cost of distance
/// </summary>
MAN_DistanceCost = 15,
}
/// <summary>
/// Class Parameter.
/// </summary>
/// <seealso cref="SpatialAnalysis.Optimization.Variable" />
public class Parameter: Variable
{
private bool _canBeDeleted = true;
/// <summary>
/// Gets a value indicating whether this instance can be deleted.
/// </summary>
/// <value><c>true</c> if this instance can be deleted; otherwise, <c>false</c>.</value>
public bool CanBeDeleted { get { return _canBeDeleted; } }
private readonly string _name;
/// <summary>
/// Gets the name of parameter.
/// </summary>
/// <value>The name.</value>
public string Name { get { return _name; } }
public HashSet<Function> LinkedFunctions { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="Parameter"/> class.
/// </summary>
/// <param name="name">The name of parameter.</param>
/// <param name="initialValue">The initial value.</param>
/// <param name="min">The minimum value.</param>
/// <param name="max">The maximum value.</param>
/// <exception cref="System.ArgumentException">Invalid identifier name for parameter</exception>
public Parameter(string name, double initialValue, double min, double max)
: base(initialValue, min, max)
{
CodeDomProvider evaluator = CodeDomProvider.CreateProvider("C#");
if (!evaluator.IsValidIdentifier(name))
{
throw new ArgumentException("Invalid identifier name for parameter");
}
this._name = name;
this.LinkedFunctions = new HashSet<Function>();
}
public override string ToString()
{
return string.Format("Name: {0}, Min: {1}, Max: {2}, Value: {3}", this.Name,
this.Minimum.ToString(), this.Maximum.ToString(), this.Value.ToString());
}
/// <summary>
/// Copies this parameter with the specified name.
/// </summary>
/// <param name="name">The name of the copied parameter.</param>
/// <returns>Parameter.</returns>
public Parameter Copy(string name)
{
var param = new Parameter(name, this.Value, this.Minimum, this.Maximum);
return param;
}
/// <summary>
/// Copies this instance.
/// </summary>
/// <returns>Parameter.</returns>
public new Parameter Copy()
{
return new Parameter(this.Name, this.Value, this.Minimum, this.Maximum);
}
public override int GetHashCode()
{
return this.Name.GetHashCode();
}
public override bool Equals(object obj)
{
Parameter param = obj as Parameter;
if (param == null)
{
return false;
}
return param.Name == this.Name;
}
/// <summary>
/// Creates a readonly parameter.
/// </summary>
/// <param name="name">The parameter name.</param>
/// <param name="initialValue">The initial value.</param>
/// <param name="min">The minimum value.</param>
/// <param name="max">The maximum value.</param>
/// <returns>Parameter.</returns>
public static Parameter CreateReadOnly(string name, double initialValue, double min, double max)
{
Parameter parameter = new Parameter(name, initialValue, min, max);
parameter._canBeDeleted = false;
return parameter;
}
public static void LoadDefaultParameters(Length_Unit_Types unitTypeOrigin,Length_Unit_Types unitTypeExpected) {
UnitConversion cntr = new UnitConversion(unitTypeOrigin, unitTypeExpected);
DefaultParameters = new Dictionary<AgentParameters, Parameter>
{
//{FreeNavigationAgentParameters.OPT_IsovistInternalDepth.ToString(),
// Parameter.CreateReadOnly(FreeNavigationAgentParameters.OPT_IsovistInternalDepth.ToString(), 5.0d, 1.0d,5.0d)},
{AgentParameters.OPT_IsovistExternalDepth,
Parameter.CreateReadOnly(AgentParameters.OPT_IsovistExternalDepth.ToString(), cntr.Convert(20.0d,6), cntr.Convert(5.0d,6),cntr.Convert(25.0d,6))},
{AgentParameters.OPT_NumberOfDestinations,
Parameter.CreateReadOnly(AgentParameters.OPT_NumberOfDestinations.ToString(), 100.0d,20.0d,200.0d)},
{AgentParameters.OPT_AngleDistributionLambdaFactor,
Parameter.CreateReadOnly(AgentParameters.OPT_AngleDistributionLambdaFactor.ToString(),2.5d,0.001d,3.0d)},
{AgentParameters.OPT_DesirabilityDistributionLambdaFactor,
Parameter.CreateReadOnly(AgentParameters.OPT_DesirabilityDistributionLambdaFactor.ToString(),1.5d,0.001d,3.0d)},
{AgentParameters.OPT_DecisionMakingPeriodLambdaFactor,
Parameter.CreateReadOnly(AgentParameters.OPT_DecisionMakingPeriodLambdaFactor.ToString(), 0.88d,0.05d,2.0d)},
{AgentParameters.GEN_VelocityMagnitude,
Parameter.CreateReadOnly(AgentParameters.GEN_VelocityMagnitude.ToString(),cntr.Convert(3.8,6),cntr.Convert(2.0d,6),cntr.Convert(5.0d,6))},
{AgentParameters.GEN_AngularVelocity,
Parameter.CreateReadOnly(AgentParameters.GEN_AngularVelocity.ToString(), Math.PI, 0.1d,6.283185d)},
{AgentParameters.GEN_BodySize,
Parameter.CreateReadOnly(AgentParameters.GEN_BodySize.ToString(),cntr.Convert(1.80d,6),cntr.Convert(1.0d,6),cntr.Convert(2.2d,6))},
{AgentParameters.GEN_VisibilityAngle,
Parameter.CreateReadOnly(AgentParameters.GEN_VisibilityAngle.ToString(),160.0d, 0.0d,180.0d)},
{AgentParameters.GEN_BarrierRepulsionRange,
Parameter.CreateReadOnly(AgentParameters.GEN_BarrierRepulsionRange.ToString(), cntr.Convert(1.4d,6),cntr.Convert(1.0d,6),cntr.Convert(5.0d,6))},
{AgentParameters.GEN_MaximumRepulsion,
Parameter.CreateReadOnly(AgentParameters.GEN_MaximumRepulsion.ToString(), cntr.Convert(15.0d,6),cntr.Convert(1.0d,6),cntr.Convert(20.0d,6))},
{AgentParameters.GEN_AccelerationMagnitude,
Parameter.CreateReadOnly(AgentParameters.GEN_AccelerationMagnitude.ToString(), cntr.Convert(15.0d,6),cntr.Convert(5.0d,6),cntr.Convert(20.0d,6))},
{AgentParameters.GEN_BarrierFriction,
Parameter.CreateReadOnly(AgentParameters.GEN_BarrierFriction.ToString(), 0.1d,0.0d,1.0d)},
{AgentParameters.GEN_AgentBodyElasticity,
Parameter.CreateReadOnly(AgentParameters.GEN_AgentBodyElasticity.ToString(), 0.2d,0.0d,1.0d)},
{AgentParameters.MAN_AngularDeviationCost,
Parameter.CreateReadOnly(AgentParameters.MAN_AngularDeviationCost.ToString(), 3.0d,1.0d,7.0d)},
{AgentParameters.MAN_DistanceCost,
Parameter.CreateReadOnly(AgentParameters.MAN_DistanceCost.ToString(),cntr.Convert(1.0d,6),cntr.Convert(0.05d,6),cntr.Convert(2.0d,6))},
//{AgentParameters.MAN_GAUSSIANNEIGHBORHOODSIZE,
// Parameter.CreateReadOnly(AgentParameters.MAN_AngularDeviationCost.ToString(),7,2,20)},
};
}
public static Dictionary<AgentParameters, Parameter> DefaultParameters { get; set; }
}
}
| |
// 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.Redis
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// PatchSchedulesOperations operations.
/// </summary>
internal partial class PatchSchedulesOperations : Microsoft.Rest.IServiceOperations<RedisManagementClient>, IPatchSchedulesOperations
{
/// <summary>
/// Initializes a new instance of the PatchSchedulesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal PatchSchedulesOperations(RedisManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the RedisManagementClient
/// </summary>
public RedisManagementClient Client { get; private set; }
/// <summary>
/// Create or replace the patching schedule for redis cache.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='name'>
/// The name of the redis cache.
/// </param>
/// <param name='parameters'>
/// Parameters to set patch schedules for redis cache.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<RedisPatchSchedule>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string name, RedisPatchSchedule parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (resourceGroupName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName");
}
if (name == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "name");
}
if (parameters == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "parameters");
}
if (parameters != null)
{
parameters.Validate();
}
if (this.Client.ApiVersion == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("name", name);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/Redis/{name}/patchSchedules/default").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{name}", System.Uri.EscapeDataString(name));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<RedisPatchSchedule>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<RedisPatchSchedule>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes the patching schedule for redis cache.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='name'>
/// The name of the redis cache.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string name, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (resourceGroupName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName");
}
if (name == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "name");
}
if (this.Client.ApiVersion == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("name", name);
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("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/Redis/{name}/patchSchedules/default").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{name}", System.Uri.EscapeDataString(name));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets the patching schedule for redis cache.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='name'>
/// The name of the redis cache.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<RedisPatchSchedule>> GetWithHttpMessagesAsync(string resourceGroupName, string name, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (resourceGroupName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName");
}
if (name == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "name");
}
if (this.Client.ApiVersion == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("name", name);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/Redis/{name}/patchSchedules/default").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{name}", System.Uri.EscapeDataString(name));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 404)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<RedisPatchSchedule>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<RedisPatchSchedule>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Original code borrowed from Ray Hayes and downloaded from
// http://www.codeproject.com/csharp/commandlineparser.asp.
// Revisions
// 1. Updates were made to support double quotes.
//
// Note, this should probably be moved to it's own GDN workspace and then the
// DLL be referenced in this workspace. However, there is a similar workspace
// called Eas.Console that serves a similar purpose and should be investigated
// before another command line parser workspace is created.
using System;
using System.Text.RegularExpressions;
namespace RJH.CommandLineHelper
{
/// <summary>Implementation of a command-line parsing class. Is capable of
/// having switches registered with it directly or can examine a registered
/// class for any properties with the appropriate attributes appended to
/// them.</summary>
public class Parser
{
/// <summary>A simple internal class for passing back to the caller
/// some information about the switch. The internals/implementation
/// of this class has privillaged access to the contents of the
/// SwitchRecord class.</summary>
public class SwitchInfo
{
#region Private Variables
private object m_Switch = null;
#endregion
#region Public Properties
public string Name { get { return (m_Switch as SwitchRecord).Name; } }
public string Description { get { return (m_Switch as SwitchRecord).Description; } }
public string[] Aliases { get { return (m_Switch as SwitchRecord).Aliases; } }
public System.Type Type { get { return (m_Switch as SwitchRecord).Type; } }
public object Value { get { return (m_Switch as SwitchRecord).Value; } }
public object InternalValue { get { return (m_Switch as SwitchRecord).InternalValue; } }
public bool IsEnum { get { return (m_Switch as SwitchRecord).Type.IsEnum; } }
public string[] Enumerations { get { return (m_Switch as SwitchRecord).Enumerations; } }
#endregion
/// <summary>
/// Constructor for the SwitchInfo class. Note, in order to hide to the outside world
/// information not necessary to know, the constructor takes a System.Object (aka
/// object) as it's registering type. If the type isn't of the correct type, an exception
/// is thrown.
/// </summary>
/// <param name="rec">The SwitchRecord for which this class store information.</param>
/// <exception cref="ArgumentException">Thrown if the rec parameter is not of
/// the type SwitchRecord.</exception>
public SwitchInfo( object rec )
{
if ( rec is SwitchRecord )
m_Switch = rec;
else
throw new ArgumentException();
}
}
/// <summary>
/// The SwitchRecord is stored within the parser's collection of registered
/// switches. This class is private to the outside world.
/// </summary>
private class SwitchRecord
{
#region Private Variables
private string m_name = "";
private string m_description = "";
private object m_value = null;
private System.Type m_switchType = typeof(bool);
private System.Collections.ArrayList m_Aliases = null;
private string m_Pattern = "";
// The following advanced functions allow for callbacks to be
// made to manipulate the associated data type.
private System.Reflection.MethodInfo m_SetMethod = null;
private System.Reflection.MethodInfo m_GetMethod = null;
private object m_PropertyOwner = null;
#endregion
#region Private Utility Functions
private void Initialize( string name, string description )
{
m_name = name;
m_description = description;
BuildPattern();
}
private void BuildPattern()
{
string matchString = Name;
if ( Aliases != null && Aliases.Length > 0 )
foreach( string s in Aliases )
matchString += "|" + s;
string strPatternStart = @"(\s|^)(?<match>(-{1,2}|/)(";
string strPatternEnd; // To be defined below.
// The common suffix ensures that the switches are followed by
// a white-space OR the end of the string. This will stop
// switches such as /help matching /helpme
//
string strCommonSuffix = @"(?=(\s|$))";
if ( Type == typeof(bool) )
strPatternEnd = @")(?<value>(\+|-){0,1}))";
else if ( Type == typeof(string) )
strPatternEnd = @")(?::|\s+))((?:"")(?<value>.+?)(?:"")|(?:')(?<value>.+?)(?:')|(?<value>\S+))";
else if ( Type == typeof(int) )
strPatternEnd = @")(?::|\s+))((?<value>(-|\+)[0-9]+)|(?<value>[0-9]+))";
else if ( Type.IsEnum )
{
string[] enumNames = Enumerations;
string e_str = enumNames[0];
for ( int e=1; e<enumNames.Length; e++ )
e_str += "|" + enumNames[e];
strPatternEnd = @")(?::|\s+))(?<value>" + e_str + @")";
}
else
throw new System.ArgumentException();
// Set the internal regular expression pattern.
m_Pattern = strPatternStart + matchString + strPatternEnd + strCommonSuffix;
}
#endregion
#region Public Properties
public object Value
{
get
{
if ( ReadValue != null )
return ReadValue;
else
return m_value;
}
}
public object InternalValue
{
get { return m_value; }
}
public string Name
{
get { return m_name; }
set { m_name = value; }
}
public string Description
{
get { return m_description; }
set { m_description = value; }
}
public System.Type Type
{
get { return m_switchType; }
}
public string[] Aliases
{
get { return (m_Aliases != null) ? (string[])m_Aliases.ToArray(typeof(string)): null; }
}
public string Pattern
{
get { return m_Pattern; }
}
public System.Reflection.MethodInfo SetMethod
{
set { m_SetMethod = value; }
}
public System.Reflection.MethodInfo GetMethod
{
set { m_GetMethod = value; }
}
public object PropertyOwner
{
set { m_PropertyOwner = value; }
}
public object ReadValue
{
get
{
object o = null;
if ( m_PropertyOwner != null && m_GetMethod != null )
o = m_GetMethod.Invoke( m_PropertyOwner, null );
return o;
}
}
public string[] Enumerations
{
get
{
if ( m_switchType.IsEnum )
return System.Enum.GetNames( m_switchType );
else
return null;
}
}
#endregion
#region Constructors
public SwitchRecord( string name, string description )
{
Initialize( name, description );
}
public SwitchRecord( string name, string description, System.Type type )
{
if ( type == typeof(bool) ||
type == typeof(string) ||
type == typeof(int) ||
type.IsEnum )
{
m_switchType = type;
Initialize( name, description );
}
else
throw new ArgumentException("Currently only Ints, Bool and Strings are supported");
}
#endregion
#region Public Methods
public void AddAlias( string alias )
{
if ( m_Aliases == null )
m_Aliases = new System.Collections.ArrayList();
m_Aliases.Add( alias );
BuildPattern();
}
public void Notify( object value )
{
if ( m_PropertyOwner != null && m_SetMethod != null )
{
object[] parameters = new object[1];
parameters[0] = value;
m_SetMethod.Invoke( m_PropertyOwner, parameters );
}
m_value = value;
}
#endregion
}
#region Private Variables
private string m_commandLine = "";
private string m_workingString = "";
private string m_applicationName = "";
private string[] m_splitParameters = null;
private System.Collections.ArrayList m_switches = null;
#endregion
#region Private Utility Functions
private void ExtractApplicationName()
{
Regex r = new Regex(@"((?:"")(?<commandLine>.+?)(?:"")|(?:')(?<commandLine>.+?)(?:')|(?<commandLine>\S+)) (?<remainder>.+)",
RegexOptions.ExplicitCapture);
Match m = r.Match(m_commandLine);
if ( m != null && m.Groups["commandLine"] != null )
{
m_applicationName = m.Groups["commandLine"].Value;
m_applicationName = m_applicationName.Trim();
if(m_applicationName.Length > 0)
{
if(m_applicationName[0]== '\'' || m_applicationName[0]== '"')
{
m_applicationName = m_applicationName.Remove(0,1);
m_applicationName = m_applicationName.Remove(m_applicationName.Length-1,1);
}
}
else
{
m_applicationName = m_commandLine;
}
m_workingString = m.Groups["remainder"].Value;
}
}
private static readonly Regex splitParametersRegex = new Regex(@"((\s*(""(?<param>.+?)""|'(?<param>.+?)'|(?<param>\S+))))",
RegexOptions.ExplicitCapture | RegexOptions.Compiled);
private void SplitParameters()
{
// Populate the split parameters array with the remaining parameters.
// Note that if quotes are used, the quotes are removed.
// e.g. one two three "four five six"
// 0 - one
// 1 - two
// 2 - three
// 3 - four five six
// (e.g. 3 is not in quotes).
MatchCollection m = splitParametersRegex.Matches( m_workingString );
if ( m != null )
{
m_splitParameters = new string[ m.Count ];
for ( int i=0; i < m.Count; i++ )
m_splitParameters[i] = m[i].Groups["param"].Value;
}
}
private void HandleSwitches()
{
if ( m_switches != null )
{
foreach ( SwitchRecord s in m_switches )
{
Regex r = new Regex( s.Pattern,
RegexOptions.ExplicitCapture
| RegexOptions.IgnoreCase );
MatchCollection m = r.Matches( m_workingString );
if ( m != null )
{
for ( int i=0; i < m.Count; i++ )
{
string value = null;
if ( m[i].Groups != null && m[i].Groups["value"] != null )
value = m[i].Groups["value"].Value;
if ( s.Type == typeof(bool))
{
bool state = true;
// The value string may indicate what value we want.
if ( m[i].Groups != null && m[i].Groups["value"] != null )
{
switch ( value )
{
case "+": state = true;
break;
case "-": state = false;
break;
case "": if ( s.ReadValue != null )
state = !(bool)s.ReadValue;
break;
default: break;
}
}
s.Notify( state );
break;
}
else if ( s.Type == typeof(string) )
s.Notify( value );
else if ( s.Type == typeof(int) )
s.Notify( int.Parse( value ) );
else if ( s.Type.IsEnum )
s.Notify( System.Enum.Parse(s.Type,value,true) );
}
}
m_workingString = r.Replace(m_workingString, " ");
}
}
}
#endregion
#region Public Properties
public string ApplicationName
{
get { return m_applicationName; }
}
public string[] Parameters
{
get { return m_splitParameters; }
}
public SwitchInfo[] Switches
{
get
{
if ( m_switches == null )
return null;
else
{
SwitchInfo[] si = new SwitchInfo[ m_switches.Count ];
for ( int i=0; i<m_switches.Count; i++ )
si[i] = new SwitchInfo( m_switches[i] );
return si;
}
}
}
public object this[string name]
{
get
{
if ( m_switches != null )
for ( int i=0; i<m_switches.Count; i++ )
if ( string.Compare( (m_switches[i] as SwitchRecord).Name, name, true )==0 )
return (m_switches[i] as SwitchRecord).Value;
return null;
}
}
private static readonly Regex switchPatternRegex = new Regex( @"(\s|^)(?<match>(-{1,2}|/)(.+?))(?=(\s|$))",
RegexOptions.ExplicitCapture
| RegexOptions.IgnoreCase | RegexOptions.Compiled);
/// <summary>This function returns a list of the unhandled switches
/// that the parser has seen, but not processed.</summary>
/// <remark>The unhandled switches are not removed from the remainder
/// of the command-line.</remark>
public string[] UnhandledSwitches
{
get
{
MatchCollection m = switchPatternRegex.Matches( m_workingString );
if ( m != null )
{
string[] unhandled = new string[ m.Count ];
for ( int i=0; i < m.Count; i++ )
unhandled[i] = m[i].Groups["match"].Value;
return unhandled;
}
else
return null;
}
}
#endregion
#region Public Methods
public void AddSwitch( string name, string description )
{
if ( m_switches == null )
m_switches = new System.Collections.ArrayList();
SwitchRecord rec = new SwitchRecord( name, description );
m_switches.Add( rec );
}
public void AddSwitch( string[] names, string description )
{
if ( m_switches == null )
m_switches = new System.Collections.ArrayList();
SwitchRecord rec = new SwitchRecord( names[0], description );
for ( int s=1; s<names.Length; s++ )
rec.AddAlias( names[s] );
m_switches.Add( rec );
}
public bool Parse()
{
ExtractApplicationName();
// Remove switches and associated info.
HandleSwitches();
// Split parameters.
SplitParameters();
return true;
}
public string GetHelpText()
{
System.Text.StringBuilder message = new System.Text.StringBuilder("");
message.Append( this.ApplicationName + " ");
foreach(Parser.SwitchInfo switchInfo in this.Switches)
{
message.Append( "[/" );
if(switchInfo.Aliases != null)
{
message.Append("{");
}
message.Append( switchInfo.Name);
if(switchInfo.Aliases != null)
{
foreach(string alias in switchInfo.Aliases)
{
message.Append( "|" + alias);
}
message.Append("}");
}
if(switchInfo.IsEnum)
{
message.Append( ":" + string.Join("|", Enum.GetNames(switchInfo.Type)));
}
message.Append( "] ");
}
message.Append("\n\n");
foreach(Parser.SwitchInfo switchInfo in this.Switches)
{
message.AppendFormat("\t/{0,-17}-{1}\n", switchInfo.Name, switchInfo.Description);
if(switchInfo.Aliases != null)
{
message.AppendFormat("{0,-30}Aliases: ", "");
message.Append(string.Join(", ", switchInfo.Aliases));
message.Append("\n");
}
}
return message.ToString();
}
public object InternalValue(string name)
{
if ( m_switches != null )
for ( int i=0; i<m_switches.Count; i++ )
if ( string.Compare( (m_switches[i] as SwitchRecord).Name, name, true )==0 )
return (m_switches[i] as SwitchRecord).InternalValue;
return null;
}
#endregion
#region Constructors
public Parser( string commandLine )
{
m_commandLine = commandLine;
}
public Parser( string commandLine,
object classForAutoAttributes )
{
m_commandLine = commandLine;
Type type = classForAutoAttributes.GetType();
System.Reflection.MemberInfo[] members = type.GetMembers();
for(int i=0; i<members.Length; i++)
{
object[] attributes = members[i].GetCustomAttributes(false);
if(attributes.Length > 0)
{
SwitchRecord rec = null;
foreach ( Attribute attribute in attributes )
{
if ( attribute is CommandLineSwitchAttribute )
{
CommandLineSwitchAttribute switchAttrib =
(CommandLineSwitchAttribute) attribute;
// Get the property information. We're only handling
// properties at the moment!
if ( members[i] is System.Reflection.PropertyInfo )
{
System.Reflection.PropertyInfo pi = (System.Reflection.PropertyInfo) members[i];
rec = new SwitchRecord( switchAttrib.Name,
switchAttrib.Description,
pi.PropertyType );
// Map in the Get/Set methods.
rec.SetMethod = pi.GetSetMethod();
rec.GetMethod = pi.GetGetMethod();
rec.PropertyOwner = classForAutoAttributes;
// Can only handle a single switch for each property
// (otherwise the parsing of aliases gets silly...)
break;
}
}
}
// See if any aliases are required. We can only do this after
// a switch has been registered and the framework doesn't make
// any guarantees about the order of attributes, so we have to
// walk the collection a second time.
if ( rec != null )
{
foreach ( Attribute attribute in attributes )
{
if ( attribute is CommandLineAliasAttribute )
{
CommandLineAliasAttribute aliasAttrib =
(CommandLineAliasAttribute) attribute;
rec.AddAlias( aliasAttrib.Alias );
}
}
}
// Assuming we have a switch record (that may or may not have
// aliases), add it to the collection of switches.
if ( rec != null )
{
if ( m_switches == null )
m_switches = new System.Collections.ArrayList();
m_switches.Add( rec );
}
}
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Globalization;
using System.Text;
using Xunit;
namespace System.Text.EncodingTests
{
public class EncodingTest
{
private static byte[] s_UTF32LEBom = new byte[] { 0xFF, 0xFE, 0x0, 0x0 };
private static byte[] s_UTF32BEBom = new byte[] { 0x0, 0x0, 0xFE, 0xFF, };
private static byte[] s_UTF8Bom = new byte[] { 0xEF, 0xBB, 0xBF };
private static byte[] s_UTF16LEBom = new byte[] { 0xFF, 0xFE };
private static byte[] s_UTF8BEBom = new byte[] { 0xFE, 0xFF };
[Fact]
[ActiveIssue(846, PlatformID.AnyUnix)]
public static void TestGetEncoding()
{
Encoding encoding = Encoding.GetEncoding("UTF-32LE");
Assert.Equal<byte>(encoding.GetPreamble(), s_UTF32LEBom);
encoding = Encoding.UTF32;
Assert.Equal<byte>(encoding.GetPreamble(), s_UTF32LEBom);
encoding = Encoding.GetEncoding("UTF-32BE");
Assert.Equal<byte>(encoding.GetPreamble(), s_UTF32BEBom);
encoding = Encoding.UTF8;
Assert.Equal<byte>(encoding.GetPreamble(), s_UTF8Bom);
encoding = Encoding.GetEncoding("UTF-16BE");
Assert.Equal<byte>(encoding.GetPreamble(), s_UTF8BEBom);
encoding = Encoding.GetEncoding("UTF-16LE");
Assert.Equal<byte>(encoding.GetPreamble(), s_UTF16LEBom);
encoding = Encoding.Unicode;
Assert.Equal<byte>(encoding.GetPreamble(), s_UTF16LEBom);
}
private static byte[] s_asciiBytes = new byte[] { (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', (byte)'H', };
private static string s_asciiString = "ABCDEFGH";
[Fact]
public static void TestEncodingDecoding()
{
Encoding encoding = Encoding.ASCII;
byte[] bytes = encoding.GetBytes(s_asciiString);
Assert.Equal<byte>(bytes, s_asciiBytes);
string s = encoding.GetString(bytes, 0, bytes.Length);
Assert.True(s.Equals(s_asciiString));
s = encoding.GetString(bytes);
Assert.True(s.Equals(s_asciiString));
encoding = Encoding.GetEncoding("us-ascii");
bytes = encoding.GetBytes(s_asciiString);
Assert.Equal<byte>(bytes, s_asciiBytes);
s = encoding.GetString(bytes, 0, bytes.Length);
Assert.True(s.Equals(s_asciiString));
s = encoding.GetString(bytes);
Assert.True(s.Equals(s_asciiString));
encoding = Encoding.GetEncoding("latin1");
bytes = encoding.GetBytes(s_asciiString);
Assert.Equal<byte>(bytes, s_asciiBytes);
s = encoding.GetString(bytes, 0, bytes.Length);
Assert.True(s.Equals(s_asciiString));
s = encoding.GetString(bytes);
Assert.True(s.Equals(s_asciiString));
}
public class CodePageMapping
{
public CodePageMapping(string name, int codepage)
{
Name = name;
CodePage = codepage;
}
public string Name { set; get; }
public int CodePage { set; get; }
}
private static CodePageMapping[] s_mapping = new CodePageMapping[] {
new CodePageMapping("ANSI_X3.4-1968", 20127 ),
new CodePageMapping("ANSI_X3.4-1986", 20127 ),
new CodePageMapping("ascii", 20127 ),
new CodePageMapping("cp367", 20127 ),
new CodePageMapping("cp819", 28591 ),
new CodePageMapping("csASCII", 20127 ),
new CodePageMapping("csISOLatin1", 28591 ),
new CodePageMapping("csUnicode11UTF7", 65000 ),
new CodePageMapping("IBM367", 20127 ),
new CodePageMapping("ibm819", 28591 ),
new CodePageMapping("ISO-10646-UCS-2", 1200),
new CodePageMapping("iso-8859-1", 28591),
new CodePageMapping("iso-ir-100", 28591),
new CodePageMapping("iso-ir-6", 20127),
new CodePageMapping("ISO646-US", 20127),
new CodePageMapping("iso8859-1", 28591),
new CodePageMapping("ISO_646.irv:1991", 20127),
new CodePageMapping("iso_8859-1", 28591),
new CodePageMapping("iso_8859-1:1987", 28591),
new CodePageMapping("l1", 28591),
new CodePageMapping("latin1", 28591),
new CodePageMapping("ucs-2", 1200),
new CodePageMapping("unicode", 1200),
new CodePageMapping("unicode-1-1-utf-7", 65000),
new CodePageMapping("unicode-1-1-utf-8", 65001),
new CodePageMapping("unicode-2-0-utf-7", 65000),
new CodePageMapping("unicode-2-0-utf-8", 65001),
new CodePageMapping("unicodeFFFE", 1201),
new CodePageMapping("us", 20127),
new CodePageMapping("us-ascii", 20127),
new CodePageMapping("utf-16", 1200),
new CodePageMapping("UTF-16BE", 1201),
new CodePageMapping("UTF-16LE", 1200),
new CodePageMapping("utf-32", 12000),
new CodePageMapping("UTF-32BE", 12001),
new CodePageMapping("UTF-32LE", 12000),
new CodePageMapping("utf-7", 65000),
new CodePageMapping("utf-8", 65001),
new CodePageMapping("x-unicode-1-1-utf-7", 65000),
new CodePageMapping("x-unicode-1-1-utf-8", 65001),
new CodePageMapping("x-unicode-2-0-utf-7", 65000),
new CodePageMapping("x-unicode-2-0-utf-8", 65001)
};
[Fact]
[ActiveIssue(846, PlatformID.AnyUnix)]
public static void TestEncodingNameAndCopdepageNumber()
{
foreach (var map in s_mapping)
{
Encoding encoding = Encoding.GetEncoding(map.Name);
Assert.True(encoding.CodePage == map.CodePage);
}
}
[Fact]
public static void TestEncodingDisplayNames()
{
CultureInfo originalUICulture = CultureInfo.CurrentUICulture;
try
{
CultureInfo.CurrentCulture = new CultureInfo("en-US");
foreach (var map in s_mapping)
{
Encoding encoding = Encoding.GetEncoding(map.Name);
string name = encoding.EncodingName;
Assert.NotNull(name);
Assert.NotEqual(string.Empty, name);
Assert.All(name, ch => Assert.InRange(ch, 0, 127));
}
}
finally
{
CultureInfo.CurrentUICulture = originalUICulture;
}
}
[Fact]
[ActiveIssue(846, PlatformID.AnyUnix)]
public static void TestCodePageToWebNameMappings()
{
foreach (var mapping in s_codePageToWebNameMappings)
{
Encoding encoding = Encoding.GetEncoding(mapping.CodePage);
Assert.True(string.Equals(mapping.WebName, encoding.WebName, StringComparison.OrdinalIgnoreCase));
}
}
internal class CodePageToWebNameMapping
{
public CodePageToWebNameMapping(int codePage, string webName)
{
_codePage = codePage;
_webName = webName;
}
public int CodePage { get { return _codePage; } }
public string WebName { get { return _webName; } }
private int _codePage;
private string _webName;
}
private static readonly CodePageToWebNameMapping[] s_codePageToWebNameMappings = new[]
{
new CodePageToWebNameMapping(1200, "utf-16"),
new CodePageToWebNameMapping(1201, "utf-16be"),
new CodePageToWebNameMapping(12000, "utf-32"),
new CodePageToWebNameMapping(12001, "utf-32be"),
new CodePageToWebNameMapping(20127, "us-ascii"),
new CodePageToWebNameMapping(28591, "iso-8859-1"),
new CodePageToWebNameMapping(65000, "utf-7"),
new CodePageToWebNameMapping(65001, "utf-8")
};
}
}
| |
#if OS_WINDOWS
using Microsoft.VisualStudio.Services.Agent.Util;
using System;
using System.IO;
using System.Linq;
using System.Security.Principal;
using System.Security;
using System.Text;
namespace Microsoft.VisualStudio.Services.Agent.Listener.Configuration
{
public class WindowsServiceControlManager : ServiceControlManager, IWindowsServiceControlManager
{
public const string WindowsServiceControllerName = "AgentService.exe";
private const string ServiceNamePattern = "vstsagent.{0}.{1}";
private const string ServiceDisplayNamePattern = "VSTS Agent ({0}.{1})";
private INativeWindowsServiceHelper _windowsServiceHelper;
private ITerminal _term;
public override void Initialize(IHostContext hostContext)
{
base.Initialize(hostContext);
_windowsServiceHelper = HostContext.GetService<INativeWindowsServiceHelper>();
_term = HostContext.GetService<ITerminal>();
}
public void ConfigureService(AgentSettings settings, CommandSettings command)
{
Trace.Entering();
if (!_windowsServiceHelper.IsRunningInElevatedMode())
{
Trace.Error("Needs Administrator privileges for configure agent as windows service.");
throw new SecurityException(StringUtil.Loc("NeedAdminForConfigAgentWinService"));
}
// TODO: Fix bug that exists in the legacy Windows agent where configuration using mirrored credentials causes an error, but the agent is still functional (after restarting). Mirrored credentials is a supported scenario and shouldn't manifest any errors.
// We use NetworkService as default account for build and release agent
// We use Local System as default account for deployment agent, deployment pool agent
bool isDeploymentGroupScenario = command.DeploymentGroup || command.DeploymentPool;
NTAccount defaultServiceAccount = isDeploymentGroupScenario ? _windowsServiceHelper.GetDefaultAdminServiceAccount() : _windowsServiceHelper.GetDefaultServiceAccount();
string logonAccount = command.GetWindowsLogonAccount(defaultValue: defaultServiceAccount.ToString(), descriptionMsg: StringUtil.Loc("WindowsLogonAccountNameDescription"));
string domainName;
string userName;
GetAccountSegments(logonAccount, out domainName, out userName);
if ((string.IsNullOrEmpty(domainName) || domainName.Equals(".", StringComparison.CurrentCultureIgnoreCase)) && !logonAccount.Contains('@'))
{
logonAccount = String.Format("{0}\\{1}", Environment.MachineName, userName);
domainName = Environment.MachineName;
}
Trace.Info("LogonAccount after transforming: {0}, user: {1}, domain: {2}", logonAccount, userName, domainName);
string logonPassword = string.Empty;
if (!defaultServiceAccount.Equals(new NTAccount(logonAccount)) && !NativeWindowsServiceHelper.IsWellKnownIdentity(logonAccount))
{
while (true)
{
logonPassword = command.GetWindowsLogonPassword(logonAccount);
if (_windowsServiceHelper.IsValidCredential(domainName, userName, logonPassword))
{
Trace.Info("Credential validation succeed");
break;
}
else
{
if (!command.Unattended)
{
Trace.Info("Invalid credential entered");
_term.WriteLine(StringUtil.Loc("InvalidWindowsCredential"));
}
else
{
throw new SecurityException(StringUtil.Loc("InvalidWindowsCredential"));
}
}
}
}
string serviceName;
string serviceDisplayName;
CalculateServiceName(settings, ServiceNamePattern, ServiceDisplayNamePattern, out serviceName, out serviceDisplayName);
if (_windowsServiceHelper.IsServiceExists(serviceName))
{
_term.WriteLine(StringUtil.Loc("ServiceAlreadyExists", serviceName));
_windowsServiceHelper.UninstallService(serviceName);
}
Trace.Info("Verifying if the account has LogonAsService permission");
if (_windowsServiceHelper.IsUserHasLogonAsServicePrivilege(domainName, userName))
{
Trace.Info($"Account: {logonAccount} already has Logon As Service Privilege.");
}
else
{
if (!_windowsServiceHelper.GrantUserLogonAsServicePrivilage(domainName, userName))
{
throw new InvalidOperationException(StringUtil.Loc("CanNotGrantPermission", logonAccount));
}
}
Trace.Info("Create local group and grant folder permission to service logon account.");
GrantDirectoryPermissionForAccount(logonAccount);
// install service.
_windowsServiceHelper.InstallService(serviceName, serviceDisplayName, logonAccount, logonPassword);
// create .service file with service name.
SaveServiceSettings(serviceName);
// Add registry key after installation
_windowsServiceHelper.CreateVstsAgentRegistryKey();
Trace.Info("Configuration was successful, trying to start the service");
_windowsServiceHelper.StartService(serviceName);
}
private void GrantDirectoryPermissionForAccount(string accountName)
{
Trace.Entering();
string groupName = _windowsServiceHelper.GetUniqueBuildGroupName();
Trace.Info(StringUtil.Format("Calculated unique group name {0}", groupName));
if (!_windowsServiceHelper.LocalGroupExists(groupName))
{
Trace.Info(StringUtil.Format("Trying to create group {0}", groupName));
_windowsServiceHelper.CreateLocalGroup(groupName);
}
Trace.Info(StringUtil.Format("Trying to add userName {0} to the group {1}", accountName, groupName));
_windowsServiceHelper.AddMemberToLocalGroup(accountName, groupName);
// grant permssion for agent root folder
string agentRoot = HostContext.GetDirectory(WellKnownDirectory.Root);
Trace.Info(StringUtil.Format("Set full access control to group for the folder {0}", agentRoot));
_windowsServiceHelper.GrantFullControlToGroup(agentRoot, groupName);
// grant permssion for work folder
string workFolder = HostContext.GetDirectory(WellKnownDirectory.Work);
Directory.CreateDirectory(workFolder);
Trace.Info(StringUtil.Format("Set full access control to group for the folder {0}", workFolder));
_term.WriteLine(StringUtil.Loc("GrantingFilePermissions", accountName));
_windowsServiceHelper.GrantFullControlToGroup(workFolder, groupName);
}
private void RevokeDirectoryPermissionForAccount()
{
Trace.Entering();
string groupName = _windowsServiceHelper.GetUniqueBuildGroupName();
Trace.Info(StringUtil.Format("Calculated unique group name {0}", groupName));
// remove the group from the work folder
string workFolder = HostContext.GetDirectory(WellKnownDirectory.Work);
if (Directory.Exists(workFolder))
{
Trace.Info(StringUtil.Format($"Remove the group {groupName} for the folder {workFolder}."));
_windowsServiceHelper.RemoveGroupFromFolderSecuritySetting(workFolder, groupName);
}
//remove group from agent root folder
string agentRoot = HostContext.GetDirectory(WellKnownDirectory.Root);
if (Directory.Exists(agentRoot))
{
Trace.Info(StringUtil.Format($"Remove the group {groupName} for the folder {agentRoot}."));
_windowsServiceHelper.RemoveGroupFromFolderSecuritySetting(agentRoot, groupName);
}
//delete group
Trace.Info(StringUtil.Format($"Delete the group {groupName}."));
_windowsServiceHelper.DeleteLocalGroup(groupName);
}
public void UnconfigureService()
{
if (!_windowsServiceHelper.IsRunningInElevatedMode())
{
Trace.Error("Needs Administrator privileges for unconfigure windows service agent.");
throw new SecurityException(StringUtil.Loc("NeedAdminForUnconfigWinServiceAgent"));
}
string serviceConfigPath = HostContext.GetConfigFile(WellKnownConfigFile.Service);
string serviceName = File.ReadAllText(serviceConfigPath);
if (_windowsServiceHelper.IsServiceExists(serviceName))
{
_windowsServiceHelper.StopService(serviceName);
_windowsServiceHelper.UninstallService(serviceName);
// Delete local group we created during confiure.
RevokeDirectoryPermissionForAccount();
// Remove registry key only on Windows
_windowsServiceHelper.DeleteVstsAgentRegistryKey();
}
IOUtil.DeleteFile(serviceConfigPath);
}
private void SaveServiceSettings(string serviceName)
{
string serviceConfigPath = HostContext.GetConfigFile(WellKnownConfigFile.Service);
if (File.Exists(serviceConfigPath))
{
IOUtil.DeleteFile(serviceConfigPath);
}
File.WriteAllText(serviceConfigPath, serviceName, new UTF8Encoding(false));
File.SetAttributes(serviceConfigPath, File.GetAttributes(serviceConfigPath) | FileAttributes.Hidden);
}
private void GetAccountSegments(string account, out string domain, out string user)
{
string[] segments = account.Split('\\');
domain = string.Empty;
user = account;
if (segments.Length == 2)
{
domain = segments[0];
user = segments[1];
}
}
}
}
#endif
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Threading;
namespace Microsoft.WindowsAzure.Commands.Sync.Threading
{
internal class Parallel
{
public readonly static int MaxParallellism = Environment.ProcessorCount;
public static LoopResult ForEach<T, TA>(IEnumerable<T> source, Func<TA> argumentConstructor, Action<T,TA> body)
{
return ForEach(source, argumentConstructor, body, MaxParallellism);
}
public static LoopResult ForEach<T, TA>(IEnumerable<T> source, Func<TA> argumentConstructor, Action<T,TA> body, int parallelism)
{
var loopResult = new InternalLoopResult();
int numProcs = parallelism;
int remainingWorkItems = numProcs;
using (var enumerator = source.GetEnumerator())
{
using (var mre = new ManualResetEvent(false))
{
// Create each of the work items.
for (int p = 0; p < numProcs; p++)
{
ThreadPool.QueueUserWorkItem(delegate
{
try
{
TA argument = argumentConstructor();
// Iterate until there's no more work.
while (true)
{
// Get the next item under a lock,
// then process that item.
T nextItem;
lock (enumerator)
{
if (!enumerator.MoveNext()) break;
nextItem = enumerator.Current;
}
body(nextItem, argument);
}
}
catch (Exception e)
{
loopResult.AddException(e);
}
if (Interlocked.Decrement(ref remainingWorkItems) == 0)
mre.Set();
});
}
// Wait for all threads to complete.
mre.WaitOne();
loopResult.SetCompleted();
}
}
return loopResult;
}
public static LoopResult ForEach<T>(IEnumerable<T> source, Action<T> body)
{
return ForEach(source, body, MaxParallellism);
}
public static LoopResult ForEach<T>(IEnumerable<T> source, Action<T> body, int parallelism)
{
var loopResult = new InternalLoopResult();
int numProcs = parallelism;
int remainingWorkItems = numProcs;
using (var enumerator = source.GetEnumerator())
{
using (var mre = new ManualResetEvent(false))
{
// Create each of the work items.
for (int p = 0; p < numProcs; p++)
{
ThreadPool.QueueUserWorkItem(delegate
{
// Iterate until there's no more work.
try
{
while (true)
{
// Get the next item under a lock,
// then process that item.
T nextItem;
lock (enumerator)
{
if (!enumerator.MoveNext()) break;
nextItem = enumerator.Current;
}
body(nextItem);
}
}
catch (Exception e)
{
loopResult.AddException(e);
}
if (Interlocked.Decrement(ref remainingWorkItems) == 0)
mre.Set();
});
}
// Wait for all threads to complete.
mre.WaitOne();
loopResult.SetCompleted();
}
}
return loopResult;
}
public static LoopResult ForEach<T, TA>(IEnumerable<T> source, Func<TA> argumentConstructor, Action<T, TA> body, Action<TA> finalize, int parallelism)
{
var loopResult = new InternalLoopResult();
int numProcs = parallelism;
int remainingWorkItems = numProcs;
IList<TA> arguments = new List<TA>();
using (var enumerator = source.GetEnumerator())
{
using (var mre = new ManualResetEvent(false))
{
// Create each of the work items.
for (int p = 0; p < numProcs; p++)
{
ThreadPool.QueueUserWorkItem(delegate
{
try
{
TA argument = argumentConstructor();
lock (arguments)
{
arguments.Add(argument);
}
// Iterate until there's no more work.
while (true && !loopResult.IsExceptional)
{
// Get the next item under a lock,
// then process that item.
T nextItem;
lock (enumerator)
{
if (!enumerator.MoveNext()) break;
nextItem = enumerator.Current;
}
body(nextItem, argument);
}
}
catch (Exception e)
{
loopResult.AddException(e);
}
if (Interlocked.Decrement(ref remainingWorkItems) == 0)
mre.Set();
});
}
// Wait for all threads to complete.
mre.WaitOne();
foreach (var argument in arguments)
{
finalize(argument);
}
loopResult.SetCompleted();
}
}
return loopResult;
}
private class InternalLoopResult : LoopResult
{
private IList<Exception> exceptions;
private object lockObject = new object();
public InternalLoopResult()
{
this.exceptions = new List<Exception>();
}
public override bool IsCompleted
{
get; protected set;
}
public override IList<Exception> Exceptions
{
get { return new List<Exception>(exceptions); }
}
public override bool IsExceptional
{
get
{
lock (lockObject)
{
return this.exceptions.Count > 0;
}
}
}
public void SetCompleted()
{
this.IsCompleted = true;
}
public void AddException(Exception exception)
{
lock (lockObject)
{
this.exceptions.Add(exception);
}
}
}
}
public abstract class LoopResult
{
public abstract bool IsCompleted { get; protected set; }
public abstract IList<Exception> Exceptions { get; }
public abstract bool IsExceptional { get; }
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V10.Resources
{
/// <summary>Resource name for the <c>Customer</c> resource.</summary>
public sealed partial class CustomerName : gax::IResourceName, sys::IEquatable<CustomerName>
{
/// <summary>The possible contents of <see cref="CustomerName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>customers/{customer_id}</c>.</summary>
Customer = 1,
}
private static gax::PathTemplate s_customer = new gax::PathTemplate("customers/{customer_id}");
/// <summary>Creates a <see cref="CustomerName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="CustomerName"/> containing the provided <paramref name="unparsedResourceName"/>
/// .
/// </returns>
public static CustomerName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new CustomerName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>Creates a <see cref="CustomerName"/> with the pattern <c>customers/{customer_id}</c>.</summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="CustomerName"/> constructed from the provided ids.</returns>
public static CustomerName FromCustomer(string customerId) =>
new CustomerName(ResourceNameType.Customer, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="CustomerName"/> with pattern
/// <c>customers/{customer_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="CustomerName"/> with pattern <c>customers/{customer_id}</c>.
/// </returns>
public static string Format(string customerId) => FormatCustomer(customerId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="CustomerName"/> with pattern
/// <c>customers/{customer_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="CustomerName"/> with pattern <c>customers/{customer_id}</c>.
/// </returns>
public static string FormatCustomer(string customerId) =>
s_customer.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)));
/// <summary>Parses the given resource name string into a new <see cref="CustomerName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>customers/{customer_id}</c></description></item></list>
/// </remarks>
/// <param name="customerName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="CustomerName"/> if successful.</returns>
public static CustomerName Parse(string customerName) => Parse(customerName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="CustomerName"/> instance; optionally allowing an
/// unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>customers/{customer_id}</c></description></item></list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="customerName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="CustomerName"/> if successful.</returns>
public static CustomerName Parse(string customerName, bool allowUnparsed) =>
TryParse(customerName, allowUnparsed, out CustomerName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="CustomerName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>customers/{customer_id}</c></description></item></list>
/// </remarks>
/// <param name="customerName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="CustomerName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string customerName, out CustomerName result) => TryParse(customerName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="CustomerName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>customers/{customer_id}</c></description></item></list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="customerName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="CustomerName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string customerName, bool allowUnparsed, out CustomerName result)
{
gax::GaxPreconditions.CheckNotNull(customerName, nameof(customerName));
gax::TemplatedResourceName resourceName;
if (s_customer.TryParseName(customerName, out resourceName))
{
result = FromCustomer(resourceName[0]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(customerName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private CustomerName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CustomerId = customerId;
}
/// <summary>
/// Constructs a new instance of a <see cref="CustomerName"/> class from the component parts of pattern
/// <c>customers/{customer_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
public CustomerName(string customerId) : this(ResourceNameType.Customer, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.Customer: return s_customer.Expand(CustomerId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as CustomerName);
/// <inheritdoc/>
public bool Equals(CustomerName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(CustomerName a, CustomerName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(CustomerName a, CustomerName b) => !(a == b);
}
public partial class Customer
{
/// <summary>
/// <see cref="CustomerName"/>-typed view over the <see cref="ResourceName"/> resource name property.
/// </summary>
internal CustomerName ResourceNameAsCustomerName
{
get => string.IsNullOrEmpty(ResourceName) ? null : CustomerName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
}
public partial class CallReportingSetting
{
/// <summary>
/// <see cref="ConversionActionName"/>-typed view over the <see cref="CallConversionAction"/> resource name
/// property.
/// </summary>
internal ConversionActionName CallConversionActionAsConversionActionName
{
get => string.IsNullOrEmpty(CallConversionAction) ? null : ConversionActionName.Parse(CallConversionAction, allowUnparsed: true);
set => CallConversionAction = value?.ToString() ?? "";
}
}
}
| |
/*
* Copyright (2011) Intel Corporation and Sandia Corporation. Under the
* terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the
* U.S. Government retains certain rights in this software.
*
* 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 Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INTEL OR ITS
* 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 Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Interfaces;
using WaterWars.Events;
using WaterWars.Models;
using WaterWars.Models.Roles;
using WaterWars.States;
using WaterWars.Views.Interactions;
namespace WaterWars
{
/// <summary>
/// Resolve incoming requests in terms of OpenSim concepts and objects.
/// </summary>
///
/// We're routing through this class rather than calling state directly in order to consistently generate
/// useful error messages if something goes wrong.
///
/// This class also acts as an intermediary which poses questions to players if they are actively in-world.
/// Otherwise the request just goes straight through!
public class OpenSimResolver
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
WaterWarsController m_controller;
public OpenSimResolver(WaterWarsController controller)
{
m_controller = controller;
}
/// <summary>
/// Add a player
/// </summary>
/// <param name="rawPlayerId"></param>
/// <param name="roleType"></param>
/// <returns>Player added</returns>
public Player AddPlayer(string rawPlayerId, RoleType roleType)
{
IRole role = null;
switch (roleType)
{
case RoleType.Developer:
role = Developer.Singleton;
break;
case RoleType.Farmer:
role = Farmer.Singleton;
break;
case RoleType.Manufacturer:
role = Manufacturer.Singleton;
break;
case RoleType.WaterMaster:
role = WaterMaster.Singleton;
break;
}
UUID playerId = WaterWarsUtils.ParseRawId(rawPlayerId);
ScenePresence scenePresence = null;
// Look for the presence in every scene. If this kind of thing becomes common we will need to refactor the
// code
foreach (Scene scene in m_controller.Scenes)
{
ScenePresence sp = scene.GetScenePresence(playerId);
if (sp != null)
{
scenePresence = sp;
break;
}
}
if (null == scenePresence)
throw new Exception(
string.Format(
"ScenePresence unexpectedly null for player {0} registering for role {1}", playerId, roleType));
Player newPlayer = m_controller.ModelFactory.CreatePlayer(scenePresence.UUID, scenePresence.Name, role);
m_controller.State.AddPlayer(newPlayer);
return newPlayer;
}
/// <summary>
/// Buy a game asset.
/// </summary>
/// This is called by code which only has the ids available.
/// <param name="rawBuyPointId"></param>
/// <param name="rawFieldId"></param>
/// <param name="level"></param>
public AbstractGameAsset BuildGameAsset(string rawBuyPointId, string rawFieldId, int level)
{
UUID buyPointId = WaterWarsUtils.ParseRawId(rawBuyPointId);
UUID fieldId = WaterWarsUtils.ParseRawId(rawFieldId);
BuyPoint bp = GetBuyPoint(buyPointId);
Field f = GetField(bp, fieldId);
Player p = bp.DevelopmentRightsOwner;
return BuildGameAsset(f, p.Role.AllowedAssets[0], level);
}
/// <summary>
/// Buy a game asset
/// </summary>
/// <param name="f"></param>
/// <param name="template"></param>
/// <param name="level"></param>
public AbstractGameAsset BuildGameAsset(
Field f, AbstractGameAsset template, int level)
{
return m_controller.State.BuildGameAsset(f, template, level);
}
/// <summary>
/// Buy a game asset.
/// </summary>
/// <param name="rawBuyPointId"></param>
/// <param name="rawAssetId"></param>
public AbstractGameAsset ContinueBuildingGameAsset(string rawBuyPointId, string rawAssetId)
{
UUID buyPointId = WaterWarsUtils.ParseRawId(rawBuyPointId);
BuyPoint bp = GetBuyPoint(buyPointId);
UUID assetId = WaterWarsUtils.ParseRawId(rawAssetId);
AbstractGameAsset asset = GetAsset(bp, assetId);
return m_controller.State.ContinueBuildingGameAsset(asset);
}
/// <summary>
/// Upgrade a game asset.
/// </summary>
/// This is called by code which only has the ids available.
/// <param name="rawBuyPointId"></param>
/// <param name="rawPlayerId"></param>
/// <param name="level"></param>
public void UpgradeGameAsset(string rawBuyPointId, string rawAssetId, int level)
{
UUID buyPointId = WaterWarsUtils.ParseRawId(rawBuyPointId);
BuyPoint bp = GetBuyPoint(buyPointId);
UUID assetId = WaterWarsUtils.ParseRawId(rawAssetId);
AbstractGameAsset asset = GetAsset(bp, assetId);
m_controller.State.UpgradeGameAsset(bp.DevelopmentRightsOwner, asset, level);
}
/// <summary>
/// Sell a game asset to the economy
/// </summary>
/// <param name="rawBuyPointId"></param>
/// <param name="rawGameAssetId"></param>
public void SellGameAssetToEconomy(string rawBuyPointId, string rawGameAssetId)
{
UUID buyPointId = WaterWarsUtils.ParseRawId(rawBuyPointId);
UUID gameAssetId = WaterWarsUtils.ParseRawId(rawGameAssetId);
BuyPoint bp = GetBuyPoint(buyPointId);
AbstractGameAsset ga = GetAsset(bp, gameAssetId);
m_controller.State.SellGameAssetToEconomy(ga);
}
/// <summary>
/// Remove a particular game asset on a parcel
/// </summary>
/// <param name="buyPointId"></param>
/// <param name="rawGameAssetId">
public Field RemoveGameAsset(string rawBuyPointId, string rawGameAssetId)
{
UUID buyPointId = WaterWarsUtils.ParseRawId(rawBuyPointId);
UUID gameAssetId = WaterWarsUtils.ParseRawId(rawGameAssetId);
BuyPoint bp = GetBuyPoint(buyPointId);
AbstractGameAsset ga = GetAsset(bp, gameAssetId);
return m_controller.State.RemoveGameAsset(ga);
}
/// <summary>
/// Register a buy point
/// </summary>
/// <param name="buyPointId"></param>
/// <param name="buyPointName"></param>
/// <param name="pos"></param>
/// <returns></returns>
public BuyPoint RegisterBuyPoint(SceneObjectGroup so)
{
Vector3 pos = so.AbsolutePosition;
ILandObject osParcel = so.Scene.LandChannel.GetLandObject(pos.X, pos.Y);
RegionInfo regionInfo = so.Scene.RegionInfo;
BuyPoint bp = m_controller.ModelFactory.CreateBuyPoint(so.UUID, so.Name, pos, osParcel, regionInfo);
m_controller.State.RegisterBuyPoint(bp);
return bp;
}
/// <summary>
/// Register a field.
/// </summary>
///
/// This is only used for registration shortly before deletion, currently. Not for continuing a restored game.
///
/// <returns></returns>
public Field RegisterField(SceneObjectGroup so)
{
Vector3 pos = so.AbsolutePosition;
BuyPoint bpFound = FindBuyPointForPosition(so.Scene, pos);
if (null == bpFound)
throw new Exception(string.Format("Could not register field {0} at {1} with any parcel", so.Name, pos));
return m_controller.ModelFactory.CreateField(bpFound, so.UUID, so.Name);
}
// public AbstractGameAsset RegisterGameAsset(IGameState state, SceneObjectGroup so, AbstractGameAssetType type)
// {
// BuyPoint bpFound = FindBuyPointForPosition(state, so.Scene, pos);
// }
/// <summary>
/// Find the buypoint that covers a given position
/// </summary>
/// <param name="pos"></param>
/// <returns>null if no buypoint was found</returns>
protected BuyPoint FindBuyPointForPosition(Scene scene, Vector3 pos)
{
ILandObject osParcel = scene.LandChannel.GetLandObject(pos.X, pos.Y);
BuyPoint bpFound = null;
foreach (BuyPoint bp in m_controller.Game.BuyPoints.Values)
{
if (bp.Location.Parcel == osParcel)
{
bpFound = bp;
break;
}
}
return bpFound;
}
/// <summary>
/// Buy water and development rights for a particular parcel
/// </summary>
/// <param name="rawBuyPointId"></param>
/// <param name="rawPlayerId"></param>
public void BuyLandRights(string rawBuyPointId, string rawPlayerId)
{
UUID playerId = WaterWarsUtils.ParseRawId(rawPlayerId);
Player buyer = GetPlayer(playerId);
UUID buyPointId = WaterWarsUtils.ParseRawId(rawBuyPointId);
BuyPoint bp = GetBuyPoint(buyPointId);
if (buyer.Money < bp.CombinedPrice)
{
// A messy abstraction breaking hack to alert the player that they can't go ahead.
m_controller.HudManager.m_playerIdToHud[buyer.Uuid].m_statusButton.SendAlert(
buyer.Uuid,
string.Format(
"Can't buy rights because they cost {0}{1} and you only have {2}{3}",
WaterWarsConstants.MONEY_UNIT, bp.CombinedPrice,
WaterWarsConstants.MONEY_UNIT, buyer.Money));
}
else
{
m_controller.State.BuyLandRights(bp, buyer);
}
}
/// <summary>
/// Sell rights for a particular parcel
/// </summary>
/// <param name="bp"></param>
/// <param name="buyerId"></param>
/// <param name="rightsType"></param>
/// <param name="price"></param>
public void SellRights(BuyPoint bp, UUID buyerId, RightsType rightsType, int price)
{
Player buyer = GetPlayer(buyerId);
Player sellingPlayer = null;
if (rightsType == RightsType.Water)
sellingPlayer = bp.WaterRightsOwner;
else
sellingPlayer = bp.DevelopmentRightsOwner;
m_log.InfoFormat(
"[WATER WARS]: Starting process of player {0} selling {1} rights on {2} to {3} for {4}",
sellingPlayer.Name, rightsType, bp.Name, buyer.Name, price);
if (m_controller.AttachedToVe)
new AskLandBuyerInteraction(
m_controller,
m_controller.HudManager.m_playerIdToHud[sellingPlayer.Uuid],
m_controller.HudManager.m_playerIdToHud[buyer.Uuid],
bp,
price,
rightsType);
else
m_controller.State.SellRights(bp, buyer, rightsType, price);
}
/// <summary>
/// Sell Water Rights from the player pool.
/// </summary>
/// <param name="bp"></param>
/// <param name="buyerId"></param>
/// <param name="rightsType"></param>
/// <param name="price"></param>
public void SellWaterRights(Player buyer, Player seller, int price, int amount)
{
m_log.InfoFormat(
"[WATER WARS]: Starting process of player {0} selling {1} waters rights to {2} for {3}",
seller.Name, amount, buyer.Name, price);
if (m_controller.AttachedToVe)
new AskWaterRightsBuyerInteraction(
m_controller,
m_controller.HudManager.m_playerIdToHud[seller.Uuid],
m_controller.HudManager.m_playerIdToHud[buyer.Uuid],
amount,
price);
else
m_controller.State.SellWaterRights(buyer, seller, price, amount);
}
/// <summary>
/// Request water rights from other players
/// </summary>
/// <param name="requesterId"></param>
/// <param name="amount"></param>
public void RequestWaterRights(UUID requesterId, int amount)
{
Player requester = GetPlayer(requesterId);
m_log.InfoFormat(
"[WATER WARS]: Starting process of player {0} requesting {1} water rights",
requester.Name, amount);
m_controller.Events.PostToAll(
string.Format("{0} would like to buy rights to {1}",
requester.Name, WaterWarsUtils.GetWaterUnitsText(amount)),
EventLevel.Alert);
}
/// <summary>
/// Request water from other players
/// </summary>
/// <param name="requesterId"></param>
/// <param name="amount"></param>
public void RequestWater(UUID requesterId, int amount)
{
Player requester = GetPlayer(requesterId);
m_log.InfoFormat(
"[WATER WARS]: Starting process of player {0} requesting {1} water",
requester.Name, amount);
m_controller.Events.PostToAll(
string.Format("{0} would like to lease {1}",
requester.Name, WaterWarsUtils.GetWaterUnitsText(amount)),
EventLevel.Alert);
}
/// <summary>
/// Sell water available on a particular parcel
/// </summary>
/// <param name="sellerId"></param>
/// <param name="buyerId"></param>
/// <param name="amount"></param>
/// <param name="price"></param>
public void SellWater(UUID sellerId, UUID buyerId, int amount, int price)
{
Player buyer = GetPlayer(buyerId);
Player seller = GetPlayer(sellerId);
if (m_controller.AttachedToVe)
{
if (amount > seller.Water)
{
// A messy abstraction breaking hack to alert the player that they can't go ahead.
m_controller.HudManager.m_playerIdToHud[seller.Uuid].m_statusButton.SendAlert(
seller.Uuid,
string.Format(
"Can't sell {0} to {1} since you only have {2}",
WaterWarsUtils.GetWaterUnitsText(amount), buyer.Name,
WaterWarsUtils.GetWaterUnitsText(seller.Water)));
}
else
{
new AskWaterBuyerInteraction(
m_controller,
m_controller.HudManager.m_playerIdToHud[seller.Uuid],
m_controller.HudManager.m_playerIdToHud[buyer.Uuid],
amount,
price);
}
}
else
{
m_controller.State.SellWater(seller, buyer, amount, price);
}
}
/// <summary>
/// Use available water on a particular asset on a particular parcel
/// </summary>
/// <param name="rawBuyPointId"></param>
/// <param name="rawAssetId"></param>
/// <param name="rawPlayerId">Temporarily, this can be UUID.Zero if no player id was supplied in the request</param>
/// <param name="amount">
/// Amount of water to use. If this is zero and there already is some water allocated then this signals undo
/// </param>
public void UseWater(string rawBuyPointId, string rawAssetId, string rawPlayerId, int amount)
{
UUID buyPointId = WaterWarsUtils.ParseRawId(rawBuyPointId);
UUID assetId = WaterWarsUtils.ParseRawId(rawAssetId);
UUID playerId = WaterWarsUtils.ParseRawId(rawPlayerId);
BuyPoint bp = GetBuyPoint(buyPointId);
AbstractGameAsset a = GetAsset(bp, assetId);
if (0 == amount)
{
m_controller.State.UndoUseWater(a);
}
else
{
Player p = null;
if (playerId != UUID.Zero)
p = GetPlayer(playerId);
else
p = bp.DevelopmentRightsOwner;
m_controller.State.UseWater(a, p, amount);
}
}
public BuyPoint GetBuyPoint(string rawUuid)
{
return GetBuyPoint(WaterWarsUtils.ParseRawId(rawUuid));
}
public Player GetPlayer(string rawUuid)
{
return GetPlayer(WaterWarsUtils.ParseRawId(rawUuid));
}
public AbstractGameAsset GetAsset(BuyPoint bp, string rawUuid)
{
return GetAsset(bp, WaterWarsUtils.ParseRawId(rawUuid));
}
public Field GetField(BuyPoint bp, string rawUuid)
{
return GetField(bp, WaterWarsUtils.ParseRawId(rawUuid));
}
public BuyPoint GetBuyPoint(UUID uuid)
{
IDictionary<UUID, BuyPoint> buypoints = m_controller.Game.BuyPoints;
lock (buypoints)
{
if (!buypoints.ContainsKey(uuid))
throw new Exception(string.Format("BuyPoint with id {0} does not exist", uuid));
else
return buypoints[uuid];
}
}
public Player GetPlayer(UUID uuid)
{
IDictionary<UUID, Player> players = m_controller.Game.Players;
lock (players)
{
if (!players.ContainsKey(uuid))
throw new Exception(string.Format("Player with id {0} does not exist", uuid));
else
return players[uuid];
}
}
public AbstractGameAsset GetAsset(BuyPoint bp, UUID uuid)
{
lock (bp.GameAssets)
{
if (!bp.GameAssets.ContainsKey(uuid))
throw new Exception(string.Format("Game asset with id {0} in buypoint {1} does not exist", uuid, bp.Name));
else
return bp.GameAssets[uuid];
}
}
public Field GetField(BuyPoint bp, UUID uuid)
{
lock (bp.Fields)
{
if (!bp.Fields.ContainsKey(uuid))
throw new Exception(string.Format("Field with id {0} in buypoint {1} does not exist", uuid, bp.Name));
else
return bp.Fields[uuid];
}
}
}
}
| |
namespace InControl
{
// @cond nodoc
[AutoDiscover]
public class XboxOneWin10AEProfile : UnityInputDeviceProfile
{
public XboxOneWin10AEProfile()
{
Name = "XBox One Controller";
Meta = "XBox One Controller on Windows";
// Link = ""
DeviceClass = InputDeviceClass.Controller;
DeviceStyle = InputDeviceStyle.XboxOne;
IncludePlatforms = new[] {
"Windows"
};
ExcludePlatforms = new[] {
"Windows 7",
"Windows 8"
};
MinSystemBuildNumber = 14393;
JoystickNames = new[] {
"Controller (Xbox One For Windows)",
"Xbox Bluetooth Gamepad"
};
ButtonMappings = new[] {
new InputControlMapping {
Handle = "A",
Target = InputControlType.Action1,
Source = Button( 0 ),
},
new InputControlMapping {
Handle = "B",
Target = InputControlType.Action2,
Source = Button( 1 ),
},
new InputControlMapping {
Handle = "X",
Target = InputControlType.Action3,
Source = Button( 2 ),
},
new InputControlMapping {
Handle = "Y",
Target = InputControlType.Action4,
Source = Button( 3 ),
},
new InputControlMapping {
Handle = "Left Bumper",
Target = InputControlType.LeftBumper,
Source = Button( 4 ),
},
new InputControlMapping {
Handle = "Right Bumper",
Target = InputControlType.RightBumper,
Source = Button( 5 ),
},
new InputControlMapping {
Handle = "View",
Target = InputControlType.View,
Source = Button( 6 ),
},
new InputControlMapping {
Handle = "Menu",
Target = InputControlType.Menu,
Source = Button( 7 ),
},
new InputControlMapping {
Handle = "Left Stick Button",
Target = InputControlType.LeftStickButton,
Source = Button( 8 ),
},
new InputControlMapping {
Handle = "Right Stick Button",
Target = InputControlType.RightStickButton,
Source = Button( 9 ),
},
new InputControlMapping {
Handle = "Guide",
Target = InputControlType.System,
Source = Button( 10 ),
},
};
AnalogMappings = new[] {
new InputControlMapping {
Handle = "Left Stick Left",
Target = InputControlType.LeftStickLeft,
Source = Analog( 0 ),
SourceRange = InputRange.ZeroToMinusOne,
TargetRange = InputRange.ZeroToOne,
},
new InputControlMapping {
Handle = "Left Stick Right",
Target = InputControlType.LeftStickRight,
Source = Analog( 0 ),
SourceRange = InputRange.ZeroToOne,
TargetRange = InputRange.ZeroToOne,
},
new InputControlMapping {
Handle = "Left Stick Up",
Target = InputControlType.LeftStickUp,
Source = Analog( 1 ),
SourceRange = InputRange.ZeroToMinusOne,
TargetRange = InputRange.ZeroToOne,
},
new InputControlMapping {
Handle = "Left Stick Down",
Target = InputControlType.LeftStickDown,
Source = Analog( 1 ),
SourceRange = InputRange.ZeroToOne,
TargetRange = InputRange.ZeroToOne,
},
new InputControlMapping {
Handle = "Right Stick Left",
Target = InputControlType.RightStickLeft,
Source = Analog( 3 ),
SourceRange = InputRange.ZeroToMinusOne,
TargetRange = InputRange.ZeroToOne,
},
new InputControlMapping {
Handle = "Right Stick Right",
Target = InputControlType.RightStickRight,
Source = Analog( 3 ),
SourceRange = InputRange.ZeroToOne,
TargetRange = InputRange.ZeroToOne,
},
new InputControlMapping {
Handle = "Right Stick Up",
Target = InputControlType.RightStickUp,
Source = Analog( 4 ),
SourceRange = InputRange.ZeroToMinusOne,
TargetRange = InputRange.ZeroToOne,
},
new InputControlMapping {
Handle = "Right Stick Down",
Target = InputControlType.RightStickDown,
Source = Analog( 4 ),
SourceRange = InputRange.ZeroToOne,
TargetRange = InputRange.ZeroToOne,
},
new InputControlMapping {
Handle = "DPad Left",
Target = InputControlType.DPadLeft,
Source = Analog( 5 ),
SourceRange = InputRange.ZeroToMinusOne,
TargetRange = InputRange.ZeroToOne,
},
new InputControlMapping {
Handle = "DPad Right",
Target = InputControlType.DPadRight,
Source = Analog( 5 ),
SourceRange = InputRange.ZeroToOne,
TargetRange = InputRange.ZeroToOne,
},
new InputControlMapping {
Handle = "DPad Up",
Target = InputControlType.DPadUp,
Source = Analog( 6 ),
SourceRange = InputRange.ZeroToOne,
TargetRange = InputRange.ZeroToOne,
},
new InputControlMapping {
Handle = "DPad Down",
Target = InputControlType.DPadDown,
Source = Analog( 6 ),
SourceRange = InputRange.ZeroToMinusOne,
TargetRange = InputRange.ZeroToOne,
},
new InputControlMapping {
Handle = "Left Trigger",
Target = InputControlType.LeftTrigger,
Source = Analog2,
SourceRange = InputRange.ZeroToOne,
TargetRange = InputRange.ZeroToOne,
},
new InputControlMapping {
Handle = "Right Trigger",
Target = InputControlType.RightTrigger,
Source = Analog2,
SourceRange = InputRange.ZeroToMinusOne,
TargetRange = InputRange.ZeroToOne,
},
new InputControlMapping {
Handle = "Left Trigger",
Target = InputControlType.LeftTrigger,
Source = Analog( 8 ),
SourceRange = InputRange.ZeroToOne,
TargetRange = InputRange.ZeroToOne,
},
new InputControlMapping {
Handle = "Right Trigger",
Target = InputControlType.RightTrigger,
Source = Analog( 9 ),
SourceRange = InputRange.ZeroToOne,
TargetRange = InputRange.ZeroToOne,
},
};
}
}
// @endcond
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.Xml.Schema
{
using System;
using Microsoft.Xml;
using System.IO;
using System.Collections;
using System.ComponentModel;
using Microsoft.Xml.Serialization;
using System.Threading;
using System.Diagnostics;
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlRoot("schema", Namespace = XmlSchema.Namespace)]
public class XmlSchema : XmlSchemaObject
{
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Namespace"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public const string Namespace = XmlReservedNs.NsXs;
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.InstanceNamespace"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public const string InstanceNamespace = XmlReservedNs.NsXsi;
private XmlSchemaForm _attributeFormDefault = XmlSchemaForm.None;
private XmlSchemaForm _elementFormDefault = XmlSchemaForm.None;
private XmlSchemaDerivationMethod _blockDefault = XmlSchemaDerivationMethod.None;
private XmlSchemaDerivationMethod _finalDefault = XmlSchemaDerivationMethod.None;
private string _targetNs;
private string _version;
private XmlSchemaObjectCollection _includes = new XmlSchemaObjectCollection();
private XmlSchemaObjectCollection _items = new XmlSchemaObjectCollection();
private string _id;
private XmlAttribute[] _moreAttributes;
// compiled info
private bool _isCompiled = false;
private bool _isCompiledBySet = false;
private bool _isPreprocessed = false;
private bool _isRedefined = false;
private int _errorCount = 0;
private XmlSchemaObjectTable _attributes;
private XmlSchemaObjectTable _attributeGroups = new XmlSchemaObjectTable();
private XmlSchemaObjectTable _elements = new XmlSchemaObjectTable();
private XmlSchemaObjectTable _types = new XmlSchemaObjectTable();
private XmlSchemaObjectTable _groups = new XmlSchemaObjectTable();
private XmlSchemaObjectTable _notations = new XmlSchemaObjectTable();
private XmlSchemaObjectTable _identityConstraints = new XmlSchemaObjectTable();
private static int s_globalIdCounter = -1;
private ArrayList _importedSchemas;
private ArrayList _importedNamespaces;
private int _schemaId = -1; //Not added to a set
private Uri _baseUri;
private bool _isChameleon;
private Hashtable _ids = new Hashtable();
private XmlDocument _document;
private XmlNameTable _nameTable;
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.XmlSchema"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSchema() { }
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Read"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static XmlSchema Read(TextReader reader, ValidationEventHandler validationEventHandler)
{
return Read(new XmlTextReader(reader), validationEventHandler);
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Read1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static XmlSchema Read(Stream stream, ValidationEventHandler validationEventHandler)
{
return Read(new XmlTextReader(stream), validationEventHandler);
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Read2"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static XmlSchema Read(XmlReader reader, ValidationEventHandler validationEventHandler)
{
XmlNameTable nameTable = reader.NameTable;
Parser parser = new Parser(SchemaType.XSD, nameTable, new SchemaNames(nameTable), validationEventHandler);
try
{
parser.Parse(reader, null);
}
catch (XmlSchemaException e)
{
if (validationEventHandler != null)
{
validationEventHandler(null, new ValidationEventArgs(e));
}
else
{
throw e;
}
return null;
}
return parser.XmlSchema;
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Write"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Write(Stream stream)
{
Write(stream, null);
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Write1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Write(Stream stream, XmlNamespaceManager namespaceManager)
{
XmlTextWriter xmlWriter = new XmlTextWriter(stream, null);
xmlWriter.Formatting = Formatting.Indented;
Write(xmlWriter, namespaceManager);
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Write2"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Write(TextWriter writer)
{
Write(writer, null);
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Write3"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Write(TextWriter writer, XmlNamespaceManager namespaceManager)
{
XmlTextWriter xmlWriter = new XmlTextWriter(writer);
xmlWriter.Formatting = Formatting.Indented;
Write(xmlWriter, namespaceManager);
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Write4"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Write(XmlWriter writer)
{
Write(writer, null);
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Write5"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Write(XmlWriter writer, XmlNamespaceManager namespaceManager)
{
XmlSerializer serializer = new XmlSerializer(typeof(XmlSchema));
XmlSerializerNamespaces ns;
if (namespaceManager != null)
{
ns = new XmlSerializerNamespaces();
bool ignoreXS = false;
if (this.Namespaces != null)
{ //User may have set both nsManager and Namespaces property on the XmlSchema object
ignoreXS = this.Namespaces.Namespaces["xs"] != null || this.Namespaces.Namespaces.ContainsValue(XmlReservedNs.NsXs);
}
if (!ignoreXS && namespaceManager.LookupPrefix(XmlReservedNs.NsXs) == null &&
namespaceManager.LookupNamespace("xs") == null)
{
ns.Add("xs", XmlReservedNs.NsXs);
}
foreach (string prefix in namespaceManager)
{
if (prefix != "xml" && prefix != "xmlns")
{
ns.Add(prefix, namespaceManager.LookupNamespace(prefix));
}
}
}
else if (this.Namespaces != null && this.Namespaces.Count > 0)
{
Hashtable serializerNS = this.Namespaces.Namespaces;
if (serializerNS["xs"] == null && !serializerNS.ContainsValue(XmlReservedNs.NsXs))
{ //Prefix xs not defined AND schema namespace not already mapped to a prefix
serializerNS.Add("xs", XmlReservedNs.NsXs);
}
ns = this.Namespaces;
}
else
{
ns = new XmlSerializerNamespaces();
ns.Add("xs", XmlSchema.Namespace);
if (_targetNs != null && _targetNs.Length != 0)
{
ns.Add("tns", _targetNs);
}
}
serializer.Serialize(writer, this, ns);
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Compile"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[Obsolete("Use Microsoft.Xml.Schema.XmlSchemaSet for schema compilation and validation. http://go.microsoft.com/fwlink/?linkid=14202")]
public void Compile(ValidationEventHandler validationEventHandler)
{
SchemaInfo sInfo = new SchemaInfo();
sInfo.SchemaType = SchemaType.XSD;
CompileSchema(null, Microsoft.Xml.XmlConfiguration.XmlReaderSection.CreateDefaultResolver(), sInfo, null, validationEventHandler, NameTable, false);
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Compileq"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[Obsolete("Use Microsoft.Xml.Schema.XmlSchemaSet for schema compilation and validation. http://go.microsoft.com/fwlink/?linkid=14202")]
public void Compile(ValidationEventHandler validationEventHandler, XmlResolver resolver)
{
SchemaInfo sInfo = new SchemaInfo();
sInfo.SchemaType = SchemaType.XSD;
CompileSchema(null, resolver, sInfo, null, validationEventHandler, NameTable, false);
}
#pragma warning disable 618
internal bool CompileSchema(XmlSchemaCollection xsc, XmlResolver resolver, SchemaInfo schemaInfo, string ns, ValidationEventHandler validationEventHandler, XmlNameTable nameTable, bool CompileContentModel)
{
//Need to lock here to prevent multi-threading problems when same schema is added to set and compiled
lock (this)
{
//Preprocessing
SchemaCollectionPreprocessor prep = new SchemaCollectionPreprocessor(nameTable, null, validationEventHandler);
prep.XmlResolver = resolver;
if (!prep.Execute(this, ns, true, xsc))
{
return false;
}
//Compilation
SchemaCollectionCompiler compiler = new SchemaCollectionCompiler(nameTable, validationEventHandler);
_isCompiled = compiler.Execute(this, schemaInfo, CompileContentModel);
this.SetIsCompiled(_isCompiled);
//TODO includes isCompiled flag
return _isCompiled;
}
}
#pragma warning restore 618
internal void CompileSchemaInSet(XmlNameTable nameTable, ValidationEventHandler eventHandler, XmlSchemaCompilationSettings compilationSettings)
{
Debug.Assert(_isPreprocessed);
Compiler setCompiler = new Compiler(nameTable, eventHandler, null, compilationSettings);
setCompiler.Prepare(this, true);
_isCompiledBySet = setCompiler.Compile();
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.AttributeFormDefault"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlAttribute("attributeFormDefault"), DefaultValue(XmlSchemaForm.None)]
public XmlSchemaForm AttributeFormDefault
{
get { return _attributeFormDefault; }
set { _attributeFormDefault = value; }
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.BlockDefault"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlAttribute("blockDefault"), DefaultValue(XmlSchemaDerivationMethod.None)]
public XmlSchemaDerivationMethod BlockDefault
{
get { return _blockDefault; }
set { _blockDefault = value; }
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.FinalDefault"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlAttribute("finalDefault"), DefaultValue(XmlSchemaDerivationMethod.None)]
public XmlSchemaDerivationMethod FinalDefault
{
get { return _finalDefault; }
set { _finalDefault = value; }
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.ElementFormDefault"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlAttribute("elementFormDefault"), DefaultValue(XmlSchemaForm.None)]
public XmlSchemaForm ElementFormDefault
{
get { return _elementFormDefault; }
set { _elementFormDefault = value; }
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.TargetNamespace"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlAttribute("targetNamespace", DataType = "anyURI")]
public string TargetNamespace
{
get { return _targetNs; }
set { _targetNs = value; }
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Version"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlAttribute("version", DataType = "token")]
public string Version
{
get { return _version; }
set { _version = value; }
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Includes"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlElement("include", typeof(XmlSchemaInclude)),
XmlElement("import", typeof(XmlSchemaImport)),
XmlElement("redefine", typeof(XmlSchemaRedefine))]
public XmlSchemaObjectCollection Includes
{
get { return _includes; }
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Items"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlElement("annotation", typeof(XmlSchemaAnnotation)),
XmlElement("attribute", typeof(XmlSchemaAttribute)),
XmlElement("attributeGroup", typeof(XmlSchemaAttributeGroup)),
XmlElement("complexType", typeof(XmlSchemaComplexType)),
XmlElement("simpleType", typeof(XmlSchemaSimpleType)),
XmlElement("element", typeof(XmlSchemaElement)),
XmlElement("group", typeof(XmlSchemaGroup)),
XmlElement("notation", typeof(XmlSchemaNotation))]
public XmlSchemaObjectCollection Items
{
get { return _items; }
}
// Compiled info
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.IsCompiled"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlIgnore]
public bool IsCompiled
{
get
{
return _isCompiled || _isCompiledBySet;
}
}
[XmlIgnore]
internal bool IsCompiledBySet
{
get { return _isCompiledBySet; }
set { _isCompiledBySet = value; }
}
[XmlIgnore]
internal bool IsPreprocessed
{
get { return _isPreprocessed; }
set { _isPreprocessed = value; }
}
[XmlIgnore]
internal bool IsRedefined
{
get { return _isRedefined; }
set { _isRedefined = value; }
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Attributes"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlIgnore]
public XmlSchemaObjectTable Attributes
{
get
{
if (_attributes == null)
{
_attributes = new XmlSchemaObjectTable();
}
return _attributes;
}
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.AttributeGroups"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlIgnore]
public XmlSchemaObjectTable AttributeGroups
{
get
{
if (_attributeGroups == null)
{
_attributeGroups = new XmlSchemaObjectTable();
}
return _attributeGroups;
}
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.SchemaTypes"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlIgnore]
public XmlSchemaObjectTable SchemaTypes
{
get
{
if (_types == null)
{
_types = new XmlSchemaObjectTable();
}
return _types;
}
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Elements"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlIgnore]
public XmlSchemaObjectTable Elements
{
get
{
if (_elements == null)
{
_elements = new XmlSchemaObjectTable();
}
return _elements;
}
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Id"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlAttribute("id", DataType = "ID")]
public string Id
{
get { return _id; }
set { _id = value; }
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.UnhandledAttributes"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlAnyAttribute]
public XmlAttribute[] UnhandledAttributes
{
get { return _moreAttributes; }
set { _moreAttributes = value; }
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Groups"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlIgnore]
public XmlSchemaObjectTable Groups
{
get { return _groups; }
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Notations"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlIgnore]
public XmlSchemaObjectTable Notations
{
get { return _notations; }
}
[XmlIgnore]
internal XmlSchemaObjectTable IdentityConstraints
{
get { return _identityConstraints; }
}
[XmlIgnore]
internal Uri BaseUri
{
get { return _baseUri; }
set
{
_baseUri = value;
}
}
[XmlIgnore]
// Please be careful with this property. Since it lazy initialized and its value depends on a global state
// if it gets called on multiple schemas in a different order the schemas will end up with different IDs
// Unfortunately the IDs are used to sort the schemas in the schema set and thus changing the IDs might change
// the order which would be a breaking change!!
// Simply put if you are planning to add or remove a call to this getter you need to be extra carefull
// or better don't do it at all.
internal int SchemaId
{
get
{
if (_schemaId == -1)
{
_schemaId = Interlocked.Increment(ref s_globalIdCounter);
}
return _schemaId;
}
}
[XmlIgnore]
internal bool IsChameleon
{
get { return _isChameleon; }
set { _isChameleon = value; }
}
[XmlIgnore]
internal Hashtable Ids
{
get { return _ids; }
}
[XmlIgnore]
internal XmlDocument Document
{
get { if (_document == null) _document = new XmlDocument(); return _document; }
}
[XmlIgnore]
internal int ErrorCount
{
get { return _errorCount; }
set { _errorCount = value; }
}
internal new XmlSchema Clone()
{
XmlSchema that = new XmlSchema();
that._attributeFormDefault = _attributeFormDefault;
that._elementFormDefault = _elementFormDefault;
that._blockDefault = _blockDefault;
that._finalDefault = _finalDefault;
that._targetNs = _targetNs;
that._version = _version;
that._includes = _includes;
that.Namespaces = this.Namespaces;
that._items = _items;
that.BaseUri = this.BaseUri;
SchemaCollectionCompiler.Cleanup(that);
return that;
}
internal XmlSchema DeepClone()
{
XmlSchema that = new XmlSchema();
that._attributeFormDefault = _attributeFormDefault;
that._elementFormDefault = _elementFormDefault;
that._blockDefault = _blockDefault;
that._finalDefault = _finalDefault;
that._targetNs = _targetNs;
that._version = _version;
that._isPreprocessed = _isPreprocessed;
//that.IsProcessing = this.IsProcessing; //Not sure if this is needed
//Clone its Items
for (int i = 0; i < _items.Count; ++i)
{
XmlSchemaObject newItem;
XmlSchemaComplexType complexType;
XmlSchemaElement element;
XmlSchemaGroup group;
if ((complexType = _items[i] as XmlSchemaComplexType) != null)
{
newItem = complexType.Clone(this);
}
else if ((element = _items[i] as XmlSchemaElement) != null)
{
newItem = element.Clone(this);
}
else if ((group = _items[i] as XmlSchemaGroup) != null)
{
newItem = group.Clone(this);
}
else
{
newItem = _items[i].Clone();
}
that.Items.Add(newItem);
}
//Clone Includes
for (int i = 0; i < _includes.Count; ++i)
{
XmlSchemaExternal newInclude = (XmlSchemaExternal)_includes[i].Clone();
that.Includes.Add(newInclude);
}
that.Namespaces = this.Namespaces;
//that.includes = this.includes; //Need to verify this is OK for redefines
that.BaseUri = this.BaseUri;
return that;
}
[XmlIgnore]
internal override string IdAttribute
{
get { return Id; }
set { Id = value; }
}
internal void SetIsCompiled(bool isCompiled)
{
_isCompiled = isCompiled;
}
internal override void SetUnhandledAttributes(XmlAttribute[] moreAttributes)
{
_moreAttributes = moreAttributes;
}
internal override void AddAnnotation(XmlSchemaAnnotation annotation)
{
_items.Add(annotation);
}
internal XmlNameTable NameTable
{
get { if (_nameTable == null) _nameTable = new Microsoft.Xml.NameTable(); return _nameTable; }
}
internal ArrayList ImportedSchemas
{
get
{
if (_importedSchemas == null)
{
_importedSchemas = new ArrayList();
}
return _importedSchemas;
}
}
internal ArrayList ImportedNamespaces
{
get
{
if (_importedNamespaces == null)
{
_importedNamespaces = new ArrayList();
}
return _importedNamespaces;
}
}
internal void GetExternalSchemasList(IList extList, XmlSchema schema)
{
Debug.Assert(extList != null && schema != null);
if (extList.Contains(schema))
{
return;
}
extList.Add(schema);
for (int i = 0; i < schema.Includes.Count; ++i)
{
XmlSchemaExternal ext = (XmlSchemaExternal)schema.Includes[i];
if (ext.Schema != null)
{
GetExternalSchemasList(extList, ext.Schema);
}
}
}
#if TRUST_COMPILE_STATE
internal void AddCompiledInfo(SchemaInfo schemaInfo) {
XmlQualifiedName itemName;
foreach (XmlSchemaElement element in elements.Values) {
itemName = element.QualifiedName;
schemaInfo.TargetNamespaces[itemName.Namespace] = true;
if (schemaInfo.ElementDecls[itemName] == null) {
schemaInfo.ElementDecls.Add(itemName, element.ElementDecl);
}
}
foreach (XmlSchemaAttribute attribute in attributes.Values) {
itemName = attribute.QualifiedName;
schemaInfo.TargetNamespaces[itemName.Namespace] = true;
if (schemaInfo.ElementDecls[itemName] == null) {
schemaInfo.AttributeDecls.Add(itemName, attribute.AttDef);
}
}
foreach (XmlSchemaType type in types.Values) {
itemName = type.QualifiedName;
schemaInfo.TargetNamespaces[itemName.Namespace] = true;
XmlSchemaComplexType complexType = type as XmlSchemaComplexType;
if ((complexType == null || type != XmlSchemaComplexType.AnyType) && schemaInfo.ElementDeclsByType[itemName] == null) {
schemaInfo.ElementDeclsByType.Add(itemName, type.ElementDecl);
}
}
foreach (XmlSchemaNotation notation in notations.Values) {
itemName = notation.QualifiedName;
schemaInfo.TargetNamespaces[itemName.Namespace] = true;
SchemaNotation no = new SchemaNotation(itemName);
no.SystemLiteral = notation.System;
no.Pubid = notation.Public;
if (schemaInfo.Notations[itemName.Name] == null) {
schemaInfo.Notations.Add(itemName.Name, no);
}
}
}
#endif//TRUST_COMPILE_STATE
}
}
| |
using System;
using System.Xml;
using System.Text;
using System.Collections;
using System.IO;
using System.Security;
namespace Hydra.Framework.XmlSerialization.Exslt
{
//
//**********************************************************************
/// <summary>
/// Specifies the redirecting state of the <c>MultiXmlTextWriter</c>.
/// </summary>
//**********************************************************************
//
internal enum RedirectState
{
//
//**********************************************************************
/// <summary>
/// The output is being relayed further (default).
/// </summary>
//**********************************************************************
//
Relaying,
//
//**********************************************************************
/// <summary>
/// The output is being redirected.
/// </summary>
//**********************************************************************
//
Redirecting,
//
//**********************************************************************
/// <summary>
/// <c><exsl:document></c> attributes are being written
/// </summary>
//**********************************************************************
//
WritingRedirectElementAttrs,
//
//**********************************************************************
/// <summary>
/// <c><exsl:document></c> attribute value is being written
/// </summary>
//**********************************************************************
//
WritingRedirectElementAttrValue
}
//
//**********************************************************************
/// <summary>
/// <para><c>MultiXmlTextWriter</c> class extends standard <see cref="XmlTextWriter"/> class
/// and represents an XML writer that provides a fast,
/// non-cached, forward-only way of generating multiple output files containing
/// either text data or XML data that conforms to the W3C Extensible Markup
/// Language (XML) 1.0 and the Namespaces in XML recommendations.</para>
/// </summary>
/// <remarks>
/// <para>Instances of <c>MultiXmlTextWriter</c> class regognize special element
/// (<c><exsl:document></c> in <c>"http://exslt.org/common"</c> namespace) as
/// instruction to redirect the output of this element's content to another file.
/// When using with <c>XslTransform</c> class, <c>MultiXmlTextWriter</c> class
/// allows to generate multiple XSL Transfromation results.</para>
/// <para><c>MultiXmlTextWriter</c> class extends <c>System.Xml.XmlTextWriter</c>
/// class, therefore its instances can be passed directly to the overloaded
/// <c>XslTransform.Transform()</c> method, which accepts <c>XmlWriter</c> as
/// object to write the transformation result to. All actual XML writing work
/// <c>MultiXmlTextWriter</c> class delegates to its base class, but it overrides
/// several <c>XmlTextWriter</c> class methods to implement output switching logic
/// as follows: once <c><exsl:document></c> element start tag is detected in
/// the XML stream, new writer (<c>XmlTextWriter</c> or <c>StreamWriter</c> depending on
/// <c>method</c> attribute value) object is created with parameters as specified
/// in the attributes of the <c><exsl:document></c> element and the output
/// is switched to this newly created writer untill the end tag of the
/// <c><exsl:document></c> element is encountered.</para>
/// <para><c><exsl:document></c> element syntax is as follows:
/// <code>
/// <exsl:document
/// href = { uri-reference }
/// method = { "xml" | "text" }
/// encoding = { string }
/// omit-xml-declaration = { "yes" | "no" }
/// standalone = { "yes" | "no" }
/// doctype-public = { string }
/// doctype-system = { string }
/// indent = { "yes" | "no" }
/// <-- Content: template -->
/// </exsl:document>
/// </code></para>
/// <para>
/// The <c>href</c> attribute specifies where new result document should be stored,
/// it must be an absolute or relative URI. Relative URIs are resolved
/// relatively to the parent result document base URI. If the <c>href</c> attribute
/// specifies that the output should be redirected to a file in a directory
/// and that directory does not exist, it will be created. This allows to create
/// directory trees of any complexity.</para>
/// <para>Semantics of the rest attributes is as defined in W3C XSLT 1.0 Recommendation
/// for <c><xsl:output></c> element, see
/// <a href="http://www.w3.org/TR/xslt.html#output">http://www.w3.org/TR/xslt.html#output</a>.
/// </para>
/// <para><b>Note:</b> <c><exsl:document></c> element namespace prefix must be bound to
/// <c>"http://exslt.org/common"</c> namespace URI in order to be recognized by
/// <c>MultiXmlTextWriter</c> class as a redirecting instruction. </para>
/// </remarks>
/// <example>This example shows how to use <c>MultiXmlTextWriter</c> along with
/// <c>XslTransform</c> to achieve create multiple result documents in one
/// transfromation run:
/// <para>In XSL stylesheet document declare <c>"http://exslt.org/common"</c> namespace
/// and whenever you want to create new result document make use of <c><exsl:documnet></c>
/// element:<br/>
/// <c>style.xsl</c> stylesheet fragment:
/// <code>
/// <![CDATA[
/// <xsl:stylesheet version="1.0"
/// xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
/// ]]><b>xmlns:exsl= "http://exslt.org/common"</b><![CDATA[
/// ]]><b>exclude-result-prefixes="exsl"</b>><![CDATA[
/// <xsl:template match="book">
/// <!-- Builds frameset -->
/// <html>
/// <head>
/// <title><xsl:value-of select="@title"/></title>
/// </head>
/// <frameset cols="20%,80%">
/// <frame src="toc.html"/>
/// <!-- Builds table of contents output document -->
/// ]]><b><exsl:document href="toc.html" indent="yes"></b><![CDATA[
/// <html>
/// <head>
/// <title>Table of Contents</title>
/// </head>
/// <body>
/// <ul>
/// <xsl:apply-templates mode="toc"/>
/// </ul>
/// </body>
/// </html>
/// ]]><b></exsl:document></b><![CDATA[
/// <frame src="{chapter[1]/@id}.html" name="body" />
/// <xsl:apply-templates />
/// </frameset>
/// </html>
/// ...
///
/// ]]>
/// </code>
/// C# code fragment:
/// <code>
/// XPathDocument doc = new XPathDocument("book.xml");
/// XslTransform xslt = new XslTransform();
/// xslt.Load("style.xsl");
/// MultiXmlTextWriter multiWriter =
/// new MultiXmlTextWriter("index.html", Encoding.UTF8);
/// multiWriter.Formatting = Formatting.Indented;
/// xslt.Transform(doc, null, multiWriter);
/// </code>
/// </para>
/// </example>
//**********************************************************************
//
public class MultiXmlTextWriter
: XmlTextWriter
{
//
//**********************************************************************
/// <summary>
/// This constant is the namespace <c><exsl:document></c> element
/// should belong to in order to be recognized as redirect instruction.
/// It's <c>"http://exslt.org/common"</c> as defined by
/// <a href="http://www.exslt.org">EXSLT community initiative</a>.
/// </summary>
//**********************************************************************
//
protected const string RedirectNamespace = "http://exslt.org/common";
//
//**********************************************************************
/// <summary>
/// This constant is the redirect instruction element name.
/// It's <c>"document"</c> as defined by
/// <a href="http://www.exslt.org">EXSLT community initiative</a>.
/// </summary>
//**********************************************************************
//
protected const string RedirectElementName = "document";
//
// Stack of output states
//
Stack states = null;
//
// Current output state
//
OutputState state = null;
//
// Currently processed attribute name
//
string currentAttributeName;
//
// Redirecting state - relaying by default
//
RedirectState redirectState = RedirectState.Relaying;
//
//**********************************************************************
/// <summary>
/// Creates an instance of the <c>MultiXmlTextWriter</c> class using the specified filename and
/// encoding.
/// Inherited from <c>XmlTextWriter</c>, see <see cref="XmlTextWriter"/>.
/// Overridden to set output directory.
/// </summary>
/// <param name="fileName">The filename to write to. If the file exists, it will truncate it and overwrite it
/// with the new content.</param>
/// <param name="encoding">The encoding to generate. If encoding is a null reference it writes the file out
/// as UTF-8, and omits the encoding attribute from the ProcessingInstruction.</param>
/// <exception cref="ArgumentException">The encoding is not supported; the filename is empty, contains only
/// white space, or contains one or more invalid characters.</exception>
/// <exception cref="UnauthorizedAccessException">Access is denied.</exception>
/// <exception cref="ArgumentNullException">The filename is a null reference.</exception>
/// <exception cref="DirectoryNotFoundException">The directory to write to is not found.</exception>
/// <exception cref="IOException">The filename includes an incorrect or invalid syntax
/// for file name, directory name, or volume label syntax.</exception>
/// <exception cref="SecurityException">The caller does not have the required permission.</exception>
//**********************************************************************
//
public MultiXmlTextWriter(String fileName, Encoding encoding)
: base(fileName, encoding)
{
DirectoryInfo dir = Directory.GetParent(fileName);
Directory.SetCurrentDirectory(dir.ToString());
}
//
//**********************************************************************
/// <summary>
/// Creates an instance of the <c>MultiXmlTextWriter</c> class using the specified
/// <c>TextWriter</c>, see <see cref="TextWriter"/>.
/// Inherited from <c>XmlTextWriter</c>, see <see cref="XmlTextWriter"/>.
/// </summary>
/// <param name="w">The <c>TextWriter</c> to write to. It is assumed that the <c>TextWriter</c> is
/// already set to the correct encoding.</param>
//**********************************************************************
//
public MultiXmlTextWriter(TextWriter w)
: base(w)
{
}
//
//**********************************************************************
/// <summary>
/// Creates an instance of the <c>MultiXmlTextWriter</c> class using the specified
/// stream and encoding.
/// Inherited from <c>XmlTextWriter</c>, see <see cref="XmlTextWriter"/>.
/// </summary>
/// <param name="w">The stream to which you want to write.</param>
/// <param name="encoding">The encoding to generate. If encoding is a null
/// reference it writes out the stream as UTF-8 and omits the encoding attribute
/// from the ProcessingInstruction.</param>
/// <exception cref="ArgumentException">The encoding is not supported or the stream
/// cannot be written to.</exception>
/// <exception cref="ArgumentNullException">w is a null reference.</exception>
//**********************************************************************
//
public MultiXmlTextWriter(Stream w, Encoding encoding)
: base(w, encoding)
{
}
//
//**********************************************************************
/// <summary>
/// Checks possible start of <c><exsl:document></c> element content.
/// </summary>
/// <remarks>
/// When <c><exsl:document></c> element start tag is detected, the beginning of the
/// element's content might be detected as any next character data (not attribute
/// value though), element start tag, processing instruction or comment.
/// </remarks>
/// <exception cref="ArgumentNullException">Thrown when <c>href</c> attribute is absent.</exception>
/// <exception cref="ArgumentException">Thrown when a document, specified by <c>href</c> attribute is
/// opened alreary. Two nested <c><exsl:document></c></exception> elements cannot specify the same
/// output URI in their <c>href</c> attributes.
//**********************************************************************
//
private void CheckContentStart()
{
if (redirectState == RedirectState.WritingRedirectElementAttrs)
{
//
// Check required href attribute
//
if (state.Href == null)
throw new ArgumentNullException("'href' attribute of exsl:document element must be specified.");
//
// Are we writing to this URI already?
//
foreach (OutputState nestedState in states)
if (nestedState.Href == state.Href)
throw new ArgumentException("Cannot write to " + state.Href + " two documents simultaneously.");
state.InitWriter();
redirectState = RedirectState.Redirecting;
}
}
//
//**********************************************************************
/// <summary>
/// Writes the specified start tag and associates it with the given namespace and prefix.
/// Inherited from <c>XmlTextWriter</c>, see <see cref="XmlTextWriter.WriteStartElement"/>
/// Overridden to detect <c>exsl:document</c> element start tag.
/// </summary>
/// <param name="prefix">The namespace prefix of the element.</param>
/// <param name="localName">The local name of the element.</param>
/// <param name="ns">The namespace URI to associate with the element. If this namespace
/// is already in scope and has an associated prefix then the writer will automatically write that prefix also. </param>
/// <exception cref="InvalidOperationException">The writer is closed.</exception>
//**********************************************************************
//
public override void WriteStartElement(string prefix, string localName, string ns)
{
CheckContentStart();
//
// Is it exsl:document redirecting instruction?
//
if (ns == RedirectNamespace && localName == RedirectElementName)
{
//
// Lazy stack of states
//
if (states == null)
states = new Stack();
//
// If we are redirecting already - push the current state into the stack
//
if (redirectState == RedirectState.Redirecting)
states.Push(state);
//
// Initialize new state
//
state = new OutputState();
redirectState = RedirectState.WritingRedirectElementAttrs;
}
else
{
if (redirectState == RedirectState.Redirecting)
{
if (state.Method == OutputMethod.Text)
{
state.Depth++;
return;
}
//
// Write doctype before the first element
//
if (state.Depth == 0 && state.SystemDoctype != null)
if (prefix != String.Empty)
state.XmlWriter.WriteDocType(prefix + ":" + localName,
state.PublicDoctype, state.SystemDoctype, null);
else
state.XmlWriter.WriteDocType(localName,
state.PublicDoctype, state.SystemDoctype, null);
state.XmlWriter.WriteStartElement(prefix, localName, ns);
state.Depth++;
}
else
base.WriteStartElement(prefix, localName, ns);
}
}
//
//**********************************************************************
/// <summary>
/// Finishes output redirecting - closes current writer
/// and pops previous state.
/// </summary>
//**********************************************************************
//
internal void FinishRedirecting()
{
state.CloseWriter();
//
// Pop previous state if it exists
//
if (states.Count != 0)
{
state = (OutputState)states.Pop();
redirectState = RedirectState.Redirecting;
}
else
{
state = null;
redirectState = RedirectState.Relaying;
}
}
//
//**********************************************************************
/// <summary>
/// Closes one element and pops the corresponding namespace scope.
/// Inherited from <c>XmlTextWriter</c>, see <see cref="XmlTextWriter.WriteEndElement"/>
/// Overridden to detect <c>exsl:document</c> element end tag.
/// </summary>
//**********************************************************************
//
public override void WriteEndElement()
{
CheckContentStart();
if (redirectState == RedirectState.Redirecting)
{
//
// Check if that's exsl:document end tag
//
if (state.Depth-- == 0)
FinishRedirecting();
else
{
if (state.Method == OutputMethod.Text)
return;
state.XmlWriter.WriteEndElement();
}
}
else
base.WriteEndElement();
}
//
//**********************************************************************
/// <summary>
/// Closes one element and pops the corresponding namespace scope.
/// Inherited from <c>XmlTextWriter</c>, see <see cref="XmlTextWriter.WriteFullEndElement"/>
/// Overridden to detect <c>exsl:document</c> element end tag.
/// </summary>
//**********************************************************************
//
public override void WriteFullEndElement()
{
CheckContentStart();
if (redirectState == RedirectState.Redirecting)
{
//
// Check if it's exsl:document end tag
//
if (state.Depth-- == 0)
FinishRedirecting();
else
{
if (state.Method == OutputMethod.Text)
return;
state.XmlWriter.WriteFullEndElement();
}
}
else
base.WriteFullEndElement();
}
//
//**********************************************************************
/// <summary>
/// Writes the start of an attribute.
/// Inherited from <c>XmlTextWriter</c>, see <see cref="XmlTextWriter.WriteStartAttribute"/>
/// Overridden to detect <c>exsl:document</c> attribute names and to redirect
/// the output.
/// </summary>
/// <param name="prefix">Namespace prefix of the attribute.</param>
/// <param name="localName">Local name of the attribute.</param>
/// <param name="ns">Namespace URI of the attribute.</param>
/// <exception cref="ArgumentException"><c>localName</c>c> is either a null reference or <c>String.Empty</c>.</exception>
//**********************************************************************
//
public override void WriteStartAttribute(string prefix, string localName, string ns)
{
if (redirectState == RedirectState.WritingRedirectElementAttrs)
{
redirectState = RedirectState.WritingRedirectElementAttrValue;
currentAttributeName = localName;
}
else if (redirectState == RedirectState.Redirecting)
{
if (state.Method == OutputMethod.Text)
return;
state.XmlWriter.WriteStartAttribute(prefix, localName, ns);
}
else
base.WriteStartAttribute(prefix, localName, ns);
}
//
//**********************************************************************
/// <summary>
/// Closes the previous <c>WriteStartAttribute</c> call.
/// Inherited from <c>XmlTextWriter</c>, see <see cref="XmlTextWriter.WriteEndAttribute"/>
/// Overridden to redirect the output.
/// </summary>
//**********************************************************************
//
public override void WriteEndAttribute()
{
if (redirectState == RedirectState.WritingRedirectElementAttrValue)
redirectState = RedirectState.WritingRedirectElementAttrs;
else if (redirectState == RedirectState.Redirecting)
{
if (state.Method == OutputMethod.Text)
return;
state.XmlWriter.WriteEndAttribute();
}
else
base.WriteEndAttribute();
}
//
//**********************************************************************
/// <summary>
/// Writes out a comment <!--...--> containing the specified text.
/// Inherited from <c>XmlTextWriter</c>, see <see cref="XmlTextWriter.WriteComment"/>
/// Overriden to redirect the output.
/// </summary>
/// <param name="text">Text to place inside the comment.</param>
/// <exception cref="ArgumentException">The text would result in a non-well formed XML document.</exception>
/// <exception cref="InvalidOperationException">The <c>WriteState</c> is Closed.</exception>
//**********************************************************************
//
public override void WriteComment(string text)
{
CheckContentStart();
if (redirectState == RedirectState.Redirecting)
{
if (state.Method == OutputMethod.Text)
return;
state.XmlWriter.WriteComment(text);
}
else
base.WriteComment(text);
}
//
//**********************************************************************
/// <summary>
/// Writes out a processing instruction with a space between the name
/// and text as follows: <?name text?>.
/// Inherited from <c>XmlTextWriter</c>, see <see cref="XmlTextWriter.WriteProcessingInstruction"/>
/// Overridden to redirect the output.
/// </summary>
/// <param name="name">StateName of the processing instruction.</param>
/// <param name="text">Text to include in the processing instruction.</param>
/// <exception cref="ArgumentException"><para>The text would result in a non-well formed XML document.</para>
/// <para><c>name</c> is either a null reference or <c>String.Empty</c>.</para>
/// <para>This method is being used to create an XML declaration after
/// <c>WriteStartDocument</c> has already been called.</para></exception>
//**********************************************************************
//
public override void WriteProcessingInstruction(string name, string text)
{
CheckContentStart();
if (redirectState == RedirectState.Redirecting)
{
if (state.Method == OutputMethod.Text)
return;
state.XmlWriter.WriteProcessingInstruction(name, text);
}
else
base.WriteProcessingInstruction(name, text);
}
//
//**********************************************************************
/// <summary>
/// Writes the given text content.
/// Inherited from <c>XmlTextWriter</c>, see <see cref="XmlTextWriter.WriteString"/>
/// Overridden to detect <c>exsl:document</c> element attribute values and to
/// redirect the output.
/// </summary>
/// <param name="text">Text to write.</param>
/// <exception cref="ArgumentException">The text string contains an invalid surrogate pair.</exception>
//**********************************************************************
//
public override void WriteString(string text)
{
//
// Possible exsl:document's attribute value
//
if (redirectState == RedirectState.WritingRedirectElementAttrValue)
{
switch (currentAttributeName)
{
case "href":
state.Href = text;
break;
case "method":
if (text == "text")
state.Method = OutputMethod.Text;
break;
case "encoding":
try
{
state.Encoding = Encoding.GetEncoding(text);
}
catch (Exception)
{
}
break;
case "indent":
if (text == "yes")
state.Indent = true;
break;
case "doctype-public":
state.PublicDoctype = text;
break;
case "doctype-system":
state.SystemDoctype = text;
break;
case "standalone":
if (text == "yes")
state.Standalone = true;
break;
case "omit-xml-declaration":
if (text == "yes")
state.OmitXmlDeclaration = true;
break;
default:
break;
}
return;
}
else
CheckContentStart();
if (redirectState == RedirectState.Redirecting)
{
if (state.Method == OutputMethod.Text)
state.TextWriter.Write(text);
else
state.XmlWriter.WriteString(text);
}
else
base.WriteString(text);
}
}
}
| |
// GridDataViewBinder.cs
//
using jQueryApi;
using Slick;
using Slick.Data;
using SparkleXrm.jQueryPlugins;
using System;
using System.Collections.Generic;
using System.Html;
using System.Runtime.CompilerServices;
using Xrm;
using Xrm.Sdk;
using Xrm.Sdk.Metadata;
namespace SparkleXrm.GridEditor
{
public class GridDataViewBinder
{
public bool SelectActiveRow = true;
public bool AddCheckBoxSelectColumn = true;
public bool MultiSelect = true;
private string _sortColumnName;
private Grid _grid;
/// <summary>
/// DataBinds a DataView that inherits from DataViewBase
///
/// </summary>
/// <param name="dataView"></param>
/// <param name="columns"></param>
/// <param name="gridId"></param>
/// <param name="pagerId"></param>
/// <param name="editable"></param>
/// <param name="allowAddNewRow"></param>
/// <returns></returns>
public Grid DataBindXrmGrid(DataViewBase dataView, List<Column> columns, string gridId, string pagerId,bool editable, bool allowAddNewRow )
{
// Always add an empty column on the end for reszing purposes
ArrayEx.Add(columns, new Column());
GridOptions gridOptions = new GridOptions();
gridOptions.EnableCellNavigation = true;
gridOptions.AutoEdit = editable;
gridOptions.Editable = editable;
gridOptions.AsyncEditorLoading = true;
gridOptions.EnableAddRow = allowAddNewRow;
// Set non-variable options
gridOptions.RowHeight = PageEx.MajorVersion==2013 ? 30 : 20;
gridOptions.HeaderRowHeight = 25;
//gridOptions.ForceFitColumns = true;
gridOptions.EnableColumnReorder = false;
CheckboxSelectColumn checkBoxSelector = null;
if (AddCheckBoxSelectColumn)
{
CheckboxSelectColumnOptions checkboxOptions = new CheckboxSelectColumnOptions();
checkboxOptions.cssClass = "sparkle-checkbox-column";
// Add check box column
checkBoxSelector = new CheckboxSelectColumn(checkboxOptions);
Column checkBoxColumn = checkBoxSelector.GetColumnDefinition();
columns.Insert(0, checkBoxColumn);
}
Grid grid = new Grid("#" + gridId, dataView, columns, gridOptions);
if (AddCheckBoxSelectColumn)
{
grid.RegisterPlugin(checkBoxSelector);
}
this.DataBindSelectionModel(grid, dataView);
if (!string.IsNullOrEmpty(pagerId))
{
CrmPagerControl pager = new CrmPagerControl(dataView, grid, jQuery.Select("#" + pagerId));
}
DataBindEvents(grid, dataView, gridId);
AddValidation(grid, dataView);
AddRefreshButton(gridId, dataView);
// Add resize event
jQuery.Window.Resize(delegate(jQueryEvent e){
// Set each column to be non resizable while we do the resize
FreezeColumns(grid, true);
grid.ResizeCanvas();
// Restore the resizing
FreezeColumns(grid, false);
});
dataView.OnDataLoaded.Subscribe(delegate(EventData e, object o)
{
FreezeColumns(grid,false);
});
_grid = grid;
return grid;
}
/// <summary>
/// Data Binds the standard Slick.DataView
/// </summary>
/// <param name="columns"></param>
/// <param name="dataView"></param>
/// <returns></returns>
public Grid DataBindDataViewGrid(DataView dataView, List<Column> columns, string gridId, string pagerId, bool editable, bool allowAddNewRow)
{
// Always add an empty column on the end for reszing purposes
ArrayEx.Add(columns, new Column());
GridOptions gridOptions = new GridOptions();
gridOptions.EnableCellNavigation = true;
gridOptions.AutoEdit = editable;
gridOptions.Editable = editable;
gridOptions.EnableAddRow = allowAddNewRow;
// Set non-variable options
gridOptions.RowHeight = 20;
gridOptions.HeaderRowHeight = 25;
gridOptions.EnableColumnReorder = false;
CheckboxSelectColumn checkBoxSelector = null;
if (AddCheckBoxSelectColumn)
{
CheckboxSelectColumnOptions checkboxOptions = new CheckboxSelectColumnOptions();
checkboxOptions.cssClass = "sparkle-checkbox-column";
// Add check box column
checkBoxSelector = new CheckboxSelectColumn(checkboxOptions);
Column checkBoxColumn = checkBoxSelector.GetColumnDefinition();
columns.Insert(0, checkBoxColumn);
}
Grid grid = new Grid("#" + gridId, dataView, columns, gridOptions);
grid.RegisterPlugin(checkBoxSelector);
dataView.OnRowsChanged.Subscribe(delegate(EventData e, object a)
{
// Only invalided the rows that have changed
OnRowsChangedEventArgs args = (OnRowsChangedEventArgs)a;
if (args != null && args.Rows != null)
{
grid.InvalidateRows(args.Rows);
grid.Render();
}
});
//AddValidation(grid, dataView);
// Add resize event
jQuery.Window.Resize(delegate(jQueryEvent e)
{
// Set each column to be non resizable while we do the resize
GridDataViewBinder.FreezeColumns(grid, true);
grid.ResizeCanvas();
// Restore the resizing
GridDataViewBinder.FreezeColumns(grid, false);
});
// Add Reset binding
Action reset = delegate() { };
Script.Literal("{0}.reset={1}", dataView, reset);
// Add Refresh button
AddRefreshButton(gridId, (DataViewBase)(object)dataView);
// Add Selection Model
RowSelectionModelOptions selectionModelOptions = new RowSelectionModelOptions();
selectionModelOptions.SelectActiveRow = true;
RowSelectionModel selectionModel = new RowSelectionModel(selectionModelOptions);
grid.SetSelectionModel(selectionModel);
// Set sorting
Action<EventData,object> onSort = delegate (EventData e, object a)
{
SortColData args = (SortColData)a;
//SortDir = args.SortAsc ? 1 : -1;
_sortColumnName = args.SortCol.Field;
dataView.Sort(Comparer, args.SortAsc);
};
grid.OnSort.Subscribe(onSort);
return grid;
}
public int Comparer(object l, object r)
{
Dictionary<string, object> a = (Dictionary<string, object>)l;
Dictionary<string, object> b = (Dictionary<string, object>)r;
object x = a[_sortColumnName], y = b[_sortColumnName];
return (x == y ? 0 : ((bool)Script.Literal("{0} > {1}", x, y) ? 1 : -1));
}
/// <summary>
/// Binds the click handler for opening records from the grid attributes -see the formatters for attributes provided
/// </summary>
/// <param name="grid"></param>
public void BindClickHandler(Grid grid)
{
Action<string, string> openEntityRecord = delegate(string logicalName, string id)
{
Utility.OpenEntityForm(logicalName, id, null);
};
grid.OnClick.Subscribe(delegate(EventData e, object sender)
{
CellSelection cell = (CellSelection)sender;
bool handled = false;
Element element = e.SrcElement;
object logicalName = element.GetAttribute("logicalName");
object id = element.GetAttribute("id");
object primaryNameLookup = element.GetAttribute("primaryNameLookup");
if (logicalName != null & id != null)
{
// Open the related record
handled = true;
}
else if (primaryNameLookup != null)
{
// Open the primary entity record
handled = true;
Entity entity = (Entity)cell.Grid.GetDataItem(cell.Row.Value);
logicalName = entity.LogicalName;
// If there is an activitytypecode then use that
string activitytypecode = entity.GetAttributeValueString("activitytypecode");
if (activitytypecode != null)
logicalName = activitytypecode;
id = entity.Id;
}
if (handled)
{
openEntityRecord((string)logicalName, (string)id);
e.StopImmediatePropagation();
e.StopPropagation();
}
});
grid.OnDblClick.Subscribe(delegate(EventData e, object sender)
{
CellSelection cell = (CellSelection)sender;
Entity entity = (Entity)cell.Grid.GetDataItem(cell.Row.Value);
string logicalName = entity.LogicalName;
// If there is an activitytypecode then use that
string activitytypecode = entity.GetAttributeValueString("activitytypecode");
if (activitytypecode != null)
logicalName = activitytypecode;
openEntityRecord(logicalName, entity.Id);
e.StopImmediatePropagation();
e.StopPropagation();
});
}
private static void FreezeColumns(Grid grid, bool freeze)
{
// Columns are added initially with their max and min width the same so they are not stretched to fit the width
// Now we restore column resizing
Column[] cols = grid.GetColumns();
for (int i = 0; i < cols.Length - 1; i++)
{
Column col = cols[i];
if (freeze)
{
col.MaxWidth = col.Width;
col.MinWidth = col.Width;
}
else
{
col.MaxWidth = null;
col.MinWidth = null;
}
}
}
public void AddValidation(Grid grid, DataViewBase dataView)
{
Action<string, Column> setValidator = delegate(string attributeName, Column col)
{
col.Validator = delegate(object value, object item)
{
Func<string,GridValidatorDelegate> indexer = dataView.GridValidationIndexer();
GridValidatorDelegate validationRule = indexer(attributeName);
if (validationRule != null)
return validationRule(value, item);
else
{
ValidationResult result = new ValidationResult();
result.Valid = true;
return result;
}
};
};
if (dataView.GridValidationIndexer() != null)
{
foreach (Column col in grid.GetColumns())
{
string fieldName = col.Field;
setValidator(fieldName, col);
}
}
}
public void DataBindSelectionModel(Grid grid, DataViewBase dataView)
{
// Set up selection model if needed
// Create selection model
RowSelectionModelOptions selectionModelOptions = new RowSelectionModelOptions();
selectionModelOptions.SelectActiveRow = SelectActiveRow;
selectionModelOptions.MultiRowSelect = this.MultiSelect;
RowSelectionModel selectionModel = new RowSelectionModel(selectionModelOptions);
// Bind two way sync of selected rows
// NOTE: the row index on the grid is not the row index in the data view due to paging
bool inHandler = false;
selectionModel.OnSelectedRangesChanged.Subscribe(delegate(EventData e, object args)
{
//if (grid.GetEditorLock().IsActive())
//{
// e.StopPropagation();
// return;
//}
if (inHandler)
return;
inHandler = true;
// Has the selected row changeD?
SelectedRange[] selectedRows = dataView.GetSelectedRows();
SelectedRange[] newSelectedRows = (SelectedRange[])args;
bool changed = selectedRows.Length!=newSelectedRows.Length;
if (!changed)
{
// Compare the actual selected rows
for (int i = 0; i < selectedRows.Length; i++)
{
if (selectedRows[i].FromRow!=newSelectedRows[i].FromRow)
{
changed = true;
break;
}
}
}
if (changed)
{
dataView.RaiseOnSelectedRowsChanged(newSelectedRows);
}
inHandler = false;
});
dataView.OnSelectedRowsChanged+=delegate()
{
//if (grid.GetEditorLock().IsActive())
// return;
if (inHandler)
return;
inHandler = true;
SelectedRange[] ranges = dataView.GetSelectedRows();
int[] selectedRows = new int[ranges.Length];
for (int i=0;i<selectedRows.Length;i++)
{
selectedRows[i] = ranges[i].FromRow.Value;
}
grid.SetSelectedRows(selectedRows);
inHandler = false;
};
grid.SetSelectionModel(selectionModel);
}
public void AddRefreshButton(string gridId, DataViewBase dataView)
{
jQueryObject gridDiv = jQuery.Select("#" + gridId);
jQueryObject refreshButton = jQuery.FromHtml("<div id='refreshButton' class='sparkle-grid-refresh-button' style='left: auto; right: 0px; display: inline;'><a href='#' id='refreshButtonLink' tabindex='0'><img id='grid_refresh' src='../../sparkle_/css/images/transparent_spacer.gif' class='sparkle-grid-refresh-button-img' style='cursor:pointer' alt='Refresh list' title='Refresh list'></a></div>").AppendTo(gridDiv);
refreshButton.Find("#refreshButtonLink").Click(delegate(jQueryEvent e)
{
dataView.Reset();
dataView.Refresh();
});
}
public void DataBindEvents(Grid grid,DataViewBase dataView,string gridContainerDivId)
{
// Data Sorting
grid.OnSort.Subscribe(delegate(EventData o, Object item)
{
SortColData sorting = (SortColData)item;
dataView.Sort(sorting);
grid.Invalidate();
grid.Render();
});
// Session Grid DataBinding
grid.OnAddNewRow.Subscribe(delegate(EventData o, Object item)
{
EditEventData data = (EditEventData)item;
dataView.AddItem(data.item);
Column column = data.column;
grid.InvalidateRow(dataView.GetLength() - 1);
grid.UpdateRowCount();
grid.Render();
});
dataView.OnRowsChanged.Subscribe(delegate(EventData e, object a)
{
OnRowsChangedEventArgs args = (OnRowsChangedEventArgs)a;
if (args != null && args.Rows != null)
{
grid.InvalidateRows(args.Rows);
grid.Render();
}
else
{
// Assume that a new row has been added
grid.InvalidateRow(dataView.GetLength());
grid.UpdateRowCount();
grid.Render();
}
grid.ResizeCanvas();
});
jQueryObject loadingIndicator = null;
// Wire up the validation error
jQueryObject validationIndicator = null;
Action<EventData, object> clearValidationIndicator = delegate(EventData e, object a)
{
if (validationIndicator != null)
{
validationIndicator.Hide();
validationIndicator.Remove();
}
};
grid.OnCellChange.Subscribe(clearValidationIndicator);
grid.OnActiveCellChanged.Subscribe(clearValidationIndicator);
grid.OnBeforeCellEditorDestroy.Subscribe(clearValidationIndicator);
grid.OnValidationError.Subscribe(delegate(EventData e, object a)
{
ValidationEventArgs args = (ValidationEventArgs)a;
ValidationResult validationResult = (ValidationResult)args.ValidationResults;
jQueryObject activeCellNode = (jQueryObject)args.CellNode;
object editor = args.Editor;
string errorMessage = "";
if (validationResult.Message != null)
errorMessage = validationResult.Message;
bool valid_result = validationResult.Valid;
// Add the message to the tooltip on the cell
if (!valid_result)
{
jQuery.FromObject(activeCellNode).Attribute("title", errorMessage);
clearValidationIndicator(e,a);
validationIndicator = jQuery.FromHtml("<div class='popup-box-container'><div width='16px' height='16px' class='sparkle-imagestrip-inlineedit_warning popup-box-icon' alt='Error' id='icon'/><div class='popup-box validation-text'/></div>").AppendTo(Document.Body);
validationIndicator.Find(".validation-text").Text(errorMessage);
Script.Literal(@"{0}.position({{
my: 'left bottom',
at: 'left top',
collision: 'fit fit',
of: {1}
}})
.show({{
effect: 'blind'
}})
.delay( 500000 )
.hide({{
effect: 'fade',
duration: 'slow',
}},
function() {{
$( this ).remove();
}});
", validationIndicator, activeCellNode);
}
else
{
clearValidationIndicator(e, a);
jQuery.FromObject(activeCellNode).Attribute("title", "");
}
});
// Wire up the loading spinner
dataView.OnDataLoading.Subscribe(delegate(EventData e, object a)
{
loadingIndicator = ShowLoadingIndicator(loadingIndicator, gridContainerDivId);
foreach (Column col in grid.GetColumns())
{
if (col.MaxWidth != null)
col.MaxWidth = 400;
}
});
dataView.OnDataLoaded.Subscribe(delegate(EventData e, object a)
{
DataLoadedNotifyEventArgs args = (DataLoadedNotifyEventArgs)a;
if (args != null)
{
if (args.ErrorMessage == null)
{
for (int i = args.From; i <= args.To; i++)
{
grid.InvalidateRow(i);
}
grid.UpdateRowCount();
grid.Render();
}
else
Script.Alert("There was a problem refreshing the grid.\nPlease contact your system administrator:\n" + args.ErrorMessage);
}
if (loadingIndicator != null)
loadingIndicator.Plugin<jQueryBlockUI>().Unblock();
});
// Wire up edit complete to property changed
grid.OnCellChange.Subscribe(delegate(EventData e, object data)
{
OnCellChangedEventData eventData = (OnCellChangedEventData)data;
dataView.RaisePropertyChanged("");
});
}
private static jQueryObject ShowLoadingIndicator(jQueryObject loadingIndicator, string gridContainerDivId)
{
jQueryObject g = jQuery.Select("#" + gridContainerDivId);
jQueryObject vp = jQuery.Select("#" + gridContainerDivId + " > .slick-viewport");
loadingIndicator = g;
jQueryBlockUIOptions blockOpts = new jQueryBlockUIOptions();
blockOpts.ShowOverlay = false;
blockOpts.IgnoreIfBlocked = true;
BlockUICSS css = new BlockUICSS();
css.border = "0px";
css.backgroundColor = "transparent";
//css.width = "100px";
//css.height = "100px";
OverlayCSS overlayCss = new OverlayCSS();
overlayCss.Opacity = "0";
//blockOpts.OverlayCSS = overlayCss;
blockOpts.Css = css;
blockOpts.Message = "<span class='loading-indicator'><label>Loading...</label></span>";
loadingIndicator.Plugin<jQueryBlockUI>().Block(blockOpts);
return loadingIndicator;
}
public static Column AddColumn(List<Column> cols, string displayName, int width, string field)
{
Column col = NewColumn(field, displayName, width);
ArrayEx.Add(cols, col);
return col;
}
public static List<Column> ParseLayout(string layout)
{
string[] layoutParts = layout.Split(',');
List<Column> cols = new List<Column>();
for (int i = 0; i < layoutParts.Length; i = i + 3)
{
string field = layoutParts[i + 1];
string name = layoutParts[i];
int width =int.Parse(layoutParts[i + 2]);
Column col = NewColumn(field, name, width);
ArrayEx.Add(cols, col);
}
return cols;
}
public static Column NewColumn(string field, string name, int width)
{
Column col = new Column();
col.Id = name;
col.Name = name;
col.Width = width;
col.MinWidth = col.Width;
col.Field = field;
col.Sortable = true;
col.Formatter = ColumnFormatter;
return col;
}
public static string ColumnFormatter(int row, int cell, object value, Column columnDef, object dataContext)
{
string typeName;
string returnValue = String.Empty;
if (columnDef.DataType != null)
typeName = columnDef.DataType;
else
typeName = value.GetType().Name;
Entity entityContext = (Entity)dataContext;
bool unchanged = (entityContext.EntityState==null) || (entityContext.EntityState == EntityStates.Unchanged);
// If unchanged we can get values from the formatted values
if (unchanged && entityContext.FormattedValues!=null && entityContext.FormattedValues.ContainsKey(columnDef.Field+"name"))
{
returnValue = entityContext.FormattedValues[columnDef.Field + "name"];
return returnValue;
}
if (value != null)
{
switch (typeName.ToLowerCase())
{
case "string":
returnValue = value.ToString();
break;
case "boolean":
case "bool":
returnValue = value.ToString();
break;
case "dateTime":
case "date":
DateTime dateValue = (DateTime)value;
string dateFormat = "dd/mm/yy";
string timeFormat = "hh:MM";
if (OrganizationServiceProxy.UserSettings != null)
{
dateFormat = OrganizationServiceProxy.UserSettings.DateFormatString;
timeFormat = OrganizationServiceProxy.UserSettings.TimeFormatString;
}
returnValue = DateTimeEx.FormatDateSpecific(dateValue, dateFormat) + " " + DateTimeEx.FormatTimeSpecific(dateValue, timeFormat);
break;
case "decimal":
returnValue = value.ToString();
break;
case "double":
returnValue = value.ToString();
break;
case "int":
returnValue = value.ToString();
break;
case "guid":
returnValue = value.ToString();
break;
case "money":
Money moneyValue = (Money)value;
returnValue = moneyValue.Value.ToString();
break;
case "customer":
case "owner":
case "lookup":
case "entityreference":
EntityReference refValue = (EntityReference)value;
returnValue = @"<a class=""sparkle-grid-link"" href=""#"" logicalName=""" + refValue.LogicalName + @""" id=""" + refValue.Id + @""">" + refValue.Name + "</a>";
break;
case "picklist":
case "status":
case "state":
case "optionsetvalue":
OptionSetValue optionValue = (OptionSetValue)value;
returnValue = optionValue.Name;
break;
case "primarynamelookup":
string lookupName = value == null ? "" : value.ToString();
returnValue = @"<a class=""sparkle-grid-link"" href=""#"" primaryNameLookup=""1"">" + lookupName + "</a>";
break;
}
}
return returnValue;
}
public static Column BindRowIcon(Column column,string entityLogicalName)
{
column.Formatter = RowIcon;
column.Options = entityLogicalName;
return column;
}
/// <summary>
/// Formattor to get the icon for a row
/// </summary>
/// <param name="row"></param>
/// <param name="cell"></param>
/// <param name="value"></param>
/// <param name="columnDef"></param>
/// <param name="dataContext"></param>
/// <returns></returns>
public static string RowIcon(int row, int cell, object value, Column columnDef, object dataContext)
{
// Get the icon of the row using the logical name of the specified entity reference column by the format string
Dictionary<string, object> item = (Dictionary<string, object>)dataContext;
if (item == null)
return "";
else
{
// Get the entity type from the specified column
EntityReference lookup = (EntityReference)item[(string)columnDef.Options];
if (lookup == null || lookup.LogicalName == null)
return "";
else
return "<span class='sparkle-grid-row-img'><img src='" + MetadataCache.GetSmallIconUrl(lookup.LogicalName) + "'/></span>";
}
}
/// <summary>
/// Adds a column that shows the state of the row as edited/new
/// </summary>
/// <param name="columns"></param>
public static void AddEditIndicatorColumn(List<Column> columns)
{
GridDataViewBinder.AddColumn(columns, "", 20, "entityState")
.Formatter = delegate(int row, int cell, object value, Column columnDef, object dataContext)
{
EntityStates state = (EntityStates)value;
switch (state)
{
case EntityStates.Created:
case EntityStates.Changed:
return "<span class='grid-edit-indicator'></span>";
case EntityStates.ReadOnly:
return "<span class='grid-readonly-indicator'></span>";
default:
return "";
}
};
}
/// <summary>
/// Wire up the OnCommitEdit event handler for the grid
/// In order to ensure that all grid edits have been commited before a VM command is run,
/// the VM must call CommitEdit on the ViewModelBase and cancel if returns false.
/// </summary>
/// <param name="vm"></param>
public void BindCommitEdit(ViewModelBase vm)
{
vm.OnCommitEdit += delegate(ViewModelBase sender, CancelEventArgs e)
{
if (_grid.GetEditorLock().IsActive())
e.Cancel = !_grid.GetEditorLock().CommitCurrentEdit();
};
}
}
}
| |
//
// ApplicationPkcs7Mime.cs
//
// Author: Jeffrey Stedfast <jeff@xamarin.com>
//
// Copyright (c) 2013-2015 Xamarin Inc. (www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using System.IO;
using System.Collections.Generic;
using MimeKit.IO;
namespace MimeKit.Cryptography {
/// <summary>
/// An S/MIME part with a Content-Type of application/pkcs7-mime.
/// </summary>
/// <remarks>
/// An application/pkcs7-mime is an S/MIME part and may contain encrypted,
/// signed or compressed data (or any combination of the above).
/// </remarks>
public class ApplicationPkcs7Mime : MimePart
{
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.Cryptography.ApplicationPkcs7Mime"/> class.
/// </summary>
/// <remarks>This constructor is used by <see cref="MimeKit.MimeParser"/>.</remarks>
/// <param name="entity">Information used by the constructor.</param>
public ApplicationPkcs7Mime (MimeEntityConstructorInfo entity) : base (entity)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.Cryptography.ApplicationPkcs7Mime"/> class.
/// </summary>
/// <remarks>
/// <para>Creates a new MIME part with a Content-Type of application/pkcs7-mime
/// and the <paramref name="stream"/> as its content.</para>
/// <para>Unless you are writing your own pkcs7 implementation, you'll probably
/// want to use the <see cref="Compress(MimeEntity)"/>,
/// <see cref="Encrypt(CmsRecipientCollection, MimeEntity)"/>, and/or
/// <see cref="Sign(CmsSigner, MimeEntity)"/> method to create new instances
/// of this class.</para>
/// </remarks>
/// <param name="type">The S/MIME type.</param>
/// <param name="stream">The content stream.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="stream"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="type"/> is not a valid value.
/// </exception>
/// <exception cref="System.ArgumentException">
/// <para><paramref name="stream"/> does not support reading.</para>
/// <para>-or-</para>
/// <para><paramref name="stream"/> does not support seeking.</para>
/// </exception>
public ApplicationPkcs7Mime (SecureMimeType type, Stream stream) : base ("application", "pkcs7-mime")
{
ContentDisposition = new ContentDisposition ("attachment");
ContentTransferEncoding = ContentEncoding.Base64;
ContentObject = new ContentObject (stream);
switch (type) {
case SecureMimeType.CompressedData:
ContentType.Parameters["smime-type"] = "compressed-data";
ContentDisposition.FileName = "smime.p7z";
ContentType.Name = "smime.p7z";
break;
case SecureMimeType.EnvelopedData:
ContentType.Parameters["smime-type"] = "enveloped-data";
ContentDisposition.FileName = "smime.p7m";
ContentType.Name = "smime.p7m";
break;
case SecureMimeType.SignedData:
ContentType.Parameters["smime-type"] = "signed-data";
ContentDisposition.FileName = "smime.p7m";
ContentType.Name = "smime.p7m";
break;
case SecureMimeType.CertsOnly:
ContentType.Parameters["smime-type"] = "certs-only";
ContentDisposition.FileName = "smime.p7c";
ContentType.Name = "smime.p7c";
break;
default:
throw new ArgumentOutOfRangeException ("type");
}
}
/// <summary>
/// Gets the value of the "smime-type" parameter.
/// </summary>
/// <remarks>
/// Gets the value of the "smime-type" parameter.
/// </remarks>
/// <value>The value of the "smime-type" parameter.</value>
public SecureMimeType SecureMimeType {
get {
var type = ContentType.Parameters["smime-type"];
if (type == null)
return SecureMimeType.Unknown;
switch (type.ToLowerInvariant ()) {
case "compressed-data": return SecureMimeType.CompressedData;
case "enveloped-data": return SecureMimeType.EnvelopedData;
case "signed-data": return SecureMimeType.SignedData;
case "certs-only": return SecureMimeType.CertsOnly;
default: return SecureMimeType.Unknown;
}
}
}
/// <summary>
/// Decompresses the content.
/// </summary>
/// <remarks>
/// Decompresses the content using the specified <see cref="SecureMimeContext"/>.
/// </remarks>
/// <returns>The decompressed <see cref="MimeKit.MimeEntity"/>.</returns>
/// <param name="ctx">The S/MIME context to use for decompressing.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="ctx"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.InvalidOperationException">
/// The "smime-type" parameter on the Content-Type header is not "compressed-data".
/// </exception>
/// <exception cref="Org.BouncyCastle.Cms.CmsException">
/// An error occurred in the cryptographic message syntax subsystem.
/// </exception>
public MimeEntity Decompress (SecureMimeContext ctx)
{
if (ctx == null)
throw new ArgumentNullException ("ctx");
if (SecureMimeType != SecureMimeType.CompressedData)
throw new InvalidOperationException ();
using (var memory = new MemoryBlockStream ()) {
ContentObject.DecodeTo (memory);
memory.Position = 0;
return ctx.Decompress (memory);
}
}
/// <summary>
/// Decompresses the content.
/// </summary>
/// <remarks>
/// Decompresses the content using the default <see cref="SecureMimeContext"/>.
/// </remarks>
/// <returns>The decompressed <see cref="MimeKit.MimeEntity"/>.</returns>
/// <exception cref="System.InvalidOperationException">
/// The "smime-type" parameter on the Content-Type header is not "compressed-data".
/// </exception>
/// <exception cref="Org.BouncyCastle.Cms.CmsException">
/// An error occurred in the cryptographic message syntax subsystem.
/// </exception>
public MimeEntity Decompress ()
{
if (SecureMimeType != SecureMimeType.CompressedData)
throw new InvalidOperationException ();
using (var ctx = (SecureMimeContext) CryptographyContext.Create ("application/pkcs7-mime")) {
return Decompress (ctx);
}
}
/// <summary>
/// Decrypts the content.
/// </summary>
/// <remarks>
/// Decrypts the content using the specified <see cref="SecureMimeContext"/>.
/// </remarks>
/// <returns>The decrypted <see cref="MimeKit.MimeEntity"/>.</returns>
/// <param name="ctx">The S/MIME context to use for decrypting.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="ctx"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.InvalidOperationException">
/// The "smime-type" parameter on the Content-Type header is not "enveloped-data".
/// </exception>
/// <exception cref="Org.BouncyCastle.Cms.CmsException">
/// An error occurred in the cryptographic message syntax subsystem.
/// </exception>
public MimeEntity Decrypt (SecureMimeContext ctx)
{
if (ctx == null)
throw new ArgumentNullException ("ctx");
if (SecureMimeType != SecureMimeType.EnvelopedData)
throw new InvalidOperationException ();
using (var memory = new MemoryBlockStream ()) {
ContentObject.DecodeTo (memory);
memory.Position = 0;
return ctx.Decrypt (memory);
}
}
/// <summary>
/// Decrypts the content.
/// </summary>
/// <remarks>
/// Decrypts the content using the default <see cref="SecureMimeContext"/>.
/// </remarks>
/// <returns>The decrypted <see cref="MimeKit.MimeEntity"/>.</returns>
/// <exception cref="System.InvalidOperationException">
/// The "smime-type" parameter on the Content-Type header is not "certs-only".
/// </exception>
/// <exception cref="Org.BouncyCastle.Cms.CmsException">
/// An error occurred in the cryptographic message syntax subsystem.
/// </exception>
public MimeEntity Decrypt ()
{
using (var ctx = (SecureMimeContext) CryptographyContext.Create ("application/pkcs7-mime")) {
return Decrypt (ctx);
}
}
/// <summary>
/// Imports the certificates contained in the content.
/// </summary>
/// <remarks>
/// Imports the certificates contained in the content.
/// </remarks>
/// <param name="ctx">The S/MIME context to import certificates into.</param>
/// <exception cref="System.InvalidOperationException">
/// The "smime-type" parameter on the Content-Type header is not "certs-only".
/// </exception>
/// <exception cref="Org.BouncyCastle.Cms.CmsException">
/// An error occurred in the cryptographic message syntax subsystem.
/// </exception>
public void Import (SecureMimeContext ctx)
{
if (SecureMimeType != SecureMimeType.CertsOnly)
throw new InvalidOperationException ();
using (var memory = new MemoryBlockStream ()) {
ContentObject.DecodeTo (memory);
memory.Position = 0;
ctx.Import (memory);
}
}
/// <summary>
/// Verifies the signed-data and returns the unencapsulated <see cref="MimeKit.MimeEntity"/>.
/// </summary>
/// <remarks>
/// Verifies the signed-data and returns the unencapsulated <see cref="MimeKit.MimeEntity"/>.
/// </remarks>
/// <returns>The list of digital signatures.</returns>
/// <param name="ctx">The S/MIME context to use for verifying the signature.</param>
/// <param name="entity">The unencapsulated entity.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="ctx"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.InvalidOperationException">
/// The "smime-type" parameter on the Content-Type header is not "signed-data".
/// </exception>
/// <exception cref="Org.BouncyCastle.Cms.CmsException">
/// An error occurred in the cryptographic message syntax subsystem.
/// </exception>
public DigitalSignatureCollection Verify (SecureMimeContext ctx, out MimeEntity entity)
{
if (ctx == null)
throw new ArgumentNullException ("ctx");
if (SecureMimeType != SecureMimeType.SignedData)
throw new InvalidOperationException ();
using (var memory = new MemoryBlockStream ()) {
ContentObject.DecodeTo (memory);
memory.Position = 0;
return ctx.Verify (memory, out entity);
}
}
/// <summary>
/// Verifies the signed-data and returns the unencapsulated <see cref="MimeKit.MimeEntity"/>.
/// </summary>
/// <remarks>
/// Verifies the signed-data and returns the unencapsulated <see cref="MimeKit.MimeEntity"/>.
/// </remarks>
/// <returns>The list of digital signatures.</returns>
/// <param name="entity">The unencapsulated entity.</param>
/// <exception cref="System.InvalidOperationException">
/// The "smime-type" parameter on the Content-Type header is not "signed-data".
/// </exception>
/// <exception cref="Org.BouncyCastle.Cms.CmsException">
/// An error occurred in the cryptographic message syntax subsystem.
/// </exception>
public DigitalSignatureCollection Verify (out MimeEntity entity)
{
using (var ctx = (SecureMimeContext) CryptographyContext.Create ("application/pkcs7-mime")) {
return Verify (ctx, out entity);
}
}
/// <summary>
/// Compresses the specified entity.
/// </summary>
/// <remarks>
/// <para>Compresses the specified entity using the specified <see cref="SecureMimeContext"/>.</para>
/// <para>It should be noted that this feature is not supported by most mail clients,
/// even among those that support S/MIME.</para>
/// </remarks>
/// <returns>The compressed entity.</returns>
/// <param name="ctx">The S/MIME context to use for compressing.</param>
/// <param name="entity">The entity.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="ctx"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="entity"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="Org.BouncyCastle.Cms.CmsException">
/// An error occurred in the cryptographic message syntax subsystem.
/// </exception>
public static ApplicationPkcs7Mime Compress (SecureMimeContext ctx, MimeEntity entity)
{
if (ctx == null)
throw new ArgumentNullException ("ctx");
if (entity == null)
throw new ArgumentNullException ("entity");
using (var memory = new MemoryBlockStream ()) {
var options = FormatOptions.GetDefault ();
options.NewLineFormat = NewLineFormat.Dos;
entity.WriteTo (options, memory);
memory.Position = 0;
return ctx.Compress (memory);
}
}
/// <summary>
/// Compresses the specified entity.
/// </summary>
/// <remarks>
/// <para>Compresses the specified entity using the default <see cref="SecureMimeContext"/>.</para>
/// <para>It should be noted that this feature is not supported by most mail clients,
/// even among those that support S/MIME.</para>
/// </remarks>
/// <returns>The compressed entity.</returns>
/// <param name="entity">The entity.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="entity"/> is <c>null</c>.
/// </exception>
/// <exception cref="Org.BouncyCastle.Cms.CmsException">
/// An error occurred in the cryptographic message syntax subsystem.
/// </exception>
public static ApplicationPkcs7Mime Compress (MimeEntity entity)
{
if (entity == null)
throw new ArgumentNullException ("entity");
using (var ctx = (SecureMimeContext) CryptographyContext.Create ("application/pkcs7-mime")) {
return Compress (ctx, entity);
}
}
/// <summary>
/// Encrypts the specified entity.
/// </summary>
/// <remarks>
/// Encrypts the entity to the specified recipients using the supplied <see cref="SecureMimeContext"/>.
/// </remarks>
/// <returns>The encrypted entity.</returns>
/// <param name="ctx">The S/MIME context to use for encrypting.</param>
/// <param name="recipients">The recipients.</param>
/// <param name="entity">The entity.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="ctx"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="recipients"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="entity"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="Org.BouncyCastle.Cms.CmsException">
/// An error occurred in the cryptographic message syntax subsystem.
/// </exception>
public static ApplicationPkcs7Mime Encrypt (SecureMimeContext ctx, CmsRecipientCollection recipients, MimeEntity entity)
{
if (ctx == null)
throw new ArgumentNullException ("ctx");
if (recipients == null)
throw new ArgumentNullException ("recipients");
if (entity == null)
throw new ArgumentNullException ("entity");
using (var memory = new MemoryBlockStream ()) {
var options = FormatOptions.GetDefault ();
options.NewLineFormat = NewLineFormat.Dos;
entity.WriteTo (options, memory);
memory.Position = 0;
return ctx.Encrypt (recipients, memory);
}
}
/// <summary>
/// Encrypts the specified entity.
/// </summary>
/// <remarks>
/// Encrypts the entity to the specified recipients using the default <see cref="SecureMimeContext"/>.
/// </remarks>
/// <returns>The encrypted entity.</returns>
/// <param name="recipients">The recipients.</param>
/// <param name="entity">The entity.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="recipients"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="entity"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="Org.BouncyCastle.Cms.CmsException">
/// An error occurred in the cryptographic message syntax subsystem.
/// </exception>
public static ApplicationPkcs7Mime Encrypt (CmsRecipientCollection recipients, MimeEntity entity)
{
if (recipients == null)
throw new ArgumentNullException ("recipients");
if (entity == null)
throw new ArgumentNullException ("entity");
using (var ctx = (SecureMimeContext) CryptographyContext.Create ("application/pkcs7-mime")) {
return Encrypt (ctx, recipients, entity);
}
}
/// <summary>
/// Encrypts the specified entity.
/// </summary>
/// <remarks>
/// Encrypts the entity to the specified recipients using the supplied <see cref="SecureMimeContext"/>.
/// </remarks>
/// <returns>The encrypted entity.</returns>
/// <param name="ctx">The S/MIME context to use for encrypting.</param>
/// <param name="recipients">The recipients.</param>
/// <param name="entity">The entity.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="ctx"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="recipients"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="entity"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentException">
/// Valid certificates could not be found for one or more of the <paramref name="recipients"/>.
/// </exception>
/// <exception cref="CertificateNotFoundException">
/// A certificate could not be found for one or more of the <paramref name="recipients"/>.
/// </exception>
/// <exception cref="Org.BouncyCastle.Cms.CmsException">
/// An error occurred in the cryptographic message syntax subsystem.
/// </exception>
public static ApplicationPkcs7Mime Encrypt (SecureMimeContext ctx, IEnumerable<MailboxAddress> recipients, MimeEntity entity)
{
if (ctx == null)
throw new ArgumentNullException ("ctx");
if (recipients == null)
throw new ArgumentNullException ("recipients");
if (entity == null)
throw new ArgumentNullException ("entity");
using (var memory = new MemoryBlockStream ()) {
var options = FormatOptions.GetDefault ();
options.NewLineFormat = NewLineFormat.Dos;
entity.WriteTo (options, memory);
memory.Position = 0;
return (ApplicationPkcs7Mime) ctx.Encrypt (recipients, memory);
}
}
/// <summary>
/// Encrypts the specified entity.
/// </summary>
/// <remarks>
/// Encrypts the entity to the specified recipients using the default <see cref="SecureMimeContext"/>.
/// </remarks>
/// <returns>The encrypted entity.</returns>
/// <param name="recipients">The recipients.</param>
/// <param name="entity">The entity.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="recipients"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="entity"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentException">
/// Valid certificates could not be found for one or more of the <paramref name="recipients"/>.
/// </exception>
/// <exception cref="CertificateNotFoundException">
/// A certificate could not be found for one or more of the <paramref name="recipients"/>.
/// </exception>
/// <exception cref="Org.BouncyCastle.Cms.CmsException">
/// An error occurred in the cryptographic message syntax subsystem.
/// </exception>
public static ApplicationPkcs7Mime Encrypt (IEnumerable<MailboxAddress> recipients, MimeEntity entity)
{
if (recipients == null)
throw new ArgumentNullException ("recipients");
if (entity == null)
throw new ArgumentNullException ("entity");
using (var ctx = (SecureMimeContext) CryptographyContext.Create ("application/pkcs7-mime")) {
return Encrypt (ctx, recipients, entity);
}
}
/// <summary>
/// Cryptographically signs the specified entity.
/// </summary>
/// <remarks>
/// <para>Signs the entity using the supplied signer and <see cref="SecureMimeContext"/>.</para>
/// <para>For better interoperability with other mail clients, you should use
/// <see cref="MultipartSigned.Create(SecureMimeContext, CmsSigner, MimeEntity)"/>
/// instead as the multipart/signed format is supported among a much larger
/// subset of mail client software.</para>
/// </remarks>
/// <returns>The signed entity.</returns>
/// <param name="ctx">The S/MIME context to use for signing.</param>
/// <param name="signer">The signer.</param>
/// <param name="entity">The entity.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="ctx"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="signer"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="entity"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="Org.BouncyCastle.Cms.CmsException">
/// An error occurred in the cryptographic message syntax subsystem.
/// </exception>
public static ApplicationPkcs7Mime Sign (SecureMimeContext ctx, CmsSigner signer, MimeEntity entity)
{
if (ctx == null)
throw new ArgumentNullException ("ctx");
if (signer == null)
throw new ArgumentNullException ("signer");
if (entity == null)
throw new ArgumentNullException ("entity");
using (var memory = new MemoryBlockStream ()) {
var options = FormatOptions.GetDefault ();
options.NewLineFormat = NewLineFormat.Dos;
entity.WriteTo (options, memory);
memory.Position = 0;
return ctx.EncapsulatedSign (signer, memory);
}
}
/// <summary>
/// Cryptographically signs the specified entity.
/// </summary>
/// <remarks>
/// <para>Signs the entity using the supplied signer.</para>
/// <para>For better interoperability with other mail clients, you should use
/// <see cref="MultipartSigned.Create(SecureMimeContext, CmsSigner, MimeEntity)"/>
/// instead as the multipart/signed format is supported among a much larger
/// subset of mail client software.</para>
/// </remarks>
/// <returns>The signed entity.</returns>
/// <param name="signer">The signer.</param>
/// <param name="entity">The entity.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="signer"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="entity"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="Org.BouncyCastle.Cms.CmsException">
/// An error occurred in the cryptographic message syntax subsystem.
/// </exception>
public static ApplicationPkcs7Mime Sign (CmsSigner signer, MimeEntity entity)
{
if (signer == null)
throw new ArgumentNullException ("signer");
if (entity == null)
throw new ArgumentNullException ("entity");
using (var ctx = (SecureMimeContext) CryptographyContext.Create ("application/pkcs7-mime")) {
return Sign (ctx, signer, entity);
}
}
/// <summary>
/// Cryptographically signs the specified entity.
/// </summary>
/// <remarks>
/// <para>Signs the entity using the supplied signer, digest algorithm and <see cref="SecureMimeContext"/>.</para>
/// <para>For better interoperability with other mail clients, you should use
/// <see cref="MultipartSigned.Create(SecureMimeContext, CmsSigner, MimeEntity)"/>
/// instead as the multipart/signed format is supported among a much larger
/// subset of mail client software.</para>
/// </remarks>
/// <returns>The signed entity.</returns>
/// <param name="ctx">The S/MIME context to use for signing.</param>
/// <param name="signer">The signer.</param>
/// <param name="digestAlgo">The digest algorithm to use for signing.</param>
/// <param name="entity">The entity.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="ctx"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="signer"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="entity"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="CertificateNotFoundException">
/// A signing certificate could not be found for <paramref name="signer"/>.
/// </exception>
/// <exception cref="Org.BouncyCastle.Cms.CmsException">
/// An error occurred in the cryptographic message syntax subsystem.
/// </exception>
public static ApplicationPkcs7Mime Sign (SecureMimeContext ctx, MailboxAddress signer, DigestAlgorithm digestAlgo, MimeEntity entity)
{
if (ctx == null)
throw new ArgumentNullException ("ctx");
if (signer == null)
throw new ArgumentNullException ("signer");
if (entity == null)
throw new ArgumentNullException ("entity");
using (var memory = new MemoryBlockStream ()) {
var options = FormatOptions.GetDefault ();
options.NewLineFormat = NewLineFormat.Dos;
entity.WriteTo (options, memory);
memory.Position = 0;
return ctx.EncapsulatedSign (signer, digestAlgo, memory);
}
}
/// <summary>
/// Cryptographically signs the specified entity.
/// </summary>
/// <remarks>
/// <para>Signs the entity using the supplied signer and digest algorithm.</para>
/// <para>For better interoperability with other mail clients, you should use
/// <see cref="MultipartSigned.Create(SecureMimeContext, CmsSigner, MimeEntity)"/>
/// instead as the multipart/signed format is supported among a much larger
/// subset of mail client software.</para>
/// </remarks>
/// <returns>The signed entity.</returns>
/// <param name="signer">The signer.</param>
/// <param name="digestAlgo">The digest algorithm to use for signing.</param>
/// <param name="entity">The entity.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="signer"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="entity"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="CertificateNotFoundException">
/// A signing certificate could not be found for <paramref name="signer"/>.
/// </exception>
/// <exception cref="Org.BouncyCastle.Cms.CmsException">
/// An error occurred in the cryptographic message syntax subsystem.
/// </exception>
public static ApplicationPkcs7Mime Sign (MailboxAddress signer, DigestAlgorithm digestAlgo, MimeEntity entity)
{
if (signer == null)
throw new ArgumentNullException ("signer");
if (entity == null)
throw new ArgumentNullException ("entity");
using (var ctx = (SecureMimeContext) CryptographyContext.Create ("application/pkcs7-mime")) {
return Sign (ctx, signer, digestAlgo, entity);
}
}
/// <summary>
/// Cryptographically signs and encrypts the specified entity.
/// </summary>
/// <remarks>
/// Cryptographically signs entity using the supplied signer and then
/// encrypts the result to the specified recipients.
/// </remarks>
/// <returns>The signed and encrypted entity.</returns>
/// <param name="ctx">The S/MIME context to use for signing and encrypting.</param>
/// <param name="signer">The signer.</param>
/// <param name="recipients">The recipients.</param>
/// <param name="entity">The entity.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="ctx"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="signer"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="recipients"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="entity"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="Org.BouncyCastle.Cms.CmsException">
/// An error occurred in the cryptographic message syntax subsystem.
/// </exception>
public static ApplicationPkcs7Mime SignAndEncrypt (SecureMimeContext ctx, CmsSigner signer, CmsRecipientCollection recipients, MimeEntity entity)
{
if (ctx == null)
throw new ArgumentNullException ("ctx");
if (signer == null)
throw new ArgumentNullException ("signer");
if (recipients == null)
throw new ArgumentNullException ("recipients");
if (entity == null)
throw new ArgumentNullException ("entity");
return Encrypt (ctx, recipients, MultipartSigned.Create (ctx, signer, entity));
}
/// <summary>
/// Cryptographically signs and encrypts the specified entity.
/// </summary>
/// <remarks>
/// Cryptographically signs entity using the supplied signer and then
/// encrypts the result to the specified recipients.
/// </remarks>
/// <returns>The signed and encrypted entity.</returns>
/// <param name="signer">The signer.</param>
/// <param name="recipients">The recipients.</param>
/// <param name="entity">The entity.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="signer"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="recipients"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="entity"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="Org.BouncyCastle.Cms.CmsException">
/// An error occurred in the cryptographic message syntax subsystem.
/// </exception>
public static ApplicationPkcs7Mime SignAndEncrypt (CmsSigner signer, CmsRecipientCollection recipients, MimeEntity entity)
{
if (signer == null)
throw new ArgumentNullException ("signer");
if (recipients == null)
throw new ArgumentNullException ("recipients");
if (entity == null)
throw new ArgumentNullException ("entity");
using (var ctx = (SecureMimeContext) CryptographyContext.Create ("application/pkcs7-mime")) {
return SignAndEncrypt (ctx, signer, recipients, entity);
}
}
/// <summary>
/// Cryptographically signs and encrypts the specified entity.
/// </summary>
/// <remarks>
/// Cryptographically signs entity using the supplied signer and then
/// encrypts the result to the specified recipients.
/// </remarks>
/// <returns>The signed and encrypted entity.</returns>
/// <param name="ctx">The S/MIME context to use for signing and encrypting.</param>
/// <param name="signer">The signer.</param>
/// <param name="digestAlgo">The digest algorithm to use for signing.</param>
/// <param name="recipients">The recipients.</param>
/// <param name="entity">The entity.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="ctx"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="signer"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="recipients"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="entity"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="CertificateNotFoundException">
/// <para>A signing certificate could not be found for <paramref name="signer"/>.</para>
/// <para>-or-</para>
/// <para>A certificate could not be found for one or more of the <paramref name="recipients"/>.</para>
/// </exception>
/// <exception cref="Org.BouncyCastle.Cms.CmsException">
/// An error occurred in the cryptographic message syntax subsystem.
/// </exception>
public static ApplicationPkcs7Mime SignAndEncrypt (SecureMimeContext ctx, MailboxAddress signer, DigestAlgorithm digestAlgo, IEnumerable<MailboxAddress> recipients, MimeEntity entity)
{
if (ctx == null)
throw new ArgumentNullException ("ctx");
if (signer == null)
throw new ArgumentNullException ("signer");
if (recipients == null)
throw new ArgumentNullException ("recipients");
if (entity == null)
throw new ArgumentNullException ("entity");
return Encrypt (ctx, recipients, MultipartSigned.Create (ctx, signer, digestAlgo, entity));
}
/// <summary>
/// Cryptographically signs and encrypts the specified entity.
/// </summary>
/// <remarks>
/// Cryptographically signs entity using the supplied signer and then
/// encrypts the result to the specified recipients.
/// </remarks>
/// <returns>The signed and encrypted entity.</returns>
/// <param name="signer">The signer.</param>
/// <param name="digestAlgo">The digest algorithm to use for signing.</param>
/// <param name="recipients">The recipients.</param>
/// <param name="entity">The entity.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="signer"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="recipients"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="entity"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="CertificateNotFoundException">
/// <para>A signing certificate could not be found for <paramref name="signer"/>.</para>
/// <para>-or-</para>
/// <para>A certificate could not be found for one or more of the <paramref name="recipients"/>.</para>
/// </exception>
/// <exception cref="Org.BouncyCastle.Cms.CmsException">
/// An error occurred in the cryptographic message syntax subsystem.
/// </exception>
public static ApplicationPkcs7Mime SignAndEncrypt (MailboxAddress signer, DigestAlgorithm digestAlgo, IEnumerable<MailboxAddress> recipients, MimeEntity entity)
{
if (signer == null)
throw new ArgumentNullException ("signer");
if (recipients == null)
throw new ArgumentNullException ("recipients");
if (entity == null)
throw new ArgumentNullException ("entity");
using (var ctx = (SecureMimeContext) CryptographyContext.Create ("application/pkcs7-mime")) {
return SignAndEncrypt (ctx, signer, digestAlgo, recipients, entity);
}
}
}
}
| |
using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
//FutileEngine by Matt Rix -
public class Futile : MonoBehaviour
{
static public Futile instance = null;
static public FScreen screen;
static public FAtlasManager atlasManager;
static public FStage stage;
static public FTouchManager touchManager;
static public bool isOpenGL; //assigned in Awake
static public int baseRenderQueueDepth = 3000;
static public bool shouldRemoveAtlasElementFileExtensions = true;
//These are set in FScreen
static public float displayScale; //set based on the resolution setting (the unit to pixel scale)
static public float displayScaleInverse; // 1/displayScale
static public float resourceScale; //set based on the resolution setting (the scale of assets)
static public float resourceScaleInverse; // 1/resourceScale
static public float screenPixelOffset; //set based on whether it's openGL or not
static public string resourceSuffix; //set based on the resLevel
//default element, a 16x16 white texture
static public FAtlasElement whiteElement;
static public Color white = Color.white; //unlike Futile.white, it doesn't create a new color every time
static internal int nextRenderLayerDepth = 0;
static private List<FStage> _stages;
static private bool _isDepthChangeNeeded = false;
public delegate void FutileUpdateDelegate();
public event FutileUpdateDelegate SignalUpdate;
public event FutileUpdateDelegate SignalFixedUpdate;
public event FutileUpdateDelegate SignalLateUpdate;
//configuration values
public bool shouldTrackNodesInRXProfiler = false;
private GameObject _cameraHolder;
private Camera _camera;
private bool _shouldRunGCNextUpdate = false; //use Futile.instance.ForceGarbageCollectionNextUpdate();
private FutileParams _futileParams;
private List<FDelayedCallback> _delayedCallbacks = new List<FDelayedCallback>();
// Use this for initialization
private void Awake ()
{
instance = this;
isOpenGL = SystemInfo.graphicsDeviceVersion.Contains("OpenGL");
enabled = false;
name = "Futile";
}
public void Init(FutileParams futileParams)
{
enabled = true;
_futileParams = futileParams;
Application.targetFrameRate = _futileParams.targetFrameRate;
FShader.Init(); //set up the basic shaders
FFacetType.Init(); //set up the types of facets (Quads, Triangles, etc)
screen = new FScreen(_futileParams);
//
//Camera setup from https://github.com/prime31/UIToolkit/blob/master/Assets/Plugins/UIToolkit/UI.cs
//
_cameraHolder = new GameObject();
_cameraHolder.transform.parent = gameObject.transform;
_camera = _cameraHolder.AddComponent<Camera>();
_camera.tag = "MainCamera";
_camera.name = "Camera";
//_camera.clearFlags = CameraClearFlags.Depth; //TODO: check if this is faster or not?
_camera.clearFlags = CameraClearFlags.SolidColor;
_camera.nearClipPlane = 0.0f;
_camera.farClipPlane = 500.0f;
_camera.depth = 100;
_camera.rect = new Rect(0.0f, 0.0f, 1.0f, 1.0f);
_camera.backgroundColor = _futileParams.backgroundColor;
//we multiply this stuff by scaleInverse to make sure everything is in points, not pixels
_camera.orthographic = true;
_camera.orthographicSize = screen.pixelHeight/2 * displayScaleInverse;
UpdateCameraPosition();
touchManager = new FTouchManager();
atlasManager = new FAtlasManager();
CreateDefaultAtlases();
_stages = new List<FStage>();
stage = new FStage("Futile.stage");
AddStage (stage);
}
public FDelayedCallback StartDelayedCallback(Action func, float delayTime)
{
if (delayTime <= 0) delayTime = 0.00001f; //super small delay for 0 to avoid divide by 0 errors
FDelayedCallback callback = new FDelayedCallback(func, delayTime);
_delayedCallbacks.Add(callback);
return callback;
}
public void StopDelayedCall(Action func)
{
int count = _delayedCallbacks.Count;
for (int d = 0; d<count; d++)
{
FDelayedCallback call = _delayedCallbacks[d];
if(call.func == func)
{
_delayedCallbacks.RemoveAt(d);
d--;
count--;
}
}
}
public void StopDelayedCall(FDelayedCallback callToRemove)
{
_delayedCallbacks.Remove(callToRemove);
}
public void CreateDefaultAtlases()
{
//atlas of plain white
Texture2D plainWhiteTex = new Texture2D(16,16);
plainWhiteTex.filterMode = FilterMode.Bilinear;
plainWhiteTex.wrapMode = TextureWrapMode.Clamp;
Color white = Futile.white;
//Color clear = new Color(1,1,1,0);
for(int r = 0; r<16; r++)
{
for(int c = 0; c<16; c++)
{
// if(c == 0 || r == 0) //clear the 0 edges
// {
// plainWhiteTex.SetPixel(c,r,clear);
// }
// else
// {
plainWhiteTex.SetPixel(c,r,white);
// }
}
}
plainWhiteTex.Apply();
atlasManager.LoadAtlasFromTexture("Futile_White",plainWhiteTex);
whiteElement = atlasManager.GetElementWithName("Futile_White");
}
static public void AddStage(FStage stageToAdd)
{
int stageIndex = _stages.IndexOf(stageToAdd);
if(stageIndex == -1) //add it if it's not a stage
{
stageToAdd.HandleAddedToFutile();
_stages.Add(stageToAdd);
UpdateStageIndices();
}
else if(stageIndex != _stages.Count-1) //if stage is already in the stages, put it at the top of the stages if it's not already
{
_stages.RemoveAt(stageIndex);
_stages.Add(stageToAdd);
UpdateStageIndices();
}
}
static public void AddStageAtIndex(FStage stageToAdd, int newIndex)
{
int stageIndex = _stages.IndexOf(stageToAdd);
if(newIndex > _stages.Count) //if it's past the end, make it at the end
{
newIndex = _stages.Count;
}
if(stageIndex == newIndex) return; //if it's already at the right index, just leave it there
if(stageIndex == -1) //add it if it's not in the stages already
{
stageToAdd.HandleAddedToFutile();
_stages.Insert(newIndex, stageToAdd);
}
else //if stage is already in the stages, move it to the desired index
{
_stages.RemoveAt(stageIndex);
if(stageIndex < newIndex)
{
_stages.Insert(newIndex-1, stageToAdd); //gotta subtract 1 to account for it moving in the order
}
else
{
_stages.Insert(newIndex, stageToAdd);
}
}
UpdateStageIndices();
}
static public void RemoveStage(FStage stageToRemove)
{
stageToRemove.HandleRemovedFromFutile();
stageToRemove.index = -1;
_stages.Remove(stageToRemove);
UpdateStageIndices();
}
static public void UpdateStageIndices ()
{
int stageCount = _stages.Count;
for(int s = 0; s<stageCount; s++)
{
_stages[s].index = s;
}
_isDepthChangeNeeded = true;
}
static public int GetStageCount()
{
return _stages.Count;
}
static public FStage GetStageAt(int index)
{
return _stages[index];
}
private void ProcessDelayedCallbacks()
{
int count = _delayedCallbacks.Count;
for (int d = 0; d<count; d++)
{
FDelayedCallback callback = _delayedCallbacks[d];
callback.timeRemaining -= Time.deltaTime;
if(callback.timeRemaining < 0)
{
callback.func();
_delayedCallbacks.RemoveAt(d);
d--;
count--;
}
}
}
private void Update()
{
ProcessDelayedCallbacks();
screen.Update();
touchManager.Update();
if(SignalUpdate != null) SignalUpdate();
for(int s = 0; s<_stages.Count; s++)
{
_stages[s].Redraw (false,_isDepthChangeNeeded);
}
_isDepthChangeNeeded = false;
if(_shouldRunGCNextUpdate)
{
_shouldRunGCNextUpdate = false;
GC.Collect();
}
}
private void LateUpdate()
{
nextRenderLayerDepth = 0;
for(int s = 0; s<_stages.Count; s++)
{
_stages[s].LateUpdate();
}
if(SignalLateUpdate != null) SignalLateUpdate();
}
private void FixedUpdate()
{
if(SignalFixedUpdate != null) SignalFixedUpdate();
}
private void OnApplicationQuit()
{
instance = null;
}
private void OnDestroy()
{
instance = null;
}
public void UpdateCameraPosition()
{
_camera.orthographicSize = screen.pixelHeight/2 * displayScaleInverse;
float camXOffset = ((screen.originX - 0.5f) * -screen.pixelWidth)*displayScaleInverse + screenPixelOffset;
float camYOffset = ((screen.originY - 0.5f) * -screen.pixelHeight)*displayScaleInverse - screenPixelOffset;
_camera.transform.position = new Vector3(camXOffset, camYOffset, -10.0f);
}
public void ForceGarbageCollectionNextUpdate()
{
_shouldRunGCNextUpdate = true;
}
new public Camera camera
{
get {return _camera;}
}
//
//THE MIGHTY LAND OF DEPRECATION
//
[Obsolete("Futile.IsLandscape() is obsolete, use Futile.screen.IsLandscape() instead")]
public bool IsLandscape()
{
throw new NotSupportedException("Obsolete! Use Futile.screen.IsLandscape() instead");
}
[Obsolete("Futile.originX is obsolete, use Futile.screen.originX instead")]
public float originX
{
get {throw new NotSupportedException("Obsolete! Use Futile.screen.originX instead");}
set {throw new NotSupportedException("Obsolete! Use Futile.screen.originX instead");}
}
[Obsolete("Futile.originY is obsolete, use Futile.screen.originY instead")]
public float originY
{
get {throw new NotSupportedException("Obsolete! Use Futile.screen.originY instead"); }
set {throw new NotSupportedException("Obsolete! Use Futile.screen.originY instead");}
}
[Obsolete("Futile.currentOrientation is obsolete, use Futile.screen.currentOrientation instead")]
public ScreenOrientation currentOrientation
{
get {throw new NotSupportedException("Obsolete! Use Futile.screen.currentOrientation instead");}
set {throw new NotSupportedException("Obsolete! Use Futile.screen.currentOrientation instead");}
}
[Obsolete("Futile.width is obsolete, use Futile.screen.width instead")]
static public float width
{
get {throw new NotSupportedException("Obsolete! Use Futile.screen.width instead");}
set {throw new NotSupportedException("Obsolete! Use Futile.screen.width instead");}
}
[Obsolete("Futile.height is obsolete, use Futile.screen.height instead")]
static public float height
{
get {throw new NotSupportedException("Obsolete! Use Futile.screen.height instead");}
set {throw new NotSupportedException("Obsolete! Use Futile.screen.height instead");}
}
}
public class FDelayedCallback
{
public float delayTime;
public float timeRemaining;
public Action func;
public FDelayedCallback(Action func, float delayTime)
{
this.func = func;
this.delayTime = delayTime;
this.timeRemaining = delayTime;
}
public float percentComplete //0.0f when started, 1.0f when finished
{
get
{
return Mathf.Clamp01(1.0f - timeRemaining/delayTime);
}
}
}
| |
#region Copyright
//
// Nini Configuration Project.
// Copyright (C) 2006 Brent R. Matzelle. All rights reserved.
//
// This software is published under the terms of the MIT X11 license, a copy of
// which has been included with this distribution in the LICENSE.txt file.
//
#endregion
using System;
using System.IO;
using System.Xml;
using System.Collections;
namespace Nini.Config
{
/// <include file='XmlConfigSource.xml' path='//Class[@name="XmlConfigSource"]/docs/*' />
public class XmlConfigSource : ConfigSourceBase
{
#region Private variables
XmlDocument configDoc = null;
string savePath = null;
#endregion
#region Constructors
/// <include file='XmlConfigSource.xml' path='//Constructor[@name="Constructor"]/docs/*' />
public XmlConfigSource ()
{
configDoc = new XmlDocument ();
configDoc.LoadXml ("<Nini/>");
PerformLoad (configDoc);
}
/// <include file='XmlConfigSource.xml' path='//Constructor[@name="ConstructorPath"]/docs/*' />
public XmlConfigSource (string path)
{
Load (path);
}
/// <include file='XmlConfigSource.xml' path='//Constructor[@name="ConstructorXmlReader"]/docs/*' />
public XmlConfigSource (XmlReader reader)
{
Load (reader);
}
#endregion
#region Public properties
/// <include file='XmlConfigSource.xml' path='//Property[@name="SavePath"]/docs/*' />
public string SavePath
{
get { return savePath; }
}
#endregion
#region Public methods
/// <include file='XmlConfigSource.xml' path='//Method[@name="LoadPath"]/docs/*' />
public void Load (string path)
{
savePath = path;
configDoc = new XmlDocument ();
configDoc.Load (path);
PerformLoad (configDoc);
}
/// <include file='XmlConfigSource.xml' path='//Method[@name="LoadXmlReader"]/docs/*' />
public void Load (XmlReader reader)
{
configDoc = new XmlDocument ();
configDoc.Load (reader);
PerformLoad (configDoc);
}
/// <include file='XmlConfigSource.xml' path='//Method[@name="Save"]/docs/*' />
public override void Save ()
{
if (!IsSavable ()) {
throw new ArgumentException ("Source cannot be saved in this state");
}
MergeConfigsIntoDocument ();
configDoc.Save (savePath);
base.Save ();
}
/// <include file='XmlConfigSource.xml' path='//Method[@name="SavePath"]/docs/*' />
public void Save (string path)
{
this.savePath = path;
this.Save ();
}
/// <include file='XmlConfigSource.xml' path='//Method[@name="SaveTextWriter"]/docs/*' />
public void Save (TextWriter writer)
{
MergeConfigsIntoDocument ();
configDoc.Save (writer);
savePath = null;
OnSaved (new EventArgs ());
}
/// <include file='XmlConfigSource.xml' path='//Method[@name="SaveStream"]/docs/*' />
public void Save (Stream stream)
{
MergeConfigsIntoDocument ();
configDoc.Save (stream);
savePath = null;
OnSaved (new EventArgs ());
}
/// <include file='IConfigSource.xml' path='//Method[@name="Reload"]/docs/*' />
public override void Reload ()
{
if (savePath == null) {
throw new ArgumentException ("Error reloading: You must have "
+ "the loaded the source from a file");
}
configDoc = new XmlDocument ();
configDoc.Load (savePath);
MergeDocumentIntoConfigs ();
base.Reload ();
}
/// <include file='XmlConfigSource.xml' path='//Method[@name="ToString"]/docs/*' />
public override string ToString ()
{
MergeConfigsIntoDocument ();
StringWriter writer = new StringWriter ();
configDoc.Save (writer);
return writer.ToString ();
}
#endregion
#region Private methods
/// <summary>
/// Merges all of the configs from the config collection into the
/// XmlDocument.
/// </summary>
private void MergeConfigsIntoDocument ()
{
RemoveSections ();
foreach (IConfig config in this.Configs)
{
string[] keys = config.GetKeys ();
XmlNode node = GetSectionByName (config.Name);
if (node == null) {
node = SectionNode (config.Name);
configDoc.DocumentElement.AppendChild (node);
}
RemoveKeys (config.Name);
for (int i = 0; i < keys.Length; i++)
{
SetKey (node, keys[i], config.Get (keys[i]));
}
}
}
/// <summary>
/// Removes all XML sections that were removed as configs.
/// </summary>
private void RemoveSections ()
{
XmlAttribute attr = null;
foreach (XmlNode node in configDoc.DocumentElement.ChildNodes)
{
if (node.NodeType == XmlNodeType.Element
&& node.Name == "Section") {
attr = node.Attributes["Name"];
if (attr != null) {
if (this.Configs[attr.Value] == null) {
configDoc.DocumentElement.RemoveChild (node);
}
} else {
throw new ArgumentException ("Section name attribute not found");
}
}
}
}
/// <summary>
/// Removes all XML keys that were removed as config keys.
/// </summary>
private void RemoveKeys (string sectionName)
{
XmlNode sectionNode = GetSectionByName (sectionName);
XmlAttribute keyName = null;
if (sectionNode != null) {
foreach (XmlNode node in sectionNode.ChildNodes)
{
if (node.NodeType == XmlNodeType.Element
&& node.Name == "Key") {
keyName = node.Attributes["Name"];
if (keyName != null) {
if (this.Configs[sectionName].Get (keyName.Value) == null) {
sectionNode.RemoveChild (node);
}
} else {
throw new ArgumentException ("Name attribute not found in key");
}
}
}
}
}
/// <summary>
/// Loads all sections and keys.
/// </summary>
private void PerformLoad (XmlDocument document)
{
this.Configs.Clear ();
this.Merge (this); // required for SaveAll
if (document.DocumentElement.Name != "Nini") {
throw new ArgumentException ("Did not find Nini XML root node");
}
LoadSections (document.DocumentElement);
}
/// <summary>
/// Loads all configuration sections.
/// </summary>
private void LoadSections (XmlNode rootNode)
{
ConfigBase config = null;
foreach (XmlNode child in rootNode.ChildNodes)
{
if (child.NodeType == XmlNodeType.Element
&& child.Name == "Section") {
config = new ConfigBase (child.Attributes["Name"].Value, this);
this.Configs.Add (config);
LoadKeys (child, config);
}
}
}
/// <summary>
/// Loads all keys for a config.
/// </summary>
private void LoadKeys (XmlNode node, ConfigBase config)
{
foreach (XmlNode child in node.ChildNodes)
{
if (child.NodeType == XmlNodeType.Element
&& child.Name == "Key") {
config.Add (child.Attributes["Name"].Value,
child.Attributes["Value"].Value);
}
}
}
/// <summary>
/// Sets an XML key. If it does not exist then it is created.
/// </summary>
private void SetKey (XmlNode sectionNode, string key, string value)
{
XmlNode node = GetKeyByName (sectionNode, key);
if (node == null) {
CreateKey (sectionNode, key, value);
} else {
node.Attributes["Value"].Value = value;
}
}
/// <summary>
/// Creates a key node and adds it to the collection at the end.
/// </summary>
private void CreateKey (XmlNode sectionNode, string key, string value)
{
XmlNode node = configDoc.CreateElement ("Key");
XmlAttribute keyAttr = configDoc.CreateAttribute ("Name");
XmlAttribute valueAttr = configDoc.CreateAttribute ("Value");
keyAttr.Value = key;
valueAttr.Value = value;
node.Attributes.Append (keyAttr);
node.Attributes.Append (valueAttr);
sectionNode.AppendChild (node);
}
/// <summary>
/// Returns a new section node.
/// </summary>
private XmlNode SectionNode (string name)
{
XmlNode result = configDoc.CreateElement ("Section");
XmlAttribute nameAttr = configDoc.CreateAttribute ("Name");
nameAttr.Value = name;
result.Attributes.Append (nameAttr);
return result;
}
/// <summary>
/// Returns a section node by name.
/// </summary>
private XmlNode GetSectionByName (string name)
{
XmlNode result = null;
foreach (XmlNode node in configDoc.DocumentElement.ChildNodes)
{
if (node.NodeType == XmlNodeType.Element
&& node.Name == "Section"
&& node.Attributes["Name"].Value == name) {
result = node;
break;
}
}
return result;
}
/// <summary>
/// Returns a key node by name.
/// </summary>
private XmlNode GetKeyByName (XmlNode sectionNode, string name)
{
XmlNode result = null;
foreach (XmlNode node in sectionNode.ChildNodes)
{
if (node.NodeType == XmlNodeType.Element
&& node.Name == "Key"
&& node.Attributes["Name"].Value == name) {
result = node;
break;
}
}
return result;
}
/// <summary>
/// Returns true if this instance is savable.
/// </summary>
private bool IsSavable ()
{
return (this.savePath != null
&& configDoc != null);
}
/// <summary>
/// Merges the XmlDocument into the Configs when the document is
/// reloaded.
/// </summary>
private void MergeDocumentIntoConfigs ()
{
// Remove all missing configs first
RemoveConfigs ();
foreach (XmlNode node in configDoc.DocumentElement.ChildNodes)
{
// If node is a section node
if (node.NodeType == XmlNodeType.Element
&& node.Name == "Section") {
string sectionName = node.Attributes["Name"].Value;
IConfig config = this.Configs[sectionName];
if (config == null) {
// The section is new so add it
config = new ConfigBase (sectionName, this);
this.Configs.Add (config);
}
RemoveConfigKeys (config);
}
}
}
/// <summary>
/// Removes all configs that are not in the newly loaded XmlDocument.
/// </summary>
private void RemoveConfigs ()
{
IConfig config = null;
for (int i = this.Configs.Count - 1; i > -1; i--)
{
config = this.Configs[i];
// If the section is not present in the XmlDocument
if (GetSectionByName (config.Name) == null) {
this.Configs.Remove (config);
}
}
}
/// <summary>
/// Removes all XML keys that were removed as config keys.
/// </summary>
private void RemoveConfigKeys (IConfig config)
{
XmlNode section = GetSectionByName (config.Name);
// Remove old keys
string[] configKeys = config.GetKeys ();
foreach (string configKey in configKeys)
{
if (GetKeyByName (section, configKey) == null) {
// Key doesn't exist, remove
config.Remove (configKey);
}
}
// Add or set all new keys
foreach (XmlNode node in section.ChildNodes)
{
// Loop through all key nodes and add to config
if (node.NodeType == XmlNodeType.Element
&& node.Name == "Key") {
config.Set (node.Attributes["Name"].Value,
node.Attributes["Value"].Value);
}
}
}
#endregion
}
}
| |
namespace YAMP.Numerics
{
using System;
using YAMP.Exceptions;
/// <summary>
/// LU Decomposition.
/// For an m-by-n matrix A with m >= n, the LU decomposition is an m-by-n
/// unit lower triangular matrix L, an n-by-n upper triangular matrix U,
/// and a permutation vector piv of length m so that A(piv,:) = L*U.
/// <code>
/// If m is smaller than n, then L is m-by-m and U is m-by-n.
/// </code>
/// The LU decompostion with pivoting always exists, even if the matrix is
/// singular, so the constructor will never fail. The primary use of the
/// LU decomposition is in the solution of square systems of simultaneous
/// linear equations. This will fail if IsNonSingular() returns false.
/// </summary>
public class LUDecomposition : DirectSolver
{
#region Fields
/// <summary>
/// Array for internal storage of decomposition.
/// </summary>
ScalarValue[][] LU;
/// <summary>
/// Row and column dimensions, and pivot sign.
/// </summary>
int m, n, pivsign;
/// <summary>
/// Internal storage of pivot vector.
/// </summary>
int[] piv;
#endregion // Class variables
#region Constructor
/// <summary>
/// LU Decomposition
/// </summary>
/// <param name="A">Rectangular matrix</param>
/// <returns>Structure to access L, U and piv.</returns>
public LUDecomposition(MatrixValue A)
{
// Use a "left-looking", dot-product, Crout / Doolittle algorithm.
LU = A.GetComplexMatrix();
m = A.DimensionY;
n = A.DimensionX;
piv = new int[m];
for (int i = 0; i < m; i++)
piv[i] = i;
pivsign = 1;
var LUrowi = new ScalarValue[0];
var LUcolj = new ScalarValue[m];
// Outer loop.
for (int j = 0; j < n; j++)
{
// Make a copy of the j-th column to localize references.
for (int i = 0; i < m; i++)
LUcolj[i] = LU[i][j];
// Apply previous transformations.
for (int i = 0; i < m; i++)
{
LUrowi = LU[i];
// Most of the time is spent in the following dot product.
var kmax = Math.Min(i, j);
var s = ScalarValue.Zero;
for (int k = 0; k < kmax; k++)
s += LUrowi[k] * LUcolj[k];
LUrowi[j] = LUcolj[i] -= s;
}
// Find pivot and exchange if necessary.
var p = j;
for (int i = j + 1; i < m; i++)
{
if (LUcolj[i].Abs() > LUcolj[p].Abs())
p = i;
}
if (p != j)
{
for (int k = 0; k < n; k++)
{
var t = LU[p][k];
LU[p][k] = LU[j][k];
LU[j][k] = t;
}
var k2 = piv[p];
piv[p] = piv[j];
piv[j] = k2;
pivsign = -pivsign;
}
// Compute multipliers.
if (j < m & LU[j][j] != 0.0)
{
for (int i = j + 1; i < m; i++)
LU[i][j] = LU[i][j] / LU[j][j];
}
}
}
#endregion // Constructor
#region Public Properties
/// <summary>
/// Is the matrix nonsingular?
/// </summary>
/// <returns>true if U, and hence A, is nonsingular.</returns>
virtual public bool IsNonSingular
{
get
{
for (int j = 0; j < n; j++)
{
if (LU[j][j] == ScalarValue.Zero)
return false;
}
return true;
}
}
/// <summary>
/// Return lower triangular factor
/// </summary>
/// <returns>L</returns>
virtual public MatrixValue L
{
get
{
var X = new MatrixValue(m, n);
for (int i = 1; i <= m; i++)
{
for (int j = 1; j <= n; j++)
{
if (i > j)
X[i, j] = LU[i - 1][j - 1];
else if (i == j)
X[i, j] = ScalarValue.One;
}
}
return X;
}
}
/// <summary>
/// Return upper triangular factor
/// </summary>
/// <returns>U</returns>
virtual public MatrixValue U
{
get
{
var X = new MatrixValue(n, n);
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
if (i <= j)
X[i, j] = LU[i - 1][j - 1];
}
}
return X;
}
}
/// <summary>
/// Return pivot permutation vector
/// </summary>
/// <returns>piv</returns>
virtual public MatrixValue Pivot
{
get
{
var P = new MatrixValue(m, m);
for (var i = 1; i <= m; i++)
P[i, piv[i - 1] + 1] = ScalarValue.One;
return P;
}
}
#endregion // Public Properties
#region Public Methods
/// <summary>
/// Determinant
/// </summary>
/// <returns>det(A)</returns>
public virtual ScalarValue Determinant()
{
if (m != n)
throw new YAMPMatrixFormatException(SpecialMatrixFormat.Square.ToString());
var d = new ScalarValue(pivsign);
for (var j = 0; j < n; j++)
{
d = d * LU[j][j];
}
return d;
}
/// <summary>
/// Solve A*X = B
/// </summary>
/// <param name="B">A Matrix with as many rows as A and any number of columns.</param>
/// <returns>X so that L*U*X = B(piv,:)</returns>
public override MatrixValue Solve(MatrixValue B)
{
if (B.DimensionY != m)
throw new YAMPDifferentDimensionsException(B.DimensionY, 1, m, 1);
if (!this.IsNonSingular)
throw new YAMPMatrixFormatException(SpecialMatrixFormat.NonSingular.ToString());
// Copy right hand side with pivoting
var nx = B.DimensionX;
var X = B.GetSubMatrix(piv, 0, nx).GetComplexMatrix();
// Solve L*Y = B(piv,:)
for (var k = 0; k < n; k++)
{
for (var i = k + 1; i < n; i++)
{
for (var j = 0; j < nx; j++)
{
X[i][j] -= X[k][j] * LU[i][k];
}
}
}
// Solve U*X = Y;
for (var k = n - 1; k >= 0; k--)
{
for (var j = 0; j < nx; j++)
{
X[k][j] = X[k][j] / LU[k][k];
}
for (var i = 0; i < k; i++)
{
for (var j = 0; j < nx; j++)
{
X[i][j] -= X[k][j] * LU[i][k];
}
}
}
return new MatrixValue(X, piv.Length, nx);
}
#endregion // Public Methods
}
}
| |
// Copyright 2016, Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using System.Threading.Tasks;
namespace Google.Devtools.Clouderrorreporting.V1Beta1
{
/// <summary>
/// Settings for a <see cref="ErrorGroupServiceClient"/>.
/// </summary>
public sealed partial class ErrorGroupServiceSettings : ServiceSettingsBase
{
/// <summary>
/// Get a new instance of the default <see cref="ErrorGroupServiceSettings"/>.
/// </summary>
/// <returns>
/// A new instance of the default <see cref="ErrorGroupServiceSettings"/>.
/// </returns>
public static ErrorGroupServiceSettings GetDefault() => new ErrorGroupServiceSettings();
/// <summary>
/// Constructs a new <see cref="ErrorGroupServiceSettings"/> object with default settings.
/// </summary>
public ErrorGroupServiceSettings() { }
private ErrorGroupServiceSettings(ErrorGroupServiceSettings existing) : base(existing)
{
GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetGroupSettings = existing.GetGroupSettings;
UpdateGroupSettings = existing.UpdateGroupSettings;
}
/// <summary>
/// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry
/// for "Idempotent" <see cref="ErrorGroupServiceClient"/> RPC methods.
/// </summary>
/// <remarks>
/// The eligible RPC <see cref="StatusCode"/>s for retry for "Idempotent" RPC methods are:
/// <list type="bullet">
/// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item>
/// <item><description><see cref="StatusCode.Unavailable"/></description></item>
/// </list>
/// </remarks>
public static Predicate<RpcException> IdempotentRetryFilter { get; } =
RetrySettings.FilterForStatusCodes(StatusCode.DeadlineExceeded, StatusCode.Unavailable);
/// <summary>
/// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry
/// for "NonIdempotent" <see cref="ErrorGroupServiceClient"/> RPC methods.
/// </summary>
/// <remarks>
/// There are no RPC <see cref="StatusCode"/>s eligible for retry for "NonIdempotent" RPC methods.
/// </remarks>
public static Predicate<RpcException> NonIdempotentRetryFilter { get; } =
RetrySettings.FilterForStatusCodes();
/// <summary>
/// "Default" retry backoff for <see cref="ErrorGroupServiceClient"/> RPC methods.
/// </summary>
/// <returns>
/// The "Default" retry backoff for <see cref="ErrorGroupServiceClient"/> RPC methods.
/// </returns>
/// <remarks>
/// The "Default" retry backoff for <see cref="ErrorGroupServiceClient"/> RPC methods is defined as:
/// <list type="bullet">
/// <item><description>Initial delay: 100 milliseconds</description></item>
/// <item><description>Maximum delay: 60000 milliseconds</description></item>
/// <item><description>Delay multiplier: 1.3</description></item>
/// </list>
/// </remarks>
public static BackoffSettings GetDefaultRetryBackoff() => new BackoffSettings(
delay: TimeSpan.FromMilliseconds(100),
maxDelay: TimeSpan.FromMilliseconds(60000),
delayMultiplier: 1.3
);
/// <summary>
/// "Default" timeout backoff for <see cref="ErrorGroupServiceClient"/> RPC methods.
/// </summary>
/// <returns>
/// The "Default" timeout backoff for <see cref="ErrorGroupServiceClient"/> RPC methods.
/// </returns>
/// <remarks>
/// The "Default" timeout backoff for <see cref="ErrorGroupServiceClient"/> RPC methods is defined as:
/// <list type="bullet">
/// <item><description>Initial timeout: 20000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.0</description></item>
/// <item><description>Maximum timeout: 20000 milliseconds</description></item>
/// </list>
/// </remarks>
public static BackoffSettings GetDefaultTimeoutBackoff() => new BackoffSettings(
delay: TimeSpan.FromMilliseconds(20000),
maxDelay: TimeSpan.FromMilliseconds(20000),
delayMultiplier: 1.0
);
/// <summary>
/// <see cref="CallSettings"/> for synchronous and asynchronous calls to
/// <c>ErrorGroupServiceClient.GetGroup</c> and <c>ErrorGroupServiceClient.GetGroupAsync</c>.
/// </summary>
/// <remarks>
/// The default <c>ErrorGroupServiceClient.GetGroup</c> and
/// <c>ErrorGroupServiceClient.GetGroupAsync</c> <see cref="RetrySettings"/> are:
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds</description></item>
/// <item><description>Initial timeout: 20000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.0</description></item>
/// <item><description>Timeout maximum delay: 20000 milliseconds</description></item>
/// </list>
/// Retry will be attempted on the following response status codes:
/// <list>
/// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item>
/// <item><description><see cref="StatusCode.Unavailable"/></description></item>
/// </list>
/// Default RPC expiration is 600000 milliseconds.
/// </remarks>
public CallSettings GetGroupSettings { get; set; } = CallSettings.FromCallTiming(
CallTiming.FromRetry(new RetrySettings(
retryBackoff: GetDefaultRetryBackoff(),
timeoutBackoff: GetDefaultTimeoutBackoff(),
totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)),
retryFilter: IdempotentRetryFilter
)));
/// <summary>
/// <see cref="CallSettings"/> for synchronous and asynchronous calls to
/// <c>ErrorGroupServiceClient.UpdateGroup</c> and <c>ErrorGroupServiceClient.UpdateGroupAsync</c>.
/// </summary>
/// <remarks>
/// The default <c>ErrorGroupServiceClient.UpdateGroup</c> and
/// <c>ErrorGroupServiceClient.UpdateGroupAsync</c> <see cref="RetrySettings"/> are:
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds</description></item>
/// <item><description>Initial timeout: 20000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.0</description></item>
/// <item><description>Timeout maximum delay: 20000 milliseconds</description></item>
/// </list>
/// Retry will be attempted on the following response status codes:
/// <list>
/// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item>
/// <item><description><see cref="StatusCode.Unavailable"/></description></item>
/// </list>
/// Default RPC expiration is 600000 milliseconds.
/// </remarks>
public CallSettings UpdateGroupSettings { get; set; } = CallSettings.FromCallTiming(
CallTiming.FromRetry(new RetrySettings(
retryBackoff: GetDefaultRetryBackoff(),
timeoutBackoff: GetDefaultTimeoutBackoff(),
totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)),
retryFilter: IdempotentRetryFilter
)));
/// <summary>
/// Creates a deep clone of this object, with all the same property values.
/// </summary>
/// <returns>A deep clone of this <see cref="ErrorGroupServiceSettings"/> object.</returns>
public ErrorGroupServiceSettings Clone() => new ErrorGroupServiceSettings(this);
}
/// <summary>
/// ErrorGroupService client wrapper, for convenient use.
/// </summary>
public abstract partial class ErrorGroupServiceClient
{
/// <summary>
/// The default endpoint for the ErrorGroupService service, which is a host of "clouderrorreporting.googleapis.com" and a port of 443.
/// </summary>
public static ServiceEndpoint DefaultEndpoint { get; } = new ServiceEndpoint("clouderrorreporting.googleapis.com", 443);
/// <summary>
/// The default ErrorGroupService scopes.
/// </summary>
/// <remarks>
/// The default ErrorGroupService scopes are:
/// <list type="bullet">
/// <item><description>"https://www.googleapis.com/auth/cloud-platform"</description></item>
/// </list>
/// </remarks>
public static IReadOnlyList<string> DefaultScopes { get; } = new ReadOnlyCollection<string>(new string[] {
"https://www.googleapis.com/auth/cloud-platform",
});
private static readonly ChannelPool s_channelPool = new ChannelPool(DefaultScopes);
/// <summary>
/// Path template for a group resource. Parameters:
/// <list type="bullet">
/// <item><description>project</description></item>
/// <item><description>group</description></item>
/// </list>
/// </summary>
public static PathTemplate GroupTemplate { get; } = new PathTemplate("projects/{project}/groups/{group}");
/// <summary>
/// Creates a group resource name from its component IDs.
/// </summary>
/// <param name="projectId">The project ID.</param>
/// <param name="groupId">The group ID.</param>
/// <returns>
/// The full group resource name.
/// </returns>
public static string FormatGroupName(string projectId, string groupId) => GroupTemplate.Expand(projectId, groupId);
/// <summary>
/// Path template for a project resource. Parameters:
/// <list type="bullet">
/// <item><description>project</description></item>
/// </list>
/// </summary>
public static PathTemplate ProjectTemplate { get; } = new PathTemplate("projects/{project}");
/// <summary>
/// Creates a project resource name from its component IDs.
/// </summary>
/// <param name="projectId">The project ID.</param>
/// <returns>
/// The full project resource name.
/// </returns>
public static string FormatProjectName(string projectId) => ProjectTemplate.Expand(projectId);
// Note: we could have parameterless overloads of Create and CreateAsync,
// documented to just use the default endpoint, settings and credentials.
// Pros:
// - Might be more reassuring on first use
// - Allows method group conversions
// Con: overloads!
/// <summary>
/// Asynchronously creates a <see cref="ErrorGroupServiceClient"/>, applying defaults for all unspecified settings,
/// and creating a channel connecting to the given endpoint with application default credentials where
/// necessary.
/// </summary>
/// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param>
/// <param name="settings">Optional <see cref="ErrorGroupServiceSettings"/>.</param>
/// <returns>The task representing the created <see cref="ErrorGroupServiceClient"/>.</returns>
public static async Task<ErrorGroupServiceClient> CreateAsync(ServiceEndpoint endpoint = null, ErrorGroupServiceSettings settings = null)
{
Channel channel = await s_channelPool.GetChannelAsync(endpoint ?? DefaultEndpoint).ConfigureAwait(false);
return Create(channel, settings);
}
/// <summary>
/// Synchronously creates a <see cref="ErrorGroupServiceClient"/>, applying defaults for all unspecified settings,
/// and creating a channel connecting to the given endpoint with application default credentials where
/// necessary.
/// </summary>
/// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param>
/// <param name="settings">Optional <see cref="ErrorGroupServiceSettings"/>.</param>
/// <returns>The created <see cref="ErrorGroupServiceClient"/>.</returns>
public static ErrorGroupServiceClient Create(ServiceEndpoint endpoint = null, ErrorGroupServiceSettings settings = null)
{
Channel channel = s_channelPool.GetChannel(endpoint ?? DefaultEndpoint);
return Create(channel, settings);
}
/// <summary>
/// Creates a <see cref="ErrorGroupServiceClient"/> which uses the specified channel for remote operations.
/// </summary>
/// <param name="channel">The <see cref="Channel"/> for remote operations. Must not be null.</param>
/// <param name="settings">Optional <see cref="ErrorGroupServiceSettings"/>.</param>
/// <returns>The created <see cref="ErrorGroupServiceClient"/>.</returns>
public static ErrorGroupServiceClient Create(Channel channel, ErrorGroupServiceSettings settings = null)
{
GaxPreconditions.CheckNotNull(channel, nameof(channel));
ErrorGroupService.ErrorGroupServiceClient grpcClient = new ErrorGroupService.ErrorGroupServiceClient(channel);
return new ErrorGroupServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create(ServiceEndpoint, ErrorGroupServiceSettings)"/>
/// and <see cref="CreateAsync(ServiceEndpoint, ErrorGroupServiceSettings)"/>. Channels which weren't automatically
/// created are not affected.
/// </summary>
/// <remarks>After calling this method, further calls to <see cref="Create(ServiceEndpoint, ErrorGroupServiceSettings)"/>
/// and <see cref="CreateAsync(ServiceEndpoint, ErrorGroupServiceSettings)"/> 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 Task ShutdownDefaultChannelsAsync() => s_channelPool.ShutdownChannelsAsync();
/// <summary>
/// The underlying gRPC ErrorGroupService client.
/// </summary>
public virtual ErrorGroupService.ErrorGroupServiceClient GrpcClient
{
get { throw new NotImplementedException(); }
}
/// <summary>
/// Get the specified group.
/// </summary>
/// <param name="groupName">
/// [Required] The group resource name. Written as
/// <code>projects/<var>projectID</var>/groups/<var>group_name</var></code>.
/// Call
/// <a href="/error-reporting/reference/rest/v1beta1/projects.groupStats/list">
/// <code>groupStats.list</code></a> to return a list of groups belonging to
/// this project.
///
/// Example: <code>projects/my-project-123/groups/my-group</code>
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<ErrorGroup> GetGroupAsync(
string groupName,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Get the specified group.
/// </summary>
/// <param name="groupName">
/// [Required] The group resource name. Written as
/// <code>projects/<var>projectID</var>/groups/<var>group_name</var></code>.
/// Call
/// <a href="/error-reporting/reference/rest/v1beta1/projects.groupStats/list">
/// <code>groupStats.list</code></a> to return a list of groups belonging to
/// this project.
///
/// Example: <code>projects/my-project-123/groups/my-group</code>
/// </param>
/// <param name="cancellationToken">
/// A <see cref="CancellationToken"/> to use for this RPC.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<ErrorGroup> GetGroupAsync(
string groupName,
CancellationToken cancellationToken) => GetGroupAsync(
groupName,
CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Get the specified group.
/// </summary>
/// <param name="groupName">
/// [Required] The group resource name. Written as
/// <code>projects/<var>projectID</var>/groups/<var>group_name</var></code>.
/// Call
/// <a href="/error-reporting/reference/rest/v1beta1/projects.groupStats/list">
/// <code>groupStats.list</code></a> to return a list of groups belonging to
/// this project.
///
/// Example: <code>projects/my-project-123/groups/my-group</code>
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual ErrorGroup GetGroup(
string groupName,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Replace the data for the specified group.
/// Fails if the group does not exist.
/// </summary>
/// <param name="group">
/// [Required] The group which replaces the resource on the server.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<ErrorGroup> UpdateGroupAsync(
ErrorGroup group,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Replace the data for the specified group.
/// Fails if the group does not exist.
/// </summary>
/// <param name="group">
/// [Required] The group which replaces the resource on the server.
/// </param>
/// <param name="cancellationToken">
/// A <see cref="CancellationToken"/> to use for this RPC.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<ErrorGroup> UpdateGroupAsync(
ErrorGroup group,
CancellationToken cancellationToken) => UpdateGroupAsync(
group,
CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Replace the data for the specified group.
/// Fails if the group does not exist.
/// </summary>
/// <param name="group">
/// [Required] The group which replaces the resource on the server.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual ErrorGroup UpdateGroup(
ErrorGroup group,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
}
/// <summary>
/// ErrorGroupService client wrapper implementation, for convenient use.
/// </summary>
public sealed partial class ErrorGroupServiceClientImpl : ErrorGroupServiceClient
{
private readonly ClientHelper _clientHelper;
private readonly ApiCall<GetGroupRequest, ErrorGroup> _callGetGroup;
private readonly ApiCall<UpdateGroupRequest, ErrorGroup> _callUpdateGroup;
/// <summary>
/// Constructs a client wrapper for the ErrorGroupService service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="ErrorGroupServiceSettings"/> used within this client </param>
public ErrorGroupServiceClientImpl(ErrorGroupService.ErrorGroupServiceClient grpcClient, ErrorGroupServiceSettings settings)
{
this.GrpcClient = grpcClient;
ErrorGroupServiceSettings effectiveSettings = settings ?? ErrorGroupServiceSettings.GetDefault();
_clientHelper = new ClientHelper(effectiveSettings);
_callGetGroup = _clientHelper.BuildApiCall<GetGroupRequest, ErrorGroup>(
GrpcClient.GetGroupAsync, GrpcClient.GetGroup, effectiveSettings.GetGroupSettings);
_callUpdateGroup = _clientHelper.BuildApiCall<UpdateGroupRequest, ErrorGroup>(
GrpcClient.UpdateGroupAsync, GrpcClient.UpdateGroup, effectiveSettings.UpdateGroupSettings);
}
/// <summary>
/// The underlying gRPC ErrorGroupService client.
/// </summary>
public override ErrorGroupService.ErrorGroupServiceClient GrpcClient { get; }
// Partial modifier methods contain '_' to ensure no name conflicts with RPC methods.
partial void Modify_GetGroupRequest(ref GetGroupRequest request, ref CallSettings settings);
partial void Modify_UpdateGroupRequest(ref UpdateGroupRequest request, ref CallSettings settings);
/// <summary>
/// Get the specified group.
/// </summary>
/// <param name="groupName">
/// [Required] The group resource name. Written as
/// <code>projects/<var>projectID</var>/groups/<var>group_name</var></code>.
/// Call
/// <a href="/error-reporting/reference/rest/v1beta1/projects.groupStats/list">
/// <code>groupStats.list</code></a> to return a list of groups belonging to
/// this project.
///
/// Example: <code>projects/my-project-123/groups/my-group</code>
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public override Task<ErrorGroup> GetGroupAsync(
string groupName,
CallSettings callSettings = null)
{
GetGroupRequest request = new GetGroupRequest
{
GroupName = groupName,
};
Modify_GetGroupRequest(ref request, ref callSettings);
return _callGetGroup.Async(request, callSettings);
}
/// <summary>
/// Get the specified group.
/// </summary>
/// <param name="groupName">
/// [Required] The group resource name. Written as
/// <code>projects/<var>projectID</var>/groups/<var>group_name</var></code>.
/// Call
/// <a href="/error-reporting/reference/rest/v1beta1/projects.groupStats/list">
/// <code>groupStats.list</code></a> to return a list of groups belonging to
/// this project.
///
/// Example: <code>projects/my-project-123/groups/my-group</code>
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public override ErrorGroup GetGroup(
string groupName,
CallSettings callSettings = null)
{
GetGroupRequest request = new GetGroupRequest
{
GroupName = groupName,
};
Modify_GetGroupRequest(ref request, ref callSettings);
return _callGetGroup.Sync(request, callSettings);
}
/// <summary>
/// Replace the data for the specified group.
/// Fails if the group does not exist.
/// </summary>
/// <param name="group">
/// [Required] The group which replaces the resource on the server.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public override Task<ErrorGroup> UpdateGroupAsync(
ErrorGroup group,
CallSettings callSettings = null)
{
UpdateGroupRequest request = new UpdateGroupRequest
{
Group = group,
};
Modify_UpdateGroupRequest(ref request, ref callSettings);
return _callUpdateGroup.Async(request, callSettings);
}
/// <summary>
/// Replace the data for the specified group.
/// Fails if the group does not exist.
/// </summary>
/// <param name="group">
/// [Required] The group which replaces the resource on the server.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public override ErrorGroup UpdateGroup(
ErrorGroup group,
CallSettings callSettings = null)
{
UpdateGroupRequest request = new UpdateGroupRequest
{
Group = group,
};
Modify_UpdateGroupRequest(ref request, ref callSettings);
return _callUpdateGroup.Sync(request, callSettings);
}
}
// Partial classes to enable page-streaming
}
| |
// 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.Net.Http.Headers;
using Xunit;
namespace System.Net.Http.Tests
{
public class AuthenticationHeaderValueTest
{
[Fact]
public void Ctor_SetBothSchemeAndParameters_MatchExpectation()
{
AuthenticationHeaderValue auth = new AuthenticationHeaderValue("Basic", "realm=\"contoso.com\"");
Assert.Equal("Basic", auth.Scheme);
Assert.Equal("realm=\"contoso.com\"", auth.Parameter);
Assert.Throws<ArgumentException>(() => { new AuthenticationHeaderValue(null, "x"); });
Assert.Throws<ArgumentException>(() => { new AuthenticationHeaderValue("", "x"); });
Assert.Throws<FormatException>(() => { new AuthenticationHeaderValue(" x", "x"); });
Assert.Throws<FormatException>(() => { new AuthenticationHeaderValue("x ", "x"); });
Assert.Throws<FormatException>(() => { new AuthenticationHeaderValue("x y", "x"); });
}
[Fact]
public void Ctor_SetSchemeOnly_MatchExpectation()
{
// Just verify that this ctor forwards the call to the overload taking 2 parameters.
AuthenticationHeaderValue auth = new AuthenticationHeaderValue("NTLM");
Assert.Equal("NTLM", auth.Scheme);
Assert.Null(auth.Parameter);
}
[Fact]
public void ToString_UseBothNoParameterAndSetParameter_AllSerializedCorrectly()
{
using (HttpResponseMessage response = new HttpResponseMessage())
{
string input = string.Empty;
AuthenticationHeaderValue auth = new AuthenticationHeaderValue("Digest",
"qop=\"auth\",algorithm=MD5-sess,nonce=\"+Upgraded+v109e309640b\",charset=utf-8,realm=\"Digest\"");
Assert.Equal(
"Digest qop=\"auth\",algorithm=MD5-sess,nonce=\"+Upgraded+v109e309640b\",charset=utf-8,realm=\"Digest\"",
auth.ToString());
response.Headers.ProxyAuthenticate.Add(auth);
input += auth.ToString();
auth = new AuthenticationHeaderValue("Negotiate");
Assert.Equal("Negotiate", auth.ToString());
response.Headers.ProxyAuthenticate.Add(auth);
input += ", " + auth.ToString();
auth = new AuthenticationHeaderValue("Custom", ""); // empty string should be treated like 'null'.
Assert.Equal("Custom", auth.ToString());
response.Headers.ProxyAuthenticate.Add(auth);
input += ", " + auth.ToString();
string result = response.Headers.ProxyAuthenticate.ToString();
Assert.Equal(input, result);
}
}
[Fact]
public void Parse_GoodValues_Success()
{
HttpRequestMessage request = new HttpRequestMessage();
string input = " Digest qop=\"auth\",algorithm=MD5-sess,nonce=\"+Upgraded+v109e309640b\",charset=utf-8 ";
request.Headers.Authorization = AuthenticationHeaderValue.Parse(input);
Assert.Equal(input.Trim(), request.Headers.Authorization.ToString());
}
[Fact]
public void TryParse_GoodValues_Success()
{
HttpRequestMessage request = new HttpRequestMessage();
string input = " Digest qop=\"auth\",algorithm=MD5-sess,nonce=\"+Upgraded+v109e309640b\",realm=\"Digest\" ";
AuthenticationHeaderValue parsedValue;
Assert.True(AuthenticationHeaderValue.TryParse(input, out parsedValue));
request.Headers.Authorization = parsedValue;
Assert.Equal(input.Trim(), request.Headers.Authorization.ToString());
}
[Fact]
public void Parse_BadValues_Throws()
{
string input = "D\rigest qop=\"auth\",algorithm=MD5-sess,charset=utf-8,realm=\"Digest\"";
Assert.Throws<FormatException>(() => { AuthenticationHeaderValue.Parse(input); });
}
[Fact]
public void TryParse_BadValues_False()
{
string input = ", Digest qop=\"auth\",nonce=\"+Upgraded+v109e309640b\",charset=utf-8,realm=\"Digest\"";
AuthenticationHeaderValue parsedValue;
Assert.False(AuthenticationHeaderValue.TryParse(input, out parsedValue));
}
[Fact]
public void Add_BadValues_Throws()
{
string x = SR.net_http_message_not_success_statuscode;
string input = "Digest algorithm=MD5-sess,nonce=\"+Upgraded+v109e309640b\",charset=utf-8,realm=\"Digest\", ";
HttpRequestMessage request = new HttpRequestMessage();
Assert.Throws<FormatException>(() => { request.Headers.Add(HttpKnownHeaderNames.Authorization, input); });
}
[Fact]
public void GetHashCode_UseSameAndDifferentAuth_SameOrDifferentHashCodes()
{
AuthenticationHeaderValue auth1 = new AuthenticationHeaderValue("A", "b");
AuthenticationHeaderValue auth2 = new AuthenticationHeaderValue("a", "b");
AuthenticationHeaderValue auth3 = new AuthenticationHeaderValue("A", "B");
AuthenticationHeaderValue auth4 = new AuthenticationHeaderValue("A");
AuthenticationHeaderValue auth5 = new AuthenticationHeaderValue("A", "");
AuthenticationHeaderValue auth6 = new AuthenticationHeaderValue("X", "b");
Assert.Equal(auth1.GetHashCode(), auth2.GetHashCode());
Assert.NotEqual(auth1.GetHashCode(), auth3.GetHashCode());
Assert.NotEqual(auth1.GetHashCode(), auth4.GetHashCode());
Assert.Equal(auth4.GetHashCode(), auth5.GetHashCode());
Assert.NotEqual(auth1.GetHashCode(), auth6.GetHashCode());
}
[Fact]
public void Equals_UseSameAndDifferentAuth_EqualOrNotEqualNoExceptions()
{
AuthenticationHeaderValue auth1 = new AuthenticationHeaderValue("A", "b");
AuthenticationHeaderValue auth2 = new AuthenticationHeaderValue("a", "b");
AuthenticationHeaderValue auth3 = new AuthenticationHeaderValue("A", "B");
AuthenticationHeaderValue auth4 = new AuthenticationHeaderValue("A");
AuthenticationHeaderValue auth5 = new AuthenticationHeaderValue("A", "");
AuthenticationHeaderValue auth6 = new AuthenticationHeaderValue("X", "b");
Assert.False(auth1.Equals(null));
Assert.True(auth1.Equals(auth2));
Assert.False(auth1.Equals(auth3));
Assert.False(auth1.Equals(auth4));
Assert.False(auth4.Equals(auth1));
Assert.False(auth1.Equals(auth5));
Assert.False(auth5.Equals(auth1));
Assert.True(auth4.Equals(auth5));
Assert.True(auth5.Equals(auth4));
Assert.False(auth1.Equals(auth6));
}
[Fact]
public void Clone_Call_CloneFieldsMatchSourceFields()
{
AuthenticationHeaderValue source = new AuthenticationHeaderValue("Basic", "QWxhZGRpbjpvcGVuIHNlc2FtZQ==");
AuthenticationHeaderValue clone = (AuthenticationHeaderValue)((ICloneable)source).Clone();
Assert.Equal(source.Scheme, clone.Scheme);
Assert.Equal(source.Parameter, clone.Parameter);
source = new AuthenticationHeaderValue("Kerberos");
clone = (AuthenticationHeaderValue)((ICloneable)source).Clone();
Assert.Equal(source.Scheme, clone.Scheme);
Assert.Null(clone.Parameter);
}
[Fact]
public void GetAuthenticationLength_DifferentValidScenarios_AllReturnNonZero()
{
CallGetAuthenticationLength(" Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== ", 1, 37,
new AuthenticationHeaderValue("Basic", "QWxhZGRpbjpvcGVuIHNlc2FtZQ=="));
CallGetAuthenticationLength(" Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== , ", 1, 37,
new AuthenticationHeaderValue("Basic", "QWxhZGRpbjpvcGVuIHNlc2FtZQ=="));
CallGetAuthenticationLength(" Basic realm=\"example.com\"", 1, 25,
new AuthenticationHeaderValue("Basic", "realm=\"example.com\""));
CallGetAuthenticationLength(" Basic realm=\"exam,,ple.com\",", 1, 27,
new AuthenticationHeaderValue("Basic", "realm=\"exam,,ple.com\""));
CallGetAuthenticationLength(" Basic realm=\"exam,ple.com\",", 1, 26,
new AuthenticationHeaderValue("Basic", "realm=\"exam,ple.com\""));
CallGetAuthenticationLength("NTLM ", 0, 7, new AuthenticationHeaderValue("NTLM"));
CallGetAuthenticationLength("Digest", 0, 6, new AuthenticationHeaderValue("Digest"));
CallGetAuthenticationLength("Digest,,", 0, 6, new AuthenticationHeaderValue("Digest"));
CallGetAuthenticationLength("Digest a=b, c=d,,", 0, 15, new AuthenticationHeaderValue("Digest", "a=b, c=d"));
CallGetAuthenticationLength("Kerberos,", 0, 8, new AuthenticationHeaderValue("Kerberos"));
CallGetAuthenticationLength("Basic,NTLM", 0, 5, new AuthenticationHeaderValue("Basic"));
CallGetAuthenticationLength("Digest a=b,c=\"d\", e=f, NTLM", 0, 21,
new AuthenticationHeaderValue("Digest", "a=b,c=\"d\", e=f"));
CallGetAuthenticationLength("Digest a = b , c = \"d\" , e = f ,NTLM", 0, 32,
new AuthenticationHeaderValue("Digest", "a = b , c = \"d\" , e = f"));
CallGetAuthenticationLength("Digest a = b , c = \"d\" , e = f , NTLM AbCdEf==", 0, 32,
new AuthenticationHeaderValue("Digest", "a = b , c = \"d\" , e = f"));
CallGetAuthenticationLength("Digest a = \"b\", c= \"d\" , e = f,NTLM AbC=,", 0, 31,
new AuthenticationHeaderValue("Digest", "a = \"b\", c= \"d\" , e = f"));
CallGetAuthenticationLength("Digest a=\"b\", c=d", 0, 17,
new AuthenticationHeaderValue("Digest", "a=\"b\", c=d"));
CallGetAuthenticationLength("Digest a=\"b\", c=d,", 0, 17,
new AuthenticationHeaderValue("Digest", "a=\"b\", c=d"));
CallGetAuthenticationLength("Digest a=\"b\", c=d ,", 0, 18,
new AuthenticationHeaderValue("Digest", "a=\"b\", c=d"));
CallGetAuthenticationLength("Digest a=\"b\", c=d ", 0, 19,
new AuthenticationHeaderValue("Digest", "a=\"b\", c=d"));
CallGetAuthenticationLength("Custom \"blob\", c=d,Custom2 \"blob\"", 0, 18,
new AuthenticationHeaderValue("Custom", "\"blob\", c=d"));
CallGetAuthenticationLength("Custom \"blob\", a=b,,,c=d,Custom2 \"blob\"", 0, 24,
new AuthenticationHeaderValue("Custom", "\"blob\", a=b,,,c=d"));
CallGetAuthenticationLength("Custom \"blob\", a=b,c=d,,,Custom2 \"blob\"", 0, 22,
new AuthenticationHeaderValue("Custom", "\"blob\", a=b,c=d"));
CallGetAuthenticationLength("Custom a=b, c=d,,,InvalidNextScheme\u670D", 0, 15,
new AuthenticationHeaderValue("Custom", "a=b, c=d"));
}
[Fact]
public void GetAuthenticationLength_DifferentInvalidScenarios_AllReturnZero()
{
CheckInvalidGetAuthenticationLength(" NTLM", 0); // no leading whitespace allowed
CheckInvalidGetAuthenticationLength("Basic=", 0);
CheckInvalidGetAuthenticationLength("=Basic", 0);
CheckInvalidGetAuthenticationLength("Digest a=b, \u670D", 0);
CheckInvalidGetAuthenticationLength("Digest a=b, c=d, \u670D", 0);
CheckInvalidGetAuthenticationLength("Digest a=b, c=", 0);
CheckInvalidGetAuthenticationLength("Digest a=\"b, c", 0);
CheckInvalidGetAuthenticationLength("Digest a=\"b", 0);
CheckInvalidGetAuthenticationLength("Digest a=b, c=\u670D", 0);
CheckInvalidGetAuthenticationLength("", 0);
CheckInvalidGetAuthenticationLength(null, 0);
}
#region Helper methods
private static void CallGetAuthenticationLength(string input, int startIndex, int expectedLength,
AuthenticationHeaderValue expectedResult)
{
object result = null;
Assert.Equal(expectedLength, AuthenticationHeaderValue.GetAuthenticationLength(input, startIndex, out result));
Assert.Equal(expectedResult, result);
}
private static void CheckInvalidGetAuthenticationLength(string input, int startIndex)
{
object result = null;
Assert.Equal(0, AuthenticationHeaderValue.GetAuthenticationLength(input, startIndex, out result));
Assert.Null(result);
}
#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.
//
// Don't override IsAlwaysNormalized because it is just a Unicode Transformation and could be confused.
//
using System;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
namespace System.Text
{
// Encodes text into and out of UTF-32. UTF-32 is a way of writing
// Unicode characters with a single storage unit (32 bits) per character,
//
// The UTF-32 byte order mark is simply the Unicode byte order mark
// (0x00FEFF) written in UTF-32 (0x0000FEFF or 0xFFFE0000). The byte order
// mark is used mostly to distinguish UTF-32 text from other encodings, and doesn't
// switch the byte orderings.
public sealed class UTF32Encoding : Encoding
{
/*
words bits UTF-32 representation
----- ---- -----------------------------------
1 16 00000000 00000000 xxxxxxxx xxxxxxxx
2 21 00000000 000xxxxx hhhhhhll llllllll
----- ---- -----------------------------------
Surrogate:
Real Unicode value = (HighSurrogate - 0xD800) * 0x400 + (LowSurrogate - 0xDC00) + 0x10000
*/
// Used by Encoding.UTF32/BigEndianUTF32 for lazy initialization
// The initialization code will not be run until a static member of the class is referenced
internal static readonly UTF32Encoding s_default = new UTF32Encoding(bigEndian: false, byteOrderMark: true);
internal static readonly UTF32Encoding s_bigEndianDefault = new UTF32Encoding(bigEndian: true, byteOrderMark: true);
private static readonly byte[] s_bigEndianPreamble = new byte[4] { 0x00, 0x00, 0xFE, 0xFF };
private static readonly byte[] s_littleEndianPreamble = new byte[4] { 0xFF, 0xFE, 0x00, 0x00 };
private bool _emitUTF32ByteOrderMark = false;
private bool _isThrowException = false;
private bool _bigEndian = false;
public UTF32Encoding() : this(false, true, false)
{
}
public UTF32Encoding(bool bigEndian, bool byteOrderMark) :
this(bigEndian, byteOrderMark, false)
{
}
public UTF32Encoding(bool bigEndian, bool byteOrderMark, bool throwOnInvalidCharacters) :
base(bigEndian ? 12001 : 12000)
{
_bigEndian = bigEndian;
_emitUTF32ByteOrderMark = byteOrderMark;
_isThrowException = throwOnInvalidCharacters;
// Encoding constructor already did this, but it'll be wrong if we're throwing exceptions
if (_isThrowException)
SetDefaultFallbacks();
}
internal override void SetDefaultFallbacks()
{
// For UTF-X encodings, we use a replacement fallback with an empty string
if (_isThrowException)
{
this.encoderFallback = EncoderFallback.ExceptionFallback;
this.decoderFallback = DecoderFallback.ExceptionFallback;
}
else
{
this.encoderFallback = new EncoderReplacementFallback("\xFFFD");
this.decoderFallback = new DecoderReplacementFallback("\xFFFD");
}
}
// The following methods are copied from EncodingNLS.cs.
// Unfortunately EncodingNLS.cs is internal and we're public, so we have to re-implement them here.
// These should be kept in sync for the following classes:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// Returns the number of bytes required to encode a range of characters in
// a character array.
//
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
public override unsafe int GetByteCount(char[] chars, int index, int count)
{
// Validate input parameters
if (chars == null)
throw new ArgumentNullException("chars", SR.ArgumentNull_Array);
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum);
if (chars.Length - index < count)
throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer);
// If no input, return 0, avoid fixed empty array problem
if (count == 0)
return 0;
// Just call the pointer version
fixed (char* pChars = chars)
return GetByteCount(pChars + index, count, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
public override unsafe int GetByteCount(String s)
{
// Validate input
if (s==null)
throw new ArgumentNullException("s");
fixed (char* pChars = s)
return GetByteCount(pChars, s.Length, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
[CLSCompliant(false)]
public override unsafe int GetByteCount(char* chars, int count)
{
// Validate Parameters
if (chars == null)
throw new ArgumentNullException("chars", SR.ArgumentNull_Array);
if (count < 0)
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
// Call it with empty encoder
return GetByteCount(chars, count, null);
}
// Parent method is safe.
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
public override unsafe int GetBytes(String s, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
if (s == null || bytes == null)
throw new ArgumentNullException((s == null ? "s" : "bytes"), SR.ArgumentNull_Array);
if (charIndex < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum);
if (s.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException("s", SR.ArgumentOutOfRange_IndexCount);
if (byteIndex < 0 || byteIndex > bytes.Length)
throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index);
int byteCount = bytes.Length - byteIndex;
fixed (char* pChars = s) fixed (byte* pBytes = &MemoryMarshal.GetReference((Span<byte>)bytes))
return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null);
}
// Encodes a range of characters in a character array into a range of bytes
// in a byte array. An exception occurs if the byte array is not large
// enough to hold the complete encoding of the characters. The
// GetByteCount method can be used to determine the exact number of
// bytes that will be produced for a given range of characters.
// Alternatively, the GetMaxByteCount method can be used to
// determine the maximum number of bytes that will be produced for a given
// number of characters, regardless of the actual character values.
//
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
public override unsafe int GetBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
// Validate parameters
if (chars == null || bytes == null)
throw new ArgumentNullException((chars == null ? "chars" : "bytes"), SR.ArgumentNull_Array);
if (charIndex < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum);
if (chars.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer);
if (byteIndex < 0 || byteIndex > bytes.Length)
throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index);
// If nothing to encode return 0, avoid fixed problem
if (charCount == 0)
return 0;
// Just call pointer version
int byteCount = bytes.Length - byteIndex;
fixed (char* pChars = chars) fixed (byte* pBytes = &MemoryMarshal.GetReference((Span<byte>)bytes))
// Remember that byteCount is # to decode, not size of array.
return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
[CLSCompliant(false)]
public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount)
{
// Validate Parameters
if (bytes == null || chars == null)
throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array);
if (charCount < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum);
return GetBytes(chars, charCount, bytes, byteCount, null);
}
// Returns the number of characters produced by decoding a range of bytes
// in a byte array.
//
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
public override unsafe int GetCharCount(byte[] bytes, int index, int count)
{
// Validate Parameters
if (bytes == null)
throw new ArgumentNullException("bytes", SR.ArgumentNull_Array);
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum);
if (bytes.Length - index < count)
throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer);
// If no input just return 0, fixed doesn't like 0 length arrays.
if (count == 0)
return 0;
// Just call pointer version
fixed (byte* pBytes = bytes)
return GetCharCount(pBytes + index, count, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
[CLSCompliant(false)]
public override unsafe int GetCharCount(byte* bytes, int count)
{
// Validate Parameters
if (bytes == null)
throw new ArgumentNullException("bytes", SR.ArgumentNull_Array);
if (count < 0)
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
return GetCharCount(bytes, count, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex)
{
// Validate Parameters
if (bytes == null || chars == null)
throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array);
if (byteIndex < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((byteIndex < 0 ? "byteIndex" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum);
if ( bytes.Length - byteIndex < byteCount)
throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer);
if (charIndex < 0 || charIndex > chars.Length)
throw new ArgumentOutOfRangeException("charIndex", SR.ArgumentOutOfRange_Index);
// If no input, return 0 & avoid fixed problem
if (byteCount == 0)
return 0;
// Just call pointer version
int charCount = chars.Length - charIndex;
fixed (byte* pBytes = bytes) fixed (char* pChars = &MemoryMarshal.GetReference((Span<char>)chars))
// Remember that charCount is # to decode, not size of array
return GetChars(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
[CLSCompliant(false)]
public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount)
{
// Validate Parameters
if (bytes == null || chars == null)
throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array);
if (charCount < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum);
return GetChars(bytes, byteCount, chars, charCount, null);
}
// Returns a string containing the decoded representation of a range of
// bytes in a byte array.
//
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
public override unsafe String GetString(byte[] bytes, int index, int count)
{
// Validate Parameters
if (bytes == null)
throw new ArgumentNullException("bytes", SR.ArgumentNull_Array);
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum);
if (bytes.Length - index < count)
throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer);
// Avoid problems with empty input buffer
if (count == 0) return String.Empty;
fixed (byte* pBytes = bytes)
return String.CreateStringFromEncoding(
pBytes + index, count, this);
}
//
// End of standard methods copied from EncodingNLS.cs
//
internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS encoder)
{
Debug.Assert(chars != null, "[UTF32Encoding.GetByteCount]chars!=null");
Debug.Assert(count >= 0, "[UTF32Encoding.GetByteCount]count >=0");
char* end = chars + count;
char* charStart = chars;
int byteCount = 0;
char highSurrogate = '\0';
// For fallback we may need a fallback buffer
EncoderFallbackBuffer fallbackBuffer = null;
char* charsForFallback;
if (encoder != null)
{
highSurrogate = encoder._charLeftOver;
fallbackBuffer = encoder.FallbackBuffer;
// We mustn't have left over fallback data when counting
if (fallbackBuffer.Remaining > 0)
throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, this.EncodingName, encoder.Fallback.GetType()));
}
else
{
fallbackBuffer = this.encoderFallback.CreateFallbackBuffer();
}
// Set our internal fallback interesting things.
fallbackBuffer.InternalInitialize(charStart, end, encoder, false);
char ch;
TryAgain:
while (((ch = fallbackBuffer.InternalGetNextChar()) != 0) || chars < end)
{
// First unwind any fallback
if (ch == 0)
{
// No fallback, just get next char
ch = *chars;
chars++;
}
// Do we need a low surrogate?
if (highSurrogate != '\0')
{
//
// In previous char, we encounter a high surrogate, so we are expecting a low surrogate here.
//
if (Char.IsLowSurrogate(ch))
{
// They're all legal
highSurrogate = '\0';
//
// One surrogate pair will be translated into 4 bytes UTF32.
//
byteCount += 4;
continue;
}
// We are missing our low surrogate, decrement chars and fallback the high surrogate
// The high surrogate may have come from the encoder, but nothing else did.
Debug.Assert(chars > charStart,
"[UTF32Encoding.GetByteCount]Expected chars to have advanced if no low surrogate");
chars--;
// Do the fallback
charsForFallback = chars;
fallbackBuffer.InternalFallback(highSurrogate, ref charsForFallback);
chars = charsForFallback;
// We're going to fallback the old high surrogate.
highSurrogate = '\0';
continue;
}
// Do we have another high surrogate?
if (Char.IsHighSurrogate(ch))
{
//
// We'll have a high surrogate to check next time.
//
highSurrogate = ch;
continue;
}
// Check for illegal characters
if (Char.IsLowSurrogate(ch))
{
// We have a leading low surrogate, do the fallback
charsForFallback = chars;
fallbackBuffer.InternalFallback(ch, ref charsForFallback);
chars = charsForFallback;
// Try again with fallback buffer
continue;
}
// We get to add the character (4 bytes UTF32)
byteCount += 4;
}
// May have to do our last surrogate
if ((encoder == null || encoder.MustFlush) && highSurrogate > 0)
{
// We have to do the fallback for the lonely high surrogate
charsForFallback = chars;
fallbackBuffer.InternalFallback(highSurrogate, ref charsForFallback);
chars = charsForFallback;
highSurrogate = (char)0;
goto TryAgain;
}
// Check for overflows.
if (byteCount < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_GetByteCountOverflow);
// Shouldn't have anything in fallback buffer for GetByteCount
// (don't have to check _throwOnOverflow for count)
Debug.Assert(fallbackBuffer.Remaining == 0,
"[UTF32Encoding.GetByteCount]Expected empty fallback buffer at end");
// Return our count
return byteCount;
}
internal override unsafe int GetBytes(char* chars, int charCount,
byte* bytes, int byteCount, EncoderNLS encoder)
{
Debug.Assert(chars != null, "[UTF32Encoding.GetBytes]chars!=null");
Debug.Assert(bytes != null, "[UTF32Encoding.GetBytes]bytes!=null");
Debug.Assert(byteCount >= 0, "[UTF32Encoding.GetBytes]byteCount >=0");
Debug.Assert(charCount >= 0, "[UTF32Encoding.GetBytes]charCount >=0");
char* charStart = chars;
char* charEnd = chars + charCount;
byte* byteStart = bytes;
byte* byteEnd = bytes + byteCount;
char highSurrogate = '\0';
// For fallback we may need a fallback buffer
EncoderFallbackBuffer fallbackBuffer = null;
char* charsForFallback;
if (encoder != null)
{
highSurrogate = encoder._charLeftOver;
fallbackBuffer = encoder.FallbackBuffer;
// We mustn't have left over fallback data when not converting
if (encoder._throwOnOverflow && fallbackBuffer.Remaining > 0)
throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, this.EncodingName, encoder.Fallback.GetType()));
}
else
{
fallbackBuffer = this.encoderFallback.CreateFallbackBuffer();
}
// Set our internal fallback interesting things.
fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, true);
char ch;
TryAgain:
while (((ch = fallbackBuffer.InternalGetNextChar()) != 0) || chars < charEnd)
{
// First unwind any fallback
if (ch == 0)
{
// No fallback, just get next char
ch = *chars;
chars++;
}
// Do we need a low surrogate?
if (highSurrogate != '\0')
{
//
// In previous char, we encountered a high surrogate, so we are expecting a low surrogate here.
//
if (Char.IsLowSurrogate(ch))
{
// Is it a legal one?
uint iTemp = GetSurrogate(highSurrogate, ch);
highSurrogate = '\0';
//
// One surrogate pair will be translated into 4 bytes UTF32.
//
if (bytes + 3 >= byteEnd)
{
// Don't have 4 bytes
if (fallbackBuffer.bFallingBack)
{
fallbackBuffer.MovePrevious(); // Aren't using these 2 fallback chars
fallbackBuffer.MovePrevious();
}
else
{
// If we don't have enough room, then either we should've advanced a while
// or we should have bytes==byteStart and throw below
Debug.Assert(chars > charStart + 1 || bytes == byteStart,
"[UnicodeEncoding.GetBytes]Expected chars to have when no room to add surrogate pair");
chars -= 2; // Aren't using those 2 chars
}
ThrowBytesOverflow(encoder, bytes == byteStart); // Throw maybe (if no bytes written)
highSurrogate = (char)0; // Nothing left over (we backed up to start of pair if supplimentary)
break;
}
if (_bigEndian)
{
*(bytes++) = (byte)(0x00);
*(bytes++) = (byte)(iTemp >> 16); // Implies & 0xFF, which isn't needed cause high are all 0
*(bytes++) = (byte)(iTemp >> 8); // Implies & 0xFF
*(bytes++) = (byte)(iTemp); // Implies & 0xFF
}
else
{
*(bytes++) = (byte)(iTemp); // Implies & 0xFF
*(bytes++) = (byte)(iTemp >> 8); // Implies & 0xFF
*(bytes++) = (byte)(iTemp >> 16); // Implies & 0xFF, which isn't needed cause high are all 0
*(bytes++) = (byte)(0x00);
}
continue;
}
// We are missing our low surrogate, decrement chars and fallback the high surrogate
// The high surrogate may have come from the encoder, but nothing else did.
Debug.Assert(chars > charStart,
"[UTF32Encoding.GetBytes]Expected chars to have advanced if no low surrogate");
chars--;
// Do the fallback
charsForFallback = chars;
fallbackBuffer.InternalFallback(highSurrogate, ref charsForFallback);
chars = charsForFallback;
// We're going to fallback the old high surrogate.
highSurrogate = '\0';
continue;
}
// Do we have another high surrogate?, if so remember it
if (Char.IsHighSurrogate(ch))
{
//
// We'll have a high surrogate to check next time.
//
highSurrogate = ch;
continue;
}
// Check for illegal characters (low surrogate)
if (Char.IsLowSurrogate(ch))
{
// We have a leading low surrogate, do the fallback
charsForFallback = chars;
fallbackBuffer.InternalFallback(ch, ref charsForFallback);
chars = charsForFallback;
// Try again with fallback buffer
continue;
}
// We get to add the character, yippee.
if (bytes + 3 >= byteEnd)
{
// Don't have 4 bytes
if (fallbackBuffer.bFallingBack)
fallbackBuffer.MovePrevious(); // Aren't using this fallback char
else
{
// Must've advanced already
Debug.Assert(chars > charStart,
"[UTF32Encoding.GetBytes]Expected chars to have advanced if normal character");
chars--; // Aren't using this char
}
ThrowBytesOverflow(encoder, bytes == byteStart); // Throw maybe (if no bytes written)
break; // Didn't throw, stop
}
if (_bigEndian)
{
*(bytes++) = (byte)(0x00);
*(bytes++) = (byte)(0x00);
*(bytes++) = (byte)((uint)ch >> 8); // Implies & 0xFF
*(bytes++) = (byte)(ch); // Implies & 0xFF
}
else
{
*(bytes++) = (byte)(ch); // Implies & 0xFF
*(bytes++) = (byte)((uint)ch >> 8); // Implies & 0xFF
*(bytes++) = (byte)(0x00);
*(bytes++) = (byte)(0x00);
}
}
// May have to do our last surrogate
if ((encoder == null || encoder.MustFlush) && highSurrogate > 0)
{
// We have to do the fallback for the lonely high surrogate
charsForFallback = chars;
fallbackBuffer.InternalFallback(highSurrogate, ref charsForFallback);
chars = charsForFallback;
highSurrogate = (char)0;
goto TryAgain;
}
// Fix our encoder if we have one
Debug.Assert(highSurrogate == 0 || (encoder != null && !encoder.MustFlush),
"[UTF32Encoding.GetBytes]Expected encoder to be flushed.");
if (encoder != null)
{
// Remember our left over surrogate (or 0 if flushing)
encoder._charLeftOver = highSurrogate;
// Need # chars used
encoder._charsUsed = (int)(chars - charStart);
}
// return the new length
return (int)(bytes - byteStart);
}
internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder)
{
Debug.Assert(bytes != null, "[UTF32Encoding.GetCharCount]bytes!=null");
Debug.Assert(count >= 0, "[UTF32Encoding.GetCharCount]count >=0");
UTF32Decoder decoder = (UTF32Decoder)baseDecoder;
// None so far!
int charCount = 0;
byte* end = bytes + count;
byte* byteStart = bytes;
// Set up decoder
int readCount = 0;
uint iChar = 0;
// For fallback we may need a fallback buffer
DecoderFallbackBuffer fallbackBuffer = null;
// See if there's anything in our decoder
if (decoder != null)
{
readCount = decoder.readByteCount;
iChar = (uint)decoder.iChar;
fallbackBuffer = decoder.FallbackBuffer;
// Shouldn't have anything in fallback buffer for GetCharCount
// (don't have to check _throwOnOverflow for chars or count)
Debug.Assert(fallbackBuffer.Remaining == 0,
"[UTF32Encoding.GetCharCount]Expected empty fallback buffer at start");
}
else
{
fallbackBuffer = this.decoderFallback.CreateFallbackBuffer();
}
// Set our internal fallback interesting things.
fallbackBuffer.InternalInitialize(byteStart, null);
// Loop through our input, 4 characters at a time!
while (bytes < end && charCount >= 0)
{
// Get our next character
if (_bigEndian)
{
// Scoot left and add it to the bottom
iChar <<= 8;
iChar += *(bytes++);
}
else
{
// Scoot right and add it to the top
iChar >>= 8;
iChar += (uint)(*(bytes++)) << 24;
}
readCount++;
// See if we have all the bytes yet
if (readCount < 4)
continue;
// Have the bytes
readCount = 0;
// See if its valid to encode
if (iChar > 0x10FFFF || (iChar >= 0xD800 && iChar <= 0xDFFF))
{
// Need to fall back these 4 bytes
byte[] fallbackBytes;
if (_bigEndian)
{
fallbackBytes = new byte[] {
unchecked((byte)(iChar>>24)), unchecked((byte)(iChar>>16)),
unchecked((byte)(iChar>>8)), unchecked((byte)(iChar)) };
}
else
{
fallbackBytes = new byte[] {
unchecked((byte)(iChar)), unchecked((byte)(iChar>>8)),
unchecked((byte)(iChar>>16)), unchecked((byte)(iChar>>24)) };
}
charCount += fallbackBuffer.InternalFallback(fallbackBytes, bytes);
// Ignore the illegal character
iChar = 0;
continue;
}
// Ok, we have something we can add to our output
if (iChar >= 0x10000)
{
// Surrogates take 2
charCount++;
}
// Add the rest of the surrogate or our normal character
charCount++;
// iChar is back to 0
iChar = 0;
}
// See if we have something left over that has to be decoded
if (readCount > 0 && (decoder == null || decoder.MustFlush))
{
// Oops, there's something left over with no place to go.
byte[] fallbackBytes = new byte[readCount];
if (_bigEndian)
{
while (readCount > 0)
{
fallbackBytes[--readCount] = unchecked((byte)iChar);
iChar >>= 8;
}
}
else
{
while (readCount > 0)
{
fallbackBytes[--readCount] = unchecked((byte)(iChar >> 24));
iChar <<= 8;
}
}
charCount += fallbackBuffer.InternalFallback(fallbackBytes, bytes);
}
// Check for overflows.
if (charCount < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_GetByteCountOverflow);
// Shouldn't have anything in fallback buffer for GetCharCount
// (don't have to check _throwOnOverflow for chars or count)
Debug.Assert(fallbackBuffer.Remaining == 0,
"[UTF32Encoding.GetCharCount]Expected empty fallback buffer at end");
// Return our count
return charCount;
}
internal override unsafe int GetChars(byte* bytes, int byteCount,
char* chars, int charCount, DecoderNLS baseDecoder)
{
Debug.Assert(chars != null, "[UTF32Encoding.GetChars]chars!=null");
Debug.Assert(bytes != null, "[UTF32Encoding.GetChars]bytes!=null");
Debug.Assert(byteCount >= 0, "[UTF32Encoding.GetChars]byteCount >=0");
Debug.Assert(charCount >= 0, "[UTF32Encoding.GetChars]charCount >=0");
UTF32Decoder decoder = (UTF32Decoder)baseDecoder;
// None so far!
char* charStart = chars;
char* charEnd = chars + charCount;
byte* byteStart = bytes;
byte* byteEnd = bytes + byteCount;
// See if there's anything in our decoder (but don't clear it yet)
int readCount = 0;
uint iChar = 0;
// For fallback we may need a fallback buffer
DecoderFallbackBuffer fallbackBuffer = null;
char* charsForFallback;
// See if there's anything in our decoder
if (decoder != null)
{
readCount = decoder.readByteCount;
iChar = (uint)decoder.iChar;
fallbackBuffer = baseDecoder.FallbackBuffer;
// Shouldn't have anything in fallback buffer for GetChars
// (don't have to check _throwOnOverflow for chars)
Debug.Assert(fallbackBuffer.Remaining == 0,
"[UTF32Encoding.GetChars]Expected empty fallback buffer at start");
}
else
{
fallbackBuffer = this.decoderFallback.CreateFallbackBuffer();
}
// Set our internal fallback interesting things.
fallbackBuffer.InternalInitialize(bytes, chars + charCount);
// Loop through our input, 4 characters at a time!
while (bytes < byteEnd)
{
// Get our next character
if (_bigEndian)
{
// Scoot left and add it to the bottom
iChar <<= 8;
iChar += *(bytes++);
}
else
{
// Scoot right and add it to the top
iChar >>= 8;
iChar += (uint)(*(bytes++)) << 24;
}
readCount++;
// See if we have all the bytes yet
if (readCount < 4)
continue;
// Have the bytes
readCount = 0;
// See if its valid to encode
if (iChar > 0x10FFFF || (iChar >= 0xD800 && iChar <= 0xDFFF))
{
// Need to fall back these 4 bytes
byte[] fallbackBytes;
if (_bigEndian)
{
fallbackBytes = new byte[] {
unchecked((byte)(iChar>>24)), unchecked((byte)(iChar>>16)),
unchecked((byte)(iChar>>8)), unchecked((byte)(iChar)) };
}
else
{
fallbackBytes = new byte[] {
unchecked((byte)(iChar)), unchecked((byte)(iChar>>8)),
unchecked((byte)(iChar>>16)), unchecked((byte)(iChar>>24)) };
}
// Chars won't be updated unless this works.
charsForFallback = chars;
bool fallbackResult = fallbackBuffer.InternalFallback(fallbackBytes, bytes, ref charsForFallback);
chars = charsForFallback;
if (!fallbackResult)
{
// Couldn't fallback, throw or wait til next time
// We either read enough bytes for bytes-=4 to work, or we're
// going to throw in ThrowCharsOverflow because chars == charStart
Debug.Assert(bytes >= byteStart + 4 || chars == charStart,
"[UTF32Encoding.GetChars]Expected to have consumed bytes or throw (bad surrogate)");
bytes -= 4; // get back to where we were
iChar = 0; // Remembering nothing
fallbackBuffer.InternalReset();
ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output
break; // Stop here, didn't throw
}
// Ignore the illegal character
iChar = 0;
continue;
}
// Ok, we have something we can add to our output
if (iChar >= 0x10000)
{
// Surrogates take 2
if (chars >= charEnd - 1)
{
// Throwing or stopping
// We either read enough bytes for bytes-=4 to work, or we're
// going to throw in ThrowCharsOverflow because chars == charStart
Debug.Assert(bytes >= byteStart + 4 || chars == charStart,
"[UTF32Encoding.GetChars]Expected to have consumed bytes or throw (surrogate)");
bytes -= 4; // get back to where we were
iChar = 0; // Remembering nothing
ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output
break; // Stop here, didn't throw
}
*(chars++) = GetHighSurrogate(iChar);
iChar = GetLowSurrogate(iChar);
}
// Bounds check for normal character
else if (chars >= charEnd)
{
// Throwing or stopping
// We either read enough bytes for bytes-=4 to work, or we're
// going to throw in ThrowCharsOverflow because chars == charStart
Debug.Assert(bytes >= byteStart + 4 || chars == charStart,
"[UTF32Encoding.GetChars]Expected to have consumed bytes or throw (normal char)");
bytes -= 4; // get back to where we were
iChar = 0; // Remembering nothing
ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output
break; // Stop here, didn't throw
}
// Add the rest of the surrogate or our normal character
*(chars++) = (char)iChar;
// iChar is back to 0
iChar = 0;
}
// See if we have something left over that has to be decoded
if (readCount > 0 && (decoder == null || decoder.MustFlush))
{
// Oops, there's something left over with no place to go.
byte[] fallbackBytes = new byte[readCount];
int tempCount = readCount;
if (_bigEndian)
{
while (tempCount > 0)
{
fallbackBytes[--tempCount] = unchecked((byte)iChar);
iChar >>= 8;
}
}
else
{
while (tempCount > 0)
{
fallbackBytes[--tempCount] = unchecked((byte)(iChar >> 24));
iChar <<= 8;
}
}
charsForFallback = chars;
bool fallbackResult = fallbackBuffer.InternalFallback(fallbackBytes, bytes, ref charsForFallback);
chars = charsForFallback;
if (!fallbackResult)
{
// Couldn't fallback.
fallbackBuffer.InternalReset();
ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output
// Stop here, didn't throw, backed up, so still nothing in buffer
}
else
{
// Don't clear our decoder unless we could fall it back.
// If we caught the if above, then we're a convert() and will catch this next time.
readCount = 0;
iChar = 0;
}
}
// Remember any left over stuff, clearing buffer as well for MustFlush
if (decoder != null)
{
decoder.iChar = (int)iChar;
decoder.readByteCount = readCount;
decoder._bytesUsed = (int)(bytes - byteStart);
}
// Shouldn't have anything in fallback buffer for GetChars
// (don't have to check _throwOnOverflow for chars)
Debug.Assert(fallbackBuffer.Remaining == 0,
"[UTF32Encoding.GetChars]Expected empty fallback buffer at end");
// Return our count
return (int)(chars - charStart);
}
private uint GetSurrogate(char cHigh, char cLow)
{
return (((uint)cHigh - 0xD800) * 0x400) + ((uint)cLow - 0xDC00) + 0x10000;
}
private char GetHighSurrogate(uint iChar)
{
return (char)((iChar - 0x10000) / 0x400 + 0xD800);
}
private char GetLowSurrogate(uint iChar)
{
return (char)((iChar - 0x10000) % 0x400 + 0xDC00);
}
public override Decoder GetDecoder()
{
return new UTF32Decoder(this);
}
public override Encoder GetEncoder()
{
return new EncoderNLS(this);
}
public override int GetMaxByteCount(int charCount)
{
if (charCount < 0)
throw new ArgumentOutOfRangeException(nameof(charCount),
SR.ArgumentOutOfRange_NeedNonNegNum);
// Characters would be # of characters + 1 in case left over high surrogate is ? * max fallback
long byteCount = (long)charCount + 1;
if (EncoderFallback.MaxCharCount > 1)
byteCount *= EncoderFallback.MaxCharCount;
// 4 bytes per char
byteCount *= 4;
if (byteCount > 0x7fffffff)
throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_GetByteCountOverflow);
return (int)byteCount;
}
public override int GetMaxCharCount(int byteCount)
{
if (byteCount < 0)
throw new ArgumentOutOfRangeException(nameof(byteCount),
SR.ArgumentOutOfRange_NeedNonNegNum);
// A supplementary character becomes 2 surrogate characters, so 4 input bytes becomes 2 chars,
// plus we may have 1 surrogate char left over if the decoder has 3 bytes in it already for a non-bmp char.
// Have to add another one because 1/2 == 0, but 3 bytes left over could be 2 char surrogate pair
int charCount = (byteCount / 2) + 2;
// Also consider fallback because our input bytes could be out of range of unicode.
// Since fallback would fallback 4 bytes at a time, we'll only fall back 1/2 of MaxCharCount.
if (DecoderFallback.MaxCharCount > 2)
{
// Multiply time fallback size
charCount *= DecoderFallback.MaxCharCount;
// We were already figuring 2 chars per 4 bytes, but fallback will be different #
charCount /= 2;
}
if (charCount > 0x7fffffff)
throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ArgumentOutOfRange_GetCharCountOverflow);
return (int)charCount;
}
public override byte[] GetPreamble()
{
if (_emitUTF32ByteOrderMark)
{
// Allocate new array to prevent users from modifying it.
if (_bigEndian)
{
return new byte[4] { 0x00, 0x00, 0xFE, 0xFF };
}
else
{
return new byte[4] { 0xFF, 0xFE, 0x00, 0x00 }; // 00 00 FE FF
}
}
else
return Array.Empty<byte>();
}
public override ReadOnlySpan<byte> Preamble =>
GetType() != typeof(UTF32Encoding) ? GetPreamble() : // in case a derived UTF32Encoding overrode GetPreamble
_emitUTF32ByteOrderMark ? (_bigEndian ? s_bigEndianPreamble : s_littleEndianPreamble) :
Array.Empty<byte>();
public override bool Equals(Object value)
{
UTF32Encoding that = value as UTF32Encoding;
if (that != null)
{
return (_emitUTF32ByteOrderMark == that._emitUTF32ByteOrderMark) &&
(_bigEndian == that._bigEndian) &&
(EncoderFallback.Equals(that.EncoderFallback)) &&
(DecoderFallback.Equals(that.DecoderFallback));
}
return (false);
}
public override int GetHashCode()
{
//Not great distribution, but this is relatively unlikely to be used as the key in a hashtable.
return this.EncoderFallback.GetHashCode() + this.DecoderFallback.GetHashCode() +
CodePage + (_emitUTF32ByteOrderMark ? 4 : 0) + (_bigEndian ? 8 : 0);
}
private sealed class UTF32Decoder : DecoderNLS
{
// Need a place to store any extra bytes we may have picked up
internal int iChar = 0;
internal int readByteCount = 0;
public UTF32Decoder(UTF32Encoding encoding) : base(encoding)
{
// base calls reset
}
public override void Reset()
{
this.iChar = 0;
this.readByteCount = 0;
if (_fallbackBuffer != null)
_fallbackBuffer.Reset();
}
// Anything left in our decoder?
internal override bool HasState
{
get
{
// ReadByteCount is our flag. (iChar==0 doesn't mean much).
return (this.readByteCount != 0);
}
}
}
}
}
| |
/*
* Copyright (c) 2009 Jim Radford http://www.jimradford.com
* Copyright (c) 2012 John Peterson
* 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.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using log4net;
using System.Diagnostics;
using System.Web;
using System.Collections.Specialized;
using SuperPutty.Data;
using WeifenLuo.WinFormsUI.Docking;
using SuperPutty.Utils;
using System.Threading;
using System.Configuration;
using SuperPutty.Gui;
using log4net.Core;
namespace SuperPutty
{
public partial class ctlPuttyPanel : ToolWindowDocument
{
private static readonly ILog Log = LogManager.GetLogger(typeof(ctlPuttyPanel));
private static int RefocusAttempts = Convert.ToInt32(ConfigurationManager.AppSettings["SuperPuTTY.RefocusAttempts"] ?? "5");
private static int RefocusIntervalMs = Convert.ToInt32(ConfigurationManager.AppSettings["SuperPuTTY.RefocusIntervalMs"] ?? "80");
private PuttyStartInfo m_puttyStartInfo;
private ApplicationPanel m_AppPanel;
private SessionData m_Session;
private PuttyClosedCallback m_ApplicationExit;
public ctlPuttyPanel(SessionData session, PuttyClosedCallback callback)
{
m_Session = session;
m_ApplicationExit = callback;
m_puttyStartInfo = new PuttyStartInfo(session);
InitializeComponent();
this.Text = session.SessionName;
this.TabText = session.SessionName;
this.TextOverride = session.SessionName;
CreatePanel();
AdjustMenu();
}
public override string Text
{
get
{
return base.Text;
}
set
{
this.TabText = value != null ? value.Replace("&", "&&") : value;
base.Text = value;
if (Log.Logger.IsEnabledFor(Level.Trace))
{
Log.DebugFormat("SetText: text={0}", value);
}
}
}
protected override void OnTextChanged(EventArgs e)
{
base.OnTextChanged(e);
this.ToolTipText = this.Text;
}
private void CreatePanel()
{
this.m_AppPanel = new ApplicationPanel();
this.SuspendLayout();
this.m_AppPanel.Dock = System.Windows.Forms.DockStyle.Fill;
this.m_AppPanel.ApplicationName = this.m_puttyStartInfo.Executable;
this.m_AppPanel.ApplicationParameters = this.m_puttyStartInfo.Args;
this.m_AppPanel.ApplicationWorkingDirectory = this.m_puttyStartInfo.WorkingDir;
this.m_AppPanel.Location = new System.Drawing.Point(0, 0);
this.m_AppPanel.Name = this.m_Session.SessionId; // "applicationControl1";
this.m_AppPanel.Size = new System.Drawing.Size(this.Width, this.Height);
this.m_AppPanel.TabIndex = 0;
this.m_AppPanel.m_CloseCallback = this.m_ApplicationExit;
this.Controls.Add(this.m_AppPanel);
this.ResumeLayout();
}
void AdjustMenu()
{
// for mintty, disable the putty menu items
if (this.Session.Proto == ConnectionProtocol.Mintty)
{
this.toolStripPuttySep1.Visible = false;
this.eventLogToolStripMenuItem.Visible = false;
this.toolStripPuttySep2.Visible = false;
this.changeSettingsToolStripMenuItem.Visible = false;
this.copyAllToClipboardToolStripMenuItem.Visible = false;
this.restartSessionToolStripMenuItem.Visible = false;
this.clearScrollbackToolStripMenuItem.Visible = false;
this.resetTerminalToolStripMenuItem.Visible = false;
}
}
void CreateMenu()
{
this.newSessionToolStripMenuItem.Enabled = SuperPuTTY.Settings.PuttyPanelShowNewSessionMenu;
if (SuperPuTTY.Settings.PuttyPanelShowNewSessionMenu)
{
this.contextMenuStrip1.SuspendLayout();
// BBB: do i need to dispose each one?
newSessionToolStripMenuItem.DropDownItems.Clear();
foreach (SessionData session in SuperPuTTY.GetAllSessions())
{
ToolStripMenuItem tsmiParent = newSessionToolStripMenuItem;
foreach (string part in SessionData.GetSessionNameParts(session.SessionId))
{
if (part == session.SessionName)
{
ToolStripMenuItem newSessionTSMI = new ToolStripMenuItem();
newSessionTSMI.Tag = session;
newSessionTSMI.Text = session.SessionName;
newSessionTSMI.Click += new System.EventHandler(newSessionTSMI_Click);
newSessionTSMI.ToolTipText = session.ToString();
tsmiParent.DropDownItems.Add(newSessionTSMI);
}
else
{
if (tsmiParent.DropDownItems.ContainsKey(part))
{
tsmiParent = (ToolStripMenuItem)tsmiParent.DropDownItems[part];
}
else
{
ToolStripMenuItem newSessionFolder = new ToolStripMenuItem(part);
newSessionFolder.Name = part;
tsmiParent.DropDownItems.Add(newSessionFolder);
tsmiParent = newSessionFolder;
}
}
}
}
this.contextMenuStrip1.ResumeLayout();
}
DockPane pane = GetDockPane();
if (pane != null)
{
this.closeOthersToTheRightToolStripMenuItem.Enabled =
pane.Contents.IndexOf(this) != pane.Contents.Count - 1;
}
this.closeOthersToolStripMenuItem.Enabled = this.DockPanel.DocumentsCount > 1;
this.closeAllToolStripMenuItem.Enabled = this.DockPanel.DocumentsCount > 1;
}
private void closeSessionToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void closeOthersToolStripMenuItem_Click(object sender, EventArgs e)
{
var docs = from doc in this.DockPanel.DocumentsToArray()
where doc is ToolWindowDocument && doc != this
select doc as ToolWindowDocument;
CloseDocs("Close Others", docs);
}
private void closeAllToolStripMenuItem_Click(object sender, EventArgs e)
{
var docs = from doc in this.DockPanel.DocumentsToArray()
where doc is ToolWindowDocument
select doc as ToolWindowDocument;
CloseDocs("Close All", docs);
}
private void closeOthersToTheRightToolStripMenuItem_Click(object sender, EventArgs e)
{
// find the dock pane with this window
DockPane pane = GetDockPane();
if (pane != null)
{
// found the pane
List<ToolWindowDocument> docsToClose = new List<ToolWindowDocument>();
bool close = false;
foreach (IDockContent content in new List<IDockContent>(pane.Contents))
{
if (content == this)
{
close = true;
continue;
}
if (close)
{
ToolWindowDocument win = content as ToolWindowDocument;
if (win != null)
{
docsToClose.Add(win);
}
}
}
if (docsToClose.Count > 0)
{
CloseDocs("Close Other To the Right", docsToClose);
}
}
}
void CloseDocs(string source, IEnumerable<ToolWindowDocument> docsToClose)
{
int n = docsToClose.Count();
Log.InfoFormat("Closing mulitple docs: source={0}, count={1}, conf={2}", source, n, SuperPuTTY.Settings.MultipleTabCloseConfirmation);
bool okToClose = true;
if (SuperPuTTY.Settings.MultipleTabCloseConfirmation && n > 1)
{
okToClose = DialogResult.Yes == MessageBox.Show(this, string.Format("Close {0} Tabs?", n), source, MessageBoxButtons.YesNo);
}
if (okToClose)
{
foreach (ToolWindowDocument doc in docsToClose)
{
doc.Close();
}
}
}
DockPane GetDockPane()
{
foreach (DockPane pane in this.DockPanel.Panes)
{
if (pane.Contents.Contains(this))
{
return pane;
}
}
return null;
}
/// <summary>
/// Reset the focus to the child application window
/// </summary>
internal void SetFocusToChildApplication(string caller)
{
if (!this.m_AppPanel.ExternalProcessCaptured) { return; }
bool success = false;
for (int i = 0; i < RefocusAttempts; i++)
{
Thread.Sleep(RefocusIntervalMs);
if (this.m_AppPanel.ReFocusPuTTY(caller))
{
if (i > 0)
{
Log.DebugFormat("SetFocusToChildApplication success after {0} attempts", i + 1);
}
success = true;
break;
}
}
if (!success)
{
Log.WarnFormat("Unable to SetFocusToChildApplication, {0}", this.Text);
}
}
protected override string GetPersistString()
{
string str = String.Format("{0}?SessionId={1}&TabName={2}",
this.GetType().FullName,
HttpUtility.UrlEncodeUnicode(this.m_Session.SessionId),
HttpUtility.UrlEncodeUnicode(this.TextOverride));
return str;
}
public static ctlPuttyPanel FromPersistString(String persistString)
{
ctlPuttyPanel panel = null;
if (persistString.StartsWith(typeof(ctlPuttyPanel).FullName))
{
int idx = persistString.IndexOf("?");
if (idx != -1)
{
NameValueCollection data = HttpUtility.ParseQueryString(persistString.Substring(idx + 1));
string sessionId = data["SessionId"] ?? data["SessionName"];
string tabName = data["TabName"];
Log.InfoFormat("Restoring putty session, sessionId={0}, tabName={1}", sessionId, tabName);
SessionData session = SuperPuTTY.GetSessionById(sessionId);
if (session != null)
{
panel = ctlPuttyPanel.NewPanel(session);
if (panel == null)
{
Log.WarnFormat("Could not restore putty session, sessionId={0}", sessionId);
}
else
{
panel.Icon = SuperPuTTY.GetIconForSession(session);
panel.Text = tabName;
panel.TextOverride = tabName;
}
}
else
{
Log.WarnFormat("Session not found, sessionId={0}", sessionId);
}
}
else
{
idx = persistString.IndexOf(":");
if (idx != -1)
{
string sessionId = persistString.Substring(idx + 1);
Log.InfoFormat("Restoring putty session, sessionId={0}", sessionId);
SessionData session = SuperPuTTY.GetSessionById(sessionId);
if (session != null)
{
panel = ctlPuttyPanel.NewPanel(session);
}
else
{
Log.WarnFormat("Session not found, sessionId={0}", sessionId);
}
}
}
}
return panel;
}
private void aboutPuttyToolStripMenuItem_Click(object sender, EventArgs e)
{
Process.Start("http://www.chiark.greenend.org.uk/~sgtatham/putty/");
}
private void duplicateSessionToolStripMenuItem_Click(object sender, EventArgs e)
{
SuperPuTTY.OpenPuttySession(this.m_Session);
}
private void renameTabToolStripMenuItem_Click(object sender, EventArgs e)
{
dlgRenameItem dialog = new dlgRenameItem();
dialog.ItemName = this.Text;
dialog.DetailName = this.m_Session.SessionId;
if (dialog.ShowDialog(this) == DialogResult.OK)
{
this.Text = dialog.ItemName;
this.TextOverride = dialog.ItemName;
}
}
private void refreshToolStripMenuItem_Click(object sender, EventArgs e)
{
if (this.m_AppPanel != null)
{
this.m_AppPanel.RefreshAppWindow();
}
}
public SessionData Session { get { return this.m_Session; } }
public ApplicationPanel AppPanel { get { return this.m_AppPanel; } }
public ctlPuttyPanel previousPanel { get; set; }
public ctlPuttyPanel nextPanel { get; set; }
public static ctlPuttyPanel NewPanel(SessionData sessionData)
{
ctlPuttyPanel puttyPanel = null;
// This is the callback fired when the panel containing the terminal is closed
// We use this to save the last docking location
PuttyClosedCallback callback = delegate(bool closed)
{
if (puttyPanel != null)
{
// save the last dockstate (if it has been changed)
if (sessionData.LastDockstate != puttyPanel.DockState
&& puttyPanel.DockState != DockState.Unknown
&& puttyPanel.DockState != DockState.Hidden)
{
sessionData.LastDockstate = puttyPanel.DockState;
SuperPuTTY.SaveSessions();
//sessionData.SaveToRegistry();
}
if (puttyPanel.InvokeRequired)
{
puttyPanel.BeginInvoke((MethodInvoker)delegate()
{
puttyPanel.Close();
});
}
else
{
puttyPanel.Close();
}
}
};
puttyPanel = new ctlPuttyPanel(sessionData, callback);
return puttyPanel;
}
private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
{
CreateMenu();
}
private void newSessionTSMI_Click(object sender, EventArgs e)
{
ToolStripMenuItem menuItem = (ToolStripMenuItem) sender;
SessionData session = menuItem.Tag as SessionData;
if (session != null)
{
SuperPuTTY.OpenPuttySession(session);
}
}
private void puTTYMenuTSMI_Click(object sender, EventArgs e)
{
ToolStripMenuItem menuItem = (ToolStripMenuItem) sender;
string tag = ((ToolStripMenuItem)sender).Tag.ToString();
uint command = Convert.ToUInt32(tag, 16);
Log.DebugFormat("Sending Putty Command: menu={2}, tag={0}, command={1}", tag, command, menuItem.Text);
ThreadPool.QueueUserWorkItem(delegate
{
try
{
this.SetFocusToChildApplication("MenuHandler");
NativeMethods.SendMessage(m_AppPanel.AppWindowHandle, (uint)NativeMethods.WM.SYSCOMMAND, command, 0);
}
catch (Exception ex)
{
Log.ErrorFormat("Error sending command menu command to embedded putty", ex);
}
});
//SuperPuTTY.MainForm.BringToFront();
}
public bool AcceptCommands
{
get { return this.acceptCommandsToolStripMenuItem.Checked; }
set { this.acceptCommandsToolStripMenuItem.Checked = value; }
}
public string TextOverride { get; set; }
}
}
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using ESRI.ArcGIS;
using ESRI.ArcGIS.ADF.CATIDs;
using ESRI.ArcGIS.Schematic;
using ESRI.ArcGIS.Framework;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.esriSystem;
using System;
using System.Runtime.InteropServices;
using System.Collections.Generic;
namespace CustomRulesCS
{
[ClassInterface(ClassInterfaceType.None)]
[Guid(NodeReductionRule.GUID)]
[ProgId(NodeReductionRule.PROGID)]
public class NodeReductionRule : ISchematicRule, ISchematicRuleDesign
{
public const string GUID = "A6CB9935-AE08-46FB-9850-77C2B4E7C6A9";
public const string PROGID = "CustomRulesCS.NodeReductionRule";
// Register/unregister categories for this class
#region "Component Category Registration"
[System.Runtime.InteropServices.ComRegisterFunction()]
public static void Register(string CLSID)
{
SchematicRules.Register(CLSID);
}
[System.Runtime.InteropServices.ComUnregisterFunction()]
public static void Unregister(string CLSID)
{
SchematicRules.Unregister(CLSID);
}
#endregion
private ISchematicDiagramClass m_diagramClass;
private string m_description = "Reduction Node Rule - Report cumulative value C#";
private string m_lengthAttributeName;
private string m_reducedNodeClassName;
private string m_superspanLinkClassName;
private string m_linkAttributeName;
private bool m_keepVertices = true;
private bool m_linkAttribute = false;
#region NodeReductionRule interface
public NodeReductionRule()
{
}
~NodeReductionRule()
{
m_diagramClass = null;
}
public bool LinkAttribute
{
get
{
return m_linkAttribute;
}
set
{
m_linkAttribute = value;
}
}
public string LinkAttributeName
{
get
{
return m_linkAttributeName;
}
set
{
m_linkAttributeName = value;
}
}
public bool KeepVertices
{
get
{
return m_keepVertices;
}
set
{
m_keepVertices = value;
}
}
public string LengthAttributeName
{
get
{
return m_lengthAttributeName;
}
set
{
m_lengthAttributeName = value;
}
}
public string ReducedNodeClassName
{
get
{
return m_reducedNodeClassName;
}
set
{
m_reducedNodeClassName = value;
}
}
public string SuperpanLinkClassName
{
get
{
return m_superspanLinkClassName;
}
set
{
m_superspanLinkClassName = value;
}
}
#endregion
#region ISchematicRule Members
public void Alter(ISchematicDiagramClass schematicDiagramClass, ESRI.ArcGIS.esriSystem.IPropertySet propertySet)
{
m_diagramClass = schematicDiagramClass;
try
{
m_description = propertySet.GetProperty("DESCRIPTION").ToString();
}
catch { }
try
{
m_reducedNodeClassName = propertySet.GetProperty("REDUCEDNODECLASS").ToString();
}
catch { }
try
{
m_superspanLinkClassName = propertySet.GetProperty("SUPERSPANLINKCLASS").ToString();
}
catch { }
try
{
m_lengthAttributeName = propertySet.GetProperty("LENGTHATTRIBUTENAME").ToString();
}
catch { }
try
{
m_keepVertices = (bool)propertySet.GetProperty("KEEPVERTICES");
}
catch { }
try
{
m_linkAttribute = (bool)propertySet.GetProperty("LINKATTRIBUTE");
}
catch { }
try
{
m_linkAttributeName = propertySet.GetProperty("LINKATTRIBUTENAME").ToString();
}
catch { }
}
public void Apply(ISchematicInMemoryDiagram inMemoryDiagram, ESRI.ArcGIS.esriSystem.ITrackCancel cancelTracker)
{
if (m_reducedNodeClassName == "" || inMemoryDiagram == null) return;
// initialize the schematic rules helper
ISchematicRulesHelper rulesHelper = new SchematicRulesHelperClass();
rulesHelper.InitHelper(inMemoryDiagram);
rulesHelper.KeepVertices = m_keepVertices;
////////////////////////
// get the feature classes processed by the rule
ISchematicDiagramClass diagramClass = null;
try
{
diagramClass = inMemoryDiagram.SchematicDiagramClass;
}
catch { }
if (diagramClass == null) return;
ISchematicDataset schematicDataset = null;
try
{
schematicDataset = diagramClass.SchematicDataset;
}
catch { }
ISchematicElementClassContainer elementclassContainer = (ISchematicElementClassContainer)schematicDataset;
if (elementclassContainer == null) return;
ISchematicElementClass elementClassReducedNode = null;
elementClassReducedNode = elementclassContainer.GetSchematicElementClass(m_reducedNodeClassName);
ISchematicElementClass elementClassSuperspan = null;
elementClassSuperspan = elementclassContainer.GetSchematicElementClass(m_superspanLinkClassName);
if (elementClassSuperspan == null || elementClassReducedNode == null) return;
ISchematicInMemoryFeatureClassContainer featureClassContainer = (ISchematicInMemoryFeatureClassContainer)inMemoryDiagram;
if (featureClassContainer == null) return;
ISchematicInMemoryFeatureClass superspanLinkClass = featureClassContainer.GetSchematicInMemoryFeatureClass(elementClassSuperspan);
//
/////////////////////////
// fetch the superspan spatial reference
IGeoDataset geoDataset = (IGeoDataset)superspanLinkClass;
ISpatialReference spatialRef = null;
if (geoDataset != null) spatialRef = geoDataset.SpatialReference;
if (spatialRef == null) return;
// Retrieve the schematic in memory feature nodes to reduce
System.Collections.Generic.Dictionary<string, ISchematicInMemoryFeature> colSchfeatureNode = new Dictionary<string, ISchematicInMemoryFeature>();
// get all feature of parent node class
IEnumSchematicInMemoryFeature enumSchematicInMemoryFeature = inMemoryDiagram.GetSchematicInMemoryFeaturesByClass(elementClassReducedNode);
// retain only the nodes of degree two
RetainNodesDegreeTwo(enumSchematicInMemoryFeature, colSchfeatureNode, rulesHelper); // there would be inserted a SQL query to also filter by attributes
IProgressor msgProgressor = null;
if (cancelTracker != null)
{
msgProgressor = cancelTracker.Progressor;
IStepProgressor stepProgressor = (IStepProgressor)msgProgressor;
if (stepProgressor != null)
{
stepProgressor.MinRange = 0;
stepProgressor.MaxRange = colSchfeatureNode.Count;
stepProgressor.StepValue = 1;
stepProgressor.Position = 0;
stepProgressor.Message = m_description;
cancelTracker.Reset();
cancelTracker.Progressor = msgProgressor;
stepProgressor.Show();
}
}
ISchematicInMemoryFeature schFeatureToReduce;
foreach (KeyValuePair<string, ISchematicInMemoryFeature> kvp in colSchfeatureNode)
{
if (cancelTracker != null)
if (cancelTracker.Continue() == false)
break;
schFeatureToReduce = colSchfeatureNode[kvp.Key];
if (schFeatureToReduce != null) ReduceNode(rulesHelper, superspanLinkClass, spatialRef, schFeatureToReduce);
}
// release memory
colSchfeatureNode.Clear();
colSchfeatureNode = null;
rulesHelper = null;
}
public ESRI.ArcGIS.esriSystem.UID ClassID
{
get
{
ESRI.ArcGIS.esriSystem.UID ruleID = new ESRI.ArcGIS.esriSystem.UID();
ruleID.Value = PROGID;
return ruleID;
}
}
public string Description
{
get
{
return m_description;
}
set
{
m_description = value;
}
}
string ISchematicRule.Description
{
get { return m_description; }
}
public string Name
{
get
{
return "Node Reduction Rule C#";
}
}
public ESRI.ArcGIS.esriSystem.IPropertySet PropertySet
{
get
{
ESRI.ArcGIS.esriSystem.IPropertySet propertySet = new ESRI.ArcGIS.esriSystem.PropertySet();
propertySet.SetProperty("DESCRIPTION", m_description);
propertySet.SetProperty("REDUCEDNODECLASS", m_reducedNodeClassName);
propertySet.SetProperty("SUPERSPANLINKCLASS", m_superspanLinkClassName);
propertySet.SetProperty("KEEPVERTICES", m_keepVertices);
propertySet.SetProperty("LENGTHATTRIBUTENAME", m_lengthAttributeName);
propertySet.SetProperty("LINKATTRIBUTE", m_linkAttribute);
propertySet.SetProperty("LINKATTRIBUTENAME", m_linkAttributeName);
return propertySet;
}
}
ISchematicDiagramClass ISchematicRule.SchematicDiagramClass
{
get { return m_diagramClass; }
}
#endregion
#region ISchematicRuleDesign Members
public void Detach()
{
m_diagramClass = null;
}
ESRI.ArcGIS.esriSystem.IPropertySet ISchematicRuleDesign.PropertySet
{
set
{
m_description = value.GetProperty("DESCRIPTION").ToString();
m_reducedNodeClassName = value.GetProperty("REDUCEDNODECLASS").ToString();
m_superspanLinkClassName = value.GetProperty("SUPERSPANLINKCLASS").ToString();
m_keepVertices = (bool)value.GetProperty("KEEPVERTICES");
m_lengthAttributeName = value.GetProperty("LENGTHATTRIBUTENAME").ToString();
m_linkAttribute = (bool)value.GetProperty("LINKATTRIBUTE");
m_linkAttributeName = value.GetProperty("LINKATTRIBUTENAME").ToString();
}
}
ISchematicDiagramClass ISchematicRuleDesign.SchematicDiagramClass
{
get
{
return m_diagramClass;
}
set
{
m_diagramClass = value;
}
}
#endregion ISchematicRuleDesign
#region private methods
private void ReduceNode(ISchematicRulesHelper rulesHelper, ISchematicInMemoryFeatureClass superspanLinkClass , ISpatialReference spatialRef, ISchematicInMemoryFeature schFeatureToReduce)
{
if (schFeatureToReduce.Displayed == false || rulesHelper == null || spatialRef == null)
return;
// get the two connected links
IEnumSchematicInMemoryFeature enumLink = rulesHelper.GetDisplayedIncidentLinks((ISchematicInMemoryFeatureNode)schFeatureToReduce, esriSchematicEndPointType.esriSchematicOriginOrExtremityNode);
if (enumLink == null || enumLink.Count != 2)
return;
enumLink.Reset();
ISchematicInMemoryFeature schFeat1 = enumLink.Next();
ISchematicInMemoryFeature schFeat2 = enumLink.Next();
ISchematicInMemoryFeatureLink schLink1 = (ISchematicInMemoryFeatureLink)schFeat1;
ISchematicInMemoryFeatureLink schLink2 = (ISchematicInMemoryFeatureLink)schFeat2;
if (schLink1 == null || schLink2 == null) return;
ISchematicInMemoryFeature schFeatureSuperspan = null;
ISchematicInMemoryFeature schFeatureTmp = null;
ISchematicInMemoryFeatureNode schNodeToReduce = (ISchematicInMemoryFeatureNode)schFeatureToReduce;
ISchematicInMemoryFeatureNode schFromNode;
ISchematicInMemoryFeatureNode schToNode;
int iFromPort;
int iToPort;
IGeometry superspanGeometry;
if (schLink2.FromNode == schNodeToReduce)
{
superspanGeometry = BuildLinkGeometry(schLink1, schNodeToReduce, schLink2, rulesHelper);
if (schLink1.ToNode == schNodeToReduce)
{
schFromNode = schLink1.FromNode;
iFromPort = schLink1.FromPort;
}
else
{
schFromNode = schLink1.ToNode;
iFromPort = schLink1.ToPort;
}
schToNode = schLink2.ToNode;
iToPort = schLink2.ToPort;
}
else
{
superspanGeometry = BuildLinkGeometry(schLink2, schNodeToReduce, schLink1, rulesHelper);
schFromNode = schLink2.FromNode;
iFromPort = schLink2.FromPort;
if (schLink1.FromNode == schNodeToReduce)
{
schToNode = schLink1.ToNode;
iToPort = schLink1.ToPort;
}
else
{
schToNode = schLink1.FromNode;
iToPort = schLink1.FromPort;
}
}
if (superspanGeometry != null)
superspanGeometry.SpatialReference = spatialRef;
// find a unique name for the superspan
string strFromName = schFromNode.Name;
string strtoName = schToNode.Name;
string strName;
long lCount = 1;
while (schFeatureSuperspan == null)
{
strName = strFromName + ";" + strtoName + ";" + lCount.ToString();
if (strName.Length >= 128)
break; // too long a name
try
{
schFeatureTmp = rulesHelper.AlterLink(superspanLinkClass, strName, null, superspanGeometry, -2, -2,
strFromName, strtoName, esriFlowDirection.esriFDWithFlow, iFromPort, iToPort);
}
catch
{
schFeatureTmp = null;
}
if (schFeatureTmp == null)
continue;
// valid new feature
schFeatureSuperspan = schFeatureTmp;
}
// last chance for a unique name
lCount = 1;
while (schFeatureSuperspan == null)
{
strName = schNodeToReduce.Name + ";" + lCount.ToString();
if (strName.Length >= 128)
break; // too long a name
try
{
schFeatureTmp = rulesHelper.AlterLink(superspanLinkClass, strName, null, superspanGeometry, -2, -2,
strFromName, strtoName, esriFlowDirection.esriFDWithFlow, iFromPort, iToPort);
}
catch
{
schFeatureTmp = null;
}
if (schFeatureTmp == null)
continue;
// valid new feature
schFeatureSuperspan = schFeatureTmp;
}
if (schFeatureSuperspan == null)
return; // cannot find a unique name
// otherwise report the cumulated length of the reduced links to the superspan
ReportCumulativeValues(schFeat1, schFeat2, schFeatureSuperspan);
// report the associations on the superspan link
rulesHelper.ReportAssociations(schFeatureToReduce, schFeatureSuperspan);
rulesHelper.ReportAssociations(schFeat1, schFeatureSuperspan);
rulesHelper.ReportAssociations(schFeat2, schFeatureSuperspan);
// hide the reduced objects
rulesHelper.HideFeature(schFeatureToReduce);
rulesHelper.HideFeature(schFeat1);
rulesHelper.HideFeature(schFeat2);
}
private void ReportCumulativeValues(ISchematicInMemoryFeature schFeat1, ISchematicInMemoryFeature schFeat2, ISchematicInMemoryFeature schTargetFeat)
{
if (schFeat1 == null || schFeat2 == null || schTargetFeat == null)
return;
// assume the attribute field name is the same on every schematic feature link classes
IFields linkFields = schFeat1.Fields;
int iIndex = linkFields.FindField(m_lengthAttributeName);
if (iIndex < 0) return; // attribute field does not exist
object value1 = schFeat1.get_Value(iIndex);
linkFields = schFeat2.Fields;
iIndex = linkFields.FindField(m_lengthAttributeName);
if (iIndex < 0) return; // attribute field does not exist
object value2 = schFeat2.get_Value(iIndex);
double dValue1 = 0;
double dValue2 = 0;
if (!DBNull.Value.Equals(value1))
{
try
{
dValue1 = Convert.ToDouble(value1);
}
catch { }
}
if (!DBNull.Value.Equals(value2))
{
try
{
dValue2 = Convert.ToDouble(value2);
}
catch{ }
}
// assume the values to be numeric
double dlength = dValue1 + dValue2;
linkFields = schTargetFeat.Fields;
iIndex = linkFields.FindField(m_lengthAttributeName);
if (iIndex < 0) return; // attribute field does not exist
schTargetFeat.set_Value(iIndex, dlength);
}
private IGeometry BuildLinkGeometry(ISchematicInMemoryFeatureLink schLink1, ISchematicInMemoryFeatureNode schNodeToReduce, ISchematicInMemoryFeatureLink schLink2, ISchematicRulesHelper rulesHelper)
{
if (schLink1 == null || schLink2 == null || schNodeToReduce == null || rulesHelper == null)
return null;
if (m_keepVertices == false)
return null; // no geometry
Polyline newPoly = new Polyline();
IPolyline polyLink1 = rulesHelper.GetLinkPoints(schLink1, (schLink1.FromNode == schNodeToReduce));
IPolyline polyLink2 = rulesHelper.GetLinkPoints(schLink2, (schLink2.ToNode == schNodeToReduce));
IPoint nodePt = rulesHelper.GetNodePoint(schNodeToReduce);
IPoint Pt;
IPointCollection newPts = (IPointCollection)newPoly;
IPointCollection link1Pts = (IPointCollection)polyLink1;
IPointCollection link2Pts = (IPointCollection)polyLink2;
int Count = link1Pts.PointCount;
int i;
for (i = 0; i < Count - 1; i++)
{
Pt = link1Pts.get_Point(i);
newPts.AddPoint(Pt);
}
newPts.AddPoint(nodePt);
Count = link2Pts.PointCount;
for (i = 1; i < Count; i++)
{
Pt = link2Pts.get_Point(i);
newPts.AddPoint(Pt);
}
IGeometry buildGeometry = (IGeometry)newPoly;
return buildGeometry;
}
private void RetainNodesDegreeTwo(IEnumSchematicInMemoryFeature enumInMemoryFeature,
Dictionary<string, ISchematicInMemoryFeature> colSchfeatureNode, ISchematicRulesHelper ruleHelper)
{
ISchematicInMemoryFeature schInMemoryfeature;
if (ruleHelper == null) return;
enumInMemoryFeature.Reset();
schInMemoryfeature = enumInMemoryFeature.Next();
while (schInMemoryfeature != null)
{
if (schInMemoryfeature.Displayed)
{
IEnumSchematicInMemoryFeature enumLinks = ruleHelper.GetDisplayedIncidentLinks((ISchematicInMemoryFeatureNode)schInMemoryfeature, esriSchematicEndPointType.esriSchematicOriginOrExtremityNode);
if (enumLinks != null && enumLinks.Count == 2)
{
// Valid degree two node
if (!colSchfeatureNode.ContainsKey(schInMemoryfeature.Name))
{
if (!LinkAttribute)
colSchfeatureNode.Add(schInMemoryfeature.Name, schInMemoryfeature);
else
{
if(SameIncidentLinkAttributeValue(enumLinks, LinkAttributeName, ruleHelper))
colSchfeatureNode.Add(schInMemoryfeature.Name, schInMemoryfeature);
}
}
}
}
schInMemoryfeature = enumInMemoryFeature.Next();
}
}
private bool SameIncidentLinkAttributeValue(IEnumSchematicInMemoryFeature enumInMemoryLinks, string attributeName, ISchematicRulesHelper ruleHelper)
{
ISchematicInMemoryFeature inMemoryFeature = null;
enumInMemoryLinks.Reset();
bool bFirstVariant = true;
object vPreviousValue = null;
object vCurrentValue = null;
inMemoryFeature = enumInMemoryLinks.Next();
while (inMemoryFeature != null)
{
// Do not take account the link if the link is not displayed
//
// Search for an attribute with the given name
//
ISchematicElementClass schematicElementClass;
schematicElementClass = inMemoryFeature.SchematicElementClass;
ISchematicAttributeContainer attributeContainer = (ISchematicAttributeContainer)schematicElementClass;
ISchematicAttribute schematicAttribute = null;
if (attributeContainer != null)
schematicAttribute = attributeContainer.GetSchematicAttribute(attributeName, true);
if (schematicAttribute != null)
{
ISchematicObject schematicObject = (ISchematicObject)inMemoryFeature;
vCurrentValue = schematicAttribute.GetValue(schematicObject);
}
else
{
// If schematic attribute not existing ==> find a field in the associated feature
IObject iObject = null;
ISchematicInMemoryFeaturePrimaryAssociation primaryAssociation = (ISchematicInMemoryFeaturePrimaryAssociation)inMemoryFeature;
if (primaryAssociation != null)
iObject = primaryAssociation.AssociatedObject;
IRow row = (IRow)iObject;
int fieldIndex = 0;
if (row != null)
{
IFields fields = row.Fields;
if (fields != null)
fieldIndex = fields.FindField(attributeName);
}
if (fieldIndex > 0)
{
vCurrentValue = row.get_Value(fieldIndex);
if (DBNull.Value.Equals(vCurrentValue))
return false;
}
else
return false;
}
if (bFirstVariant)
{
vPreviousValue = vCurrentValue;
bFirstVariant = false;
}
else
{
// Compare PreviousValue and CurrentValue
if (vPreviousValue.GetType() != vCurrentValue.GetType())
return false;
if (DBNull.Value.Equals(vPreviousValue) || DBNull.Value.Equals(vCurrentValue))
return false;
if (vPreviousValue.GetType().FullName is System.String)//Speciale Case for string.
{
string str1 = (string)vPreviousValue;
string str2 = (string)vCurrentValue;
if( string.Compare(str1, str2, true) != 0)
return false;
}
else if (vPreviousValue != vCurrentValue)// == or != operator compare for Variant match the right type.
return false;
}
inMemoryFeature = enumInMemoryLinks.Next();
}
return true;
}
}
#endregion
}
| |
namespace AmbientHue.ViewModel
{
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using Q42.HueApi;
using Q42.HueApi.Interfaces;
using Q42.HueApi.NET;
using Color = System.Drawing.Color;
public class ConfigurationViewModel : ViewModelBase, IConfigurationViewModel
{
private readonly IHueConfiguration hueConfiguration;
private readonly ObservableCollection<string> bridges = new ObservableCollection<string>();
public ObservableCollection<string> Bridges => this.bridges;
private string selectedBridge;
public string SelectedBridge
{
get
{
return this.selectedBridge;
}
set
{
this.hueConfiguration.IP = value;
this.selectedBridge = value;
this.AppKey = null;
this.Lights.Clear();
this.SelectedLight = null;
this.RaisePropertyChanged(() => this.SelectedBridge);
this.RegisterCommand.RaiseCanExecuteChanged();
}
}
private string appKey;
public string AppKey
{
get
{
return this.appKey;
}
set
{
this.hueConfiguration.AppKey = value;
this.appKey = value;
this.RaisePropertyChanged(() => this.AppKey);
this.RegisterCommand.RaiseCanExecuteChanged();
}
}
private readonly ObservableCollection<string> lights = new ObservableCollection<string>();
public ObservableCollection<string> Lights => this.lights;
private string selectedLight;
public string SelectedLight
{
get
{
return this.selectedLight;
}
set
{
this.hueConfiguration.LightName = value;
this.selectedLight = value;
this.RaisePropertyChanged(() => this.SelectedLight);
}
}
private readonly ObservableCollection<string> captureMethods = new ObservableCollection<string>();
public ObservableCollection<string> CaptureMethods => this.captureMethods;
private string selectedCaptureMethod;
public string SelectedCaptureMethod
{
get
{
return this.selectedCaptureMethod;
}
set
{
this.hueConfiguration.CaptureMethod = (CaptureMethod)Enum.Parse(typeof(CaptureMethod), value);
this.selectedCaptureMethod = value;
this.RaisePropertyChanged(() => this.SelectedCaptureMethod);
}
}
private SolidColorBrush background = new SolidColorBrush();
public SolidColorBrush Background
{
get
{
return this.background;
}
set
{
this.background = value;
this.RaisePropertyChanged(() => this.Background);
}
}
private Task locateTask;
public ConfigurationViewModel(IHueConfiguration hueConfiguration)
{
this.hueConfiguration = hueConfiguration;
var defaultBridge = this.hueConfiguration.IP;
if (this.bridges.Contains(defaultBridge) == false)
{
this.bridges.Add(defaultBridge);
}
this.selectedBridge = defaultBridge;
this.appKey = this.hueConfiguration.AppKey;
this.LoadLights();
var defaultLightName = this.hueConfiguration.LightName;
if (this.lights.Contains(defaultLightName) == false)
{
this.lights.Add(defaultLightName);
}
this.selectedLight = defaultLightName;
this.LocateCommand = new RelayCommand(
() =>
{
this.bridges.Clear();
var uiContext = TaskScheduler.FromCurrentSynchronizationContext();
this.locateTask = new Task(
async () =>
{
IBridgeLocator locator = new SSDPBridgeLocator();
var newBridges = (await locator.LocateBridgesAsync(TimeSpan.FromSeconds(1))).ToList();
await Task.Factory.StartNew(() =>
{
newBridges.ForEach(bridge => this.bridges.Add(bridge));
if (this.bridges.Contains(this.SelectedBridge) == false)
{
this.SelectedBridge = this.bridges.Count > 0 ? this.bridges[0] : null;
}
this.locateTask = null;
this.LocateCommand.RaiseCanExecuteChanged();
}, CancellationToken.None, TaskCreationOptions.None, uiContext);
});
this.locateTask.Start();
this.LocateCommand.RaiseCanExecuteChanged();
}, () => this.locateTask == null);
this.RegisterCommand = new RelayCommand(
async () =>
{
try
{
this.ShowRegisterMessage = Visibility.Visible;
int nrOfTries = 1;
while (nrOfTries < 30)
{
try
{
ILocalHueClient client = new LocalHueClient(this.selectedBridge);
this.AppKey = await client.RegisterAsync("AmbientHue", "v0.1");
break;
}
catch (Exception)
{
nrOfTries++;
Thread.Sleep(500);
}
}
}
finally
{
this.ShowRegisterMessage = Visibility.Hidden;
}
this.LoadLights();
},
() => string.IsNullOrEmpty(this.selectedBridge) == false && string.IsNullOrEmpty(this.appKey));
Enum.GetNames(typeof(CaptureMethod))
.ToList().ForEach(cm => this.captureMethods.Add(cm));
this.selectedCaptureMethod = this.hueConfiguration.CaptureMethod.ToString();
this.Color = Color.Blue;
}
public RelayCommand LocateCommand
{
get; set;
}
public RelayCommand RegisterCommand { get; set; }
public Color Color
{
set
{
this.Background = new SolidColorBrush(System.Windows.Media.Color.FromRgb(value.R, value.G, value.B));
}
}
public ICommand HideWindowCommand
{
get
{
return new GalaSoft.MvvmLight.CommandWpf.RelayCommand(
() =>
{
Application.Current.MainWindow.Hide();
Application.Current.MainWindow = null;
}
);
}
}
private string elapsedMsec;
public string ElapsedMsec
{
get
{
return this.elapsedMsec;
}
set
{
this.elapsedMsec = value;
this.RaisePropertyChanged(() => this.ElapsedMsec);
}
}
private Visibility showRegisterMessage = Visibility.Hidden;
public Visibility ShowRegisterMessage
{
get
{
return this.showRegisterMessage;
}
set
{
this.showRegisterMessage = value;
this.RaisePropertyChanged(() => this.ShowRegisterMessage);
}
}
private async void LoadLights()
{
this.lights.Clear();
if (string.IsNullOrEmpty(this.selectedBridge) || string.IsNullOrEmpty(this.appKey))
{
return;
}
ILocalHueClient client = new LocalHueClient(this.selectedBridge);
client.Initialize(this.appKey);
(await client.GetLightsAsync()).ToList()
.ForEach(light => this.lights.Add(light.Name));
if (this.lights.Contains(this.SelectedLight) == false)
{
this.SelectedLight = this.lights.Count > 0 ? this.lights[0] : null;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
namespace System
{
[Serializable]
[CLSCompliant(false)]
[StructLayout(LayoutKind.Sequential)]
[TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public readonly struct UInt32 : IComparable, IConvertible, IFormattable, IComparable<uint>, IEquatable<uint>, ISpanFormattable
{
private readonly uint m_value; // Do not rename (binary serialization)
public const uint MaxValue = (uint)0xffffffff;
public const uint MinValue = 0U;
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this object
// null is considered to be less than any instance.
// If object is not of type UInt32, this method throws an ArgumentException.
//
public int CompareTo(object? value)
{
if (value == null)
{
return 1;
}
if (value is uint)
{
// Need to use compare because subtraction will wrap
// to positive for very large neg numbers, etc.
uint i = (uint)value;
if (m_value < i) return -1;
if (m_value > i) return 1;
return 0;
}
throw new ArgumentException(SR.Arg_MustBeUInt32);
}
public int CompareTo(uint value)
{
// Need to use compare because subtraction will wrap
// to positive for very large neg numbers, etc.
if (m_value < value) return -1;
if (m_value > value) return 1;
return 0;
}
public override bool Equals(object? obj)
{
if (!(obj is uint))
{
return false;
}
return m_value == ((uint)obj).m_value;
}
[NonVersionable]
public bool Equals(uint obj)
{
return m_value == obj;
}
// The absolute value of the int contained.
public override int GetHashCode()
{
return ((int)m_value);
}
// The base 10 representation of the number with no extra padding.
public override string ToString()
{
return Number.FormatUInt32(m_value, null, null);
}
public string ToString(IFormatProvider? provider)
{
return Number.FormatUInt32(m_value, null, provider);
}
public string ToString(string? format)
{
return Number.FormatUInt32(m_value, format, null);
}
public string ToString(string? format, IFormatProvider? provider)
{
return Number.FormatUInt32(m_value, format, provider);
}
public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider? provider = null)
{
return Number.TryFormatUInt32(m_value, format, provider, destination, out charsWritten);
}
[CLSCompliant(false)]
public static uint Parse(string s)
{
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseUInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}
[CLSCompliant(false)]
public static uint Parse(string s, NumberStyles style)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseUInt32(s, style, NumberFormatInfo.CurrentInfo);
}
[CLSCompliant(false)]
public static uint Parse(string s, IFormatProvider? provider)
{
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseUInt32(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
}
[CLSCompliant(false)]
public static uint Parse(string s, NumberStyles style, IFormatProvider? provider)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseUInt32(s, style, NumberFormatInfo.GetInstance(provider));
}
[CLSCompliant(false)]
public static uint Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider? provider = null)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.ParseUInt32(s, style, NumberFormatInfo.GetInstance(provider));
}
[CLSCompliant(false)]
public static bool TryParse(string? s, out uint result)
{
if (s == null)
{
result = 0;
return false;
}
return Number.TryParseUInt32IntegerStyle(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result) == Number.ParsingStatus.OK;
}
[CLSCompliant(false)]
public static bool TryParse(ReadOnlySpan<char> s, out uint result)
{
return Number.TryParseUInt32IntegerStyle(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result) == Number.ParsingStatus.OK;
}
[CLSCompliant(false)]
public static bool TryParse(string? s, NumberStyles style, IFormatProvider? provider, out uint result)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
if (s == null)
{
result = 0;
return false;
}
return Number.TryParseUInt32(s, style, NumberFormatInfo.GetInstance(provider), out result) == Number.ParsingStatus.OK;
}
[CLSCompliant(false)]
public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider? provider, out uint result)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.TryParseUInt32(s, style, NumberFormatInfo.GetInstance(provider), out result) == Number.ParsingStatus.OK;
}
//
// IConvertible implementation
//
public TypeCode GetTypeCode()
{
return TypeCode.UInt32;
}
bool IConvertible.ToBoolean(IFormatProvider? provider)
{
return Convert.ToBoolean(m_value);
}
char IConvertible.ToChar(IFormatProvider? provider)
{
return Convert.ToChar(m_value);
}
sbyte IConvertible.ToSByte(IFormatProvider? provider)
{
return Convert.ToSByte(m_value);
}
byte IConvertible.ToByte(IFormatProvider? provider)
{
return Convert.ToByte(m_value);
}
short IConvertible.ToInt16(IFormatProvider? provider)
{
return Convert.ToInt16(m_value);
}
ushort IConvertible.ToUInt16(IFormatProvider? provider)
{
return Convert.ToUInt16(m_value);
}
int IConvertible.ToInt32(IFormatProvider? provider)
{
return Convert.ToInt32(m_value);
}
uint IConvertible.ToUInt32(IFormatProvider? provider)
{
return m_value;
}
long IConvertible.ToInt64(IFormatProvider? provider)
{
return Convert.ToInt64(m_value);
}
ulong IConvertible.ToUInt64(IFormatProvider? provider)
{
return Convert.ToUInt64(m_value);
}
float IConvertible.ToSingle(IFormatProvider? provider)
{
return Convert.ToSingle(m_value);
}
double IConvertible.ToDouble(IFormatProvider? provider)
{
return Convert.ToDouble(m_value);
}
decimal IConvertible.ToDecimal(IFormatProvider? provider)
{
return Convert.ToDecimal(m_value);
}
DateTime IConvertible.ToDateTime(IFormatProvider? provider)
{
throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "UInt32", "DateTime"));
}
object IConvertible.ToType(Type type, IFormatProvider? provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CppSharp
{
public enum NewLineKind
{
Never,
Always,
BeforeNextBlock,
IfNotEmpty
}
public class BlockKind
{
public const int Unknown = 0;
public const int BlockComment = 1;
public const int InlineComment = 2;
public const int Header = 3;
public const int Footer = 4;
public const int LAST = 5;
}
public class Block : ITextGenerator
{
public TextGenerator Text { get; set; }
public int Kind { get; set; }
public NewLineKind NewLineKind { get; set; }
public object Object { get; set; }
public Block Parent { get; set; }
public List<Block> Blocks { get; set; }
private bool hasIndentChanged;
private bool isSubBlock;
public Func<bool> CheckGenerate;
public Block() : this(BlockKind.Unknown)
{
}
public Block(int kind)
{
Kind = kind;
Blocks = new List<Block>();
Text = new TextGenerator();
hasIndentChanged = false;
isSubBlock = false;
}
public void AddBlock(Block block)
{
if (Text.StringBuilder.Length != 0 || hasIndentChanged)
{
hasIndentChanged = false;
var newBlock = new Block { Text = Text.Clone(), isSubBlock = true };
Text.StringBuilder.Clear();
AddBlock(newBlock);
}
block.Parent = this;
Blocks.Add(block);
}
public IEnumerable<Block> FindBlocks(int kind)
{
foreach (var block in Blocks)
{
if (block.Kind == kind)
yield return block;
foreach (var childBlock in block.FindBlocks(kind))
yield return childBlock;
}
}
public virtual string Generate()
{
if (CheckGenerate != null && !CheckGenerate())
return "";
if (Blocks.Count == 0)
return Text.ToString();
var builder = new StringBuilder();
uint totalIndent = 0;
Block previousBlock = null;
var blockIndex = 0;
foreach (var childBlock in Blocks)
{
var childText = childBlock.Generate();
var nextBlock = (++blockIndex < Blocks.Count)
? Blocks[blockIndex]
: null;
var skipBlock = false;
if (nextBlock != null)
{
var nextText = nextBlock.Generate();
if (string.IsNullOrEmpty(nextText) &&
childBlock.NewLineKind == NewLineKind.IfNotEmpty)
skipBlock = true;
}
if (skipBlock)
continue;
if (string.IsNullOrEmpty(childText))
continue;
var lines = childText.SplitAndKeep(Environment.NewLine).ToList();
if (previousBlock != null &&
previousBlock.NewLineKind == NewLineKind.BeforeNextBlock)
builder.AppendLine();
if (childBlock.isSubBlock)
totalIndent = 0;
foreach (var line in lines)
{
if (string.IsNullOrEmpty(line))
continue;
if (!string.IsNullOrWhiteSpace(line))
builder.Append(new string(' ', (int)totalIndent));
builder.Append(line);
if (!line.EndsWith(Environment.NewLine, StringComparison.Ordinal))
builder.AppendLine();
}
if (childBlock.NewLineKind == NewLineKind.Always)
builder.AppendLine();
totalIndent += childBlock.Text.Indent;
previousBlock = childBlock;
}
if (Text.StringBuilder.Length != 0)
builder.Append(Text.StringBuilder);
return builder.ToString();
}
public StringBuilder GenerateUnformatted()
{
if (CheckGenerate != null && !CheckGenerate())
return new StringBuilder(0);
if (Blocks.Count == 0)
return Text.StringBuilder;
var builder = new StringBuilder();
Block previousBlock = null;
var blockIndex = 0;
foreach (var childBlock in Blocks)
{
var childText = childBlock.GenerateUnformatted();
var nextBlock = (++blockIndex < Blocks.Count)
? Blocks[blockIndex]
: null;
if (nextBlock != null)
{
var nextText = nextBlock.GenerateUnformatted();
if (nextText.Length == 0 &&
childBlock.NewLineKind == NewLineKind.IfNotEmpty)
continue;
}
if (childText.Length == 0)
continue;
if (previousBlock != null &&
previousBlock.NewLineKind == NewLineKind.BeforeNextBlock)
builder.AppendLine();
builder.Append(childText);
if (childBlock.NewLineKind == NewLineKind.Always)
builder.AppendLine();
previousBlock = childBlock;
}
if (Text.StringBuilder.Length != 0)
builder.Append(Text.StringBuilder);
return builder;
}
public bool IsEmpty
{
get
{
if (Blocks.Any(block => !block.IsEmpty))
return false;
return string.IsNullOrEmpty(Text.ToString());
}
}
#region ITextGenerator implementation
public uint Indent { get { return Text.Indent; } }
public void Write(string msg, params object[] args)
{
Text.Write(msg, args);
}
public void WriteLine(string msg, params object[] args)
{
Text.WriteLine(msg, args);
}
public void WriteLineIndent(string msg, params object[] args)
{
Text.WriteLineIndent(msg, args);
}
public void NewLine()
{
Text.NewLine();
}
public void NewLineIfNeeded()
{
Text.NewLineIfNeeded();
}
public void NeedNewLine()
{
Text.NeedNewLine();
}
public void ResetNewLine()
{
Text.ResetNewLine();
}
public void PushIndent(uint indent = 4u)
{
hasIndentChanged = true;
Text.PushIndent(indent);
}
public void PopIndent()
{
hasIndentChanged = true;
Text.PopIndent();
}
public void WriteStartBraceIndent()
{
Text.WriteStartBraceIndent();
}
public void WriteCloseBraceIndent()
{
Text.WriteCloseBraceIndent();
}
#endregion
}
public abstract class BlockGenerator : ITextGenerator
{
public Block RootBlock { get; private set; }
public Block ActiveBlock { get; private set; }
protected BlockGenerator()
{
RootBlock = new Block();
ActiveBlock = RootBlock;
}
public virtual string Generate()
{
return RootBlock.Generate();
}
public string GenerateUnformatted()
{
return RootBlock.GenerateUnformatted().ToString();
}
#region Block helpers
public void AddBlock(Block block)
{
ActiveBlock.AddBlock(block);
}
public void PushBlock(int kind = 0, object obj = null)
{
var block = new Block { Kind = kind, Object = obj };
PushBlock(block);
}
public void PushBlock(Block block)
{
block.Parent = ActiveBlock;
ActiveBlock.AddBlock(block);
ActiveBlock = block;
}
public Block PopBlock(NewLineKind newLineKind = NewLineKind.Never)
{
var block = ActiveBlock;
ActiveBlock.NewLineKind = newLineKind;
ActiveBlock = ActiveBlock.Parent;
return block;
}
public IEnumerable<Block> FindBlocks(int kind)
{
return RootBlock.FindBlocks(kind);
}
public Block FindBlock(int kind)
{
return FindBlocks(kind).SingleOrDefault();
}
#endregion
#region ITextGenerator implementation
public uint Indent { get { return ActiveBlock.Indent; } }
public void Write(string msg, params object[] args)
{
ActiveBlock.Write(msg, args);
}
public void WriteLine(string msg, params object[] args)
{
ActiveBlock.WriteLine(msg, args);
}
public void WriteLineIndent(string msg, params object[] args)
{
ActiveBlock.WriteLineIndent(msg, args);
}
public void NewLine()
{
ActiveBlock.NewLine();
}
public void NewLineIfNeeded()
{
ActiveBlock.NewLineIfNeeded();
}
public void NeedNewLine()
{
ActiveBlock.NeedNewLine();
}
public void ResetNewLine()
{
ActiveBlock.ResetNewLine();
}
public void PushIndent(uint indent = 4u)
{
ActiveBlock.PushIndent(indent);
}
public void PopIndent()
{
ActiveBlock.PopIndent();
}
public void WriteStartBraceIndent()
{
ActiveBlock.WriteStartBraceIndent();
}
public void WriteCloseBraceIndent()
{
ActiveBlock.WriteCloseBraceIndent();
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NuGet.Frameworks;
using NuGet.Versioning;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using PropertyNames = NuGet.Client.ManagedCodeConventions.PropertyNames;
namespace Microsoft.DotNet.Build.Tasks.Packaging
{
public class ValidatePackage : ValidationTask
{
[Required]
public string ContractName
{
get;
set;
}
[Required]
public string PackageId
{
get;
set;
}
[Required]
public string PackageVersion
{
get;
set;
}
/// <summary>
/// Frameworks supported by this package
/// Identity: name of framework, can suffx '+' to indicate all later frameworks under validation.
/// RuntimeIDs: Semi-colon seperated list of runtime IDs. If specified overrides the value specified in Frameworks.
/// Version: version of API supported
/// </summary>
[Required]
public ITaskItem[] SupportedFrameworks
{
get;
set;
}
/// <summary>
/// Frameworks to evaluate.
/// Identity: Framework
/// RuntimeIDs: Semi-colon seperated list of runtime IDs
/// </summary>
[Required]
public ITaskItem[] Frameworks
{
get;
set;
}
/// <summary>
/// Path to runtime.json that contains the runtime graph.
/// </summary>
[Required]
public string RuntimeFile
{
get;
set;
}
public bool SkipGenerationCheck
{
get;
set;
}
public bool SkipIndexCheck
{
get;
set;
}
public bool SkipSupportCheck
{
get;
set;
}
public bool UseNetPlatform
{
get { return _generationIdentifier == FrameworkConstants.FrameworkIdentifiers.NetPlatform; }
set { _generationIdentifier = value ? FrameworkConstants.FrameworkIdentifiers.NetPlatform : FrameworkConstants.FrameworkIdentifiers.NetStandard; }
}
/// <summary>
/// List of frameworks which were validated and determined to be supported
/// Identity: framework short name
/// Framework: framework full name
/// Version: assembly version of API that is supported
/// Inbox: true if assembly is expected to come from targeting pack
/// ValidatedRIDs: all RIDs that were scanned
/// </summary>
[Output]
public ITaskItem[] AllSupportedFrameworks
{
get;
set;
}
private Dictionary<NuGetFramework, ValidationFramework> _frameworks;
private string _generationIdentifier = FrameworkConstants.FrameworkIdentifiers.NetStandard;
public override bool Execute()
{
InitializeValidationTask();
if (!SkipSupportCheck)
{
LoadSupport();
if (!SkipGenerationCheck)
{
ValidateGenerations();
}
// TODO: need to validate dependencies.
ValidateSupport();
}
ValidateIndex();
return !Log.HasLoggedErrors;
}
private void ValidateGenerations()
{
// get the generation of all portable implementation dlls.
var allRuntimeGenerations = _report.Targets.Values.SelectMany(t => t.RuntimeAssets.NullAsEmpty())
.Select(r => r.TargetFramework)
.Where(fx => fx != null && fx.Framework == _generationIdentifier && fx.Version != null)
.Select(fx => fx.Version);
// get the generation of all supported frameworks (some may have framework specific implementations
// or placeholders).
var allSupportedGenerations = _frameworks.Values.Where(vf => vf.SupportedVersion != null && FrameworkUtilities.IsGenerationMoniker(vf.Framework) && vf.Framework.Version != null)
.Select(vf => vf.Framework.Version);
// find the minimum supported version as the minimum of any generation explicitly implemented
// with a portable implementation, or the generation of a framework with a platform specific
// implementation.
Version minSupportedGeneration = allRuntimeGenerations.Concat(allSupportedGenerations).Min();
// validate API version against generation for all files
foreach (var compileAsset in _report.Targets.Values.SelectMany(t => t.CompileAssets)
.Where(f => IsDll(f.LocalPath) && FrameworkUtilities.IsGenerationMoniker(f.TargetFramework)))
{
if (compileAsset.TargetFramework.Version < minSupportedGeneration)
{
Log.LogError($"Invalid generation {compileAsset.TargetFramework.Version} for {compileAsset.LocalPath}, must be at least {minSupportedGeneration} based on the implementations in the package. If you meant to target the lower generation you may be missing an implementation for a framework on that lower generation. If not you should raise the generation of the reference assembly to match that of the lowest supported generation of all implementations/placeholders.");
}
}
}
private void ValidateSupport()
{
var runtimeFxSuppression = GetSuppressionValues(Suppression.PermitRuntimeTargetMonikerMismatch) ?? new HashSet<string>();
// validate support for each TxM:RID
foreach (var validateFramework in _frameworks.Values)
{
NuGetFramework fx = validateFramework.Framework;
Version supportedVersion = validateFramework.SupportedVersion;
Target compileTarget;
if (!_report.Targets.TryGetValue(fx.ToString(), out compileTarget))
{
Log.LogError($"Missing target {fx.ToString()} from validation report {ReportFile}");
continue;
}
var compileAssetPaths = compileTarget.CompileAssets.Select(ca => ca.PackagePath);
bool hasCompileAsset, hasCompilePlaceHolder;
NuGetAssetResolver.ExamineAssets(Log, "Compile", ContractName, fx.ToString(), compileAssetPaths, out hasCompileAsset, out hasCompilePlaceHolder);
// resolve/test for each RID associated with this framework.
foreach (string runtimeId in validateFramework.RuntimeIds)
{
string target = String.IsNullOrEmpty(runtimeId) ? fx.ToString() : $"{fx}/{runtimeId}";
Target runtimeTarget;
if (!_report.Targets.TryGetValue(target, out runtimeTarget))
{
Log.LogError($"Missing target {target} from validation report {ReportFile}");
continue;
}
var runtimeAssetPaths = runtimeTarget.RuntimeAssets.Select(ra => ra.PackagePath);
bool hasRuntimeAsset, hasRuntimePlaceHolder;
NuGetAssetResolver.ExamineAssets(Log, "Runtime", ContractName, target, runtimeAssetPaths, out hasRuntimeAsset, out hasRuntimePlaceHolder);
if (null == supportedVersion)
{
// Contract should not be supported on this platform.
bool permitImplementation = HasSuppression(Suppression.PermitImplementation, target);
if (hasCompileAsset && (hasRuntimeAsset & !permitImplementation))
{
Log.LogError($"{ContractName} should not be supported on {target} but has both compile and runtime assets.");
}
else if (hasRuntimeAsset & !permitImplementation)
{
Log.LogError($"{ContractName} should not be supported on {target} but has runtime assets.");
}
if (hasRuntimePlaceHolder && hasCompilePlaceHolder)
{
Log.LogError($"{ContractName} should not be supported on {target} but has placeholders for both compile and runtime which will permit the package to install.");
}
}
else
{
if (validateFramework.IsInbox && !HasSuppression(Suppression.TreatAsOutOfBox, fx))
{
if (!hasCompileAsset && !hasCompilePlaceHolder)
{
Log.LogError($"Framework {fx} should support {ContractName} inbox but was missing a placeholder for compile-time. You may need to add <InboxOnTargetFramework Include=\"{fx.GetShortFolderName()}\" /> to your project.");
}
else if (hasCompileAsset)
{
Log.LogError($"Framework {fx} should support {ContractName} inbox but contained a reference assemblies: {String.Join(", ", compileAssetPaths)}. You may need to add <InboxOnTargetFramework Include=\"{fx.GetShortFolderName()}\" /> to your project.");
}
if (!hasRuntimeAsset && !hasRuntimePlaceHolder)
{
Log.LogError($"Framework {fx} should support {ContractName} inbox but was missing a placeholder for run-time. You may need to add <InboxOnTargetFramework Include=\"{fx.GetShortFolderName()}\" /> to your project.");
}
else if (hasRuntimeAsset)
{
Log.LogError($"Framework {fx} should support {ContractName} inbox but contained a implementation assemblies: {String.Join(", ", runtimeAssetPaths)}. You may need to add <InboxOnTargetFramework Include=\"{fx.GetShortFolderName()}\" /> to your project.");
}
}
else
{
Version referenceAssemblyVersion = null;
if (!hasCompileAsset)
{
if (hasCompilePlaceHolder)
{
Log.LogError($"{ContractName} should be supported on {target} but has a compile placeholder. You may need to remove InboxOnTargetFramework Include=\"{fx.GetShortFolderName()}\" /> from your project.");
}
else
{
Log.LogError($"{ContractName} should be supported on {target} but has no compile assets.");
}
// skip the runtime checks
continue;
}
else
{
var referenceAssemblies = compileTarget.CompileAssets.Where(ca => IsDll(ca.PackagePath));
if (referenceAssemblies.Count() > 1)
{
Log.LogError($"{ContractName} should only contain a single compile asset for {target}.");
}
foreach (var referenceAssembly in referenceAssemblies)
{
referenceAssemblyVersion = referenceAssembly.Version;
if (!VersionUtility.IsCompatibleApiVersion(supportedVersion, referenceAssemblyVersion))
{
Log.LogError($"{ContractName} should support API version {supportedVersion} on {target} but {referenceAssembly.LocalPath} was found to support {referenceAssemblyVersion?.ToString() ?? "<unknown version>"}.");
}
}
}
if (!hasRuntimeAsset)
{
if (HasSuppression(Suppression.PermitMissingImplementation, target))
{
Log.LogMessage($"Suppressed: {ContractName} should be supported on {target} but has no runtime assets.");
}
else
{
// Contract should not be supported on this platform.
Log.LogError($"{ContractName} should be supported on {target} but has no runtime assets.");
}
}
else
{
var implementationAssemblies = runtimeTarget.RuntimeAssets.Where(ra => IsDll(ra.PackagePath));
Dictionary<string, PackageAsset> implementationFiles = new Dictionary<string, PackageAsset>();
foreach (var implementationAssembly in implementationAssemblies)
{
Version implementationVersion = implementationAssembly.Version;
if (!VersionUtility.IsCompatibleApiVersion(supportedVersion, implementationVersion))
{
Log.LogError($"{ContractName} should support API version {supportedVersion} on {target} but {implementationAssembly.LocalPath} was found to support {implementationVersion?.ToString() ?? "<unknown version>"}.");
}
// Previously we only permitted compatible mismatch if Suppression.PermitHigherCompatibleImplementationVersion was specified
// this is a permitted thing on every framework but desktop (which requires exact match to ensure bindingRedirects exist)
// Now make this the default, we'll check desktop, where it matters, more strictly
if (referenceAssemblyVersion != null &&
!VersionUtility.IsCompatibleApiVersion(referenceAssemblyVersion, implementationVersion))
{
Log.LogError($"{ContractName} has mismatched compile ({referenceAssemblyVersion}) and runtime ({implementationVersion}) versions on {target}.");
}
if (fx.Framework == FrameworkConstants.FrameworkIdentifiers.Net &&
referenceAssemblyVersion != null &&
!referenceAssemblyVersion.Equals(implementationVersion))
{
Log.LogError($"{ContractName} has a higher runtime version ({implementationVersion}) than compile version ({referenceAssemblyVersion}) on .NET Desktop framework {target}. This will break bindingRedirects. If the live reference was replaced with a harvested reference you may need to set <Preserve>true</Preserve> on your reference assembly ProjectReference.");
}
string fileName = Path.GetFileName(implementationAssembly.PackagePath);
if (implementationFiles.ContainsKey(fileName))
{
Log.LogError($"{ContractName} includes both {implementationAssembly.LocalPath} and {implementationFiles[fileName].LocalPath} an on {target} which have the same name and will clash when both packages are used.");
}
else
{
implementationFiles[fileName] = implementationAssembly;
}
if (!implementationAssembly.TargetFramework.Equals(fx) && !runtimeFxSuppression.Contains(fx.ToString()))
{
// the selected asset wasn't an exact framework match, let's see if we have an exact match in any other runtime asset.
var matchingFxAssets = _report.UnusedAssets.Where(i => i.TargetFramework != null && i.TargetFramework.Equals(fx) && // exact framework
// Same file
Path.GetFileName(i.PackagePath).Equals(fileName, StringComparison.OrdinalIgnoreCase) &&
// Is implementation
(i.PackagePath.StartsWith("lib") || i.PackagePath.StartsWith("runtimes")) &&
// is not the same source file as was already selected
i.LocalPath != implementationAssembly.LocalPath);
if (matchingFxAssets.Any())
{
Log.LogError($"When targeting {target} {ContractName} will use {implementationAssembly.LocalPath} which targets {implementationAssembly.TargetFramework.GetShortFolderName()} but {String.Join(";", matchingFxAssets.Select(i => i.PackagePath))} targets {fx.GetShortFolderName()} specifically.");
}
}
}
}
}
}
}
}
// Set output items
AllSupportedFrameworks = _frameworks.Values.Where(fx => fx.SupportedVersion != null).Select(fx => fx.ToItem()).OrderBy(i => i.ItemSpec).ToArray();
}
private void ValidateIndex()
{
if (SkipIndexCheck)
{
return;
}
if (PackageIndexes == null || PackageIndexes.Length == 0)
{
return;
}
var index = PackageIndex.Load(PackageIndexes.Select(pi => pi.GetMetadata("FullPath")));
PackageInfo info;
if (!index.Packages.TryGetValue(PackageId, out info))
{
Log.LogError($"PackageIndex from {String.Join(", ", PackageIndexes.Select(i => i.ItemSpec))} is missing an entry for package {PackageId}. Please run /t:UpdatePackageIndex on this project to commit an update.");
return;
}
var allDlls = _report.Targets.Values.SelectMany(t => t.CompileAssets.NullAsEmpty().Concat(t.RuntimeAssets.NullAsEmpty()));
var allAssemblies = allDlls.Where(f => f.Version != null);
var assemblyVersions = new HashSet<Version>(allAssemblies.Select(f => VersionUtility.As4PartVersion(f.Version)));
var thisPackageVersion = VersionUtility.As3PartVersion(NuGetVersion.Parse(PackageVersion).Version);
foreach (var fileVersion in assemblyVersions)
{
Version packageVersion;
// determine if we're missing a mapping for this package
if (!info.AssemblyVersionInPackageVersion.TryGetValue(fileVersion, out packageVersion))
{
Log.LogError($"PackageIndex from {String.Join(", ", PackageIndexes.Select(i => i.ItemSpec))} is missing an assembly version entry for {fileVersion} for package {PackageId}. Please run /t:UpdatePackageIndex on this project to commit an update.");
}
else
{
// determine if we have a mapping for an unstable package and that unstable package is not this one
if (!info.StableVersions.Contains(packageVersion) && packageVersion != thisPackageVersion)
{
Log.LogError($"PackageIndex from {String.Join(", ", PackageIndexes.Select(i => i.ItemSpec))} indicates that assembly version {fileVersion} is contained in non-stable package version {packageVersion} which differs from this package version {thisPackageVersion}.");
}
}
}
var orphanedAssemblyVersions = info.AssemblyVersionInPackageVersion
.Where(pair => pair.Value == thisPackageVersion && !assemblyVersions.Contains(pair.Key))
.Select(pair => pair.Key);
if (orphanedAssemblyVersions.Any())
{
Log.LogError($"PackageIndex from {String.Join(", ", PackageIndexes.Select(i => i.ItemSpec))} is has an assembly version entry(s) for {String.Join(", ", orphanedAssemblyVersions)} which are no longer in package {PackageId}. Please run /t:UpdatePackageIndex on this project to commit an update.");
}
// if no assemblies are present in this package nor were ever present
if (assemblyVersions.Count == 0 &&
info.AssemblyVersionInPackageVersion.Count == 0)
{
// if in the native module map
if (index.ModulesToPackages.Values.Any(p => p.Equals(PackageId)))
{
// ensure the baseline is set
if (info.BaselineVersion != thisPackageVersion)
{
Log.LogError($"PackageIndex from {String.Join(", ", PackageIndexes.Select(i => i.ItemSpec))} is missing an baseline entry(s) for native module {PackageId}. Please run /t:UpdatePackageIndex on this project to commit an update.");
}
}
else
{
// not in the native module map, see if any of the modules in this package are present
// (with a different package, as would be the case for runtime-specific packages)
var moduleNames = allDlls.Select(d => Path.GetFileNameWithoutExtension(d.LocalPath));
var missingModuleNames = moduleNames.Where(m => !index.ModulesToPackages.ContainsKey(m));
if (missingModuleNames.Any())
{
Log.LogError($"PackageIndex from {String.Join(", ", PackageIndexes.Select(i => i.ItemSpec))} is missing ModulesToPackages entry(s) for {String.Join(", ", missingModuleNames)} to package {PackageId}. Please add a an entry for the appropriate package.");
}
}
}
}
private static bool IsDll(string path)
{
return !String.IsNullOrWhiteSpace(path) && Path.GetExtension(path).Equals(".dll", StringComparison.OrdinalIgnoreCase);
}
private void LoadSupport()
{
_frameworks = new Dictionary<NuGetFramework, ValidationFramework>();
// determine which TxM:RIDs should be considered for support based on Frameworks item
foreach (var framework in Frameworks)
{
NuGetFramework fx;
try
{
fx = FrameworkUtilities.ParseNormalized(framework.ItemSpec);
}
catch (Exception ex)
{
Log.LogError($"Could not parse Framework {framework.ItemSpec}. {ex}");
continue;
}
if (fx.Equals(NuGetFramework.UnsupportedFramework))
{
Log.LogError($"Did not recognize {framework.ItemSpec} as valid Framework.");
continue;
}
string runtimeIdList = framework.GetMetadata("RuntimeIDs");
if (_frameworks.ContainsKey(fx))
{
Log.LogError($"Framework {fx} has been listed in Frameworks more than once.");
continue;
}
_frameworks[fx] = new ValidationFramework(fx);
if (!String.IsNullOrWhiteSpace(runtimeIdList))
{
_frameworks[fx].RuntimeIds = runtimeIdList.Split(';');
}
}
// keep a list of explicitly listed supported frameworks so that we can check for conflicts.
HashSet<NuGetFramework> explicitlySupportedFrameworks = new HashSet<NuGetFramework>(NuGetFramework.Comparer);
// determine what version should be supported based on SupportedFramework items
foreach (var supportedFramework in SupportedFrameworks)
{
NuGetFramework fx;
string fxString = supportedFramework.ItemSpec;
bool isExclusiveVersion = fxString.Length > 1 && fxString[0] == '[' && fxString[fxString.Length - 1] == ']';
if (isExclusiveVersion)
{
fxString = fxString.Substring(1, fxString.Length - 2);
}
try
{
fx = FrameworkUtilities.ParseNormalized(fxString);
}
catch (Exception ex)
{
Log.LogError($"Could not parse TargetFramework {fxString} as a SupportedFramework. {ex}");
continue;
}
if (fx.Equals(NuGetFramework.UnsupportedFramework))
{
Log.LogError($"Did not recognize TargetFramework {fxString} as a SupportedFramework.");
continue;
}
Version supportedVersion;
string version = supportedFramework.GetMetadata("Version");
try
{
supportedVersion = Version.Parse(version);
}
catch (Exception ex)
{
Log.LogError($"Could not parse Version {version} on SupportedFramework item {supportedFramework.ItemSpec}. {ex}");
continue;
}
ValidationFramework validationFramework = null;
if (!_frameworks.TryGetValue(fx, out validationFramework))
{
Log.LogError($"SupportedFramework {fx} was specified but is not part of the Framework list to use for validation.");
continue;
}
if (explicitlySupportedFrameworks.Contains(fx))
{
if (supportedVersion <= validationFramework.SupportedVersion)
{
// if we've already picked up a higher/equal version, prefer it
continue;
}
}
else
{
explicitlySupportedFrameworks.Add(fx);
}
validationFramework.SupportedVersion = supportedVersion;
if (!isExclusiveVersion)
{
// find all frameworks of higher version, sorted by version ascending
IEnumerable<ValidationFramework> higherFrameworks = _frameworks.Values.Where(vf => vf.Framework.Framework == fx.Framework && vf.Framework.Version > fx.Version).OrderBy(vf => vf.Framework.Version);
// netcore50 is the last `netcore` framework, after that we use `uap`
if (fx.Framework == FrameworkConstants.FrameworkIdentifiers.NetCore)
{
var uapFrameworks = _frameworks.Values.Where(vf => vf.Framework.Framework == FrameworkConstants.FrameworkIdentifiers.UAP).OrderBy(vf => vf.Framework.Version);
higherFrameworks = higherFrameworks.Concat(uapFrameworks);
}
foreach (var higherFramework in higherFrameworks)
{
if (higherFramework.SupportedVersion != null && higherFramework.SupportedVersion > supportedVersion)
{
// found an higher framework version a higher API version, stop applying this supported version
break;
}
higherFramework.SupportedVersion = supportedVersion;
}
}
}
// determine which Frameworks should support inbox
PackageInfo packageInfo;
if (_index.Packages.TryGetValue(ContractName, out packageInfo))
{
foreach (var inboxPair in packageInfo.InboxOn.GetInboxVersions())
{
if (!_frameworks.ContainsKey(inboxPair.Key))
{
_frameworks[inboxPair.Key] = new ValidationFramework(inboxPair.Key)
{
SupportedVersion = inboxPair.Value,
IsInbox = true
};
}
}
foreach (var validationFramework in _frameworks.Values)
{
if (packageInfo.InboxOn.IsInbox(validationFramework.Framework,
validationFramework.SupportedVersion,
permitRevisions: HasSuppression(Suppression.PermitInboxRevsion)))
{
validationFramework.IsInbox = true;
}
}
}
// validate netstandard frameworks supported by references
foreach (var supportedFramework in _report.SupportedFrameworks)
{
var framework = NuGetFramework.Parse(supportedFramework.Key);
if (framework.Framework != _generationIdentifier)
{
continue;
}
Version supportedVersion;
if (!Version.TryParse(supportedFramework.Value, out supportedVersion))
{
continue;
}
if (!_frameworks.ContainsKey(framework))
{
_frameworks[framework] = new ValidationFramework(framework)
{
SupportedVersion = supportedVersion
};
}
}
}
private class ValidationFramework
{
private static readonly string[] s_nullRidList = new string[] { null };
public ValidationFramework(NuGetFramework framework)
{
Framework = framework;
RuntimeIds = s_nullRidList;
}
public NuGetFramework Framework { get; }
public string[] RuntimeIds { get; set; }
// if null indicates the contract should not be supported.
public Version SupportedVersion { get; set; }
public bool IsInbox { get; set; }
public string ShortName { get { return Framework.GetShortFolderName(); } }
public ITaskItem ToItem()
{
ITaskItem item = new TaskItem(Framework.ToString());
item.SetMetadata("ShortName", ShortName);
item.SetMetadata("Version", SupportedVersion.ToString());
item.SetMetadata("Inbox", IsInbox.ToString());
item.SetMetadata("ValidatedRIDs", String.Join(";", RuntimeIds));
return item;
}
}
}
}
| |
/*
Bullet for XNA Copyright (c) 2003-2007 Vsevolod Klementjev http://www.codeplex.com/xnadevru
Bullet original C++ version Copyright (c) 2003-2007 Erwin Coumans http://bulletphysics.com
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
namespace XnaDevRu.BulletX.Dynamics
{
public struct WheelInfoConstructionInfo
{
private Vector3 _chassicConnectionCS;
private Vector3 _wheelDirectionCS;
private Vector3 _wheelAxisCS;
private Single _suspensionRestLength;
private Single _maxSuspensionTravelCm;
private Single _wheelRadius;
private Single _suspensionStiffness;
private Single _wheelsDampingCompression;
private Single _wheelsDampingRelaxation;
private Single _frictionSlip;
private Boolean _isFrontWheel;
#region Basic Properties
public Vector3 ChassicConnectionCS
{
get { return _chassicConnectionCS; }
set { _chassicConnectionCS = value; }
}
public Vector3 WheelDirectionCS
{
get { return _wheelDirectionCS; }
set { _wheelDirectionCS = value; }
}
public Vector3 WheelAxleCS
{
get { return _wheelAxisCS; }
set { _wheelAxisCS = value; }
}
public Single SuspensionRestLength
{
get { return _suspensionRestLength; }
set { _suspensionRestLength = value; }
}
public Single MaxSuspensionTravelCm
{
get { return _maxSuspensionTravelCm; }
set { _maxSuspensionTravelCm = value; }
}
public Single WheelRadius
{
get { return _wheelRadius; }
set { _wheelRadius = value; }
}
public Single SuspensionStiffness
{
get { return _suspensionStiffness; }
set { _suspensionStiffness = value; }
}
public Single WheelsDampingCompression
{
get { return _wheelsDampingCompression; }
set { _wheelsDampingCompression = value; }
}
public Single WheelsDampingRelaxation
{
get { return _wheelsDampingRelaxation; }
set { _wheelsDampingRelaxation = value; }
}
public Single FrictionSlip
{
get { return _frictionSlip; }
set { _frictionSlip = value; }
}
public Boolean IsFrontWheel
{
get { return _isFrontWheel; }
set { _isFrontWheel = value; }
}
#endregion
}
public struct RaycastInfo
{
private Vector3 _contractNormalWS;
private Vector3 _contractPointWS;
private Vector3 _hardPointWS;
private Vector3 _wheelDirectionWS;
private Vector3 _wheelAxleWS;
private Single _suspensionLength;
private Boolean _isInContract;
#region Basic Properties
public Single SuspensionLength
{
get { return _suspensionLength; }
set { _suspensionLength = value; }
}
public Boolean IsInContact
{
get { return _isInContract; }
set { _isInContract = value; }
}
public Vector3 ContactNormalWS
{
get { return _contractNormalWS; }
set { _contractNormalWS = value; }
}
public Vector3 ContactPointWS
{
get { return _contractPointWS; }
set { _contractPointWS = value; }
}
public Vector3 HardPointWS
{
get { return _hardPointWS; }
set { _hardPointWS = value; }
}
public Vector3 WheelDirectionWS
{
get { return _wheelDirectionWS; }
set { _wheelDirectionWS = value; }
}
public Vector3 WheelAxleWS
{
get { return _wheelAxleWS; }
set { _wheelAxleWS = value; }
}
#endregion
}
public struct WheelInfo
{
private RaycastInfo _raycastInfo;
private Matrix _worldTransform;
private Vector3 _chassicConnectionPointCS;
private Vector3 _wheelDirectionCS;
private Vector3 _wheelAxleCS;
private Single _suspensionRestLength;
private Single _maxSuspensionTravelCm;
private Single _wheelsRadius;
private Single _rollInfluence;
private Single _suspensionStiffness;
private Single _wheelsDampingCompression;
private Single _wheelsDampingRelaxation;
private Single _frictionSlip;
private Single _steering;
private Single _rotation;
private Single _deltaRotation;
private Single _engineForce;
private Single _brake;
private Boolean _isFrontWheel;
private Single _clippedInvContactDotSuspension;
private Single _skidInfo;
private Single _wheelsSuspensionForce;
private Single _suspensionRelativeVelocity;
//can be used to store pointer to sync transforms...
private object _clientInfo;
#region Constructor
public WheelInfo(WheelInfoConstructionInfo constructionInfo)
{
_suspensionRestLength = constructionInfo.SuspensionRestLength;
_maxSuspensionTravelCm = constructionInfo.MaxSuspensionTravelCm;
_wheelsRadius = constructionInfo.WheelRadius;
_wheelsDampingCompression = constructionInfo.WheelsDampingCompression;
_wheelsDampingRelaxation = constructionInfo.WheelsDampingRelaxation;
_wheelDirectionCS = constructionInfo.WheelDirectionCS;
_suspensionStiffness = constructionInfo.SuspensionStiffness;
_chassicConnectionPointCS = constructionInfo.ChassicConnectionCS;
_wheelAxleCS = constructionInfo.WheelAxleCS;
_frictionSlip = constructionInfo.FrictionSlip;
_clippedInvContactDotSuspension = 0;
_suspensionRelativeVelocity = 0;
_wheelsSuspensionForce = 0;
_skidInfo = 0;
_steering = 0;
_engineForce = 0;
_rotation = 0;
_rotation = 0;
_deltaRotation = 0;
_brake = 0;
_rollInfluence = 0.1f;
_brake = 0;
_rollInfluence = 0.1f;
_isFrontWheel = constructionInfo.IsFrontWheel;
_raycastInfo = default(RaycastInfo);
_worldTransform = default(Matrix);
_clientInfo = null;
}
#endregion
#region BasicProperties
public object ClientInfo { get { return _clientInfo; } set { _clientInfo = value; } }
public RaycastInfo RaycastInfo
{
get { return _raycastInfo; }
set { _raycastInfo = value; }
}
public Matrix WorldTransform
{
get { return _worldTransform; }
set { _worldTransform = value; }
}
public Vector3 ChassicConnectionPointCS
{
get { return _chassicConnectionPointCS; }
set { _chassicConnectionPointCS = value; }
}
public Vector3 WheelDirectionCS
{
get { return _wheelDirectionCS; }
set { _wheelDirectionCS = value; }
}
public Vector3 WheelAxleCS
{
get { return _wheelAxleCS; }
set { _wheelAxleCS = value; }
}
public Single SuspensionRestLength
{
get { return _suspensionRestLength; }
set { _suspensionRestLength = value; }
}
public Single MaxSuspensionTravelCm
{
get { return _maxSuspensionTravelCm; }
set { _maxSuspensionTravelCm = value; }
}
public Single WheelsRadius
{
get { return _wheelsRadius; }
set { _wheelsRadius = value; }
}
public Single SuspensionStiffness
{
get { return _suspensionStiffness; }
set { _suspensionStiffness = value; }
}
public Single WheelsDampingCompression
{
get { return _wheelsDampingCompression; }
set { _wheelsDampingCompression = value; }
}
public Single WheelsDampingRelaxation
{
get { return _wheelsDampingRelaxation; }
set { _wheelsDampingRelaxation = value; }
}
public Single FrictionSlip
{
get { return _frictionSlip; }
set { _frictionSlip = value; }
}
public Single Steering
{
get { return _steering; }
set { _steering = value; }
}
public Single Rotation
{
get { return _rotation; }
set { _rotation = value; }
}
public Single DeltaRotation
{
get { return _deltaRotation; }
set { _deltaRotation = value; }
}
public Single RollInfluence
{
get { return _rollInfluence; }
set { _rollInfluence = value; }
}
public Single EngineForce
{
get { return _engineForce; }
set { _engineForce = value; }
}
public Single Brake
{
get { return _brake; }
set { _brake = value; }
}
public Boolean IsFrontWheel
{
get { return _isFrontWheel; }
set { _isFrontWheel = value; }
}
public Single ClippedInvContactDotSuspension
{
get { return _clippedInvContactDotSuspension; }
set { _clippedInvContactDotSuspension = value; }
}
public Single SuspensionRelativeVelocity
{
get { return _suspensionRelativeVelocity; }
set { _suspensionRelativeVelocity = value; }
}
public Single WheelsSuspensionForce
{
get { return _wheelsSuspensionForce; }
set { _wheelsSuspensionForce = value; }
}
public Single SkidInfo
{
get { return _skidInfo; }
set { _skidInfo = value; }
}
#endregion
/// <summary>
///
/// </summary>
/// <param name="chassis"></param>
/// <param name="paramRaycastInfo">Not used!</param>
public void UpdateWheel(RigidBody chassis, RaycastInfo paramRaycastInfo)
{
if (_raycastInfo.IsInContact)
{
float project = Vector3.Dot(_raycastInfo.ContactNormalWS, _raycastInfo.WheelDirectionWS);
Vector3 chassisVelocityAtContactPoint = new Vector3();
Vector3 relpos = _raycastInfo.ContactPointWS - chassis.CenterOfMassPosition;
chassisVelocityAtContactPoint = chassis.GetVelocityInLocalPoint(relpos);
float projVel = Vector3.Dot(_raycastInfo.ContactNormalWS, chassisVelocityAtContactPoint);
if (project >= -0.1f)
{
_suspensionRelativeVelocity = 0;
_clippedInvContactDotSuspension = 1.0f / 0.1f;
}
else
{
float inv = -1 / project;
_suspensionRelativeVelocity = projVel * inv;
_clippedInvContactDotSuspension = inv;
}
}
else
{
_raycastInfo.SuspensionLength = _suspensionRestLength;
_suspensionRelativeVelocity = 0.0f;
_raycastInfo.ContactNormalWS = -_raycastInfo.WheelDirectionWS;
_clippedInvContactDotSuspension = 1.0f;
}
}
// if (m_raycastInfo.m_isInContact)
//{
// btScalar project= m_raycastInfo.m_contactNormalWS.dot( m_raycastInfo.m_wheelDirectionWS );
// btVector3 chassis_velocity_at_contactPoint;
// btVector3 relpos = m_raycastInfo.m_contactPointWS - chassis.getCenterOfMassPosition();
// chassis_velocity_at_contactPoint = chassis.getVelocityInLocalPoint( relpos );
// btScalar projVel = m_raycastInfo.m_contactNormalWS.dot( chassis_velocity_at_contactPoint );
// if ( project >= -0.1f)
// {
// m_suspensionRelativeVelocity = 0.0f;
// m_clippedInvContactDotSuspension = 1.0f / 0.1f;
// }
// else
// {
// btScalar inv = -1.f / project;
// m_suspensionRelativeVelocity = projVel * inv;
// m_clippedInvContactDotSuspension = inv;
// }
//}
//else // Not in contact : position wheel in a nice (rest length) position
//{
// m_raycastInfo.m_suspensionLength = this->getSuspensionRestLength();
// m_suspensionRelativeVelocity = 0.0f;
// m_raycastInfo.m_contactNormalWS = -m_raycastInfo.m_wheelDirectionWS;
// m_clippedInvContactDotSuspension = 1.0f;
//}
};
//btScalar m_clippedInvContactDotSuspension;
//btScalar m_suspensionRelativeVelocity;
//btScalar m_wheelsSuspensionForce;
//btScalar m_skidInfo;
//void* m_clientInfo;//can be used to store pointer to sync transforms...
//btWheelInfo(btWheelInfoConstructionInfo& ci)
//{
// m_suspensionRestLength1 = ci.m_suspensionRestLength;
// m_maxSuspensionTravelCm = ci.m_maxSuspensionTravelCm;
// m_wheelsRadius = ci.m_wheelRadius;
// m_suspensionStiffness = ci.m_suspensionStiffness;
// m_wheelsDampingCompression = ci.m_wheelsDampingCompression;
// m_wheelsDampingRelaxation = ci.m_wheelsDampingRelaxation;
// m_chassisConnectionPointCS = ci.m_chassisConnectionCS;
// m_wheelDirectionCS = ci.m_wheelDirectionCS;
// m_wheelAxleCS = ci.m_wheelAxleCS;
// m_frictionSlip = ci.m_frictionSlip;
// m_steering = 0.f;
// m_engineForce = 0.f;
// m_rotation = 0.f;
// m_deltaRotation = 0.f;
// m_brake = 0.f;
// m_rollInfluence = 0.1f;
// m_bIsFrontWheel = ci.m_bIsFrontWheel;
//}
//void updateWheel(const btRigidBody& chassis,RaycastInfo& raycastInfo);
//btScalar m_clippedInvContactDotSuspension;
//btScalar m_suspensionRelativeVelocity;
////calculated by suspension
//btScalar m_wheelsSuspensionForce;
//btScalar m_skidInfo;
//};
//struct RaycastInfo
//{
// //set by raycaster
// btVector3 m_contactNormalWS;//contactnormal
// btVector3 m_contactPointWS;//raycast hitpoint
// btScalar m_suspensionLength;
// btVector3 m_hardPointWS;//raycast starting point
// btVector3 m_wheelDirectionWS; //direction in worldspace
// btVector3 m_wheelAxleWS; // axle in worldspace
// bool m_isInContact;
// void* m_groundObject; //could be general void* ptr
//};
//struct btWheelInfoConstructionInfo
//{
// btVector3 m_chassisConnectionCS;
// btVector3 m_wheelDirectionCS;
// btVector3 m_wheelAxleCS;
// btScalar m_suspensionRestLength;
// btScalar m_maxSuspensionTravelCm;
// btScalar m_wheelRadius;
// float m_suspensionStiffness;
// float m_wheelsDampingCompression;
// float m_wheelsDampingRelaxation;
// float m_frictionSlip;
// bool m_bIsFrontWheel;
//};
}
| |
//
// SmartPlaylistSource.cs
//
// Author:
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2006-2007 Gabriel Burt
// Copyright (C) 2007 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Data;
using System.Collections;
using System.Collections.Generic;
using Mono.Unix;
using Hyena;
using Hyena.Query;
using Hyena.Data.Sqlite;
using Banshee.Base;
using Banshee.Query;
using Banshee.Sources;
using Banshee.Database;
using Banshee.Playlist;
using Banshee.ServiceStack;
using Banshee.Collection;
using Banshee.Collection.Database;
#pragma warning disable 0169
namespace Banshee.SmartPlaylist
{
public class SmartPlaylistSource : AbstractPlaylistSource, IUnmapableSource
{
private static List<SmartPlaylistSource> playlists = new List<SmartPlaylistSource> ();
private static uint timeout_id = 0;
static SmartPlaylistSource () {
Migrator.MigrateAll ();
ServiceManager.SourceManager.SourceAdded += HandleSourceAdded;
ServiceManager.SourceManager.SourceRemoved += HandleSourceRemoved;
}
private static string generic_name = Catalog.GetString ("Smart Playlist");
private static string properties_label = Catalog.GetString ("Edit Smart Playlist");
private QueryOrder query_order;
private QueryLimit limit;
private IntegerQueryValue limit_value;
private List<SmartPlaylistSource> dependencies = new List<SmartPlaylistSource>();
#region Properties
// Source override
public override bool HasProperties {
get { return true; }
}
public override bool CanAddTracks {
get { return false; }
}
public override bool CanRemoveTracks {
get { return false; }
}
// AbstractPlaylistSource overrides
protected override string SourceTable {
get { return "CoreSmartPlaylists"; }
}
protected override string SourcePrimaryKey {
get { return "SmartPlaylistID"; }
}
protected override string TrackJoinTable {
get { return "CoreSmartPlaylistEntries"; }
}
protected override bool CachesJoinTableEntries {
get { return false; }
}
// Custom properties
private List<QueryField> relevant_fields = new List<QueryField> ();
private QueryNode condition;
public QueryNode ConditionTree {
get { return condition; }
set {
condition = value;
relevant_fields.Clear ();
if (condition != null) {
condition_sql = condition.ToSql (BansheeQuery.FieldSet);
condition_xml = condition.ToXml (BansheeQuery.FieldSet);
foreach (QueryTermNode term in condition.GetTerms ()) {
if (!relevant_fields.Contains (term.Field))
relevant_fields.Add (term.Field);
}
}
}
}
private string additional_conditions;
public void AddCondition (string part)
{
if (!String.IsNullOrEmpty (part)) {
additional_conditions = additional_conditions == null ? part : String.Format ("{0} AND {1}", additional_conditions, part);
}
}
private string condition_sql;
public virtual string ConditionSql {
get { return condition_sql; }
protected set { condition_sql = value; }
}
private string condition_xml;
public string ConditionXml {
get { return condition_xml; }
set {
condition_xml = value;
ConditionTree = XmlQueryParser.Parse (condition_xml, BansheeQuery.FieldSet);
}
}
public QueryOrder QueryOrder {
get { return query_order; }
set { query_order = value; }
}
public IntegerQueryValue LimitValue {
get { return limit_value; }
set { limit_value = value; }
}
public QueryLimit Limit {
get { return limit; }
set { limit = value; }
}
protected string OrderSql {
get { return QueryOrder == null ? null : QueryOrder.ToSql (); }
}
protected string LimitSql {
get { return IsLimited ? Limit.ToSql (LimitValue) : null; }
}
public bool IsLimited {
get {
return (Limit != null && LimitValue != null && !LimitValue.IsEmpty && QueryOrder != null);
}
}
public override bool HasDependencies {
get { return dependencies.Count > 0; }
}
// FIXME scan ConditionTree for date fields
// FIXME even better, scan for date fields and see how fine-grained they are;
// eg if set to Last Added < 2 weeks ago, don't need a timer going off
// every 1 minute - every hour or two would suffice. Just change this
// property to a TimeSpan, rename it TimeDependentResolution or something
public bool TimeDependent {
get { return false; }
}
#endregion
#region Constructors
public SmartPlaylistSource (string name, PrimarySource parent) : base (generic_name, name, parent)
{
SetProperties ();
}
public SmartPlaylistSource (string name, QueryNode condition, QueryOrder order, QueryLimit limit, IntegerQueryValue limit_value, PrimarySource parent)
: this (name, parent)
{
ConditionTree = condition;
QueryOrder = order;
Limit = limit;
LimitValue = limit_value;
SetProperties ();
UpdateDependencies ();
}
// For existing smart playlists that we're loading from the database
protected SmartPlaylistSource (int dbid, string name, string condition_xml, string order_by, string limit_number, string limit_criterion, PrimarySource parent, int count, bool is_temp) :
base (generic_name, name, dbid, -1, 0, parent, is_temp)
{
ConditionXml = condition_xml;
QueryOrder = BansheeQuery.FindOrder (order_by);
Limit = BansheeQuery.FindLimit (limit_criterion);
LimitValue = new IntegerQueryValue ();
LimitValue.ParseUserQuery (limit_number);
SavedCount = count;
SetProperties ();
UpdateDependencies ();
}
private void SetProperties ()
{
Properties.SetString ("Icon.Name", "source-smart-playlist");
Properties.SetString ("SourcePropertiesActionLabel", properties_label);
Properties.SetString ("UnmapSourceActionLabel", Catalog.GetString ("Delete Smart Playlist"));
}
#endregion
#region Public Methods
public void ListenToPlaylists ()
{
}
public bool DependsOn (SmartPlaylistSource source)
{
dependencies.Contains (source);
return false;
}
#endregion
#region Private Methods
private void UpdateDependencies ()
{
foreach (SmartPlaylistSource s in dependencies) {
s.Updated -= OnDependencyUpdated;
}
dependencies.Clear ();
if (ConditionTree != null) {
foreach (SmartPlaylistQueryValue value in ConditionTree.SearchForValues<SmartPlaylistQueryValue> ()) {
SmartPlaylistSource playlist = value.ObjectValue;
if (playlist != null) {
playlist.Updated += OnDependencyUpdated;
dependencies.Add (playlist);
}
}
}
}
private void OnDependencyUpdated (object sender, EventArgs args)
{
Reload ();
}
#endregion
#region AbstractPlaylist overrides
protected override void AfterInitialized ()
{
base.AfterInitialized ();
if (PrimarySource != null) {
PrimarySource.TracksAdded += HandleTracksAdded;
PrimarySource.TracksChanged += HandleTracksChanged;
PrimarySource.TracksDeleted += HandleTracksDeleted;
}
}
protected override void Create ()
{
DbId = ServiceManager.DbConnection.Execute (new HyenaSqliteCommand (@"
INSERT INTO CoreSmartPlaylists
(Name, Condition, OrderBy, LimitNumber, LimitCriterion, PrimarySourceID, IsTemporary)
VALUES (?, ?, ?, ?, ?, ?, ?)",
Name, ConditionXml,
IsLimited ? QueryOrder.Name : null,
IsLimited ? LimitValue.ToSql () : null,
IsLimited ? Limit.Name : null,
PrimarySourceId, IsTemporary
));
UpdateDependencies ();
}
protected override void Update ()
{
ServiceManager.DbConnection.Execute (new HyenaSqliteCommand (@"
UPDATE CoreSmartPlaylists
SET Name = ?,
Condition = ?,
OrderBy = ?,
LimitNumber = ?,
LimitCriterion = ?,
CachedCount = ?,
IsTemporary = ?
WHERE SmartPlaylistID = ?",
Name, ConditionXml,
IsLimited ? QueryOrder.Name : null,
IsLimited ? LimitValue.ToSql () : null,
IsLimited ? Limit.Name : null,
Count, IsTemporary, DbId
));
UpdateDependencies ();
}
protected override bool NeedsReloadWhenFieldChanged (Hyena.Query.QueryField field)
{
if (base.NeedsReloadWhenFieldChanged (field))
return true;
if (QueryOrder != null && QueryOrder.Field == field)
return true;
if (relevant_fields.Contains (field))
return true;
return false;
}
#endregion
#region DatabaseSource overrides
public void RefreshAndReload ()
{
Refresh ();
Reload ();
}
private bool refreshed = false;
public override void Reload ()
{
if (!refreshed)
Refresh ();
base.Reload ();
}
public void Refresh ()
{
// Wipe the member list clean and repopulate it
string reload_str = String.Format (
@"DELETE FROM CoreSmartPlaylistEntries WHERE SmartPlaylistID = {0};
INSERT INTO CoreSmartPlaylistEntries
(EntryID, SmartPlaylistID, TrackID)
SELECT NULL, {0} as SmartPlaylistID, TrackId FROM {1}
WHERE {2} AND CoreTracks.PrimarySourceID = {3}
{4} {5} {6}",
DbId, DatabaseTrackInfo.Provider.From, DatabaseTrackInfo.Provider.Where,
PrimarySourceId, PrependCondition ("AND"), OrderSql, LimitSql
);
ServiceManager.DbConnection.Execute (reload_str);
// If the smart playlist is limited by file size or media duration, limit it here
if (IsLimited && !Limit.RowBased) {
// Identify where the cut off mark is
HyenaSqliteCommand limit_command = new HyenaSqliteCommand (String.Format (
@"SELECT EntryID, {0}
FROM CoreTracks, CoreSmartPlaylistEntries
WHERE SmartPlaylistID = {1} AND CoreSmartPlaylistEntries.TrackID = CoreTracks.TrackID
ORDER BY EntryID",
Limit.Column, DbId
));
long limit = LimitValue.IntValue * Limit.Factor;
long sum = 0;
long? cut_off_id = null;
using (IDataReader reader = ServiceManager.DbConnection.Query (limit_command)) {
while (reader.Read ()) {
sum += Convert.ToInt64 (reader[1]);
if (sum > limit) {
cut_off_id = Convert.ToInt64 (reader[0]);
break;
}
}
}
// Remove the playlist entries after the cut off
if (cut_off_id != null) {
ServiceManager.DbConnection.Execute (new HyenaSqliteCommand (
"DELETE FROM CoreSmartPlaylistEntries WHERE SmartPlaylistID = ? AND EntryID >= ?",
DbId, cut_off_id
));
}
}
refreshed = true;
}
#endregion
#region IUnmapableSource Implementation
public bool Unmap ()
{
if (DbId != null) {
ServiceManager.DbConnection.Execute (new HyenaSqliteCommand (@"
BEGIN TRANSACTION;
DELETE FROM CoreSmartPlaylists WHERE SmartPlaylistID = ?;
DELETE FROM CoreSmartPlaylistEntries WHERE SmartPlaylistID = ?;
COMMIT TRANSACTION",
DbId, DbId
));
}
ThreadAssist.ProxyToMain (Remove);
return true;
}
public bool CanRefresh {
get { return QueryOrder == BansheeQuery.RandomOrder; }
}
protected override void HandleTracksAdded (Source sender, TrackEventArgs args)
{
if (args.When > last_added) {
last_added = args.When;
RefreshAndReload ();
}
}
protected override void HandleTracksChanged (Source sender, TrackEventArgs args)
{
if (args.When > last_updated) {
if (NeedsReloadWhenFieldsChanged (args.ChangedFields)) {
last_updated = args.When;
RefreshAndReload ();
} else {
InvalidateCaches ();
}
}
}
protected override void HandleTracksDeleted (Source sender, TrackEventArgs args)
{
if (args.When > last_removed) {
last_removed = args.When;
RefreshAndReload ();
/*if (ServiceManager.DbConnection.Query<int> (count_removed_command, last_removed) > 0) {
if (Limit == null) {
//track_model.UpdateAggregates ();
//OnUpdated ();
Reload ();
} else {
Reload ();
}
}*/
}
}
public override void SetParentSource (Source parent)
{
base.SetParentSource (parent);
}
#endregion
private string PrependCondition (string with)
{
string sql = String.IsNullOrEmpty (ConditionSql) ? " " : String.Format ("{0} ({1})", with, ConditionSql);
if (!String.IsNullOrEmpty (additional_conditions)) {
sql = String.IsNullOrEmpty (sql) ? additional_conditions : String.Format ("{0} AND ({1})", sql, additional_conditions);
}
return sql;
}
public static IEnumerable<SmartPlaylistSource> LoadAll (PrimarySource parent)
{
ClearTemporary ();
using (HyenaDataReader reader = new HyenaDataReader (ServiceManager.DbConnection.Query (
@"SELECT SmartPlaylistID, Name, Condition, OrderBy, LimitNumber, LimitCriterion, PrimarySourceID, CachedCount, IsTemporary
FROM CoreSmartPlaylists WHERE PrimarySourceID = ?", parent.DbId))) {
while (reader.Read ()) {
SmartPlaylistSource playlist = null;
try {
playlist = new SmartPlaylistSource (
reader.Get<int> (0), reader.Get<string> (1),
reader.Get<string> (2), reader.Get<string> (3),
reader.Get<string> (4), reader.Get<string> (5),
parent, reader.Get<int> (7), reader.Get<bool> (8)
);
} catch (Exception e) {
Log.Warning ("Ignoring Smart Playlist", String.Format ("Caught error: {0}", e), false);
}
if (playlist != null) {
yield return playlist;
}
}
}
}
private static void ClearTemporary ()
{
ServiceManager.DbConnection.Execute (@"
BEGIN TRANSACTION;
DELETE FROM CoreSmartPlaylistEntries WHERE SmartPlaylistID IN (SELECT SmartPlaylistID FROM CoreSmartPlaylists WHERE IsTemporary = 1);
DELETE FROM CoreSmartPlaylists WHERE IsTemporary = 1;
COMMIT TRANSACTION"
);
}
private static void HandleSourceAdded (SourceEventArgs args)
{
SmartPlaylistSource playlist = args.Source as SmartPlaylistSource;
if (playlist == null)
return;
StartTimer (playlist);
playlists.Add (playlist);
SortPlaylists();
}
private static void HandleSourceRemoved (SourceEventArgs args)
{
SmartPlaylistSource playlist = args.Source as SmartPlaylistSource;
if (playlist == null)
return;
playlists.Remove (playlist);
StopTimer();
}
public static void StartTimer (SmartPlaylistSource playlist)
{
// Check if the playlist is time-dependent, and if it is,
// start the auto-refresh timer.
if (timeout_id == 0 && playlist.TimeDependent) {
Log.Information (
"Starting Smart Playlist Auto-Refresh",
"Time-dependent smart playlist added, so starting one-minute auto-refresh timer.",
false
);
timeout_id = GLib.Timeout.Add(1000*60, OnTimerBeep);
}
}
public static void StopTimer ()
{
// If the timer is going and there are no more time-dependent playlists,
// stop the timer.
if (timeout_id != 0) {
foreach (SmartPlaylistSource p in playlists) {
if (p.TimeDependent) {
return;
}
}
// No more time-dependent playlists, so remove the timer
Log.Information (
"Stopping timer",
"There are no time-dependent smart playlists, so stopping auto-refresh timer.",
false
);
GLib.Source.Remove (timeout_id);
timeout_id = 0;
}
}
private static bool OnTimerBeep ()
{
foreach (SmartPlaylistSource p in playlists) {
if (p.TimeDependent) {
p.Reload();
}
}
// Keep the timer going
return true;
}
public static void SortPlaylists () {
playlists.Sort (new DependencyComparer ());
}
public static SmartPlaylistSource GetById (int dbId)
{
// TODO use a dictionary
foreach (SmartPlaylistSource sp in playlists) {
if (sp.DbId == dbId) {
return sp;
}
}
return null;
}
}
public class DependencyComparer : IComparer<SmartPlaylistSource> {
public int Compare(SmartPlaylistSource a, SmartPlaylistSource b)
{
if (b.DependsOn (a)) {
return -1;
} else if (a.DependsOn (b)) {
return 1;
} else {
return 0;
}
}
}
}
#pragma warning restore 0169
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.