context
stringlengths
2.52k
185k
gt
stringclasses
1 value
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.IdentityModel.Claims { using System.Collections.Generic; using System.IdentityModel.Policy; using System.Net.Mail; using System.Security.Claims; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; public class X509CertificateClaimSet : ClaimSet, IIdentityInfo, IDisposable { X509Certificate2 certificate; DateTime expirationTime = SecurityUtils.MinUtcDateTime; ClaimSet issuer; X509Identity identity; X509ChainElementCollection elements; IList<Claim> claims; int index; bool disposed = false; public X509CertificateClaimSet(X509Certificate2 certificate) : this(certificate, true) { } internal X509CertificateClaimSet(X509Certificate2 certificate, bool clone) { if (certificate == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("certificate"); this.certificate = clone ? new X509Certificate2(certificate) : certificate; } X509CertificateClaimSet(X509CertificateClaimSet from) : this(from.X509Certificate, true) { } X509CertificateClaimSet(X509ChainElementCollection elements, int index) { this.elements = elements; this.index = index; this.certificate = elements[index].Certificate; } public override Claim this[int index] { get { ThrowIfDisposed(); EnsureClaims(); return this.claims[index]; } } public override int Count { get { ThrowIfDisposed(); EnsureClaims(); return this.claims.Count; } } IIdentity IIdentityInfo.Identity { get { ThrowIfDisposed(); if (this.identity == null) this.identity = new X509Identity(this.certificate, false, false); return this.identity; } } public DateTime ExpirationTime { get { ThrowIfDisposed(); if (this.expirationTime == SecurityUtils.MinUtcDateTime) this.expirationTime = this.certificate.NotAfter.ToUniversalTime(); return this.expirationTime; } } public override ClaimSet Issuer { get { ThrowIfDisposed(); if (this.issuer == null) { if (this.elements == null) { X509Chain chain = new X509Chain(); chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; chain.Build(certificate); this.index = 0; this.elements = chain.ChainElements; } if (this.index + 1 < this.elements.Count) { this.issuer = new X509CertificateClaimSet(this.elements, this.index + 1); this.elements = null; } // SelfSigned? else if (StringComparer.OrdinalIgnoreCase.Equals(this.certificate.SubjectName.Name, this.certificate.IssuerName.Name)) this.issuer = this; else this.issuer = new X500DistinguishedNameClaimSet(this.certificate.IssuerName); } return this.issuer; } } public X509Certificate2 X509Certificate { get { ThrowIfDisposed(); return this.certificate; } } internal X509CertificateClaimSet Clone() { ThrowIfDisposed(); return new X509CertificateClaimSet(this); } public void Dispose() { if (!this.disposed) { this.disposed = true; SecurityUtils.DisposeIfNecessary(this.identity); if (this.issuer != null) { if (this.issuer != this) { SecurityUtils.DisposeIfNecessary(this.issuer as IDisposable); } } if (this.elements != null) { for (int i = this.index + 1; i < this.elements.Count; ++i) { SecurityUtils.ResetCertificate(this.elements[i].Certificate); } } SecurityUtils.ResetCertificate(this.certificate); } } IList<Claim> InitializeClaimsCore() { List<Claim> claims = new List<Claim>(); byte[] thumbprint = this.certificate.GetCertHash(); claims.Add(new Claim(ClaimTypes.Thumbprint, thumbprint, Rights.Identity)); claims.Add(new Claim(ClaimTypes.Thumbprint, thumbprint, Rights.PossessProperty)); // Ordering SubjectName, Dns, SimpleName, Email, Upn string value = this.certificate.SubjectName.Name; if (!string.IsNullOrEmpty(value)) claims.Add(Claim.CreateX500DistinguishedNameClaim(this.certificate.SubjectName)); // App context switch for disabling support for multiple dns entries in a SAN certificate if (LocalAppContextSwitches.DisableMultipleDNSEntriesInSANCertificate) { // old behavior, default for <= 4.6 value = this.certificate.GetNameInfo(X509NameType.DnsName, false); if (!string.IsNullOrEmpty(value)) claims.Add(Claim.CreateDnsClaim(value)); } else { // new behavior as this is the default long term behavior // Since a SAN can have multiple DNS entries string[] entries = GetDnsFromExtensions(this.certificate); for (int i = 0; i < entries.Length; ++i) { claims.Add(Claim.CreateDnsClaim(entries[i])); } } value = this.certificate.GetNameInfo(X509NameType.SimpleName, false); if (!string.IsNullOrEmpty(value)) claims.Add(Claim.CreateNameClaim(value)); value = this.certificate.GetNameInfo(X509NameType.EmailName, false); if (!string.IsNullOrEmpty(value)) claims.Add(Claim.CreateMailAddressClaim(new MailAddress(value))); value = this.certificate.GetNameInfo(X509NameType.UpnName, false); if (!string.IsNullOrEmpty(value)) claims.Add(Claim.CreateUpnClaim(value)); value = this.certificate.GetNameInfo(X509NameType.UrlName, false); if (!string.IsNullOrEmpty(value)) claims.Add(Claim.CreateUriClaim(new Uri(value))); RSA rsa = this.certificate.PublicKey.Key as RSA; if (rsa != null) claims.Add(Claim.CreateRsaClaim(rsa)); return claims; } void EnsureClaims() { if (this.claims != null) return; this.claims = InitializeClaimsCore(); } static bool SupportedClaimType(string claimType) { return claimType == null || ClaimTypes.Thumbprint.Equals(claimType) || ClaimTypes.X500DistinguishedName.Equals(claimType) || ClaimTypes.Dns.Equals(claimType) || ClaimTypes.Name.Equals(claimType) || ClaimTypes.Email.Equals(claimType) || ClaimTypes.Upn.Equals(claimType) || ClaimTypes.Uri.Equals(claimType) || ClaimTypes.Rsa.Equals(claimType); } // Note: null string represents any. public override IEnumerable<Claim> FindClaims(string claimType, string right) { ThrowIfDisposed(); if (!SupportedClaimType(claimType) || !ClaimSet.SupportedRight(right)) { yield break; } else if (this.claims == null && ClaimTypes.Thumbprint.Equals(claimType)) { if (right == null || Rights.Identity.Equals(right)) { yield return new Claim(ClaimTypes.Thumbprint, this.certificate.GetCertHash(), Rights.Identity); } if (right == null || Rights.PossessProperty.Equals(right)) { yield return new Claim(ClaimTypes.Thumbprint, this.certificate.GetCertHash(), Rights.PossessProperty); } } else if (this.claims == null && ClaimTypes.Dns.Equals(claimType)) { if (right == null || Rights.PossessProperty.Equals(right)) { // App context switch for disabling support for multiple dns entries in a SAN certificate if (LocalAppContextSwitches.DisableMultipleDNSEntriesInSANCertificate) { // old behavior, default for <= 4.6 string value = this.certificate.GetNameInfo(X509NameType.DnsName, false); if (!string.IsNullOrEmpty(value)) { yield return Claim.CreateDnsClaim(value); } } else { // new behavior since this is the default long term behavior string[] entries = GetDnsFromExtensions(certificate); for (int i = 0; i < entries.Length; ++i) { yield return Claim.CreateDnsClaim(entries[i]); } } } } else { EnsureClaims(); bool anyClaimType = (claimType == null); bool anyRight = (right == null); for (int i = 0; i < this.claims.Count; ++i) { Claim claim = this.claims[i]; if ((claim != null) && (anyClaimType || claimType.Equals(claim.ClaimType)) && (anyRight || right.Equals(claim.Right))) { yield return claim; } } } } // Fixing Bug 795660: SAN having multiple DNS entries private static string[] GetDnsFromExtensions(X509Certificate2 cert) { foreach (X509Extension ext in cert.Extensions) { // Extension is SAN or SAN2 if (ext.Oid.Value == "2.5.29.7" || ext.Oid.Value == "2.5.29.17") { string asnString = ext.Format(true); if (string.IsNullOrEmpty(asnString)) { return new string[0]; } string[] rawDnsEntries = asnString.Split(new string[1] { "\n" }, StringSplitOptions.RemoveEmptyEntries); string[] dnsEntries = new string[rawDnsEntries.Length]; for (int i = 0; i < rawDnsEntries.Length; ++i) { int equalSignIndex = rawDnsEntries[i].IndexOf('='); dnsEntries[i] = rawDnsEntries[i].Substring(equalSignIndex + 1).Trim(); } return dnsEntries; } } return new string[0]; } public override IEnumerator<Claim> GetEnumerator() { ThrowIfDisposed(); EnsureClaims(); return this.claims.GetEnumerator(); } public override string ToString() { return this.disposed ? base.ToString() : SecurityUtils.ClaimSetToString(this); } void ThrowIfDisposed() { if (this.disposed) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException(this.GetType().FullName)); } } class X500DistinguishedNameClaimSet : DefaultClaimSet, IIdentityInfo { IIdentity identity; public X500DistinguishedNameClaimSet(X500DistinguishedName x500DistinguishedName) { if (x500DistinguishedName == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("x500DistinguishedName"); this.identity = new X509Identity(x500DistinguishedName); List<Claim> claims = new List<Claim>(2); claims.Add(new Claim(ClaimTypes.X500DistinguishedName, x500DistinguishedName, Rights.Identity)); claims.Add(Claim.CreateX500DistinguishedNameClaim(x500DistinguishedName)); Initialize(ClaimSet.Anonymous, claims); } public IIdentity Identity { get { return this.identity; } } } } class X509Identity : GenericIdentity, IDisposable { const string X509 = "X509"; const string Thumbprint = "; "; X500DistinguishedName x500DistinguishedName; X509Certificate2 certificate; string name; bool disposed = false; bool disposable = true; public X509Identity(X509Certificate2 certificate) : this(certificate, true, true) { } public X509Identity(X500DistinguishedName x500DistinguishedName) : base(X509, X509) { this.x500DistinguishedName = x500DistinguishedName; } internal X509Identity(X509Certificate2 certificate, bool clone, bool disposable) : base(X509, X509) { this.certificate = clone ? new X509Certificate2(certificate) : certificate; this.disposable = clone || disposable; } public override string Name { get { ThrowIfDisposed(); if (this.name == null) { // // DCR 48092: PrincipalPermission authorization using certificates could cause Elevation of Privilege. // because there could be duplicate subject name. In order to be more unique, we use SubjectName + Thumbprint // instead // this.name = GetName() + Thumbprint + this.certificate.Thumbprint; } return this.name; } } string GetName() { if (this.x500DistinguishedName != null) return this.x500DistinguishedName.Name; string value = this.certificate.SubjectName.Name; if (!string.IsNullOrEmpty(value)) return value; value = this.certificate.GetNameInfo(X509NameType.DnsName, false); if (!string.IsNullOrEmpty(value)) return value; value = this.certificate.GetNameInfo(X509NameType.SimpleName, false); if (!string.IsNullOrEmpty(value)) return value; value = this.certificate.GetNameInfo(X509NameType.EmailName, false); if (!string.IsNullOrEmpty(value)) return value; value = this.certificate.GetNameInfo(X509NameType.UpnName, false); if (!string.IsNullOrEmpty(value)) return value; return String.Empty; } public override ClaimsIdentity Clone() { return this.certificate != null ? new X509Identity(this.certificate) : new X509Identity(this.x500DistinguishedName); } public void Dispose() { if (this.disposable && !this.disposed) { this.disposed = true; if (this.certificate != null) { this.certificate.Reset(); } } } void ThrowIfDisposed() { if (this.disposed) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException(this.GetType().FullName)); } } } }
using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using UnityEngine; [assembly: InternalsVisibleTo("Unity.Formats.Alembic.UnitTests.Editor")] [assembly: InternalsVisibleTo("Unity.Formats.Alembic.UnitTests.Runtime")] [assembly: InternalsVisibleTo("Unity.Formats.Alembic.Tests")] [assembly: InternalsVisibleTo("Unity.Formats.Alembic.Editor")] namespace UnityEngine.Formats.Alembic.Sdk { enum aeArchiveType { HDF5, Ogawa, }; enum aeTimeSamplingType { Uniform = 0, // Cyclic = 1, Acyclic = 2, }; enum aeXformType { Matrix, TRS, }; enum aeTopology { Points, Lines, Triangles, Quads, }; enum aePropertyType { Unknown, // scalar types Bool, Int, UInt, Float, Float2, Float3, Float4, Float4x4, // array types BoolArray, IntArray, UIntArray, FloatArray, Float2Array, Float3Array, Float4Array, Float4x4Array, ScalarTypeBegin = Bool, ScalarTypeEnd = Float4x4, ArrayTypeBegin = BoolArray, ArrayTypeEnd = Float4x4Array, }; [Serializable] struct aeConfig { [SerializeField] private aeArchiveType archiveType; public aeArchiveType ArchiveType { get { return archiveType; } set { archiveType = value; } } [SerializeField] private aeTimeSamplingType timeSamplingType; public aeTimeSamplingType TimeSamplingType { get { return timeSamplingType; } set { timeSamplingType = value; } } [SerializeField] private float frameRate; public float FrameRate { get { return frameRate; } set { frameRate = value; } } [SerializeField] private aeXformType xformType; public aeXformType XformType { get { return xformType; } set { xformType = value; } } [SerializeField] private Bool swapHandedness; public Bool SwapHandedness { get { return swapHandedness; } set { swapHandedness = value; } } [SerializeField] private Bool swapFaces; public Bool SwapFaces { get { return swapFaces; } set { swapFaces = value; } } [SerializeField] private float scaleFactor; public float ScaleFactor { get { return scaleFactor; } set { scaleFactor = value; } } public static aeConfig defaultValue { get { return new aeConfig { ArchiveType = aeArchiveType.Ogawa, TimeSamplingType = aeTimeSamplingType.Uniform, FrameRate = 30.0f, XformType = aeXformType.TRS, SwapHandedness = true, SwapFaces = false, ScaleFactor = 100.0f, }; } } } struct aeXformData { public Bool visibility { get; set; } public Vector3 translation { get; set; } public Quaternion rotation { get; set; } public Vector3 scale { get; set; } public Bool inherits { get; set; } } struct aePointsData { public Bool visibility { get; set; } public IntPtr positions { get; set; } // Vector3* public IntPtr velocities { get; set; } // Vector3*. can be null public IntPtr ids { get; set; } // uint*. can be null public int count { get; set; } } struct aeSubmeshData { internal IntPtr indexes { get; set; } public int indexCount { get; set; } public aeTopology topology { get; set; } }; struct aePolyMeshData { public Bool visibility { get; set; } public IntPtr points { get; set; } // Vector3* public int pointCount { get; set; } public IntPtr normals; // Vector3*. can be null public IntPtr uv0; // Vector2*. can be null public IntPtr uv1; // Vector2*. can be null public IntPtr colors; // Vector2*. can be null public IntPtr submeshes; // aeSubmeshData*. can be null public int submeshCount; } struct aeCameraData { public Bool visibility; public float nearClippingPlane; public float farClippingPlane; public float fieldOfView; // in degree. relevant only if focalLength==0.0 (default) public float aspectRatio; public float focusDistance; // in cm public float focalLength; // in mm. if 0.0f, automatically computed by aperture and fieldOfView. alembic's default value is 0.035f. public float aperture; // in cm. vertical one public static aeCameraData defaultValue { get { return new aeCameraData { nearClippingPlane = 0.3f, farClippingPlane = 1000.0f, fieldOfView = 60.0f, aspectRatio = 16.0f / 9.0f, focusDistance = 5.0f, focalLength = 0.0f, aperture = 2.4f, }; } } } struct aeContext { public IntPtr self; public aeObject topObject { get { return NativeMethods.aeGetTopObject(self); } } public static aeContext Create() { return NativeMethods.aeCreateContext(); } public void Destroy() { NativeMethods.aeDestroyContext(self); self = IntPtr.Zero; } public void SetConfig(ref aeConfig conf) { NativeMethods.aeSetConfig(self, ref conf); } public bool OpenArchive(string path) { return NativeMethods.aeOpenArchive(self, path); } public int AddTimeSampling(float start_time) { return NativeMethods.aeAddTimeSampling(self, start_time); } public void AddTime(float start_time) { NativeMethods.aeAddTime(self, start_time); } public void MarkFrameBegin() { NativeMethods.aeMarkFrameBegin(self); } public void MarkFrameEnd() { NativeMethods.aeMarkFrameEnd(self); } } struct aeObject { public IntPtr self; public aeObject(IntPtr self) { this.self = self; } public aeObject NewXform(string name, int tsi) { return NativeMethods.aeNewXform(self, name, tsi); } public aeObject NewCamera(string name, int tsi) { return NativeMethods.aeNewCamera(self, name, tsi); } public aeObject NewPoints(string name, int tsi) { return NativeMethods.aeNewPoints(self, name, tsi); } public aeObject NewPolyMesh(string name, int tsi) { return NativeMethods.aeNewPolyMesh(self, name, tsi); } public void WriteSample(ref aeXformData data) { NativeMethods.aeXformWriteSample(self, ref data); } public void WriteSample(ref CameraData data) { NativeMethods.aeCameraWriteSample(self, ref data); } public void WriteSample(ref aePolyMeshData data) { NativeMethods.aePolyMeshWriteSample(self, ref data); } public void AddFaceSet(string name) { NativeMethods.aePolyMeshAddFaceSet(self, name); } public void WriteSample(ref aePointsData data) { NativeMethods.aePointsWriteSample(self, ref data); } public aeProperty NewProperty(string name, aePropertyType type) { return NativeMethods.aeNewProperty(self, name, type); } public void MarkForceInvisible() { NativeMethods.aeMarkForceInvisible(self); } } struct aeProperty { public IntPtr self; public aeProperty(IntPtr self) { this.self = self; } public void WriteArraySample(IntPtr data, int numData) { NativeMethods.aePropertyWriteArraySample(self, data, numData); } public void WriteScalarSample(ref float data) { NativeMethods.aePropertyWriteScalarSample(self, ref data); } public void WriteScalarSample(ref int data) { NativeMethods.aePropertyWriteScalarSample(self, ref data); } public void WriteScalarSample(ref Bool data) { NativeMethods.aePropertyWriteScalarSample(self, ref data); } public void WriteScalarSample(ref Vector2 data) { NativeMethods.aePropertyWriteScalarSample(self, ref data); } public void WriteScalarSample(ref Vector3 data) { NativeMethods.aePropertyWriteScalarSample(self, ref data); } public void WriteScalarSample(ref Vector4 data) { NativeMethods.aePropertyWriteScalarSample(self, ref data); } public void WriteScalarSample(ref Matrix4x4 data) { NativeMethods.aePropertyWriteScalarSample(self, ref data); } } static partial class AbcAPI { public static void aeWaitMaxDeltaTime() { var next = Time.unscaledTime + Time.maximumDeltaTime; while (Time.realtimeSinceStartup < next) System.Threading.Thread.Sleep(1); } } internal static class NativeMethods { [DllImport(Abci.Lib)] public static extern aeContext aeCreateContext(); [DllImport(Abci.Lib)] public static extern void aeDestroyContext(IntPtr ctx); [DllImport(Abci.Lib)] public static extern void aeSetConfig(IntPtr ctx, ref aeConfig conf); [DllImport(Abci.Lib, BestFitMapping = false, ThrowOnUnmappableChar = true)] public static extern Bool aeOpenArchive(IntPtr ctx, string path); [DllImport(Abci.Lib)] public static extern aeObject aeGetTopObject(IntPtr ctx); [DllImport(Abci.Lib)] public static extern int aeAddTimeSampling(IntPtr ctx, float start_time); // relevant only if plingType is acyclic. if tsi==-1, add time to all time samplings. [DllImport(Abci.Lib)] public static extern void aeAddTime(IntPtr ctx, float time, int tsi = -1); [DllImport(Abci.Lib)] public static extern void aeMarkFrameBegin(IntPtr ctx); [DllImport(Abci.Lib)] public static extern void aeMarkFrameEnd(IntPtr ctx); [DllImport(Abci.Lib, BestFitMapping = false, ThrowOnUnmappableChar = true)] public static extern aeObject aeNewXform(IntPtr self, string name, int tsi); [DllImport(Abci.Lib, BestFitMapping = false, ThrowOnUnmappableChar = true)] public static extern aeObject aeNewCamera(IntPtr self, string name, int tsi); [DllImport(Abci.Lib, BestFitMapping = false, ThrowOnUnmappableChar = true)] public static extern aeObject aeNewPoints(IntPtr self, string name, int tsi); [DllImport(Abci.Lib, BestFitMapping = false, ThrowOnUnmappableChar = true)] public static extern aeObject aeNewPolyMesh(IntPtr self, string name, int tsi); [DllImport(Abci.Lib)] public static extern void aeXformWriteSample(IntPtr self, ref aeXformData data); [DllImport(Abci.Lib)] public static extern void aeCameraWriteSample(IntPtr self, ref CameraData data); [DllImport(Abci.Lib)] public static extern void aePolyMeshWriteSample(IntPtr self, ref aePolyMeshData data); [DllImport(Abci.Lib, BestFitMapping = false, ThrowOnUnmappableChar = true)] public static extern int aePolyMeshAddFaceSet(IntPtr self, string name); [DllImport(Abci.Lib)] public static extern void aePointsWriteSample(IntPtr self, ref aePointsData data); [DllImport(Abci.Lib, BestFitMapping = false, ThrowOnUnmappableChar = true)] public static extern aeProperty aeNewProperty(IntPtr self, string name, aePropertyType type); [DllImport(Abci.Lib)] public static extern void aeMarkForceInvisible(IntPtr self); [DllImport(Abci.Lib)] public static extern void aePropertyWriteArraySample(IntPtr self, IntPtr data, int num_data); // all of these are IntPtr version. just for convenience. [DllImport(Abci.Lib)] public static extern void aePropertyWriteScalarSample(IntPtr self, ref float data); [DllImport(Abci.Lib)] public static extern void aePropertyWriteScalarSample(IntPtr self, ref int data); [DllImport(Abci.Lib)] public static extern void aePropertyWriteScalarSample(IntPtr self, ref Bool data); [DllImport(Abci.Lib)] public static extern void aePropertyWriteScalarSample(IntPtr self, ref Vector2 data); [DllImport(Abci.Lib)] public static extern void aePropertyWriteScalarSample(IntPtr self, ref Vector3 data); [DllImport(Abci.Lib)] public static extern void aePropertyWriteScalarSample(IntPtr self, ref Vector4 data); [DllImport(Abci.Lib)] public static extern void aePropertyWriteScalarSample(IntPtr self, ref Matrix4x4 data); [DllImport(Abci.Lib)] public static extern int aeGenerateRemapIndices(IntPtr dstIndices, IntPtr points, IntPtr weights4, int numPoints); [DllImport(Abci.Lib)] public static extern void aeApplyMatrixP(IntPtr dstPoints, int num, ref Matrix4x4 mat); [DllImport(Abci.Lib)] public static extern void aeApplyMatrixV(IntPtr dstVectors, int num, ref Matrix4x4 mat); [DllImport(Abci.Lib, BestFitMapping = false, ThrowOnUnmappableChar = true)] public static extern void aiClearContextsWithPath(string path); [DllImport(Abci.Lib)] public static extern aiContext aiContextCreate(int uid); [DllImport(Abci.Lib)] public static extern void aiContextDestroy(IntPtr ctx); [DllImport(Abci.Lib, BestFitMapping = false, ThrowOnUnmappableChar = true)] public static extern Bool aiContextLoad(IntPtr ctx, string path); [DllImport(Abci.Lib)] public static extern void aiContextSetConfig(IntPtr ctx, ref aiConfig conf); [DllImport(Abci.Lib)] public static extern int aiContextGetTimeSamplingCount(IntPtr ctx); [DllImport(Abci.Lib)] public static extern aiTimeSampling aiContextGetTimeSampling(IntPtr ctx, int i); [DllImport(Abci.Lib)] public static extern void aiContextGetTimeRange(IntPtr ctx, ref double begin, ref double end); [DllImport(Abci.Lib)] public static extern aiObject aiContextGetTopObject(IntPtr ctx); [DllImport(Abci.Lib)] public static extern void aiContextUpdateSamples(IntPtr ctx, double time); [DllImport(Abci.Lib)] public static extern int aiTimeSamplingGetSampleCount(IntPtr self); [DllImport(Abci.Lib)] public static extern double aiTimeSamplingGetTime(IntPtr self, int index); [DllImport(Abci.Lib)] public static extern void aiTimeSamplingGetRange(IntPtr self, ref double start, ref double end); [DllImport(Abci.Lib)] public static extern aiContext aiObjectGetContext(IntPtr obj); [DllImport(Abci.Lib)] public static extern int aiObjectGetNumChildren(IntPtr obj); [DllImport(Abci.Lib)] public static extern aiObject aiObjectGetChild(IntPtr obj, int i); [DllImport(Abci.Lib)] public static extern aiObject aiObjectGetParent(IntPtr obj); [DllImport(Abci.Lib)] public static extern void aiObjectSetEnabled(IntPtr obj, Bool v); [DllImport(Abci.Lib)] public static extern IntPtr aiObjectGetName(IntPtr obj); [DllImport(Abci.Lib)] public static extern IntPtr aiObjectGetFullName(IntPtr obj); [DllImport(Abci.Lib)] public static extern Sdk.aiXform aiObjectAsXform(IntPtr obj); [DllImport(Abci.Lib)] public static extern Sdk.aiCamera aiObjectAsCamera(IntPtr obj); [DllImport(Abci.Lib)] public static extern Sdk.aiPoints aiObjectAsPoints(IntPtr obj); [DllImport(Abci.Lib)] public static extern Sdk.aiPolyMesh aiObjectAsPolyMesh(IntPtr obj); [DllImport(Abci.Lib)] public static extern void aiSchemaUpdateSample(IntPtr schema, ref aiSampleSelector ss); [DllImport(Abci.Lib)] public static extern void aiSchemaSync(IntPtr schema); [DllImport(Abci.Lib)] public static extern aiSample aiSchemaGetSample(IntPtr schema); [DllImport(Abci.Lib)] public static extern Bool aiSchemaIsConstant(IntPtr schema); [DllImport(Abci.Lib)] public static extern Bool aiSchemaIsDataUpdated(IntPtr schema); [DllImport(Abci.Lib)] public static extern int aiSchemaGetNumProperties(IntPtr schema); [DllImport(Abci.Lib)] public static extern aiProperty aiSchemaGetPropertyByIndex(IntPtr schema, int i); [DllImport(Abci.Lib, BestFitMapping = false, ThrowOnUnmappableChar = true)] public static extern aiProperty aiSchemaGetPropertyByName(IntPtr schema, string name); [DllImport(Abci.Lib)] public static extern void aiPolyMeshGetSummary(IntPtr schema, ref aiMeshSummary dst); [DllImport(Abci.Lib)] public static extern void aiPointsSetSort(IntPtr schema, Bool v); [DllImport(Abci.Lib)] public static extern void aiPointsSetSortBasePosition(IntPtr schema, Vector3 v); [DllImport(Abci.Lib)] public static extern void aiPointsGetSummary(IntPtr schema, ref aiPointsSummary dst); [DllImport(Abci.Lib)] public static extern void aiXformGetData(IntPtr sample, ref aiXformData data); [DllImport(Abci.Lib)] public static extern void aiCameraGetData(IntPtr sample, ref CameraData dst); [DllImport(Abci.Lib)] public static extern void aiPolyMeshGetSampleSummary(IntPtr sample, ref aiMeshSampleSummary dst); [DllImport(Abci.Lib)] public static extern int aiPolyMeshGetSplitSummaries(IntPtr sample, IntPtr dst); [DllImport(Abci.Lib)] public static extern void aiPolyMeshGetSubmeshSummaries(IntPtr sample, IntPtr dst); [DllImport(Abci.Lib)] public static extern void aiPolyMeshFillVertexBuffer(IntPtr sample, IntPtr vbs, IntPtr ibs); [DllImport(Abci.Lib)] public static extern void aiSampleSync(IntPtr sample); [DllImport(Abci.Lib)] public static extern void aiPointsGetSampleSummary(IntPtr sample, ref aiPointsSampleSummary dst); [DllImport(Abci.Lib)] public static extern void aiPointsFillData(IntPtr sample, IntPtr dst); [DllImport(Abci.Lib)] public static extern IntPtr aiPropertyGetName(IntPtr prop); [DllImport(Abci.Lib)] public static extern aiPropertyType aiPropertyGetType(IntPtr prop); [DllImport(Abci.Lib)] public static extern void aiPropertyGetData(IntPtr prop, aiPropertyData oData); [DllImport(Abci.Lib)] public static extern aiSampleSelector aiTimeToSampleSelector(double time); [DllImport(Abci.Lib)] public static extern void aiCleanup(); internal struct aiXform { [DllImport(Abci.Lib)] public static extern aiXformSample aiSchemaGetSample(IntPtr schema); } internal struct aiCamera { [DllImport(Abci.Lib)] public static extern aiCameraSample aiSchemaGetSample(IntPtr schema); } internal struct aiPolyMesh { [DllImport(Abci.Lib)] public static extern aiPolyMeshSample aiSchemaGetSample(IntPtr schema); } internal struct aiPoints { [DllImport(Abci.Lib)] public static extern aiPointsSample aiSchemaGetSample(IntPtr schema); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Abp.Authorization.Roles; using Abp.Configuration; using Abp.Configuration.Startup; using Abp.Dependency; using Abp.Domain.Repositories; using Abp.Domain.Uow; using Abp.Extensions; using Abp.IdentityFramework; using Abp.Localization; using Abp.MultiTenancy; using Abp.Runtime.Security; using Abp.Runtime.Session; using Abp.Timing; using Abp.Zero; using Abp.Zero.Configuration; using Microsoft.AspNet.Identity; namespace Abp.Authorization.Users { /// <summary> /// Extends <see cref="UserManager{TUser,TKey}"/> of ASP.NET Identity Framework. /// </summary> public abstract class AbpUserManager<TTenant, TRole, TUser> : UserManager<TUser, long>, ITransientDependency where TTenant : AbpTenant<TTenant, TUser> where TRole : AbpRole<TTenant, TUser>, new() where TUser : AbpUser<TTenant, TUser> { private IUserPermissionStore<TTenant, TUser> UserPermissionStore { get { if (!(Store is IUserPermissionStore<TTenant, TUser>)) { throw new AbpException("Store is not IUserPermissionStore"); } return Store as IUserPermissionStore<TTenant, TUser>; } } public ILocalizationManager LocalizationManager { get; set; } public IAbpSession AbpSession { get; set; } protected AbpRoleManager<TTenant, TRole, TUser> RoleManager { get; private set; } protected ISettingManager SettingManager { get; private set; } protected AbpUserStore<TTenant, TRole, TUser> AbpStore { get; private set; } private readonly IPermissionManager _permissionManager; private readonly IUnitOfWorkManager _unitOfWorkManager; private readonly IUserManagementConfig _userManagementConfig; private readonly IIocResolver _iocResolver; private readonly IRepository<TTenant> _tenantRepository; private readonly IMultiTenancyConfig _multiTenancyConfig; //TODO: Non-generic parameters may be converted to property-injection protected AbpUserManager( AbpUserStore<TTenant, TRole, TUser> userStore, AbpRoleManager<TTenant, TRole, TUser> roleManager, IRepository<TTenant> tenantRepository, IMultiTenancyConfig multiTenancyConfig, IPermissionManager permissionManager, IUnitOfWorkManager unitOfWorkManager, ISettingManager settingManager, IUserManagementConfig userManagementConfig, IIocResolver iocResolver) : base(userStore) { AbpStore = userStore; RoleManager = roleManager; SettingManager = settingManager; _tenantRepository = tenantRepository; _multiTenancyConfig = multiTenancyConfig; _permissionManager = permissionManager; _unitOfWorkManager = unitOfWorkManager; _userManagementConfig = userManagementConfig; _iocResolver = iocResolver; LocalizationManager = NullLocalizationManager.Instance; } public override async Task<IdentityResult> CreateAsync(TUser user) { var result = await CheckDuplicateUsernameOrEmailAddressAsync(user.Id, user.UserName, user.EmailAddress); if (!result.Succeeded) { return result; } if (AbpSession.TenantId.HasValue) { user.TenantId = AbpSession.TenantId.Value; } return await base.CreateAsync(user); } /// <summary> /// Check whether a user is granted for a permission. /// </summary> /// <param name="userId">User id</param> /// <param name="permissionName">Permission name</param> public virtual async Task<bool> IsGrantedAsync(long userId, string permissionName) { return await IsGrantedAsync( await GetUserByIdAsync(userId), _permissionManager.GetPermission(permissionName) ); } /// <summary> /// Check whether a user is granted for a permission. /// </summary> /// <param name="user">User</param> /// <param name="permission">Permission</param> public virtual async Task<bool> IsGrantedAsync(TUser user, Permission permission) { //Check for multi-tenancy side if (!permission.MultiTenancySides.HasFlag(AbpSession.MultiTenancySide)) { return false; } //Check for user-specific value if (await UserPermissionStore.HasPermissionAsync(user, new PermissionGrantInfo(permission.Name, true))) { return true; } if (await UserPermissionStore.HasPermissionAsync(user, new PermissionGrantInfo(permission.Name, false))) { return false; } //Check for roles var roleNames = await GetRolesAsync(user.Id); if (!roleNames.Any()) { return permission.IsGrantedByDefault; } foreach (var roleName in roleNames) { if (await RoleManager.HasPermissionAsync(roleName, permission.Name)) { return true; } } return false; } /// <summary> /// Gets granted permissions for a user. /// </summary> /// <param name="user">Role</param> /// <returns>List of granted permissions</returns> public virtual async Task<IReadOnlyList<Permission>> GetGrantedPermissionsAsync(TUser user) { var permissionList = new List<Permission>(); foreach (var permission in _permissionManager.GetAllPermissions()) { if (await IsGrantedAsync(user, permission)) { permissionList.Add(permission); } } return permissionList; } /// <summary> /// Sets all granted permissions of a user at once. /// Prohibits all other permissions. /// </summary> /// <param name="user">The user</param> /// <param name="permissions">Permissions</param> public virtual async Task SetGrantedPermissionsAsync(TUser user, IEnumerable<Permission> permissions) { var oldPermissions = await GetGrantedPermissionsAsync(user); var newPermissions = permissions.ToArray(); foreach (var permission in oldPermissions.Where(p => !newPermissions.Contains(p))) { await ProhibitPermissionAsync(user, permission); } foreach (var permission in newPermissions.Where(p => !oldPermissions.Contains(p))) { await GrantPermissionAsync(user, permission); } } /// <summary> /// Prohibits all permissions for a user. /// </summary> /// <param name="user">User</param> public async Task ProhibitAllPermissionsAsync(TUser user) { foreach (var permission in _permissionManager.GetAllPermissions()) { await ProhibitPermissionAsync(user, permission); } } /// <summary> /// Resets all permission settings for a user. /// It removes all permission settings for the user. /// User will have permissions according to his roles. /// This method does not prohibit all permissions. /// For that, use <see cref="ProhibitAllPermissionsAsync"/>. /// </summary> /// <param name="user">User</param> public async Task ResetAllPermissionsAsync(TUser user) { await UserPermissionStore.RemoveAllPermissionSettingsAsync(user); } /// <summary> /// Grants a permission for a user if not already granted. /// </summary> /// <param name="user">User</param> /// <param name="permission">Permission</param> public virtual async Task GrantPermissionAsync(TUser user, Permission permission) { await UserPermissionStore.RemovePermissionAsync(user, new PermissionGrantInfo(permission.Name, false)); if (await IsGrantedAsync(user, permission)) { return; } await UserPermissionStore.AddPermissionAsync(user, new PermissionGrantInfo(permission.Name, true)); } /// <summary> /// Prohibits a permission for a user if it's granted. /// </summary> /// <param name="user">User</param> /// <param name="permission">Permission</param> public virtual async Task ProhibitPermissionAsync(TUser user, Permission permission) { await UserPermissionStore.RemovePermissionAsync(user, new PermissionGrantInfo(permission.Name, true)); if (!await IsGrantedAsync(user, permission)) { return; } await UserPermissionStore.AddPermissionAsync(user, new PermissionGrantInfo(permission.Name, false)); } public virtual async Task<TUser> FindByNameOrEmailAsync(string userNameOrEmailAddress) { return await AbpStore.FindByNameOrEmailAsync(userNameOrEmailAddress); } public virtual Task<List<TUser>> FindAllAsync(UserLoginInfo login) { return AbpStore.FindAllAsync(login); } [UnitOfWork] public virtual async Task<AbpLoginResult> LoginAsync(UserLoginInfo login, string tenancyName = null) { if (login == null || login.LoginProvider.IsNullOrEmpty() || login.ProviderKey.IsNullOrEmpty()) { throw new ArgumentException("login"); } //Get and check tenant TTenant tenant = null; if (!_multiTenancyConfig.IsEnabled) { tenant = await GetDefaultTenantAsync(); } else if (!string.IsNullOrWhiteSpace(tenancyName)) { tenant = await _tenantRepository.FirstOrDefaultAsync(t => t.TenancyName == tenancyName); if (tenant == null) { return new AbpLoginResult(AbpLoginResultType.InvalidTenancyName); } if (!tenant.IsActive) { return new AbpLoginResult(AbpLoginResultType.TenantIsNotActive); } } using (_unitOfWorkManager.Current.DisableFilter(AbpDataFilters.MayHaveTenant)) { var user = await AbpStore.FindAsync(tenant == null ? (int?)null : tenant.Id, login); if (user == null) { return new AbpLoginResult(AbpLoginResultType.UnknownExternalLogin); } return await CreateLoginResultAsync(user); } } [UnitOfWork] public virtual async Task<AbpLoginResult> LoginAsync(string userNameOrEmailAddress, string plainPassword, string tenancyName = null) { if (userNameOrEmailAddress.IsNullOrEmpty()) { throw new ArgumentNullException("userNameOrEmailAddress"); } if (plainPassword.IsNullOrEmpty()) { throw new ArgumentNullException("plainPassword"); } //Get and check tenant TTenant tenant = null; if (!_multiTenancyConfig.IsEnabled) { tenant = await GetDefaultTenantAsync(); } else if (!string.IsNullOrWhiteSpace(tenancyName)) { tenant = await _tenantRepository.FirstOrDefaultAsync(t => t.TenancyName == tenancyName); if (tenant == null) { return new AbpLoginResult(AbpLoginResultType.InvalidTenancyName); } if (!tenant.IsActive) { return new AbpLoginResult(AbpLoginResultType.TenantIsNotActive); } } using (_unitOfWorkManager.Current.DisableFilter(AbpDataFilters.MayHaveTenant)) { var loggedInFromExternalSource = await TryLoginFromExternalAuthenticationSources(userNameOrEmailAddress, plainPassword, tenant); var user = await AbpStore.FindByNameOrEmailAsync(tenant == null ? (int?)null : tenant.Id, userNameOrEmailAddress); if (user == null) { return new AbpLoginResult(AbpLoginResultType.InvalidUserNameOrEmailAddress); } if (!loggedInFromExternalSource) { var verificationResult = new PasswordHasher().VerifyHashedPassword(user.Password, plainPassword); if (verificationResult != PasswordVerificationResult.Success) { return new AbpLoginResult(AbpLoginResultType.InvalidPassword); } } return await CreateLoginResultAsync(user); } } private async Task<AbpLoginResult> CreateLoginResultAsync(TUser user) { if (!user.IsActive) { return new AbpLoginResult(AbpLoginResultType.UserIsNotActive); } if (await IsEmailConfirmationRequiredForLoginAsync(user.TenantId) && !user.IsEmailConfirmed) { return new AbpLoginResult(AbpLoginResultType.UserEmailIsNotConfirmed); } user.LastLoginTime = Clock.Now; await Store.UpdateAsync(user); await _unitOfWorkManager.Current.SaveChangesAsync(); return new AbpLoginResult(user, await CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie)); } private async Task<bool> TryLoginFromExternalAuthenticationSources(string userNameOrEmailAddress, string plainPassword, TTenant tenant) { if (!_userManagementConfig.ExternalAuthenticationSources.Any()) { return false; } foreach (var sourceType in _userManagementConfig.ExternalAuthenticationSources) { using (var source = _iocResolver.ResolveAsDisposable<IExternalAuthenticationSource<TTenant, TUser>>(sourceType)) { if (await source.Object.TryAuthenticateAsync(userNameOrEmailAddress, plainPassword, tenant)) { var tenantId = tenant == null ? (int?) null : tenant.Id; var user = await AbpStore.FindByNameOrEmailAsync(tenantId, userNameOrEmailAddress); if (user == null) { user = await source.Object.CreateUserAsync(userNameOrEmailAddress, tenant); user.Tenant = tenant; user.AuthenticationSource = source.Object.Name; user.Password = new PasswordHasher().HashPassword(Guid.NewGuid().ToString("N").Left(16)); //Setting a random password since it will not be used user.Roles = new List<UserRole>(); foreach (var defaultRole in RoleManager.Roles.Where(r => r.TenantId == tenantId && r.IsDefault).ToList()) { user.Roles.Add(new UserRole { RoleId = defaultRole.Id }); } await Store.CreateAsync(user); } else { await source.Object.UpdateUserAsync(user, tenant); user.AuthenticationSource = source.Object.Name; await Store.UpdateAsync(user); } await _unitOfWorkManager.Current.SaveChangesAsync(); return true; } } } return false; } /// <summary> /// Gets a user by given id. /// Throws exception if no user found with given id. /// </summary> /// <param name="userId">User id</param> /// <returns>User</returns> /// <exception cref="AbpException">Throws exception if no user found with given id</exception> public virtual async Task<TUser> GetUserByIdAsync(long userId) { var user = await FindByIdAsync(userId); if (user == null) { throw new AbpException("There is no user with id: " + userId); } return user; } public async override Task<ClaimsIdentity> CreateIdentityAsync(TUser user, string authenticationType) { var identity = await base.CreateIdentityAsync(user, authenticationType); if (user.TenantId.HasValue) { identity.AddClaim(new Claim(AbpClaimTypes.TenantId, user.TenantId.Value.ToString(CultureInfo.InvariantCulture))); } return identity; } public async override Task<IdentityResult> UpdateAsync(TUser user) { var result = await CheckDuplicateUsernameOrEmailAddressAsync(user.Id, user.UserName, user.EmailAddress); if (!result.Succeeded) { return result; } var oldUserName = (await GetUserByIdAsync(user.Id)).UserName; if (oldUserName == AbpUser<TTenant, TUser>.AdminUserName && user.UserName != AbpUser<TTenant, TUser>.AdminUserName) { return AbpIdentityResult.Failed(string.Format(L("CanNotRenameAdminUser"), AbpUser<TTenant, TUser>.AdminUserName)); } return await base.UpdateAsync(user); } public async override Task<IdentityResult> DeleteAsync(TUser user) { if (user.UserName == AbpUser<TTenant, TUser>.AdminUserName) { return AbpIdentityResult.Failed(string.Format(L("CanNotDeleteAdminUser"), AbpUser<TTenant, TUser>.AdminUserName)); } return await base.DeleteAsync(user); } public virtual async Task<IdentityResult> ChangePasswordAsync(TUser user, string newPassword) { var result = await PasswordValidator.ValidateAsync(newPassword); if (!result.Succeeded) { return result; } await AbpStore.SetPasswordHashAsync(user, PasswordHasher.HashPassword(newPassword)); return IdentityResult.Success; } public virtual async Task<IdentityResult> CheckDuplicateUsernameOrEmailAddressAsync(long? expectedUserId, string userName, string emailAddress) { var user = (await FindByNameAsync(userName)); if (user != null && user.Id != expectedUserId) { return AbpIdentityResult.Failed(string.Format(L("Identity.DuplicateName"), userName)); } user = (await FindByEmailAsync(emailAddress)); if (user != null && user.Id != expectedUserId) { return AbpIdentityResult.Failed(string.Format(L("Identity.DuplicateEmail"), emailAddress)); } return IdentityResult.Success; } public virtual async Task<IdentityResult> SetRoles(TUser user, string[] roleNames) { //Remove from removed roles foreach (var userRole in user.Roles.ToList()) { var role = await RoleManager.FindByIdAsync(userRole.RoleId); if (roleNames.All(roleName => role.Name != roleName)) { var result = await RemoveFromRoleAsync(user.Id, role.Name); if (!result.Succeeded) { return result; } } } //Add to added roles foreach (var roleName in roleNames) { var role = await RoleManager.GetRoleByNameAsync(roleName); if (user.Roles.All(ur => ur.RoleId != role.Id)) { var result = await AddToRoleAsync(user.Id, roleName); if (!result.Succeeded) { return result; } } } return IdentityResult.Success; } private async Task<bool> IsEmailConfirmationRequiredForLoginAsync(int? tenantId) { if (tenantId.HasValue) { return await SettingManager.GetSettingValueForTenantAsync<bool>(AbpZeroSettingNames.UserManagement.IsEmailConfirmationRequiredForLogin, tenantId.Value); } return await SettingManager.GetSettingValueForApplicationAsync<bool>(AbpZeroSettingNames.UserManagement.IsEmailConfirmationRequiredForLogin); } private async Task<TTenant> GetDefaultTenantAsync() { var tenant = await _tenantRepository.FirstOrDefaultAsync(t => t.TenancyName == AbpTenant<TTenant, TUser>.DefaultTenantName); if (tenant == null) { throw new AbpException("There should be a 'Default' tenant if multi-tenancy is disabled!"); } return tenant; } private string L(string name) { return LocalizationManager.GetString(AbpZeroConsts.LocalizationSourceName, name); } public class AbpLoginResult { public AbpLoginResultType Result { get; private set; } public TUser User { get; private set; } public ClaimsIdentity Identity { get; private set; } public AbpLoginResult(AbpLoginResultType result) { Result = result; } public AbpLoginResult(TUser user, ClaimsIdentity identity) : this(AbpLoginResultType.Success) { User = user; Identity = identity; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. #if FEATURE_COM using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq.Expressions; using System.Reflection; namespace Microsoft.Scripting.ComInterop { internal static class TypeUtils { internal const MethodAttributes PublicStatic = MethodAttributes.Public | MethodAttributes.Static; //CONFORMING internal static Type GetNonNullableType(Type type) { if (IsNullableType(type)) { return type.GetGenericArguments()[0]; } return type; } //CONFORMING internal static bool IsNullableType(this Type type) { return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>); } //CONFORMING internal static bool AreReferenceAssignable(Type dest, Type src) { // WARNING: This actually implements "Is this identity assignable and/or reference assignable?" if (dest == src) { return true; } if (!dest.IsValueType && !src.IsValueType && AreAssignable(dest, src)) { return true; } return false; } //CONFORMING internal static bool AreAssignable(Type dest, Type src) { if (dest == src) { return true; } if (dest.IsAssignableFrom(src)) { return true; } if (dest.IsArray && src.IsArray && dest.GetArrayRank() == src.GetArrayRank() && AreReferenceAssignable(dest.GetElementType(), src.GetElementType())) { return true; } if (src.IsArray && dest.IsGenericType && (dest.GetGenericTypeDefinition() == typeof(System.Collections.Generic.IEnumerable<>) || dest.GetGenericTypeDefinition() == typeof(System.Collections.Generic.IList<>) || dest.GetGenericTypeDefinition() == typeof(System.Collections.Generic.ICollection<>)) && dest.GetGenericArguments()[0] == src.GetElementType()) { return true; } return false; } //CONFORMING internal static bool IsImplicitlyConvertible(Type source, Type destination) { return IsIdentityConversion(source, destination) || IsImplicitNumericConversion(source, destination) || IsImplicitReferenceConversion(source, destination) || IsImplicitBoxingConversion(source, destination); } internal static bool IsImplicitlyConvertible(Type source, Type destination, bool considerUserDefined) { return IsImplicitlyConvertible(source, destination) || (considerUserDefined && GetUserDefinedCoercionMethod(source, destination, true) != null); } //CONFORMING internal static MethodInfo GetUserDefinedCoercionMethod(Type convertFrom, Type convertToType, bool implicitOnly) { // check for implicit coercions first Type nnExprType = TypeUtils.GetNonNullableType(convertFrom); Type nnConvType = TypeUtils.GetNonNullableType(convertToType); // try exact match on types MethodInfo[] eMethods = nnExprType.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); MethodInfo method = FindConversionOperator(eMethods, convertFrom, convertToType, implicitOnly); if (method != null) { return method; } MethodInfo[] cMethods = nnConvType.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); method = FindConversionOperator(cMethods, convertFrom, convertToType, implicitOnly); if (method != null) { return method; } // try lifted conversion if (nnExprType != convertFrom || nnConvType != convertToType) { method = FindConversionOperator(eMethods, nnExprType, nnConvType, implicitOnly); if (method == null) { method = FindConversionOperator(cMethods, nnExprType, nnConvType, implicitOnly); } if (method != null) { return method; } } return null; } //CONFORMING internal static MethodInfo FindConversionOperator(MethodInfo[] methods, Type typeFrom, Type typeTo, bool implicitOnly) { foreach (MethodInfo mi in methods) { if (mi.Name != "op_Implicit" && (implicitOnly || mi.Name != "op_Explicit")) continue; if (mi.ReturnType != typeTo) continue; ParameterInfo[] pis = mi.GetParameters(); if (pis[0].ParameterType != typeFrom) continue; return mi; } return null; } //CONFORMING private static bool IsIdentityConversion(Type source, Type destination) { return source == destination; } //CONFORMING [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] private static bool IsImplicitNumericConversion(Type source, Type destination) { TypeCode tcSource = Type.GetTypeCode(source); TypeCode tcDest = Type.GetTypeCode(destination); switch (tcSource) { case TypeCode.SByte: switch (tcDest) { case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } return false; case TypeCode.Byte: switch (tcDest) { case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } return false; case TypeCode.Int16: switch (tcDest) { case TypeCode.Int32: case TypeCode.Int64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } return false; case TypeCode.UInt16: switch (tcDest) { case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } return false; case TypeCode.Int32: switch (tcDest) { case TypeCode.Int64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } return false; case TypeCode.UInt32: switch (tcDest) { case TypeCode.UInt32: case TypeCode.UInt64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } return false; case TypeCode.Int64: case TypeCode.UInt64: switch (tcDest) { case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } return false; case TypeCode.Char: switch (tcDest) { case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } return false; case TypeCode.Single: return (tcDest == TypeCode.Double); } return false; } //CONFORMING private static bool IsImplicitReferenceConversion(Type source, Type destination) { return AreAssignable(destination, source); } //CONFORMING private static bool IsImplicitBoxingConversion(Type source, Type destination) { if (source.IsValueType && (destination == typeof(object) || destination == typeof(System.ValueType))) return true; if (source.IsEnum && destination == typeof(System.Enum)) return true; return false; } } } #endif
// 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. // // This file was autogenerated by a tool. // Do not modify it. // namespace Microsoft.Azure.Batch { using Models = Microsoft.Azure.Batch.Protocol.Models; using System; using System.Collections.Generic; using System.Linq; /// <summary> /// The specification for a pool. /// </summary> public partial class PoolSpecification : ITransportObjectProvider<Models.PoolSpecification>, IPropertyMetadata { private class PropertyContainer : PropertyCollection { public readonly PropertyAccessor<IList<string>> ApplicationLicensesProperty; public readonly PropertyAccessor<IList<ApplicationPackageReference>> ApplicationPackageReferencesProperty; public readonly PropertyAccessor<bool?> AutoScaleEnabledProperty; public readonly PropertyAccessor<TimeSpan?> AutoScaleEvaluationIntervalProperty; public readonly PropertyAccessor<string> AutoScaleFormulaProperty; public readonly PropertyAccessor<IList<CertificateReference>> CertificateReferencesProperty; public readonly PropertyAccessor<CloudServiceConfiguration> CloudServiceConfigurationProperty; public readonly PropertyAccessor<string> DisplayNameProperty; public readonly PropertyAccessor<bool?> InterComputeNodeCommunicationEnabledProperty; public readonly PropertyAccessor<int?> MaxTasksPerComputeNodeProperty; public readonly PropertyAccessor<IList<MetadataItem>> MetadataProperty; public readonly PropertyAccessor<NetworkConfiguration> NetworkConfigurationProperty; public readonly PropertyAccessor<TimeSpan?> ResizeTimeoutProperty; public readonly PropertyAccessor<StartTask> StartTaskProperty; public readonly PropertyAccessor<int?> TargetDedicatedComputeNodesProperty; public readonly PropertyAccessor<int?> TargetLowPriorityComputeNodesProperty; public readonly PropertyAccessor<TaskSchedulingPolicy> TaskSchedulingPolicyProperty; public readonly PropertyAccessor<IList<UserAccount>> UserAccountsProperty; public readonly PropertyAccessor<VirtualMachineConfiguration> VirtualMachineConfigurationProperty; public readonly PropertyAccessor<string> VirtualMachineSizeProperty; public PropertyContainer() : base(BindingState.Unbound) { this.ApplicationLicensesProperty = this.CreatePropertyAccessor<IList<string>>(nameof(ApplicationLicenses), BindingAccess.Read | BindingAccess.Write); this.ApplicationPackageReferencesProperty = this.CreatePropertyAccessor<IList<ApplicationPackageReference>>(nameof(ApplicationPackageReferences), BindingAccess.Read | BindingAccess.Write); this.AutoScaleEnabledProperty = this.CreatePropertyAccessor<bool?>(nameof(AutoScaleEnabled), BindingAccess.Read | BindingAccess.Write); this.AutoScaleEvaluationIntervalProperty = this.CreatePropertyAccessor<TimeSpan?>(nameof(AutoScaleEvaluationInterval), BindingAccess.Read | BindingAccess.Write); this.AutoScaleFormulaProperty = this.CreatePropertyAccessor<string>(nameof(AutoScaleFormula), BindingAccess.Read | BindingAccess.Write); this.CertificateReferencesProperty = this.CreatePropertyAccessor<IList<CertificateReference>>(nameof(CertificateReferences), BindingAccess.Read | BindingAccess.Write); this.CloudServiceConfigurationProperty = this.CreatePropertyAccessor<CloudServiceConfiguration>(nameof(CloudServiceConfiguration), BindingAccess.Read | BindingAccess.Write); this.DisplayNameProperty = this.CreatePropertyAccessor<string>(nameof(DisplayName), BindingAccess.Read | BindingAccess.Write); this.InterComputeNodeCommunicationEnabledProperty = this.CreatePropertyAccessor<bool?>(nameof(InterComputeNodeCommunicationEnabled), BindingAccess.Read | BindingAccess.Write); this.MaxTasksPerComputeNodeProperty = this.CreatePropertyAccessor<int?>(nameof(MaxTasksPerComputeNode), BindingAccess.Read | BindingAccess.Write); this.MetadataProperty = this.CreatePropertyAccessor<IList<MetadataItem>>(nameof(Metadata), BindingAccess.Read | BindingAccess.Write); this.NetworkConfigurationProperty = this.CreatePropertyAccessor<NetworkConfiguration>(nameof(NetworkConfiguration), BindingAccess.Read | BindingAccess.Write); this.ResizeTimeoutProperty = this.CreatePropertyAccessor<TimeSpan?>(nameof(ResizeTimeout), BindingAccess.Read | BindingAccess.Write); this.StartTaskProperty = this.CreatePropertyAccessor<StartTask>(nameof(StartTask), BindingAccess.Read | BindingAccess.Write); this.TargetDedicatedComputeNodesProperty = this.CreatePropertyAccessor<int?>(nameof(TargetDedicatedComputeNodes), BindingAccess.Read | BindingAccess.Write); this.TargetLowPriorityComputeNodesProperty = this.CreatePropertyAccessor<int?>(nameof(TargetLowPriorityComputeNodes), BindingAccess.Read | BindingAccess.Write); this.TaskSchedulingPolicyProperty = this.CreatePropertyAccessor<TaskSchedulingPolicy>(nameof(TaskSchedulingPolicy), BindingAccess.Read | BindingAccess.Write); this.UserAccountsProperty = this.CreatePropertyAccessor<IList<UserAccount>>(nameof(UserAccounts), BindingAccess.Read | BindingAccess.Write); this.VirtualMachineConfigurationProperty = this.CreatePropertyAccessor<VirtualMachineConfiguration>(nameof(VirtualMachineConfiguration), BindingAccess.Read | BindingAccess.Write); this.VirtualMachineSizeProperty = this.CreatePropertyAccessor<string>(nameof(VirtualMachineSize), BindingAccess.Read | BindingAccess.Write); } public PropertyContainer(Models.PoolSpecification protocolObject) : base(BindingState.Bound) { this.ApplicationLicensesProperty = this.CreatePropertyAccessor( UtilitiesInternal.CollectionToThreadSafeCollection(protocolObject.ApplicationLicenses, o => o), nameof(ApplicationLicenses), BindingAccess.Read | BindingAccess.Write); this.ApplicationPackageReferencesProperty = this.CreatePropertyAccessor( ApplicationPackageReference.ConvertFromProtocolCollection(protocolObject.ApplicationPackageReferences), nameof(ApplicationPackageReferences), BindingAccess.Read | BindingAccess.Write); this.AutoScaleEnabledProperty = this.CreatePropertyAccessor( protocolObject.EnableAutoScale, nameof(AutoScaleEnabled), BindingAccess.Read | BindingAccess.Write); this.AutoScaleEvaluationIntervalProperty = this.CreatePropertyAccessor( protocolObject.AutoScaleEvaluationInterval, nameof(AutoScaleEvaluationInterval), BindingAccess.Read | BindingAccess.Write); this.AutoScaleFormulaProperty = this.CreatePropertyAccessor( protocolObject.AutoScaleFormula, nameof(AutoScaleFormula), BindingAccess.Read | BindingAccess.Write); this.CertificateReferencesProperty = this.CreatePropertyAccessor( CertificateReference.ConvertFromProtocolCollection(protocolObject.CertificateReferences), nameof(CertificateReferences), BindingAccess.Read | BindingAccess.Write); this.CloudServiceConfigurationProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.CloudServiceConfiguration, o => new CloudServiceConfiguration(o)), nameof(CloudServiceConfiguration), BindingAccess.Read | BindingAccess.Write); this.DisplayNameProperty = this.CreatePropertyAccessor( protocolObject.DisplayName, nameof(DisplayName), BindingAccess.Read | BindingAccess.Write); this.InterComputeNodeCommunicationEnabledProperty = this.CreatePropertyAccessor( protocolObject.EnableInterNodeCommunication, nameof(InterComputeNodeCommunicationEnabled), BindingAccess.Read); this.MaxTasksPerComputeNodeProperty = this.CreatePropertyAccessor( protocolObject.MaxTasksPerNode, nameof(MaxTasksPerComputeNode), BindingAccess.Read | BindingAccess.Write); this.MetadataProperty = this.CreatePropertyAccessor( MetadataItem.ConvertFromProtocolCollection(protocolObject.Metadata), nameof(Metadata), BindingAccess.Read | BindingAccess.Write); this.NetworkConfigurationProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.NetworkConfiguration, o => new NetworkConfiguration(o).Freeze()), nameof(NetworkConfiguration), BindingAccess.Read); this.ResizeTimeoutProperty = this.CreatePropertyAccessor( protocolObject.ResizeTimeout, nameof(ResizeTimeout), BindingAccess.Read | BindingAccess.Write); this.StartTaskProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.StartTask, o => new StartTask(o)), nameof(StartTask), BindingAccess.Read | BindingAccess.Write); this.TargetDedicatedComputeNodesProperty = this.CreatePropertyAccessor( protocolObject.TargetDedicatedNodes, nameof(TargetDedicatedComputeNodes), BindingAccess.Read | BindingAccess.Write); this.TargetLowPriorityComputeNodesProperty = this.CreatePropertyAccessor( protocolObject.TargetLowPriorityNodes, nameof(TargetLowPriorityComputeNodes), BindingAccess.Read | BindingAccess.Write); this.TaskSchedulingPolicyProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.TaskSchedulingPolicy, o => new TaskSchedulingPolicy(o)), nameof(TaskSchedulingPolicy), BindingAccess.Read | BindingAccess.Write); this.UserAccountsProperty = this.CreatePropertyAccessor( UserAccount.ConvertFromProtocolCollection(protocolObject.UserAccounts), nameof(UserAccounts), BindingAccess.Read | BindingAccess.Write); this.VirtualMachineConfigurationProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.VirtualMachineConfiguration, o => new VirtualMachineConfiguration(o)), nameof(VirtualMachineConfiguration), BindingAccess.Read | BindingAccess.Write); this.VirtualMachineSizeProperty = this.CreatePropertyAccessor( protocolObject.VmSize, nameof(VirtualMachineSize), BindingAccess.Read | BindingAccess.Write); } } private readonly PropertyContainer propertyContainer; #region Constructors /// <summary> /// Initializes a new instance of the <see cref="PoolSpecification"/> class. /// </summary> public PoolSpecification() { this.propertyContainer = new PropertyContainer(); } internal PoolSpecification(Models.PoolSpecification protocolObject) { this.propertyContainer = new PropertyContainer(protocolObject); } #endregion Constructors #region PoolSpecification /// <summary> /// Gets or sets the list of application licenses the Batch service will make available on each compute node in the /// pool. /// </summary> /// <remarks> /// The list of application licenses must be a subset of available Batch service application licenses. /// </remarks> public IList<string> ApplicationLicenses { get { return this.propertyContainer.ApplicationLicensesProperty.Value; } set { this.propertyContainer.ApplicationLicensesProperty.Value = ConcurrentChangeTrackedList<string>.TransformEnumerableToConcurrentList(value); } } /// <summary> /// Gets or sets a list of application package references to be installed on each compute node in the pool. /// </summary> public IList<ApplicationPackageReference> ApplicationPackageReferences { get { return this.propertyContainer.ApplicationPackageReferencesProperty.Value; } set { this.propertyContainer.ApplicationPackageReferencesProperty.Value = ConcurrentChangeTrackedModifiableList<ApplicationPackageReference>.TransformEnumerableToConcurrentModifiableList(value); } } /// <summary> /// Gets or sets whether the pool size should automatically adjust over time. /// </summary> /// <remarks> /// <para>If false, one of the <see cref="TargetDedicatedComputeNodes"/> or <see cref="TargetLowPriorityComputeNodes"/> /// property is required.</para> <para>If true, the <see cref="AutoScaleFormula"/> property is required. The pool /// automatically resizes according to the formula.</para> <para>The default value is false.</para> /// </remarks> public bool? AutoScaleEnabled { get { return this.propertyContainer.AutoScaleEnabledProperty.Value; } set { this.propertyContainer.AutoScaleEnabledProperty.Value = value; } } /// <summary> /// Gets or sets a time interval at which to automatically adjust the pool size according to the <see cref="AutoScaleFormula"/>. /// </summary> /// <remarks> /// The default value is 15 minutes. The minimum allowed value is 5 minutes. /// </remarks> public TimeSpan? AutoScaleEvaluationInterval { get { return this.propertyContainer.AutoScaleEvaluationIntervalProperty.Value; } set { this.propertyContainer.AutoScaleEvaluationIntervalProperty.Value = value; } } /// <summary> /// Gets or sets a formula for the desired number of compute nodes in the pool. /// </summary> /// <remarks> /// <para>For how to write autoscale formulas, see https://azure.microsoft.com/documentation/articles/batch-automatic-scaling/. /// This property is required if <see cref="AutoScaleEnabled"/> is set to true. It must be null if AutoScaleEnabled /// is false.</para><para>The formula is checked for validity before the pool is created. If the formula is not valid, /// an exception is thrown when you try to commit the <see cref="PoolSpecification"/>.</para> /// </remarks> public string AutoScaleFormula { get { return this.propertyContainer.AutoScaleFormulaProperty.Value; } set { this.propertyContainer.AutoScaleFormulaProperty.Value = value; } } /// <summary> /// Gets or sets a list of certificates to be installed on each compute node in the pool. /// </summary> public IList<CertificateReference> CertificateReferences { get { return this.propertyContainer.CertificateReferencesProperty.Value; } set { this.propertyContainer.CertificateReferencesProperty.Value = ConcurrentChangeTrackedModifiableList<CertificateReference>.TransformEnumerableToConcurrentModifiableList(value); } } /// <summary> /// Gets or sets the <see cref="CloudServiceConfiguration"/> for the pool. /// </summary> /// <remarks> /// This property is mutually exclusive with <see cref="VirtualMachineConfiguration"/>. /// </remarks> public CloudServiceConfiguration CloudServiceConfiguration { get { return this.propertyContainer.CloudServiceConfigurationProperty.Value; } set { this.propertyContainer.CloudServiceConfigurationProperty.Value = value; } } /// <summary> /// Gets or sets the display name for the pool. /// </summary> public string DisplayName { get { return this.propertyContainer.DisplayNameProperty.Value; } set { this.propertyContainer.DisplayNameProperty.Value = value; } } /// <summary> /// Gets or sets whether the pool permits direct communication between its compute nodes. /// </summary> /// <remarks> /// Enabling inter-node communication limits the maximum size of the pool due to deployment restrictions on the nodes /// of the pool. This may result in the pool not reaching its desired size. /// </remarks> public bool? InterComputeNodeCommunicationEnabled { get { return this.propertyContainer.InterComputeNodeCommunicationEnabledProperty.Value; } set { this.propertyContainer.InterComputeNodeCommunicationEnabledProperty.Value = value; } } /// <summary> /// Gets or sets the maximum number of tasks that can run concurrently on a single compute node in the pool. /// </summary> /// <remarks> /// The default value is 1. The maximum value of this setting depends on the size of the compute nodes in the pool /// (the <see cref="VirtualMachineSize"/> property). /// </remarks> public int? MaxTasksPerComputeNode { get { return this.propertyContainer.MaxTasksPerComputeNodeProperty.Value; } set { this.propertyContainer.MaxTasksPerComputeNodeProperty.Value = value; } } /// <summary> /// Gets or sets a list of name-value pairs associated with the pool as metadata. /// </summary> public IList<MetadataItem> Metadata { get { return this.propertyContainer.MetadataProperty.Value; } set { this.propertyContainer.MetadataProperty.Value = ConcurrentChangeTrackedModifiableList<MetadataItem>.TransformEnumerableToConcurrentModifiableList(value); } } /// <summary> /// Gets or sets the network configuration of the pool. /// </summary> public NetworkConfiguration NetworkConfiguration { get { return this.propertyContainer.NetworkConfigurationProperty.Value; } set { this.propertyContainer.NetworkConfigurationProperty.Value = value; } } /// <summary> /// Gets or sets the timeout for allocation of compute nodes to the pool. /// </summary> /// <remarks> /// <para>This timeout applies only to manual scaling; it has no effect when <see cref="AutoScaleEnabled"/> is set /// to true.</para><para>The default value is 15 minutes. The minimum value is 5 minutes.</para> /// </remarks> public TimeSpan? ResizeTimeout { get { return this.propertyContainer.ResizeTimeoutProperty.Value; } set { this.propertyContainer.ResizeTimeoutProperty.Value = value; } } /// <summary> /// Gets or sets a task to run on each compute node as it joins the pool. The task runs when the node is added to /// the pool or when the node is restarted. /// </summary> public StartTask StartTask { get { return this.propertyContainer.StartTaskProperty.Value; } set { this.propertyContainer.StartTaskProperty.Value = value; } } /// <summary> /// Gets or sets the desired number of dedicated compute nodes in the pool. /// </summary> /// <remarks> /// This setting cannot be specified if <see cref="AutoScaleEnabled"/> is set to true. At least one of this property /// and <see cref="TargetLowPriorityComputeNodes"/> must be specified if <see cref="AutoScaleEnabled"/> is false. /// If not specified, the default is 0. /// </remarks> public int? TargetDedicatedComputeNodes { get { return this.propertyContainer.TargetDedicatedComputeNodesProperty.Value; } set { this.propertyContainer.TargetDedicatedComputeNodesProperty.Value = value; } } /// <summary> /// Gets or sets the desired number of low-priority compute nodes in the pool. /// </summary> /// <remarks> /// This setting cannot be specified if <see cref="AutoScaleEnabled"/> is set to true. At least one of <see cref="TargetDedicatedComputeNodes"/> /// and this property must be specified if <see cref="AutoScaleEnabled"/> is false. If not specified, the default /// is 0. /// </remarks> public int? TargetLowPriorityComputeNodes { get { return this.propertyContainer.TargetLowPriorityComputeNodesProperty.Value; } set { this.propertyContainer.TargetLowPriorityComputeNodesProperty.Value = value; } } /// <summary> /// Gets or sets how tasks are distributed among compute nodes in the pool. /// </summary> public TaskSchedulingPolicy TaskSchedulingPolicy { get { return this.propertyContainer.TaskSchedulingPolicyProperty.Value; } set { this.propertyContainer.TaskSchedulingPolicyProperty.Value = value; } } /// <summary> /// Gets or sets the list of user accounts to be created on each node in the pool. /// </summary> public IList<UserAccount> UserAccounts { get { return this.propertyContainer.UserAccountsProperty.Value; } set { this.propertyContainer.UserAccountsProperty.Value = ConcurrentChangeTrackedModifiableList<UserAccount>.TransformEnumerableToConcurrentModifiableList(value); } } /// <summary> /// Gets or sets the <see cref="VirtualMachineConfiguration"/> of the pool. /// </summary> /// <remarks> /// This property is mutually exclusive with <see cref="CloudServiceConfiguration"/>. /// </remarks> public VirtualMachineConfiguration VirtualMachineConfiguration { get { return this.propertyContainer.VirtualMachineConfigurationProperty.Value; } set { this.propertyContainer.VirtualMachineConfigurationProperty.Value = value; } } /// <summary> /// Gets or sets the size of the virtual machines in the pool. All virtual machines in a pool are the same size. /// </summary> /// <remarks> /// <para>For information about available sizes of virtual machines in pools, see Choose a VM size for compute nodes /// in an Azure Batch pool (https://docs.microsoft.com/azure/batch/batch-pool-vm-sizes).</para> /// </remarks> public string VirtualMachineSize { get { return this.propertyContainer.VirtualMachineSizeProperty.Value; } set { this.propertyContainer.VirtualMachineSizeProperty.Value = value; } } #endregion // PoolSpecification #region IPropertyMetadata bool IModifiable.HasBeenModified { get { return this.propertyContainer.HasBeenModified; } } bool IReadOnly.IsReadOnly { get { return this.propertyContainer.IsReadOnly; } set { this.propertyContainer.IsReadOnly = value; } } #endregion //IPropertyMetadata #region Internal/private methods /// <summary> /// Return a protocol object of the requested type. /// </summary> /// <returns>The protocol object of the requested type.</returns> Models.PoolSpecification ITransportObjectProvider<Models.PoolSpecification>.GetTransportObject() { Models.PoolSpecification result = new Models.PoolSpecification() { ApplicationLicenses = this.ApplicationLicenses, ApplicationPackageReferences = UtilitiesInternal.ConvertToProtocolCollection(this.ApplicationPackageReferences), EnableAutoScale = this.AutoScaleEnabled, AutoScaleEvaluationInterval = this.AutoScaleEvaluationInterval, AutoScaleFormula = this.AutoScaleFormula, CertificateReferences = UtilitiesInternal.ConvertToProtocolCollection(this.CertificateReferences), CloudServiceConfiguration = UtilitiesInternal.CreateObjectWithNullCheck(this.CloudServiceConfiguration, (o) => o.GetTransportObject()), DisplayName = this.DisplayName, EnableInterNodeCommunication = this.InterComputeNodeCommunicationEnabled, MaxTasksPerNode = this.MaxTasksPerComputeNode, Metadata = UtilitiesInternal.ConvertToProtocolCollection(this.Metadata), NetworkConfiguration = UtilitiesInternal.CreateObjectWithNullCheck(this.NetworkConfiguration, (o) => o.GetTransportObject()), ResizeTimeout = this.ResizeTimeout, StartTask = UtilitiesInternal.CreateObjectWithNullCheck(this.StartTask, (o) => o.GetTransportObject()), TargetDedicatedNodes = this.TargetDedicatedComputeNodes, TargetLowPriorityNodes = this.TargetLowPriorityComputeNodes, TaskSchedulingPolicy = UtilitiesInternal.CreateObjectWithNullCheck(this.TaskSchedulingPolicy, (o) => o.GetTransportObject()), UserAccounts = UtilitiesInternal.ConvertToProtocolCollection(this.UserAccounts), VirtualMachineConfiguration = UtilitiesInternal.CreateObjectWithNullCheck(this.VirtualMachineConfiguration, (o) => o.GetTransportObject()), VmSize = this.VirtualMachineSize, }; return result; } #endregion // Internal/private methods } }
//----------------------------------------------------------------------- // <copyright file="GraphInterpreterSpec.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using Akka.Streams.Dsl; using Akka.Streams.Implementation.Fusing; using Akka.Streams.Stage; using FluentAssertions; using Xunit; using Xunit.Abstractions; using RequestOne = Akka.Streams.Tests.Implementation.Fusing.GraphInterpreterSpecKit.TestSetup.RequestOne; using OnNext = Akka.Streams.Tests.Implementation.Fusing.GraphInterpreterSpecKit.TestSetup.OnNext; using OnComplete = Akka.Streams.Tests.Implementation.Fusing.GraphInterpreterSpecKit.TestSetup.OnComplete; namespace Akka.Streams.Tests.Implementation.Fusing { public class GraphInterpreterSpec : GraphInterpreterSpecKit { private readonly SimpleLinearGraphStage<int> _identity; private readonly Detacher<int> _detach; private readonly Zip<int, string> _zip; private readonly Broadcast<int> _broadcast; private readonly Merge<int> _merge; private readonly Balance<int> _balance; public GraphInterpreterSpec(ITestOutputHelper output = null) : base(output) { _identity = GraphStages.Identity<int>(); _detach = new Detacher<int>(); _zip = new Zip<int, string>(); _broadcast = new Broadcast<int>(2); _merge = new Merge<int>(2); _balance = new Balance<int>(2); } [Fact] public void GraphInterpreter_should_implement_identity() { WithTestSetup((setup, builder, lastEvents) => { var source = setup.NewUpstreamProbe<int>("source"); var sink = setup.NewDownstreamProbe<int>("sink"); builder(_identity) .Connect(source, _identity.Inlet) .Connect(_identity.Outlet, sink) .Init(); lastEvents().Should().BeEmpty(); sink.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne(source)); source.OnNext(1); lastEvents().Should().BeEquivalentTo(new OnNext(sink, 1)); }); } [Fact] public void GraphInterpreter_should_implement_chained_identity() { WithTestSetup((setup, lastEvents) => { var source = setup.NewUpstreamProbe<int>("source"); var sink = setup.NewDownstreamProbe<int>("sink"); // Constructing an assembly by hand and resolving ambiguities var assembly = new GraphAssembly( stages: new IGraphStageWithMaterializedValue<Shape, object>[] {_identity, _identity}, originalAttributes: new[] {Attributes.None, Attributes.None}, inlets: new Inlet[] {_identity.Inlet, _identity.Inlet, null}, inletOwners: new[] {0, 1, -1}, outlets: new Outlet[] {null, _identity.Outlet, _identity.Outlet}, outletOwners: new[] {-1, 0, 1} ); setup.ManualInit(assembly); setup.Interpreter.AttachDownstreamBoundary(2, sink); setup.Interpreter.AttachUpstreamBoundary(0, source); setup.Interpreter.Init(null); lastEvents().Should().BeEmpty(); sink.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne(source)); source.OnNext(1); lastEvents().Should().BeEquivalentTo(new OnNext(sink, 1)); }); } [Fact] public void GraphInterpreter_should_implement_detacher_stage() { WithTestSetup((setup, builder, lastEvents) => { var source = setup.NewUpstreamProbe<int>("source"); var sink = setup.NewDownstreamProbe<int>("sink"); builder(_detach) .Connect(source, _detach.Shape.Inlet) .Connect(_detach.Shape.Outlet, sink) .Init(); lastEvents().Should().BeEmpty(); sink.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne(source)); source.OnNext(1); lastEvents().Should().BeEquivalentTo(new OnNext(sink, 1), new RequestOne(source)); // Source waits source.OnNext(2); lastEvents().Should().BeEmpty(); // "PushAndPull sink.RequestOne(); lastEvents().Should().BeEquivalentTo(new OnNext(sink, 2), new RequestOne(source)); // Source waits sink.RequestOne(); lastEvents().Should().BeEmpty(); // "PushAndPull source.OnNext(3); lastEvents().Should().BeEquivalentTo(new OnNext(sink, 3), new RequestOne(source)); }); } [Fact] public void GraphInterpreter_should_implement_Zip() { WithTestSetup((setup, builder, lastEvents) => { var source1 = setup.NewUpstreamProbe<int>("source1"); var source2 = setup.NewUpstreamProbe<string>("source2"); var sink = setup.NewDownstreamProbe<Tuple<int, string>>("sink"); builder(_zip) .Connect(source1, _zip.In0) .Connect(source2, _zip.In1) .Connect(_zip.Out, sink) .Init(); lastEvents().Should().BeEmpty(); sink.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne(source1), new RequestOne(source2)); source1.OnNext(42); lastEvents().Should().BeEmpty(); source2.OnNext("Meaning of life"); lastEvents() .Should() .Equal(new OnNext(sink, new Tuple<int, string>(42, "Meaning of life")), new RequestOne(source1), new RequestOne(source2)); }); } [Fact] public void GraphInterpreter_should_implement_Broadcast() { WithTestSetup((setup, builder, lastEvents) => { var source = setup.NewUpstreamProbe<int>("source"); var sink1 = setup.NewDownstreamProbe<int>("sink1"); var sink2 = setup.NewDownstreamProbe<int>("sink2"); builder(_broadcast) .Connect(source, _broadcast.In) .Connect(_broadcast.Out(0), sink1) .Connect(_broadcast.Out(1), sink2) .Init(); lastEvents().Should().BeEmpty(); sink1.RequestOne(); lastEvents().Should().BeEmpty(); sink2.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne(source)); source.OnNext(1); lastEvents().Should().BeEquivalentTo(new OnNext(sink1, 1), new OnNext(sink2, 1)); }); } [Fact] public void GraphInterpreter_should_implement_broadcast_zip() { WithTestSetup((setup, builder, lastEvents) => { var source = setup.NewUpstreamProbe<int>("source"); var sink = setup.NewDownstreamProbe<Tuple<int, int>>("sink"); var zip = new Zip<int, int>(); builder(new IGraphStageWithMaterializedValue<Shape, object>[] {zip, _broadcast}) .Connect(source, _broadcast.In) .Connect(_broadcast.Out(0), zip.In0) .Connect(_broadcast.Out(1), zip.In1) .Connect(zip.Out, sink) .Init(); lastEvents().Should().BeEmpty(); sink.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne(source)); source.OnNext(1); lastEvents().Should().BeEquivalentTo(new OnNext(sink, new Tuple<int, int>(1, 1)), new RequestOne(source)); sink.RequestOne(); source.OnNext(2); lastEvents().Should().BeEquivalentTo(new OnNext(sink, new Tuple<int, int>(2, 2)), new RequestOne(source)); }); } [Fact] public void GraphInterpreter_should_implement_zip_broadcast() { WithTestSetup((setup, builder, lastEvents) => { var source1 = setup.NewUpstreamProbe<int>("source1"); var source2 = setup.NewUpstreamProbe<int>("source2"); var sink1 = setup.NewDownstreamProbe<Tuple<int, int>>("sink1"); var sink2 = setup.NewDownstreamProbe<Tuple<int, int>>("sink2"); var zip = new Zip<int, int>(); var broadcast = new Broadcast<Tuple<int, int>>(2); builder(new IGraphStageWithMaterializedValue<Shape, object>[] {broadcast, zip}) .Connect(source1, zip.In0) .Connect(source2, zip.In1) .Connect(zip.Out, broadcast.In) .Connect(broadcast.Out(0), sink1) .Connect(broadcast.Out(1), sink2) .Init(); lastEvents().Should().BeEmpty(); sink1.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne(source1), new RequestOne(source2)); sink2.RequestOne(); source1.OnNext(1); lastEvents().Should().BeEmpty(); source2.OnNext(2); lastEvents() .Should() .Equal(new OnNext(sink1, new Tuple<int, int>(1, 2)), new RequestOne(source1), new RequestOne(source2), new OnNext(sink2, new Tuple<int, int>(1, 2))); }); } [Fact] public void GraphInterpreter_should_implement_merge() { WithTestSetup((setup, builder, lastEvents) => { var source1 = setup.NewUpstreamProbe<int>("source1"); var source2 = setup.NewUpstreamProbe<int>("source2"); var sink = setup.NewDownstreamProbe<int>("sink"); builder(_merge) .Connect(source1, _merge.In(0)) .Connect(source2, _merge.In(1)) .Connect(_merge.Out, sink) .Init(); lastEvents().Should().BeEmpty(); sink.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne(source1), new RequestOne(source2)); source1.OnNext(1); lastEvents().Should().BeEquivalentTo(new OnNext(sink, 1), new RequestOne(source1)); source2.OnNext(2); lastEvents().Should().BeEmpty(); sink.RequestOne(); lastEvents().Should().BeEquivalentTo(new OnNext(sink, 2), new RequestOne(source2)); sink.RequestOne(); lastEvents().Should().BeEmpty(); source2.OnNext(3); lastEvents().Should().BeEquivalentTo(new OnNext(sink, 3), new RequestOne(source2)); sink.RequestOne(); lastEvents().Should().BeEmpty(); source1.OnNext(4); lastEvents().Should().BeEquivalentTo(new OnNext(sink, 4), new RequestOne(source1)); }); } [Fact] public void GraphInterpreter_should_implement_balance() { WithTestSetup((setup, builder, lastEvents) => { var source = setup.NewUpstreamProbe<int>("source"); var sink1 = setup.NewDownstreamProbe<int>("sink1"); var sink2 = setup.NewDownstreamProbe<int>("sink2"); builder(_balance) .Connect(source, _balance.In) .Connect(_balance.Out(0), sink1) .Connect(_balance.Out(1), sink2) .Init(); lastEvents().Should().BeEmpty(); sink1.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne(source)); sink2.RequestOne(); lastEvents().Should().BeEmpty(); source.OnNext(1); lastEvents().Should().BeEquivalentTo(new OnNext(sink1, 1), new RequestOne(source)); source.OnNext(2); lastEvents().Should().BeEquivalentTo(new OnNext(sink2, 2)); }); } [Fact] public void GraphInterpreter_should_implement_non_divergent_cycle() { WithTestSetup((setup, builder, lastEvents) => { var source = setup.NewUpstreamProbe<int>("source"); var sink = setup.NewDownstreamProbe<int>("sink"); builder(new IGraphStageWithMaterializedValue<Shape, object>[] { _merge, _balance }) .Connect(source, _merge.In(0)) .Connect(_merge.Out, _balance.In) .Connect(_balance.Out(0), sink) .Connect(_balance.Out(1), _merge.In(1)) .Init(); lastEvents().Should().BeEmpty(); sink.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne(source)); source.OnNext(1); lastEvents().Should().BeEquivalentTo(new RequestOne(source), new OnNext(sink, 1)); // Token enters merge-balance cycle and gets stuck source.OnNext(2); lastEvents().Should().BeEquivalentTo(new RequestOne(source)); // Unstuck it sink.RequestOne(); lastEvents().Should().BeEquivalentTo(new OnNext(sink, 2)); }); } [Fact] public void GraphInterpreter_should_implement_divergent_cycle() { WithTestSetup((setup, builder, lastEvents) => { var source = setup.NewUpstreamProbe<int>("source"); var sink = setup.NewDownstreamProbe<int>("sink"); builder(new IGraphStageWithMaterializedValue<Shape, object>[] { _detach, _balance, _merge }) .Connect(source, _merge.In(0)) .Connect(_merge.Out, _balance.In) .Connect(_balance.Out(0), sink) .Connect(_balance.Out(1), _detach.Shape.Inlet) .Connect(_detach.Shape.Outlet, _merge.In(1)) .Init(); lastEvents().Should().BeEmpty(); sink.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne(source)); source.OnNext(1); lastEvents().Should().BeEquivalentTo(new RequestOne(source), new OnNext(sink, 1)); // Token enters merge-balance cycle and spins until event limit // Without the limit this would spin forever (where forever = int.MaxValue iterations) source.OnNext(2, eventLimit: 1000); lastEvents().Should().BeEquivalentTo(new RequestOne(source)); // The cycle is still alive and kicking, just suspended due to the event limit setup.Interpreter.IsSuspended.Should().BeTrue(); // Do to the fairness properties of both the interpreter event queue and the balance stage // the element will eventually leave the cycle and reaches the sink. // This should not hang even though we do not have an event limit set sink.RequestOne(); lastEvents().Should().BeEquivalentTo(new OnNext(sink, 2)); // The cycle is now empty setup.Interpreter.IsSuspended.Should().BeFalse(); }); } [Fact] public void GraphInterpreter_should_implement_buffer() { WithTestSetup((setup, builder, lastEvents) => { var source = setup.NewUpstreamProbe<string>("source"); var sink = setup.NewDownstreamProbe<string>("sink"); var buffer = new Buffer<string>(2, OverflowStrategy.Backpressure); builder(buffer) .Connect(source, buffer.Inlet) .Connect(buffer.Outlet, sink) .Init(); setup.StepAll(); lastEvents().Should().BeEquivalentTo(new RequestOne(source)); sink.RequestOne(); lastEvents().Should().BeEmpty(); source.OnNext("A"); lastEvents().Should().BeEquivalentTo(new OnNext(sink, "A"), new RequestOne(source)); source.OnNext("B"); lastEvents().Should().BeEquivalentTo(new RequestOne(source)); source.OnNext("C", eventLimit: 0); sink.RequestOne(); lastEvents().Should().BeEquivalentTo(new OnNext(sink, "B"), new RequestOne(source)); sink.RequestOne(eventLimit: 0); source.OnComplete(eventLimit: 3); // OnComplete arrives early due to push chasing lastEvents().Should().BeEquivalentTo(new OnNext(sink, "C"), new OnComplete(sink)); }); } } }
/* * 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 Apache.Ignite.Core.Impl.Binary { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Apache.Ignite.Core.Impl.Binary.IO; using Apache.Ignite.Core.Impl.Common; /** * <summary>Collection of predefined handlers for various system types.</summary> */ internal static class BinarySystemHandlers { /** Write handlers. */ private static readonly CopyOnWriteConcurrentDictionary<Type, BinarySystemWriteHandler> WriteHandlers = new CopyOnWriteConcurrentDictionary<Type, BinarySystemWriteHandler>(); /** Read handlers. */ private static readonly IBinarySystemReader[] ReadHandlers = new IBinarySystemReader[255]; /** Type ids. */ private static readonly Dictionary<Type, byte> TypeIds = new Dictionary<Type, byte> { {typeof (bool), BinaryUtils.TypeBool}, {typeof (byte), BinaryUtils.TypeByte}, {typeof (sbyte), BinaryUtils.TypeByte}, {typeof (short), BinaryUtils.TypeShort}, {typeof (ushort), BinaryUtils.TypeShort}, {typeof (char), BinaryUtils.TypeChar}, {typeof (int), BinaryUtils.TypeInt}, {typeof (uint), BinaryUtils.TypeInt}, {typeof (long), BinaryUtils.TypeLong}, {typeof (ulong), BinaryUtils.TypeLong}, {typeof (float), BinaryUtils.TypeFloat}, {typeof (double), BinaryUtils.TypeDouble}, {typeof (string), BinaryUtils.TypeString}, {typeof (decimal), BinaryUtils.TypeDecimal}, {typeof (Guid), BinaryUtils.TypeGuid}, {typeof (Guid?), BinaryUtils.TypeGuid}, {typeof (ArrayList), BinaryUtils.TypeCollection}, {typeof (Hashtable), BinaryUtils.TypeDictionary}, {typeof (bool[]), BinaryUtils.TypeArrayBool}, {typeof (byte[]), BinaryUtils.TypeArrayByte}, {typeof (sbyte[]), BinaryUtils.TypeArrayByte}, {typeof (short[]), BinaryUtils.TypeArrayShort}, {typeof (ushort[]), BinaryUtils.TypeArrayShort}, {typeof (char[]), BinaryUtils.TypeArrayChar}, {typeof (int[]), BinaryUtils.TypeArrayInt}, {typeof (uint[]), BinaryUtils.TypeArrayInt}, {typeof (long[]), BinaryUtils.TypeArrayLong}, {typeof (ulong[]), BinaryUtils.TypeArrayLong}, {typeof (float[]), BinaryUtils.TypeArrayFloat}, {typeof (double[]), BinaryUtils.TypeArrayDouble}, {typeof (string[]), BinaryUtils.TypeArrayString}, {typeof (decimal?[]), BinaryUtils.TypeArrayDecimal}, {typeof (Guid?[]), BinaryUtils.TypeArrayGuid}, {typeof (object[]), BinaryUtils.TypeArray} }; /// <summary> /// Initializes the <see cref="BinarySystemHandlers"/> class. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = "Readability.")] static BinarySystemHandlers() { // 1. Primitives. ReadHandlers[BinaryUtils.TypeBool] = new BinarySystemReader<bool>(s => s.ReadBool()); ReadHandlers[BinaryUtils.TypeByte] = new BinarySystemReader<byte>(s => s.ReadByte()); ReadHandlers[BinaryUtils.TypeShort] = new BinarySystemReader<short>(s => s.ReadShort()); ReadHandlers[BinaryUtils.TypeChar] = new BinarySystemReader<char>(s => s.ReadChar()); ReadHandlers[BinaryUtils.TypeInt] = new BinarySystemReader<int>(s => s.ReadInt()); ReadHandlers[BinaryUtils.TypeLong] = new BinarySystemReader<long>(s => s.ReadLong()); ReadHandlers[BinaryUtils.TypeFloat] = new BinarySystemReader<float>(s => s.ReadFloat()); ReadHandlers[BinaryUtils.TypeDouble] = new BinarySystemReader<double>(s => s.ReadDouble()); ReadHandlers[BinaryUtils.TypeDecimal] = new BinarySystemReader<decimal?>(BinaryUtils.ReadDecimal); // 2. Date. ReadHandlers[BinaryUtils.TypeTimestamp] = new BinarySystemReader<DateTime?>(BinaryUtils.ReadTimestamp); // 3. String. ReadHandlers[BinaryUtils.TypeString] = new BinarySystemReader<string>(BinaryUtils.ReadString); // 4. Guid. ReadHandlers[BinaryUtils.TypeGuid] = new BinarySystemReader<Guid?>(s => BinaryUtils.ReadGuid(s)); // 5. Primitive arrays. ReadHandlers[BinaryUtils.TypeArrayBool] = new BinarySystemReader<bool[]>(BinaryUtils.ReadBooleanArray); ReadHandlers[BinaryUtils.TypeArrayByte] = new BinarySystemDualReader<byte[], sbyte[]>(BinaryUtils.ReadByteArray, BinaryUtils.ReadSbyteArray); ReadHandlers[BinaryUtils.TypeArrayShort] = new BinarySystemDualReader<short[], ushort[]>(BinaryUtils.ReadShortArray, BinaryUtils.ReadUshortArray); ReadHandlers[BinaryUtils.TypeArrayChar] = new BinarySystemReader<char[]>(BinaryUtils.ReadCharArray); ReadHandlers[BinaryUtils.TypeArrayInt] = new BinarySystemDualReader<int[], uint[]>(BinaryUtils.ReadIntArray, BinaryUtils.ReadUintArray); ReadHandlers[BinaryUtils.TypeArrayLong] = new BinarySystemDualReader<long[], ulong[]>(BinaryUtils.ReadLongArray, BinaryUtils.ReadUlongArray); ReadHandlers[BinaryUtils.TypeArrayFloat] = new BinarySystemReader<float[]>(BinaryUtils.ReadFloatArray); ReadHandlers[BinaryUtils.TypeArrayDouble] = new BinarySystemReader<double[]>(BinaryUtils.ReadDoubleArray); ReadHandlers[BinaryUtils.TypeArrayDecimal] = new BinarySystemReader<decimal?[]>(BinaryUtils.ReadDecimalArray); // 6. Date array. ReadHandlers[BinaryUtils.TypeArrayTimestamp] = new BinarySystemReader<DateTime?[]>(BinaryUtils.ReadTimestampArray); // 7. String array. ReadHandlers[BinaryUtils.TypeArrayString] = new BinarySystemTypedArrayReader<string>(); // 8. Guid array. ReadHandlers[BinaryUtils.TypeArrayGuid] = new BinarySystemTypedArrayReader<Guid?>(); // 9. Array. ReadHandlers[BinaryUtils.TypeArray] = new BinarySystemReader(ReadArray); // 11. Arbitrary collection. ReadHandlers[BinaryUtils.TypeCollection] = new BinarySystemReader(ReadCollection); // 13. Arbitrary dictionary. ReadHandlers[BinaryUtils.TypeDictionary] = new BinarySystemReader(ReadDictionary); // 14. Enum. ReadHandlers[BinaryUtils.TypeArrayEnum] = new BinarySystemReader(ReadEnumArray); } /// <summary> /// Try getting write handler for type. /// </summary> /// <param name="type"></param> /// <returns></returns> public static BinarySystemWriteHandler GetWriteHandler(Type type) { return WriteHandlers.GetOrAdd(type, t => { bool supportsHandles; var handler = FindWriteHandler(t, out supportsHandles); return handler == null ? null : new BinarySystemWriteHandler(handler, supportsHandles); }); } /// <summary> /// Find write handler for type. /// </summary> /// <param name="type">Type.</param> /// <param name="supportsHandles">Flag indicating whether returned delegate supports handles.</param> /// <returns> /// Write handler or NULL. /// </returns> private static Action<BinaryWriter, object> FindWriteHandler(Type type, out bool supportsHandles) { supportsHandles = false; // 1. Well-known types. if (type == typeof(string)) return WriteString; if (type == typeof(decimal)) return WriteDecimal; if (type == typeof(Guid)) return WriteGuid; if (type == typeof (BinaryObject)) return WriteBinary; if (type == typeof (BinaryEnum)) return WriteBinaryEnum; if (type.IsEnum) return WriteEnum; if (type == typeof(Ignite)) return WriteIgnite; // All types below can be written as handles. supportsHandles = true; if (type == typeof (ArrayList)) return WriteArrayList; if (type == typeof (Hashtable)) return WriteHashtable; if (type.IsArray) { // We know how to write any array type. Type elemType = type.GetElementType(); // Primitives. if (elemType == typeof (bool)) return WriteBoolArray; if (elemType == typeof(byte)) return WriteByteArray; if (elemType == typeof(short)) return WriteShortArray; if (elemType == typeof(char)) return WriteCharArray; if (elemType == typeof(int)) return WriteIntArray; if (elemType == typeof(long)) return WriteLongArray; if (elemType == typeof(float)) return WriteFloatArray; if (elemType == typeof(double)) return WriteDoubleArray; // Non-CLS primitives. if (elemType == typeof(sbyte)) return WriteSbyteArray; if (elemType == typeof(ushort)) return WriteUshortArray; if (elemType == typeof(uint)) return WriteUintArray; if (elemType == typeof(ulong)) return WriteUlongArray; // Special types. if (elemType == typeof (decimal?)) return WriteDecimalArray; if (elemType == typeof(string)) return WriteStringArray; if (elemType == typeof(Guid?)) return WriteGuidArray; // Enums. if (elemType.IsEnum || elemType == typeof(BinaryEnum)) return WriteEnumArray; // Object array. return WriteArray; } return null; } /// <summary> /// Find write handler for type. /// </summary> /// <param name="type">Type.</param> /// <returns>Write handler or NULL.</returns> public static byte GetTypeId(Type type) { byte res; if (TypeIds.TryGetValue(type, out res)) return res; if (type.IsEnum) return BinaryUtils.TypeEnum; if (type.IsArray && type.GetElementType().IsEnum) return BinaryUtils.TypeArrayEnum; return BinaryUtils.TypeObject; } /// <summary> /// Reads an object of predefined type. /// </summary> public static bool TryReadSystemType<T>(byte typeId, BinaryReader ctx, out T res) { var handler = ReadHandlers[typeId]; if (handler == null) { res = default(T); return false; } res = handler.Read<T>(ctx); return true; } /// <summary> /// Write decimal. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteDecimal(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeDecimal); BinaryUtils.WriteDecimal((decimal)obj, ctx.Stream); } /// <summary> /// Write string. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Object.</param> private static void WriteString(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeString); BinaryUtils.WriteString((string)obj, ctx.Stream); } /// <summary> /// Write Guid. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteGuid(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeGuid); BinaryUtils.WriteGuid((Guid)obj, ctx.Stream); } /// <summary> /// Write boolaen array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteBoolArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayBool); BinaryUtils.WriteBooleanArray((bool[])obj, ctx.Stream); } /// <summary> /// Write byte array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteByteArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayByte); BinaryUtils.WriteByteArray((byte[])obj, ctx.Stream); } /// <summary> /// Write sbyte array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteSbyteArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayByte); BinaryUtils.WriteByteArray((byte[]) obj, ctx.Stream); } /// <summary> /// Write short array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteShortArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayShort); BinaryUtils.WriteShortArray((short[])obj, ctx.Stream); } /// <summary> /// Write ushort array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteUshortArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayShort); BinaryUtils.WriteShortArray((short[]) obj, ctx.Stream); } /// <summary> /// Write char array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteCharArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayChar); BinaryUtils.WriteCharArray((char[])obj, ctx.Stream); } /// <summary> /// Write int array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteIntArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayInt); BinaryUtils.WriteIntArray((int[])obj, ctx.Stream); } /// <summary> /// Write uint array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteUintArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayInt); BinaryUtils.WriteIntArray((int[]) obj, ctx.Stream); } /// <summary> /// Write long array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteLongArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayLong); BinaryUtils.WriteLongArray((long[])obj, ctx.Stream); } /// <summary> /// Write ulong array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteUlongArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayLong); BinaryUtils.WriteLongArray((long[]) obj, ctx.Stream); } /// <summary> /// Write float array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteFloatArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayFloat); BinaryUtils.WriteFloatArray((float[])obj, ctx.Stream); } /// <summary> /// Write double array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteDoubleArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayDouble); BinaryUtils.WriteDoubleArray((double[])obj, ctx.Stream); } /// <summary> /// Write decimal array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteDecimalArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayDecimal); BinaryUtils.WriteDecimalArray((decimal?[])obj, ctx.Stream); } /// <summary> /// Write string array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteStringArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayString); BinaryUtils.WriteStringArray((string[])obj, ctx.Stream); } /// <summary> /// Write nullable GUID array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteGuidArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayGuid); BinaryUtils.WriteGuidArray((Guid?[])obj, ctx.Stream); } /// <summary> /// Writes the enum array. /// </summary> private static void WriteEnumArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayEnum); BinaryUtils.WriteArray((Array) obj, ctx); } /// <summary> /// Writes the array. /// </summary> private static void WriteArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArray); BinaryUtils.WriteArray((Array) obj, ctx); } /** * <summary>Write ArrayList.</summary> */ private static void WriteArrayList(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeCollection); BinaryUtils.WriteCollection((ICollection)obj, ctx, BinaryUtils.CollectionArrayList); } /** * <summary>Write Hashtable.</summary> */ private static void WriteHashtable(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeDictionary); BinaryUtils.WriteDictionary((IDictionary)obj, ctx, BinaryUtils.MapHashMap); } /** * <summary>Write binary object.</summary> */ private static void WriteBinary(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeBinary); BinaryUtils.WriteBinary(ctx.Stream, (BinaryObject)obj); } /// <summary> /// Write enum. /// </summary> private static void WriteEnum(BinaryWriter ctx, object obj) { ctx.WriteEnum(obj); } /// <summary> /// Write enum. /// </summary> private static void WriteBinaryEnum(BinaryWriter ctx, object obj) { var binEnum = (BinaryEnum) obj; ctx.Stream.WriteByte(BinaryUtils.TypeEnum); ctx.WriteInt(binEnum.TypeId); ctx.WriteInt(binEnum.EnumValue); } /** * <summary>Read enum array.</summary> */ private static object ReadEnumArray(BinaryReader ctx, Type type) { var elemType = type.GetElementType() ?? typeof(object); return BinaryUtils.ReadTypedArray(ctx, true, elemType); } /// <summary> /// Reads the array. /// </summary> private static object ReadArray(BinaryReader ctx, Type type) { var elemType = type.GetElementType(); if (elemType == null) { if (ctx.Mode == BinaryMode.ForceBinary) { // Forced binary mode: use object because primitives are not represented as IBinaryObject. elemType = typeof(object); } else { // Infer element type from typeId. var typeId = ctx.ReadInt(); if (typeId != BinaryUtils.ObjTypeId) { elemType = ctx.Marshaller.GetDescriptor(true, typeId, true).Type; } return BinaryUtils.ReadTypedArray(ctx, false, elemType ?? typeof(object)); } } // Element type is known, no need to check typeId. // In case of incompatible types we'll get exception either way. return BinaryUtils.ReadTypedArray(ctx, true, elemType); } /** * <summary>Read collection.</summary> */ private static object ReadCollection(BinaryReader ctx, Type type) { return BinaryUtils.ReadCollection(ctx, null, null); } /** * <summary>Read dictionary.</summary> */ private static object ReadDictionary(BinaryReader ctx, Type type) { return BinaryUtils.ReadDictionary(ctx, null); } /// <summary> /// Write Ignite. /// </summary> private static void WriteIgnite(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.HdrNull); } /** * <summary>Read delegate.</summary> * <param name="ctx">Read context.</param> * <param name="type">Type.</param> */ private delegate object BinarySystemReadDelegate(BinaryReader ctx, Type type); /// <summary> /// System type reader. /// </summary> private interface IBinarySystemReader { /// <summary> /// Reads a value of specified type from reader. /// </summary> T Read<T>(BinaryReader ctx); } /// <summary> /// System type generic reader. /// </summary> private interface IBinarySystemReader<out T> { /// <summary> /// Reads a value of specified type from reader. /// </summary> T Read(BinaryReader ctx); } /// <summary> /// Default reader with boxing. /// </summary> private class BinarySystemReader : IBinarySystemReader { /** */ private readonly BinarySystemReadDelegate _readDelegate; /// <summary> /// Initializes a new instance of the <see cref="BinarySystemReader"/> class. /// </summary> /// <param name="readDelegate">The read delegate.</param> public BinarySystemReader(BinarySystemReadDelegate readDelegate) { Debug.Assert(readDelegate != null); _readDelegate = readDelegate; } /** <inheritdoc /> */ public T Read<T>(BinaryReader ctx) { return (T)_readDelegate(ctx, typeof(T)); } } /// <summary> /// Reader without boxing. /// </summary> private class BinarySystemReader<T> : IBinarySystemReader { /** */ private readonly Func<IBinaryStream, T> _readDelegate; /// <summary> /// Initializes a new instance of the <see cref="BinarySystemReader{T}"/> class. /// </summary> /// <param name="readDelegate">The read delegate.</param> public BinarySystemReader(Func<IBinaryStream, T> readDelegate) { Debug.Assert(readDelegate != null); _readDelegate = readDelegate; } /** <inheritdoc /> */ public TResult Read<TResult>(BinaryReader ctx) { return TypeCaster<TResult>.Cast(_readDelegate(ctx.Stream)); } } /// <summary> /// Reader without boxing. /// </summary> private class BinarySystemTypedArrayReader<T> : IBinarySystemReader { public TResult Read<TResult>(BinaryReader ctx) { return TypeCaster<TResult>.Cast(BinaryUtils.ReadArray<T>(ctx, false)); } } /// <summary> /// Reader with selection based on requested type. /// </summary> private class BinarySystemDualReader<T1, T2> : IBinarySystemReader, IBinarySystemReader<T2> { /** */ private readonly Func<IBinaryStream, T1> _readDelegate1; /** */ private readonly Func<IBinaryStream, T2> _readDelegate2; /// <summary> /// Initializes a new instance of the <see cref="BinarySystemDualReader{T1,T2}"/> class. /// </summary> /// <param name="readDelegate1">The read delegate1.</param> /// <param name="readDelegate2">The read delegate2.</param> public BinarySystemDualReader(Func<IBinaryStream, T1> readDelegate1, Func<IBinaryStream, T2> readDelegate2) { Debug.Assert(readDelegate1 != null); Debug.Assert(readDelegate2 != null); _readDelegate1 = readDelegate1; _readDelegate2 = readDelegate2; } /** <inheritdoc /> */ [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")] T2 IBinarySystemReader<T2>.Read(BinaryReader ctx) { return _readDelegate2(ctx.Stream); } /** <inheritdoc /> */ public T Read<T>(BinaryReader ctx) { // Can't use "as" because of variance. // For example, IBinarySystemReader<byte[]> can be cast to IBinarySystemReader<sbyte[]>, which // will cause incorrect behavior. if (typeof (T) == typeof (T2)) return ((IBinarySystemReader<T>) this).Read(ctx); return TypeCaster<T>.Cast(_readDelegate1(ctx.Stream)); } } } /// <summary> /// Write delegate + handles flag. /// </summary> internal class BinarySystemWriteHandler { /** */ private readonly Action<BinaryWriter, object> _writeAction; /** */ private readonly bool _supportsHandles; /// <summary> /// Initializes a new instance of the <see cref="BinarySystemWriteHandler" /> class. /// </summary> /// <param name="writeAction">The write action.</param> /// <param name="supportsHandles">Handles flag.</param> public BinarySystemWriteHandler(Action<BinaryWriter, object> writeAction, bool supportsHandles) { Debug.Assert(writeAction != null); _writeAction = writeAction; _supportsHandles = supportsHandles; } /// <summary> /// Writes object to a specified writer. /// </summary> /// <param name="writer">The writer.</param> /// <param name="obj">The object.</param> public void Write(BinaryWriter writer, object obj) { _writeAction(writer, obj); } /// <summary> /// Gets a value indicating whether this handler supports handles. /// </summary> public bool SupportsHandles { get { return _supportsHandles; } } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using NonSilo.Tests.Utilities; using NSubstitute; using Orleans; using Orleans.Configuration; using Orleans.Runtime; using Orleans.Runtime.MembershipService; using TestExtensions; using Xunit; using Xunit.Abstractions; namespace NonSilo.Tests.Membership { [TestCategory("BVT"), TestCategory("Membership")] public class ClusterHealthMonitorTests { private readonly ITestOutputHelper output; private readonly LoggerFactory loggerFactory; private readonly ILocalSiloDetails localSiloDetails; private readonly SiloAddress localSilo; private readonly IFatalErrorHandler fatalErrorHandler; private readonly IMembershipGossiper membershipGossiper; private readonly SiloLifecycleSubject lifecycle; private readonly List<DelegateAsyncTimer> timers; private readonly ConcurrentQueue<(TimeSpan? DelayOverride, TaskCompletionSource<bool> Completion)> timerCalls; private readonly DelegateAsyncTimerFactory timerFactory; private readonly IRemoteSiloProber prober; private readonly InMemoryMembershipTable membershipTable; private readonly MembershipTableManager manager; public ClusterHealthMonitorTests(ITestOutputHelper output) { MessagingStatisticsGroup.Init(); this.output = output; this.loggerFactory = new LoggerFactory(new[] { new XunitLoggerProvider(this.output) }); this.localSiloDetails = Substitute.For<ILocalSiloDetails>(); this.localSilo = Silo("127.0.0.1:100@100"); this.localSiloDetails.SiloAddress.Returns(this.localSilo); this.localSiloDetails.DnsHostName.Returns("MyServer11"); this.localSiloDetails.Name.Returns(Guid.NewGuid().ToString("N")); this.fatalErrorHandler = Substitute.For<IFatalErrorHandler>(); this.membershipGossiper = Substitute.For<IMembershipGossiper>(); this.lifecycle = new SiloLifecycleSubject(this.loggerFactory.CreateLogger<SiloLifecycleSubject>()); this.timers = new List<DelegateAsyncTimer>(); this.timerCalls = new ConcurrentQueue<(TimeSpan? DelayOverride, TaskCompletionSource<bool> Completion)>(); this.timerFactory = new DelegateAsyncTimerFactory( (period, name) => { var t = new DelegateAsyncTimer( overridePeriod => { var task = new TaskCompletionSource<bool>(); this.timerCalls.Enqueue((overridePeriod, task)); return task.Task; }); this.timers.Add(t); return t; }); this.prober = Substitute.For<IRemoteSiloProber>(); this.membershipTable = new InMemoryMembershipTable(new TableVersion(1, "1")); this.manager = new MembershipTableManager( localSiloDetails: this.localSiloDetails, clusterMembershipOptions: Options.Create(new ClusterMembershipOptions()), membershipTable: membershipTable, fatalErrorHandler: this.fatalErrorHandler, gossiper: this.membershipGossiper, log: this.loggerFactory.CreateLogger<MembershipTableManager>(), timerFactory: new AsyncTimerFactory(this.loggerFactory), this.lifecycle); ((ILifecycleParticipant<ISiloLifecycle>)this.manager).Participate(this.lifecycle); } /// <summary> /// Tests basic operation of <see cref="ClusterHealthMonitor"/> and <see cref="SiloHealthMonitor"/>. /// </summary> [Fact] public async Task ClusterHealthMonitor_BasicScenario() { var probeCalls = new ConcurrentQueue<(SiloAddress, int)>(); this.prober.Probe(default, default).ReturnsForAnyArgs(info => { probeCalls.Enqueue((info.ArgAt<SiloAddress>(0), info.ArgAt<int>(1))); return Task.CompletedTask; }); var clusterMembershipOptions = new ClusterMembershipOptions(); var monitor = new ClusterHealthMonitor( this.localSiloDetails, this.manager, this.loggerFactory.CreateLogger<ClusterHealthMonitor>(), Options.Create(clusterMembershipOptions), this.fatalErrorHandler, null, this.timerFactory); ((ILifecycleParticipant<ISiloLifecycle>)monitor).Participate(this.lifecycle); var testAccessor = (ClusterHealthMonitor.ITestAccessor)monitor; testAccessor.CreateMonitor = s => new SiloHealthMonitor(s, this.loggerFactory, this.prober); await this.lifecycle.OnStart(); Assert.NotEmpty(this.timers); Assert.Empty(testAccessor.MonitoredSilos); var otherSilos = new[] { Entry(Silo("127.0.0.200:100@100"), SiloStatus.Active), Entry(Silo("127.0.0.200:200@100"), SiloStatus.Active), Entry(Silo("127.0.0.200:300@100"), SiloStatus.Active), Entry(Silo("127.0.0.200:400@100"), SiloStatus.Active), Entry(Silo("127.0.0.200:500@100"), SiloStatus.Active), Entry(Silo("127.0.0.200:600@100"), SiloStatus.Active), Entry(Silo("127.0.0.200:700@100"), SiloStatus.Active), Entry(Silo("127.0.0.200:800@100"), SiloStatus.Active), Entry(Silo("127.0.0.200:900@100"), SiloStatus.Active) }; var lastVersion = testAccessor.ObservedVersion; // Add the new silos foreach (var entry in otherSilos) { var table = await this.membershipTable.ReadAll(); Assert.True(await this.membershipTable.InsertRow(entry, table.Version.Next())); } await this.manager.Refresh(); (TimeSpan? DelayOverride, TaskCompletionSource<bool> Completion) timer = (default, default); while (!this.timerCalls.TryDequeue(out timer)) await Task.Delay(1); timer.Completion.TrySetResult(true); await Until(() => testAccessor.ObservedVersion > lastVersion); lastVersion = testAccessor.ObservedVersion; // No silos should be monitored by this silo until it becomes active. Assert.Empty(testAccessor.MonitoredSilos); await this.manager.UpdateStatus(SiloStatus.Active); await Until(() => testAccessor.ObservedVersion > lastVersion); lastVersion = testAccessor.ObservedVersion; // Now that this silo is active, it should be monitoring some fraction of the other active silos Assert.NotEmpty(testAccessor.MonitoredSilos); Assert.DoesNotContain(testAccessor.MonitoredSilos, s => s.Key.Equals(this.localSilo)); Assert.Equal(clusterMembershipOptions.NumProbedSilos, testAccessor.MonitoredSilos.Count); Assert.All(testAccessor.MonitoredSilos, m => m.Key.Equals(m.Value.SiloAddress)); Assert.Empty(probeCalls); // Check that those silos are actually being probed periodically while (!this.timerCalls.TryDequeue(out timer)) await Task.Delay(1); timer.Completion.TrySetResult(true); await Until(() => probeCalls.Count == clusterMembershipOptions.NumProbedSilos); Assert.Equal(clusterMembershipOptions.NumProbedSilos, probeCalls.Count); while (probeCalls.TryDequeue(out var call)) Assert.Contains(testAccessor.MonitoredSilos, k => k.Key.Equals(call.Item1)); foreach (var siloMonitor in testAccessor.MonitoredSilos.Values) { Assert.Equal(0, ((SiloHealthMonitor.ITestAccessor)siloMonitor).MissedProbes); } // Make the probes fail. this.prober.Probe(default, default).ReturnsForAnyArgs(info => { probeCalls.Enqueue((info.ArgAt<SiloAddress>(0), info.ArgAt<int>(1))); return Task.FromException(new Exception("no")); }); // The above call to specify the probe behaviour also enqueued a value, so clear it here. while (probeCalls.TryDequeue(out _)) ; for (var expectedMissedProbes = 1; expectedMissedProbes <= clusterMembershipOptions.NumMissedProbesLimit; expectedMissedProbes++) { var now = DateTime.UtcNow; this.membershipTable.ClearCalls(); while (!this.timerCalls.TryDequeue(out timer)) await Task.Delay(1); timer.Completion.TrySetResult(true); // Wait for probes to be fired await Until(() => probeCalls.Count == clusterMembershipOptions.NumProbedSilos); while (probeCalls.TryDequeue(out var call)) ; // Check that probes match the expected missed probes var table = await this.membershipTable.ReadAll(); foreach (var siloMonitor in testAccessor.MonitoredSilos.Values) { Assert.Equal(expectedMissedProbes, ((SiloHealthMonitor.ITestAccessor)siloMonitor).MissedProbes); var entry = table.Members.Single(m => m.Item1.SiloAddress.Equals(siloMonitor.SiloAddress)).Item1; var votes = entry.GetFreshVotes(now, clusterMembershipOptions.DeathVoteExpirationTimeout); if (expectedMissedProbes < clusterMembershipOptions.NumMissedProbesLimit) { Assert.Empty(votes); } else { // After a certain number of failures, a vote should be added to the table. Assert.Single(votes); } } } // Make the probes succeed again. this.prober.Probe(default, default).ReturnsForAnyArgs(info => { probeCalls.Enqueue((info.ArgAt<SiloAddress>(0), info.ArgAt<int>(1))); return Task.CompletedTask; }); // The above call to specify the probe behaviour also enqueued a value, so clear it here. while (probeCalls.TryDequeue(out _)) ; while (!this.timerCalls.TryDequeue(out timer)) await Task.Delay(1); timer.Completion.TrySetResult(true); // Wait for probes to be fired await Until(() => probeCalls.Count == clusterMembershipOptions.NumProbedSilos); while (probeCalls.TryDequeue(out var call)) ; foreach (var siloMonitor in testAccessor.MonitoredSilos.Values) { Assert.Equal(0, ((SiloHealthMonitor.ITestAccessor)siloMonitor).MissedProbes); } await StopLifecycle(); } private static SiloAddress Silo(string value) => SiloAddress.FromParsableString(value); private static MembershipEntry Entry(SiloAddress address, SiloStatus status) => new MembershipEntry { SiloAddress = address, Status = status }; private static async Task Until(Func<bool> condition) { var maxTimeout = 40_000; while (!condition() && (maxTimeout -= 10) > 0) await Task.Delay(10); Assert.True(maxTimeout > 0); } private async Task StopLifecycle(CancellationToken cancellation = default) { var stopped = this.lifecycle.OnStop(cancellation); while (!stopped.IsCompleted) { while (this.timerCalls.TryDequeue(out var call)) call.Completion.TrySetResult(false); await Task.Delay(15); } await stopped; } } }
// // Copyright (c) .NET Foundation and Contributors // Portions Copyright (c) Microsoft Corporation. All rights reserved. // See LICENSE file in the project root for full license information. // using CorDebugInterop; using nanoFramework.Tools.Debugger; using nanoFramework.Tools.VisualStudio.Extension.MetaData; using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; namespace nanoFramework.Tools.VisualStudio.Extension { public class CorDebugAssembly : ICorDebugAssembly, ICorDebugModule, ICorDebugModule2, IDisposable { CorDebugAppDomain _appDomain; CorDebugProcess _process; Hashtable _htTokenCLRToPdbx; Hashtable _htTokennanoCLRToPdbx; Pdbx.PdbxFile _pdbxFile; Pdbx.Assembly _pdbxAssembly; IMetaDataImport _iMetaDataImport; uint _idx; string _name; string _path; ulong _dummyBaseAddress; FileStream _fileStream; CorDebugAssembly _primaryAssembly; bool _isFrameworkAssembly; // this list holds the official assemblies name List<string> frameworkAssemblies_v1_0 = new List<string> { "mscorlib", "nanoframework.hardware.esp32", "nanoframework.networking.sntp", "nanoframework.runtime.events", "nanoframework.runtime.native", "windows.devices.adc", "windows.devices.gpio", "windows.devices.i2c", "windows.devices.pwm", "windows.devices.serialcommunication", "windows.devices.spi", "windows.networking.sockets", "windows.storage.streams", "system.net", }; public CorDebugAssembly( CorDebugProcess process, string name, Pdbx.PdbxFile pdbxFile, uint idx ) { _process = process; _appDomain = null; _name = name; _pdbxFile = pdbxFile; _pdbxAssembly = (pdbxFile != null) ? pdbxFile.Assembly : null; _htTokenCLRToPdbx = new Hashtable(); _htTokennanoCLRToPdbx = new Hashtable(); _idx = idx; _primaryAssembly = null; _isFrameworkAssembly = false; if(_pdbxAssembly != null) { if (!string.IsNullOrEmpty(pdbxFile.PdbxPath)) { string pdbxPath = pdbxFile.PdbxPath.ToLower(); // pdbx files are supposed to be in the 'packages' folder if (pdbxPath.Contains(@"\packages\")) { _isFrameworkAssembly = (frameworkAssemblies_v1_0.Contains(name.ToLower())); } } _pdbxAssembly.CorDebugAssembly = this; foreach(Pdbx.Class c in _pdbxAssembly.Classes) { AddTokenToHashtables( c.Token, c ); foreach(Pdbx.Field field in c.Fields) { AddTokenToHashtables( field.Token, field ); } foreach(Pdbx.Method method in c.Methods) { AddTokenToHashtables( method.Token, method ); } } } } public ICorDebugAssembly ICorDebugAssembly { get { return ((ICorDebugAssembly)this); } } public ICorDebugModule ICorDebugModule { get { return ((ICorDebugModule)this); } } private bool IsPrimaryAssembly { get { return _primaryAssembly == null; } } public bool IsFrameworkAssembly { get { return _isFrameworkAssembly; } } private FileStream EnsureFileStream() { if(IsPrimaryAssembly) { if(_path != null && _fileStream == null) { _fileStream = File.OpenRead( _path ); _dummyBaseAddress = _process.FakeLoadAssemblyIntoMemory( this ); } return _fileStream; } else { FileStream fileStream = _primaryAssembly.EnsureFileStream(); _dummyBaseAddress = _primaryAssembly._dummyBaseAddress; return fileStream; } } public CorDebugAssembly CreateAssemblyInstance( CorDebugAppDomain appDomain ) { //Ensure the metadata import is created. IMetaDataImport iMetaDataImport = MetaDataImport; CorDebugAssembly assm = (CorDebugAssembly)MemberwiseClone(); assm._appDomain = appDomain; assm._primaryAssembly = this; return assm; } internal void ReadMemory( ulong address, uint size, byte[] buffer, out uint read ) { FileStream fileStream = EnsureFileStream(); read = 0; if(fileStream != null) { lock(fileStream) { fileStream.Position = (long)address; read = (uint)fileStream.Read( buffer, 0, (int)size ); } } } public static CorDebugAssembly AssemblyFromIdx( uint idx, ArrayList assemblies ) { foreach(CorDebugAssembly assembly in assemblies) { if(assembly.Idx == idx) return assembly; } return null; } public static CorDebugAssembly AssemblyFromIndex( uint index, ArrayList assemblies ) { return AssemblyFromIdx( nanoCLR_TypeSystem.IdxAssemblyFromIndex( index ), assemblies ); } public string Name { get { return _name; } } public bool HasSymbols { get { return _pdbxAssembly != null; } } private void AddTokenToHashtables( Pdbx.Token token, object o ) { _htTokenCLRToPdbx[token.CLR] = o; _htTokennanoCLRToPdbx[token.nanoCLR] = o; } private string FindAssemblyOnDisk() { if (_path == null && _pdbxAssembly != null) { string[] pathsToTry = new string[] { // Look next to pdbx file Path.Combine( Path.GetDirectoryName( _pdbxFile.PdbxPath ), _pdbxAssembly.FileName ), }; for (int iPath = 0; iPath < pathsToTry.Length; iPath++) { string path = pathsToTry[iPath]; if (File.Exists(path)) { //is this the right file? _path = path; break; } } } return _path; } private IMetaDataImport FindMetadataImport() { Debug.Assert( _iMetaDataImport == null ); IMetaDataDispenser mdd = new CorMetaDataDispenser() as IMetaDataDispenser; object pImport = null; Guid iid = typeof( IMetaDataImport ).GUID; IMetaDataImport metaDataImport = null; try { string path = FindAssemblyOnDisk(); if(path != null) { mdd.OpenScope( path, (int)MetaData.CorOpenFlags.ofRead, ref iid, out pImport ); metaDataImport = pImport as IMetaDataImport; } } catch { } //check the version? return metaDataImport; } public IMetaDataImport MetaDataImport { get { if(_iMetaDataImport == null) { if(HasSymbols) { _iMetaDataImport = FindMetadataImport(); } if(_iMetaDataImport == null) { _pdbxFile = null; _pdbxAssembly = null; _iMetaDataImport = new MetaDataImport( this ); } } return _iMetaDataImport; } } public CorDebugProcess Process { [DebuggerHidden] get { return _process; } } public CorDebugAppDomain AppDomain { [DebuggerHidden] get { return _appDomain; } } public uint Idx { [DebuggerHidden] get { return _idx; } } private CorDebugFunction GetFunctionFromToken( uint tk, Hashtable ht ) { CorDebugFunction function = null; Pdbx.Method method = ht[tk] as Pdbx.Method; if(method != null) { CorDebugClass c = new CorDebugClass( this, method.Class ); function = new CorDebugFunction( c, method ); } Debug.Assert( function != null ); return function; } public CorDebugFunction GetFunctionFromTokenCLR( uint tk ) { return GetFunctionFromToken( tk, _htTokenCLRToPdbx ); } public CorDebugFunction GetFunctionFromTokennanoCLR( uint tk ) { if(HasSymbols) { return GetFunctionFromToken( tk, _htTokennanoCLRToPdbx ); } else { uint index = nanoCLR_TypeSystem.ClassMemberIndexFromnanoCLRToken( tk, this ); Debugger.WireProtocol.Commands.Debugging_Resolve_Method.Result resolvedMethod = Process.Engine.ResolveMethod(index); Debug.Assert( nanoCLR_TypeSystem.IdxAssemblyFromIndex( resolvedMethod.m_td ) == Idx); uint tkMethod = nanoCLR_TypeSystem.SymbollessSupport.MethodDefTokenFromnanoCLRToken( tk ); uint tkClass = nanoCLR_TypeSystem.nanoCLRTokenFromTypeIndex( resolvedMethod.m_td ); CorDebugClass c = GetClassFromTokennanoCLR( tkClass ); return new CorDebugFunction( c, tkMethod ); } } public Pdbx.ClassMember GetPdbxClassMemberFromTokenCLR( uint tk ) { return _htTokenCLRToPdbx[tk] as Pdbx.ClassMember; } private CorDebugClass GetClassFromToken( uint tk, Hashtable ht ) { CorDebugClass cls = null; Pdbx.Class c = ht[tk] as Pdbx.Class; if(c != null) { cls = new CorDebugClass( this, c ); } return cls; } public CorDebugClass GetClassFromTokenCLR( uint tk ) { return GetClassFromToken( tk, _htTokenCLRToPdbx ); } public CorDebugClass GetClassFromTokennanoCLR( uint tk ) { if(HasSymbols) return GetClassFromToken( tk, _htTokennanoCLRToPdbx ); else return new CorDebugClass( this, nanoCLR_TypeSystem.SymbollessSupport.TypeDefTokenFromnanoCLRToken( tk ) ); } ~CorDebugAssembly() { try { ((IDisposable)this).Dispose(); } catch(Exception) { } } #region IDisposable Members void IDisposable.Dispose() { if(IsPrimaryAssembly) { if(_iMetaDataImport != null && !(_iMetaDataImport is MetaDataImport)) { Marshal.ReleaseComObject( _iMetaDataImport ); } _iMetaDataImport = null; if(_fileStream != null) { ((IDisposable)_fileStream).Dispose(); _fileStream = null; } } GC.SuppressFinalize( this ); } #endregion #region ICorDebugAssembly Members int ICorDebugAssembly.GetProcess( out ICorDebugProcess ppProcess ) { ppProcess = Process; return COM_HResults.S_OK; } int ICorDebugAssembly.GetAppDomain( out ICorDebugAppDomain ppAppDomain ) { ppAppDomain = _appDomain; return COM_HResults.S_OK; } int ICorDebugAssembly.EnumerateModules( out ICorDebugModuleEnum ppModules ) { ppModules = new CorDebugEnum( this, typeof( ICorDebugModule ), typeof( ICorDebugModuleEnum ) ); return COM_HResults.S_OK; } int ICorDebugAssembly.GetCodeBase( uint cchName, IntPtr pcchName, IntPtr szName ) { Utility.MarshalString( "", cchName, pcchName, szName ); return COM_HResults.S_OK; } int ICorDebugAssembly.GetName( uint cchName, IntPtr pcchName, IntPtr szName ) { string name = _path != null ? _path : _name; Utility.MarshalString( name, cchName, pcchName, szName ); return COM_HResults.S_OK; } #endregion #region ICorDebugModule Members int ICorDebugModule.GetProcess( out ICorDebugProcess ppProcess ) { ppProcess = Process; return COM_HResults.S_OK; } int ICorDebugModule.GetBaseAddress( out ulong pAddress ) { EnsureFileStream(); pAddress = _dummyBaseAddress; return COM_HResults.S_OK; } int ICorDebugModule.GetAssembly( out ICorDebugAssembly ppAssembly ) { ppAssembly = this; return COM_HResults.S_OK; } int ICorDebugModule.GetName( uint cchName, IntPtr pcchName, IntPtr szName ) { return ICorDebugAssembly.GetName( cchName, pcchName, szName ); } int ICorDebugModule.EnableJITDebugging( int bTrackJITInfo, int bAllowJitOpts ) { return COM_HResults.S_OK; } int ICorDebugModule.EnableClassLoadCallbacks( int bClassLoadCallbacks ) { return COM_HResults.S_OK; } int ICorDebugModule.GetFunctionFromToken( uint methodDef, out ICorDebugFunction ppFunction ) { ppFunction = GetFunctionFromTokenCLR( methodDef ); return COM_HResults.S_OK; } int ICorDebugModule.GetFunctionFromRVA( ulong rva, out ICorDebugFunction ppFunction ) { ppFunction = null; return COM_HResults.S_OK; } int ICorDebugModule.GetClassFromToken( uint typeDef, out ICorDebugClass ppClass ) { ppClass = GetClassFromTokenCLR( typeDef ); return COM_HResults.S_OK; } int ICorDebugModule.CreateBreakpoint( out ICorDebugModuleBreakpoint ppBreakpoint ) { ppBreakpoint = null; return COM_HResults.E_NOTIMPL; } int ICorDebugModule.GetEditAndContinueSnapshot( out ICorDebugEditAndContinueSnapshot ppEditAndContinueSnapshot ) { ppEditAndContinueSnapshot = null; return COM_HResults.S_OK; } int ICorDebugModule.GetMetaDataInterface( ref Guid riid, out IntPtr ppObj ) { IntPtr pMetaDataImport = Marshal.GetIUnknownForObject(MetaDataImport); Marshal.QueryInterface( pMetaDataImport, ref riid, out ppObj ); int cRef = Marshal.Release( pMetaDataImport ); Debug.Assert( riid == typeof( IMetaDataImport ).GUID || riid == typeof( IMetaDataImport2 ).GUID || riid == typeof( IMetaDataAssemblyImport ).GUID ); Debug.Assert(MetaDataImport != null && ppObj != IntPtr.Zero ); return COM_HResults.S_OK; } int ICorDebugModule.GetToken( out uint pToken ) { pToken = _pdbxAssembly.Token.CLR; return COM_HResults.S_OK; } int ICorDebugModule.IsDynamic( out int pDynamic ) { pDynamic = Boolean.FALSE; return COM_HResults.S_OK; } int ICorDebugModule.GetGlobalVariableValue( uint fieldDef, out ICorDebugValue ppValue ) { ppValue = null; return COM_HResults.S_OK; } int ICorDebugModule.GetSize( out uint pcBytes ) { pcBytes = 0x1000; FileStream fileStream = EnsureFileStream(); if(fileStream != null) { pcBytes = (uint)fileStream.Length; } return COM_HResults.S_OK; } int ICorDebugModule.IsInMemory( out int pInMemory ) { pInMemory = Boolean.BoolToInt( !HasSymbols );// Boolean.FALSE; return COM_HResults.S_OK; } #endregion #region ICorDebugModule2 Members int ICorDebugModule2.SetJMCStatus( int bIsJustMyCode, uint cTokens, ref uint pTokens ) { Debug.Assert(cTokens == 0); bool fJMC = Boolean.IntToBool( bIsJustMyCode ); int hres = fJMC ? COM_HResults.E_FAIL : COM_HResults.S_OK; Debug.Assert( Utility.FImplies( fJMC, HasSymbols) ); if (HasSymbols) { if (Process.Engine.Info_SetJMC(fJMC, ReflectionDefinition.Kind.REFLECTION_ASSEMBLY, nanoCLR_TypeSystem.IndexFromIdxAssemblyIdx(Idx))) { if(!_isFrameworkAssembly) { //now update the debugger JMC state... foreach (Pdbx.Class c in _pdbxAssembly.Classes) { foreach (Pdbx.Method m in c.Methods) { m.IsJMC = fJMC; } } } hres = COM_HResults.S_OK; } } return hres; } int ICorDebugModule2.ApplyChanges( uint cbMetadata, byte[] pbMetadata, uint cbIL, byte[] pbIL ) { return COM_HResults.S_OK; } int ICorDebugModule2.SetJITCompilerFlags( uint dwFlags ) { return COM_HResults.S_OK; } int ICorDebugModule2.GetJITCompilerFlags( out uint pdwFlags ) { pdwFlags = (uint)CorDebugJITCompilerFlags.CORDEBUG_JIT_DISABLE_OPTIMIZATION; return COM_HResults.S_OK; } int ICorDebugModule2.ResolveAssembly( uint tkAssemblyRef, out ICorDebugAssembly ppAssembly ) { ppAssembly = null; return COM_HResults.S_OK; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // (C) Ameya Gargesh // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using Xunit; using System; using System.Data.Common; namespace System.Data.Tests.Common { public class DataColumnMappingCollectionTest : IDisposable { //DataTableMapping tableMap; private DataColumnMappingCollection _columnMapCollection; private DataColumnMapping[] _cols; public DataColumnMappingCollectionTest() { _cols = new DataColumnMapping[5]; _cols[0] = new DataColumnMapping("sourceName", "dataSetName"); _cols[1] = new DataColumnMapping("sourceID", "dataSetID"); _cols[2] = new DataColumnMapping("sourceAddress", "dataSetAddress"); _cols[3] = new DataColumnMapping("sourcePhone", "dataSetPhone"); _cols[4] = new DataColumnMapping("sourcePIN", "dataSetPIN"); _columnMapCollection = new DataColumnMappingCollection(); } public void Dispose() { _columnMapCollection.Clear(); } [Fact] public void Add() { DataColumnMapping col1 = new DataColumnMapping("sourceName", "dataSetName"); int t = _columnMapCollection.Add(col1); Assert.Equal(0, t); bool eq1 = col1.Equals(_columnMapCollection[0]); Assert.Equal(true, eq1); Assert.Equal(1, _columnMapCollection.Count); DataColumnMapping col2; col2 = _columnMapCollection.Add("sourceID", "dataSetID"); bool eq2 = col2.Equals(_columnMapCollection[1]); Assert.Equal(true, eq2); Assert.Equal(2, _columnMapCollection.Count); } [Fact] public void AddException1() { Assert.Throws<InvalidCastException>(() => { DataColumnMappingCollection c = new DataColumnMappingCollection(); _columnMapCollection.Add(c); }); } [Fact] public void AddRange() { _columnMapCollection.Add(new DataColumnMapping("sourceAge", "dataSetAge")); Assert.Equal(1, _columnMapCollection.Count); _columnMapCollection.AddRange(_cols); Assert.Equal(6, _columnMapCollection.Count); bool eq; eq = _cols[0].Equals(_columnMapCollection[1]); Assert.Equal(true, eq); eq = _cols[1].Equals(_columnMapCollection[2]); Assert.Equal(true, eq); eq = _cols[0].Equals(_columnMapCollection[0]); Assert.Equal(false, eq); eq = _cols[1].Equals(_columnMapCollection[0]); Assert.Equal(false, eq); } [Fact] public void Clear() { DataColumnMapping col1 = new DataColumnMapping("sourceName", "dataSetName"); _columnMapCollection.Add(col1); Assert.Equal(1, _columnMapCollection.Count); _columnMapCollection.Clear(); Assert.Equal(0, _columnMapCollection.Count); _columnMapCollection.AddRange(_cols); Assert.Equal(5, _columnMapCollection.Count); _columnMapCollection.Clear(); Assert.Equal(0, _columnMapCollection.Count); } [Fact] public void Contains() { DataColumnMapping col1 = new DataColumnMapping("sourceName", "dataSetName"); _columnMapCollection.AddRange(_cols); bool eq; eq = _columnMapCollection.Contains(_cols[0]); Assert.Equal(true, eq); eq = _columnMapCollection.Contains(_cols[1]); Assert.Equal(true, eq); eq = _columnMapCollection.Contains(col1); Assert.Equal(false, eq); eq = _columnMapCollection.Contains(_cols[0].SourceColumn); Assert.Equal(true, eq); eq = _columnMapCollection.Contains(_cols[1].SourceColumn); Assert.Equal(true, eq); eq = _columnMapCollection.Contains(col1.SourceColumn); Assert.Equal(true, eq); eq = _columnMapCollection.Contains(_cols[0].DataSetColumn); Assert.Equal(false, eq); eq = _columnMapCollection.Contains(_cols[1].DataSetColumn); Assert.Equal(false, eq); eq = _columnMapCollection.Contains(col1.DataSetColumn); Assert.Equal(false, eq); } [Fact] public void ContainsException1() { Assert.Throws<InvalidCastException>(() => { object o = new object(); bool a = _columnMapCollection.Contains(o); }); } [Fact] public void CopyTo() { DataColumnMapping[] colcops = new DataColumnMapping[5]; _columnMapCollection.AddRange(_cols); _columnMapCollection.CopyTo(colcops, 0); bool eq; for (int i = 0; i < 5; i++) { eq = _columnMapCollection[i].Equals(colcops[i]); Assert.Equal(true, eq); } colcops = null; colcops = new DataColumnMapping[7]; _columnMapCollection.CopyTo(colcops, 2); for (int i = 0; i < 5; i++) { eq = _columnMapCollection[i].Equals(colcops[i + 2]); Assert.Equal(true, eq); } eq = _columnMapCollection[0].Equals(colcops[0]); Assert.Equal(false, eq); eq = _columnMapCollection[0].Equals(colcops[1]); Assert.Equal(false, eq); } [Fact] public void Equals() { // DataColumnMappingCollection collect2=new DataColumnMappingCollection(); _columnMapCollection.AddRange(_cols); // collect2.AddRange(cols); DataColumnMappingCollection copy1; copy1 = _columnMapCollection; // Assert.Equal (false, columnMapCollection.Equals(collect2)); Assert.Equal(true, _columnMapCollection.Equals(copy1)); // Assert.Equal (false, collect2.Equals(columnMapCollection)); Assert.Equal(true, copy1.Equals(_columnMapCollection)); // Assert.Equal (false, collect2.Equals(copy1)); Assert.Equal(true, copy1.Equals(_columnMapCollection)); Assert.Equal(true, _columnMapCollection.Equals(_columnMapCollection)); // Assert.Equal (true, collect2.Equals(collect2)); Assert.Equal(true, copy1.Equals(copy1)); // Assert.Equal (false, Object.Equals(collect2, columnMapCollection)); Assert.Equal(true, object.Equals(copy1, _columnMapCollection)); // Assert.Equal (false, Object.Equals(columnMapCollection, collect2)); Assert.Equal(true, object.Equals(_columnMapCollection, copy1)); // Assert.Equal (false, Object.Equals(copy1, collect2)); Assert.Equal(true, object.Equals(_columnMapCollection, copy1)); Assert.Equal(true, object.Equals(_columnMapCollection, _columnMapCollection)); // Assert.Equal (true, Object.Equals(collect2, collect2)); Assert.Equal(true, object.Equals(copy1, copy1)); // Assert.Equal (false, Object.Equals(columnMapCollection, collect2)); Assert.Equal(true, object.Equals(_columnMapCollection, copy1)); // Assert.Equal (false, Object.Equals(collect2, columnMapCollection)); Assert.Equal(true, object.Equals(copy1, _columnMapCollection)); // Assert.Equal (false, Object.Equals(collect2, copy1)); Assert.Equal(true, object.Equals(copy1, _columnMapCollection)); } [Fact] public void GetByDataSetColumn() { _columnMapCollection.AddRange(_cols); bool eq; DataColumnMapping col1; col1 = _columnMapCollection.GetByDataSetColumn("dataSetName"); eq = (col1.DataSetColumn.Equals("dataSetName") && col1.SourceColumn.Equals("sourceName")); Assert.Equal(true, eq); col1 = _columnMapCollection.GetByDataSetColumn("dataSetID"); eq = (col1.DataSetColumn.Equals("dataSetID") && col1.SourceColumn.Equals("sourceID")); Assert.Equal(true, eq); col1 = _columnMapCollection.GetByDataSetColumn("datasetname"); eq = (col1.DataSetColumn.Equals("dataSetName") && col1.SourceColumn.Equals("sourceName")); Assert.Equal(true, eq); col1 = _columnMapCollection.GetByDataSetColumn("datasetid"); eq = (col1.DataSetColumn.Equals("dataSetID") && col1.SourceColumn.Equals("sourceID")); Assert.Equal(true, eq); } [Fact] public void GetByDataSetColumn_String_InvalidArguments() { DataColumnMappingCollection dataColumnMappingCollection = new DataColumnMappingCollection(); Assert.Throws<IndexOutOfRangeException>(() => dataColumnMappingCollection.GetByDataSetColumn((string)null)); } [Fact] public void GetColumnMappingBySchemaAction() { _columnMapCollection.AddRange(_cols); bool eq; DataColumnMapping col1; col1 = DataColumnMappingCollection.GetColumnMappingBySchemaAction(_columnMapCollection, "sourceName", MissingMappingAction.Passthrough); eq = (col1.DataSetColumn.Equals("dataSetName") && col1.SourceColumn.Equals("sourceName")); Assert.Equal(true, eq); col1 = DataColumnMappingCollection.GetColumnMappingBySchemaAction(_columnMapCollection, "sourceID", MissingMappingAction.Passthrough); eq = (col1.DataSetColumn.Equals("dataSetID") && col1.SourceColumn.Equals("sourceID")); Assert.Equal(true, eq); col1 = DataColumnMappingCollection.GetColumnMappingBySchemaAction(_columnMapCollection, "sourceData", MissingMappingAction.Passthrough); eq = (col1.DataSetColumn.Equals("sourceData") && col1.SourceColumn.Equals("sourceData")); Assert.Equal(true, eq); eq = _columnMapCollection.Contains(col1); Assert.Equal(false, eq); col1 = DataColumnMappingCollection.GetColumnMappingBySchemaAction(_columnMapCollection, "sourceData", MissingMappingAction.Ignore); Assert.Equal(null, col1); } [Fact] public void GetColumnMappingBySchemaActionException1() { Assert.Throws<InvalidOperationException>(() => { DataColumnMappingCollection.GetColumnMappingBySchemaAction(_columnMapCollection, "sourceName", MissingMappingAction.Error); }); } [Fact] public void IndexOf() { _columnMapCollection.AddRange(_cols); int ind; ind = _columnMapCollection.IndexOf(_cols[0]); Assert.Equal(0, ind); ind = _columnMapCollection.IndexOf(_cols[1]); Assert.Equal(1, ind); ind = _columnMapCollection.IndexOf(_cols[0].SourceColumn); Assert.Equal(0, ind); ind = _columnMapCollection.IndexOf(_cols[1].SourceColumn); Assert.Equal(1, ind); } [Fact] public void IndexOf_Object_IsNull() { DataColumnMappingCollection dataColumnMappingCollection = new DataColumnMappingCollection(); Assert.Equal(-1, dataColumnMappingCollection.IndexOf((object)null)); } [Fact] public void IndexOf_String_IsNull() { DataColumnMappingCollection dataColumnMappingCollection = new DataColumnMappingCollection(); Assert.Equal(-1, dataColumnMappingCollection.IndexOf((string)null)); } [Fact] public void IndexOfDataSetColumn() { _columnMapCollection.AddRange(_cols); int ind; ind = _columnMapCollection.IndexOfDataSetColumn(_cols[0].DataSetColumn); Assert.Equal(0, ind); ind = _columnMapCollection.IndexOfDataSetColumn(_cols[1].DataSetColumn); Assert.Equal(1, ind); ind = _columnMapCollection.IndexOfDataSetColumn("datasetname"); Assert.Equal(0, ind); ind = _columnMapCollection.IndexOfDataSetColumn("datasetid"); Assert.Equal(1, ind); ind = _columnMapCollection.IndexOfDataSetColumn("sourcedeter"); Assert.Equal(-1, ind); } [Fact] public void Insert() { _columnMapCollection.AddRange(_cols); DataColumnMapping mymap = new DataColumnMapping("sourceAge", "dataSetAge"); _columnMapCollection.Insert(3, mymap); int ind = _columnMapCollection.IndexOfDataSetColumn("dataSetAge"); Assert.Equal(3, ind); } [Fact] public void Remove_DataColumnMapping_InvalidArguments() { DataColumnMappingCollection dataColumnMappingCollection = new DataColumnMappingCollection(); Assert.Throws<ArgumentNullException>(() => dataColumnMappingCollection.Remove((DataColumnMapping)null)); } [Fact] public void Remove_DataColumnMapping_Success() { DataColumnMapping dataColumnMapping = new DataColumnMapping("source", "dataSet"); DataColumnMappingCollection dataColumnMappingCollection = new DataColumnMappingCollection { dataColumnMapping }; Assert.Equal(1, dataColumnMappingCollection.Count); dataColumnMappingCollection.Remove(dataColumnMapping); Assert.Equal(0, dataColumnMappingCollection.Count); } [Fact] public void RemoveException1() { Assert.Throws<InvalidCastException>(() => { string te = "testingdata"; _columnMapCollection.AddRange(_cols); _columnMapCollection.Remove(te); }); } [Fact] public void RemoveException2() { Assert.Throws<ArgumentException>(() => { _columnMapCollection.AddRange(_cols); DataColumnMapping mymap = new DataColumnMapping("sourceAge", "dataSetAge"); _columnMapCollection.Remove(mymap); }); } [Fact] public void RemoveAt() { _columnMapCollection.AddRange(_cols); bool eq; _columnMapCollection.RemoveAt(0); eq = _columnMapCollection.Contains(_cols[0]); Assert.Equal(false, eq); eq = _columnMapCollection.Contains(_cols[1]); Assert.Equal(true, eq); _columnMapCollection.RemoveAt("sourceID"); eq = _columnMapCollection.Contains(_cols[1]); Assert.Equal(false, eq); eq = _columnMapCollection.Contains(_cols[2]); Assert.Equal(true, eq); } [Fact] public void RemoveAtException1() { Assert.Throws<IndexOutOfRangeException>(() => { _columnMapCollection.RemoveAt(3); }); } [Fact] public void RemoveAtException2() { Assert.Throws<IndexOutOfRangeException>(() => { _columnMapCollection.RemoveAt("sourceAge"); }); } [Fact] public void ToStringTest() { Assert.Equal("System.Data.Common.DataColumnMappingCollection", _columnMapCollection.ToString()); } [Fact] public void Insert_Int_DataColumnMapping_InvalidArguments() { DataColumnMappingCollection dataColumnMappingCollection = new DataColumnMappingCollection(); Assert.Throws<ArgumentNullException>(() => dataColumnMappingCollection.Insert(123, (DataColumnMapping)null)); } [Fact] public void GetDataColumn_DataColumnMappingCollection_String_Type_DataTable_MissingMappingAction_MissingSchemaAction_InvalidArguments() { AssertExtensions.Throws<ArgumentException>("sourceColumn", () => DataColumnMappingCollection.GetDataColumn((DataColumnMappingCollection)null, null, typeof(string), new DataTable(), new MissingMappingAction(), new MissingSchemaAction())); } [Fact] public void GetDataColumn_DataColumnMappingCollection_String_Type_DataTable_MissingMappingAction_MissingSchemaAction_MissingMappingActionIgnoreReturnsNull() { Assert.Null(DataColumnMappingCollection.GetDataColumn((DataColumnMappingCollection)null, "not null", typeof(string), new DataTable(), MissingMappingAction.Ignore, new MissingSchemaAction())); } [Fact] public void GetDataColumn_DataColumnMappingCollection_String_Type_DataTable_MissingMappingAction_MissingSchemaAction_MissingMappingActionErrorThrowsException() { Assert.Throws<InvalidOperationException>(() => DataColumnMappingCollection.GetDataColumn((DataColumnMappingCollection)null, "not null", typeof(string), new DataTable(), MissingMappingAction.Error, new MissingSchemaAction())); } [Fact] public void GetDataColumn_DataColumnMappingCollection_String_Type_DataTable_MissingMappingAction_MissingSchemaAction_MissingMappingActionNotFoundThrowsException() { AssertExtensions.Throws<ArgumentOutOfRangeException>("MissingMappingAction", () => DataColumnMappingCollection.GetDataColumn((DataColumnMappingCollection)null, "not null", typeof(string), new DataTable(), new MissingMappingAction(), new MissingSchemaAction())); } } }
namespace Ocelot.AcceptanceTests { using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Ocelot.Configuration.File; using TestStack.BDDfy; using Xunit; public class HeaderTests : IDisposable { private int _count; private readonly Steps _steps; private readonly ServiceHandler _serviceHandler; public HeaderTests() { _serviceHandler = new ServiceHandler(); _steps = new Steps(); } [Fact] public void should_transform_upstream_header() { var configuration = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 51871, } }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List<string> { "Get" }, UpstreamHeaderTransform = new Dictionary<string,string> { {"Laz", "D, GP"} } } } }; this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:51871", "/", 200, "Laz")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .And(x => _steps.GivenIAddAHeader("Laz", "D")) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => _steps.ThenTheResponseBodyShouldBe("GP")) .BDDfy(); } [Fact] public void should_transform_downstream_header() { var configuration = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 51871, } }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List<string> { "Get" }, DownstreamHeaderTransform = new Dictionary<string,string> { {"Location", "http://www.bbc.co.uk/, http://ocelot.com/"} } } } }; this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:51871", "/", 200, "Location", "http://www.bbc.co.uk/")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => _steps.ThenTheResponseHeaderIs("Location", "http://ocelot.com/")) .BDDfy(); } [Fact] public void should_fix_issue_190() { var configuration = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 6773, } }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List<string> { "Get" }, DownstreamHeaderTransform = new Dictionary<string,string> { {"Location", "http://localhost:6773, {BaseUrl}"} }, HttpHandlerOptions = new FileHttpHandlerOptions { AllowAutoRedirect = false } } } }; this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:6773", "/", 302, "Location", "http://localhost:6773/pay/Receive")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.Redirect)) .And(x => _steps.ThenTheResponseHeaderIs("Location", "http://localhost:5000/pay/Receive")) .BDDfy(); } [Fact] public void should_fix_issue_205() { var configuration = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 6773, } }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List<string> { "Get" }, DownstreamHeaderTransform = new Dictionary<string,string> { {"Location", "{DownstreamBaseUrl}, {BaseUrl}"} }, HttpHandlerOptions = new FileHttpHandlerOptions { AllowAutoRedirect = false } } } }; this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:6773", "/", 302, "Location", "http://localhost:6773/pay/Receive")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.Redirect)) .And(x => _steps.ThenTheResponseHeaderIs("Location", "http://localhost:5000/pay/Receive")) .BDDfy(); } [Fact] public void should_fix_issue_417() { var configuration = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 6773, } }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List<string> { "Get" }, DownstreamHeaderTransform = new Dictionary<string,string> { {"Location", "{DownstreamBaseUrl}, {BaseUrl}"} }, HttpHandlerOptions = new FileHttpHandlerOptions { AllowAutoRedirect = false } } }, GlobalConfiguration = new FileGlobalConfiguration { BaseUrl = "http://anotherapp.azurewebsites.net" } }; this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:6773", "/", 302, "Location", "http://localhost:6773/pay/Receive")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.Redirect)) .And(x => _steps.ThenTheResponseHeaderIs("Location", "http://anotherapp.azurewebsites.net/pay/Receive")) .BDDfy(); } [Fact] public void request_should_reuse_cookies_with_cookie_container() { var configuration = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/sso/{everything}", DownstreamScheme = "http", DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 6774, } }, UpstreamPathTemplate = "/sso/{everything}", UpstreamHttpMethod = new List<string> { "Get", "Post", "Options" }, HttpHandlerOptions = new FileHttpHandlerOptions { UseCookieContainer = true } } } }; this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:6774", "/sso/test", 200)) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .And(x => _steps.WhenIGetUrlOnTheApiGateway("/sso/test")) .And(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => _steps.ThenTheResponseHeaderIs("Set-Cookie", "test=0; path=/")) .And(x => _steps.GivenIAddCookieToMyRequest("test=1; path=/")) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/sso/test")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .BDDfy(); } [Fact] public void request_should_have_own_cookies_no_cookie_container() { var configuration = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/sso/{everything}", DownstreamScheme = "http", DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 6775, } }, UpstreamPathTemplate = "/sso/{everything}", UpstreamHttpMethod = new List<string> { "Get", "Post", "Options" }, HttpHandlerOptions = new FileHttpHandlerOptions { UseCookieContainer = false } } } }; this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:6775", "/sso/test", 200)) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .And(x => _steps.WhenIGetUrlOnTheApiGateway("/sso/test")) .And(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => _steps.ThenTheResponseHeaderIs("Set-Cookie", "test=0; path=/")) .And(x => _steps.GivenIAddCookieToMyRequest("test=1; path=/")) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/sso/test")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .BDDfy(); } [Fact] public void issue_474_should_not_put_spaces_in_header() { var configuration = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 51879, } }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List<string> { "Get" }, } } }; this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:51879", "/", 200, "Accept")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .And(x => _steps.GivenIAddAHeader("Accept", "text/html,application/xhtml+xml,application/xml;")) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => _steps.ThenTheResponseBodyShouldBe("text/html,application/xhtml+xml,application/xml;")) .BDDfy(); } [Fact] public void issue_474_should_put_spaces_in_header() { var configuration = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 51879, } }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List<string> { "Get" }, } } }; this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:51879", "/", 200, "Accept")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .And(x => _steps.GivenIAddAHeader("Accept", "text/html")) .And(x => _steps.GivenIAddAHeader("Accept", "application/xhtml+xml")) .And(x => _steps.GivenIAddAHeader("Accept", "application/xml")) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => _steps.ThenTheResponseBodyShouldBe("text/html, application/xhtml+xml, application/xml")) .BDDfy(); } private void GivenThereIsAServiceRunningOn(string baseUrl, string basePath, int statusCode) { _serviceHandler.GivenThereIsAServiceRunningOn(baseUrl, basePath, context => { if (_count == 0) { context.Response.Cookies.Append("test", "0"); _count++; context.Response.StatusCode = statusCode; return Task.CompletedTask; } if (context.Request.Cookies.TryGetValue("test", out var cookieValue) || context.Request.Headers.TryGetValue("Set-Cookie", out var headerValue)) { if (cookieValue == "0" || headerValue == "test=1; path=/") { context.Response.StatusCode = statusCode; return Task.CompletedTask; } } context.Response.StatusCode = 500; return Task.CompletedTask; }); } private void GivenThereIsAServiceRunningOn(string baseUrl, string basePath, int statusCode, string headerKey) { _serviceHandler.GivenThereIsAServiceRunningOn(baseUrl, basePath, async context => { if (context.Request.Headers.TryGetValue(headerKey, out var values)) { var result = values.First(); context.Response.StatusCode = statusCode; await context.Response.WriteAsync(result); } }); } private void GivenThereIsAServiceRunningOn(string baseUrl, string basePath, int statusCode, string headerKey, string headerValue) { _serviceHandler.GivenThereIsAServiceRunningOn(baseUrl, basePath, context => { context.Response.OnStarting(() => { context.Response.Headers.Add(headerKey, headerValue); context.Response.StatusCode = statusCode; return Task.CompletedTask; }); return Task.CompletedTask; }); } public void Dispose() { _serviceHandler?.Dispose(); _steps.Dispose(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using PX.Data; using PX.Objects.PO; using PX.Objects.AP; using PX.Objects.CR; using PX.Objects.CM; using PX.Objects.CS; using System.Collections; using PX.Objects.EP; using PX.Objects.IN; using PX.Objects.SO; using PX.Objects.AR; using PX.Objects.GL; using PX.TM; using PX.Objects; using PX.Objects.RQ; namespace PX.Objects.RQ { public class RQRequisitionEntry_Extension:PXGraphExtension<RQRequisitionEntry> { #region Event Handlers // ------------------------------------------------------------------------------------------------------------------------------------------------------------ public PXAction<PX.Objects.RQ.RQRequisition> createQuote; [PXButton(CommitChanges = true)] [PXUIField(DisplayName = "Create Quote")] public virtual IEnumerable CreateQuote(PXAdapter adapter) { SOOrderEntry sograph = PXGraph.CreateInstance<SOOrderEntry>(); List<SOOrder> list = new List<SOOrder>(); foreach (RQRequisition item in adapter.Get<RQRequisition>()) { RQRequisition result = item; RQRequisitionOrder req = PXSelectJoin<RQRequisitionOrder, InnerJoin<SOOrder, On<SOOrder.orderNbr, Equal<RQRequisitionOrder.orderNbr>, And<SOOrder.status, Equal<SOOrderStatus.open>>>>, Where<RQRequisitionOrder.reqNbr, Equal<Required<RQRequisitionOrder.reqNbr>>, And<RQRequisitionOrder.orderCategory, Equal<RQOrderCategory.so>>>> .Select(Base, item.ReqNbr); if (item.CustomerID != null && req == null) { Base.Document.Current = item; bool validateResult = true; foreach (RQRequisitionLine line in Base.Lines.Select(item.ReqNbr)) { if (!ValidateOpenState(line, PXErrorLevel.Error)) validateResult = false; } if (!validateResult) throw new PXRowPersistingException(typeof(RQRequisition).Name, item, Messages.UnableToCreateOrders); sograph.TimeStamp = Base.TimeStamp; sograph.Document.Current = null; foreach (PXResult<RQRequisitionLine, InventoryItem> r in PXSelectJoin<RQRequisitionLine, LeftJoin<InventoryItem, On<InventoryItem.inventoryID, Equal<RQRequisitionLine.inventoryID>>>, Where<RQRequisitionLine.reqNbr, Equal<Required<RQRequisition.reqNbr>>>>.Select(Base, item.ReqNbr)) { RQRequisitionLine l = r; InventoryItem i = r; RQBidding bidding = item.VendorID == null ? PXSelect<RQBidding, Where<RQBidding.reqNbr, Equal<Current<RQRequisitionLine.reqNbr>>, And<RQBidding.lineNbr, Equal<Current<RQRequisitionLine.lineNbr>>, And<RQBidding.orderQty, Greater<decimal0>>>>, OrderBy<Desc<RQBidding.quoteUnitCost>>> .SelectSingleBound(Base, new object[] { l }) : PXSelect<RQBidding, Where<RQBidding.reqNbr, Equal<Current<RQRequisitionLine.reqNbr>>, And<RQBidding.lineNbr, Equal<Current<RQRequisitionLine.lineNbr>>, And<RQBidding.vendorID, Equal<Current<RQRequisition.vendorID>>, And<RQBidding.vendorLocationID, Equal<Current<RQRequisition.vendorLocationID>>>>>>> .SelectSingleBound(Base, new object[] { l, item }); if (sograph.Document.Current == null) { SOOrder order = (SOOrder)sograph.Document.Cache.CreateInstance(); order.OrderType = "QT"; order = sograph.Document.Insert(order); order = PXCache<SOOrder>.CreateCopy(sograph.Document.Search<SOOrder.orderNbr>(order.OrderNbr)); order.CustomerID = item.CustomerID; order.CustomerLocationID = item.CustomerLocationID; order = PXCache<SOOrder>.CreateCopy(sograph.Document.Update(order)); order.CuryID = item.CuryID; order.CuryInfoID = CopyCurrenfyInfo(sograph, item.CuryInfoID); sograph.Document.Update(order); sograph.Save.Press(); order = sograph.Document.Current; list.Add(order); RQRequisitionOrder link = new RQRequisitionOrder(); link.OrderCategory = RQOrderCategory.SO; link.OrderType = order.OrderType; link.OrderNbr = order.OrderNbr; Base.ReqOrders.Insert(link); } SOLine line = (SOLine)sograph.Transactions.Cache.CreateInstance(); line.OrderType = sograph.Document.Current.OrderType; line.OrderNbr = sograph.Document.Current.OrderNbr; line = PXCache<SOLine>.CreateCopy(sograph.Transactions.Insert(line)); line.InventoryID = l.InventoryID; if(line.InventoryID != null) line.SubItemID = l.SubItemID; line.UOM = l.UOM; line.Qty = l.OrderQty; if (l.SiteID != null) line.SiteID = l.SiteID; if (l.IsUseMarkup == true) { string curyID = item.CuryID; decimal profit = (1m + l.MarkupPct.GetValueOrDefault() / 100m); line.ManualPrice = true; decimal unitPrice = l.EstUnitCost.GetValueOrDefault(); decimal curyUnitPrice = l.CuryEstUnitCost.GetValueOrDefault(); decimal curyTotalCost = l.CuryEstExtCost.GetValueOrDefault(); decimal totalCost = l.EstExtCost.GetValueOrDefault(); if (bidding != null && bidding.MinQty <= line.OrderQty && bidding.OrderQty >= line.OrderQty) { curyID = (string)Base.Bidding.GetValueExt<RQBidding.curyID>(bidding); unitPrice = bidding.QuoteUnitCost.GetValueOrDefault(); curyUnitPrice = bidding.CuryQuoteUnitCost.GetValueOrDefault(); curyTotalCost = l.CuryEstExtCost.GetValueOrDefault(); totalCost = l.EstExtCost.GetValueOrDefault(); } if (curyID == sograph.Document.Current.CuryID) //line.CuryUnitPrice = curyUnitPrice * profit; line.CuryUnitPrice = (curyTotalCost / l.OrderQty) * profit; else { //line.UnitPrice = unitPrice * profit; line.UnitPrice = (totalCost / l.OrderQty) * profit; PXCurrencyAttribute.CuryConvCury<SOLine.curyUnitPrice>( sograph.Transactions.Cache, line); } } line = PXCache<SOLine>.CreateCopy(sograph.Transactions.Update(line)); RQRequisitionLine upd = PXCache<RQRequisitionLine>.CreateCopy(l); l.QTOrderNbr = line.OrderNbr; l.QTLineNbr = line.LineNbr; Base.Lines.Update(l); } using (PXTransactionScope scope = new PXTransactionScope()) { try { if (sograph.IsDirty) sograph.Save.Press(); RQRequisition upd = PXCache<RQRequisition>.CreateCopy(item); upd.Quoted = true; result = Base.Document.Update(upd); Base.Save.Press(); } catch { Base.Clear(); throw; } scope.Complete(); } } else { RQRequisition upd = PXCache<RQRequisition>.CreateCopy(item); upd.Quoted = true; result = Base.Document.Update(upd); Base.Save.Press(); } yield return result; } if(list.Count == 1 && adapter.MassProcess == true) { sograph.Clear(); sograph.SelectTimeStamp(); sograph.Document.Current = list[0]; throw new PXRedirectRequiredException(sograph, SO.Messages.SOOrder); } } private bool ValidateOpenState(RQRequisitionLine row, PXErrorLevel level) { bool result = true; Type[] requestOnOpen = row.LineType == POLineType.GoodsForInventory && row.InventoryID != null ? new Type[] {typeof (RQRequisitionLine.uOM), typeof (RQRequisitionLine.siteID), typeof (RQRequisitionLine.subItemID)} : row.LineType == POLineType.NonStock ? new Type[] {typeof (RQRequisitionLine.uOM), typeof (RQRequisitionLine.siteID),} : new Type[] {typeof (RQRequisitionLine.uOM)}; foreach (Type type in requestOnOpen) { object value = Base.Lines.Cache.GetValue(row, type.Name); if (value == null) { Base.Lines.Cache.RaiseExceptionHandling(type.Name, row, null, new PXSetPropertyException(Messages.ShouldBeDefined, level)); result = false; } else Base.Lines.Cache.RaiseExceptionHandling(type.Name, row, value, null); } return result; } private long? CopyCurrenfyInfo(PXGraph graph, long? SourceCuryInfoID) { CurrencyInfo curryInfo = Base.currencyinfo.Select(SourceCuryInfoID); curryInfo.CuryInfoID = null; graph.Caches[typeof (CurrencyInfo)].Clear(); curryInfo = (CurrencyInfo)graph.Caches[typeof(CurrencyInfo)].Insert(curryInfo); return curryInfo.CuryInfoID; } // ------------------------------------------------------------------------------------------------------------------------------------------------------------ public Boolean RequesRefresh = false; public PXAction<RQRequisition> createQTOrder; [PXButton(ImageKey = PX.Web.UI.Sprite.Main.DataEntry)] [PXUIField(DisplayName = Messages.CreateQuotation)] public virtual IEnumerable CreateQTOrder(PXAdapter adapter) { PXGraph.InstanceCreated.AddHandler<SOOrderEntry>(delegate(SOOrderEntry graph) { Base.FieldUpdated.AddHandler<RQRequisitionLine.qTOrderNbr>(delegate(PXCache cache, PXFieldUpdatedEventArgs e) { RQRequisition req = Base.Document.Current; RQRequisitionLine reqline = (RQRequisitionLine)e.Row; if (reqline.QTOrderNbr != null && reqline.QTLineNbr != null) { SOOrder order = graph.Document.Current; SOLine line = PXSelect<SOLine, Where<SOLine.orderType, Equal<SOOrderTypeConstants.quoteOrder>, And<SOLine.orderNbr, Equal<Required<SOLine.orderNbr>>, And<SOLine.lineNbr, Equal<Required<SOLine.lineNbr>>>>>> .Select(graph, reqline.QTOrderNbr, reqline.QTLineNbr); if(line != null) { decimal profit = (1m + reqline.MarkupPct.GetValueOrDefault() / 100m); decimal unitcost = (reqline.EstExtCost ?? 0m) / (reqline.OrderQty ?? 0m); decimal extcost = reqline.EstExtCost ?? 0m; if (reqline.IsUseMarkup == true) { unitcost = unitcost * profit; extcost = extcost * profit; } if (req.CuryID != order.CuryID) { unitcost = Tools.ConvertCurrency<SOLine.curyInfoID>(cache, line, unitcost); extcost = Tools.ConvertCurrency<SOLine.curyInfoID>(cache, line, extcost); } line.ManualPrice = true; graph.Transactions.Cache.SetValueExt<SOLine.curyUnitPrice>(line, unitcost); line = graph.Transactions.Update(line); graph.Transactions.Cache.SetValueExt<SOLine.curyExtPrice>(line, extcost); line = graph.Transactions.Update(line); } } }); }); return Base.CreateQTOrder(adapter); } public Boolean preventRecursion = false; public PXAction<RQRequisition> createPOOrder; [PXButton(ImageKey = PX.Web.UI.Sprite.Main.DataEntry)] [PXUIField(DisplayName = Messages.CreateOrders)] public virtual IEnumerable CreatePOOrder(PXAdapter adapter) { PXGraph.InstanceCreated.AddHandler<POOrderEntry>(delegate(POOrderEntry graph) { //graph.RowUpdated.AddHandler<POLine>(delegate(PXCache cache, PXRowUpdatedEventArgs e) //{ // POLine poline = (POLine)e.Row; // if (!preventRecursion && poline.RQReqNbr != null && poline.RQReqLineNbr != null) // { // RQRequisitionLine line = PXSelect<RQRequisitionLine, // Where<RQRequisitionLine.reqNbr, Equal<Required<RQRequisitionLine.reqNbr>>, // And<RQRequisitionLine.lineNbr, Equal<Required<RQRequisitionLine.lineNbr>>>>> // .Select(graph, poline.RQReqNbr, poline.RQReqLineNbr); // if (line != null) // { // RQRequisitionLineExt lineext = line.GetExtension<RQRequisitionLineExt>(); // try // { // preventRecursion = true; // Decimal amt = line.OrderQty > 0 ? (lineext.UsrIntermediateCost ?? 0) / (line.OrderQty ?? 1) : (lineext.UsrIntermediateCost ?? 0); // amt = Tools.ConvertCurrency<POLine.curyInfoID>(cache, line, amt); // graph.Transactions.Cache.SetValueExt<POLine.curyUnitCost>(poline, amt); // amt = Tools.ConvertCurrency<POLine.curyInfoID>(cache, line, lineext.UsrIntermediateCost ?? 0); // graph.Transactions.Cache.SetValueExt<POLine.curyExtCost>(poline, amt); // poline = graph.Transactions.Update(poline); // } // finally // { // preventRecursion = false; // } // } // } //}); }); Base.RowSelecting.AddHandler<RQBidding>(delegate(PXCache cache, PXRowSelectingEventArgs e) { RQBidding row = e.Row as RQBidding; RQBiddingExt rowext = row.GetExtension<RQBiddingExt>(); if (row.CuryID == null) { using (new PXConnectionScope()) { CurrencyInfo ci = PXSelect<CurrencyInfo, Where<CurrencyInfo.curyInfoID, Equal<Required<CurrencyInfo.curyInfoID>>>>.Select(Base, row.CuryInfoID); if (ci != null) { row.CuryID = ci.CuryID; } } row.CuryQuoteUnitCost = row.QuoteQty > 0 ? rowext.CuryQuoteExtCost / row.QuoteQty : rowext.CuryQuoteExtCost; } }); return Base.CreatePOOrder(adapter); } protected virtual void RQRequisition_VendorLocationID_FieldUpdated(PXCache sender, PXFieldUpdatedEventArgs e) { RQRequisition row = e.Row as RQRequisition; foreach(RQRequisitionLine line in Base.Lines.Select()) { RQRequisitionLineExt lineext = Base.Lines.Cache.GetExtension<RQRequisitionLineExt>(line); if (row.VendorID == null || row.VendorLocationID == null) { lineext.UsrPatternCost = 0; lineext.UsrCuryPatternCost = 0; } else { RQBidding bidding = PXSelect<RQBidding, Where<RQBidding.reqNbr, Equal<Required<RQBidding.reqNbr>>, And<RQBidding.lineNbr, Equal<Required<RQBidding.lineNbr>>, And<RQBidding.vendorID, Equal<Required<RQBidding.vendorID>>, And<RQBidding.vendorLocationID, Equal<Required<RQBidding.vendorLocationID>>>>>>>.Select(Base, line.ReqNbr, line.LineNbr, row.VendorID, row.VendorLocationID); if (bidding != null) { RQBiddingExt biddingext = bidding.GetExtension<RQBiddingExt>(); //Pattern lineext.UsrCuryPatternCost = Tools.ConvertCurrency<RQRequisitionLine.curyInfoID>(Base.Lines.Cache, line, biddingext.UsrPatternCost ?? 0); //Unit Cost line.CuryEstUnitCost = Tools.ConvertCurrency<RQRequisitionLine.curyInfoID>(Base.Lines.Cache, line, bidding.QuoteUnitCost ?? 0); //Ext Cost line.CuryEstExtCost = Tools.ConvertCurrency<RQRequisitionLine.curyInfoID>(Base.Lines.Cache, line, bidding.QuoteExtCost ?? 0); } } Base.Lines.Update(line); } } protected virtual void RQRequisition_UsrCuryEngineeringCost_FieldUpdated(PXCache sender, PXFieldUpdatedEventArgs e) { CalculateAdditioanCost(); } protected virtual void RQRequisition_UsrCuryShippingCost_FieldUpdated(PXCache sender, PXFieldUpdatedEventArgs e) { CalculateAdditioanCost(); } protected virtual void RQRequisition_UsrCuryCustomsClearanceCost_FieldUpdated(PXCache sender, PXFieldUpdatedEventArgs e) { CalculateAdditioanCost(); } protected virtual void RQRequisition_RowSelected(PXCache sender, PXRowSelectedEventArgs e) { if (RequesRefresh) { CalculateAdditioanCost(); Base.Lines.View.RequestRefresh(); RequesRefresh = false; } } protected virtual void RQRequisitionLine_RowUpdated(PXCache sender, PXRowUpdatedEventArgs e) { if (!sender.ObjectsEqual<RQRequisitionLineExt.usrCuryIntermediateCost, RQRequisitionLineExt.usrCuryPatternCost>(e.Row, e.OldRow)) { RequesRefresh = true; } } protected virtual void RQRequisitionLine_RowDeleted(PXCache sender, PXRowDeletedEventArgs e) { CalculateAdditioanCost(); } public virtual void CalculateAdditioanCost() { RQRequisition req = Base.Document.Current; RQRequisitionExt reqext = req.GetExtension<RQRequisitionExt>(); Decimal intermediate = 0; List<RQRequisitionLine> lines = new List<RQRequisitionLine>(); foreach (RQRequisitionLine line in Base.Lines.Select()) { RQRequisitionLineExt lineext = line.GetExtension<RQRequisitionLineExt>(); intermediate += lineext.UsrCuryIntermediateCost ?? 0; lines.Add(line); } Decimal additional = (reqext.UsrCuryCustomsClearanceCost ?? 0) + (reqext.UsrCuryEngineeringCost ?? 0) + (reqext.UsrCuryShippingCost ?? 0); Decimal running = 0; for (int i = 0; i < lines.Count; i++) { RQRequisitionLine line = lines[i]; RQRequisitionLineExt lineext = line.GetExtension<RQRequisitionLineExt>(); if (intermediate <= 0) { lineext.UsrCuryAdditionalCost = 0; } else { if (i >= (lines.Count - 1)) { lineext.UsrCuryAdditionalCost = additional - running; } else { Decimal val = additional * ((lineext.UsrCuryIntermediateCost ?? 0) / intermediate); lineext.UsrCuryAdditionalCost = PXDBCurrencyAttribute.RoundCury<RQRequisitionLine.curyInfoID>(Base.Lines.Cache, line, val); running += lineext.UsrCuryAdditionalCost ?? 0; } } Base.Lines.Cache.Update(line); } } #endregion } }
// $ANTLR 2.7.6 (20061021): "iCal.g" -> "iCalParser.cs"$ using System.Text; using System.IO; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; using DDay.iCal.Serialization; using DDay.iCal.Serialization.iCalendar; namespace DDay.iCal { // Generate the header common to all output files. using System; using TokenBuffer = antlr.TokenBuffer; using TokenStreamException = antlr.TokenStreamException; using TokenStreamIOException = antlr.TokenStreamIOException; using ANTLRException = antlr.ANTLRException; using LLkParser = antlr.LLkParser; using Token = antlr.Token; using IToken = antlr.IToken; using TokenStream = antlr.TokenStream; using RecognitionException = antlr.RecognitionException; using NoViableAltException = antlr.NoViableAltException; using MismatchedTokenException = antlr.MismatchedTokenException; using SemanticException = antlr.SemanticException; using ParserSharedInputState = antlr.ParserSharedInputState; using BitSet = antlr.collections.impl.BitSet; public class iCalParser : antlr.LLkParser { public const int EOF = 1; public const int NULL_TREE_LOOKAHEAD = 3; public const int CRLF = 4; public const int BEGIN = 5; public const int COLON = 6; public const int VCALENDAR = 7; public const int END = 8; public const int IANA_TOKEN = 9; public const int X_NAME = 10; public const int SEMICOLON = 11; public const int EQUAL = 12; public const int COMMA = 13; public const int DQUOTE = 14; public const int CTL = 15; public const int BACKSLASH = 16; public const int NUMBER = 17; public const int DOT = 18; public const int CR = 19; public const int LF = 20; public const int ALPHA = 21; public const int DIGIT = 22; public const int DASH = 23; public const int UNDERSCORE = 24; public const int UNICODE = 25; public const int SPECIAL = 26; public const int SPACE = 27; public const int HTAB = 28; public const int SLASH = 29; public const int ESCAPED_CHAR = 30; public const int LINEFOLDER = 31; protected void initialize() { tokenNames = tokenNames_; } protected iCalParser(TokenBuffer tokenBuf, int k) : base(tokenBuf, k) { initialize(); } public iCalParser(TokenBuffer tokenBuf) : this(tokenBuf,3) { } protected iCalParser(TokenStream lexer, int k) : base(lexer,k) { initialize(); } public iCalParser(TokenStream lexer) : this(lexer,3) { } public iCalParser(ParserSharedInputState state) : base(state,3) { initialize(); } public IICalendarCollection icalendar( ISerializationContext ctx ) //throws RecognitionException, TokenStreamException { IICalendarCollection iCalendars = new iCalendarCollection(); SerializationUtil.OnDeserializing(iCalendars); IICalendar iCal = null; ISerializationSettings settings = ctx.GetService(typeof(ISerializationSettings)) as ISerializationSettings; { // ( ... )* for (;;) { if ((LA(1)==CRLF||LA(1)==BEGIN)) { { // ( ... )* for (;;) { if ((LA(1)==CRLF)) { match(CRLF); } else { goto _loop4_breakloop; } } _loop4_breakloop: ; } // ( ... )* match(BEGIN); match(COLON); match(VCALENDAR); { // ( ... )* for (;;) { if ((LA(1)==CRLF)) { match(CRLF); } else { goto _loop6_breakloop; } } _loop6_breakloop: ; } // ( ... )* ISerializationProcessor<IICalendar> processor = ctx.GetService(typeof(ISerializationProcessor<IICalendar>)) as ISerializationProcessor<IICalendar>; // Do some pre-processing on the calendar: if (processor != null) processor.PreDeserialization(iCal); iCal = (IICalendar)SerializationUtil.GetUninitializedObject(settings.iCalendarType); SerializationUtil.OnDeserializing(iCal); // Push the iCalendar onto the serialization context stack ctx.Push(iCal); icalbody(ctx, iCal); match(END); match(COLON); match(VCALENDAR); { // ( ... )* for (;;) { if ((LA(1)==CRLF) && (LA(2)==EOF||LA(2)==CRLF||LA(2)==BEGIN) && (tokenSet_0_.member(LA(3)))) { match(CRLF); } else { goto _loop8_breakloop; } } _loop8_breakloop: ; } // ( ... )* // Do some final processing on the calendar: if (processor != null) processor.PostDeserialization(iCal); // Notify that the iCalendar has been loaded iCal.OnLoaded(); iCalendars.Add(iCal); SerializationUtil.OnDeserialized(iCal); // Pop the iCalendar off the serialization context stack ctx.Pop(); } else { goto _loop9_breakloop; } } _loop9_breakloop: ; } // ( ... )* SerializationUtil.OnDeserialized(iCalendars); return iCalendars; } public void icalbody( ISerializationContext ctx, IICalendar iCal ) //throws RecognitionException, TokenStreamException { ISerializerFactory sf = ctx.GetService(typeof(ISerializerFactory)) as ISerializerFactory; ICalendarComponentFactory cf = ctx.GetService(typeof(ICalendarComponentFactory)) as ICalendarComponentFactory; #pragma warning disable 0168 ICalendarComponent c; ICalendarProperty p; #pragma warning restore 0168 { // ( ... )* for (;;) { switch ( LA(1) ) { case IANA_TOKEN: case X_NAME: { property(ctx, iCal); break; } case BEGIN: { component(ctx, sf, cf, iCal); break; } default: { goto _loop12_breakloop; } } } _loop12_breakloop: ; } // ( ... )* } public ICalendarProperty property( ISerializationContext ctx, ICalendarPropertyListContainer c ) //throws RecognitionException, TokenStreamException { ICalendarProperty p = null;; IToken n = null; IToken m = null; string v; { switch ( LA(1) ) { case IANA_TOKEN: { n = LT(1); match(IANA_TOKEN); p = new CalendarProperty(n.getLine(), n.getColumn()); p.Name = n.getText().ToUpper(); break; } case X_NAME: { m = LT(1); match(X_NAME); p = new CalendarProperty(m.getLine(), m.getColumn()); p.Name = m.getText().ToUpper(); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } ISerializationProcessor<ICalendarProperty> processor = ctx.GetService(typeof(ISerializationProcessor<ICalendarProperty>)) as ISerializationProcessor<ICalendarProperty>; // Do some pre-processing on the property if (processor != null) processor.PreDeserialization(p); if (c != null) { // Add the property to the container, as the parent object(s) // may be needed during deserialization. c.Properties.Add(p); } // Push the property onto the serialization context stack ctx.Push(p); IStringSerializer dataMapSerializer = new DataMapSerializer(ctx); { // ( ... )* for (;;) { if ((LA(1)==SEMICOLON)) { match(SEMICOLON); parameter(ctx, p); } else { goto _loop24_breakloop; } } _loop24_breakloop: ; } // ( ... )* match(COLON); v=value(); // Deserialize the value of the property // into a concrete iCalendar data type, // a list of concrete iCalendar data types, // or string value. object deserialized = dataMapSerializer.Deserialize(new StringReader(v)); if (deserialized != null) { // Try to determine if this is was deserialized as a *list* // of concrete types. Type targetType = dataMapSerializer.TargetType; Type listOfTargetType = typeof(IList<>).MakeGenericType(targetType); if (listOfTargetType.IsAssignableFrom(deserialized.GetType())) { // We deserialized a list - add each value to the // resulting object. foreach (var item in (IEnumerable)deserialized) p.AddValue(item); } else { // We deserialized a single value - add it to the object. p.AddValue(deserialized); } } { // ( ... )* for (;;) { if ((LA(1)==CRLF)) { match(CRLF); } else { goto _loop26_breakloop; } } _loop26_breakloop: ; } // ( ... )* // Do some final processing on the property: if (processor != null) processor.PostDeserialization(p); // Notify that the property has been loaded p.OnLoaded(); // Pop the property off the serialization context stack ctx.Pop(); return p; } public ICalendarComponent component( ISerializationContext ctx, ISerializerFactory sf, ICalendarComponentFactory cf, ICalendarObject o ) //throws RecognitionException, TokenStreamException { ICalendarComponent c = null;; IToken n = null; IToken m = null; match(BEGIN); match(COLON); { switch ( LA(1) ) { case IANA_TOKEN: { n = LT(1); match(IANA_TOKEN); c = cf.Build(n.getText().ToLower(), true); break; } case X_NAME: { m = LT(1); match(X_NAME); c = cf.Build(m.getText().ToLower(), true); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } ISerializationProcessor<ICalendarComponent> processor = ctx.GetService(typeof(ISerializationProcessor<ICalendarComponent>)) as ISerializationProcessor<ICalendarComponent>; // Do some pre-processing on the component if (processor != null) processor.PreDeserialization(c); SerializationUtil.OnDeserializing(c); // Push the component onto the serialization context stack ctx.Push(c); if (o != null) { // Add the component as a child immediately, in case // embedded components need to access this component, // or the iCalendar itself. o.AddChild(c); } c.Line = n.getLine(); c.Column = n.getColumn(); { // ( ... )* for (;;) { if ((LA(1)==CRLF)) { match(CRLF); } else { goto _loop16_breakloop; } } _loop16_breakloop: ; } // ( ... )* { // ( ... )* for (;;) { switch ( LA(1) ) { case IANA_TOKEN: case X_NAME: { property(ctx, c); break; } case BEGIN: { component(ctx, sf, cf, c); break; } default: { goto _loop18_breakloop; } } } _loop18_breakloop: ; } // ( ... )* match(END); match(COLON); match(IANA_TOKEN); { // ( ... )* for (;;) { if ((LA(1)==CRLF)) { match(CRLF); } else { goto _loop20_breakloop; } } _loop20_breakloop: ; } // ( ... )* // Do some final processing on the component if (processor != null) processor.PostDeserialization(c); // Notify that the component has been loaded c.OnLoaded(); SerializationUtil.OnDeserialized(c); // Pop the component off the serialization context stack ctx.Pop(); return c; } public ICalendarParameter parameter( ISerializationContext ctx, ICalendarParameterCollectionContainer container ) //throws RecognitionException, TokenStreamException { ICalendarParameter p = null;; IToken n = null; IToken m = null; string v; List<string> values = new List<string>(); { switch ( LA(1) ) { case IANA_TOKEN: { n = LT(1); match(IANA_TOKEN); p = new CalendarParameter(n.getText()); break; } case X_NAME: { m = LT(1); match(X_NAME); p = new CalendarParameter(m.getText()); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } // Push the parameter onto the serialization context stack ctx.Push(p); match(EQUAL); v=param_value(); values.Add(v); { // ( ... )* for (;;) { if ((LA(1)==COMMA)) { match(COMMA); v=param_value(); values.Add(v); } else { goto _loop30_breakloop; } } _loop30_breakloop: ; } // ( ... )* p.SetValue(values); if (container != null) { container.Parameters.Add(p); } // Notify that the parameter has been loaded p.OnLoaded(); // Pop the parameter off the serialization context stack ctx.Pop(); return p; } public string value() //throws RecognitionException, TokenStreamException { string v = string.Empty; StringBuilder sb = new StringBuilder(); string c; { // ( ... )* for (;;) { if ((tokenSet_1_.member(LA(1))) && (tokenSet_2_.member(LA(2))) && (tokenSet_2_.member(LA(3)))) { c=value_char(); sb.Append(c); } else { goto _loop37_breakloop; } } _loop37_breakloop: ; } // ( ... )* v = sb.ToString(); return v; } public string param_value() //throws RecognitionException, TokenStreamException { string v = string.Empty;; switch ( LA(1) ) { case BEGIN: case COLON: case VCALENDAR: case END: case IANA_TOKEN: case X_NAME: case SEMICOLON: case EQUAL: case COMMA: case BACKSLASH: case NUMBER: case DOT: case CR: case LF: case ALPHA: case DIGIT: case DASH: case UNDERSCORE: case UNICODE: case SPECIAL: case SPACE: case HTAB: case SLASH: case ESCAPED_CHAR: case LINEFOLDER: { v=paramtext(); break; } case DQUOTE: { v=quoted_string(); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } return v; } public string paramtext() //throws RecognitionException, TokenStreamException { string s = null;; StringBuilder sb = new StringBuilder(); string c; { // ( ... )* for (;;) { if ((tokenSet_3_.member(LA(1)))) { c=safe_char(); sb.Append(c); } else { goto _loop34_breakloop; } } _loop34_breakloop: ; } // ( ... )* s = sb.ToString(); return s; } public string quoted_string() //throws RecognitionException, TokenStreamException { string s = string.Empty; StringBuilder sb = new StringBuilder(); string c; match(DQUOTE); { // ( ... )* for (;;) { if ((tokenSet_4_.member(LA(1)))) { c=qsafe_char(); sb.Append(c); } else { goto _loop40_breakloop; } } _loop40_breakloop: ; } // ( ... )* match(DQUOTE); s = sb.ToString(); return s; } public string safe_char() //throws RecognitionException, TokenStreamException { string c = string.Empty; IToken a = null; { a = LT(1); match(tokenSet_3_); } c = a.getText(); return c; } public string value_char() //throws RecognitionException, TokenStreamException { string c = string.Empty; IToken a = null; { a = LT(1); match(tokenSet_1_); } c = a.getText(); return c; } public string qsafe_char() //throws RecognitionException, TokenStreamException { string c = string.Empty; IToken a = null; { a = LT(1); match(tokenSet_4_); } c = a.getText(); return c; } public string tsafe_char() //throws RecognitionException, TokenStreamException { string s = string.Empty; IToken a = null; { a = LT(1); match(tokenSet_5_); } s = a.getText(); return s; } public string text_char() //throws RecognitionException, TokenStreamException { string s = string.Empty; IToken a = null; { a = LT(1); match(tokenSet_6_); } s = a.getText(); return s; } public string text() //throws RecognitionException, TokenStreamException { string s = string.Empty; string t; { // ( ... )* for (;;) { if ((tokenSet_6_.member(LA(1)))) { t=text_char(); s += t; } else { goto _loop53_breakloop; } } _loop53_breakloop: ; } // ( ... )* return s; } public string number() //throws RecognitionException, TokenStreamException { string s = string.Empty; IToken n1 = null; IToken n2 = null; n1 = LT(1); match(NUMBER); s += n1.getText(); { switch ( LA(1) ) { case DOT: { match(DOT); s += "."; n2 = LT(1); match(NUMBER); s += n2.getText(); break; } case EOF: case SEMICOLON: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } return s; } public string version_number() //throws RecognitionException, TokenStreamException { string s = string.Empty; string t; t=number(); s += t; { switch ( LA(1) ) { case SEMICOLON: { match(SEMICOLON); s += ";"; t=number(); s += t; break; } case EOF: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } return s; } private void initializeFactory() { } public static readonly string[] tokenNames_ = new string[] { @"""<0>""", @"""EOF""", @"""<2>""", @"""NULL_TREE_LOOKAHEAD""", @"""CRLF""", @"""BEGIN""", @"""COLON""", @"""VCALENDAR""", @"""END""", @"""IANA_TOKEN""", @"""X_NAME""", @"""SEMICOLON""", @"""EQUAL""", @"""COMMA""", @"""DQUOTE""", @"""CTL""", @"""BACKSLASH""", @"""NUMBER""", @"""DOT""", @"""CR""", @"""LF""", @"""ALPHA""", @"""DIGIT""", @"""DASH""", @"""UNDERSCORE""", @"""UNICODE""", @"""SPECIAL""", @"""SPACE""", @"""HTAB""", @"""SLASH""", @"""ESCAPED_CHAR""", @"""LINEFOLDER""" }; private static long[] mk_tokenSet_0_() { long[] data = { 114L, 0L}; return data; } public static readonly BitSet tokenSet_0_ = new BitSet(mk_tokenSet_0_()); private static long[] mk_tokenSet_1_() { long[] data = { 4294934496L, 0L, 0L, 0L}; return data; } public static readonly BitSet tokenSet_1_ = new BitSet(mk_tokenSet_1_()); private static long[] mk_tokenSet_2_() { long[] data = { 4294934512L, 0L, 0L, 0L}; return data; } public static readonly BitSet tokenSet_2_ = new BitSet(mk_tokenSet_2_()); private static long[] mk_tokenSet_3_() { long[] data = { 4294907808L, 0L, 0L, 0L}; return data; } public static readonly BitSet tokenSet_3_ = new BitSet(mk_tokenSet_3_()); private static long[] mk_tokenSet_4_() { long[] data = { 4294918112L, 0L, 0L, 0L}; return data; } public static readonly BitSet tokenSet_4_ = new BitSet(mk_tokenSet_4_()); private static long[] mk_tokenSet_5_() { long[] data = { 4294842272L, 0L, 0L, 0L}; return data; } public static readonly BitSet tokenSet_5_ = new BitSet(mk_tokenSet_5_()); private static long[] mk_tokenSet_6_() { long[] data = { 4294868960L, 0L, 0L, 0L}; return data; } public static readonly BitSet tokenSet_6_ = new BitSet(mk_tokenSet_6_()); } }
//Test is checking the ReserveSlot function // If someone screws up the function we will end up // setting values in the wrong slots and the totals will be wrong using System; using System.Threading; public class Value0 { [ThreadStatic] private static object One= 1; [ThreadStatic] private static object Two= 2; [ThreadStatic] private static object Three= 3; [ThreadStatic] private static object Four= 4; [ThreadStatic] private static object Five= 5; [ThreadStatic] private static object Six= 6; [ThreadStatic] private static object Seven= 7; [ThreadStatic] private static object Eight= 8; [ThreadStatic] private static object Nine= 9; [ThreadStatic] private static object Ten= 10; [ThreadStatic] private static object Eleven= 11; [ThreadStatic] private static object Twelve= 12; [ThreadStatic] private static object Thirteen= 13; [ThreadStatic] private static object Fourteen= 14; [ThreadStatic] private static object Fifteen= 15; [ThreadStatic] private static object Sixteen= 16; [ThreadStatic] private static object Seventeen= 17; [ThreadStatic] private static object Eightteen= 18; [ThreadStatic] private static object Nineteen= 19; [ThreadStatic] private static object Twenty= 20; [ThreadStatic] private static object TwentyOne= 21; [ThreadStatic] private static object TwentyTwo= 22; [ThreadStatic] private static object TwentyThree= 23; [ThreadStatic] private static object TwentyFour= 24; [ThreadStatic] private static object TwentyFive= 25; [ThreadStatic] private static object TwentySix= 26; [ThreadStatic] private static object TwentySeven= 27; [ThreadStatic] private static object TwentyEight= 28; [ThreadStatic] private static object TwentyNine= 29; [ThreadStatic] private static object Thirty= 30; [ThreadStatic] private static object ThirtyOne= 31; [ThreadStatic] private static object ThirtyTwo= 32; public bool CheckValues() { if((int)ThirtyTwo != 32) { Console.WriteLine("ThirtySecond spot was incorrect!!!"); return false; } int value = 0; value = (int)One + (int)Two + (int)Three + (int)Four + (int)Five + (int)Six + (int)Seven + (int)Eight + (int)Nine + (int)Ten + (int)Eleven + (int)Twelve + (int)Thirteen + (int)Fourteen + (int)Fifteen + (int)Sixteen + (int)Seventeen + (int)Eightteen + (int)Nineteen + (int)Twenty + (int)TwentyOne + (int)TwentyTwo + (int)TwentyThree + (int)TwentyFour + (int)TwentyFive + (int)TwentySix + (int)TwentySeven + (int)TwentyEight + (int)TwentyNine + (int)Thirty + (int)ThirtyOne + (int)ThirtyTwo; if(value != 528) { Console.WriteLine("Value0 - Wrong values in ThreadStatics!!! {0}",value); return false; } return true; } } public class Value1 { [ThreadStatic] private static object One= 1; [ThreadStatic] private static object Two= 2; [ThreadStatic] private static object Three= 3; [ThreadStatic] private static object Four= 4; [ThreadStatic] private static object Five= 5; [ThreadStatic] private static object Six= 6; [ThreadStatic] private static object Seven= 7; [ThreadStatic] private static object Eight= 8; [ThreadStatic] private static object Nine= 9; [ThreadStatic] private static object Ten= 10; [ThreadStatic] private static object Eleven= 11; [ThreadStatic] private static object Twelve= 12; [ThreadStatic] private static object Thirteen= 13; [ThreadStatic] private static object Fourteen= 14; [ThreadStatic] private static object Fifteen= 15; [ThreadStatic] private static object Sixteen= 16; [ThreadStatic] private static object Seventeen= 17; [ThreadStatic] private static object Eightteen= 18; [ThreadStatic] private static object Nineteen= 19; [ThreadStatic] private static object Twenty= 20; [ThreadStatic] private static object TwentyOne= 21; [ThreadStatic] private static object TwentyTwo= 22; [ThreadStatic] private static object TwentyThree= 23; [ThreadStatic] private static object TwentyFour= 24; [ThreadStatic] private static object TwentyFive= 25; [ThreadStatic] private static object TwentySix= 26; [ThreadStatic] private static object TwentySeven= 27; [ThreadStatic] private static object TwentyEight= 28; [ThreadStatic] private static object TwentyNine= 29; [ThreadStatic] private static object Thirty= 30; [ThreadStatic] private static object ThirtyOne= 31; [ThreadStatic] private static object ThirtyTwo= 32; public bool CheckValues() { if((int)ThirtyTwo != 32) { Console.WriteLine("ThirtySecond spot was incorrect!!!"); return false; } int value = 0; value = (int)One + (int)Two + (int)Three + (int)Four + (int)Five + (int)Six + (int)Seven + (int)Eight + (int)Nine + (int)Ten + (int)Eleven + (int)Twelve + (int)Thirteen + (int)Fourteen + (int)Fifteen + (int)Sixteen + (int)Seventeen + (int)Eightteen + (int)Nineteen + (int)Twenty + (int)TwentyOne + (int)TwentyTwo + (int)TwentyThree + (int)TwentyFour + (int)TwentyFive + (int)TwentySix + (int)TwentySeven + (int)TwentyEight + (int)TwentyNine + (int)Thirty + (int)ThirtyOne + (int)ThirtyTwo; if(value != 528) { Console.WriteLine("Value1 - Wrong values in ThreadStatics!!! {0}",value); return false; } return true; } } public class Value2 { [ThreadStatic] private static object One= 1; [ThreadStatic] private static object Two= 2; [ThreadStatic] private static object Three= 3; [ThreadStatic] private static object Four= 4; [ThreadStatic] private static object Five= 5; [ThreadStatic] private static object Six= 6; [ThreadStatic] private static object Seven= 7; [ThreadStatic] private static object Eight= 8; [ThreadStatic] private static object Nine= 9; [ThreadStatic] private static object Ten= 10; [ThreadStatic] private static object Eleven= 11; [ThreadStatic] private static object Twelve= 12; [ThreadStatic] private static object Thirteen= 13; [ThreadStatic] private static object Fourteen= 14; [ThreadStatic] private static object Fifteen= 15; [ThreadStatic] private static object Sixteen= 16; [ThreadStatic] private static object Seventeen= 17; [ThreadStatic] private static object Eightteen= 18; [ThreadStatic] private static object Nineteen= 19; [ThreadStatic] private static object Twenty= 20; [ThreadStatic] private static object TwentyOne= 21; [ThreadStatic] private static object TwentyTwo= 22; [ThreadStatic] private static object TwentyThree= 23; [ThreadStatic] private static object TwentyFour= 24; [ThreadStatic] private static object TwentyFive= 25; [ThreadStatic] private static object TwentySix= 26; [ThreadStatic] private static object TwentySeven= 27; [ThreadStatic] private static object TwentyEight= 28; [ThreadStatic] private static object TwentyNine= 29; [ThreadStatic] private static object Thirty= 30; [ThreadStatic] private static object ThirtyOne= 31; [ThreadStatic] private static object ThirtyTwo= 32; public bool CheckValues() { if((int)ThirtyTwo != 32) { Console.WriteLine("Value2 - ThirtySecond spot was incorrect!!!"); return false; } int value = 0; value = (int)One + (int)Two + (int)Three + (int)Four + (int)Five + (int)Six + (int)Seven + (int)Eight + (int)Nine + (int)Ten + (int)Eleven + (int)Twelve + (int)Thirteen + (int)Fourteen + (int)Fifteen + (int)Sixteen + (int)Seventeen + (int)Eightteen + (int)Nineteen + (int)Twenty + (int)TwentyOne + (int)TwentyTwo + (int)TwentyThree + (int)TwentyFour + (int)TwentyFive + (int)TwentySix + (int)TwentySeven + (int)TwentyEight + (int)TwentyNine + (int)Thirty + (int)ThirtyOne + (int)ThirtyTwo; if(value != 528) { Console.WriteLine("Wrong values in ThreadStatics!!! {0}",value); return false; } return true; } } public class Value3 { [ThreadStatic] private static object One= 1; [ThreadStatic] private static object Two= 2; [ThreadStatic] private static object Three= 3; [ThreadStatic] private static object Four= 4; [ThreadStatic] private static object Five= 5; [ThreadStatic] private static object Six= 6; [ThreadStatic] private static object Seven= 7; [ThreadStatic] private static object Eight= 8; [ThreadStatic] private static object Nine= 9; [ThreadStatic] private static object Ten= 10; [ThreadStatic] private static object Eleven= 11; [ThreadStatic] private static object Twelve= 12; [ThreadStatic] private static object Thirteen= 13; [ThreadStatic] private static object Fourteen= 14; [ThreadStatic] private static object Fifteen= 15; [ThreadStatic] private static object Sixteen= 16; [ThreadStatic] private static object Seventeen= 17; [ThreadStatic] private static object Eightteen= 18; [ThreadStatic] private static object Nineteen= 19; [ThreadStatic] private static object Twenty= 20; [ThreadStatic] private static object TwentyOne= 21; [ThreadStatic] private static object TwentyTwo= 22; [ThreadStatic] private static object TwentyThree= 23; [ThreadStatic] private static object TwentyFour= 24; [ThreadStatic] private static object TwentyFive= 25; [ThreadStatic] private static object TwentySix= 26; [ThreadStatic] private static object TwentySeven= 27; [ThreadStatic] private static object TwentyEight= 28; [ThreadStatic] private static object TwentyNine= 29; [ThreadStatic] private static object Thirty= 30; [ThreadStatic] private static object ThirtyOne= 31; [ThreadStatic] private static object ThirtyTwo= 32; public bool CheckValues() { if((int)ThirtyTwo != 32) { Console.WriteLine("Value2 - ThirtySecond spot was incorrect!!!"); return false; } int value = 0; value = (int)One + (int)Two + (int)Three + (int)Four + (int)Five + (int)Six + (int)Seven + (int)Eight + (int)Nine + (int)Ten + (int)Eleven + (int)Twelve + (int)Thirteen + (int)Fourteen + (int)Fifteen + (int)Sixteen + (int)Seventeen + (int)Eightteen + (int)Nineteen + (int)Twenty + (int)TwentyOne + (int)TwentyTwo + (int)TwentyThree + (int)TwentyFour + (int)TwentyFive + (int)TwentySix + (int)TwentySeven + (int)TwentyEight + (int)TwentyNine + (int)Thirty + (int)ThirtyOne + (int)ThirtyTwo; if(value != 528) { Console.WriteLine("Wrong values in ThreadStatics!!! {0}",value); return false; } return true; } } public class Value4 { [ThreadStatic] private static object One= 1; [ThreadStatic] private static object Two= 2; [ThreadStatic] private static object Three= 3; [ThreadStatic] private static object Four= 4; [ThreadStatic] private static object Five= 5; [ThreadStatic] private static object Six= 6; [ThreadStatic] private static object Seven= 7; [ThreadStatic] private static object Eight= 8; [ThreadStatic] private static object Nine= 9; [ThreadStatic] private static object Ten= 10; [ThreadStatic] private static object Eleven= 11; [ThreadStatic] private static object Twelve= 12; [ThreadStatic] private static object Thirteen= 13; [ThreadStatic] private static object Fourteen= 14; [ThreadStatic] private static object Fifteen= 15; [ThreadStatic] private static object Sixteen= 16; [ThreadStatic] private static object Seventeen= 17; [ThreadStatic] private static object Eightteen= 18; [ThreadStatic] private static object Nineteen= 19; [ThreadStatic] private static object Twenty= 20; [ThreadStatic] private static object TwentyOne= 21; [ThreadStatic] private static object TwentyTwo= 22; [ThreadStatic] private static object TwentyThree= 23; [ThreadStatic] private static object TwentyFour= 24; [ThreadStatic] private static object TwentyFive= 25; [ThreadStatic] private static object TwentySix= 26; [ThreadStatic] private static object TwentySeven= 27; [ThreadStatic] private static object TwentyEight= 28; [ThreadStatic] private static object TwentyNine= 29; [ThreadStatic] private static object Thirty= 30; [ThreadStatic] private static object ThirtyOne= 31; [ThreadStatic] private static object ThirtyTwo= 32; public bool CheckValues() { if((int)ThirtyTwo != 32) { Console.WriteLine("Value2 - ThirtySecond spot was incorrect!!!"); return false; } int value = 0; value = (int)One + (int)Two + (int)Three + (int)Four + (int)Five + (int)Six + (int)Seven + (int)Eight + (int)Nine + (int)Ten + (int)Eleven + (int)Twelve + (int)Thirteen + (int)Fourteen + (int)Fifteen + (int)Sixteen + (int)Seventeen + (int)Eightteen + (int)Nineteen + (int)Twenty + (int)TwentyOne + (int)TwentyTwo + (int)TwentyThree + (int)TwentyFour + (int)TwentyFive + (int)TwentySix + (int)TwentySeven + (int)TwentyEight + (int)TwentyNine + (int)Thirty + (int)ThirtyOne + (int)ThirtyTwo; if(value != 528) { Console.WriteLine("Wrong values in ThreadStatics!!! {0}",value); return false; } return true; } } public class Value5 { [ThreadStatic] private static object One= 1; [ThreadStatic] private static object Two= 2; [ThreadStatic] private static object Three= 3; [ThreadStatic] private static object Four= 4; [ThreadStatic] private static object Five= 5; [ThreadStatic] private static object Six= 6; [ThreadStatic] private static object Seven= 7; [ThreadStatic] private static object Eight= 8; [ThreadStatic] private static object Nine= 9; [ThreadStatic] private static object Ten= 10; [ThreadStatic] private static object Eleven= 11; [ThreadStatic] private static object Twelve= 12; [ThreadStatic] private static object Thirteen= 13; [ThreadStatic] private static object Fourteen= 14; [ThreadStatic] private static object Fifteen= 15; [ThreadStatic] private static object Sixteen= 16; [ThreadStatic] private static object Seventeen= 17; [ThreadStatic] private static object Eightteen= 18; [ThreadStatic] private static object Nineteen= 19; [ThreadStatic] private static object Twenty= 20; [ThreadStatic] private static object TwentyOne= 21; [ThreadStatic] private static object TwentyTwo= 22; [ThreadStatic] private static object TwentyThree= 23; [ThreadStatic] private static object TwentyFour= 24; [ThreadStatic] private static object TwentyFive= 25; [ThreadStatic] private static object TwentySix= 26; [ThreadStatic] private static object TwentySeven= 27; [ThreadStatic] private static object TwentyEight= 28; [ThreadStatic] private static object TwentyNine= 29; [ThreadStatic] private static object Thirty= 30; [ThreadStatic] private static object ThirtyOne= 31; [ThreadStatic] private static object ThirtyTwo= 32; public bool CheckValues() { if((int)ThirtyTwo != 32) { Console.WriteLine("Value2 - ThirtySecond spot was incorrect!!!"); return false; } int value = 0; value = (int)One + (int)Two + (int)Three + (int)Four + (int)Five + (int)Six + (int)Seven + (int)Eight + (int)Nine + (int)Ten + (int)Eleven + (int)Twelve + (int)Thirteen + (int)Fourteen + (int)Fifteen + (int)Sixteen + (int)Seventeen + (int)Eightteen + (int)Nineteen + (int)Twenty + (int)TwentyOne + (int)TwentyTwo + (int)TwentyThree + (int)TwentyFour + (int)TwentyFive + (int)TwentySix + (int)TwentySeven + (int)TwentyEight + (int)TwentyNine + (int)Thirty + (int)ThirtyOne + (int)ThirtyTwo; if(value != 528) { Console.WriteLine("Wrong values in ThreadStatics!!! {0}",value); return false; } return true; } } public class MyData { public AutoResetEvent autoEvent; [ThreadStatic] private static Value0 v0; [ThreadStatic] private static Value1 v1; [ThreadStatic] private static Value2 v2; [ThreadStatic] private static Value3 v3; [ThreadStatic] private static Value4 v4; [ThreadStatic] private static Value5 v5; public bool pass = false; public void ThreadTarget() { autoEvent.WaitOne(); v0 = new Value0(); v1 = new Value1(); v2 = new Value2(); v3 = new Value3(); v4 = new Value4(); v5 = new Value5(); pass = v0.CheckValues() && v1.CheckValues() && v2.CheckValues() && v3.CheckValues() && v4.CheckValues() && v5.CheckValues(); } } public class Test { private int retVal = 0; public static int Main() { Test staticsTest = new Test(); staticsTest.RunTest(); Console.WriteLine(100 == staticsTest.retVal ? "Test Passed":"Test Failed"); return staticsTest.retVal; } public void RunTest() { MyData data = new MyData(); data.autoEvent = new AutoResetEvent(false); Thread t = new Thread(data.ThreadTarget); t.Start(); if(!t.IsAlive) { Console.WriteLine("Thread was not set to Alive after starting"); retVal = 50; return; } data.autoEvent.Set(); t.Join(); if(data.pass) retVal = 100; } }
namespace StockSharp.Algo { using System; using System.Linq; using Ecng.Collections; using Ecng.Common; using StockSharp.Algo.Storages; using StockSharp.BusinessEntities; using StockSharp.Messages; /// <summary> /// The messages adapter builds market data for basket securities. /// </summary> public class BasketSecurityMessageAdapter : MessageAdapterWrapper { private class SubscriptionInfo { public IBasketSecurityProcessor Processor { get; } public long TransactionId { get; } public CachedSynchronizedDictionary<long, SubscriptionStates> LegsSubscriptions { get; } = new CachedSynchronizedDictionary<long, SubscriptionStates>(); public SubscriptionInfo(IBasketSecurityProcessor processor, long transactionId) { Processor = processor ?? throw new ArgumentNullException(nameof(processor)); TransactionId = transactionId; } public SubscriptionStates State { get; set; } = SubscriptionStates.Stopped; } private readonly SynchronizedDictionary<long, SubscriptionInfo> _subscriptionsByChildId = new(); private readonly SynchronizedDictionary<long, SubscriptionInfo> _subscriptionsByParentId = new(); private readonly ISecurityProvider _securityProvider; private readonly IBasketSecurityProcessorProvider _processorProvider; private readonly IExchangeInfoProvider _exchangeInfoProvider; /// <summary> /// Initializes a new instance of the <see cref="BasketSecurityMessageAdapter"/>. /// </summary> /// <param name="innerAdapter">Underlying adapter.</param> /// <param name="securityProvider">The provider of information about instruments.</param> /// <param name="processorProvider">Basket security processors provider.</param> /// <param name="exchangeInfoProvider">Exchanges and trading boards provider.</param> public BasketSecurityMessageAdapter(IMessageAdapter innerAdapter, ISecurityProvider securityProvider, IBasketSecurityProcessorProvider processorProvider, IExchangeInfoProvider exchangeInfoProvider) : base(innerAdapter) { _securityProvider = securityProvider ?? throw new ArgumentNullException(nameof(securityProvider)); _processorProvider = processorProvider ?? throw new ArgumentNullException(nameof(processorProvider)); _exchangeInfoProvider = exchangeInfoProvider ?? throw new ArgumentNullException(nameof(exchangeInfoProvider)); } /// <inheritdoc /> protected override bool OnSendInMessage(Message message) { switch (message.Type) { case MessageTypes.Reset: { _subscriptionsByChildId.Clear(); _subscriptionsByParentId.Clear(); break; } case MessageTypes.MarketData: { var mdMsg = (MarketDataMessage)message; if (mdMsg.SecurityId.IsDefault()) break; var security = _securityProvider.LookupById(mdMsg.SecurityId); if (security == null) { if (!mdMsg.IsBasket()) break; security = mdMsg.ToSecurity(_exchangeInfoProvider).ToBasket(_processorProvider); } else if (!security.IsBasket()) break; if (mdMsg.IsSubscribe) { var processor = _processorProvider.CreateProcessor(security); var info = new SubscriptionInfo(processor, mdMsg.TransactionId); _subscriptionsByParentId.Add(mdMsg.TransactionId, info); var inners = new MarketDataMessage[processor.BasketLegs.Length]; for (var i = 0; i < inners.Length; i++) { var inner = mdMsg.TypedClone(); inner.TransactionId = TransactionIdGenerator.GetNextId(); inner.SecurityId = processor.BasketLegs[i]; inners[i] = inner; info.LegsSubscriptions.Add(inner.TransactionId, SubscriptionStates.Stopped); _subscriptionsByChildId.Add(inner.TransactionId, info); } foreach (var inner in inners) base.OnSendInMessage(inner); } else { if (!_subscriptionsByParentId.TryGetValue(mdMsg.OriginalTransactionId, out var info)) break; // TODO //_subscriptionsByParentId.Remove(mdMsg.OriginalTransactionId); foreach (var id in info.LegsSubscriptions.CachedKeys) { base.OnSendInMessage(new MarketDataMessage { TransactionId = TransactionIdGenerator.GetNextId(), IsSubscribe = false, OriginalTransactionId = id }); } } RaiseNewOutMessage(new SubscriptionResponseMessage { OriginalTransactionId = mdMsg.TransactionId }); return true; } } return base.OnSendInMessage(message); } private void ChangeState(SubscriptionInfo info, SubscriptionStates state) { info.State = info.State.ChangeSubscriptionState(state, info.TransactionId, this); } /// <inheritdoc /> protected override void OnInnerAdapterNewOutMessage(Message message) { switch (message.Type) { case MessageTypes.SubscriptionResponse: { var responseMsg = (SubscriptionResponseMessage)message; if (_subscriptionsByChildId.TryGetValue(responseMsg.OriginalTransactionId, out var info)) { lock (info.LegsSubscriptions.SyncRoot) { if (responseMsg.Error == null) { info.LegsSubscriptions[responseMsg.OriginalTransactionId] = SubscriptionStates.Active; if (info.State != SubscriptionStates.Active) ChangeState(info, SubscriptionStates.Active); } else { info.LegsSubscriptions[responseMsg.OriginalTransactionId] = SubscriptionStates.Error; if (info.State != SubscriptionStates.Error) ChangeState(info, SubscriptionStates.Error); } } } break; } case MessageTypes.SubscriptionOnline: case MessageTypes.SubscriptionFinished: { var originIdMsg = (IOriginalTransactionIdMessage)message; var id = originIdMsg.OriginalTransactionId; var state = message.Type == MessageTypes.SubscriptionOnline ? SubscriptionStates.Online : SubscriptionStates.Finished; if (_subscriptionsByChildId.TryGetValue(id, out var info)) { lock (info.LegsSubscriptions.SyncRoot) { info.LegsSubscriptions[id] = state; if (info.LegsSubscriptions.CachedValues.All(s => s == state)) ChangeState(info, state); } } break; } default: { if (message is ISubscriptionIdMessage subscrMsg) { foreach (var id in subscrMsg.GetSubscriptionIds()) { if (_subscriptionsByChildId.TryGetValue(id, out var info)) { var basketMsgs = info.Processor.Process(message); foreach (var basketMsg in basketMsgs) { ((ISubscriptionIdMessage)basketMsg).SetSubscriptionIds(subscriptionId: info.TransactionId); base.OnInnerAdapterNewOutMessage(basketMsg); } } } } break; } } base.OnInnerAdapterNewOutMessage(message); } /// <summary> /// Create a copy of <see cref="BasketSecurityMessageAdapter"/>. /// </summary> /// <returns>Copy.</returns> public override IMessageChannel Clone() { return new BasketSecurityMessageAdapter(InnerAdapter, _securityProvider, _processorProvider, _exchangeInfoProvider); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.Network; using Microsoft.Azure.Management.Network.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Network { /// <summary> /// The Network Resource Provider API includes operations for managing the /// PublicIPAddress for your subscription. /// </summary> internal partial class PublicIpAddressOperations : IServiceOperations<NetworkResourceProviderClient>, IPublicIpAddressOperations { /// <summary> /// Initializes a new instance of the PublicIpAddressOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal PublicIpAddressOperations(NetworkResourceProviderClient client) { this._client = client; } private NetworkResourceProviderClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Network.NetworkResourceProviderClient. /// </summary> public NetworkResourceProviderClient Client { get { return this._client; } } /// <summary> /// The Put PublicIPAddress operation creates/updates a stable/dynamic /// PublicIP address /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='publicIpAddressName'> /// Required. The name of the publicIpAddress. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the create/update PublicIPAddress /// operation /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Response for PutPublicIpAddress Api servive call /// </returns> public async Task<PublicIpAddressPutResponse> BeginCreateOrUpdatingAsync(string resourceGroupName, string publicIpAddressName, PublicIpAddress parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (publicIpAddressName == null) { throw new ArgumentNullException("publicIpAddressName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Location == null) { throw new ArgumentNullException("parameters.Location"); } if (parameters.PublicIpAllocationMethod == null) { throw new ArgumentNullException("parameters.PublicIpAllocationMethod"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("publicIpAddressName", publicIpAddressName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "BeginCreateOrUpdatingAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Network"; url = url + "/publicIPAddresses/"; url = url + Uri.EscapeDataString(publicIpAddressName); url = url + "/"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-05-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject publicIpAddressJsonFormatValue = new JObject(); requestDoc = publicIpAddressJsonFormatValue; JObject propertiesValue = new JObject(); publicIpAddressJsonFormatValue["properties"] = propertiesValue; propertiesValue["publicIPAllocationMethod"] = parameters.PublicIpAllocationMethod; if (parameters.IpConfiguration != null) { JObject ipConfigurationValue = new JObject(); propertiesValue["ipConfiguration"] = ipConfigurationValue; if (parameters.IpConfiguration.Id != null) { ipConfigurationValue["id"] = parameters.IpConfiguration.Id; } } if (parameters.DnsSettings != null) { JObject dnsSettingsValue = new JObject(); propertiesValue["dnsSettings"] = dnsSettingsValue; if (parameters.DnsSettings.DomainNameLabel != null) { dnsSettingsValue["domainNameLabel"] = parameters.DnsSettings.DomainNameLabel; } if (parameters.DnsSettings.Fqdn != null) { dnsSettingsValue["fqdn"] = parameters.DnsSettings.Fqdn; } if (parameters.DnsSettings.ReverseFqdn != null) { dnsSettingsValue["reverseFqdn"] = parameters.DnsSettings.ReverseFqdn; } } if (parameters.IpAddress != null) { propertiesValue["ipAddress"] = parameters.IpAddress; } if (parameters.IdleTimeoutInMinutes != null) { propertiesValue["idleTimeoutInMinutes"] = parameters.IdleTimeoutInMinutes.Value; } if (parameters.ResourceGuid != null) { propertiesValue["resourceGuid"] = parameters.ResourceGuid; } if (parameters.ProvisioningState != null) { propertiesValue["provisioningState"] = parameters.ProvisioningState; } if (parameters.Etag != null) { publicIpAddressJsonFormatValue["etag"] = parameters.Etag; } if (parameters.Id != null) { publicIpAddressJsonFormatValue["id"] = parameters.Id; } if (parameters.Name != null) { publicIpAddressJsonFormatValue["name"] = parameters.Name; } if (parameters.Type != null) { publicIpAddressJsonFormatValue["type"] = parameters.Type; } publicIpAddressJsonFormatValue["location"] = parameters.Location; if (parameters.Tags != null) { JObject tagsDictionary = new JObject(); foreach (KeyValuePair<string, string> pair in parameters.Tags) { string tagsKey = pair.Key; string tagsValue = pair.Value; tagsDictionary[tagsKey] = tagsValue; } publicIpAddressJsonFormatValue["tags"] = tagsDictionary; } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result PublicIpAddressPutResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new PublicIpAddressPutResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { PublicIpAddress publicIpAddressInstance = new PublicIpAddress(); result.PublicIpAddress = publicIpAddressInstance; JToken propertiesValue2 = responseDoc["properties"]; if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null) { JToken publicIPAllocationMethodValue = propertiesValue2["publicIPAllocationMethod"]; if (publicIPAllocationMethodValue != null && publicIPAllocationMethodValue.Type != JTokenType.Null) { string publicIPAllocationMethodInstance = ((string)publicIPAllocationMethodValue); publicIpAddressInstance.PublicIpAllocationMethod = publicIPAllocationMethodInstance; } JToken ipConfigurationValue2 = propertiesValue2["ipConfiguration"]; if (ipConfigurationValue2 != null && ipConfigurationValue2.Type != JTokenType.Null) { ResourceId ipConfigurationInstance = new ResourceId(); publicIpAddressInstance.IpConfiguration = ipConfigurationInstance; JToken idValue = ipConfigurationValue2["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); ipConfigurationInstance.Id = idInstance; } } JToken dnsSettingsValue2 = propertiesValue2["dnsSettings"]; if (dnsSettingsValue2 != null && dnsSettingsValue2.Type != JTokenType.Null) { PublicIpAddressDnsSettings dnsSettingsInstance = new PublicIpAddressDnsSettings(); publicIpAddressInstance.DnsSettings = dnsSettingsInstance; JToken domainNameLabelValue = dnsSettingsValue2["domainNameLabel"]; if (domainNameLabelValue != null && domainNameLabelValue.Type != JTokenType.Null) { string domainNameLabelInstance = ((string)domainNameLabelValue); dnsSettingsInstance.DomainNameLabel = domainNameLabelInstance; } JToken fqdnValue = dnsSettingsValue2["fqdn"]; if (fqdnValue != null && fqdnValue.Type != JTokenType.Null) { string fqdnInstance = ((string)fqdnValue); dnsSettingsInstance.Fqdn = fqdnInstance; } JToken reverseFqdnValue = dnsSettingsValue2["reverseFqdn"]; if (reverseFqdnValue != null && reverseFqdnValue.Type != JTokenType.Null) { string reverseFqdnInstance = ((string)reverseFqdnValue); dnsSettingsInstance.ReverseFqdn = reverseFqdnInstance; } } JToken ipAddressValue = propertiesValue2["ipAddress"]; if (ipAddressValue != null && ipAddressValue.Type != JTokenType.Null) { string ipAddressInstance = ((string)ipAddressValue); publicIpAddressInstance.IpAddress = ipAddressInstance; } JToken idleTimeoutInMinutesValue = propertiesValue2["idleTimeoutInMinutes"]; if (idleTimeoutInMinutesValue != null && idleTimeoutInMinutesValue.Type != JTokenType.Null) { int idleTimeoutInMinutesInstance = ((int)idleTimeoutInMinutesValue); publicIpAddressInstance.IdleTimeoutInMinutes = idleTimeoutInMinutesInstance; } JToken resourceGuidValue = propertiesValue2["resourceGuid"]; if (resourceGuidValue != null && resourceGuidValue.Type != JTokenType.Null) { string resourceGuidInstance = ((string)resourceGuidValue); publicIpAddressInstance.ResourceGuid = resourceGuidInstance; } JToken provisioningStateValue = propertiesValue2["provisioningState"]; if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null) { string provisioningStateInstance = ((string)provisioningStateValue); publicIpAddressInstance.ProvisioningState = provisioningStateInstance; } } JToken etagValue = responseDoc["etag"]; if (etagValue != null && etagValue.Type != JTokenType.Null) { string etagInstance = ((string)etagValue); publicIpAddressInstance.Etag = etagInstance; } JToken idValue2 = responseDoc["id"]; if (idValue2 != null && idValue2.Type != JTokenType.Null) { string idInstance2 = ((string)idValue2); publicIpAddressInstance.Id = idInstance2; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); publicIpAddressInstance.Name = nameInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); publicIpAddressInstance.Type = typeInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); publicIpAddressInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey2 = ((string)property.Name); string tagsValue2 = ((string)property.Value); publicIpAddressInstance.Tags.Add(tagsKey2, tagsValue2); } } JToken errorValue = responseDoc["error"]; if (errorValue != null && errorValue.Type != JTokenType.Null) { Error errorInstance = new Error(); result.Error = errorInstance; JToken codeValue = errorValue["code"]; if (codeValue != null && codeValue.Type != JTokenType.Null) { string codeInstance = ((string)codeValue); errorInstance.Code = codeInstance; } JToken messageValue = errorValue["message"]; if (messageValue != null && messageValue.Type != JTokenType.Null) { string messageInstance = ((string)messageValue); errorInstance.Message = messageInstance; } JToken targetValue = errorValue["target"]; if (targetValue != null && targetValue.Type != JTokenType.Null) { string targetInstance = ((string)targetValue); errorInstance.Target = targetInstance; } JToken detailsArray = errorValue["details"]; if (detailsArray != null && detailsArray.Type != JTokenType.Null) { foreach (JToken detailsValue in ((JArray)detailsArray)) { ErrorDetails errorDetailsInstance = new ErrorDetails(); errorInstance.Details.Add(errorDetailsInstance); JToken codeValue2 = detailsValue["code"]; if (codeValue2 != null && codeValue2.Type != JTokenType.Null) { string codeInstance2 = ((string)codeValue2); errorDetailsInstance.Code = codeInstance2; } JToken targetValue2 = detailsValue["target"]; if (targetValue2 != null && targetValue2.Type != JTokenType.Null) { string targetInstance2 = ((string)targetValue2); errorDetailsInstance.Target = targetInstance2; } JToken messageValue2 = detailsValue["message"]; if (messageValue2 != null && messageValue2.Type != JTokenType.Null) { string messageInstance2 = ((string)messageValue2); errorDetailsInstance.Message = messageInstance2; } } } JToken innerErrorValue = errorValue["innerError"]; if (innerErrorValue != null && innerErrorValue.Type != JTokenType.Null) { string innerErrorInstance = ((string)innerErrorValue); errorInstance.InnerError = innerErrorInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("Azure-AsyncOperation")) { result.AzureAsyncOperation = httpResponse.Headers.GetValues("Azure-AsyncOperation").FirstOrDefault(); } if (httpResponse.Headers.Contains("Retry-After")) { result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The delete publicIpAddress operation deletes the specified /// publicIpAddress. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='publicIpAddressName'> /// Required. The name of the subnet. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// If the resource provide needs to return an error to any operation, /// it should return the appropriate HTTP error code and a message /// body as can be seen below.The message should be localized per the /// Accept-Language header specified in the original request such /// thatit could be directly be exposed to users /// </returns> public async Task<UpdateOperationResponse> BeginDeletingAsync(string resourceGroupName, string publicIpAddressName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (publicIpAddressName == null) { throw new ArgumentNullException("publicIpAddressName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("publicIpAddressName", publicIpAddressName); TracingAdapter.Enter(invocationId, this, "BeginDeletingAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Network"; url = url + "/publicIPAddresses/"; url = url + Uri.EscapeDataString(publicIpAddressName); url = url + "/"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-05-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted && statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result UpdateOperationResponse result = null; // Deserialize Response result = new UpdateOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("Azure-AsyncOperation")) { result.AzureAsyncOperation = httpResponse.Headers.GetValues("Azure-AsyncOperation").FirstOrDefault(); } if (httpResponse.Headers.Contains("Retry-After")) { result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Put PublicIPAddress operation creates/updates a stable/dynamic /// PublicIP address /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='publicIpAddressName'> /// Required. The name of the publicIpAddress. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the create PublicIPAddress /// operation /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public async Task<AzureAsyncOperationResponse> CreateOrUpdateAsync(string resourceGroupName, string publicIpAddressName, PublicIpAddress parameters, CancellationToken cancellationToken) { NetworkResourceProviderClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("publicIpAddressName", publicIpAddressName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); PublicIpAddressPutResponse response = await client.PublicIpAddresses.BeginCreateOrUpdatingAsync(resourceGroupName, publicIpAddressName, parameters, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); AzureAsyncOperationResponse result = await client.GetLongRunningOperationStatusAsync(response.AzureAsyncOperation, cancellationToken).ConfigureAwait(false); int delayInSeconds = response.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 30; } if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while (result.Status == NetworkOperationStatus.InProgress) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetLongRunningOperationStatusAsync(response.AzureAsyncOperation, cancellationToken).ConfigureAwait(false); delayInSeconds = result.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 15; } if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } /// <summary> /// The Get Role operation retrieves information about the specified /// virtual machine. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='publicIpAddressName'> /// Required. The name of the subnet. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string publicIpAddressName, CancellationToken cancellationToken) { NetworkResourceProviderClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("publicIpAddressName", publicIpAddressName); TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); UpdateOperationResponse response = await client.PublicIpAddresses.BeginDeletingAsync(resourceGroupName, publicIpAddressName, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); AzureAsyncOperationResponse result = await client.GetLongRunningOperationStatusAsync(response.AzureAsyncOperation, cancellationToken).ConfigureAwait(false); int delayInSeconds = response.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 30; } if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while (result.Status == NetworkOperationStatus.InProgress) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetLongRunningOperationStatusAsync(response.AzureAsyncOperation, cancellationToken).ConfigureAwait(false); delayInSeconds = result.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 15; } if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } /// <summary> /// The Get publicIpAddress operation retreives information about the /// specified pubicIpAddress /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='publicIpAddressName'> /// Required. The name of the subnet. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Response for GetPublicIpAddress Api servive call /// </returns> public async Task<PublicIpAddressGetResponse> GetAsync(string resourceGroupName, string publicIpAddressName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (publicIpAddressName == null) { throw new ArgumentNullException("publicIpAddressName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("publicIpAddressName", publicIpAddressName); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Network"; url = url + "/publicIPAddresses/"; url = url + Uri.EscapeDataString(publicIpAddressName); url = url + "/"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-05-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result PublicIpAddressGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new PublicIpAddressGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { PublicIpAddress publicIpAddressInstance = new PublicIpAddress(); result.PublicIpAddress = publicIpAddressInstance; JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { JToken publicIPAllocationMethodValue = propertiesValue["publicIPAllocationMethod"]; if (publicIPAllocationMethodValue != null && publicIPAllocationMethodValue.Type != JTokenType.Null) { string publicIPAllocationMethodInstance = ((string)publicIPAllocationMethodValue); publicIpAddressInstance.PublicIpAllocationMethod = publicIPAllocationMethodInstance; } JToken ipConfigurationValue = propertiesValue["ipConfiguration"]; if (ipConfigurationValue != null && ipConfigurationValue.Type != JTokenType.Null) { ResourceId ipConfigurationInstance = new ResourceId(); publicIpAddressInstance.IpConfiguration = ipConfigurationInstance; JToken idValue = ipConfigurationValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); ipConfigurationInstance.Id = idInstance; } } JToken dnsSettingsValue = propertiesValue["dnsSettings"]; if (dnsSettingsValue != null && dnsSettingsValue.Type != JTokenType.Null) { PublicIpAddressDnsSettings dnsSettingsInstance = new PublicIpAddressDnsSettings(); publicIpAddressInstance.DnsSettings = dnsSettingsInstance; JToken domainNameLabelValue = dnsSettingsValue["domainNameLabel"]; if (domainNameLabelValue != null && domainNameLabelValue.Type != JTokenType.Null) { string domainNameLabelInstance = ((string)domainNameLabelValue); dnsSettingsInstance.DomainNameLabel = domainNameLabelInstance; } JToken fqdnValue = dnsSettingsValue["fqdn"]; if (fqdnValue != null && fqdnValue.Type != JTokenType.Null) { string fqdnInstance = ((string)fqdnValue); dnsSettingsInstance.Fqdn = fqdnInstance; } JToken reverseFqdnValue = dnsSettingsValue["reverseFqdn"]; if (reverseFqdnValue != null && reverseFqdnValue.Type != JTokenType.Null) { string reverseFqdnInstance = ((string)reverseFqdnValue); dnsSettingsInstance.ReverseFqdn = reverseFqdnInstance; } } JToken ipAddressValue = propertiesValue["ipAddress"]; if (ipAddressValue != null && ipAddressValue.Type != JTokenType.Null) { string ipAddressInstance = ((string)ipAddressValue); publicIpAddressInstance.IpAddress = ipAddressInstance; } JToken idleTimeoutInMinutesValue = propertiesValue["idleTimeoutInMinutes"]; if (idleTimeoutInMinutesValue != null && idleTimeoutInMinutesValue.Type != JTokenType.Null) { int idleTimeoutInMinutesInstance = ((int)idleTimeoutInMinutesValue); publicIpAddressInstance.IdleTimeoutInMinutes = idleTimeoutInMinutesInstance; } JToken resourceGuidValue = propertiesValue["resourceGuid"]; if (resourceGuidValue != null && resourceGuidValue.Type != JTokenType.Null) { string resourceGuidInstance = ((string)resourceGuidValue); publicIpAddressInstance.ResourceGuid = resourceGuidInstance; } JToken provisioningStateValue = propertiesValue["provisioningState"]; if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null) { string provisioningStateInstance = ((string)provisioningStateValue); publicIpAddressInstance.ProvisioningState = provisioningStateInstance; } } JToken etagValue = responseDoc["etag"]; if (etagValue != null && etagValue.Type != JTokenType.Null) { string etagInstance = ((string)etagValue); publicIpAddressInstance.Etag = etagInstance; } JToken idValue2 = responseDoc["id"]; if (idValue2 != null && idValue2.Type != JTokenType.Null) { string idInstance2 = ((string)idValue2); publicIpAddressInstance.Id = idInstance2; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); publicIpAddressInstance.Name = nameInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); publicIpAddressInstance.Type = typeInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); publicIpAddressInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); publicIpAddressInstance.Tags.Add(tagsKey, tagsValue); } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The List publicIpAddress opertion retrieves all the /// publicIpAddresses in a resource group. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Response for ListPublicIpAddresses Api service call /// </returns> public async Task<PublicIpAddressListResponse> ListAsync(string resourceGroupName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Network"; url = url + "/publicIPAddresses"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-05-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result PublicIpAddressListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new PublicIpAddressListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { PublicIpAddress publicIpAddressJsonFormatInstance = new PublicIpAddress(); result.PublicIpAddresses.Add(publicIpAddressJsonFormatInstance); JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { JToken publicIPAllocationMethodValue = propertiesValue["publicIPAllocationMethod"]; if (publicIPAllocationMethodValue != null && publicIPAllocationMethodValue.Type != JTokenType.Null) { string publicIPAllocationMethodInstance = ((string)publicIPAllocationMethodValue); publicIpAddressJsonFormatInstance.PublicIpAllocationMethod = publicIPAllocationMethodInstance; } JToken ipConfigurationValue = propertiesValue["ipConfiguration"]; if (ipConfigurationValue != null && ipConfigurationValue.Type != JTokenType.Null) { ResourceId ipConfigurationInstance = new ResourceId(); publicIpAddressJsonFormatInstance.IpConfiguration = ipConfigurationInstance; JToken idValue = ipConfigurationValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); ipConfigurationInstance.Id = idInstance; } } JToken dnsSettingsValue = propertiesValue["dnsSettings"]; if (dnsSettingsValue != null && dnsSettingsValue.Type != JTokenType.Null) { PublicIpAddressDnsSettings dnsSettingsInstance = new PublicIpAddressDnsSettings(); publicIpAddressJsonFormatInstance.DnsSettings = dnsSettingsInstance; JToken domainNameLabelValue = dnsSettingsValue["domainNameLabel"]; if (domainNameLabelValue != null && domainNameLabelValue.Type != JTokenType.Null) { string domainNameLabelInstance = ((string)domainNameLabelValue); dnsSettingsInstance.DomainNameLabel = domainNameLabelInstance; } JToken fqdnValue = dnsSettingsValue["fqdn"]; if (fqdnValue != null && fqdnValue.Type != JTokenType.Null) { string fqdnInstance = ((string)fqdnValue); dnsSettingsInstance.Fqdn = fqdnInstance; } JToken reverseFqdnValue = dnsSettingsValue["reverseFqdn"]; if (reverseFqdnValue != null && reverseFqdnValue.Type != JTokenType.Null) { string reverseFqdnInstance = ((string)reverseFqdnValue); dnsSettingsInstance.ReverseFqdn = reverseFqdnInstance; } } JToken ipAddressValue = propertiesValue["ipAddress"]; if (ipAddressValue != null && ipAddressValue.Type != JTokenType.Null) { string ipAddressInstance = ((string)ipAddressValue); publicIpAddressJsonFormatInstance.IpAddress = ipAddressInstance; } JToken idleTimeoutInMinutesValue = propertiesValue["idleTimeoutInMinutes"]; if (idleTimeoutInMinutesValue != null && idleTimeoutInMinutesValue.Type != JTokenType.Null) { int idleTimeoutInMinutesInstance = ((int)idleTimeoutInMinutesValue); publicIpAddressJsonFormatInstance.IdleTimeoutInMinutes = idleTimeoutInMinutesInstance; } JToken resourceGuidValue = propertiesValue["resourceGuid"]; if (resourceGuidValue != null && resourceGuidValue.Type != JTokenType.Null) { string resourceGuidInstance = ((string)resourceGuidValue); publicIpAddressJsonFormatInstance.ResourceGuid = resourceGuidInstance; } JToken provisioningStateValue = propertiesValue["provisioningState"]; if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null) { string provisioningStateInstance = ((string)provisioningStateValue); publicIpAddressJsonFormatInstance.ProvisioningState = provisioningStateInstance; } } JToken etagValue = valueValue["etag"]; if (etagValue != null && etagValue.Type != JTokenType.Null) { string etagInstance = ((string)etagValue); publicIpAddressJsonFormatInstance.Etag = etagInstance; } JToken idValue2 = valueValue["id"]; if (idValue2 != null && idValue2.Type != JTokenType.Null) { string idInstance2 = ((string)idValue2); publicIpAddressJsonFormatInstance.Id = idInstance2; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); publicIpAddressJsonFormatInstance.Name = nameInstance; } JToken typeValue = valueValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); publicIpAddressJsonFormatInstance.Type = typeInstance; } JToken locationValue = valueValue["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); publicIpAddressJsonFormatInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)valueValue["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); publicIpAddressJsonFormatInstance.Tags.Add(tagsKey, tagsValue); } } } } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The List publicIpAddress opertion retrieves all the /// publicIpAddresses in a subscription. /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Response for ListPublicIpAddresses Api service call /// </returns> public async Task<PublicIpAddressListResponse> ListAllAsync(CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); TracingAdapter.Enter(invocationId, this, "ListAllAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/providers/"; url = url + "Microsoft.Network"; url = url + "/publicIPAddresses"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-05-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result PublicIpAddressListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new PublicIpAddressListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { PublicIpAddress publicIpAddressJsonFormatInstance = new PublicIpAddress(); result.PublicIpAddresses.Add(publicIpAddressJsonFormatInstance); JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { JToken publicIPAllocationMethodValue = propertiesValue["publicIPAllocationMethod"]; if (publicIPAllocationMethodValue != null && publicIPAllocationMethodValue.Type != JTokenType.Null) { string publicIPAllocationMethodInstance = ((string)publicIPAllocationMethodValue); publicIpAddressJsonFormatInstance.PublicIpAllocationMethod = publicIPAllocationMethodInstance; } JToken ipConfigurationValue = propertiesValue["ipConfiguration"]; if (ipConfigurationValue != null && ipConfigurationValue.Type != JTokenType.Null) { ResourceId ipConfigurationInstance = new ResourceId(); publicIpAddressJsonFormatInstance.IpConfiguration = ipConfigurationInstance; JToken idValue = ipConfigurationValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); ipConfigurationInstance.Id = idInstance; } } JToken dnsSettingsValue = propertiesValue["dnsSettings"]; if (dnsSettingsValue != null && dnsSettingsValue.Type != JTokenType.Null) { PublicIpAddressDnsSettings dnsSettingsInstance = new PublicIpAddressDnsSettings(); publicIpAddressJsonFormatInstance.DnsSettings = dnsSettingsInstance; JToken domainNameLabelValue = dnsSettingsValue["domainNameLabel"]; if (domainNameLabelValue != null && domainNameLabelValue.Type != JTokenType.Null) { string domainNameLabelInstance = ((string)domainNameLabelValue); dnsSettingsInstance.DomainNameLabel = domainNameLabelInstance; } JToken fqdnValue = dnsSettingsValue["fqdn"]; if (fqdnValue != null && fqdnValue.Type != JTokenType.Null) { string fqdnInstance = ((string)fqdnValue); dnsSettingsInstance.Fqdn = fqdnInstance; } JToken reverseFqdnValue = dnsSettingsValue["reverseFqdn"]; if (reverseFqdnValue != null && reverseFqdnValue.Type != JTokenType.Null) { string reverseFqdnInstance = ((string)reverseFqdnValue); dnsSettingsInstance.ReverseFqdn = reverseFqdnInstance; } } JToken ipAddressValue = propertiesValue["ipAddress"]; if (ipAddressValue != null && ipAddressValue.Type != JTokenType.Null) { string ipAddressInstance = ((string)ipAddressValue); publicIpAddressJsonFormatInstance.IpAddress = ipAddressInstance; } JToken idleTimeoutInMinutesValue = propertiesValue["idleTimeoutInMinutes"]; if (idleTimeoutInMinutesValue != null && idleTimeoutInMinutesValue.Type != JTokenType.Null) { int idleTimeoutInMinutesInstance = ((int)idleTimeoutInMinutesValue); publicIpAddressJsonFormatInstance.IdleTimeoutInMinutes = idleTimeoutInMinutesInstance; } JToken resourceGuidValue = propertiesValue["resourceGuid"]; if (resourceGuidValue != null && resourceGuidValue.Type != JTokenType.Null) { string resourceGuidInstance = ((string)resourceGuidValue); publicIpAddressJsonFormatInstance.ResourceGuid = resourceGuidInstance; } JToken provisioningStateValue = propertiesValue["provisioningState"]; if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null) { string provisioningStateInstance = ((string)provisioningStateValue); publicIpAddressJsonFormatInstance.ProvisioningState = provisioningStateInstance; } } JToken etagValue = valueValue["etag"]; if (etagValue != null && etagValue.Type != JTokenType.Null) { string etagInstance = ((string)etagValue); publicIpAddressJsonFormatInstance.Etag = etagInstance; } JToken idValue2 = valueValue["id"]; if (idValue2 != null && idValue2.Type != JTokenType.Null) { string idInstance2 = ((string)idValue2); publicIpAddressJsonFormatInstance.Id = idInstance2; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); publicIpAddressJsonFormatInstance.Name = nameInstance; } JToken typeValue = valueValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); publicIpAddressJsonFormatInstance.Type = typeInstance; } JToken locationValue = valueValue["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); publicIpAddressJsonFormatInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)valueValue["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); publicIpAddressJsonFormatInstance.Tags.Add(tagsKey, tagsValue); } } } } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
/* * 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.Collections.Generic; namespace ParquetSharp.Hadoop { /** * : a memory manager that keeps a global context of how many Parquet * writers there are and manages the memory between them. For use cases with * dynamic partitions, it is easy to end up with many writers in the same task. * By managing the size of each allocation, we try to cut down the size of each * allocation and keep the task from running out of memory. * * This class balances the allocation size of each writer by resize them averagely. * When the sum of each writer's allocation size is less than total memory pool, * keep them original value. * When the sum exceeds, decrease each writer's allocation size by a ratio. */ public class MemoryManager { private static readonly Log LOG = Log.getLog(typeof(MemoryManager)); internal const float DEFAULT_MEMORY_POOL_RATIO = 0.95f; internal const long DEFAULT_MIN_MEMORY_ALLOCATION = 1 * 1024 * 1024; // 1MB private readonly float memoryPoolRatio; private readonly object lockObject = new object(); private readonly long totalMemoryPool; private readonly long minMemoryAllocation; private readonly Dictionary<InternalParquetRecordWriter, long> writerList = new Dictionary<InternalParquetRecordWriter, long>(); private readonly Dictionary<string, Action> callBacks = new Dictionary<string, Action>(); private double scale = 1.0; public MemoryManager(float ratio, long minAllocation) { checkRatio(ratio); memoryPoolRatio = ratio; minMemoryAllocation = minAllocation; totalMemoryPool = Math.Round((double)ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getMax () * ratio); LOG.debug(string.Format("Allocated total memory pool is: %,d", totalMemoryPool)); } private void checkRatio(float ratio) { if (ratio <= 0 || ratio > 1) { throw new ArgumentException("The configured memory pool ratio " + ratio + " is " + "not between 0 and 1."); } } /** * Add a new writer and its memory allocation to the memory manager. * @param writer the new created writer * @param allocation the requested buffer size */ internal void addWriter(InternalParquetRecordWriter writer, long allocation) { lock (lockObject) { long oldValue; if (!writerList.TryGetValue(writer, out oldValue)) { writerList.Add(writer, allocation); } else { throw new ArgumentException("[BUG] The Parquet Memory Manager should not add an " + "instance of InternalParquetRecordWriter more than once. The Manager already contains " + "the writer: " + writer); } updateAllocation(); } } /** * Remove the given writer from the memory manager. * @param writer the writer that has been closed */ internal void removeWriter(InternalParquetRecordWriter writer) { lock (lockObject) { writerList.Remove(writer); if (writerList.Count > 0) { updateAllocation(); } } } /** * Update the allocated size of each writer based on the current allocations and pool size. */ private void updateAllocation() { long totalAllocations = 0; foreach (long allocation in writerList.Values) { totalAllocations += allocation; } if (totalAllocations <= totalMemoryPool) { scale = 1.0; } else { scale = (double)totalMemoryPool / totalAllocations; LOG.warn(string.Format( "Total allocation exceeds %.2f%% (%,d bytes) of heap memory\n" + "Scaling row group sizes to %.2f%% for %d writers", 100 * memoryPoolRatio, totalMemoryPool, 100 * scale, writerList.Count)); foreach (Action callBack in callBacks.Values) { // we do not really want to start a new thread here. callBack(); } } int maxColCount = 0; foreach (InternalParquetRecordWriter w in writerList.Keys) { maxColCount = Math.Max(w.getSchema().getColumns().Count, maxColCount); } foreach (KeyValuePair<InternalParquetRecordWriter, long> entry in writerList) { long newSize = (long)Math.Floor(entry.Value * scale); if (scale < 1.0 && minMemoryAllocation > 0 && newSize < minMemoryAllocation) { throw new ParquetRuntimeException(string.Format("New Memory allocation %d bytes" + " is smaller than the minimum allocation size of %d bytes.", newSize, minMemoryAllocation)) { }; } entry.Key.setRowGroupSizeThreshold(newSize); LOG.debug(string.Format("Adjust block size from %,d to %,d for writer: %s", entry.Value, newSize, entry.Key)); } } /** * Get the total memory pool size that is available for writers. * @return the number of bytes in the memory pool */ long getTotalMemoryPool() { return totalMemoryPool; } /** * Get the writers list * @return the writers in this memory manager */ Dictionary<InternalParquetRecordWriter, long> getWriterList() { return writerList; } /** * Get the ratio of memory allocated for all the writers. * @return the memory pool ratio */ internal float getMemoryPoolRatio() { return memoryPoolRatio; } /** * Register callback and deduplicate it if any. * @param callBackName the name of callback. It should be identical. * @param callBack the callback passed in from upper layer, such as Hive. */ public void registerScaleCallBack(string callBackName, Action callBack) { Preconditions.checkNotNull(callBackName, "callBackName"); Preconditions.checkNotNull(callBack, "callBack"); if (callBacks.ContainsKey(callBackName)) { throw new ArgumentException("The callBackName " + callBackName + " is duplicated and has been registered already."); } else { callBacks.Add(callBackName, callBack); } } /** * Get the registered callbacks. * @return */ Dictionary<string, Action> getScaleCallBacks() { return Collections.unmodifiableMap(callBacks); } /** * Get the internal scale value of MemoryManger * @return */ double getScale() { return scale; } } }
/* * 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 Apache.Ignite.Core.Tests { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache.Query; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Events; using Apache.Ignite.Core.Impl; using Apache.Ignite.Core.Impl.Events; using Apache.Ignite.Core.Tests.Compute; using NUnit.Framework; /// <summary> /// <see cref="IEvents"/> tests. /// </summary> public class EventsTest { /** */ private IIgnite _grid1; /** */ private IIgnite _grid2; /** */ private IIgnite _grid3; /** */ private IIgnite[] _grids; /** */ public static int IdGen; [TestFixtureTearDown] public void FixtureTearDown() { StopGrids(); } /// <summary> /// Executes before each test. /// </summary> [SetUp] public void SetUp() { StartGrids(); EventsTestHelper.ListenResult = true; } /// <summary> /// Executes after each test. /// </summary> [TearDown] public virtual void TearDown() { try { TestUtils.AssertHandleRegistryIsEmpty(1000, _grid1, _grid2, _grid3); } catch (Exception) { // Restart grids to cleanup StopGrids(); throw; } finally { EventsTestHelper.AssertFailures(); if (TestContext.CurrentContext.Test.Name.StartsWith("TestEventTypes")) StopGrids(); // clean events for other tests } } /// <summary> /// Tests enable/disable of event types. /// </summary> [Test] public void TestEnableDisable() { var events = _grid1.GetEvents(); Assert.AreEqual(0, events.GetEnabledEvents().Count); Assert.IsFalse(EventType.CacheAll.Any(events.IsEnabled)); events.EnableLocal(EventType.CacheAll); Assert.AreEqual(EventType.CacheAll, events.GetEnabledEvents()); Assert.IsTrue(EventType.CacheAll.All(events.IsEnabled)); events.EnableLocal(EventType.TaskExecutionAll); events.DisableLocal(EventType.CacheAll); Assert.AreEqual(EventType.TaskExecutionAll, events.GetEnabledEvents()); } /// <summary> /// Tests LocalListen. /// </summary> [Test] public void TestLocalListen() { var events = _grid1.GetEvents(); var listener = EventsTestHelper.GetListener(); var eventType = EventType.TaskExecutionAll; events.EnableLocal(eventType); events.LocalListen(listener, eventType); CheckSend(3); // 3 events per task * 3 grids // Check unsubscription for specific event events.StopLocalListen(listener, EventType.TaskReduced); CheckSend(2); // Unsubscribe from all events events.StopLocalListen(listener); CheckNoEvent(); // Check unsubscription by filter events.LocalListen(listener, EventType.TaskReduced); CheckSend(); EventsTestHelper.ListenResult = false; CheckSend(); // one last event will be received for each listener CheckNoEvent(); } /// <summary> /// Tests LocalListen. /// </summary> [Test] [Ignore("IGNITE-879")] public void TestLocalListenRepeatedSubscription() { var events = _grid1.GetEvents(); var listener = EventsTestHelper.GetListener(); var eventType = EventType.TaskExecutionAll; events.EnableLocal(eventType); events.LocalListen(listener, eventType); CheckSend(3); // 3 events per task * 3 grids events.LocalListen(listener, eventType); events.LocalListen(listener, eventType); CheckSend(9); events.StopLocalListen(listener, eventType); CheckSend(6); events.StopLocalListen(listener, eventType); CheckSend(3); events.StopLocalListen(listener, eventType); CheckNoEvent(); } /// <summary> /// Tests all available event types/classes. /// </summary> [Test, TestCaseSource("TestCases")] public void TestEventTypes(EventTestCase testCase) { var events = _grid1.GetEvents(); events.EnableLocal(testCase.EventType); var listener = EventsTestHelper.GetListener(); events.LocalListen(listener, testCase.EventType); EventsTestHelper.ClearReceived(testCase.EventCount); testCase.GenerateEvent(_grid1); EventsTestHelper.VerifyReceive(testCase.EventCount, testCase.EventObjectType, testCase.EventType); if (testCase.VerifyEvents != null) testCase.VerifyEvents(EventsTestHelper.ReceivedEvents.Reverse(), _grid1); // Check stop events.StopLocalListen(listener); EventsTestHelper.ClearReceived(0); testCase.GenerateEvent(_grid1); Thread.Sleep(EventsTestHelper.Timeout); } /// <summary> /// Test cases for TestEventTypes: type id + type + event generator. /// </summary> public IEnumerable<EventTestCase> TestCases { get { yield return new EventTestCase { EventType = EventType.CacheAll, EventObjectType = typeof (CacheEvent), GenerateEvent = g => g.GetCache<int, int>(null).Put(1, 1), VerifyEvents = (e, g) => VerifyCacheEvents(e, g), EventCount = 2 }; yield return new EventTestCase { EventType = EventType.TaskExecutionAll, EventObjectType = typeof (TaskEvent), GenerateEvent = g => GenerateTaskEvent(g), VerifyEvents = (e, g) => VerifyTaskEvents(e), EventCount = 3 }; yield return new EventTestCase { EventType = EventType.JobExecutionAll, EventObjectType = typeof (JobEvent), GenerateEvent = g => GenerateTaskEvent(g), EventCount = 7 }; yield return new EventTestCase { EventType = new[] {EventType.CacheQueryExecuted}, EventObjectType = typeof (CacheQueryExecutedEvent), GenerateEvent = g => GenerateCacheQueryEvent(g), EventCount = 1 }; yield return new EventTestCase { EventType = new[] { EventType.CacheQueryObjectRead }, EventObjectType = typeof (CacheQueryReadEvent), GenerateEvent = g => GenerateCacheQueryEvent(g), EventCount = 1 }; } } /// <summary> /// Tests the LocalQuery. /// </summary> [Test] public void TestLocalQuery() { var events = _grid1.GetEvents(); var eventType = EventType.TaskExecutionAll; events.EnableLocal(eventType); var oldEvents = events.LocalQuery(); GenerateTaskEvent(); // "Except" works because of overridden equality var qryResult = events.LocalQuery(eventType).Except(oldEvents).ToList(); Assert.AreEqual(3, qryResult.Count); } /// <summary> /// Tests the WaitForLocal. /// </summary> [Test] public void TestWaitForLocal([Values(true, false)] bool async) { var events = _grid1.GetEvents(); var timeout = TimeSpan.FromSeconds(3); var eventType = EventType.TaskExecutionAll; events.EnableLocal(eventType); Func<IEventFilter<IEvent>, int[], Task<IEvent>> getWaitTask; if (async) getWaitTask = (filter, types) => { var task = events.WaitForLocalAsync(filter, types); GenerateTaskEvent(); return task; }; else getWaitTask = (filter, types) => { var task = Task.Factory.StartNew(() => events.WaitForLocal(filter, types)); Thread.Sleep(500); // allow task to start and begin waiting for events GenerateTaskEvent(); return task; }; // No params var waitTask = getWaitTask(null, new int[0]); waitTask.Wait(timeout); // Event types waitTask = getWaitTask(null, new[] {EventType.TaskReduced}); Assert.IsTrue(waitTask.Wait(timeout)); Assert.IsInstanceOf(typeof(TaskEvent), waitTask.Result); Assert.AreEqual(EventType.TaskReduced, waitTask.Result.Type); // Filter waitTask = getWaitTask(new EventFilter<IEvent>(e => e.Type == EventType.TaskReduced), new int[0]); Assert.IsTrue(waitTask.Wait(timeout)); Assert.IsInstanceOf(typeof(TaskEvent), waitTask.Result); Assert.AreEqual(EventType.TaskReduced, waitTask.Result.Type); // Filter & types waitTask = getWaitTask(new EventFilter<IEvent>(e => e.Type == EventType.TaskReduced), new[] {EventType.TaskReduced}); Assert.IsTrue(waitTask.Wait(timeout)); Assert.IsInstanceOf(typeof(TaskEvent), waitTask.Result); Assert.AreEqual(EventType.TaskReduced, waitTask.Result.Type); } /* /// <summary> /// Tests RemoteListen. /// </summary> [Test] public void TestRemoteListen( [Values(true, false)] bool async, [Values(true, false)] bool binarizable, [Values(true, false)] bool autoUnsubscribe) { foreach (var g in _grids) { g.GetEvents().EnableLocal(EventType.JobExecutionAll); g.GetEvents().EnableLocal(EventType.TaskExecutionAll); } var events = _grid1.GetEvents(); var expectedType = EventType.JobStarted; var remoteFilter = binary ? (IEventFilter<IEvent>) new RemoteEventBinarizableFilter(expectedType) : new RemoteEventFilter(expectedType); var localListener = EventsTestHelper.GetListener(); if (async) events = events.WithAsync(); var listenId = events.RemoteListen(localListener: localListener, remoteFilter: remoteFilter, autoUnsubscribe: autoUnsubscribe); if (async) listenId = events.GetFuture<Guid>().Get(); Assert.IsNotNull(listenId); CheckSend(3, typeof(JobEvent), expectedType); _grid3.GetEvents().DisableLocal(EventType.JobExecutionAll); CheckSend(2, typeof(JobEvent), expectedType); events.StopRemoteListen(listenId.Value); if (async) events.GetFuture().Get(); CheckNoEvent(); // Check unsubscription with listener events.RemoteListen(localListener: localListener, remoteFilter: remoteFilter, autoUnsubscribe: autoUnsubscribe); if (async) events.GetFuture<Guid>().Get(); CheckSend(2, typeof(JobEvent), expectedType); EventsTestHelper.ListenResult = false; CheckSend(1, typeof(JobEvent), expectedType); // one last event CheckNoEvent(); }*/ /// <summary> /// Tests RemoteQuery. /// </summary> [Test] public void TestRemoteQuery([Values(true, false)] bool async) { foreach (var g in _grids) g.GetEvents().EnableLocal(EventType.JobExecutionAll); var events = _grid1.GetEvents(); var eventFilter = new RemoteEventFilter(EventType.JobStarted); var oldEvents = events.RemoteQuery(eventFilter); GenerateTaskEvent(); var remoteQuery = !async ? events.RemoteQuery(eventFilter, EventsTestHelper.Timeout, EventType.JobExecutionAll) : events.RemoteQueryAsync(eventFilter, EventsTestHelper.Timeout, EventType.JobExecutionAll).Result; var qryResult = remoteQuery.Except(oldEvents).Cast<JobEvent>().ToList(); Assert.AreEqual(_grids.Length - 1, qryResult.Count); Assert.IsTrue(qryResult.All(x => x.Type == EventType.JobStarted)); } /// <summary> /// Tests serialization. /// </summary> [Test] public void TestSerialization() { var grid = (Ignite) _grid1; var comp = (Impl.Compute.Compute) grid.GetCluster().ForLocal().GetCompute(); var locNode = grid.GetCluster().GetLocalNode(); var expectedGuid = Guid.Parse("00000000-0000-0001-0000-000000000002"); var expectedGridGuid = new IgniteGuid(expectedGuid, 3); using (var inStream = IgniteManager.Memory.Allocate().GetStream()) { var result = comp.ExecuteJavaTask<bool>("org.apache.ignite.platform.PlatformEventsWriteEventTask", inStream.MemoryPointer); Assert.IsTrue(result); inStream.SynchronizeInput(); var reader = grid.Marshaller.StartUnmarshal(inStream); var cacheEvent = EventReader.Read<CacheEvent>(reader); CheckEventBase(cacheEvent); Assert.AreEqual("cacheName", cacheEvent.CacheName); Assert.AreEqual(locNode, cacheEvent.EventNode); Assert.AreEqual(1, cacheEvent.Partition); Assert.AreEqual(true, cacheEvent.IsNear); Assert.AreEqual(2, cacheEvent.Key); Assert.AreEqual(expectedGridGuid, cacheEvent.Xid); Assert.AreEqual(null, cacheEvent.LockId); Assert.AreEqual(4, cacheEvent.NewValue); Assert.AreEqual(true, cacheEvent.HasNewValue); Assert.AreEqual(5, cacheEvent.OldValue); Assert.AreEqual(true, cacheEvent.HasOldValue); Assert.AreEqual(expectedGuid, cacheEvent.SubjectId); Assert.AreEqual("cloClsName", cacheEvent.ClosureClassName); Assert.AreEqual("taskName", cacheEvent.TaskName); var qryExecEvent = EventReader.Read<CacheQueryExecutedEvent>(reader); CheckEventBase(qryExecEvent); Assert.AreEqual("qryType", qryExecEvent.QueryType); Assert.AreEqual("cacheName", qryExecEvent.CacheName); Assert.AreEqual("clsName", qryExecEvent.ClassName); Assert.AreEqual("clause", qryExecEvent.Clause); Assert.AreEqual(expectedGuid, qryExecEvent.SubjectId); Assert.AreEqual("taskName", qryExecEvent.TaskName); var qryReadEvent = EventReader.Read<CacheQueryReadEvent>(reader); CheckEventBase(qryReadEvent); Assert.AreEqual("qryType", qryReadEvent.QueryType); Assert.AreEqual("cacheName", qryReadEvent.CacheName); Assert.AreEqual("clsName", qryReadEvent.ClassName); Assert.AreEqual("clause", qryReadEvent.Clause); Assert.AreEqual(expectedGuid, qryReadEvent.SubjectId); Assert.AreEqual("taskName", qryReadEvent.TaskName); Assert.AreEqual(1, qryReadEvent.Key); Assert.AreEqual(2, qryReadEvent.Value); Assert.AreEqual(3, qryReadEvent.OldValue); Assert.AreEqual(4, qryReadEvent.Row); var cacheRebalancingEvent = EventReader.Read<CacheRebalancingEvent>(reader); CheckEventBase(cacheRebalancingEvent); Assert.AreEqual("cacheName", cacheRebalancingEvent.CacheName); Assert.AreEqual(1, cacheRebalancingEvent.Partition); Assert.AreEqual(locNode, cacheRebalancingEvent.DiscoveryNode); Assert.AreEqual(2, cacheRebalancingEvent.DiscoveryEventType); Assert.AreEqual(3, cacheRebalancingEvent.DiscoveryTimestamp); var checkpointEvent = EventReader.Read<CheckpointEvent>(reader); CheckEventBase(checkpointEvent); Assert.AreEqual("cpKey", checkpointEvent.Key); var discoEvent = EventReader.Read<DiscoveryEvent>(reader); CheckEventBase(discoEvent); Assert.AreEqual(grid.TopologyVersion, discoEvent.TopologyVersion); Assert.AreEqual(grid.GetNodes(), discoEvent.TopologyNodes); var jobEvent = EventReader.Read<JobEvent>(reader); CheckEventBase(jobEvent); Assert.AreEqual(expectedGridGuid, jobEvent.JobId); Assert.AreEqual("taskClsName", jobEvent.TaskClassName); Assert.AreEqual("taskName", jobEvent.TaskName); Assert.AreEqual(locNode, jobEvent.TaskNode); Assert.AreEqual(expectedGridGuid, jobEvent.TaskSessionId); Assert.AreEqual(expectedGuid, jobEvent.TaskSubjectId); var spaceEvent = EventReader.Read<SwapSpaceEvent>(reader); CheckEventBase(spaceEvent); Assert.AreEqual("space", spaceEvent.Space); var taskEvent = EventReader.Read<TaskEvent>(reader); CheckEventBase(taskEvent); Assert.AreEqual(true,taskEvent.Internal); Assert.AreEqual(expectedGuid, taskEvent.SubjectId); Assert.AreEqual("taskClsName", taskEvent.TaskClassName); Assert.AreEqual("taskName", taskEvent.TaskName); Assert.AreEqual(expectedGridGuid, taskEvent.TaskSessionId); } } /// <summary> /// Checks base event fields serialization. /// </summary> /// <param name="evt">The evt.</param> private void CheckEventBase(IEvent evt) { var locNode = _grid1.GetCluster().GetLocalNode(); Assert.AreEqual(locNode, evt.Node); Assert.AreEqual("msg", evt.Message); Assert.AreEqual(EventType.SwapSpaceCleared, evt.Type); Assert.IsNotNullOrEmpty(evt.Name); Assert.AreNotEqual(Guid.Empty, evt.Id.GlobalId); Assert.IsTrue(Math.Abs((evt.Timestamp - DateTime.UtcNow).TotalSeconds) < 20, "Invalid event timestamp: '{0}', current time: '{1}'", evt.Timestamp, DateTime.Now); } /// <summary> /// Sends events in various ways and verifies correct receive. /// </summary> /// <param name="repeat">Expected event count multiplier.</param> /// <param name="eventObjectType">Expected event object type.</param> /// <param name="eventType">Type of the event.</param> private void CheckSend(int repeat = 1, Type eventObjectType = null, params int[] eventType) { EventsTestHelper.ClearReceived(repeat); GenerateTaskEvent(); EventsTestHelper.VerifyReceive(repeat, eventObjectType ?? typeof (TaskEvent), eventType.Any() ? eventType : EventType.TaskExecutionAll); } /// <summary> /// Checks that no event has arrived. /// </summary> private void CheckNoEvent() { // this will result in an exception in case of a event EventsTestHelper.ClearReceived(0); GenerateTaskEvent(); Thread.Sleep(EventsTestHelper.Timeout); EventsTestHelper.AssertFailures(); } /// <summary> /// Gets the Ignite configuration. /// </summary> private static IgniteConfiguration Configuration(string springConfigUrl) { return new IgniteConfiguration { SpringConfigUrl = springConfigUrl, JvmClasspath = TestUtils.CreateTestClasspath(), JvmOptions = TestUtils.TestJavaOptions(), BinaryConfiguration = new BinaryConfiguration { TypeConfigurations = new List<BinaryTypeConfiguration> { new BinaryTypeConfiguration(typeof (RemoteEventBinarizableFilter)) } } }; } /// <summary> /// Generates the task event. /// </summary> private void GenerateTaskEvent(IIgnite grid = null) { (grid ?? _grid1).GetCompute().Broadcast(new ComputeAction()); } /// <summary> /// Verifies the task events. /// </summary> private static void VerifyTaskEvents(IEnumerable<IEvent> events) { var e = events.Cast<TaskEvent>().ToArray(); // started, reduced, finished Assert.AreEqual( new[] {EventType.TaskStarted, EventType.TaskReduced, EventType.TaskFinished}, e.Select(x => x.Type).ToArray()); } /// <summary> /// Generates the cache query event. /// </summary> private static void GenerateCacheQueryEvent(IIgnite g) { var cache = g.GetCache<int, int>(null); cache.Clear(); cache.Put(1, 1); cache.Query(new ScanQuery<int, int>()).GetAll(); } /// <summary> /// Verifies the cache events. /// </summary> private static void VerifyCacheEvents(IEnumerable<IEvent> events, IIgnite grid) { var e = events.Cast<CacheEvent>().ToArray(); foreach (var cacheEvent in e) { Assert.AreEqual(null, cacheEvent.CacheName); Assert.AreEqual(null, cacheEvent.ClosureClassName); Assert.AreEqual(null, cacheEvent.TaskName); Assert.AreEqual(grid.GetCluster().GetLocalNode(), cacheEvent.EventNode); Assert.AreEqual(grid.GetCluster().GetLocalNode(), cacheEvent.Node); Assert.AreEqual(false, cacheEvent.HasOldValue); Assert.AreEqual(null, cacheEvent.OldValue); if (cacheEvent.Type == EventType.CacheObjectPut) { Assert.AreEqual(true, cacheEvent.HasNewValue); Assert.AreEqual(1, cacheEvent.NewValue); } else if (cacheEvent.Type == EventType.CacheEntryCreated) { Assert.AreEqual(false, cacheEvent.HasNewValue); Assert.AreEqual(null, cacheEvent.NewValue); } else { Assert.Fail("Unexpected event type"); } } } /// <summary> /// Starts the grids. /// </summary> private void StartGrids() { if (_grid1 != null) return; _grid1 = Ignition.Start(Configuration("config\\compute\\compute-grid1.xml")); _grid2 = Ignition.Start(Configuration("config\\compute\\compute-grid2.xml")); _grid3 = Ignition.Start(Configuration("config\\compute\\compute-grid3.xml")); _grids = new[] {_grid1, _grid2, _grid3}; } /// <summary> /// Stops the grids. /// </summary> private void StopGrids() { _grid1 = _grid2 = _grid3 = null; _grids = null; Ignition.StopAll(true); } } /// <summary> /// Event test helper class. /// </summary> [Serializable] public static class EventsTestHelper { /** */ public static readonly ConcurrentStack<IEvent> ReceivedEvents = new ConcurrentStack<IEvent>(); /** */ public static readonly ConcurrentStack<string> Failures = new ConcurrentStack<string>(); /** */ public static readonly CountdownEvent ReceivedEvent = new CountdownEvent(0); /** */ public static readonly ConcurrentStack<Guid?> LastNodeIds = new ConcurrentStack<Guid?>(); /** */ public static volatile bool ListenResult = true; /** */ public static readonly TimeSpan Timeout = TimeSpan.FromMilliseconds(800); /// <summary> /// Clears received event information. /// </summary> /// <param name="expectedCount">The expected count of events to be received.</param> public static void ClearReceived(int expectedCount) { ReceivedEvents.Clear(); ReceivedEvent.Reset(expectedCount); LastNodeIds.Clear(); } /// <summary> /// Verifies received events against events events. /// </summary> public static void VerifyReceive(int count, Type eventObjectType, ICollection<int> eventTypes) { // check if expected event count has been received; Wait returns false if there were none. Assert.IsTrue(ReceivedEvent.Wait(Timeout), "Failed to receive expected number of events. Remaining count: " + ReceivedEvent.CurrentCount); Assert.AreEqual(count, ReceivedEvents.Count); Assert.IsTrue(ReceivedEvents.All(x => x.GetType() == eventObjectType)); Assert.IsTrue(ReceivedEvents.All(x => eventTypes.Contains(x.Type))); AssertFailures(); } /// <summary> /// Gets the event listener. /// </summary> /// <returns>New instance of event listener.</returns> public static IEventListener<IEvent> GetListener() { return new EventFilter<IEvent>(Listen); } /// <summary> /// Combines accumulated failures and throws an assertion, if there are any. /// Clears accumulated failures. /// </summary> public static void AssertFailures() { try { if (Failures.Any()) Assert.Fail(Failures.Reverse().Aggregate((x, y) => string.Format("{0}\n{1}", x, y))); } finally { Failures.Clear(); } } /// <summary> /// Listen method. /// </summary> /// <param name="evt">Event.</param> private static bool Listen(IEvent evt) { try { LastNodeIds.Push(evt.Node.Id); ReceivedEvents.Push(evt); ReceivedEvent.Signal(); return ListenResult; } catch (Exception ex) { // When executed on remote nodes, these exceptions will not go to sender, // so we have to accumulate them. Failures.Push(string.Format("Exception in Listen (msg: {0}, id: {1}): {2}", evt, evt.Node.Id, ex)); throw; } } } /// <summary> /// Test event filter. /// </summary> [Serializable] public class EventFilter<T> : IEventFilter<T>, IEventListener<T> where T : IEvent { /** */ private readonly Func<T, bool> _invoke; /// <summary> /// Initializes a new instance of the <see cref="RemoteListenEventFilter"/> class. /// </summary> /// <param name="invoke">The invoke delegate.</param> public EventFilter(Func<T, bool> invoke) { _invoke = invoke; } /** <inheritdoc /> */ bool IEventFilter<T>.Invoke(T evt) { return _invoke(evt); } /** <inheritdoc /> */ bool IEventListener<T>.Invoke(T evt) { return _invoke(evt); } /** <inheritdoc /> */ public bool Invoke(T evt) { throw new Exception("Invalid method"); } } /// <summary> /// Remote event filter. /// </summary> [Serializable] public class RemoteEventFilter : IEventFilter<IEvent> { /** */ private readonly int _type; public RemoteEventFilter(int type) { _type = type; } /** <inheritdoc /> */ public bool Invoke(IEvent evt) { return evt.Type == _type; } } /// <summary> /// Binary remote event filter. /// </summary> public class RemoteEventBinarizableFilter : IEventFilter<IEvent>, IBinarizable { /** */ private int _type; /// <summary> /// Initializes a new instance of the <see cref="RemoteEventBinarizableFilter"/> class. /// </summary> /// <param name="type">The event type.</param> public RemoteEventBinarizableFilter(int type) { _type = type; } /** <inheritdoc /> */ public bool Invoke(IEvent evt) { return evt.Type == _type; } /** <inheritdoc /> */ public void WriteBinary(IBinaryWriter writer) { writer.GetRawWriter().WriteInt(_type); } /** <inheritdoc /> */ public void ReadBinary(IBinaryReader reader) { _type = reader.GetRawReader().ReadInt(); } } /// <summary> /// Event test case. /// </summary> public class EventTestCase { /// <summary> /// Gets or sets the type of the event. /// </summary> public ICollection<int> EventType { get; set; } /// <summary> /// Gets or sets the type of the event object. /// </summary> public Type EventObjectType { get; set; } /// <summary> /// Gets or sets the generate event action. /// </summary> public Action<IIgnite> GenerateEvent { get; set; } /// <summary> /// Gets or sets the verify events action. /// </summary> public Action<IEnumerable<IEvent>, IIgnite> VerifyEvents { get; set; } /// <summary> /// Gets or sets the event count. /// </summary> public int EventCount { get; set; } /** <inheritdoc /> */ public override string ToString() { return EventObjectType.ToString(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Globalization; using System.Runtime.InteropServices; using Xunit; namespace System.Numerics.Tests { public class Vector3Tests { [Fact] public void Vector3MarshalSizeTest() { Assert.Equal(12, Marshal.SizeOf<Vector3>()); Assert.Equal(12, Marshal.SizeOf<Vector3>(new Vector3())); } [Fact] public void Vector3CopyToTest() { Vector3 v1 = new Vector3(2.0f, 3.0f, 3.3f); Single[] a = new Single[4]; Single[] b = new Single[3]; v1.CopyTo(a, 1); v1.CopyTo(b); Assert.Equal(0.0f, a[0]); Assert.Equal(2.0f, a[1]); Assert.Equal(3.0f, a[2]); Assert.Equal(3.3f, a[3]); Assert.Equal(2.0f, b[0]); Assert.Equal(3.0f, b[1]); Assert.Equal(3.3f, b[2]); } [Fact] public void Vector3GetHashCodeTest() { Vector3 v1 = new Vector3(2.0f, 3.0f, 3.3f); Vector3 v2 = new Vector3(4.5f, 6.5f, 7.5f); Vector3 v3 = new Vector3(2.0f, 3.0f, 3.3f); Vector3 v5 = new Vector3(3.0f, 2.0f, 3.3f); Assert.True(v1.GetHashCode() == v1.GetHashCode()); Assert.False(v1.GetHashCode() == v5.GetHashCode()); Assert.True(v1.GetHashCode() == v3.GetHashCode()); Vector3 v4 = new Vector3(0.0f, 0.0f, 0.0f); Vector3 v6 = new Vector3(1.0f, 0.0f, 0.0f); Vector3 v7 = new Vector3(0.0f, 1.0f, 0.0f); Vector3 v8 = new Vector3(1.0f, 1.0f, 1.0f); Vector3 v9 = new Vector3(1.0f, 1.0f, 0.0f); Assert.False(v4.GetHashCode() == v6.GetHashCode()); Assert.False(v4.GetHashCode() == v7.GetHashCode()); Assert.False(v4.GetHashCode() == v8.GetHashCode()); Assert.False(v7.GetHashCode() == v6.GetHashCode()); Assert.False(v8.GetHashCode() == v6.GetHashCode()); Assert.True(v8.GetHashCode() == v7.GetHashCode()); Assert.False(v8.GetHashCode() == v9.GetHashCode()); Assert.False(v7.GetHashCode() == v9.GetHashCode()); } [Fact] public void Vector3ToStringTest() { string separator = CultureInfo.CurrentCulture.NumberFormat.NumberGroupSeparator; CultureInfo enUsCultureInfo = new CultureInfo("en-US"); Vector3 v1 = new Vector3(2.0f, 3.0f, 3.3f); string v1str = v1.ToString(); string expectedv1 = string.Format(CultureInfo.CurrentCulture , "<{1:G}{0} {2:G}{0} {3:G}>" , separator, 2, 3, 3.3); Assert.Equal(expectedv1, v1str); string v1strformatted = v1.ToString("c", CultureInfo.CurrentCulture); string expectedv1formatted = string.Format(CultureInfo.CurrentCulture , "<{1:c}{0} {2:c}{0} {3:c}>" , separator, 2, 3, 3.3); Assert.Equal(expectedv1formatted, v1strformatted); string v2strformatted = v1.ToString("c", enUsCultureInfo); string expectedv2formatted = string.Format(enUsCultureInfo , "<{1:c}{0} {2:c}{0} {3:c}>" , enUsCultureInfo.NumberFormat.NumberGroupSeparator, 2, 3, 3.3); Assert.Equal(expectedv2formatted, v2strformatted); string v3strformatted = v1.ToString("c"); string expectedv3formatted = string.Format(CultureInfo.CurrentCulture , "<{1:c}{0} {2:c}{0} {3:c}>" , separator, 2, 3, 3.3); Assert.Equal(expectedv3formatted, v3strformatted); } // A test for Cross (Vector3f, Vector3f) [Fact] public void Vector3CrossTest() { Vector3 a = new Vector3(1.0f, 0.0f, 0.0f); Vector3 b = new Vector3(0.0f, 1.0f, 0.0f); Vector3 expected = new Vector3(0.0f, 0.0f, 1.0f); Vector3 actual; actual = Vector3.Cross(a, b); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Cross did not return the expected value."); } // A test for Cross (Vector3f, Vector3f) // Cross test of the same vector [Fact] public void Vector3CrossTest1() { Vector3 a = new Vector3(0.0f, 1.0f, 0.0f); Vector3 b = new Vector3(0.0f, 1.0f, 0.0f); Vector3 expected = new Vector3(0.0f, 0.0f, 0.0f); Vector3 actual = Vector3.Cross(a, b); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Cross did not return the expected value."); } // A test for Distance (Vector3f, Vector3f) [Fact] public void Vector3DistanceTest() { Vector3 a = new Vector3(1.0f, 2.0f, 3.0f); Vector3 b = new Vector3(4.0f, 5.0f, 6.0f); float expected = (float)System.Math.Sqrt(27); float actual; actual = Vector3.Distance(a, b); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Distance did not return the expected value."); } // A test for Distance (Vector3f, Vector3f) // Distance from the same point [Fact] public void Vector3DistanceTest1() { Vector3 a = new Vector3(1.051f, 2.05f, 3.478f); Vector3 b = new Vector3(new Vector2(1.051f, 0.0f), 1); b.Y = 2.05f; b.Z = 3.478f; float actual = Vector3.Distance(a, b); Assert.Equal(0.0f, actual); } // A test for DistanceSquared (Vector3f, Vector3f) [Fact] public void Vector3DistanceSquaredTest() { Vector3 a = new Vector3(1.0f, 2.0f, 3.0f); Vector3 b = new Vector3(4.0f, 5.0f, 6.0f); float expected = 27.0f; float actual; actual = Vector3.DistanceSquared(a, b); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.DistanceSquared did not return the expected value."); } // A test for Dot (Vector3f, Vector3f) [Fact] public void Vector3DotTest() { Vector3 a = new Vector3(1.0f, 2.0f, 3.0f); Vector3 b = new Vector3(4.0f, 5.0f, 6.0f); float expected = 32.0f; float actual; actual = Vector3.Dot(a, b); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Dot did not return the expected value."); } // A test for Dot (Vector3f, Vector3f) // Dot test for perpendicular vector [Fact] public void Vector3DotTest1() { Vector3 a = new Vector3(1.55f, 1.55f, 1); Vector3 b = new Vector3(2.5f, 3, 1.5f); Vector3 c = Vector3.Cross(a, b); float expected = 0.0f; float actual1 = Vector3.Dot(a, c); float actual2 = Vector3.Dot(b, c); Assert.True(MathHelper.Equal(expected, actual1), "Vector3f.Dot did not return the expected value."); Assert.True(MathHelper.Equal(expected, actual2), "Vector3f.Dot did not return the expected value."); } // A test for Length () [Fact] public void Vector3LengthTest() { Vector2 a = new Vector2(1.0f, 2.0f); float z = 3.0f; Vector3 target = new Vector3(a, z); float expected = (float)System.Math.Sqrt(14.0f); float actual; actual = target.Length(); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Length did not return the expected value."); } // A test for Length () // Length test where length is zero [Fact] public void Vector3LengthTest1() { Vector3 target = new Vector3(); float expected = 0.0f; float actual = target.Length(); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Length did not return the expected value."); } // A test for LengthSquared () [Fact] public void Vector3LengthSquaredTest() { Vector2 a = new Vector2(1.0f, 2.0f); float z = 3.0f; Vector3 target = new Vector3(a, z); float expected = 14.0f; float actual; actual = target.LengthSquared(); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.LengthSquared did not return the expected value."); } // A test for Min (Vector3f, Vector3f) [Fact] public void Vector3MinTest() { Vector3 a = new Vector3(-1.0f, 4.0f, -3.0f); Vector3 b = new Vector3(2.0f, 1.0f, -1.0f); Vector3 expected = new Vector3(-1.0f, 1.0f, -3.0f); Vector3 actual; actual = Vector3.Min(a, b); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Min did not return the expected value."); } // A test for Max (Vector3f, Vector3f) [Fact] public void Vector3MaxTest() { Vector3 a = new Vector3(-1.0f, 4.0f, -3.0f); Vector3 b = new Vector3(2.0f, 1.0f, -1.0f); Vector3 expected = new Vector3(2.0f, 4.0f, -1.0f); Vector3 actual; actual = Vector3.Max(a, b); Assert.True(MathHelper.Equal(expected, actual), "vector3.Max did not return the expected value."); } [Fact] public void Vector3MinMaxCodeCoverageTest() { Vector3 min = Vector3.Zero; Vector3 max = Vector3.One; Vector3 actual; // Min. actual = Vector3.Min(min, max); Assert.Equal(actual, min); actual = Vector3.Min(max, min); Assert.Equal(actual, min); // Max. actual = Vector3.Max(min, max); Assert.Equal(actual, max); actual = Vector3.Max(max, min); Assert.Equal(actual, max); } // A test for Lerp (Vector3f, Vector3f, float) [Fact] public void Vector3LerpTest() { Vector3 a = new Vector3(1.0f, 2.0f, 3.0f); Vector3 b = new Vector3(4.0f, 5.0f, 6.0f); float t = 0.5f; Vector3 expected = new Vector3(2.5f, 3.5f, 4.5f); Vector3 actual; actual = Vector3.Lerp(a, b, t); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Lerp did not return the expected value."); } // A test for Lerp (Vector3f, Vector3f, float) // Lerp test with factor zero [Fact] public void Vector3LerpTest1() { Vector3 a = new Vector3(1.0f, 2.0f, 3.0f); Vector3 b = new Vector3(4.0f, 5.0f, 6.0f); float t = 0.0f; Vector3 expected = new Vector3(1.0f, 2.0f, 3.0f); Vector3 actual = Vector3.Lerp(a, b, t); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Lerp did not return the expected value."); } // A test for Lerp (Vector3f, Vector3f, float) // Lerp test with factor one [Fact] public void Vector3LerpTest2() { Vector3 a = new Vector3(1.0f, 2.0f, 3.0f); Vector3 b = new Vector3(4.0f, 5.0f, 6.0f); float t = 1.0f; Vector3 expected = new Vector3(4.0f, 5.0f, 6.0f); Vector3 actual = Vector3.Lerp(a, b, t); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Lerp did not return the expected value."); } // A test for Lerp (Vector3f, Vector3f, float) // Lerp test with factor > 1 [Fact] public void Vector3LerpTest3() { Vector3 a = new Vector3(0.0f, 0.0f, 0.0f); Vector3 b = new Vector3(4.0f, 5.0f, 6.0f); float t = 2.0f; Vector3 expected = new Vector3(8.0f, 10.0f, 12.0f); Vector3 actual = Vector3.Lerp(a, b, t); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Lerp did not return the expected value."); } // A test for Lerp (Vector3f, Vector3f, float) // Lerp test with factor < 0 [Fact] public void Vector3LerpTest4() { Vector3 a = new Vector3(0.0f, 0.0f, 0.0f); Vector3 b = new Vector3(4.0f, 5.0f, 6.0f); float t = -2.0f; Vector3 expected = new Vector3(-8.0f, -10.0f, -12.0f); Vector3 actual = Vector3.Lerp(a, b, t); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Lerp did not return the expected value."); } // A test for Lerp (Vector3f, Vector3f, float) // Lerp test from the same point [Fact] public void Vector3LerpTest5() { Vector3 a = new Vector3(1.68f, 2.34f, 5.43f); Vector3 b = a; float t = 0.18f; Vector3 expected = new Vector3(1.68f, 2.34f, 5.43f); Vector3 actual = Vector3.Lerp(a, b, t); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Lerp did not return the expected value."); } // A test for Reflect (Vector3f, Vector3f) [Fact] public void Vector3ReflectTest() { Vector3 a = Vector3.Normalize(new Vector3(1.0f, 1.0f, 1.0f)); // Reflect on XZ plane. Vector3 n = new Vector3(0.0f, 1.0f, 0.0f); Vector3 expected = new Vector3(a.X, -a.Y, a.Z); Vector3 actual = Vector3.Reflect(a, n); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Reflect did not return the expected value."); // Reflect on XY plane. n = new Vector3(0.0f, 0.0f, 1.0f); expected = new Vector3(a.X, a.Y, -a.Z); actual = Vector3.Reflect(a, n); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Reflect did not return the expected value."); // Reflect on YZ plane. n = new Vector3(1.0f, 0.0f, 0.0f); expected = new Vector3(-a.X, a.Y, a.Z); actual = Vector3.Reflect(a, n); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Reflect did not return the expected value."); } // A test for Reflect (Vector3f, Vector3f) // Reflection when normal and source are the same [Fact] public void Vector3ReflectTest1() { Vector3 n = new Vector3(0.45f, 1.28f, 0.86f); n = Vector3.Normalize(n); Vector3 a = n; Vector3 expected = -n; Vector3 actual = Vector3.Reflect(a, n); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Reflect did not return the expected value."); } // A test for Reflect (Vector3f, Vector3f) // Reflection when normal and source are negation [Fact] public void Vector3ReflectTest2() { Vector3 n = new Vector3(0.45f, 1.28f, 0.86f); n = Vector3.Normalize(n); Vector3 a = -n; Vector3 expected = n; Vector3 actual = Vector3.Reflect(a, n); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Reflect did not return the expected value."); } // A test for Reflect (Vector3f, Vector3f) // Reflection when normal and source are perpendicular (a dot n = 0) [Fact] public void Vector3ReflectTest3() { Vector3 n = new Vector3(0.45f, 1.28f, 0.86f); Vector3 temp = new Vector3(1.28f, 0.45f, 0.01f); // find a perpendicular vector of n Vector3 a = Vector3.Cross(temp, n); Vector3 expected = a; Vector3 actual = Vector3.Reflect(a, n); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Reflect did not return the expected value."); } // A test for Transform(Vector3f, Matrix4x4) [Fact] public void Vector3TransformTest() { Vector3 v = new Vector3(1.0f, 2.0f, 3.0f); Matrix4x4 m = Matrix4x4.CreateRotationX(MathHelper.ToRadians(30.0f)) * Matrix4x4.CreateRotationY(MathHelper.ToRadians(30.0f)) * Matrix4x4.CreateRotationZ(MathHelper.ToRadians(30.0f)); m.M41 = 10.0f; m.M42 = 20.0f; m.M43 = 30.0f; Vector3 expected = new Vector3(12.191987f, 21.533493f, 32.616024f); Vector3 actual; actual = Vector3.Transform(v, m); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Transform did not return the expected value."); } // A test for Clamp (Vector3f, Vector3f, Vector3f) [Fact] public void Vector3ClampTest() { Vector3 a = new Vector3(0.5f, 0.3f, 0.33f); Vector3 min = new Vector3(0.0f, 0.1f, 0.13f); Vector3 max = new Vector3(1.0f, 1.1f, 1.13f); // Normal case. // Case N1: specfied value is in the range. Vector3 expected = new Vector3(0.5f, 0.3f, 0.33f); Vector3 actual = Vector3.Clamp(a, min, max); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Clamp did not return the expected value."); // Normal case. // Case N2: specfied value is bigger than max value. a = new Vector3(2.0f, 3.0f, 4.0f); expected = max; actual = Vector3.Clamp(a, min, max); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Clamp did not return the expected value."); // Case N3: specfied value is smaller than max value. a = new Vector3(-2.0f, -3.0f, -4.0f); expected = min; actual = Vector3.Clamp(a, min, max); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Clamp did not return the expected value."); // Case N4: combination case. a = new Vector3(-2.0f, 0.5f, 4.0f); expected = new Vector3(min.X, a.Y, max.Z); actual = Vector3.Clamp(a, min, max); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Clamp did not return the expected value."); // User specfied min value is bigger than max value. max = new Vector3(0.0f, 0.1f, 0.13f); min = new Vector3(1.0f, 1.1f, 1.13f); // Case W1: specfied value is in the range. a = new Vector3(0.5f, 0.3f, 0.33f); expected = min; actual = Vector3.Clamp(a, min, max); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Clamp did not return the expected value."); // Normal case. // Case W2: specfied value is bigger than max and min value. a = new Vector3(2.0f, 3.0f, 4.0f); expected = min; actual = Vector3.Clamp(a, min, max); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Clamp did not return the expected value."); // Case W3: specfied value is smaller than min and max value. a = new Vector3(-2.0f, -3.0f, -4.0f); expected = min; actual = Vector3.Clamp(a, min, max); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Clamp did not return the expected value."); } // A test for TransformNormal (Vector3f, Matrix4x4) [Fact] public void Vector3TransformNormalTest() { Vector3 v = new Vector3(1.0f, 2.0f, 3.0f); Matrix4x4 m = Matrix4x4.CreateRotationX(MathHelper.ToRadians(30.0f)) * Matrix4x4.CreateRotationY(MathHelper.ToRadians(30.0f)) * Matrix4x4.CreateRotationZ(MathHelper.ToRadians(30.0f)); m.M41 = 10.0f; m.M42 = 20.0f; m.M43 = 30.0f; Vector3 expected = new Vector3(2.19198728f, 1.53349364f, 2.61602545f); Vector3 actual; actual = Vector3.TransformNormal(v, m); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.TransformNormal did not return the expected value."); } // A test for Transform (Vector3f, Quaternion) [Fact] public void Vector3TransformByQuaternionTest() { Vector3 v = new Vector3(1.0f, 2.0f, 3.0f); Matrix4x4 m = Matrix4x4.CreateRotationX(MathHelper.ToRadians(30.0f)) * Matrix4x4.CreateRotationY(MathHelper.ToRadians(30.0f)) * Matrix4x4.CreateRotationZ(MathHelper.ToRadians(30.0f)); Quaternion q = Quaternion.CreateFromRotationMatrix(m); Vector3 expected = Vector3.Transform(v, m); Vector3 actual = Vector3.Transform(v, q); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Transform did not return the expected value."); } // A test for Transform (Vector3f, Quaternion) // Transform vector3 with zero quaternion [Fact] public void Vector3TransformByQuaternionTest1() { Vector3 v = new Vector3(1.0f, 2.0f, 3.0f); Quaternion q = new Quaternion(); Vector3 expected = v; Vector3 actual = Vector3.Transform(v, q); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Transform did not return the expected value."); } // A test for Transform (Vector3f, Quaternion) // Transform vector3 with identity quaternion [Fact] public void Vector3TransformByQuaternionTest2() { Vector3 v = new Vector3(1.0f, 2.0f, 3.0f); Quaternion q = Quaternion.Identity; Vector3 expected = v; Vector3 actual = Vector3.Transform(v, q); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Transform did not return the expected value."); } // A test for Normalize (Vector3f) [Fact] public void Vector3NormalizeTest() { Vector3 a = new Vector3(1.0f, 2.0f, 3.0f); Vector3 expected = new Vector3( 0.26726124191242438468455348087975f, 0.53452248382484876936910696175951f, 0.80178372573727315405366044263926f); Vector3 actual; actual = Vector3.Normalize(a); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Normalize did not return the expected value."); } // A test for Normalize (Vector3f) // Normalize vector of length one [Fact] public void Vector3NormalizeTest1() { Vector3 a = new Vector3(1.0f, 0.0f, 0.0f); Vector3 expected = new Vector3(1.0f, 0.0f, 0.0f); Vector3 actual = Vector3.Normalize(a); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Normalize did not return the expected value."); } // A test for Normalize (Vector3f) // Normalize vector of length zero [Fact] public void Vector3NormalizeTest2() { Vector3 a = new Vector3(0.0f, 0.0f, 0.0f); Vector3 expected = new Vector3(0.0f, 0.0f, 0.0f); Vector3 actual = Vector3.Normalize(a); Assert.True(float.IsNaN(actual.X) && float.IsNaN(actual.Y) && float.IsNaN(actual.Z), "Vector3f.Normalize did not return the expected value."); } // A test for operator - (Vector3f) [Fact] public void Vector3UnaryNegationTest() { Vector3 a = new Vector3(1.0f, 2.0f, 3.0f); Vector3 expected = new Vector3(-1.0f, -2.0f, -3.0f); Vector3 actual; actual = -a; Assert.True(MathHelper.Equal(expected, actual), "Vector3f.operator - did not return the expected value."); } [Fact] public void Vector3UnaryNegationTest1() { Vector3 a = -new Vector3(Single.NaN, Single.PositiveInfinity, Single.NegativeInfinity); Vector3 b = -new Vector3(0.0f, 0.0f, 0.0f); Assert.Equal(Single.NaN, a.X); Assert.Equal(Single.NegativeInfinity, a.Y); Assert.Equal(Single.PositiveInfinity, a.Z); Assert.Equal(0.0f, b.X); Assert.Equal(0.0f, b.Y); Assert.Equal(0.0f, b.Z); } // A test for operator - (Vector3f, Vector3f) [Fact] public void Vector3SubtractionTest() { Vector3 a = new Vector3(4.0f, 2.0f, 3.0f); Vector3 b = new Vector3(1.0f, 5.0f, 7.0f); Vector3 expected = new Vector3(3.0f, -3.0f, -4.0f); Vector3 actual; actual = a - b; Assert.True(MathHelper.Equal(expected, actual), "Vector3f.operator - did not return the expected value."); } // A test for operator * (Vector3f, float) [Fact] public void Vector3MultiplyTest() { Vector3 a = new Vector3(1.0f, 2.0f, 3.0f); float factor = 2.0f; Vector3 expected = new Vector3(2.0f, 4.0f, 6.0f); Vector3 actual; actual = a * factor; Assert.True(MathHelper.Equal(expected, actual), "Vector3f.operator * did not return the expected value."); } // A test for operator * (Vector3f, Vector3f) [Fact] public void Vector3MultiplyTest1() { Vector3 a = new Vector3(1.0f, 2.0f, 3.0f); Vector3 b = new Vector3(4.0f, 5.0f, 6.0f); Vector3 expected = new Vector3(4.0f, 10.0f, 18.0f); Vector3 actual; actual = a * b; Assert.True(MathHelper.Equal(expected, actual), "Vector3f.operator * did not return the expected value."); } // A test for operator / (Vector3f, float) [Fact] public void Vector3DivisionTest() { Vector3 a = new Vector3(1.0f, 2.0f, 3.0f); float div = 2.0f; Vector3 expected = new Vector3(0.5f, 1.0f, 1.5f); Vector3 actual; actual = a / div; Assert.True(MathHelper.Equal(expected, actual), "Vector3f.operator / did not return the expected value."); } // A test for operator / (Vector3f, Vector3f) [Fact] public void Vector3DivisionTest1() { Vector3 a = new Vector3(4.0f, 2.0f, 3.0f); Vector3 b = new Vector3(1.0f, 5.0f, 6.0f); Vector3 expected = new Vector3(4.0f, 0.4f, 0.5f); Vector3 actual; actual = a / b; Assert.True(MathHelper.Equal(expected, actual), "Vector3f.operator / did not return the expected value."); } // A test for operator / (Vector3f, Vector3f) // Divide by zero [Fact] public void Vector3DivisionTest2() { Vector3 a = new Vector3(-2.0f, 3.0f, float.MaxValue); float div = 0.0f; Vector3 actual = a / div; Assert.True(float.IsNegativeInfinity(actual.X), "Vector3f.operator / did not return the expected value."); Assert.True(float.IsPositiveInfinity(actual.Y), "Vector3f.operator / did not return the expected value."); Assert.True(float.IsPositiveInfinity(actual.Z), "Vector3f.operator / did not return the expected value."); } // A test for operator / (Vector3f, Vector3f) // Divide by zero [Fact] public void Vector3DivisionTest3() { Vector3 a = new Vector3(0.047f, -3.0f, float.NegativeInfinity); Vector3 b = new Vector3(); Vector3 actual = a / b; Assert.True(float.IsPositiveInfinity(actual.X), "Vector3f.operator / did not return the expected value."); Assert.True(float.IsNegativeInfinity(actual.Y), "Vector3f.operator / did not return the expected value."); Assert.True(float.IsNegativeInfinity(actual.Z), "Vector3f.operator / did not return the expected value."); } // A test for operator + (Vector3f, Vector3f) [Fact] public void Vector3AdditionTest() { Vector3 a = new Vector3(1.0f, 2.0f, 3.0f); Vector3 b = new Vector3(4.0f, 5.0f, 6.0f); Vector3 expected = new Vector3(5.0f, 7.0f, 9.0f); Vector3 actual; actual = a + b; Assert.True(MathHelper.Equal(expected, actual), "Vector3f.operator + did not return the expected value."); } // A test for Vector3f (float, float, float) [Fact] public void Vector3ConstructorTest() { float x = 1.0f; float y = 2.0f; float z = 3.0f; Vector3 target = new Vector3(x, y, z); Assert.True(MathHelper.Equal(target.X, x) && MathHelper.Equal(target.Y, y) && MathHelper.Equal(target.Z, z), "Vector3f.constructor (x,y,z) did not return the expected value."); } // A test for Vector3f (Vector2f, float) [Fact] public void Vector3ConstructorTest1() { Vector2 a = new Vector2(1.0f, 2.0f); float z = 3.0f; Vector3 target = new Vector3(a, z); Assert.True(MathHelper.Equal(target.X, a.X) && MathHelper.Equal(target.Y, a.Y) && MathHelper.Equal(target.Z, z), "Vector3f.constructor (Vector2f,z) did not return the expected value."); } // A test for Vector3f () // Constructor with no parameter [Fact] public void Vector3ConstructorTest3() { Vector3 a = new Vector3(); Assert.Equal(a.X, 0.0f); Assert.Equal(a.Y, 0.0f); Assert.Equal(a.Z, 0.0f); } // A test for Vector2f (float, float) // Constructor with special floating values [Fact] public void Vector3ConstructorTest4() { Vector3 target = new Vector3(float.NaN, float.MaxValue, float.PositiveInfinity); Assert.True(float.IsNaN(target.X), "Vector3f.constructor (Vector3f) did not return the expected value."); Assert.True(float.Equals(float.MaxValue, target.Y), "Vector3f.constructor (Vector3f) did not return the expected value."); Assert.True(float.IsPositiveInfinity(target.Z), "Vector3f.constructor (Vector3f) did not return the expected value."); } // A test for Add (Vector3f, Vector3f) [Fact] public void Vector3AddTest() { Vector3 a = new Vector3(1.0f, 2.0f, 3.0f); Vector3 b = new Vector3(5.0f, 6.0f, 7.0f); Vector3 expected = new Vector3(6.0f, 8.0f, 10.0f); Vector3 actual; actual = Vector3.Add(a, b); Assert.Equal(expected, actual); } // A test for Divide (Vector3f, float) [Fact] public void Vector3DivideTest() { Vector3 a = new Vector3(1.0f, 2.0f, 3.0f); float div = 2.0f; Vector3 expected = new Vector3(0.5f, 1.0f, 1.5f); Vector3 actual; actual = Vector3.Divide(a, div); Assert.Equal(expected, actual); } // A test for Divide (Vector3f, Vector3f) [Fact] public void Vector3DivideTest1() { Vector3 a = new Vector3(1.0f, 6.0f, 7.0f); Vector3 b = new Vector3(5.0f, 2.0f, 3.0f); Vector3 expected = new Vector3(1.0f / 5.0f, 6.0f / 2.0f, 7.0f / 3.0f); Vector3 actual; actual = Vector3.Divide(a, b); Assert.Equal(expected, actual); } // A test for Equals (object) [Fact] public void Vector3EqualsTest() { Vector3 a = new Vector3(1.0f, 2.0f, 3.0f); Vector3 b = new Vector3(1.0f, 2.0f, 3.0f); // case 1: compare between same values object obj = b; bool expected = true; bool actual = a.Equals(obj); Assert.Equal(expected, actual); // case 2: compare between different values b.X = 10.0f; obj = b; expected = false; actual = a.Equals(obj); Assert.Equal(expected, actual); // case 3: compare between different types. obj = new Quaternion(); expected = false; actual = a.Equals(obj); Assert.Equal(expected, actual); // case 3: compare against null. obj = null; expected = false; actual = a.Equals(obj); Assert.Equal(expected, actual); } // A test for Multiply (Vector3f, float) [Fact] public void Vector3MultiplyTest2() { Vector3 a = new Vector3(1.0f, 2.0f, 3.0f); float factor = 2.0f; Vector3 expected = new Vector3(2.0f, 4.0f, 6.0f); Vector3 actual = Vector3.Multiply(a, factor); Assert.Equal(expected, actual); } // A test for Multiply (Vector3f, Vector3f) [Fact] public void Vector3MultiplyTest3() { Vector3 a = new Vector3(1.0f, 2.0f, 3.0f); Vector3 b = new Vector3(5.0f, 6.0f, 7.0f); Vector3 expected = new Vector3(5.0f, 12.0f, 21.0f); Vector3 actual; actual = Vector3.Multiply(a, b); Assert.Equal(expected, actual); } // A test for Negate (Vector3f) [Fact] public void Vector3NegateTest() { Vector3 a = new Vector3(1.0f, 2.0f, 3.0f); Vector3 expected = new Vector3(-1.0f, -2.0f, -3.0f); Vector3 actual; actual = Vector3.Negate(a); Assert.Equal(expected, actual); } // A test for operator != (Vector3f, Vector3f) [Fact] public void Vector3InequalityTest() { Vector3 a = new Vector3(1.0f, 2.0f, 3.0f); Vector3 b = new Vector3(1.0f, 2.0f, 3.0f); // case 1: compare between same values bool expected = false; bool actual = a != b; Assert.Equal(expected, actual); // case 2: compare between different values b.X = 10.0f; expected = true; actual = a != b; Assert.Equal(expected, actual); } // A test for operator == (Vector3f, Vector3f) [Fact] public void Vector3EqualityTest() { Vector3 a = new Vector3(1.0f, 2.0f, 3.0f); Vector3 b = new Vector3(1.0f, 2.0f, 3.0f); // case 1: compare between same values bool expected = true; bool actual = a == b; Assert.Equal(expected, actual); // case 2: compare between different values b.X = 10.0f; expected = false; actual = a == b; Assert.Equal(expected, actual); } // A test for Subtract (Vector3f, Vector3f) [Fact] public void Vector3SubtractTest() { Vector3 a = new Vector3(1.0f, 6.0f, 3.0f); Vector3 b = new Vector3(5.0f, 2.0f, 3.0f); Vector3 expected = new Vector3(-4.0f, 4.0f, 0.0f); Vector3 actual; actual = Vector3.Subtract(a, b); Assert.Equal(expected, actual); } // A test for One [Fact] public void Vector3OneTest() { Vector3 val = new Vector3(1.0f, 1.0f, 1.0f); Assert.Equal(val, Vector3.One); } // A test for UnitX [Fact] public void Vector3UnitXTest() { Vector3 val = new Vector3(1.0f, 0.0f, 0.0f); Assert.Equal(val, Vector3.UnitX); } // A test for UnitY [Fact] public void Vector3UnitYTest() { Vector3 val = new Vector3(0.0f, 1.0f, 0.0f); Assert.Equal(val, Vector3.UnitY); } // A test for UnitZ [Fact] public void Vector3UnitZTest() { Vector3 val = new Vector3(0.0f, 0.0f, 1.0f); Assert.Equal(val, Vector3.UnitZ); } // A test for Zero [Fact] public void Vector3ZeroTest() { Vector3 val = new Vector3(0.0f, 0.0f, 0.0f); Assert.Equal(val, Vector3.Zero); } // A test for Equals (Vector3f) [Fact] public void Vector3EqualsTest1() { Vector3 a = new Vector3(1.0f, 2.0f, 3.0f); Vector3 b = new Vector3(1.0f, 2.0f, 3.0f); // case 1: compare between same values bool expected = true; bool actual = a.Equals(b); Assert.Equal(expected, actual); // case 2: compare between different values b.X = 10.0f; expected = false; actual = a.Equals(b); Assert.Equal(expected, actual); } // A test for Vector3f (float) [Fact] public void Vector3ConstructorTest5() { float value = 1.0f; Vector3 target = new Vector3(value); Vector3 expected = new Vector3(value, value, value); Assert.Equal(expected, target); value = 2.0f; target = new Vector3(value); expected = new Vector3(value, value, value); Assert.Equal(expected, target); } // A test for Vector3f comparison involving NaN values [Fact] public void Vector3EqualsNanTest() { Vector3 a = new Vector3(float.NaN, 0, 0); Vector3 b = new Vector3(0, float.NaN, 0); Vector3 c = new Vector3(0, 0, float.NaN); Assert.False(a == Vector3.Zero); Assert.False(b == Vector3.Zero); Assert.False(c == Vector3.Zero); Assert.True(a != Vector3.Zero); Assert.True(b != Vector3.Zero); Assert.True(c != Vector3.Zero); Assert.False(a.Equals(Vector3.Zero)); Assert.False(b.Equals(Vector3.Zero)); Assert.False(c.Equals(Vector3.Zero)); // Counterintuitive result - IEEE rules for NaN comparison are weird! Assert.False(a.Equals(a)); Assert.False(b.Equals(b)); Assert.False(c.Equals(c)); } [Fact] public void Vector3AbsTest() { Vector3 v1 = new Vector3(-2.5f, 2.0f, 0.5f); Vector3 v3 = Vector3.Abs(new Vector3(0.0f, Single.NegativeInfinity, Single.NaN)); Vector3 v = Vector3.Abs(v1); Assert.Equal(2.5f, v.X); Assert.Equal(2.0f, v.Y); Assert.Equal(0.5f, v.Z); Assert.Equal(0.0f, v3.X); Assert.Equal(Single.PositiveInfinity, v3.Y); Assert.Equal(Single.NaN, v3.Z); } [Fact] public void Vector3SqrtTest() { Vector3 a = new Vector3(-2.5f, 2.0f, 0.5f); Vector3 b = new Vector3(5.5f, 4.5f, 16.5f); Assert.Equal(2, (int)Vector3.SquareRoot(b).X); Assert.Equal(2, (int)Vector3.SquareRoot(b).Y); Assert.Equal(4, (int)Vector3.SquareRoot(b).Z); Assert.Equal(Single.NaN, Vector3.SquareRoot(a).X); } // A test to make sure these types are blittable directly into GPU buffer memory layouts [Fact] public unsafe void Vector3SizeofTest() { Assert.Equal(12, sizeof(Vector3)); Assert.Equal(24, sizeof(Vector3_2x)); Assert.Equal(16, sizeof(Vector3PlusFloat)); Assert.Equal(32, sizeof(Vector3PlusFloat_2x)); } [StructLayout(LayoutKind.Sequential)] struct Vector3_2x { private Vector3 _a; private Vector3 _b; } [StructLayout(LayoutKind.Sequential)] struct Vector3PlusFloat { private Vector3 _v; private float _f; } [StructLayout(LayoutKind.Sequential)] struct Vector3PlusFloat_2x { private Vector3PlusFloat _a; private Vector3PlusFloat _b; } [Fact] public void SetFieldsTest() { Vector3 v3 = new Vector3(4f, 5f, 6f); v3.X = 1.0f; v3.Y = 2.0f; v3.Z = 3.0f; Assert.Equal(1.0f, v3.X); Assert.Equal(2.0f, v3.Y); Assert.Equal(3.0f, v3.Z); Vector3 v4 = v3; v4.Y = 0.5f; v4.Z = 2.2f; Assert.Equal(1.0f, v4.X); Assert.Equal(0.5f, v4.Y); Assert.Equal(2.2f, v4.Z); Assert.Equal(2.0f, v3.Y); Vector3 before = new Vector3(1f, 2f, 3f); Vector3 after = before; after.X = 500.0f; Assert.NotEqual(before, after); } [Fact] public void EmbeddedVectorSetFields() { EmbeddedVectorObject evo = new EmbeddedVectorObject(); evo.FieldVector.X = 5.0f; evo.FieldVector.Y = 5.0f; evo.FieldVector.Z = 5.0f; Assert.Equal(5.0f, evo.FieldVector.X); Assert.Equal(5.0f, evo.FieldVector.Y); Assert.Equal(5.0f, evo.FieldVector.Z); } private class EmbeddedVectorObject { public Vector3 FieldVector; } } }
using System; using System.Collections.Generic; using System.Text; using System.ComponentModel; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework; using FlatRedBall; namespace EffectEditor.HelperClasses { public class EffectProperty { #region Fields private string mName; private object mValue; private bool mReadOnly; private bool mVisible; #endregion #region Properties public string Name { get { return mName; } set { mName = value; } } public object Value { get { return mValue; } set { mValue = value; } } public bool ReadOnly { get { return mReadOnly; } set { mReadOnly = value; } } public bool Visible { get { return mVisible; } set { mVisible = value; } } #endregion #region Methods public EffectProperty(string name, object value, bool readOnly, bool visible) { mName = name; mValue = value; mReadOnly = readOnly; mVisible = visible; } #endregion } public class EffectPropertyDescriptor : PropertyDescriptor { #region Fields private EffectParameter mParameter; private string mTagString; #endregion #region Properties public EffectParameter Parameter { get { return mParameter; } } public override string Category { get { if (mParameter.ParameterClass == EffectParameterClass.MatrixColumns || mParameter.ParameterClass == EffectParameterClass.MatrixRows) { return "Matrices"; } else if (mParameter.ParameterClass == EffectParameterClass.Object && (mParameter.ParameterType == EffectParameterType.Texture || mParameter.ParameterType == EffectParameterType.Texture1D || mParameter.ParameterType == EffectParameterType.Texture2D || mParameter.ParameterType == EffectParameterType.Texture3D || mParameter.ParameterType == EffectParameterType.TextureCube)) { return "Textures"; } else return String.Empty; } } public override string DisplayName { get { return mParameter.Name; } } public override string Name { get { return mParameter.Name; } } public override bool IsBrowsable { get { // Look for annotation if (mParameter.Annotations.Count > 0) { foreach (EffectAnnotation annotation in mParameter.Annotations) { if (annotation.Name == "SasUiVisible") return annotation.GetValueBoolean(); } } switch (mParameter.ParameterType) { case EffectParameterType.Bool: case EffectParameterType.Int32: case EffectParameterType.Single: case EffectParameterType.String: return true; break; case EffectParameterType.Texture: return true; break; case EffectParameterType.Texture1D: case EffectParameterType.Texture2D: case EffectParameterType.Texture3D: case EffectParameterType.TextureCube: default: return false; break; } } } public override string Description { get { // Try to find the annotation if (mParameter.Annotations.Count > 0) { foreach (EffectAnnotation annotation in mParameter.Annotations) { if (annotation.Name == "SasUiDescription") return annotation.GetValueString(); } } // Provide better description based on property // mParameter.Annotations return "Edit the " + Name + " Parameter"; } } #endregion #region Constructor public EffectPropertyDescriptor(EffectParameter parameter, Attribute[] attributes) : base(parameter.Name, attributes) { mParameter = parameter; } Type GetParameterType() { switch (mParameter.ParameterType) { case EffectParameterType.Bool: return typeof(bool); break; case EffectParameterType.Int32: return typeof(Int32); break; case EffectParameterType.Single: switch (mParameter.ParameterClass) { case EffectParameterClass.MatrixColumns: return typeof(Matrix); break; case EffectParameterClass.MatrixRows: return typeof(Matrix); break; case EffectParameterClass.Scalar: return typeof(float); break; case EffectParameterClass.Vector: switch (mParameter.ColumnCount) { case 1: return typeof(float); break; case 2: return typeof(Vector2); break; case 3: return typeof(Vector3); break; case 4: return typeof(Vector4); break; default: return null; break; } break; default: return typeof(float); break; } break; case EffectParameterType.String: return typeof(string); break; case EffectParameterType.Texture: return typeof(string); break; default: return null; break; } } #endregion #region Methods public override bool CanResetValue(object component) { return false; } public override Type ComponentType { get { switch (mParameter.ParameterType) { case EffectParameterType.Bool: return typeof(bool); break; case EffectParameterType.Int32: return typeof(Int32); break; case EffectParameterType.Single: return typeof(float); break; case EffectParameterType.String: return typeof(string); break; case EffectParameterType.Texture: return typeof(string); break; default: return null; break; } } } public override object GetValue(object component) { switch (mParameter.ParameterType) { case EffectParameterType.Bool: return mParameter.GetValueBoolean(); break; case EffectParameterType.Int32: return mParameter.GetValueInt32(); break; case EffectParameterType.Single: switch (mParameter.ParameterClass) { case EffectParameterClass.MatrixColumns: return mParameter.GetValueMatrix(); break; case EffectParameterClass.MatrixRows: return mParameter.GetValueMatrix(); break; case EffectParameterClass.Scalar: return mParameter.GetValueSingle(); break; case EffectParameterClass.Vector: switch (mParameter.ColumnCount) { case 1: return mParameter.GetValueSingle(); break; case 2: return mParameter.GetValueVector2(); break; case 3: return mParameter.GetValueVector3(); break; case 4: return mParameter.GetValueVector4(); break; default: return null; break; } break; default: return mParameter.GetValueSingle(); break; } break; case EffectParameterType.String: return mParameter.GetValueString(); break; case EffectParameterType.Texture: return (mTagString != null) ? mTagString : String.Empty; break; default: return null; break; } return null; } public override bool IsReadOnly { get { return false; } } public override Type PropertyType { get { return GetParameterType(); } } public override void ResetValue(object component) { } public override void SetValue(object component, object value) { switch (mParameter.ParameterType) { case EffectParameterType.Bool: mParameter.SetValue((bool)value); break; case EffectParameterType.Int32: mParameter.SetValue((Int32)value); break; case EffectParameterType.Single: switch (mParameter.ParameterClass) { case EffectParameterClass.MatrixColumns: mParameter.SetValue((Matrix)value); break; case EffectParameterClass.MatrixRows: mParameter.SetValue((Matrix)value); break; case EffectParameterClass.Scalar: mParameter.SetValue((float)value); break; case EffectParameterClass.Vector: switch (mParameter.ColumnCount) { case 1: mParameter.SetValue((float)value); break; case 2: mParameter.SetValue((Vector2)value); break; case 3: mParameter.SetValue((Vector3)value); break; case 4: mParameter.SetValue((Vector4)value); break; default: break; } break; default: mParameter.SetValue((float)value); break; } break; case EffectParameterType.String: mParameter.SetValue((string)value); break; case EffectParameterType.Texture: string fileName = (string)value; if (System.IO.File.Exists(fileName)) { Texture2D texture = FlatRedBallServices.Load<Texture2D>(fileName); mParameter.SetValue(texture); mTagString = fileName; } break; default: break; } } public override object GetEditor(Type editorBaseType) { return base.GetEditor(editorBaseType); } public override bool ShouldSerializeValue(object component) { return false; } #endregion } public class EffectPropertyEditor : ICustomTypeDescriptor { Effect mEffect; public EffectPropertyEditor(Effect effect) { mEffect = effect; } #region ICustomTypeDescriptor Members public AttributeCollection GetAttributes() { return TypeDescriptor.GetAttributes(this, true); } public string GetClassName() { return TypeDescriptor.GetClassName(this, true); } public string GetComponentName() { return TypeDescriptor.GetComponentName(this, true); } public TypeConverter GetConverter() { return TypeDescriptor.GetConverter(this, true); } public EventDescriptor GetDefaultEvent() { return TypeDescriptor.GetDefaultEvent(this, true); } public PropertyDescriptor GetDefaultProperty() { return TypeDescriptor.GetDefaultProperty(this, true); } public object GetEditor(Type editorBaseType) { return TypeDescriptor.GetEditor(this, editorBaseType, true); } public EventDescriptorCollection GetEvents(Attribute[] attributes) { return TypeDescriptor.GetEvents(this, attributes, true); } public EventDescriptorCollection GetEvents() { return TypeDescriptor.GetEvents(this, true); } public PropertyDescriptorCollection GetProperties(Attribute[] attributes) { List<EffectPropertyDescriptor> newProps = new List<EffectPropertyDescriptor>(); for (int i = 0; i < mEffect.Parameters.Count; i++) { List<Attribute> attrs = new List<Attribute>(); if (mEffect.Parameters[i].ParameterType == EffectParameterType.Texture) { attrs.Add(new EditorAttribute( typeof(System.Windows.Forms.Design.FileNameEditor), typeof(System.Drawing.Design.UITypeEditor))); } attrs.AddRange(attributes); EffectPropertyDescriptor newPropDesc = new EffectPropertyDescriptor( mEffect.Parameters[i], attrs.ToArray()); if (newPropDesc.IsBrowsable) newProps.Add(newPropDesc); } return new PropertyDescriptorCollection(newProps.ToArray()); } public PropertyDescriptorCollection GetProperties() { return TypeDescriptor.GetProperties(this, true); } public object GetPropertyOwner(PropertyDescriptor pd) { return this; } #endregion } }
// Generated by ProtoGen, Version=2.4.1.521, Culture=neutral, PublicKeyToken=17b3b1f090c3ea48. DO NOT EDIT! #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.ProtocolBuffers; using pbc = global::Google.ProtocolBuffers.Collections; using pbd = global::Google.ProtocolBuffers.Descriptors; using scg = global::System.Collections.Generic; namespace Google.ProtocolBuffers.TestProtos { [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class UnitTestCSharpOptionsProtoFile { #region Extension registration public static void RegisterAllExtensions(pb::ExtensionRegistry registry) { } #endregion #region Static variables internal static pbd::MessageDescriptor internal__static_protobuf_unittest_OptionsMessage__Descriptor; internal static pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.OptionsMessage, global::Google.ProtocolBuffers.TestProtos.OptionsMessage.Builder> internal__static_protobuf_unittest_OptionsMessage__FieldAccessorTable; #endregion #region Descriptor public static pbd::FileDescriptor Descriptor { get { return descriptor; } } private static pbd::FileDescriptor descriptor; static UnitTestCSharpOptionsProtoFile() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Ci1nb29nbGUvcHJvdG9idWYvdW5pdHRlc3RfY3NoYXJwX29wdGlvbnMucHJv", "dG8SEXByb3RvYnVmX3VuaXR0ZXN0GiRnb29nbGUvcHJvdG9idWYvY3NoYXJw", "X29wdGlvbnMucHJvdG8iXgoOT3B0aW9uc01lc3NhZ2USDgoGbm9ybWFsGAEg", "ASgJEhcKD29wdGlvbnNfbWVzc2FnZRgCIAEoCRIjCgpjdXN0b21pemVkGAMg", "ASgJQg/CPgwKCkN1c3RvbU5hbWVCRsI+QwohR29vZ2xlLlByb3RvY29sQnVm", "ZmVycy5UZXN0UHJvdG9zEh5Vbml0VGVzdENTaGFycE9wdGlvbnNQcm90b0Zp", "bGU=")); pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) { descriptor = root; internal__static_protobuf_unittest_OptionsMessage__Descriptor = Descriptor.MessageTypes[0]; internal__static_protobuf_unittest_OptionsMessage__FieldAccessorTable = new pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.OptionsMessage, global::Google.ProtocolBuffers.TestProtos.OptionsMessage.Builder>(internal__static_protobuf_unittest_OptionsMessage__Descriptor, new string[] { "Normal", "OptionsMessage_", "CustomName", }); pb::ExtensionRegistry registry = pb::ExtensionRegistry.CreateInstance(); RegisterAllExtensions(registry); global::Google.ProtocolBuffers.DescriptorProtos.CSharpOptions.RegisterAllExtensions(registry); return registry; }; pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, new pbd::FileDescriptor[] { global::Google.ProtocolBuffers.DescriptorProtos.CSharpOptions.Descriptor, }, assigner); } #endregion } #region Messages [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class OptionsMessage : pb::GeneratedMessage<OptionsMessage, OptionsMessage.Builder> { private OptionsMessage() { } private static readonly OptionsMessage defaultInstance = new OptionsMessage().MakeReadOnly(); private static readonly string[] _optionsMessageFieldNames = new string[] { "customized", "normal", "options_message" }; private static readonly uint[] _optionsMessageFieldTags = new uint[] { 26, 10, 18 }; public static OptionsMessage DefaultInstance { get { return defaultInstance; } } public override OptionsMessage DefaultInstanceForType { get { return DefaultInstance; } } protected override OptionsMessage ThisMessage { get { return this; } } public static pbd::MessageDescriptor Descriptor { get { return global::Google.ProtocolBuffers.TestProtos.UnitTestCSharpOptionsProtoFile.internal__static_protobuf_unittest_OptionsMessage__Descriptor; } } protected override pb::FieldAccess.FieldAccessorTable<OptionsMessage, OptionsMessage.Builder> InternalFieldAccessors { get { return global::Google.ProtocolBuffers.TestProtos.UnitTestCSharpOptionsProtoFile.internal__static_protobuf_unittest_OptionsMessage__FieldAccessorTable; } } public const int NormalFieldNumber = 1; private bool hasNormal; private string normal_ = ""; public bool HasNormal { get { return hasNormal; } } public string Normal { get { return normal_; } } public const int OptionsMessage_FieldNumber = 2; private bool hasOptionsMessage_; private string optionsMessage_ = ""; public bool HasOptionsMessage_ { get { return hasOptionsMessage_; } } public string OptionsMessage_ { get { return optionsMessage_; } } public const int CustomNameFieldNumber = 3; private bool hasCustomName; private string customized_ = ""; public bool HasCustomName { get { return hasCustomName; } } public string CustomName { get { return customized_; } } public override bool IsInitialized { get { return true; } } public override void WriteTo(pb::ICodedOutputStream output) { int size = SerializedSize; string[] field_names = _optionsMessageFieldNames; if (hasNormal) { output.WriteString(1, field_names[1], Normal); } if (hasOptionsMessage_) { output.WriteString(2, field_names[2], OptionsMessage_); } if (hasCustomName) { output.WriteString(3, field_names[0], CustomName); } UnknownFields.WriteTo(output); } private int memoizedSerializedSize = -1; public override int SerializedSize { get { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (hasNormal) { size += pb::CodedOutputStream.ComputeStringSize(1, Normal); } if (hasOptionsMessage_) { size += pb::CodedOutputStream.ComputeStringSize(2, OptionsMessage_); } if (hasCustomName) { size += pb::CodedOutputStream.ComputeStringSize(3, CustomName); } size += UnknownFields.SerializedSize; memoizedSerializedSize = size; return size; } } public static OptionsMessage ParseFrom(pb::ByteString data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static OptionsMessage ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static OptionsMessage ParseFrom(byte[] data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static OptionsMessage ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static OptionsMessage ParseFrom(global::System.IO.Stream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static OptionsMessage ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } public static OptionsMessage ParseDelimitedFrom(global::System.IO.Stream input) { return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); } public static OptionsMessage ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); } public static OptionsMessage ParseFrom(pb::ICodedInputStream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static OptionsMessage ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } private OptionsMessage MakeReadOnly() { return this; } public static Builder CreateBuilder() { return new Builder(); } public override Builder ToBuilder() { return CreateBuilder(this); } public override Builder CreateBuilderForType() { return new Builder(); } public static Builder CreateBuilder(OptionsMessage prototype) { return new Builder(prototype); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Builder : pb::GeneratedBuilder<OptionsMessage, Builder> { protected override Builder ThisBuilder { get { return this; } } public Builder() { result = DefaultInstance; resultIsReadOnly = true; } internal Builder(OptionsMessage cloneFrom) { result = cloneFrom; resultIsReadOnly = true; } private bool resultIsReadOnly; private OptionsMessage result; private OptionsMessage PrepareBuilder() { if (resultIsReadOnly) { OptionsMessage original = result; result = new OptionsMessage(); resultIsReadOnly = false; MergeFrom(original); } return result; } public override bool IsInitialized { get { return result.IsInitialized; } } protected override OptionsMessage MessageBeingBuilt { get { return PrepareBuilder(); } } public override Builder Clear() { result = DefaultInstance; resultIsReadOnly = true; return this; } public override Builder Clone() { if (resultIsReadOnly) { return new Builder(result); } else { return new Builder().MergeFrom(result); } } public override pbd::MessageDescriptor DescriptorForType { get { return global::Google.ProtocolBuffers.TestProtos.OptionsMessage.Descriptor; } } public override OptionsMessage DefaultInstanceForType { get { return global::Google.ProtocolBuffers.TestProtos.OptionsMessage.DefaultInstance; } } public override OptionsMessage BuildPartial() { if (resultIsReadOnly) { return result; } resultIsReadOnly = true; return result.MakeReadOnly(); } public override Builder MergeFrom(pb::IMessage other) { if (other is OptionsMessage) { return MergeFrom((OptionsMessage) other); } else { base.MergeFrom(other); return this; } } public override Builder MergeFrom(OptionsMessage other) { if (other == global::Google.ProtocolBuffers.TestProtos.OptionsMessage.DefaultInstance) return this; PrepareBuilder(); if (other.HasNormal) { Normal = other.Normal; } if (other.HasOptionsMessage_) { OptionsMessage_ = other.OptionsMessage_; } if (other.HasCustomName) { CustomName = other.CustomName; } this.MergeUnknownFields(other.UnknownFields); return this; } public override Builder MergeFrom(pb::ICodedInputStream input) { return MergeFrom(input, pb::ExtensionRegistry.Empty); } public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { PrepareBuilder(); pb::UnknownFieldSet.Builder unknownFields = null; uint tag; string field_name; while (input.ReadTag(out tag, out field_name)) { if(tag == 0 && field_name != null) { int field_ordinal = global::System.Array.BinarySearch(_optionsMessageFieldNames, field_name, global::System.StringComparer.Ordinal); if(field_ordinal >= 0) tag = _optionsMessageFieldTags[field_ordinal]; else { if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); continue; } } switch (tag) { case 0: { throw pb::InvalidProtocolBufferException.InvalidTag(); } default: { if (pb::WireFormat.IsEndGroupTag(tag)) { if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); break; } case 10: { result.hasNormal = input.ReadString(ref result.normal_); break; } case 18: { result.hasOptionsMessage_ = input.ReadString(ref result.optionsMessage_); break; } case 26: { result.hasCustomName = input.ReadString(ref result.customized_); break; } } } if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } public bool HasNormal { get { return result.hasNormal; } } public string Normal { get { return result.Normal; } set { SetNormal(value); } } public Builder SetNormal(string value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasNormal = true; result.normal_ = value; return this; } public Builder ClearNormal() { PrepareBuilder(); result.hasNormal = false; result.normal_ = ""; return this; } public bool HasOptionsMessage_ { get { return result.hasOptionsMessage_; } } public string OptionsMessage_ { get { return result.OptionsMessage_; } set { SetOptionsMessage_(value); } } public Builder SetOptionsMessage_(string value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasOptionsMessage_ = true; result.optionsMessage_ = value; return this; } public Builder ClearOptionsMessage_() { PrepareBuilder(); result.hasOptionsMessage_ = false; result.optionsMessage_ = ""; return this; } public bool HasCustomName { get { return result.hasCustomName; } } public string CustomName { get { return result.CustomName; } set { SetCustomName(value); } } public Builder SetCustomName(string value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasCustomName = true; result.customized_ = value; return this; } public Builder ClearCustomName() { PrepareBuilder(); result.hasCustomName = false; result.customized_ = ""; return this; } } static OptionsMessage() { object.ReferenceEquals(global::Google.ProtocolBuffers.TestProtos.UnitTestCSharpOptionsProtoFile.Descriptor, null); } } #endregion } #endregion Designer generated code
/* Project Orleans Cloud Service SDK ver. 1.0 Copyright (c) Microsoft Corporation All rights reserved. MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; namespace Orleans { namespace Concurrency { /// <summary> /// The ReadOnly attribute is used to mark methods that do not modify the state of a grain. /// <para> /// Marking methods as ReadOnly allows the run-time system to perform a number of optimizations /// that may significantly improve the performance of your application. /// </para> /// </summary> [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property)] internal sealed class ReadOnlyAttribute : Attribute { } /// <summary> /// The Reentrant attribute is used to mark grain implementation classes that allow request interleaving within a task. /// <para> /// This is an advanced feature and should not be used unless the implications are fully understood. /// That said, allowing request interleaving allows the run-time system to perform a number of optimizations /// that may significantly improve the performance of your application. /// </para> /// </summary> [AttributeUsage(AttributeTargets.Class)] public sealed class ReentrantAttribute : Attribute { } /// <summary> /// The Unordered attribute is used to mark grain interface in which the delivery order of /// messages is not significant. /// </summary> [AttributeUsage(AttributeTargets.Interface)] public sealed class UnorderedAttribute : Attribute { } /// <summary> /// The StatelessWorker attribute is used to mark grain class in which there is no expectation /// of preservation of grain state between requests and where multiple activations of the same grain are allowed to be created by the runtime. /// </summary> [AttributeUsage(AttributeTargets.Class)] public sealed class StatelessWorkerAttribute : Attribute { } /// <summary> /// The AlwaysInterleaveAttribute attribute is used to mark methods that can interleave with any other method type, including write (non ReadOnly) requests. /// </summary> [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property)] public sealed class AlwaysInterleaveAttribute : Attribute { } /// <summary> /// The Immutable attribute indicates that instances of the marked class or struct are never modified /// after they are created. /// </summary> /// <remarks> /// Note that this implies that sub-objects are also not modified after the instance is created. /// </remarks> [AttributeUsage(AttributeTargets.Struct | AttributeTargets.Class)] public sealed class ImmutableAttribute : Attribute { } } namespace Placement { using Orleans.Runtime; /// <summary> /// Base for all placement policy marker attributes. /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public abstract class PlacementAttribute : Attribute { internal PlacementStrategy PlacementStrategy { get; private set; } internal PlacementAttribute(PlacementStrategy placement) { PlacementStrategy = placement ?? PlacementStrategy.GetDefault(); } } /// <summary> /// Marks a grain class as using the <c>RandomPlacement</c> policy. /// </summary> /// <remarks> /// This is the default placement policy, so this attribute does not need to be used for normal grains. /// </remarks> [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public sealed class RandomPlacementAttribute : PlacementAttribute { public RandomPlacementAttribute() : base(RandomPlacement.Singleton) { } } /// <summary> /// Marks a grain class as using the <c>PreferLocalPlacement</c> policy. /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = false) ] public sealed class PreferLocalPlacementAttribute : PlacementAttribute { public PreferLocalPlacementAttribute() : base(PreferLocalPlacement.Singleton) { } } /// <summary> /// Marks a grain class as using the <c>ActivationCountBasedPlacement</c> policy. /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public sealed class ActivationCountBasedPlacementAttribute : PlacementAttribute { public ActivationCountBasedPlacementAttribute() : base(ActivationCountBasedPlacement.Singleton) { } } } namespace CodeGeneration { /// <summary> /// The TypeCodeOverrideAttribute attribute allows to specify the grain interface ID or the grain class type code /// to override the default ones to avoid hash collisions /// </summary> [AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class)] public sealed class TypeCodeOverrideAttribute : Attribute { /// <summary> /// Use a specific grain interface ID or grain class type code (e.g. to avoid hash collisions) /// </summary> public int TypeCode { get; private set; } public TypeCodeOverrideAttribute(int typeCode) { TypeCode = typeCode; } } /// <summary> /// Used to mark a method as providing a copier function for that type. /// </summary> [AttributeUsage(AttributeTargets.Method)] public sealed class CopierMethodAttribute : Attribute { } /// <summary> /// Used to mark a method as providinga serializer function for that type. /// </summary> [AttributeUsage(AttributeTargets.Method)] public sealed class SerializerMethodAttribute : Attribute { } /// <summary> /// Used to mark a method as providing a deserializer function for that type. /// </summary> [AttributeUsage(AttributeTargets.Method)] public sealed class DeserializerMethodAttribute : Attribute { } /// <summary> /// Used to make a class for auto-registration as a serialization helper. /// </summary> [AttributeUsage(AttributeTargets.Class)] public sealed class RegisterSerializerAttribute : Attribute { } } namespace Providers { /// <summary> /// The [Orleans.Providers.StorageProvider] attribute is used to define which storage provider to use for persistence of grain state. /// <para> /// Specifying [Orleans.Providers.StorageProvider] property is recommended for all grains which extend Grain&lt;T&gt;. /// If no [Orleans.Providers.StorageProvider] attribute is specified, then a "Default" strorage provider will be used. /// If a suitable storage provider cannot be located for this grain, then the grain will fail to load into the Silo. /// </para> /// </summary> [AttributeUsage(AttributeTargets.Class)] public sealed class StorageProviderAttribute : Attribute { public StorageProviderAttribute() { ProviderName = Runtime.Constants.DEFAULT_STORAGE_PROVIDER_NAME; } /// <summary> /// The name of the storage provider to ne used for persisting state for this grain. /// </summary> public string ProviderName { get; set; } } } [AttributeUsage(AttributeTargets.Interface)] internal sealed class FactoryAttribute : Attribute { public enum FactoryTypes { Grain, ClientObject, Both }; private readonly FactoryTypes factoryType = FactoryTypes.Grain; public FactoryAttribute(FactoryTypes factoryType) { this.factoryType = factoryType; } internal static FactoryTypes CollectFactoryTypesSpecified(Type type) { var attribs = type.GetCustomAttributes(typeof(FactoryAttribute), inherit: true); // if no attributes are specified, we default to FactoryTypes.Grain. if (0 == attribs.Length) return FactoryTypes.Grain; // otherwise, we'll consider all of them and aggregate the specifications // like flags. FactoryTypes? result = null; foreach (var i in attribs) { var a = (FactoryAttribute)i; if (result.HasValue) { if (a.factoryType == FactoryTypes.Both) result = a.factoryType; else if (a.factoryType != result.Value) result = FactoryTypes.Both; } else result = a.factoryType; } if (result.Value == FactoryTypes.Both) { throw new NotSupportedException( "Orleans doesn't currently support generating both a grain and a client object factory but we really want to!"); } return result.Value; } public static FactoryTypes CollectFactoryTypesSpecified<T>() { return CollectFactoryTypesSpecified(typeof(T)); } } [AttributeUsage(AttributeTargets.Class)] public sealed class ImplicitStreamSubscriptionAttribute : Attribute { internal string Namespace { get; private set; } // We have not yet come to an agreement whether the provider should be specified as well. public ImplicitStreamSubscriptionAttribute(string streamNamespace) { Namespace = streamNamespace; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Debug = System.Diagnostics.Debug; using SuppressMessageAttribute = System.Diagnostics.CodeAnalysis.SuppressMessageAttribute; using Interlocked = System.Threading.Interlocked; namespace System.Xml.Linq { /// <summary> /// Represents an XML namespace. This class cannot be inherited. /// </summary> public sealed class XNamespace { internal const string xmlPrefixNamespace = "http://www.w3.org/XML/1998/namespace"; internal const string xmlnsPrefixNamespace = "http://www.w3.org/2000/xmlns/"; static XHashtable<WeakReference> namespaces; static WeakReference refNone; static WeakReference refXml; static WeakReference refXmlns; string namespaceName; int hashCode; XHashtable<XName> names; const int NamesCapacity = 8; // Starting capacity of XName table, which must be power of 2 const int NamespacesCapacity = 32; // Starting capacity of XNamespace table, which must be power of 2 /// <summary> /// Constructor, internal so that external users must go through the Get() method to create an XNamespace. /// </summary> internal XNamespace(string namespaceName) { this.namespaceName = namespaceName; this.hashCode = namespaceName.GetHashCode(); names = new XHashtable<XName>(ExtractLocalName, NamesCapacity); } /// <summary> /// Gets the namespace name of the namespace. /// </summary> public string NamespaceName { get { return namespaceName; } } /// <summary> /// Returns an <see cref="XName"/> object created from the current instance and the specified local name. /// </summary> /// <remarks> /// The returned <see cref="XName"/> object is guaranteed to be atomic (i.e. the only one in the system for this /// particular expanded name). /// </remarks> public XName GetName(string localName) { if (localName == null) throw new ArgumentNullException("localName"); return GetName(localName, 0, localName.Length); } /// <summary> /// Returns the namespace name of this <see cref="XNamespace"/>. /// </summary> /// <returns>A string value containing the namespace name.</returns> public override string ToString() { return namespaceName; } /// <summary> /// Gets the <see cref="XNamespace"/> object that corresponds to no namespace. /// </summary> /// <remarks> /// If an element or attribute is in no namespace, its namespace /// will be set to the namespace returned by this property. /// </remarks> public static XNamespace None { get { return EnsureNamespace(ref refNone, string.Empty); } } /// <summary> /// Gets the <see cref="XNamespace"/> object that corresponds to the xml uri (http://www.w3.org/XML/1998/namespace). /// </summary> public static XNamespace Xml { get { return EnsureNamespace(ref refXml, xmlPrefixNamespace); } } /// <summary> /// Gets the <see cref="XNamespace"/> object that corresponds to the xmlns uri (http://www.w3.org/2000/xmlns/). /// </summary> public static XNamespace Xmlns { get { return EnsureNamespace(ref refXmlns, xmlnsPrefixNamespace); } } /// <summary> /// Gets an <see cref="XNamespace"/> created from the specified namespace name. /// </summary> /// <remarks> /// The returned <see cref="XNamespace"/> object is guaranteed to be atomic /// (i.e. the only one in the system for that particular namespace name). /// </remarks> public static XNamespace Get(string namespaceName) { if (namespaceName == null) throw new ArgumentNullException("namespaceName"); return Get(namespaceName, 0, namespaceName.Length); } /// <summary> /// Converts a string containing a namespace name to an <see cref="XNamespace"/>. /// </summary> /// <param name="namespaceName">A string containing the namespace name.</param> /// <returns>An <see cref="XNamespace"/> constructed from the namespace name string.</returns> [CLSCompliant(false)] public static implicit operator XNamespace(string namespaceName) { return namespaceName != null ? Get(namespaceName) : null; } /// <summary> /// Combines an <see cref="XNamespace"/> object with a local name to create an <see cref="XName"/>. /// </summary> /// <param name="ns">The namespace for the expanded name.</param> /// <param name="localName">The local name for the expanded name.</param> /// <returns>The new XName constructed from the namespace and local name.</returns> [SuppressMessage("Microsoft.Usage", "CA2225:OperatorOverloadsHaveNamedAlternates", Justification = "Functionality available via XNamespace.Get().")] public static XName operator +(XNamespace ns, string localName) { if (ns == null) throw new ArgumentNullException("ns"); return ns.GetName(localName); } /// <summary> /// Determines whether the specified <see cref="XNamespace"/> is equal to the current <see cref="XNamespace"/>. /// </summary> /// <param name="obj">The <see cref="XNamespace"/> to compare to the current <see cref="XNamespace"/>.</param> /// <returns> /// true if the specified <see cref="XNamespace"/> is equal to the current <see cref="XNamespace"/>; otherwise false. /// </returns> /// <remarks> /// For two <see cref="XNamespace"/> objects to be equal they must have the same /// namespace name. /// </remarks> public override bool Equals(object obj) { return (object)this == obj; } /// <summary> /// Serves as a hash function for <see cref="XNamespace"/>. GetHashCode is suitable /// for use in hashing algorithms and data structures like a hash table. /// </summary> public override int GetHashCode() { return hashCode; } // The overloads of == and != are included to enable comparisons between // XNamespace and string (e.g. element.Name.Namespace == "foo"). C#'s // predefined reference equality operators require one operand to be // convertible to the type of the other through reference conversions only // and do not consider the implicit conversion from string to XNamespace. /// <summary> /// Returns a value indicating whether two instances of <see cref="XNamespace"/> are equal. /// </summary> /// <param name="left">The first <see cref="XNamespace"/> to compare.</param> /// <param name="right">The second <see cref="XNamespace"/> to compare.</param> /// <returns>true if left and right are equal; otherwise false.</returns> /// <remarks> /// This overload is included to enable the comparison between /// an instance of <see cref="XNamespace"/> and string. /// </remarks> public static bool operator ==(XNamespace left, XNamespace right) { return (object)left == (object)right; } /// <summary> /// Returns a value indicating whether two instances of <see cref="XNamespace"/> are not equal. /// </summary> /// <param name="left">The first <see cref="XNamespace"/> to compare.</param> /// <param name="right">The second <see cref="XNamespace"/> to compare.</param> /// <returns>true if left and right are not equal; otherwise false.</returns> /// <remarks> /// This overload is included to enable the comparison between /// an instance of <see cref="XNamespace"/> and string. /// </remarks> public static bool operator !=(XNamespace left, XNamespace right) { return (object)left != (object)right; } /// <summary> /// Returns an <see cref="XName"/> created from this XNamespace <see cref="XName"/> and a portion of the passed in /// local name parameter. The returned <see cref="XName"/> object is guaranteed to be atomic (i.e. the only one in the system for /// this particular expanded name). /// </summary> internal XName GetName(string localName, int index, int count) { Debug.Assert(index >= 0 && index <= localName.Length, "Caller should have checked that index was in bounds"); Debug.Assert(count >= 0 && index + count <= localName.Length, "Caller should have checked that count was in bounds"); // Attempt to get the local name from the hash table XName name; if (names.TryGetValue(localName, index, count, out name)) return name; // No local name has yet been added, so add it now return names.Add(new XName(this, localName.Substring(index, count))); } /// <summary> /// Returns an <see cref="XNamespace"/> created from a portion of the passed in namespace name parameter. The returned <see cref="XNamespace"/> /// object is guaranteed to be atomic (i.e. the only one in the system for this particular namespace name). /// </summary> internal static XNamespace Get(string namespaceName, int index, int count) { Debug.Assert(index >= 0 && index <= namespaceName.Length, "Caller should have checked that index was in bounds"); Debug.Assert(count >= 0 && index + count <= namespaceName.Length, "Caller should have checked that count was in bounds"); if (count == 0) return None; // Use CompareExchange to ensure that exactly one XHashtable<WeakReference> is used to store namespaces if (namespaces == null) Interlocked.CompareExchange(ref namespaces, new XHashtable<WeakReference>(ExtractNamespace, NamespacesCapacity), null); WeakReference refNamespace; XNamespace ns; // Keep looping until a non-null namespace has been retrieved do { // Attempt to get the WeakReference for the namespace from the hash table if (!namespaces.TryGetValue(namespaceName, index, count, out refNamespace)) { // If it is not there, first determine whether it's a special namespace if (count == xmlPrefixNamespace.Length && string.CompareOrdinal(namespaceName, index, xmlPrefixNamespace, 0, count) == 0) return Xml; if (count == xmlnsPrefixNamespace.Length && string.CompareOrdinal(namespaceName, index, xmlnsPrefixNamespace, 0, count) == 0) return Xmlns; // Go ahead and create the namespace and add it to the table refNamespace = namespaces.Add(new WeakReference(new XNamespace(namespaceName.Substring(index, count)))); } ns = (refNamespace != null) ? (XNamespace)refNamespace.Target : null; } while (ns == null); return ns; } /// <summary> /// This function is used by the <see cref="XHashtable{XName}"/> to extract the local name part from an <see cref="XName"/>. The hash table /// uses the local name as the hash key. /// </summary> private static string ExtractLocalName(XName n) { Debug.Assert(n != null, "Null name should never exist here"); return n.LocalName; } /// <summary> /// This function is used by the <see cref="XHashtable{WeakReference}"/> to extract the XNamespace that the WeakReference is /// referencing. In cases where the XNamespace has been cleaned up, this function returns null. /// </summary> private static string ExtractNamespace(WeakReference r) { XNamespace ns; if (r == null || (ns = (XNamespace)r.Target) == null) return null; return ns.NamespaceName; } /// <summary> /// Ensure that an XNamespace object for 'namespaceName' has been atomically created. In other words, all outstanding /// references to this particular namespace, on any thread, must all be to the same object. Care must be taken, /// since other threads can be concurrently calling this method, and the target of a WeakReference can be cleaned up /// at any time by the GC. /// </summary> private static XNamespace EnsureNamespace(ref WeakReference refNmsp, string namespaceName) { WeakReference refOld; // Keep looping until a non-null namespace has been retrieved while (true) { // Save refNmsp in local variable, so we can work on a value that will not be changed by another thread refOld = refNmsp; if (refOld != null) { // If the target of the WeakReference is non-null, then we're done--just return the value XNamespace ns = (XNamespace)refOld.Target; if (ns != null) return ns; } // Either refNmsp is null, or its target is null, so update it // Make sure to do this atomically, so that we can guarantee atomicity of XNamespace objects Interlocked.CompareExchange(ref refNmsp, new WeakReference(new XNamespace(namespaceName)), refOld); } } } }
using System; using System.Runtime.InteropServices; using System.Collections.Generic; using System.Text; using UnityEngine; namespace FMODUnity { [AddComponentMenu("")] public class RuntimeManager : MonoBehaviour { static SystemNotInitializedException initException = null; static RuntimeManager instance; static bool isQuitting = false; [SerializeField] FMODPlatform fmodPlatform; static RuntimeManager Instance { get { if (initException != null) { throw initException; } if (isQuitting) { throw new Exception("FMOD Studio attempted access by script to RuntimeManager while application is quitting"); } if (instance == null) { var existing = FindObjectOfType(typeof(RuntimeManager)) as RuntimeManager; if (existing != null) { // Older versions of the integration may have leaked the runtime manager game object into the scene, // which was then serialized. It won't have valid pointers so don't use it. if (existing.cachedPointers[0] != 0) { instance = existing; instance.studioSystem = new FMOD.Studio.System((IntPtr)instance.cachedPointers[0]); instance.lowlevelSystem = new FMOD.System((IntPtr)instance.cachedPointers[1]); instance.mixerHead = new FMOD.DSP((IntPtr)instance.cachedPointers[2]); return instance; } } var gameObject = new GameObject("FMOD.UnityItegration.RuntimeManager"); instance = gameObject.AddComponent<RuntimeManager>(); DontDestroyOnLoad(gameObject); gameObject.hideFlags = HideFlags.HideInHierarchy; try { #if UNITY_ANDROID && !UNITY_EDITOR // First, obtain the current activity context AndroidJavaObject activity = null; using (var activityClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer")) { activity = activityClass.GetStatic<AndroidJavaObject>("currentActivity"); } using (var fmodJava = new AndroidJavaClass("org.fmod.FMOD")) { if (fmodJava != null) { fmodJava.CallStatic("init", activity); } else { UnityEngine.Debug.LogWarning("FMOD Studio: Cannot initialiaze Java wrapper"); } } #endif RuntimeUtils.EnforceLibraryOrder(); instance.Initialiase(false); } catch (Exception e) { initException = e as SystemNotInitializedException; if (initException == null) { initException = new SystemNotInitializedException(e); } throw initException; } } return instance; } } public static FMOD.Studio.System StudioSystem { get { return Instance.studioSystem; } } public static FMOD.System LowlevelSystem { get { return Instance.lowlevelSystem; } } FMOD.Studio.System studioSystem; FMOD.System lowlevelSystem; FMOD.DSP mixerHead; [SerializeField] private long[] cachedPointers = new long[3]; struct LoadedBank { public FMOD.Studio.Bank Bank; public int RefCount; } Dictionary<string, LoadedBank> loadedBanks = new Dictionary<string, LoadedBank>(); Dictionary<string, uint> loadedPlugins = new Dictionary<string, uint>(); // Explicit comparer to avoid issues on platforms that don't support JIT compilation class GuidComparer : IEqualityComparer<Guid> { bool IEqualityComparer<Guid>.Equals(Guid x, Guid y) { return x.Equals(y); } int IEqualityComparer<Guid>.GetHashCode(Guid obj) { return obj.GetHashCode(); } } Dictionary<Guid, FMOD.Studio.EventDescription> cachedDescriptions = new Dictionary<Guid, FMOD.Studio.EventDescription>(new GuidComparer()); void CheckInitResult(FMOD.RESULT result, string cause) { if (result != FMOD.RESULT.OK) { if (studioSystem != null) { studioSystem.release(); studioSystem = null; } throw new SystemNotInitializedException(result, cause); } } void Initialiase(bool forceNoNetwork) { UnityEngine.Debug.Log("FMOD Studio: Creating runtime system instance"); FMOD.RESULT result; result = FMOD.Studio.System.create(out studioSystem); CheckInitResult(result, "Creating System Object"); studioSystem.getLowLevelSystem(out lowlevelSystem); Settings fmodSettings = Settings.Instance; fmodPlatform = RuntimeUtils.GetCurrentPlatform(); #if UNITY_EDITOR || ((UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX) && DEVELOPMENT_BUILD) result = FMOD.Debug.Initialize(FMOD.DEBUG_FLAGS.LOG, FMOD.DEBUG_MODE.FILE, null, RuntimeUtils.LogFileName); if (result == FMOD.RESULT.ERR_FILE_NOTFOUND) { UnityEngine.Debug.LogWarningFormat("FMOD Studio: Cannot open FMOD debug log file '{0}', logs will be missing for this session.", System.IO.Path.Combine(Application.dataPath, RuntimeUtils.LogFileName)); } else { CheckInitResult(result, "Applying debug settings"); } #endif int realChannels = fmodSettings.GetRealChannels(fmodPlatform); realChannels = Math.Min(realChannels, 256); // Prior to 1.08.10 we didn't clamp this properly in the settings screen result = lowlevelSystem.setSoftwareChannels(realChannels); CheckInitResult(result, "Set software channels"); result = lowlevelSystem.setSoftwareFormat( fmodSettings.GetSampleRate(fmodPlatform), (FMOD.SPEAKERMODE)fmodSettings.GetSpeakerMode(fmodPlatform), 0 // raw not supported ); CheckInitResult(result, "Set software format"); // Setup up the platforms recommended codec to match the real channel count FMOD.ADVANCEDSETTINGS advancedsettings = new FMOD.ADVANCEDSETTINGS(); #if UNITY_EDITOR || UNITY_STANDALONE advancedsettings.maxVorbisCodecs = realChannels; #elif UNITY_IOS || UNITY_ANDROID || UNITY_WP8_1 || UNITY_PSP2 || UNITY_WII advancedsettings.maxFADPCMCodecs = realChannels; #elif UNITY_XBOXONE advancedsettings.maxXMACodecs = realChannels; #elif UNITY_PS4 advancedsettings.maxAT9Codecs = realChannels; #endif #if UNITY_5_0 || UNITY_5_1 if (fmodSettings.IsLiveUpdateEnabled(fmodPlatform) && !forceNoNetwork) { UnityEngine.Debug.LogWarning("FMOD Studio: Detected Unity 5, running on port 9265"); advancedsettings.profilePort = 9265; } #endif advancedsettings.randomSeed = (uint) DateTime.Now.Ticks; result = lowlevelSystem.setAdvancedSettings(ref advancedsettings); CheckInitResult(result, "Set advanced settings"); FMOD.INITFLAGS lowlevelInitFlags = FMOD.INITFLAGS.NORMAL; FMOD.Studio.INITFLAGS studioInitFlags = FMOD.Studio.INITFLAGS.NORMAL | FMOD.Studio.INITFLAGS.DEFERRED_CALLBACKS; if (fmodSettings.IsLiveUpdateEnabled(fmodPlatform) && !forceNoNetwork) { studioInitFlags |= FMOD.Studio.INITFLAGS.LIVEUPDATE; } FMOD.RESULT initResult = studioSystem.initialize( fmodSettings.GetVirtualChannels(fmodPlatform), studioInitFlags, lowlevelInitFlags, IntPtr.Zero ); CheckInitResult(initResult, "Calling initialize"); // Dummy flush and update to get network state studioSystem.flushCommands(); FMOD.RESULT updateResult = studioSystem.update(); // Restart without liveupdate if there was a socket error if (updateResult == FMOD.RESULT.ERR_NET_SOCKET_ERROR) { studioSystem.release(); UnityEngine.Debug.LogWarning("FMOD Studio: Cannot open network port for Live Update, restarting with Live Update disabled. Check for other applications that are running FMOD Studio"); Initialiase(true); } else { // Load plugins (before banks) #if (UNITY_IOS || UNITY_TVOS) && !UNITY_EDITOR FmodUnityNativePluginInit(lowlevelSystem.getRaw()); #else foreach (var pluginName in fmodSettings.Plugins) { string pluginPath = RuntimeUtils.GetPluginPath(pluginName); uint handle; result = lowlevelSystem.loadPlugin(pluginPath, out handle); #if UNITY_64 || UNITY_EDITOR_64 // Add a "64" suffix and try again if (result == FMOD.RESULT.ERR_FILE_BAD || result == FMOD.RESULT.ERR_FILE_NOTFOUND) { string pluginPath64 = RuntimeUtils.GetPluginPath(pluginName + "64"); result = lowlevelSystem.loadPlugin(pluginPath64, out handle); } #endif CheckInitResult(result, String.Format("Loading plugin '{0}' from '{1}'", pluginName, pluginPath)); loadedPlugins.Add(pluginName, handle); } #endif if (fmodSettings.ImportType == ImportType.StreamingAssets) { // Always load strings bank try { LoadBank(fmodSettings.MasterBank + ".strings", fmodSettings.AutomaticSampleLoading); } catch (BankLoadException e) { UnityEngine.Debug.LogException(e); } if (fmodSettings.AutomaticEventLoading) { try { LoadBank(fmodSettings.MasterBank, fmodSettings.AutomaticSampleLoading); } catch (BankLoadException e) { UnityEngine.Debug.LogException(e); } foreach (var bank in fmodSettings.Banks) { try { LoadBank(bank, fmodSettings.AutomaticSampleLoading); } catch (BankLoadException e) { UnityEngine.Debug.LogException(e); } } WaitForAllLoads(); } } }; FMOD.ChannelGroup master; lowlevelSystem.getMasterChannelGroup(out master); master.getDSP(0, out mixerHead); mixerHead.setMeteringEnabled(false, true); } class AttachedInstance { public FMOD.Studio.EventInstance instance; public Transform transform; public Rigidbody rigidBody; } List<AttachedInstance> attachedInstances = new List<AttachedInstance>(128); #if UNITY_EDITOR Dictionary<IntPtr, bool> warnedInvalidInstances = new Dictionary<IntPtr, bool>(2048); #endif bool listenerWarningIssued = false; void Update() { if (studioSystem != null) { studioSystem.update(); bool foundListener = false; bool hasAllListeners = false; int numListeners = 0; for (int i = FMOD.CONSTANTS.MAX_LISTENERS - 1; i >=0 ; i--) { if (!foundListener && HasListener[i]) { numListeners = i + 1; foundListener = true; hasAllListeners = true; } if (!HasListener[i] && foundListener) { hasAllListeners = false; } } if (foundListener) { studioSystem.setNumListeners(numListeners); } if (!hasAllListeners && !listenerWarningIssued) { listenerWarningIssued = true; UnityEngine.Debug.LogWarning("FMOD Studio Integration: Please add an 'FMOD Studio Listener' component to your a camera in the scene for correct 3D positioning of sounds"); } for (int i = 0; i < attachedInstances.Count; i++) { FMOD.Studio.PLAYBACK_STATE playbackState = FMOD.Studio.PLAYBACK_STATE.STOPPED; attachedInstances[i].instance.getPlaybackState(out playbackState); if (!attachedInstances[i].instance.isValid() || playbackState == FMOD.Studio.PLAYBACK_STATE.STOPPED || attachedInstances[i].transform == null // destroyed game object ) { attachedInstances.RemoveAt(i); i--; continue; } attachedInstances[i].instance.set3DAttributes(RuntimeUtils.To3DAttributes(attachedInstances[i].transform, attachedInstances[i].rigidBody)); } #if UNITY_EDITOR MuteAllEvents(UnityEditor.EditorUtility.audioMasterMute); #endif #if UNITY_EDITOR // Catch any 3D events that are being played at the origin foreach(FMOD.Studio.EventDescription desc in cachedDescriptions.Values) { if (!desc.isValid()) { continue; } bool is3d; desc.is3D(out is3d); if (!is3d) { continue; } string path; desc.getPath(out path); int instanceCount; desc.getInstanceCount(out instanceCount); FMOD.Studio.EventInstance[] instances = new FMOD.Studio.EventInstance[instanceCount]; desc.getInstanceList(out instances); for (int i = 0; i < instances.Length; i++) { if (warnedInvalidInstances.ContainsKey(instances[i].getRaw())) { continue; } FMOD.ATTRIBUTES_3D attributes = new FMOD.ATTRIBUTES_3D(); instances[i].get3DAttributes(out attributes); if (attributes.position.x == 0 && attributes.position.y == 0 && attributes.position.z == 0) { warnedInvalidInstances.Add(instances[i].getRaw(), true); Debug.LogWarningFormat("FMOD Studio: Instance of Event {0} found playing at the origin. EventInstance.set3DAttributes() should be called on all 3D events", path); } } } #endif } } public static void AttachInstanceToGameObject(FMOD.Studio.EventInstance instance, Transform transform, Rigidbody rigidBody) { var attachedInstance = new AttachedInstance(); attachedInstance.transform = transform; attachedInstance.instance = instance; attachedInstance.rigidBody = rigidBody; Instance.attachedInstances.Add(attachedInstance); } public static void DetachInstanceFromGameObject(FMOD.Studio.EventInstance instance) { var manager = Instance; for (int i = 0; i < manager.attachedInstances.Count; i++) { if (manager.attachedInstances[i].instance == instance) { manager.attachedInstances.RemoveAt(i); return; } } } Rect windowRect = new Rect(10, 10, 300, 100); void OnGUI() { if (studioSystem != null && Settings.Instance.IsOverlayEnabled(fmodPlatform)) { windowRect = GUI.Window(0, windowRect, DrawDebugOverlay, "FMOD Studio Debug"); } } string lastDebugText; float lastDebugUpdate = 0; void DrawDebugOverlay(int windowID) { if (lastDebugUpdate + 0.25f < Time.unscaledTime) { if (initException != null) { lastDebugText = initException.Message; } else { StringBuilder debug = new StringBuilder(); FMOD.Studio.CPU_USAGE cpuUsage; studioSystem.getCPUUsage(out cpuUsage); debug.AppendFormat("CPU: dsp = {0:F1}%, studio = {1:F1}%\n", cpuUsage.dspUsage, cpuUsage.studioUsage); int currentAlloc, maxAlloc; FMOD.Memory.GetStats(out currentAlloc, out maxAlloc); debug.AppendFormat("MEMORY: cur = {0}MB, max = {1}MB\n", currentAlloc >> 20, maxAlloc >> 20); int realchannels, channels; lowlevelSystem.getChannelsPlaying(out channels, out realchannels); debug.AppendFormat("CHANNELS: real = {0}, total = {1}\n", realchannels, channels); FMOD.DSP_METERING_INFO metering = new FMOD.DSP_METERING_INFO(); mixerHead.getMeteringInfo(null, metering); float rms = 0; for (int i = 0; i < metering.numchannels; i++) { rms += metering.rmslevel[i] * metering.rmslevel[i]; } rms = Mathf.Sqrt(rms / (float)metering.numchannels); float db = rms > 0 ? 20.0f * Mathf.Log10(rms * Mathf.Sqrt(2.0f)) : -80.0f; if (db > 10.0f) db = 10.0f; debug.AppendFormat("VOLUME: RMS = {0:f2}db\n", db); lastDebugText = debug.ToString(); lastDebugUpdate = Time.unscaledTime; } } GUI.Label(new Rect(10, 20, 290, 100), lastDebugText); GUI.DragWindow(); } void OnDisable() { // If we're being torn down for a script reload - cache the native pointers in something unity can serialize cachedPointers[0] = (long)studioSystem.getRaw(); cachedPointers[1] = (long)lowlevelSystem.getRaw(); cachedPointers[2] = (long)mixerHead.getRaw(); } void OnDestroy() { if (studioSystem != null) { UnityEngine.Debug.Log("FMOD Studio: Destroying runtime system instance"); studioSystem.release(); studioSystem = null; } initException = null; instance = null; isQuitting = true; } void OnApplicationPause(bool pauseStatus) { if (studioSystem != null && studioSystem.isValid()) { PauseAllEvents(pauseStatus); if (pauseStatus) { lowlevelSystem.mixerSuspend(); } else { lowlevelSystem.mixerResume(); } } } public static void LoadBank(string bankName, bool loadSamples = false) { if (Instance.loadedBanks.ContainsKey(bankName)) { LoadedBank loadedBank = Instance.loadedBanks[bankName]; loadedBank.RefCount++; if (loadSamples) { loadedBank.Bank.loadSampleData(); } } else { LoadedBank loadedBank = new LoadedBank(); string bankPath = RuntimeUtils.GetBankPath(bankName); FMOD.RESULT loadResult; #if UNITY_ANDROID && !UNITY_EDITOR if (!bankPath.StartsWith("file:///android_asset")) { using (var www = new WWW(bankPath)) { while (!www.isDone) { } if (!String.IsNullOrEmpty(www.error)) { throw new BankLoadException(bankPath, www.error); } else { loadResult = Instance.studioSystem.loadBankMemory(www.bytes, FMOD.Studio.LOAD_BANK_FLAGS.NORMAL, out loadedBank.Bank); } } } else #endif { loadResult = Instance.studioSystem.loadBankFile(bankPath, FMOD.Studio.LOAD_BANK_FLAGS.NORMAL, out loadedBank.Bank); } if (loadResult == FMOD.RESULT.OK) { loadedBank.RefCount = 1; Instance.loadedBanks.Add(bankName, loadedBank); if (loadSamples) { loadedBank.Bank.loadSampleData(); } } else if (loadResult == FMOD.RESULT.ERR_EVENT_ALREADY_LOADED) { // someone loaded this bank directly using the studio API // TODO: will the null bank handle be an issue loadedBank.RefCount = 2; Instance.loadedBanks.Add(bankName, loadedBank); } else { throw new BankLoadException(bankPath, loadResult); } } } public static void LoadBank(TextAsset asset, bool loadSamples = false) { string bankName = asset.name; if (Instance.loadedBanks.ContainsKey(bankName)) { LoadedBank loadedBank = Instance.loadedBanks[bankName]; loadedBank.RefCount++; if (loadSamples) { loadedBank.Bank.loadSampleData(); } } else { LoadedBank loadedBank = new LoadedBank(); FMOD.RESULT loadResult = Instance.studioSystem.loadBankMemory(asset.bytes, FMOD.Studio.LOAD_BANK_FLAGS.NORMAL, out loadedBank.Bank); if (loadResult == FMOD.RESULT.OK) { loadedBank.RefCount = 1; Instance.loadedBanks.Add(bankName, loadedBank); if (loadSamples) { loadedBank.Bank.loadSampleData(); } } else if (loadResult == FMOD.RESULT.ERR_EVENT_ALREADY_LOADED) { // someone loaded this bank directly using the studio API // TODO: will the null bank handle be an issue loadedBank.RefCount = 2; Instance.loadedBanks.Add(bankName, loadedBank); } else { throw new BankLoadException(bankName, loadResult); } } } public static void UnloadBank(string bankName) { LoadedBank loadedBank; if (Instance.loadedBanks.TryGetValue(bankName, out loadedBank)) { loadedBank.RefCount--; if (loadedBank.RefCount == 0) { loadedBank.Bank.unload(); Instance.loadedBanks.Remove(bankName); } } } public static bool AnyBankLoading() { bool loading = false; foreach (LoadedBank bank in Instance.loadedBanks.Values) { FMOD.Studio.LOADING_STATE loadingState; bank.Bank.getSampleLoadingState(out loadingState); loading |= (loadingState == FMOD.Studio.LOADING_STATE.LOADING); } return loading; } public static void WaitForAllLoads() { Instance.studioSystem.flushSampleLoading(); } public static Guid PathToGUID(string path) { Guid guid = Guid.Empty; if (path.StartsWith("{")) { FMOD.Studio.Util.ParseID(path, out guid); } else { var result = Instance.studioSystem.lookupID(path, out guid); if (result == FMOD.RESULT.ERR_EVENT_NOTFOUND) { throw new EventNotFoundException(path); } } return guid; } public static FMOD.Studio.EventInstance CreateInstance(string path) { try { return CreateInstance(PathToGUID(path)); } catch(EventNotFoundException) { // Switch from exception with GUID to exception with path throw new EventNotFoundException(path); } } public static FMOD.Studio.EventInstance CreateInstance(Guid guid) { FMOD.Studio.EventDescription eventDesc = GetEventDescription(guid); FMOD.Studio.EventInstance newInstance; eventDesc.createInstance(out newInstance); return newInstance; } public static void PlayOneShot(string path, Vector3 position = new Vector3()) { try { PlayOneShot(PathToGUID(path), position); } catch (EventNotFoundException) { // Switch from exception with GUID to exception with path throw new EventNotFoundException(path); } } public static void PlayOneShot(Guid guid, Vector3 position = new Vector3()) { var instance = CreateInstance(guid); instance.set3DAttributes(RuntimeUtils.To3DAttributes(position)); instance.start(); instance.release(); } public static void PlayOneShotAttached(string path, GameObject gameObject) { try { PlayOneShotAttached(PathToGUID(path), gameObject); } catch (EventNotFoundException) { // Switch from exception with GUID to exception with path throw new EventNotFoundException(path); } } public static void PlayOneShotAttached(Guid guid, GameObject gameObject) { var instance = CreateInstance(guid); AttachInstanceToGameObject(instance, gameObject.transform, gameObject.GetComponent<Rigidbody>()); instance.start(); } public static FMOD.Studio.EventDescription GetEventDescription(string path) { try { return GetEventDescription(PathToGUID(path)); } catch (EventNotFoundException) { throw new EventNotFoundException(path); } } public static FMOD.Studio.EventDescription GetEventDescription(Guid guid) { FMOD.Studio.EventDescription eventDesc = null; if (Instance.cachedDescriptions.ContainsKey(guid) && Instance.cachedDescriptions[guid].isValid()) { eventDesc = Instance.cachedDescriptions[guid]; } else { var result = Instance.studioSystem.getEventByID(guid, out eventDesc); if (result != FMOD.RESULT.OK) { throw new EventNotFoundException(guid); } if (eventDesc != null && eventDesc.isValid()) { Instance.cachedDescriptions[guid] = eventDesc; } } return eventDesc; } public static bool[] HasListener = new bool[FMOD.CONSTANTS.MAX_LISTENERS]; public static void SetListenerLocation(GameObject gameObject, Rigidbody rigidBody = null) { Instance.studioSystem.setListenerAttributes(0, RuntimeUtils.To3DAttributes(gameObject, rigidBody)); } public static void SetListenerLocation(Transform transform) { Instance.studioSystem.setListenerAttributes(0, transform.To3DAttributes()); } public static void SetListenerLocation(int listenerIndex, GameObject gameObject, Rigidbody rigidBody = null) { Instance.studioSystem.setListenerAttributes(listenerIndex, RuntimeUtils.To3DAttributes(gameObject, rigidBody)); } public static void SetListenerLocation(int listenerIndex, Transform transform) { Instance.studioSystem.setListenerAttributes(listenerIndex, transform.To3DAttributes()); } public static FMOD.Studio.Bus GetBus(String path) { FMOD.RESULT result; FMOD.Studio.Bus bus; result = StudioSystem.getBus(path, out bus); if (result != FMOD.RESULT.OK) { throw new BusNotFoundException(path); } return bus; } public static FMOD.Studio.VCA GetVCA(String path) { FMOD.RESULT result; FMOD.Studio.VCA vca; result = StudioSystem.getVCA(path, out vca); if (result != FMOD.RESULT.OK) { throw new VCANotFoundException(path); } return vca; } public static void PauseAllEvents(bool paused) { GetBus("bus:/").setPaused(paused); } public static void MuteAllEvents(bool muted) { GetBus("bus:/").setMute(muted); } public static bool IsInitialized { get { return instance != null && instance.studioSystem != null; } } #if (UNITY_IOS || UNITY_TVOS) && !UNITY_EDITOR [DllImport("__Internal")] private static extern FMOD.RESULT FmodUnityNativePluginInit(IntPtr system); #endif } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { internal partial class InlineRenameSession { /// <summary> /// Manages state for open text buffers. /// </summary> internal class OpenTextBufferManager : ForegroundThreadAffinitizedObject { private readonly DynamicReadOnlyRegionQuery _isBufferReadOnly; private readonly InlineRenameSession _session; private readonly ITextBuffer _subjectBuffer; private readonly IEnumerable<Document> _baseDocuments; private readonly ITextBufferFactoryService _textBufferFactoryService; private static readonly object s_propagateSpansEditTag = new object(); private static readonly object s_calculateMergedSpansEditTag = new object(); /// <summary> /// The list of active tracking spans that are updated with the session's replacement text. /// These are also the only spans the user can edit during an inline rename session. /// </summary> private readonly Dictionary<TextSpan, RenameTrackingSpan> _referenceSpanToLinkedRenameSpanMap = new Dictionary<TextSpan, RenameTrackingSpan>(); private readonly List<RenameTrackingSpan> _conflictResolutionRenameTrackingSpans = new List<RenameTrackingSpan>(); private readonly IList<IReadOnlyRegion> _readOnlyRegions = new List<IReadOnlyRegion>(); private readonly IList<IWpfTextView> _textViews = new List<IWpfTextView>(); private TextSpan? _activeSpan; public OpenTextBufferManager( InlineRenameSession session, ITextBuffer subjectBuffer, Workspace workspace, IEnumerable<Document> documents, ITextBufferFactoryService textBufferFactoryService) { _session = session; _subjectBuffer = subjectBuffer; _baseDocuments = documents; _textBufferFactoryService = textBufferFactoryService; _subjectBuffer.ChangedLowPriority += OnTextBufferChanged; foreach (var view in session._textBufferAssociatedViewService.GetAssociatedTextViews(_subjectBuffer)) { ConnectToView(view); } session.UndoManager.CreateStartRenameUndoTransaction(workspace, subjectBuffer, session); _isBufferReadOnly = new DynamicReadOnlyRegionQuery((isEdit) => !_session._isApplyingEdit); UpdateReadOnlyRegions(); } public IWpfTextView ActiveTextview { get { foreach (var view in _textViews) { if (view.HasAggregateFocus) { return view; } } return _textViews.FirstOrDefault(); } } private void UpdateReadOnlyRegions(bool removeOnly = false) { AssertIsForeground(); if (!removeOnly && _session.ReplacementText == string.Empty) { return; } using (var readOnlyEdit = _subjectBuffer.CreateReadOnlyRegionEdit()) { foreach (var oldReadOnlyRegion in _readOnlyRegions) { readOnlyEdit.RemoveReadOnlyRegion(oldReadOnlyRegion); } _readOnlyRegions.Clear(); if (!removeOnly) { // We will compute the new read only regions to be all spans that are not currently in an editable span var editableSpans = GetEditableSpansForSnapshot(_subjectBuffer.CurrentSnapshot); var entireBufferSpan = _subjectBuffer.CurrentSnapshot.GetSnapshotSpanCollection(); var newReadOnlySpans = NormalizedSnapshotSpanCollection.Difference(entireBufferSpan, new NormalizedSnapshotSpanCollection(editableSpans)); foreach (var newReadOnlySpan in newReadOnlySpans) { _readOnlyRegions.Add(readOnlyEdit.CreateDynamicReadOnlyRegion(newReadOnlySpan, SpanTrackingMode.EdgeExclusive, EdgeInsertionMode.Allow, _isBufferReadOnly)); } // The spans we added allow typing at the start and end. We'll add extra // zero-width read-only regions at the start and end of the file to fix this, // but only if we don't have an identifier at the start or end that _would_ let // them type there. if (editableSpans.All(s => s.Start > 0)) { _readOnlyRegions.Add(readOnlyEdit.CreateDynamicReadOnlyRegion(new Span(0, 0), SpanTrackingMode.EdgeExclusive, EdgeInsertionMode.Deny, _isBufferReadOnly)); } if (editableSpans.All(s => s.End < _subjectBuffer.CurrentSnapshot.Length)) { _readOnlyRegions.Add(readOnlyEdit.CreateDynamicReadOnlyRegion(new Span(_subjectBuffer.CurrentSnapshot.Length, 0), SpanTrackingMode.EdgeExclusive, EdgeInsertionMode.Deny, _isBufferReadOnly)); } } readOnlyEdit.Apply(); } } private void OnTextViewClosed(object sender, EventArgs e) { var view = sender as IWpfTextView; view.Closed -= OnTextViewClosed; _textViews.Remove(view); if (!_session._dismissed) { _session.Cancel(); } } internal void ConnectToView(IWpfTextView textView) { textView.Closed += OnTextViewClosed; _textViews.Add(textView); } public event Action SpansChanged; private void RaiseSpansChanged() { this.SpansChanged?.Invoke(); } internal IEnumerable<RenameTrackingSpan> GetRenameTrackingSpans() { return _referenceSpanToLinkedRenameSpanMap.Values.Where(r => r.Type != RenameSpanKind.None).Concat(_conflictResolutionRenameTrackingSpans); } internal IEnumerable<SnapshotSpan> GetEditableSpansForSnapshot(ITextSnapshot snapshot) { return _referenceSpanToLinkedRenameSpanMap.Values.Where(r => r.Type != RenameSpanKind.None).Select(r => r.TrackingSpan.GetSpan(snapshot)); } internal void SetReferenceSpans(IEnumerable<TextSpan> spans) { AssertIsForeground(); if (spans.SetEquals(_referenceSpanToLinkedRenameSpanMap.Keys)) { return; } using (new SelectionTracking(this)) { // Revert any previous edits in case we're removing spans. Undo conflict resolution as well to avoid // handling the various edge cases where a tracking span might not map to the right span in the current snapshot _session.UndoManager.UndoTemporaryEdits(_subjectBuffer, disconnect: false); _referenceSpanToLinkedRenameSpanMap.Clear(); foreach (var span in spans) { var renameableSpan = _session._renameInfo.GetReferenceEditSpan( new InlineRenameLocation(_baseDocuments.First(), span), CancellationToken.None); var trackingSpan = new RenameTrackingSpan( _subjectBuffer.CurrentSnapshot.CreateTrackingSpan(renameableSpan.ToSpan(), SpanTrackingMode.EdgeInclusive, TrackingFidelityMode.Forward), RenameSpanKind.Reference); _referenceSpanToLinkedRenameSpanMap[span] = trackingSpan; } _activeSpan = _activeSpan.HasValue && spans.Contains(_activeSpan.Value) ? _activeSpan : spans.Where(s => // in tests `ActiveTextview` can be null so don't depend on it ActiveTextview == null || ActiveTextview.GetSpanInView(_subjectBuffer.CurrentSnapshot.GetSpan(s.ToSpan())).Count != 0) // spans were successfully projected .FirstOrNullable(); // filter to spans that have a projection UpdateReadOnlyRegions(); this.ApplyReplacementText(updateSelection: false); } RaiseSpansChanged(); } private void OnTextBufferChanged(object sender, TextContentChangedEventArgs args) { AssertIsForeground(); // This might be an event fired due to our own edit if (args.EditTag == s_propagateSpansEditTag || _session._isApplyingEdit) { return; } using (Logger.LogBlock(FunctionId.Rename_OnTextBufferChanged, CancellationToken.None)) { var trackingSpansAfterEdit = new NormalizedSpanCollection(GetEditableSpansForSnapshot(args.After).Select(ss => (Span)ss)); var spansTouchedInEdit = new NormalizedSpanCollection(args.Changes.Select(c => c.NewSpan)); var intersectionSpans = NormalizedSpanCollection.Intersection(trackingSpansAfterEdit, spansTouchedInEdit); if (intersectionSpans.Count == 0) { // In Razor we sometimes get formatting changes during inline rename that // do not intersect with any of our spans. Ideally this shouldn't happen at // all, but if it does happen we can just ignore it. return; } // Cases with invalid identifiers may cause there to be multiple intersection // spans, but they should still all map to a single tracked rename span (e.g. // renaming "two" to "one two three" may be interpreted as two distinct // additions of "one" and "three"). var boundingIntersectionSpan = Span.FromBounds(intersectionSpans.First().Start, intersectionSpans.Last().End); var trackingSpansTouched = GetEditableSpansForSnapshot(args.After).Where(ss => ss.IntersectsWith(boundingIntersectionSpan)); Contract.Assert(trackingSpansTouched.Count() == 1); var singleTrackingSpanTouched = trackingSpansTouched.Single(); _activeSpan = _referenceSpanToLinkedRenameSpanMap.Where(kvp => kvp.Value.TrackingSpan.GetSpan(args.After).Contains(boundingIntersectionSpan)).Single().Key; _session.UndoManager.OnTextChanged(this.ActiveTextview.Selection, singleTrackingSpanTouched); } } /// <summary> /// This is a work around for a bug in Razor where the projection spans can get out-of-sync with the /// identifiers. When that bug is fixed this helper can be deleted. /// </summary> private bool AreAllReferenceSpansMappable() { // in tests `ActiveTextview` could be null so don't depend on it return ActiveTextview == null || _referenceSpanToLinkedRenameSpanMap.Keys .Select(s => s.ToSpan()) .All(s => s.End <= _subjectBuffer.CurrentSnapshot.Length && // span is valid for the snapshot ActiveTextview.GetSpanInView(_subjectBuffer.CurrentSnapshot.GetSpan(s)).Count != 0); // spans were successfully projected } internal void ApplyReplacementText(bool updateSelection = true) { AssertIsForeground(); if (!AreAllReferenceSpansMappable()) { // don't dynamically update the reference spans for documents with unmappable projections return; } _session.UndoManager.ApplyCurrentState( _subjectBuffer, s_propagateSpansEditTag, _referenceSpanToLinkedRenameSpanMap.Values.Where(r => r.Type != RenameSpanKind.None).Select(r => r.TrackingSpan)); if (updateSelection && _activeSpan.HasValue && this.ActiveTextview != null) { var snapshot = _subjectBuffer.CurrentSnapshot; _session.UndoManager.UpdateSelection(this.ActiveTextview, _subjectBuffer, _referenceSpanToLinkedRenameSpanMap[_activeSpan.Value].TrackingSpan); } } internal void Disconnect(bool documentIsClosed, bool rollbackTemporaryEdits) { AssertIsForeground(); // Detach from the buffer; it is important that this is done before we start // undoing transactions, since the undo actions will cause buffer changes. _subjectBuffer.ChangedLowPriority -= OnTextBufferChanged; foreach (var view in _textViews) { view.Closed -= OnTextViewClosed; } // Remove any old read only regions we had UpdateReadOnlyRegions(removeOnly: true); if (rollbackTemporaryEdits && !documentIsClosed) { _session.UndoManager.UndoTemporaryEdits(_subjectBuffer, disconnect: true); } } internal void ApplyConflictResolutionEdits(IInlineRenameReplacementInfo conflictResolution, IEnumerable<Document> documents, CancellationToken cancellationToken) { AssertIsForeground(); if (!AreAllReferenceSpansMappable()) { // don't dynamically update the reference spans for documents with unmappable projections return; } using (new SelectionTracking(this)) { // 1. Undo any previous edits and update the buffer to resulting document after conflict resolution _session.UndoManager.UndoTemporaryEdits(_subjectBuffer, disconnect: false); var preMergeSolution = _session._baseSolution; var postMergeSolution = conflictResolution.NewSolution; var diffMergingSession = new LinkedFileDiffMergingSession(preMergeSolution, postMergeSolution, postMergeSolution.GetChanges(preMergeSolution), logSessionInfo: true); var mergeResult = diffMergingSession.MergeDiffsAsync(mergeConflictHandler: null, cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken); var newDocument = mergeResult.MergedSolution.GetDocument(documents.First().Id); var originalDocument = _baseDocuments.Single(d => d.Id == newDocument.Id); var changes = GetTextChangesFromTextDifferencingServiceAsync(originalDocument, newDocument, cancellationToken).WaitAndGetResult(cancellationToken); // TODO: why does the following line hang when uncommented? // newDocument.GetTextChangesAsync(this.baseDocuments.Single(d => d.Id == newDocument.Id), cancellationToken).WaitAndGetResult(cancellationToken).Reverse(); _session.UndoManager.CreateConflictResolutionUndoTransaction(_subjectBuffer, () => { using (var edit = _subjectBuffer.CreateEdit(EditOptions.DefaultMinimalChange, null, s_propagateSpansEditTag)) { foreach (var change in changes) { edit.Replace(change.Span.Start, change.Span.Length, change.NewText); } edit.Apply(); } }); // 2. We want to update referenceSpanToLinkedRenameSpanMap where spans were affected by conflict resolution. // We also need to add the remaining document edits to conflictResolutionRenameTrackingSpans // so they get classified/tagged correctly in the editor. _conflictResolutionRenameTrackingSpans.Clear(); foreach (var document in documents) { var relevantReplacements = conflictResolution.GetReplacements(document.Id).Where(r => GetRenameSpanKind(r.Kind) != RenameSpanKind.None); if (!relevantReplacements.Any()) { continue; } var bufferContainsLinkedDocuments = documents.Skip(1).Any(); var mergedReplacements = bufferContainsLinkedDocuments ? GetMergedReplacementInfos( relevantReplacements, conflictResolution.NewSolution.GetDocument(document.Id), mergeResult.MergedSolution.GetDocument(document.Id), cancellationToken) : relevantReplacements; // Show merge conflicts comments as unresolvable conflicts, and do not // show any other rename-related spans that overlap a merge conflict comment. var mergeConflictComments = mergeResult.MergeConflictCommentSpans.ContainsKey(document.Id) ? mergeResult.MergeConflictCommentSpans[document.Id] : SpecializedCollections.EmptyEnumerable<TextSpan>(); foreach (var conflict in mergeConflictComments) { // TODO: Add these to the unresolvable conflict counts in the dashboard _conflictResolutionRenameTrackingSpans.Add(new RenameTrackingSpan( _subjectBuffer.CurrentSnapshot.CreateTrackingSpan(conflict.ToSpan(), SpanTrackingMode.EdgeInclusive, TrackingFidelityMode.Forward), RenameSpanKind.UnresolvedConflict)); } foreach (var replacement in mergedReplacements) { var kind = GetRenameSpanKind(replacement.Kind); if (_referenceSpanToLinkedRenameSpanMap.ContainsKey(replacement.OriginalSpan) && kind != RenameSpanKind.Complexified) { var linkedRenameSpan = _session._renameInfo.GetConflictEditSpan( new InlineRenameLocation(newDocument, replacement.NewSpan), _session.ReplacementText, cancellationToken); if (linkedRenameSpan.HasValue) { if (!mergeConflictComments.Any(s => replacement.NewSpan.IntersectsWith(s))) { _referenceSpanToLinkedRenameSpanMap[replacement.OriginalSpan] = new RenameTrackingSpan( _subjectBuffer.CurrentSnapshot.CreateTrackingSpan( linkedRenameSpan.Value.ToSpan(), SpanTrackingMode.EdgeInclusive, TrackingFidelityMode.Forward), kind); } } else { // We might not have a renameable span if an alias conflict completely changed the text _referenceSpanToLinkedRenameSpanMap[replacement.OriginalSpan] = new RenameTrackingSpan( _referenceSpanToLinkedRenameSpanMap[replacement.OriginalSpan].TrackingSpan, RenameSpanKind.None); if (_activeSpan.HasValue && _activeSpan.Value.IntersectsWith(replacement.OriginalSpan)) { _activeSpan = null; } } } else { if (!mergeConflictComments.Any(s => replacement.NewSpan.IntersectsWith(s))) { _conflictResolutionRenameTrackingSpans.Add(new RenameTrackingSpan( _subjectBuffer.CurrentSnapshot.CreateTrackingSpan(replacement.NewSpan.ToSpan(), SpanTrackingMode.EdgeInclusive, TrackingFidelityMode.Forward), kind)); } } } } UpdateReadOnlyRegions(); // 3. Reset the undo state and notify the taggers. this.ApplyReplacementText(updateSelection: false); RaiseSpansChanged(); } } private static async Task<IEnumerable<TextChange>> GetTextChangesFromTextDifferencingServiceAsync(Document oldDocument, Document newDocument, CancellationToken cancellationToken = default(CancellationToken)) { try { using (Logger.LogBlock(FunctionId.Workspace_Document_GetTextChanges, newDocument.Name, cancellationToken)) { if (oldDocument == newDocument) { // no changes return SpecializedCollections.EmptyEnumerable<TextChange>(); } if (newDocument.Id != oldDocument.Id) { throw new ArgumentException(WorkspacesResources.The_specified_document_is_not_a_version_of_this_document); } SourceText oldText = await oldDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); SourceText newText = await newDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); if (oldText == newText) { return SpecializedCollections.EmptyEnumerable<TextChange>(); } var textChanges = newText.GetTextChanges(oldText).ToList(); // if changes are significant (not the whole document being replaced) then use these changes if (textChanges.Count != 1 || textChanges[0].Span != new TextSpan(0, oldText.Length)) { return textChanges; } var textDiffService = oldDocument.Project.Solution.Workspace.Services.GetService<IDocumentTextDifferencingService>(); return await textDiffService.GetTextChangesAsync(oldDocument, newDocument, cancellationToken).ConfigureAwait(false); } } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } private IEnumerable<InlineRenameReplacement> GetMergedReplacementInfos( IEnumerable<InlineRenameReplacement> relevantReplacements, Document preMergeDocument, Document postMergeDocument, CancellationToken cancellationToken) { AssertIsForeground(); var textDiffService = preMergeDocument.Project.Solution.Workspace.Services.GetService<IDocumentTextDifferencingService>(); var contentType = preMergeDocument.Project.LanguageServices.GetService<IContentTypeLanguageService>().GetDefaultContentType(); // TODO: Track all spans at once ITextBufferCloneService textBufferCloneService = null; SnapshotSpan? snapshotSpanToClone = null; string preMergeDocumentTextString = null; var preMergeDocumentText = preMergeDocument.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken); var snapshot = preMergeDocumentText.FindCorrespondingEditorTextSnapshot(); if (snapshot != null) { textBufferCloneService = preMergeDocument.Project.Solution.Workspace.Services.GetService<ITextBufferCloneService>(); if (textBufferCloneService != null) { snapshotSpanToClone = snapshot.GetFullSpan(); } } if (snapshotSpanToClone == null) { preMergeDocumentTextString = preMergeDocument.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken).ToString(); } foreach (var replacement in relevantReplacements) { var buffer = snapshotSpanToClone.HasValue ? textBufferCloneService.Clone(snapshotSpanToClone.Value) : _textBufferFactoryService.CreateTextBuffer(preMergeDocumentTextString, contentType); var trackingSpan = buffer.CurrentSnapshot.CreateTrackingSpan(replacement.NewSpan.ToSpan(), SpanTrackingMode.EdgeExclusive, TrackingFidelityMode.Forward); using (var edit = _subjectBuffer.CreateEdit(EditOptions.None, null, s_calculateMergedSpansEditTag)) { foreach (var change in textDiffService.GetTextChangesAsync(preMergeDocument, postMergeDocument, cancellationToken).WaitAndGetResult(cancellationToken)) { buffer.Replace(change.Span.ToSpan(), change.NewText); } edit.Apply(); } yield return new InlineRenameReplacement(replacement.Kind, replacement.OriginalSpan, trackingSpan.GetSpan(buffer.CurrentSnapshot).Span.ToTextSpan()); } } private static RenameSpanKind GetRenameSpanKind(InlineRenameReplacementKind kind) { switch (kind) { case InlineRenameReplacementKind.NoConflict: case InlineRenameReplacementKind.ResolvedReferenceConflict: return RenameSpanKind.Reference; case InlineRenameReplacementKind.ResolvedNonReferenceConflict: return RenameSpanKind.None; case InlineRenameReplacementKind.UnresolvedConflict: return RenameSpanKind.UnresolvedConflict; case InlineRenameReplacementKind.Complexified: return RenameSpanKind.Complexified; default: throw ExceptionUtilities.UnexpectedValue(kind); } } private struct SelectionTracking : IDisposable { private readonly int? _anchor; private readonly int? _active; private readonly TextSpan _anchorSpan; private readonly TextSpan _activeSpan; private readonly OpenTextBufferManager _openTextBufferManager; public SelectionTracking(OpenTextBufferManager openTextBufferManager) { _openTextBufferManager = openTextBufferManager; _anchor = null; _anchorSpan = default(TextSpan); _active = null; _activeSpan = default(TextSpan); var textView = openTextBufferManager.ActiveTextview; if (textView == null) { return; } var selection = textView.Selection; var snapshot = openTextBufferManager._subjectBuffer.CurrentSnapshot; var containingSpans = openTextBufferManager._referenceSpanToLinkedRenameSpanMap.Select(kvp => { // GetSpanInView() can return an empty collection if the tracking span isn't mapped to anything // in the current view, specifically a `@model SomeModelClass` directive in a Razor file. var ss = textView.GetSpanInView(kvp.Value.TrackingSpan.GetSpan(snapshot)).FirstOrDefault(); if (ss != default(SnapshotSpan) && (ss.IntersectsWith(selection.ActivePoint.Position) || ss.IntersectsWith(selection.AnchorPoint.Position))) { return Tuple.Create(kvp.Key, ss); } else { return null; } }).WhereNotNull(); foreach (var tuple in containingSpans) { if (tuple.Item2.IntersectsWith(selection.AnchorPoint.Position)) { _anchor = tuple.Item2.End - selection.AnchorPoint.Position; _anchorSpan = tuple.Item1; } if (tuple.Item2.IntersectsWith(selection.ActivePoint.Position)) { _active = tuple.Item2.End - selection.ActivePoint.Position; _activeSpan = tuple.Item1; } } } public void Dispose() { var textView = _openTextBufferManager.ActiveTextview; if (textView == null) { return; } if (_anchor.HasValue || _active.HasValue) { var selection = textView.Selection; var snapshot = _openTextBufferManager._subjectBuffer.CurrentSnapshot; var anchorSpan = _anchorSpan; var anchorPoint = new VirtualSnapshotPoint(textView.TextSnapshot, _anchor.HasValue && _openTextBufferManager._referenceSpanToLinkedRenameSpanMap.Keys.Any(s => s.OverlapsWith(anchorSpan)) ? GetNewEndpoint(_anchorSpan) - _anchor.Value : selection.AnchorPoint.Position); var activeSpan = _activeSpan; var activePoint = new VirtualSnapshotPoint(textView.TextSnapshot, _active.HasValue && _openTextBufferManager._referenceSpanToLinkedRenameSpanMap.Keys.Any(s => s.OverlapsWith(activeSpan)) ? GetNewEndpoint(_activeSpan) - _active.Value : selection.ActivePoint.Position); textView.SetSelection(anchorPoint, activePoint); } } private SnapshotPoint GetNewEndpoint(TextSpan span) { var snapshot = _openTextBufferManager._subjectBuffer.CurrentSnapshot; var endPoint = _openTextBufferManager._referenceSpanToLinkedRenameSpanMap.ContainsKey(span) ? _openTextBufferManager._referenceSpanToLinkedRenameSpanMap[span].TrackingSpan.GetEndPoint(snapshot) : _openTextBufferManager._referenceSpanToLinkedRenameSpanMap.First(kvp => kvp.Key.OverlapsWith(span)).Value.TrackingSpan.GetEndPoint(snapshot); return _openTextBufferManager.ActiveTextview.BufferGraph.MapUpToBuffer(endPoint, PointTrackingMode.Positive, PositionAffinity.Successor, _openTextBufferManager.ActiveTextview.TextBuffer).Value; } } } } }
// 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>AssetGroupAsset</c> resource.</summary> public sealed partial class AssetGroupAssetName : gax::IResourceName, sys::IEquatable<AssetGroupAssetName> { /// <summary>The possible contents of <see cref="AssetGroupAssetName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>customers/{customer_id}/assetGroupAssets/{asset_group_id}~{asset_id}~{field_type}</c>. /// </summary> CustomerAssetGroupAssetFieldType = 1, } private static gax::PathTemplate s_customerAssetGroupAssetFieldType = new gax::PathTemplate("customers/{customer_id}/assetGroupAssets/{asset_group_id_asset_id_field_type}"); /// <summary>Creates a <see cref="AssetGroupAssetName"/> 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="AssetGroupAssetName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static AssetGroupAssetName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new AssetGroupAssetName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="AssetGroupAssetName"/> with the pattern /// <c>customers/{customer_id}/assetGroupAssets/{asset_group_id}~{asset_id}~{field_type}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="assetGroupId">The <c>AssetGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="fieldTypeId">The <c>FieldType</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="AssetGroupAssetName"/> constructed from the provided ids.</returns> public static AssetGroupAssetName FromCustomerAssetGroupAssetFieldType(string customerId, string assetGroupId, string assetId, string fieldTypeId) => new AssetGroupAssetName(ResourceNameType.CustomerAssetGroupAssetFieldType, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), assetGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(assetGroupId, nameof(assetGroupId)), assetId: gax::GaxPreconditions.CheckNotNullOrEmpty(assetId, nameof(assetId)), fieldTypeId: gax::GaxPreconditions.CheckNotNullOrEmpty(fieldTypeId, nameof(fieldTypeId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="AssetGroupAssetName"/> with pattern /// <c>customers/{customer_id}/assetGroupAssets/{asset_group_id}~{asset_id}~{field_type}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="assetGroupId">The <c>AssetGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="fieldTypeId">The <c>FieldType</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="AssetGroupAssetName"/> with pattern /// <c>customers/{customer_id}/assetGroupAssets/{asset_group_id}~{asset_id}~{field_type}</c>. /// </returns> public static string Format(string customerId, string assetGroupId, string assetId, string fieldTypeId) => FormatCustomerAssetGroupAssetFieldType(customerId, assetGroupId, assetId, fieldTypeId); /// <summary> /// Formats the IDs into the string representation of this <see cref="AssetGroupAssetName"/> with pattern /// <c>customers/{customer_id}/assetGroupAssets/{asset_group_id}~{asset_id}~{field_type}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="assetGroupId">The <c>AssetGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="fieldTypeId">The <c>FieldType</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="AssetGroupAssetName"/> with pattern /// <c>customers/{customer_id}/assetGroupAssets/{asset_group_id}~{asset_id}~{field_type}</c>. /// </returns> public static string FormatCustomerAssetGroupAssetFieldType(string customerId, string assetGroupId, string assetId, string fieldTypeId) => s_customerAssetGroupAssetFieldType.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(assetGroupId, nameof(assetGroupId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(assetId, nameof(assetId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(fieldTypeId, nameof(fieldTypeId)))}"); /// <summary> /// Parses the given resource name string into a new <see cref="AssetGroupAssetName"/> 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}/assetGroupAssets/{asset_group_id}~{asset_id}~{field_type}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="assetGroupAssetName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="AssetGroupAssetName"/> if successful.</returns> public static AssetGroupAssetName Parse(string assetGroupAssetName) => Parse(assetGroupAssetName, false); /// <summary> /// Parses the given resource name string into a new <see cref="AssetGroupAssetName"/> 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}/assetGroupAssets/{asset_group_id}~{asset_id}~{field_type}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="assetGroupAssetName">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="AssetGroupAssetName"/> if successful.</returns> public static AssetGroupAssetName Parse(string assetGroupAssetName, bool allowUnparsed) => TryParse(assetGroupAssetName, allowUnparsed, out AssetGroupAssetName 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="AssetGroupAssetName"/> 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}/assetGroupAssets/{asset_group_id}~{asset_id}~{field_type}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="assetGroupAssetName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="AssetGroupAssetName"/>, 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 assetGroupAssetName, out AssetGroupAssetName result) => TryParse(assetGroupAssetName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="AssetGroupAssetName"/> 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}/assetGroupAssets/{asset_group_id}~{asset_id}~{field_type}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="assetGroupAssetName">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="AssetGroupAssetName"/>, 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 assetGroupAssetName, bool allowUnparsed, out AssetGroupAssetName result) { gax::GaxPreconditions.CheckNotNull(assetGroupAssetName, nameof(assetGroupAssetName)); gax::TemplatedResourceName resourceName; if (s_customerAssetGroupAssetFieldType.TryParseName(assetGroupAssetName, out resourceName)) { string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', '~', }); if (split1 == null) { result = null; return false; } result = FromCustomerAssetGroupAssetFieldType(resourceName[0], split1[0], split1[1], split1[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(assetGroupAssetName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private static string[] ParseSplitHelper(string s, char[] separators) { string[] result = new string[separators.Length + 1]; int i0 = 0; for (int i = 0; i <= separators.Length; i++) { int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length; if (i1 < 0 || i1 == i0) { return null; } result[i] = s.Substring(i0, i1 - i0); i0 = i1 + 1; } return result; } private AssetGroupAssetName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string assetId = null, string assetGroupId = null, string customerId = null, string fieldTypeId = null) { Type = type; UnparsedResource = unparsedResourceName; AssetId = assetId; AssetGroupId = assetGroupId; CustomerId = customerId; FieldTypeId = fieldTypeId; } /// <summary> /// Constructs a new instance of a <see cref="AssetGroupAssetName"/> class from the component parts of pattern /// <c>customers/{customer_id}/assetGroupAssets/{asset_group_id}~{asset_id}~{field_type}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="assetGroupId">The <c>AssetGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="fieldTypeId">The <c>FieldType</c> ID. Must not be <c>null</c> or empty.</param> public AssetGroupAssetName(string customerId, string assetGroupId, string assetId, string fieldTypeId) : this(ResourceNameType.CustomerAssetGroupAssetFieldType, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), assetGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(assetGroupId, nameof(assetGroupId)), assetId: gax::GaxPreconditions.CheckNotNullOrEmpty(assetId, nameof(assetId)), fieldTypeId: gax::GaxPreconditions.CheckNotNullOrEmpty(fieldTypeId, nameof(fieldTypeId))) { } /// <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>Asset</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string AssetId { get; } /// <summary> /// The <c>AssetGroup</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string AssetGroupId { 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> /// The <c>FieldType</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string FieldTypeId { 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.CustomerAssetGroupAssetFieldType: return s_customerAssetGroupAssetFieldType.Expand(CustomerId, $"{AssetGroupId}~{AssetId}~{FieldTypeId}"); 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 AssetGroupAssetName); /// <inheritdoc/> public bool Equals(AssetGroupAssetName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(AssetGroupAssetName a, AssetGroupAssetName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(AssetGroupAssetName a, AssetGroupAssetName b) => !(a == b); } public partial class AssetGroupAsset { /// <summary> /// <see cref="AssetGroupAssetName"/>-typed view over the <see cref="ResourceName"/> resource name property. /// </summary> internal AssetGroupAssetName ResourceNameAsAssetGroupAssetName { get => string.IsNullOrEmpty(ResourceName) ? null : AssetGroupAssetName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } /// <summary> /// <see cref="AssetGroupName"/>-typed view over the <see cref="AssetGroup"/> resource name property. /// </summary> internal AssetGroupName AssetGroupAsAssetGroupName { get => string.IsNullOrEmpty(AssetGroup) ? null : AssetGroupName.Parse(AssetGroup, allowUnparsed: true); set => AssetGroup = value?.ToString() ?? ""; } /// <summary><see cref="AssetName"/>-typed view over the <see cref="Asset"/> resource name property.</summary> internal AssetName AssetAsAssetName { get => string.IsNullOrEmpty(Asset) ? null : AssetName.Parse(Asset, allowUnparsed: true); set => Asset = value?.ToString() ?? ""; } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the cloudformation-2010-05-15.normal.json service model. */ using System; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Amazon.CloudFormation.Model; namespace Amazon.CloudFormation { /// <summary> /// Interface for accessing CloudFormation /// /// AWS CloudFormation /// <para> /// AWS CloudFormation enables you to create and manage AWS infrastructure deployments /// predictably and repeatedly. AWS CloudFormation helps you leverage AWS products such /// as Amazon EC2, EBS, Amazon SNS, ELB, and Auto Scaling to build highly-reliable, highly /// scalable, cost effective applications without worrying about creating and configuring /// the underlying AWS infrastructure. /// </para> /// /// <para> /// With AWS CloudFormation, you declare all of your resources and dependencies in a template /// file. The template defines a collection of resources as a single unit called a stack. /// AWS CloudFormation creates and deletes all member resources of the stack together /// and manages all dependencies between the resources for you. /// </para> /// /// <para> /// For more information about this product, go to the <a href="http://aws.amazon.com/cloudformation/">CloudFormation /// Product Page</a>. /// </para> /// /// <para> /// Amazon CloudFormation makes use of other AWS products. If you need additional technical /// information about a specific AWS product, you can find the product's technical documentation /// at <a href="http://aws.amazon.com/documentation/">http://aws.amazon.com/documentation/</a>. /// </para> /// </summary> public partial interface IAmazonCloudFormation : IDisposable { #region CancelUpdateStack /// <summary> /// Cancels an update on the specified stack. If the call completes successfully, the /// stack will roll back the update and revert to the previous stack configuration. /// /// <note>Only stacks that are in the UPDATE_IN_PROGRESS state can be canceled.</note> /// </summary> /// <param name="request">Container for the necessary parameters to execute the CancelUpdateStack service method.</param> /// /// <returns>The response from the CancelUpdateStack service method, as returned by CloudFormation.</returns> CancelUpdateStackResponse CancelUpdateStack(CancelUpdateStackRequest request); /// <summary> /// Initiates the asynchronous execution of the CancelUpdateStack operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CancelUpdateStack operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<CancelUpdateStackResponse> CancelUpdateStackAsync(CancelUpdateStackRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region CreateStack /// <summary> /// Creates a stack as specified in the template. After the call completes successfully, /// the stack creation starts. You can check the status of the stack via the <a>DescribeStacks</a> /// API. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateStack service method.</param> /// /// <returns>The response from the CreateStack service method, as returned by CloudFormation.</returns> /// <exception cref="Amazon.CloudFormation.Model.AlreadyExistsException"> /// Resource with the name requested already exists. /// </exception> /// <exception cref="Amazon.CloudFormation.Model.InsufficientCapabilitiesException"> /// The template contains resources with capabilities that were not specified in the Capabilities /// parameter. /// </exception> /// <exception cref="Amazon.CloudFormation.Model.LimitExceededException"> /// Quota for the resource has already been reached. /// </exception> CreateStackResponse CreateStack(CreateStackRequest request); /// <summary> /// Initiates the asynchronous execution of the CreateStack operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateStack operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<CreateStackResponse> CreateStackAsync(CreateStackRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DeleteStack /// <summary> /// Deletes a specified stack. Once the call completes successfully, stack deletion starts. /// Deleted stacks do not show up in the <a>DescribeStacks</a> API if the deletion has /// been completed successfully. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteStack service method.</param> /// /// <returns>The response from the DeleteStack service method, as returned by CloudFormation.</returns> DeleteStackResponse DeleteStack(DeleteStackRequest request); /// <summary> /// Initiates the asynchronous execution of the DeleteStack operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteStack operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DeleteStackResponse> DeleteStackAsync(DeleteStackRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeStackEvents /// <summary> /// Returns all stack related events for a specified stack. For more information about /// a stack's event history, go to <a href="http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/concept-stack.html">Stacks</a> /// in the AWS CloudFormation User Guide. /// /// <note>You can list events for stacks that have failed to create or have been deleted /// by specifying the unique stack identifier (stack ID).</note> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeStackEvents service method.</param> /// /// <returns>The response from the DescribeStackEvents service method, as returned by CloudFormation.</returns> DescribeStackEventsResponse DescribeStackEvents(DescribeStackEventsRequest request); /// <summary> /// Initiates the asynchronous execution of the DescribeStackEvents operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeStackEvents operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DescribeStackEventsResponse> DescribeStackEventsAsync(DescribeStackEventsRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeStackResource /// <summary> /// Returns a description of the specified resource in the specified stack. /// /// /// <para> /// For deleted stacks, DescribeStackResource returns resource information for up to 90 /// days after the stack has been deleted. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeStackResource service method.</param> /// /// <returns>The response from the DescribeStackResource service method, as returned by CloudFormation.</returns> DescribeStackResourceResponse DescribeStackResource(DescribeStackResourceRequest request); /// <summary> /// Initiates the asynchronous execution of the DescribeStackResource operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeStackResource operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DescribeStackResourceResponse> DescribeStackResourceAsync(DescribeStackResourceRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeStackResources /// <summary> /// Returns AWS resource descriptions for running and deleted stacks. If <code>StackName</code> /// is specified, all the associated resources that are part of the stack are returned. /// If <code>PhysicalResourceId</code> is specified, the associated resources of the stack /// that the resource belongs to are returned. /// /// <note>Only the first 100 resources will be returned. If your stack has more resources /// than this, you should use <code>ListStackResources</code> instead.</note> /// <para> /// For deleted stacks, <code>DescribeStackResources</code> returns resource information /// for up to 90 days after the stack has been deleted. /// </para> /// /// <para> /// You must specify either <code>StackName</code> or <code>PhysicalResourceId</code>, /// but not both. In addition, you can specify <code>LogicalResourceId</code> to filter /// the returned result. For more information about resources, the <code>LogicalResourceId</code> /// and <code>PhysicalResourceId</code>, go to the <a href="http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide">AWS /// CloudFormation User Guide</a>. /// </para> /// <note>A <code>ValidationError</code> is returned if you specify both <code>StackName</code> /// and <code>PhysicalResourceId</code> in the same request.</note> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeStackResources service method.</param> /// /// <returns>The response from the DescribeStackResources service method, as returned by CloudFormation.</returns> DescribeStackResourcesResponse DescribeStackResources(DescribeStackResourcesRequest request); /// <summary> /// Initiates the asynchronous execution of the DescribeStackResources operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeStackResources operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DescribeStackResourcesResponse> DescribeStackResourcesAsync(DescribeStackResourcesRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeStacks /// <summary> /// Returns the description for the specified stack; if no stack name was specified, then /// it returns the description for all the stacks created. /// </summary> /// /// <returns>The response from the DescribeStacks service method, as returned by CloudFormation.</returns> DescribeStacksResponse DescribeStacks(); /// <summary> /// Returns the description for the specified stack; if no stack name was specified, then /// it returns the description for all the stacks created. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeStacks service method.</param> /// /// <returns>The response from the DescribeStacks service method, as returned by CloudFormation.</returns> DescribeStacksResponse DescribeStacks(DescribeStacksRequest request); /// <summary> /// Returns the description for the specified stack; if no stack name was specified, then /// it returns the description for all the stacks created. /// </summary> /// <param name="cancellationToken"> ttd1 /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribeStacks service method, as returned by CloudFormation.</returns> Task<DescribeStacksResponse> DescribeStacksAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Initiates the asynchronous execution of the DescribeStacks operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeStacks operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DescribeStacksResponse> DescribeStacksAsync(DescribeStacksRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region EstimateTemplateCost /// <summary> /// Returns the estimated monthly cost of a template. The return value is an AWS Simple /// Monthly Calculator URL with a query string that describes the resources required to /// run the template. /// </summary> /// <param name="request">Container for the necessary parameters to execute the EstimateTemplateCost service method.</param> /// /// <returns>The response from the EstimateTemplateCost service method, as returned by CloudFormation.</returns> EstimateTemplateCostResponse EstimateTemplateCost(EstimateTemplateCostRequest request); /// <summary> /// Initiates the asynchronous execution of the EstimateTemplateCost operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the EstimateTemplateCost operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<EstimateTemplateCostResponse> EstimateTemplateCostAsync(EstimateTemplateCostRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetStackPolicy /// <summary> /// Returns the stack policy for a specified stack. If a stack doesn't have a policy, /// a null value is returned. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetStackPolicy service method.</param> /// /// <returns>The response from the GetStackPolicy service method, as returned by CloudFormation.</returns> GetStackPolicyResponse GetStackPolicy(GetStackPolicyRequest request); /// <summary> /// Initiates the asynchronous execution of the GetStackPolicy operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetStackPolicy operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<GetStackPolicyResponse> GetStackPolicyAsync(GetStackPolicyRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetTemplate /// <summary> /// Returns the template body for a specified stack. You can get the template for running /// or deleted stacks. /// /// /// <para> /// For deleted stacks, GetTemplate returns the template for up to 90 days after the stack /// has been deleted. /// </para> /// <note> If the template does not exist, a <code>ValidationError</code> is returned. /// </note> /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetTemplate service method.</param> /// /// <returns>The response from the GetTemplate service method, as returned by CloudFormation.</returns> GetTemplateResponse GetTemplate(GetTemplateRequest request); /// <summary> /// Initiates the asynchronous execution of the GetTemplate operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetTemplate operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<GetTemplateResponse> GetTemplateAsync(GetTemplateRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetTemplateSummary /// <summary> /// Returns information about a new or existing template. The <code>GetTemplateSummary</code> /// action is useful for viewing parameter information, such as default parameter values /// and parameter types, before you create or update a stack. /// /// /// <para> /// You can use the <code>GetTemplateSummary</code> action when you submit a template, /// or you can get template information for a running or deleted stack. /// </para> /// /// <para> /// For deleted stacks, <code>GetTemplateSummary</code> returns the template information /// for up to 90 days after the stack has been deleted. If the template does not exist, /// a <code>ValidationError</code> is returned. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetTemplateSummary service method.</param> /// /// <returns>The response from the GetTemplateSummary service method, as returned by CloudFormation.</returns> GetTemplateSummaryResponse GetTemplateSummary(GetTemplateSummaryRequest request); /// <summary> /// Initiates the asynchronous execution of the GetTemplateSummary operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetTemplateSummary operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<GetTemplateSummaryResponse> GetTemplateSummaryAsync(GetTemplateSummaryRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListStackResources /// <summary> /// Returns descriptions of all resources of the specified stack. /// /// /// <para> /// For deleted stacks, ListStackResources returns resource information for up to 90 days /// after the stack has been deleted. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListStackResources service method.</param> /// /// <returns>The response from the ListStackResources service method, as returned by CloudFormation.</returns> ListStackResourcesResponse ListStackResources(ListStackResourcesRequest request); /// <summary> /// Initiates the asynchronous execution of the ListStackResources operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListStackResources operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<ListStackResourcesResponse> ListStackResourcesAsync(ListStackResourcesRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListStacks /// <summary> /// Returns the summary information for stacks whose status matches the specified StackStatusFilter. /// Summary information for stacks that have been deleted is kept for 90 days after the /// stack is deleted. If no StackStatusFilter is specified, summary information for all /// stacks is returned (including existing stacks and stacks that have been deleted). /// </summary> /// /// <returns>The response from the ListStacks service method, as returned by CloudFormation.</returns> ListStacksResponse ListStacks(); /// <summary> /// Returns the summary information for stacks whose status matches the specified StackStatusFilter. /// Summary information for stacks that have been deleted is kept for 90 days after the /// stack is deleted. If no StackStatusFilter is specified, summary information for all /// stacks is returned (including existing stacks and stacks that have been deleted). /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListStacks service method.</param> /// /// <returns>The response from the ListStacks service method, as returned by CloudFormation.</returns> ListStacksResponse ListStacks(ListStacksRequest request); /// <summary> /// Returns the summary information for stacks whose status matches the specified StackStatusFilter. /// Summary information for stacks that have been deleted is kept for 90 days after the /// stack is deleted. If no StackStatusFilter is specified, summary information for all /// stacks is returned (including existing stacks and stacks that have been deleted). /// </summary> /// <param name="cancellationToken"> ttd1 /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListStacks service method, as returned by CloudFormation.</returns> Task<ListStacksResponse> ListStacksAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Initiates the asynchronous execution of the ListStacks operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListStacks operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<ListStacksResponse> ListStacksAsync(ListStacksRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region SetStackPolicy /// <summary> /// Sets a stack policy for a specified stack. /// </summary> /// <param name="request">Container for the necessary parameters to execute the SetStackPolicy service method.</param> /// /// <returns>The response from the SetStackPolicy service method, as returned by CloudFormation.</returns> SetStackPolicyResponse SetStackPolicy(SetStackPolicyRequest request); /// <summary> /// Initiates the asynchronous execution of the SetStackPolicy operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the SetStackPolicy operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<SetStackPolicyResponse> SetStackPolicyAsync(SetStackPolicyRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region SignalResource /// <summary> /// Sends a signal to the specified resource with a success or failure status. You can /// use the SignalResource API in conjunction with a creation policy or update policy. /// AWS CloudFormation doesn't proceed with a stack creation or update until resources /// receive the required number of signals or the timeout period is exceeded. The SignalResource /// API is useful in cases where you want to send signals from anywhere other than an /// Amazon EC2 instance. /// </summary> /// <param name="request">Container for the necessary parameters to execute the SignalResource service method.</param> /// /// <returns>The response from the SignalResource service method, as returned by CloudFormation.</returns> SignalResourceResponse SignalResource(SignalResourceRequest request); /// <summary> /// Initiates the asynchronous execution of the SignalResource operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the SignalResource operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<SignalResourceResponse> SignalResourceAsync(SignalResourceRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region UpdateStack /// <summary> /// Updates a stack as specified in the template. After the call completes successfully, /// the stack update starts. You can check the status of the stack via the <a>DescribeStacks</a> /// action. /// /// /// <para> /// To get a copy of the template for an existing stack, you can use the <a>GetTemplate</a> /// action. /// </para> /// /// <para> /// Tags that were associated with this stack during creation time will still be associated /// with the stack after an <code>UpdateStack</code> operation. /// </para> /// /// <para> /// For more information about creating an update template, updating a stack, and monitoring /// the progress of the update, see <a href="http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks.html">Updating /// a Stack</a>. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the UpdateStack service method.</param> /// /// <returns>The response from the UpdateStack service method, as returned by CloudFormation.</returns> /// <exception cref="Amazon.CloudFormation.Model.InsufficientCapabilitiesException"> /// The template contains resources with capabilities that were not specified in the Capabilities /// parameter. /// </exception> UpdateStackResponse UpdateStack(UpdateStackRequest request); /// <summary> /// Initiates the asynchronous execution of the UpdateStack operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UpdateStack operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<UpdateStackResponse> UpdateStackAsync(UpdateStackRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ValidateTemplate /// <summary> /// Validates a specified template. /// </summary> /// /// <returns>The response from the ValidateTemplate service method, as returned by CloudFormation.</returns> ValidateTemplateResponse ValidateTemplate(); /// <summary> /// Validates a specified template. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ValidateTemplate service method.</param> /// /// <returns>The response from the ValidateTemplate service method, as returned by CloudFormation.</returns> ValidateTemplateResponse ValidateTemplate(ValidateTemplateRequest request); /// <summary> /// Validates a specified template. /// </summary> /// <param name="cancellationToken"> ttd1 /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ValidateTemplate service method, as returned by CloudFormation.</returns> Task<ValidateTemplateResponse> ValidateTemplateAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Initiates the asynchronous execution of the ValidateTemplate operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ValidateTemplate operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<ValidateTemplateResponse> ValidateTemplateAsync(ValidateTemplateRequest request, CancellationToken cancellationToken = default(CancellationToken)); #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.Collections.Concurrent; using System.Diagnostics.Contracts; using System.Globalization; using System.Reflection; using System.Runtime; using System.Runtime.CompilerServices; using System.ServiceModel.Description; using System.ServiceModel.Diagnostics; using System.ServiceModel.Dispatcher; using System.Threading.Tasks; namespace System.ServiceModel.Channels { public class ServiceChannelProxy : DispatchProxy, ICommunicationObject, IChannel, IClientChannel, IOutputChannel, IRequestChannel, IServiceChannel { private const String activityIdSlotName = "E2ETrace.ActivityID"; private Type _proxiedType; private ServiceChannel _serviceChannel; private ImmutableClientRuntime _proxyRuntime; private MethodDataCache _methodDataCache; // ServiceChannelProxy serves 2 roles. It is the TChannel proxy called by the client, // and it is also the handler of those calls that dispatches them to the appropriate service channel. // In .Net Remoting terms, it is conceptually the same as a RealProxy and a TransparentProxy combined. internal static TChannel CreateProxy<TChannel>(MessageDirection direction, ServiceChannel serviceChannel) { TChannel proxy = DispatchProxy.Create<TChannel, ServiceChannelProxy>(); if (proxy == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.FailedToCreateTypedProxy, typeof(TChannel)))); } ServiceChannelProxy channelProxy = (ServiceChannelProxy)(object)proxy; channelProxy._proxiedType = typeof(TChannel); channelProxy._serviceChannel = serviceChannel; channelProxy._proxyRuntime = serviceChannel.ClientRuntime.GetRuntime(); channelProxy._methodDataCache = new MethodDataCache(); return proxy; } //Workaround is to set the activityid in remoting call's LogicalCallContext // Override ToString() to reveal only the expected proxy type, not the generated one public override string ToString() { return _proxiedType.ToString(); } private MethodData GetMethodData(MethodCall methodCall) { MethodData methodData; MethodBase method = methodCall.MethodBase; if (_methodDataCache.TryGetMethodData(method, out methodData)) { return methodData; } bool canCacheMessageData; Type declaringType = method.DeclaringType; if (declaringType == typeof(object) && method == typeof(object).GetMethod("GetType")) { canCacheMessageData = true; methodData = new MethodData(method, MethodType.GetType); } else if (declaringType.IsAssignableFrom(_serviceChannel.GetType())) { canCacheMessageData = true; methodData = new MethodData(method, MethodType.Channel); } else { ProxyOperationRuntime operation = _proxyRuntime.GetOperation(method, methodCall.Args, out canCacheMessageData); if (operation == null) { if (_serviceChannel.Factory != null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.SFxMethodNotSupported1, method.Name))); else throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.SFxMethodNotSupportedOnCallback1, method.Name))); } MethodType methodType; if (operation.IsTaskCall(methodCall)) { methodType = MethodType.TaskService; } else if (operation.IsSyncCall(methodCall)) { methodType = MethodType.Service; } else if (operation.IsBeginCall(methodCall)) { methodType = MethodType.BeginService; } else { methodType = MethodType.EndService; } methodData = new MethodData(method, methodType, operation); } if (canCacheMessageData) { _methodDataCache.SetMethodData(methodData); } return methodData; } internal ServiceChannel GetServiceChannel() { return _serviceChannel; } protected override object Invoke(MethodInfo targetMethod, object[] args) { if (args == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("args"); } if (targetMethod == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.InvalidTypedProxyMethodHandle, _proxiedType.Name))); } MethodCall methodCall = new MethodCall(targetMethod, args); MethodData methodData = GetMethodData(methodCall); switch (methodData.MethodType) { case MethodType.Service: return InvokeService(methodCall, methodData.Operation); case MethodType.BeginService: return InvokeBeginService(methodCall, methodData.Operation); case MethodType.EndService: return InvokeEndService(methodCall, methodData.Operation); case MethodType.TaskService: return InvokeTaskService(methodCall, methodData.Operation); case MethodType.Channel: return InvokeChannel(methodCall); case MethodType.GetType: return InvokeGetType(methodCall); default: Fx.Assert("Invalid proxy method type"); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "Invalid proxy method type"))); } } internal static class TaskCreator { public static Task CreateTask(ServiceChannel channel, MethodCall methodCall, ProxyOperationRuntime operation) { if (operation.TaskTResult == ServiceReflector.VoidType) { return TaskCreator.CreateTask(channel, operation, methodCall.Args); } return TaskCreator.CreateGenericTask(channel, operation, methodCall.Args); } private static Task CreateGenericTask(ServiceChannel channel, ProxyOperationRuntime operation, object[] inputParameters) { TaskCompletionSourceProxy tcsp = new TaskCompletionSourceProxy(operation.TaskTResult); bool completedCallback = false; Action<IAsyncResult> endCallDelegate = (asyncResult) => { Contract.Assert(asyncResult != null, "'asyncResult' MUST NOT be NULL."); completedCallback = true; OperationContext originalOperationContext = OperationContext.Current; OperationContext.Current = asyncResult.AsyncState as OperationContext; try { object result = channel.EndCall(operation.Action, Array.Empty<object>(), asyncResult); tcsp.TrySetResult(result); } catch (Exception e) { tcsp.TrySetException(e); } finally { OperationContext.Current = originalOperationContext; } }; try { IAsyncResult ar = ServiceChannel.BeginCall(channel, operation, inputParameters, new AsyncCallback(endCallDelegate), OperationContext.Current); if (ar.CompletedSynchronously && !completedCallback) { endCallDelegate(ar); } } catch (Exception e) { tcsp.TrySetException(e); } return tcsp.Task; } private static Task CreateTask(ServiceChannel channel, ProxyOperationRuntime operation, object[] inputParameters) { TaskCompletionSource<object> tcs = new TaskCompletionSource<object>(); bool completedCallback = false; Action<IAsyncResult> endCallDelegate = (asyncResult) => { Contract.Assert(asyncResult != null, "'asyncResult' MUST NOT be NULL."); completedCallback = true; OperationContext originalOperationContext = OperationContext.Current; OperationContext.Current = asyncResult.AsyncState as OperationContext; try { channel.EndCall(operation.Action, Array.Empty<object>(), asyncResult); tcs.TrySetResult(null); } catch (Exception e) { tcs.TrySetException(e); } finally { OperationContext.Current = originalOperationContext; } }; try { IAsyncResult ar = ServiceChannel.BeginCall(channel, operation, inputParameters, new AsyncCallback(endCallDelegate), OperationContext.Current); if (ar.CompletedSynchronously && !completedCallback) { endCallDelegate(ar); } } catch (Exception e) { tcs.TrySetException(e); } return tcs.Task; } } private class TaskCompletionSourceProxy { private TaskCompletionSourceInfo _tcsInfo; private object _tcsInstance; public TaskCompletionSourceProxy(Type resultType) { _tcsInfo = TaskCompletionSourceInfo.GetTaskCompletionSourceInfo(resultType); _tcsInstance = Activator.CreateInstance(_tcsInfo.GenericType); } public Task Task { get { return (Task)_tcsInfo.TaskProperty.GetValue(_tcsInstance); } } public bool TrySetResult(object result) { return (bool)_tcsInfo.TrySetResultMethod.Invoke(_tcsInstance, new object[] { result }); } public bool TrySetException(Exception exception) { return (bool)_tcsInfo.TrySetExceptionMethod.Invoke(_tcsInstance, new object[] { exception }); } public bool TrySetCanceled() { return (bool)_tcsInfo.TrySetCanceledMethod.Invoke(_tcsInstance, Array.Empty<object>()); } } private class TaskCompletionSourceInfo { private static ConcurrentDictionary<Type, TaskCompletionSourceInfo> s_cache = new ConcurrentDictionary<Type, TaskCompletionSourceInfo>(); public TaskCompletionSourceInfo(Type resultType) { ResultType = resultType; Type tcsType = typeof(TaskCompletionSource<>); GenericType = tcsType.MakeGenericType(new Type[] { resultType }); TaskProperty = GenericType.GetTypeInfo().GetDeclaredProperty("Task"); TrySetResultMethod = GenericType.GetTypeInfo().GetDeclaredMethod("TrySetResult"); TrySetExceptionMethod = GenericType.GetRuntimeMethod("TrySetException", new Type[] { typeof(Exception) }); TrySetCanceledMethod = GenericType.GetRuntimeMethod("TrySetCanceled", Array.Empty<Type>()); } public Type ResultType { get; private set; } public Type GenericType { get; private set; } public PropertyInfo TaskProperty { get; private set; } public MethodInfo TrySetResultMethod { get; private set; } public MethodInfo TrySetExceptionMethod { get; set; } public MethodInfo TrySetCanceledMethod { get; set; } public static TaskCompletionSourceInfo GetTaskCompletionSourceInfo(Type resultType) { return s_cache.GetOrAdd(resultType, t => new TaskCompletionSourceInfo(t)); } } private object InvokeTaskService(MethodCall methodCall, ProxyOperationRuntime operation) { Task task = TaskCreator.CreateTask(_serviceChannel, methodCall, operation); return task; } private object InvokeChannel(MethodCall methodCall) { string activityName = null; ActivityType activityType = ActivityType.Unknown; if (DiagnosticUtility.ShouldUseActivity) { if (ServiceModelActivity.Current == null || ServiceModelActivity.Current.ActivityType != ActivityType.Close) { MethodData methodData = this.GetMethodData(methodCall); if (methodData.MethodBase.DeclaringType == typeof(System.ServiceModel.ICommunicationObject) && methodData.MethodBase.Name.Equals("Close", StringComparison.Ordinal)) { activityName = SR.Format(SR.ActivityClose, _serviceChannel.GetType().FullName); activityType = ActivityType.Close; } } } using (ServiceModelActivity activity = string.IsNullOrEmpty(activityName) ? null : ServiceModelActivity.CreateBoundedActivity()) { if (DiagnosticUtility.ShouldUseActivity) { ServiceModelActivity.Start(activity, activityName, activityType); } return ExecuteMessage(_serviceChannel, methodCall); } } private object InvokeGetType(MethodCall methodCall) { return _proxiedType; } private object InvokeBeginService(MethodCall methodCall, ProxyOperationRuntime operation) { AsyncCallback callback; object asyncState; object[] ins = operation.MapAsyncBeginInputs(methodCall, out callback, out asyncState); object ret = _serviceChannel.BeginCall(operation.Action, operation.IsOneWay, operation, ins, callback, asyncState); return ret; } private object InvokeEndService(MethodCall methodCall, ProxyOperationRuntime operation) { IAsyncResult result; object[] outs; operation.MapAsyncEndInputs(methodCall, out result, out outs); object ret = _serviceChannel.EndCall(operation.Action, outs, result); operation.MapAsyncOutputs(methodCall, outs, ref ret); return ret; } private object InvokeService(MethodCall methodCall, ProxyOperationRuntime operation) { object[] outs; object[] ins = operation.MapSyncInputs(methodCall, out outs); object ret = _serviceChannel.Call(operation.Action, operation.IsOneWay, operation, ins, outs); operation.MapSyncOutputs(methodCall, outs, ref ret); return ret; } private object ExecuteMessage(object target, MethodCall methodCall) { MethodBase targetMethod = methodCall.MethodBase; object[] args = methodCall.Args; object returnValue = null; try { returnValue = targetMethod.Invoke(target, args); } catch (TargetInvocationException e) { throw e.InnerException; } return returnValue; } internal class MethodDataCache { private MethodData[] _methodDatas; public MethodDataCache() { _methodDatas = new MethodData[4]; } private object ThisLock { get { return this; } } public bool TryGetMethodData(MethodBase method, out MethodData methodData) { lock (ThisLock) { MethodData[] methodDatas = _methodDatas; int index = FindMethod(methodDatas, method); if (index >= 0) { methodData = methodDatas[index]; return true; } else { methodData = new MethodData(); return false; } } } private static int FindMethod(MethodData[] methodDatas, MethodBase methodToFind) { for (int i = 0; i < methodDatas.Length; i++) { MethodBase method = methodDatas[i].MethodBase; if (method == null) { break; } if (method == methodToFind) { return i; } } return -1; } public void SetMethodData(MethodData methodData) { lock (ThisLock) { int index = FindMethod(_methodDatas, methodData.MethodBase); if (index < 0) { for (int i = 0; i < _methodDatas.Length; i++) { if (_methodDatas[i].MethodBase == null) { _methodDatas[i] = methodData; return; } } MethodData[] newMethodDatas = new MethodData[_methodDatas.Length * 2]; Array.Copy(_methodDatas, newMethodDatas, _methodDatas.Length); newMethodDatas[_methodDatas.Length] = methodData; _methodDatas = newMethodDatas; } } } } internal enum MethodType { Service, BeginService, EndService, Channel, Object, GetType, TaskService } internal struct MethodData { private MethodBase _methodBase; private MethodType _methodType; private ProxyOperationRuntime _operation; public MethodData(MethodBase methodBase, MethodType methodType) : this(methodBase, methodType, null) { } public MethodData(MethodBase methodBase, MethodType methodType, ProxyOperationRuntime operation) { _methodBase = methodBase; _methodType = methodType; _operation = operation; } public MethodBase MethodBase { get { return _methodBase; } } public MethodType MethodType { get { return _methodType; } } public ProxyOperationRuntime Operation { get { return _operation; } } } #region Channel interfaces // These channel methods exist only to implement additional channel interfaces for ServiceChannelProxy. // This is required because clients can down-cast typed proxies to the these channel interfaces. // On the desktop, the .Net Remoting layer allowed that type cast, and subsequent calls against the // interface went back through the RealProxy and invoked the underlying ServiceChannel. // Net Native and CoreClr do not have .Net Remoting and therefore cannot use that mechanism. // But because typed proxies derive from ServiceChannelProxy, implementing these interfaces // on ServiceChannelProxy permits casting the typed proxy to these interfaces. // All interface implentations delegate directly to the underlying ServiceChannel. T IChannel.GetProperty<T>() { return _serviceChannel.GetProperty<T>(); } CommunicationState ICommunicationObject.State { get { return _serviceChannel.State; } } event EventHandler ICommunicationObject.Closed { add { _serviceChannel.Closed += value; } remove { _serviceChannel.Closed -= value; } } event EventHandler ICommunicationObject.Closing { add { _serviceChannel.Closing += value; } remove { _serviceChannel.Closing -= value; } } event EventHandler ICommunicationObject.Faulted { add { _serviceChannel.Faulted += value; } remove { _serviceChannel.Faulted -= value; } } event EventHandler ICommunicationObject.Opened { add { _serviceChannel.Opened += value; } remove { _serviceChannel.Opened -= value; } } event EventHandler ICommunicationObject.Opening { add { _serviceChannel.Opening += value; } remove { _serviceChannel.Opening -= value; } } void ICommunicationObject.Abort() { _serviceChannel.Abort(); } void ICommunicationObject.Close() { _serviceChannel.Close(); } void ICommunicationObject.Close(TimeSpan timeout) { _serviceChannel.Close(timeout); } IAsyncResult ICommunicationObject.BeginClose(AsyncCallback callback, object state) { return _serviceChannel.BeginClose(callback, state); } IAsyncResult ICommunicationObject.BeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return _serviceChannel.BeginClose(timeout, callback, state); } void ICommunicationObject.EndClose(IAsyncResult result) { _serviceChannel.EndClose(result); } void ICommunicationObject.Open() { _serviceChannel.Open(); } void ICommunicationObject.Open(TimeSpan timeout) { _serviceChannel.Open(timeout); } IAsyncResult ICommunicationObject.BeginOpen(AsyncCallback callback, object state) { return _serviceChannel.BeginOpen(callback, state); } IAsyncResult ICommunicationObject.BeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { return _serviceChannel.BeginOpen(timeout, callback, state); } void ICommunicationObject.EndOpen(IAsyncResult result) { _serviceChannel.EndOpen(result); } bool IClientChannel.AllowInitializationUI { get { return ((IClientChannel)_serviceChannel).AllowInitializationUI; } set { ((IClientChannel)_serviceChannel).AllowInitializationUI = value; } } bool IClientChannel.DidInteractiveInitialization { get { return ((IClientChannel)_serviceChannel).DidInteractiveInitialization; } } Uri IClientChannel.Via { get { return _serviceChannel.Via; } } event EventHandler<UnknownMessageReceivedEventArgs> IClientChannel.UnknownMessageReceived { add { ((IClientChannel)_serviceChannel).UnknownMessageReceived += value; } remove { ((IClientChannel)_serviceChannel).UnknownMessageReceived -= value; } } IAsyncResult IClientChannel.BeginDisplayInitializationUI(AsyncCallback callback, object state) { return _serviceChannel.BeginDisplayInitializationUI(callback, state); } void IClientChannel.DisplayInitializationUI() { _serviceChannel.DisplayInitializationUI(); } void IClientChannel.EndDisplayInitializationUI(IAsyncResult result) { _serviceChannel.EndDisplayInitializationUI(result); } void IDisposable.Dispose() { ((IClientChannel)_serviceChannel).Dispose(); } bool IContextChannel.AllowOutputBatching { get { return ((IContextChannel)_serviceChannel).AllowOutputBatching; } set { ((IContextChannel)_serviceChannel).AllowOutputBatching = value; } } IInputSession IContextChannel.InputSession { get { return ((IContextChannel)_serviceChannel).InputSession; } } EndpointAddress IContextChannel.LocalAddress { get { return ((IContextChannel)_serviceChannel).LocalAddress; } } TimeSpan IContextChannel.OperationTimeout { get { return ((IContextChannel)_serviceChannel).OperationTimeout; } set { ((IContextChannel)_serviceChannel).OperationTimeout = value; } } IOutputSession IContextChannel.OutputSession { get { return ((IContextChannel)_serviceChannel).OutputSession; } } EndpointAddress IOutputChannel.RemoteAddress { get { return ((IContextChannel)_serviceChannel).RemoteAddress; } } Uri IOutputChannel.Via { get { return _serviceChannel.Via; } } EndpointAddress IContextChannel.RemoteAddress { get { return ((IContextChannel)_serviceChannel).RemoteAddress; } } string IContextChannel.SessionId { get { return ((IContextChannel)_serviceChannel).SessionId; } } IExtensionCollection<IContextChannel> IExtensibleObject<IContextChannel>.Extensions { get { return ((IContextChannel)_serviceChannel).Extensions; } } IAsyncResult IOutputChannel.BeginSend(Message message, AsyncCallback callback, object state) { return _serviceChannel.BeginSend(message, callback, state); } IAsyncResult IOutputChannel.BeginSend(Message message, TimeSpan timeout, AsyncCallback callback, object state) { return _serviceChannel.BeginSend(message, timeout, callback, state); } void IOutputChannel.EndSend(IAsyncResult result) { _serviceChannel.EndSend(result); } void IOutputChannel.Send(Message message) { _serviceChannel.Send(message); } void IOutputChannel.Send(Message message, TimeSpan timeout) { _serviceChannel.Send(message, timeout); } Message IRequestChannel.Request(Message message) { return _serviceChannel.Request(message); } Message IRequestChannel.Request(Message message, TimeSpan timeout) { return _serviceChannel.Request(message, timeout); } IAsyncResult IRequestChannel.BeginRequest(Message message, AsyncCallback callback, object state) { return _serviceChannel.BeginRequest(message, callback, state); } IAsyncResult IRequestChannel.BeginRequest(Message message, TimeSpan timeout, AsyncCallback callback, object state) { return _serviceChannel.BeginRequest(message, timeout, callback, state); } Message IRequestChannel.EndRequest(IAsyncResult result) { return _serviceChannel.EndRequest(result); } EndpointAddress IRequestChannel.RemoteAddress { get { return ((IContextChannel)_serviceChannel).RemoteAddress; } } Uri IRequestChannel.Via { get { return _serviceChannel.Via; } } Uri IServiceChannel.ListenUri { get { return _serviceChannel.ListenUri; } } #endregion // Channel interfaces } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using Xunit; namespace List_List_SortTests { public class Driver<T> where T : IComparable<T> { #region Sort public void Sort1(T[] items) { List<T> list = new List<T>(new TestCollection<T>(items)); //search for each item list.Sort(); EnsureSorted(list, 0, list.Count); } public RefX1<int>[] MakeRefX1ArrayInt(int[] items) { RefX1<int>[] arr = new RefX1<int>[items.Length]; for (int i = 0; i < items.Length; i++) { arr[i] = new RefX1<int>(items[i]); } return arr; } public ValX1<int>[] MakeValX1ArrayInt(int[] items) { ValX1<int>[] arr = new ValX1<int>[items.Length]; for (int i = 0; i < items.Length; i++) { arr[i] = new ValX1<int>(items[i]); } return arr; } private void EnsureSorted(List<T> list, int index, int count) { for (int i = index; i < index + count - 1; i++) { Assert.True( ((null == (object)list[i]) && (null != (object)list[i + 1]) && (-1 < list[i + 1].CompareTo(list[i]))) || (1 > list[i].CompareTo(list[i + 1])), "The list is not sorted at index: " + i); } } #endregion #region Sort(Comparison) public void VerifyVanilla(T[] items) { List<T> list = new List<T>(); int[] numbers = new int[] { -1, 0, 1 }; int currentIndex = 0; T[] tempArray; //[] Verify Sort with random comparison list.Clear(); for (int i = 0; i < items.Length; ++i) list.Add(items[i]); list.Sort((T x, T y) => { int index = currentIndex % numbers.Length; currentIndex++; return numbers[index]; }); VerifyListOutOfOrder(list, items); //[] Verify Sort with comparison that reverses the order list.Clear(); for (int i = 0; i < items.Length; ++i) list.Add(items[i]); list.Sort(delegate (T x, T y) { return Array.IndexOf(items, y) - Array.IndexOf(items, x); }); tempArray = new T[items.Length]; Array.Copy(items, 0, tempArray, 0, items.Length); Array.Reverse(tempArray); VerifyList(list, tempArray); //[] Verify Sort with comparison that reverses the order AGAIN //[] We are using the reversed list from the previous scenario list.Sort(delegate (T x, T y) { return Array.IndexOf(items, x) - Array.IndexOf(items, y); }); VerifyList(list, items); } public void VerifyExceptions(T[] items) { List<T> list = new List<T>(); for (int i = 0; i < items.Length; ++i) list.Add(items[i]); //[] Verify Null Comparison Assert.Throws<ArgumentNullException>(() => list.Sort((Comparison<T>)null)); //"Err_858ahia Expected null match to throw ArgumentNullException" } private void VerifyList(List<T> list, T[] expectedItems) { Assert.Equal(list.Count, expectedItems.Length); //"Err_2828ahid Expected" //Only verify the indexer. List should be in a good enough state that we //do not have to verify consistancy with any other method. for (int i = 0; i < list.Count; ++i) { Assert.Equal(list[i], expectedItems[i]); //"Err_19818ayiadb Expceted" } } private void VerifyListOutOfOrder(List<T> list, T[] expectedItems) { Assert.Equal(list.Count, expectedItems.Length); //"Err_5808ajhdo Expected" //do not have to verify consistancy with any other method. for (int i = 0; i < list.Count; ++i) { Assert.True(list.Contains(expectedItems[i])); //"Err_51108ajdiu Expceted" } } public void CallSortAndVerify(T[] items, T[] expectedItems, Comparison<T> comparison) { List<T> list = new List<T>(); List<T> visitedItems = new List<T>(); for (int i = 0; i < items.Length; ++i) list.Add(items[i]); list.Sort(comparison); VerifyList(list, expectedItems); } #endregion } public class Driver2<T> where T : IComparableValue { #region Sort(IComparer<T>) public void SortIComparer(T[] items) { List<T> list = new List<T>(new TestCollection<T>(items)); //search for each item list.Sort(new ValueComparer<T>()); EnsureSorted(list, 0, list.Count); } public void SortIComparerValidations(T[] items) { List<T> list = new List<T>(new TestCollection<T>(items)); Assert.Throws<InvalidOperationException>(() => list.Sort((IComparer<T>)null)); //"InvalidOperationException expected." } public RefX1_IC<int>[] MakeRefX1ArrayInt(int[] items) { RefX1_IC<int>[] arr = new RefX1_IC<int>[items.Length]; for (int i = 0; i < items.Length; i++) { arr[i] = new RefX1_IC<int>(items[i]); } return arr; } public ValX1_IC<int>[] MakeValX1ArrayInt(int[] items) { ValX1_IC<int>[] arr = new ValX1_IC<int>[items.Length]; for (int i = 0; i < items.Length; i++) { arr[i] = new ValX1_IC<int>(items[i]); } return arr; } #endregion #region Sort(int, int, IComparer<T>) public void SortIntIntIComparer(T[] items, int index, int count) { List<T> list = new List<T>(new TestCollection<T>(items)); //search for each item list.Sort(index, count, new ValueComparer<T>()); EnsureSorted(list, index, count); for (int i = 0; i < index; i++) { Assert.Equal(((Object)list[i]), items[i]); //"Expected them to be the same." } for (int i = index + count; i < items.Length; i++) { Assert.Equal(((Object)list[i]), items[i]); //"Expected them to be the same." } } public void SortIntIntIComparerValidations(T[] items) { List<T> list = new List<T>(new TestCollection<T>(items)); Assert.Throws<InvalidOperationException>(() => list.Sort((IComparer<T>)null)); //"InvalidOperationException expected" int[] bad = new int[] { items.Length,1, items.Length+1,0, int.MaxValue,0 }; for (int i = 0; i < bad.Length; i++) { Assert.Throws<ArgumentException>(() => list.Sort(bad[i], bad[++i], new ValueComparer<T>())); //"ArgumentException expected." } bad = new int[] { -1,0, -2,0, int.MinValue,0, 0,-1, 0,-2, 0,int.MinValue }; for (int i = 0; i < bad.Length; i++) { Assert.Throws<ArgumentOutOfRangeException>(() => list.Sort(bad[i], bad[++i], new ValueComparer<T>())); //"ArgumentOutOfRangeException expected." } } #endregion private void EnsureSorted(List<T> list, int index, int count) { for (int i = index; i < index + count - 1; i++) { Assert.True( ((null == (object)list[i]) && (null != (object)list[i + 1]) && (-1 < list[i + 1].CompareTo(list[i]))) || (1 > list[i].CompareTo(list[i + 1])), "The list is not sorted at index: " + i); } } } public class List_SortTests { #region Static Member Variables private static readonly int[] s_arr1 = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; private static readonly int[] s_arr2 = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 }; private static readonly int[] s_arr3 = new int[] { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }; private static readonly int[] s_arr4 = new int[] { 9, 8, 7, 6, 5, 4, 3, 2, 1 }; private static readonly int[] s_arr5 = new int[] { 9, 1, 2, 3, 4, 5, 6, 7, 8, 0 }; private static readonly int[] s_arr6 = new int[] { 8, 1, 2, 3, 4, 5, 6, 7, 0 }; private static readonly int[] s_arr7 = new int[] { 0, 9, 8, 7, 6, 5, 4, 3, 2, 1 }; private static readonly int[] s_arr8 = new int[] { 1, 9, 8, 7, 6, 5, 4, 3, 2 }; private static readonly int[] s_arr9 = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; private static readonly int[] s_arr10 = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 0 }; private static readonly int[] s_arr11 = new int[] { 8, 7, 6, 5, 4, 3, 2, 1, 0, 9 }; private static readonly int[] s_arr12 = new int[] { 7, 6, 5, 4, 3, 2, 1, 0, 8 }; private static readonly int[] s_arr13 = new int[] { 5, 1, 2, 3, 4, 9, 6, 7, 8, 0 }; private static readonly int[] s_arr14 = new int[] { 4, 1, 2, 3, 8, 5, 6, 7, 0 }; private static readonly int[] s_arr15 = new int[] { 0, 9, 8, 7, 1, 5, 4, 3, 2, 6 }; private static readonly int[] s_arr16 = new int[] { 1, 9, 8, 7, 6, 2, 4, 3, 5 }; private static readonly int[] s_arr17 = new int[] { 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2 }; private static readonly int[] s_arr18 = new int[] { 1, 1, 2, 0, 2, 2, 0, 0, 2, 0, 1, 1 }; private static readonly int[] s_arr19 = new int[] { 2, 1, 3 }; private static readonly int[] s_arr20 = new int[] { 2, 3, 1 }; private static readonly int[] s_arr21 = new int[] { 1, 2, 3 }; private static readonly int[] s_arr22 = new int[] { 1, 3, 2 }; private static readonly int[] s_arr23 = new int[] { 3, 2, 1 }; private static readonly int[] s_arr24 = new int[] { 3, 1, 2 }; private static readonly int[] s_arr25 = new int[] { 2, 1 }; private static readonly int[] s_arr26 = new int[] { 0, 1 }; private static readonly int[] s_arr27 = new int[] { 1 }; private static readonly int[] s_arr28 = new int[] { }; #endregion [Fact] public static void SortTest() { Driver<RefX1<int>> RefDriver = new Driver<RefX1<int>>(); RefDriver.Sort1(RefDriver.MakeRefX1ArrayInt(s_arr1)); RefDriver.Sort1(RefDriver.MakeRefX1ArrayInt(s_arr2)); RefDriver.Sort1(RefDriver.MakeRefX1ArrayInt(s_arr3)); RefDriver.Sort1(RefDriver.MakeRefX1ArrayInt(s_arr4)); RefDriver.Sort1(RefDriver.MakeRefX1ArrayInt(s_arr5)); RefDriver.Sort1(RefDriver.MakeRefX1ArrayInt(s_arr6)); RefDriver.Sort1(RefDriver.MakeRefX1ArrayInt(s_arr7)); RefDriver.Sort1(RefDriver.MakeRefX1ArrayInt(s_arr8)); RefDriver.Sort1(RefDriver.MakeRefX1ArrayInt(s_arr9)); RefDriver.Sort1(RefDriver.MakeRefX1ArrayInt(s_arr10)); RefDriver.Sort1(RefDriver.MakeRefX1ArrayInt(s_arr11)); RefDriver.Sort1(RefDriver.MakeRefX1ArrayInt(s_arr12)); RefDriver.Sort1(RefDriver.MakeRefX1ArrayInt(s_arr13)); RefDriver.Sort1(RefDriver.MakeRefX1ArrayInt(s_arr14)); RefDriver.Sort1(RefDriver.MakeRefX1ArrayInt(s_arr15)); RefDriver.Sort1(RefDriver.MakeRefX1ArrayInt(s_arr16)); RefDriver.Sort1(RefDriver.MakeRefX1ArrayInt(s_arr17)); RefDriver.Sort1(RefDriver.MakeRefX1ArrayInt(s_arr18)); RefDriver.Sort1(RefDriver.MakeRefX1ArrayInt(s_arr19)); RefDriver.Sort1(RefDriver.MakeRefX1ArrayInt(s_arr20)); RefDriver.Sort1(RefDriver.MakeRefX1ArrayInt(s_arr21)); RefDriver.Sort1(RefDriver.MakeRefX1ArrayInt(s_arr22)); RefDriver.Sort1(RefDriver.MakeRefX1ArrayInt(s_arr23)); RefDriver.Sort1(RefDriver.MakeRefX1ArrayInt(s_arr24)); RefDriver.Sort1(RefDriver.MakeRefX1ArrayInt(s_arr25)); RefDriver.Sort1(RefDriver.MakeRefX1ArrayInt(s_arr26)); RefDriver.Sort1(RefDriver.MakeRefX1ArrayInt(s_arr27)); RefDriver.Sort1(RefDriver.MakeRefX1ArrayInt(s_arr28)); Driver<ValX1<int>> ValDriver = new Driver<ValX1<int>>(); ValDriver.Sort1(ValDriver.MakeValX1ArrayInt(s_arr1)); ValDriver.Sort1(ValDriver.MakeValX1ArrayInt(s_arr2)); ValDriver.Sort1(ValDriver.MakeValX1ArrayInt(s_arr3)); ValDriver.Sort1(ValDriver.MakeValX1ArrayInt(s_arr4)); ValDriver.Sort1(ValDriver.MakeValX1ArrayInt(s_arr5)); ValDriver.Sort1(ValDriver.MakeValX1ArrayInt(s_arr6)); ValDriver.Sort1(ValDriver.MakeValX1ArrayInt(s_arr7)); ValDriver.Sort1(ValDriver.MakeValX1ArrayInt(s_arr8)); ValDriver.Sort1(ValDriver.MakeValX1ArrayInt(s_arr9)); ValDriver.Sort1(ValDriver.MakeValX1ArrayInt(s_arr10)); ValDriver.Sort1(ValDriver.MakeValX1ArrayInt(s_arr11)); ValDriver.Sort1(ValDriver.MakeValX1ArrayInt(s_arr12)); ValDriver.Sort1(ValDriver.MakeValX1ArrayInt(s_arr13)); ValDriver.Sort1(ValDriver.MakeValX1ArrayInt(s_arr14)); ValDriver.Sort1(ValDriver.MakeValX1ArrayInt(s_arr15)); ValDriver.Sort1(ValDriver.MakeValX1ArrayInt(s_arr16)); ValDriver.Sort1(ValDriver.MakeValX1ArrayInt(s_arr17)); ValDriver.Sort1(ValDriver.MakeValX1ArrayInt(s_arr18)); ValDriver.Sort1(ValDriver.MakeValX1ArrayInt(s_arr19)); ValDriver.Sort1(ValDriver.MakeValX1ArrayInt(s_arr20)); ValDriver.Sort1(ValDriver.MakeValX1ArrayInt(s_arr21)); ValDriver.Sort1(ValDriver.MakeValX1ArrayInt(s_arr22)); ValDriver.Sort1(ValDriver.MakeValX1ArrayInt(s_arr23)); ValDriver.Sort1(ValDriver.MakeValX1ArrayInt(s_arr24)); ValDriver.Sort1(ValDriver.MakeValX1ArrayInt(s_arr25)); ValDriver.Sort1(ValDriver.MakeValX1ArrayInt(s_arr26)); ValDriver.Sort1(ValDriver.MakeValX1ArrayInt(s_arr27)); ValDriver.Sort1(ValDriver.MakeValX1ArrayInt(s_arr28)); } [Fact] public static void ComparerReturns0YieldsStableSort() { var originalList = new List<int>(); for (int i = 0; i < 10; i++) { originalList.Add(i); } var sortedList = new List<int>(originalList); sortedList.Sort(new Comparison<int>((a, b) => 0)); Assert.Equal(originalList.Count, sortedList.Count); for (int i = 0; i < originalList.Count; i++) { Assert.Equal(originalList[i], sortedList[i]); } } [Fact] public static void SortIComparer_Tests() { Driver2<RefX1_IC<int>> RefDriver = new Driver2<RefX1_IC<int>>(); RefDriver.SortIComparer(RefDriver.MakeRefX1ArrayInt(s_arr1)); RefDriver.SortIComparer(RefDriver.MakeRefX1ArrayInt(s_arr2)); RefDriver.SortIComparer(RefDriver.MakeRefX1ArrayInt(s_arr3)); RefDriver.SortIComparer(RefDriver.MakeRefX1ArrayInt(s_arr4)); RefDriver.SortIComparer(RefDriver.MakeRefX1ArrayInt(s_arr5)); RefDriver.SortIComparer(RefDriver.MakeRefX1ArrayInt(s_arr6)); RefDriver.SortIComparer(RefDriver.MakeRefX1ArrayInt(s_arr7)); RefDriver.SortIComparer(RefDriver.MakeRefX1ArrayInt(s_arr8)); RefDriver.SortIComparer(RefDriver.MakeRefX1ArrayInt(s_arr9)); RefDriver.SortIComparer(RefDriver.MakeRefX1ArrayInt(s_arr10)); RefDriver.SortIComparer(RefDriver.MakeRefX1ArrayInt(s_arr11)); RefDriver.SortIComparer(RefDriver.MakeRefX1ArrayInt(s_arr12)); RefDriver.SortIComparer(RefDriver.MakeRefX1ArrayInt(s_arr13)); RefDriver.SortIComparer(RefDriver.MakeRefX1ArrayInt(s_arr14)); RefDriver.SortIComparer(RefDriver.MakeRefX1ArrayInt(s_arr15)); RefDriver.SortIComparer(RefDriver.MakeRefX1ArrayInt(s_arr16)); RefDriver.SortIComparer(RefDriver.MakeRefX1ArrayInt(s_arr17)); RefDriver.SortIComparer(RefDriver.MakeRefX1ArrayInt(s_arr18)); RefDriver.SortIComparer(RefDriver.MakeRefX1ArrayInt(s_arr19)); RefDriver.SortIComparer(RefDriver.MakeRefX1ArrayInt(s_arr20)); RefDriver.SortIComparer(RefDriver.MakeRefX1ArrayInt(s_arr21)); RefDriver.SortIComparer(RefDriver.MakeRefX1ArrayInt(s_arr22)); RefDriver.SortIComparer(RefDriver.MakeRefX1ArrayInt(s_arr23)); RefDriver.SortIComparer(RefDriver.MakeRefX1ArrayInt(s_arr24)); RefDriver.SortIComparer(RefDriver.MakeRefX1ArrayInt(s_arr25)); RefDriver.SortIComparer(RefDriver.MakeRefX1ArrayInt(s_arr26)); RefDriver.SortIComparer(RefDriver.MakeRefX1ArrayInt(s_arr27)); RefDriver.SortIComparer(RefDriver.MakeRefX1ArrayInt(s_arr28)); Driver2<ValX1_IC<int>> ValDriver = new Driver2<ValX1_IC<int>>(); ValDriver.SortIComparer(ValDriver.MakeValX1ArrayInt(s_arr1)); ValDriver.SortIComparer(ValDriver.MakeValX1ArrayInt(s_arr2)); ValDriver.SortIComparer(ValDriver.MakeValX1ArrayInt(s_arr3)); ValDriver.SortIComparer(ValDriver.MakeValX1ArrayInt(s_arr4)); ValDriver.SortIComparer(ValDriver.MakeValX1ArrayInt(s_arr5)); ValDriver.SortIComparer(ValDriver.MakeValX1ArrayInt(s_arr6)); ValDriver.SortIComparer(ValDriver.MakeValX1ArrayInt(s_arr7)); ValDriver.SortIComparer(ValDriver.MakeValX1ArrayInt(s_arr8)); ValDriver.SortIComparer(ValDriver.MakeValX1ArrayInt(s_arr9)); ValDriver.SortIComparer(ValDriver.MakeValX1ArrayInt(s_arr10)); ValDriver.SortIComparer(ValDriver.MakeValX1ArrayInt(s_arr11)); ValDriver.SortIComparer(ValDriver.MakeValX1ArrayInt(s_arr12)); ValDriver.SortIComparer(ValDriver.MakeValX1ArrayInt(s_arr13)); ValDriver.SortIComparer(ValDriver.MakeValX1ArrayInt(s_arr14)); ValDriver.SortIComparer(ValDriver.MakeValX1ArrayInt(s_arr15)); ValDriver.SortIComparer(ValDriver.MakeValX1ArrayInt(s_arr16)); ValDriver.SortIComparer(ValDriver.MakeValX1ArrayInt(s_arr17)); ValDriver.SortIComparer(ValDriver.MakeValX1ArrayInt(s_arr18)); ValDriver.SortIComparer(ValDriver.MakeValX1ArrayInt(s_arr19)); ValDriver.SortIComparer(ValDriver.MakeValX1ArrayInt(s_arr20)); ValDriver.SortIComparer(ValDriver.MakeValX1ArrayInt(s_arr21)); ValDriver.SortIComparer(ValDriver.MakeValX1ArrayInt(s_arr22)); ValDriver.SortIComparer(ValDriver.MakeValX1ArrayInt(s_arr23)); ValDriver.SortIComparer(ValDriver.MakeValX1ArrayInt(s_arr24)); ValDriver.SortIComparer(ValDriver.MakeValX1ArrayInt(s_arr25)); ValDriver.SortIComparer(ValDriver.MakeValX1ArrayInt(s_arr26)); ValDriver.SortIComparer(ValDriver.MakeValX1ArrayInt(s_arr27)); ValDriver.SortIComparer(ValDriver.MakeValX1ArrayInt(s_arr28)); } [Fact] public static void SortIComparer_Tests_Negative() { int[] arr21 = new int[] { 1, 2, 3 }; Driver2<RefX1_IC<int>> RefDriver = new Driver2<RefX1_IC<int>>(); RefDriver.SortIComparerValidations(RefDriver.MakeRefX1ArrayInt(arr21)); Driver2<ValX1_IC<int>> ValDriver = new Driver2<ValX1_IC<int>>(); ValDriver.SortIComparerValidations(ValDriver.MakeValX1ArrayInt(arr21)); } [Fact] public static void SortIntIntIComparer_Tests() { Driver2<RefX1_IC<int>> RefDriver = new Driver2<RefX1_IC<int>>(); RefDriver.SortIntIntIComparer(RefDriver.MakeRefX1ArrayInt(s_arr1), 0, 10); RefDriver.SortIntIntIComparer(RefDriver.MakeRefX1ArrayInt(s_arr1), 1, 9); RefDriver.SortIntIntIComparer(RefDriver.MakeRefX1ArrayInt(s_arr1), 9, 1); RefDriver.SortIntIntIComparer(RefDriver.MakeRefX1ArrayInt(s_arr1), 5, 5); RefDriver.SortIntIntIComparer(RefDriver.MakeRefX1ArrayInt(s_arr1), 0, 5); RefDriver.SortIntIntIComparer(RefDriver.MakeRefX1ArrayInt(s_arr1), 3, 3); Driver2<ValX1_IC<int>> ValDriver = new Driver2<ValX1_IC<int>>(); ValDriver.SortIntIntIComparer(ValDriver.MakeValX1ArrayInt(s_arr1), 0, 10); ValDriver.SortIntIntIComparer(ValDriver.MakeValX1ArrayInt(s_arr1), 1, 9); ValDriver.SortIntIntIComparer(ValDriver.MakeValX1ArrayInt(s_arr1), 9, 1); ValDriver.SortIntIntIComparer(ValDriver.MakeValX1ArrayInt(s_arr1), 5, 5); ValDriver.SortIntIntIComparer(ValDriver.MakeValX1ArrayInt(s_arr1), 0, 5); ValDriver.SortIntIntIComparer(ValDriver.MakeValX1ArrayInt(s_arr1), 3, 3); } [Fact] public static void SortIntIntIComparer_Tests_Negative() { Driver2<RefX1_IC<int>> RefDriver = new Driver2<RefX1_IC<int>>(); Driver2<ValX1_IC<int>> ValDriver = new Driver2<ValX1_IC<int>>(); RefDriver.SortIntIntIComparerValidations(RefDriver.MakeRefX1ArrayInt(s_arr1)); ValDriver.SortIntIntIComparerValidations(ValDriver.MakeValX1ArrayInt(s_arr1)); } [Fact] public static void SortComparison_Tests() { Driver<int> intDriver = new Driver<int>(); Driver<string> stringDriver = new Driver<string>(); int[] intArray; string[] stringArray; int arraySize = 16; intArray = new int[arraySize]; stringArray = new string[arraySize]; for (int i = 0; i < arraySize; ++i) { intArray[i] = i + 1; stringArray[i] = (i + 1).ToString(); } intDriver.VerifyVanilla(new int[0]); intDriver.VerifyVanilla(new int[] { 1 }); intDriver.VerifyVanilla(intArray); intDriver.CallSortAndVerify( new int[] { 1, 0, 5, 4, 2 }, new int[] { 0, 1, 2, 4, 5 }, (int x, int y) => { return x - y; }); stringDriver.VerifyVanilla(new string[0]); stringDriver.VerifyVanilla(new string[] { "1" }); stringDriver.VerifyVanilla(stringArray); stringDriver.CallSortAndVerify( new string[] { "1", "", "12345", "1234", "12" }, new string[] { "", "1", "12", "1234", "12345" }, (string x, string y) => { return x.Length - y.Length; }); } [Fact] public static void SortComparison_Tests_Negative() { Driver<int> intDriver = new Driver<int>(); Driver<string> stringDriver = new Driver<string>(); int[] intArray; string[] stringArray; int arraySize = 16; intArray = new int[arraySize]; stringArray = new string[arraySize]; for (int i = 0; i < arraySize; ++i) { intArray[i] = i + 1; stringArray[i] = (i + 1).ToString(); } intDriver.VerifyExceptions(intArray); stringDriver.VerifyExceptions(stringArray); } } #region Helper Classes /// <summary> /// Helper class that implements ICollection. /// </summary> public class TestCollection<T> : ICollection<T> { /// <summary> /// Expose the Items in Array to give more test flexibility... /// </summary> public readonly T[] m_items; public TestCollection(T[] items) { m_items = items; } public void CopyTo(T[] array, int index) { Array.Copy(m_items, 0, array, index, m_items.Length); } public int Count { get { if (m_items == null) return 0; else return m_items.Length; } } public Object SyncRoot { get { return this; } } public bool IsSynchronized { get { return false; } } public IEnumerator<T> GetEnumerator() { return new TestCollectionEnumerator<T>(this); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new TestCollectionEnumerator<T>(this); } private class TestCollectionEnumerator<T1> : IEnumerator<T1> { private TestCollection<T1> _col; private int _index; public void Dispose() { } public TestCollectionEnumerator(TestCollection<T1> col) { _col = col; _index = -1; } public bool MoveNext() { return (++_index < _col.m_items.Length); } public T1 Current { get { return _col.m_items[_index]; } } Object System.Collections.IEnumerator.Current { get { return _col.m_items[_index]; } } public void Reset() { _index = -1; } } #region Non Implemented methods public void Add(T item) { throw new NotSupportedException(); } public void Clear() { throw new NotSupportedException(); } public bool Contains(T item) { throw new NotSupportedException(); } public bool Remove(T item) { throw new NotSupportedException(); } public bool IsReadOnly { get { throw new NotSupportedException(); } } #endregion } public class RefX1<T> : IComparable<RefX1<T>> where T : IComparable { private T _val; public T Val { get { return _val; } set { _val = value; } } public RefX1(T t) { _val = t; } public int CompareTo(RefX1<T> obj) { if (null == obj) return 1; if (null == _val) if (null == obj.Val) return 0; else return -1; return _val.CompareTo(obj.Val); } public override bool Equals(object obj) { if (obj is RefX1<T>) { RefX1<T> v = (RefX1<T>)obj; return (CompareTo(v) == 0); } return false; } public override int GetHashCode() { return base.GetHashCode(); } public bool Equals(RefX1<T> x) { return 0 == CompareTo(x); } } public struct ValX1<T> : IComparable<ValX1<T>> where T : IComparable { private T _val; public T Val { get { return _val; } set { _val = value; } } public ValX1(T t) { _val = t; } public int CompareTo(ValX1<T> obj) { if (Object.ReferenceEquals(_val, obj._val)) return 0; if (null == _val) return -1; return _val.CompareTo(obj.Val); } public override bool Equals(object obj) { if (obj is ValX1<T>) { ValX1<T> v = (ValX1<T>)obj; return (CompareTo(v) == 0); } return false; } public override int GetHashCode() { return ((object)this).GetHashCode(); } public bool Equals(ValX1<T> x) { return 0 == CompareTo(x); } } public interface IComparableValue { IComparable Val { get; set; } int CompareTo(IComparableValue obj); } public class RefX1_IC<T> : IComparableValue where T : IComparable { private T _val; public System.IComparable Val { get { return _val; } set { _val = (T)(object)value; } } public RefX1_IC(T t) { _val = t; } public int CompareTo(IComparableValue obj) { if (null == (object)obj) return 1; if (null == (object)_val) if (null == (object)obj.Val) return 0; else return -1; return _val.CompareTo(obj.Val); } } public struct ValX1_IC<T> : IComparableValue where T : IComparable { private T _val; public System.IComparable Val { get { return _val; } set { _val = (T)(object)value; } } public ValX1_IC(T t) { _val = t; } public int CompareTo(IComparableValue obj) { return _val.CompareTo(obj.Val); } } public class ValueComparer<T> : IComparer<T> where T : IComparableValue { public int Compare(T x, T y) { if (null == (object)x) if (null == (object)y) return 0; else return -1; if (null == (object)y) return 1; if (null == (object)x.Val) if (null == (object)y.Val) return 0; else return -1; return x.Val.CompareTo(y.Val); } public bool Equals(T x, T y) { return 0 == Compare(x, y); } public int GetHashCode(T x) { return x.GetHashCode(); } } #endregion }
using Lucene.Net.Support; using System; using System.Diagnostics; using System.Reflection; using CompoundFileDirectory = Lucene.Net.Store.CompoundFileDirectory; namespace Lucene.Net.Codecs.Lucene3x { /* * 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 CorruptIndexException = Lucene.Net.Index.CorruptIndexException; using Directory = Lucene.Net.Store.Directory; using FieldInfo = Lucene.Net.Index.FieldInfo; using FieldInfos = Lucene.Net.Index.FieldInfos; using IndexFileNames = Lucene.Net.Index.IndexFileNames; using IndexFormatTooNewException = Lucene.Net.Index.IndexFormatTooNewException; using IndexFormatTooOldException = Lucene.Net.Index.IndexFormatTooOldException; using IndexInput = Lucene.Net.Store.IndexInput; using IOContext = Lucene.Net.Store.IOContext; using IOUtils = Lucene.Net.Util.IOUtils; using SegmentInfo = Lucene.Net.Index.SegmentInfo; using StoredFieldVisitor = Lucene.Net.Index.StoredFieldVisitor; /// <summary> /// Class responsible for access to stored document fields. /// <para/> /// It uses &lt;segment&gt;.fdt and &lt;segment&gt;.fdx; files. /// </summary> [Obsolete("Only for reading existing 3.x indexes")] internal sealed class Lucene3xStoredFieldsReader : StoredFieldsReader, IDisposable #if FEATURE_CLONEABLE , System.ICloneable #endif { private const int FORMAT_SIZE = 4; /// <summary> /// Extension of stored fields file. </summary> public const string FIELDS_EXTENSION = "fdt"; /// <summary> /// Extension of stored fields index file. </summary> public const string FIELDS_INDEX_EXTENSION = "fdx"; // Lucene 3.0: Removal of compressed fields internal const int FORMAT_LUCENE_3_0_NO_COMPRESSED_FIELDS = 2; // Lucene 3.2: NumericFields are stored in binary format internal const int FORMAT_LUCENE_3_2_NUMERIC_FIELDS = 3; // NOTE: if you introduce a new format, make it 1 higher // than the current one, and always change this if you // switch to a new format! public const int FORMAT_CURRENT = FORMAT_LUCENE_3_2_NUMERIC_FIELDS; // when removing support for old versions, leave the last supported version here internal const int FORMAT_MINIMUM = FORMAT_LUCENE_3_0_NO_COMPRESSED_FIELDS; // NOTE: bit 0 is free here! You can steal it! public static readonly int FIELD_IS_BINARY = 1 << 1; // the old bit 1 << 2 was compressed, is now left out private const int _NUMERIC_BIT_SHIFT = 3; internal static readonly int FIELD_IS_NUMERIC_MASK = 0x07 << _NUMERIC_BIT_SHIFT; public const int FIELD_IS_NUMERIC_INT = 1 << _NUMERIC_BIT_SHIFT; public const int FIELD_IS_NUMERIC_LONG = 2 << _NUMERIC_BIT_SHIFT; public const int FIELD_IS_NUMERIC_FLOAT = 3 << _NUMERIC_BIT_SHIFT; public const int FIELD_IS_NUMERIC_DOUBLE = 4 << _NUMERIC_BIT_SHIFT; private readonly FieldInfos fieldInfos; private readonly IndexInput fieldsStream; private readonly IndexInput indexStream; private int numTotalDocs; private int size; private bool closed; private readonly int format; // The docID offset where our docs begin in the index // file. this will be 0 if we have our own private file. private int docStoreOffset; // when we are inside a compound share doc store (CFX), // (lucene 3.0 indexes only), we privately open our own fd. private readonly CompoundFileDirectory storeCFSReader; /// <summary> /// Returns a cloned FieldsReader that shares open /// IndexInputs with the original one. It is the caller's /// job not to close the original FieldsReader until all /// clones are called (eg, currently SegmentReader manages /// this logic). /// </summary> public override object Clone() { EnsureOpen(); return new Lucene3xStoredFieldsReader(fieldInfos, numTotalDocs, size, format, docStoreOffset, (IndexInput)fieldsStream.Clone(), (IndexInput)indexStream.Clone()); } /// <summary> /// Verifies that the code version which wrote the segment is supported. </summary> public static void CheckCodeVersion(Directory dir, string segment) { string indexStreamFN = IndexFileNames.SegmentFileName(segment, "", FIELDS_INDEX_EXTENSION); IndexInput idxStream = dir.OpenInput(indexStreamFN, IOContext.DEFAULT); try { int format = idxStream.ReadInt32(); if (format < FORMAT_MINIMUM) { throw new IndexFormatTooOldException(idxStream, format, FORMAT_MINIMUM, FORMAT_CURRENT); } if (format > FORMAT_CURRENT) { throw new IndexFormatTooNewException(idxStream, format, FORMAT_MINIMUM, FORMAT_CURRENT); } } finally { idxStream.Dispose(); } } // Used only by clone private Lucene3xStoredFieldsReader(FieldInfos fieldInfos, int numTotalDocs, int size, int format, int docStoreOffset, IndexInput fieldsStream, IndexInput indexStream) { this.fieldInfos = fieldInfos; this.numTotalDocs = numTotalDocs; this.size = size; this.format = format; this.docStoreOffset = docStoreOffset; this.fieldsStream = fieldsStream; this.indexStream = indexStream; this.storeCFSReader = null; } public Lucene3xStoredFieldsReader(Directory d, SegmentInfo si, FieldInfos fn, IOContext context) { string segment = Lucene3xSegmentInfoFormat.GetDocStoreSegment(si); int docStoreOffset = Lucene3xSegmentInfoFormat.GetDocStoreOffset(si); int size = si.DocCount; bool success = false; fieldInfos = fn; try { if (docStoreOffset != -1 && Lucene3xSegmentInfoFormat.GetDocStoreIsCompoundFile(si)) { d = storeCFSReader = new CompoundFileDirectory(si.Dir, IndexFileNames.SegmentFileName(segment, "", Lucene3xCodec.COMPOUND_FILE_STORE_EXTENSION), context, false); } else { storeCFSReader = null; } fieldsStream = d.OpenInput(IndexFileNames.SegmentFileName(segment, "", FIELDS_EXTENSION), context); string indexStreamFN = IndexFileNames.SegmentFileName(segment, "", FIELDS_INDEX_EXTENSION); indexStream = d.OpenInput(indexStreamFN, context); format = indexStream.ReadInt32(); if (format < FORMAT_MINIMUM) { throw new IndexFormatTooOldException(indexStream, format, FORMAT_MINIMUM, FORMAT_CURRENT); } if (format > FORMAT_CURRENT) { throw new IndexFormatTooNewException(indexStream, format, FORMAT_MINIMUM, FORMAT_CURRENT); } long indexSize = indexStream.Length - FORMAT_SIZE; if (docStoreOffset != -1) { // We read only a slice out of this shared fields file this.docStoreOffset = docStoreOffset; this.size = size; // Verify the file is long enough to hold all of our // docs Debug.Assert(((int)(indexSize / 8)) >= size + this.docStoreOffset, "indexSize=" + indexSize + " size=" + size + " docStoreOffset=" + docStoreOffset); } else { this.docStoreOffset = 0; this.size = (int)(indexSize >> 3); // Verify two sources of "maxDoc" agree: if (this.size != si.DocCount) { throw new CorruptIndexException("doc counts differ for segment " + segment + ": fieldsReader shows " + this.size + " but segmentInfo shows " + si.DocCount); } } numTotalDocs = (int)(indexSize >> 3); success = true; } finally { // With lock-less commits, it's entirely possible (and // fine) to hit a FileNotFound exception above. In // this case, we want to explicitly close any subset // of things that were opened so that we don't have to // wait for a GC to do so. if (!success) { try { Dispose(); } // keep our original exception #pragma warning disable 168 catch (Exception t) #pragma warning restore 168 { } } } } /// <exception cref="ObjectDisposedException"> If this FieldsReader is disposed. </exception> private void EnsureOpen() { if (closed) { throw new ObjectDisposedException(this.GetType().FullName, "this FieldsReader is closed"); } } /// <summary> /// Closes the underlying <see cref="Lucene.Net.Store.IndexInput"/> streams. /// This means that the Fields values will not be accessible. /// </summary> /// <exception cref="System.IO.IOException"> If there is a low-level I/O error. </exception> protected override void Dispose(bool disposing) { if (disposing) { if (!closed) { IOUtils.Dispose(fieldsStream, indexStream, storeCFSReader); closed = true; } } } private void SeekIndex(int docID) { indexStream.Seek(FORMAT_SIZE + (docID + docStoreOffset) * 8L); } public override sealed void VisitDocument(int n, StoredFieldVisitor visitor) { SeekIndex(n); fieldsStream.Seek(indexStream.ReadInt64()); int numFields = fieldsStream.ReadVInt32(); for (int fieldIDX = 0; fieldIDX < numFields; fieldIDX++) { int fieldNumber = fieldsStream.ReadVInt32(); FieldInfo fieldInfo = fieldInfos.FieldInfo(fieldNumber); int bits = fieldsStream.ReadByte() & 0xFF; Debug.Assert(bits <= (FIELD_IS_NUMERIC_MASK | FIELD_IS_BINARY), "bits=" + bits.ToString("x")); switch (visitor.NeedsField(fieldInfo)) { case StoredFieldVisitor.Status.YES: ReadField(visitor, fieldInfo, bits); break; case StoredFieldVisitor.Status.NO: SkipField(bits); break; case StoredFieldVisitor.Status.STOP: return; } } } private void ReadField(StoredFieldVisitor visitor, FieldInfo info, int bits) { int numeric = bits & FIELD_IS_NUMERIC_MASK; if (numeric != 0) { switch (numeric) { case FIELD_IS_NUMERIC_INT: visitor.Int32Field(info, fieldsStream.ReadInt32()); return; case FIELD_IS_NUMERIC_LONG: visitor.Int64Field(info, fieldsStream.ReadInt64()); return; case FIELD_IS_NUMERIC_FLOAT: visitor.SingleField(info, Number.Int32BitsToSingle(fieldsStream.ReadInt32())); return; case FIELD_IS_NUMERIC_DOUBLE: visitor.DoubleField(info, BitConverter.Int64BitsToDouble(fieldsStream.ReadInt64())); return; default: throw new CorruptIndexException("Invalid numeric type: " + numeric.ToString("x")); } } else { int length = fieldsStream.ReadVInt32(); var bytes = new byte[length]; fieldsStream.ReadBytes(bytes, 0, length); if ((bits & FIELD_IS_BINARY) != 0) { visitor.BinaryField(info, bytes); } else { visitor.StringField(info, IOUtils.CHARSET_UTF_8.GetString(bytes)); } } } private void SkipField(int bits) { int numeric = bits & FIELD_IS_NUMERIC_MASK; if (numeric != 0) { switch (numeric) { case FIELD_IS_NUMERIC_INT: case FIELD_IS_NUMERIC_FLOAT: fieldsStream.ReadInt32(); return; case FIELD_IS_NUMERIC_LONG: case FIELD_IS_NUMERIC_DOUBLE: fieldsStream.ReadInt64(); return; default: throw new CorruptIndexException("Invalid numeric type: " + numeric.ToString("x")); } } else { int length = fieldsStream.ReadVInt32(); fieldsStream.Seek(fieldsStream.GetFilePointer() + length); } } public override long RamBytesUsed() { // everything is stored on disk return 0; } public override void CheckIntegrity() { } } }
namespace ModuleZeroSampleProject.Migrations { using System; using System.Collections.Generic; using System.Data.Entity.Infrastructure.Annotations; using System.Data.Entity.Migrations; public partial class Upgraded_To_AbpZero_0_5_13 : DbMigration { public override void Up() { CreateTable( "dbo.AbpAuditLogs", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(), ServiceName = c.String(maxLength: 256), MethodName = c.String(maxLength: 256), Parameters = c.String(maxLength: 1024), ExecutionTime = c.DateTime(nullable: false), ExecutionDuration = c.Int(nullable: false), ClientIpAddress = c.String(maxLength: 64), ClientName = c.String(maxLength: 128), BrowserInfo = c.String(maxLength: 256), Exception = c.String(maxLength: 2000), }) .PrimaryKey(t => t.Id); AlterTableAnnotations( "dbo.AbpUsers", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), Name = c.String(nullable: false, maxLength: 32), Surname = c.String(nullable: false, maxLength: 32), UserName = c.String(nullable: false, maxLength: 32), Password = c.String(nullable: false, maxLength: 128), EmailAddress = c.String(nullable: false, maxLength: 256), IsEmailConfirmed = c.Boolean(nullable: false), EmailConfirmationCode = c.String(maxLength: 128), PasswordResetCode = c.String(maxLength: 128), LastLoginTime = c.DateTime(), IsActive = c.Boolean(nullable: false), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, AnnotationValues> { { "Abp_SoftDelete", new AnnotationValues(oldValue: "True", newValue: null) }, { "DynamicFilter_User_MayHaveTenant", new AnnotationValues(oldValue: null, newValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition") }, { "DynamicFilter_User_SoftDelete", new AnnotationValues(oldValue: null, newValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition") }, }); AlterTableAnnotations( "dbo.AbpTenants", c => new { Id = c.Int(nullable: false, identity: true), TenancyName = c.String(nullable: false, maxLength: 64), Name = c.String(nullable: false, maxLength: 128), IsActive = c.Boolean(nullable: false), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, AnnotationValues> { { "DynamicFilter_Tenant_SoftDelete", new AnnotationValues(oldValue: null, newValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition") }, }); AlterTableAnnotations( "dbo.AbpRoles", c => new { Id = c.Int(nullable: false, identity: true), TenantId = c.Int(), Name = c.String(nullable: false, maxLength: 32), DisplayName = c.String(nullable: false, maxLength: 64), IsStatic = c.Boolean(nullable: false), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, AnnotationValues> { { "DynamicFilter_Role_MayHaveTenant", new AnnotationValues(oldValue: null, newValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition") }, }); AddColumn("dbo.AbpTenants", "IsDeleted", c => c.Boolean(nullable: false)); AddColumn("dbo.AbpTenants", "DeleterUserId", c => c.Long()); AddColumn("dbo.AbpTenants", "DeletionTime", c => c.DateTime()); AlterColumn("dbo.AbpUsers", "EmailConfirmationCode", c => c.String(maxLength: 128)); AlterColumn("dbo.AbpUsers", "PasswordResetCode", c => c.String(maxLength: 128)); AlterColumn("dbo.AbpTenants", "TenancyName", c => c.String(nullable: false, maxLength: 64)); AlterColumn("dbo.AbpTenants", "Name", c => c.String(nullable: false, maxLength: 128)); CreateIndex("dbo.AbpTenants", "DeleterUserId"); AddForeignKey("dbo.AbpTenants", "DeleterUserId", "dbo.AbpUsers", "Id"); } public override void Down() { DropForeignKey("dbo.AbpTenants", "DeleterUserId", "dbo.AbpUsers"); DropIndex("dbo.AbpTenants", new[] { "DeleterUserId" }); AlterColumn("dbo.AbpTenants", "Name", c => c.String()); AlterColumn("dbo.AbpTenants", "TenancyName", c => c.String()); AlterColumn("dbo.AbpUsers", "PasswordResetCode", c => c.String(maxLength: 32)); AlterColumn("dbo.AbpUsers", "EmailConfirmationCode", c => c.String(maxLength: 16)); DropColumn("dbo.AbpTenants", "DeletionTime"); DropColumn("dbo.AbpTenants", "DeleterUserId"); DropColumn("dbo.AbpTenants", "IsDeleted"); AlterTableAnnotations( "dbo.AbpRoles", c => new { Id = c.Int(nullable: false, identity: true), TenantId = c.Int(), Name = c.String(nullable: false, maxLength: 32), DisplayName = c.String(nullable: false, maxLength: 64), IsStatic = c.Boolean(nullable: false), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, AnnotationValues> { { "DynamicFilter_Role_MayHaveTenant", new AnnotationValues(oldValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition", newValue: null) }, }); AlterTableAnnotations( "dbo.AbpTenants", c => new { Id = c.Int(nullable: false, identity: true), TenancyName = c.String(nullable: false, maxLength: 64), Name = c.String(nullable: false, maxLength: 128), IsActive = c.Boolean(nullable: false), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, AnnotationValues> { { "DynamicFilter_Tenant_SoftDelete", new AnnotationValues(oldValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition", newValue: null) }, }); AlterTableAnnotations( "dbo.AbpUsers", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), Name = c.String(nullable: false, maxLength: 32), Surname = c.String(nullable: false, maxLength: 32), UserName = c.String(nullable: false, maxLength: 32), Password = c.String(nullable: false, maxLength: 128), EmailAddress = c.String(nullable: false, maxLength: 256), IsEmailConfirmed = c.Boolean(nullable: false), EmailConfirmationCode = c.String(maxLength: 128), PasswordResetCode = c.String(maxLength: 128), LastLoginTime = c.DateTime(), IsActive = c.Boolean(nullable: false), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, AnnotationValues> { { "Abp_SoftDelete", new AnnotationValues(oldValue: null, newValue: "True") }, { "DynamicFilter_User_MayHaveTenant", new AnnotationValues(oldValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition", newValue: null) }, { "DynamicFilter_User_SoftDelete", new AnnotationValues(oldValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition", newValue: null) }, }); DropTable("dbo.AbpAuditLogs"); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Threading; using System.Threading.Tasks; using Azure.Core; using Azure.Core.Pipeline; namespace Azure.Communication.CallingServer { /// <summary> /// The Azure Communication Services Server Call Client. /// </summary> public class ServerCall { private readonly ClientDiagnostics _clientDiagnostics; internal ServerCallsRestClient RestClient { get; } /// <summary> /// The server call id. /// </summary> internal virtual string ServerCallId { get; set; } /// <summary>Initializes a new instance of <see cref="ServerCall"/>.</summary> internal ServerCall(string serverCallId, ServerCallsRestClient serverCallRestClient, ClientDiagnostics clientDiagnostics) { ServerCallId = serverCallId; RestClient = serverCallRestClient; _clientDiagnostics = clientDiagnostics; } /// <summary>Initializes a new instance of <see cref="ServerCall"/> for mocking.</summary> protected ServerCall() { ServerCallId = null; _clientDiagnostics = null; RestClient = null; } /// <summary> Play audio in the call. </summary> /// <param name="audioFileUri"> The uri of the audio file. </param> /// <param name="audioFileId">Tne id for the media in the AudioFileUri, using which we cache the media resource. </param> /// <param name="callbackUri">The callback Uri to receive PlayAudio status notifications. </param> /// <param name="operationContext">The operation context. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> public virtual async Task<Response<PlayAudioResult>> PlayAudioAsync(Uri audioFileUri, string audioFileId, Uri callbackUri, string operationContext = null, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(ServerCall)}.{nameof(PlayAudio)}"); scope.Start(); try { // Currently looping media is not supported for out-call scenarios, thus setting it to false. return await RestClient.PlayAudioAsync( serverCallId: ServerCallId, audioFileUri: audioFileUri?.AbsoluteUri, loop: false, audioFileId: audioFileId, callbackUri: callbackUri?.AbsoluteUri, operationContext: operationContext, cancellationToken: cancellationToken ).ConfigureAwait(false); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> Play audio in the call. </summary> /// <param name="audioFileUri"> The uri of the audio file. </param> /// <param name="audioFileId">Tne id for the media in the AudioFileUri, using which we cache the media resource. </param> /// <param name="callbackUri">The callback Uri to receive PlayAudio status notifications. </param> /// <param name="operationContext">The operation context. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> public virtual Response<PlayAudioResult> PlayAudio(Uri audioFileUri, string audioFileId, Uri callbackUri, string operationContext = null, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(ServerCall)}.{nameof(PlayAudio)}"); scope.Start(); try { // Currently looping media is not supported for out-call scenarios, thus setting it to false. return RestClient.PlayAudio( serverCallId: ServerCallId, audioFileUri: audioFileUri?.AbsoluteUri, loop: false, audioFileId: audioFileId, callbackUri: callbackUri?.AbsoluteUri, operationContext: operationContext, cancellationToken: cancellationToken ); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Add participant to the call. /// </summary> /// <param name="participant"> The identity of participant to be added to the call. </param> /// <param name="callbackUri">The callback uri to receive the notification.</param> /// <param name="alternateCallerId">The phone number to use when adding a pstn participant.</param> /// <param name="operationContext">The operation context.</param> /// <param name="cancellationToken">The cancellation token.</param> public virtual Response<AddParticipantResult> AddParticipant(CommunicationIdentifier participant, Uri callbackUri, string alternateCallerId = default, string operationContext = default, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(ServerCall)}.{nameof(AddParticipant)}"); scope.Start(); try { Argument.AssertNotNull(participant, nameof(participant)); return RestClient.AddParticipant( serverCallId: ServerCallId, participant: CommunicationIdentifierSerializer.Serialize(participant), alternateCallerId: string.IsNullOrEmpty(alternateCallerId) ? null : new PhoneNumberIdentifierModel(alternateCallerId), callbackUri: callbackUri?.AbsoluteUri, operationContext: operationContext, cancellationToken: cancellationToken ); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Add participant to the call. /// </summary> /// <param name="participant"> The identity of participant to be added to the call. </param> /// <param name="callbackUri"></param> /// <param name="alternateCallerId">The phone number to use when adding a pstn participant.</param> /// <param name="operationContext">The operation context.</param> /// <param name="cancellationToken">The cancellation token.</param> public virtual async Task<Response<AddParticipantResult>> AddParticipantAsync(CommunicationIdentifier participant, Uri callbackUri, string alternateCallerId = default, string operationContext = default, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(ServerCall)}.{nameof(AddParticipant)}"); scope.Start(); try { Argument.AssertNotNull(participant, nameof(participant)); return await RestClient.AddParticipantAsync( serverCallId: ServerCallId, participant: CommunicationIdentifierSerializer.Serialize(participant), alternateCallerId: string.IsNullOrEmpty(alternateCallerId) ? null : new PhoneNumberIdentifierModel(alternateCallerId), callbackUri: callbackUri?.AbsoluteUri, operationContext: operationContext, cancellationToken: cancellationToken ).ConfigureAwait(false); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Remove participant from the call. /// </summary> /// <param name="participantId">The participant id.</param> /// <param name="cancellationToken">The cancellation token.</param> public virtual Response RemoveParticipant(string participantId, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(ServerCall)}.{nameof(RemoveParticipant)}"); scope.Start(); try { return RestClient.RemoveParticipant( serverCallId: ServerCallId, participantId: participantId, cancellationToken: cancellationToken ); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Remove participant from the call. /// </summary> /// <param name="participantId">The participant id.</param> /// <param name="cancellationToken">The cancellation token.</param> public virtual async Task<Response> RemoveParticipantAsync(string participantId, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(ServerCall)}.{nameof(RemoveParticipant)}"); scope.Start(); try { return await RestClient.RemoveParticipantAsync( serverCallId: ServerCallId, participantId: participantId, cancellationToken: cancellationToken ).ConfigureAwait(false); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Start recording of the call. /// </summary> /// <param name="recordingStateCallbackUri">The uri to send state change callbacks.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <param name="content">content for recording.</param> /// <param name="channel">channel for recording.</param> /// <param name="format">format for recording.</param> public virtual async Task<Response<StartRecordingResult>> StartRecordingAsync(Uri recordingStateCallbackUri, RecordingContent? content = null, RecordingChannel? channel = null, RecordingFormat? format = null, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(ServerCall)}.{nameof(StartRecording)}"); scope.Start(); try { return await RestClient.StartRecordingAsync( serverCallId: ServerCallId, recordingStateCallbackUri: recordingStateCallbackUri.AbsoluteUri, recordingContentType: content, recordingChannelType: channel, recordingFormatType: format, cancellationToken: cancellationToken ).ConfigureAwait(false); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Start recording of the call. /// </summary> /// <param name="recordingStateCallbackUri">The uri to send state change callbacks.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <param name="content">content for recording.</param> /// <param name="channel">channel for recording.</param> /// <param name="format">format for recording.</param> public virtual Response<StartRecordingResult> StartRecording(Uri recordingStateCallbackUri, RecordingContent? content = null, RecordingChannel? channel = null, RecordingFormat? format = null, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(ServerCall)}.{nameof(StartRecording)}"); scope.Start(); try { return RestClient.StartRecording( serverCallId: ServerCallId, recordingStateCallbackUri: recordingStateCallbackUri.AbsoluteUri, recordingContentType: content, recordingChannelType: channel, recordingFormatType: format, cancellationToken: cancellationToken ); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Get the current recording state by recording id. /// </summary> /// <param name="recordingId">The recording id to get the state of.</param> /// <param name="cancellationToken">The cancellation token.</param> public virtual async Task<Response<CallRecordingProperties>> GetRecordingStateAsync(string recordingId, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(ServerCall)}.{nameof(GetRecordingState)}"); scope.Start(); try { return await RestClient.GetRecordingPropertiesAsync( serverCallId: ServerCallId, recordingId: recordingId, cancellationToken: cancellationToken ).ConfigureAwait(false); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Get the current recording state by recording id. /// </summary> /// <param name="recordingId">The recording id to get the state of.</param> /// <param name="cancellationToken">The cancellation token.</param> public virtual Response<CallRecordingProperties> GetRecordingState(string recordingId, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(ServerCall)}.{nameof(GetRecordingState)}"); scope.Start(); try { return RestClient.GetRecordingProperties( serverCallId: ServerCallId, recordingId: recordingId, cancellationToken: cancellationToken ); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Stop recording of the call. /// </summary> /// <param name="recordingId">The recording id to stop.</param> /// <param name="cancellationToken">The cancellation token.</param> public virtual async Task<Response> StopRecordingAsync(string recordingId, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(ServerCall)}.{nameof(StopRecording)}"); scope.Start(); try { return await RestClient.StopRecordingAsync( serverCallId: ServerCallId, recordingId: recordingId, cancellationToken: cancellationToken ).ConfigureAwait(false); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Stop recording of the call. /// </summary> /// <param name="recordingId">The recording id to stop.</param> /// <param name="cancellationToken">The cancellation token.</param> public virtual Response StopRecording(string recordingId, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(ServerCall)}.{nameof(StopRecording)}"); scope.Start(); try { return RestClient.StopRecording( serverCallId: ServerCallId, recordingId: recordingId, cancellationToken: cancellationToken ); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Pause recording of the call. /// </summary> /// <param name="recordingId">The recording id to pause.</param> /// <param name="cancellationToken">The cancellation token.</param> public virtual async Task<Response> PauseRecordingAsync(string recordingId, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(ServerCall)}.{nameof(PauseRecording)}"); scope.Start(); try { return await RestClient.PauseRecordingAsync( serverCallId: ServerCallId, recordingId: recordingId, cancellationToken: cancellationToken ).ConfigureAwait(false); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Pause recording of the call. /// </summary> /// <param name="recordingId">The recording id to pause.</param> /// <param name="cancellationToken">The cancellation token.</param> public virtual Response PauseRecording(string recordingId, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(ServerCall)}.{nameof(PauseRecording)}"); scope.Start(); try { return RestClient.PauseRecording( serverCallId: ServerCallId, recordingId: recordingId, cancellationToken: cancellationToken ); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Resume recording of the call. /// </summary> /// <param name="recordingId">The recording id to pause.</param> /// <param name="cancellationToken">The cancellation token.</param> public virtual async Task<Response> ResumeRecordingAsync(string recordingId, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(ServerCall)}.{nameof(ResumeRecording)}"); scope.Start(); try { return await RestClient.ResumeRecordingAsync( serverCallId: ServerCallId, recordingId: recordingId, cancellationToken: cancellationToken ).ConfigureAwait(false); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// resume recording of the call. /// </summary> /// <param name="recordingId">The recording id to resume.</param> /// <param name="cancellationToken">The cancellation token.</param> public virtual Response ResumeRecording(string recordingId, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(ServerCall)}.{nameof(ResumeRecording)}"); scope.Start(); try { return RestClient.ResumeRecording( serverCallId: ServerCallId, recordingId: recordingId, cancellationToken: cancellationToken ); } catch (Exception ex) { scope.Failed(ex); throw; } } } }
using System; using System.IO; using System.Reflection; using Zenject.ReflectionBaking.Mono.Cecil.Cil; using NUnit.Framework; using Zenject.ReflectionBaking.Mono.Cecil.PE; namespace Zenject.ReflectionBaking.Mono.Cecil.Tests { public abstract class BaseTestFixture { protected static void IgnoreOnMono () { if (Platform.OnMono) Assert.Ignore (); } public static string GetResourcePath (string name, Assembly assembly) { return Path.Combine (FindResourcesDirectory (assembly), name); } public static string GetAssemblyResourcePath (string name, Assembly assembly) { return GetResourcePath (Path.Combine ("assemblies", name), assembly); } public static string GetCSharpResourcePath (string name, Assembly assembly) { return GetResourcePath (Path.Combine ("cs", name), assembly); } public static string GetILResourcePath (string name, Assembly assembly) { return GetResourcePath (Path.Combine ("il", name), assembly); } public ModuleDefinition GetResourceModule (string name) { return ModuleDefinition.ReadModule (GetAssemblyResourcePath (name, GetType ().Assembly)); } public ModuleDefinition GetResourceModule (string name, ReaderParameters parameters) { return ModuleDefinition.ReadModule (GetAssemblyResourcePath (name, GetType ().Assembly), parameters); } public ModuleDefinition GetResourceModule (string name, ReadingMode mode) { return ModuleDefinition.ReadModule (GetAssemblyResourcePath (name, GetType ().Assembly), new ReaderParameters (mode)); } internal Image GetResourceImage (string name) { using (var fs = new FileStream (GetAssemblyResourcePath (name, GetType ().Assembly), FileMode.Open, FileAccess.Read)) return ImageReader.ReadImageFrom (fs); } public ModuleDefinition GetCurrentModule () { return ModuleDefinition.ReadModule (GetType ().Module.FullyQualifiedName); } public ModuleDefinition GetCurrentModule (ReaderParameters parameters) { return ModuleDefinition.ReadModule (GetType ().Module.FullyQualifiedName, parameters); } public static string FindResourcesDirectory (Assembly assembly) { var path = Path.GetDirectoryName (new Uri (assembly.CodeBase).LocalPath); while (!Directory.Exists (Path.Combine (path, "Resources"))) { var old = path; path = Path.GetDirectoryName (path); Assert.AreNotEqual (old, path); } return Path.Combine (path, "Resources"); } public static void TestModule (string file, Action<ModuleDefinition> test, bool verify = true, bool readOnly = false, Type symbolReaderProvider = null, Type symbolWriterProvider = null) { Run (new ModuleTestCase (file, test, verify, readOnly, symbolReaderProvider, symbolWriterProvider)); } public static void TestCSharp (string file, Action<ModuleDefinition> test, bool verify = true, bool readOnly = false, Type symbolReaderProvider = null, Type symbolWriterProvider = null) { Run (new CSharpTestCase (file, test, verify, readOnly, symbolReaderProvider, symbolWriterProvider)); } public static void TestIL (string file, Action<ModuleDefinition> test, bool verify = true, bool readOnly = false, Type symbolReaderProvider = null, Type symbolWriterProvider = null) { Run (new ILTestCase (file, test, verify, readOnly, symbolReaderProvider, symbolWriterProvider)); } private static void Run (TestCase testCase) { var runner = new TestRunner (testCase, TestCaseType.ReadDeferred); runner.RunTest (); runner = new TestRunner (testCase, TestCaseType.ReadImmediate); runner.RunTest (); if (testCase.ReadOnly) return; runner = new TestRunner (testCase, TestCaseType.WriteFromDeferred); runner.RunTest(); runner = new TestRunner (testCase, TestCaseType.WriteFromImmediate); runner.RunTest(); } } abstract class TestCase { public readonly bool Verify; public readonly bool ReadOnly; public readonly Type SymbolReaderProvider; public readonly Type SymbolWriterProvider; public readonly Action<ModuleDefinition> Test; public abstract string ModuleLocation { get; } protected Assembly Assembly { get { return Test.Method.Module.Assembly; } } protected TestCase (Action<ModuleDefinition> test, bool verify, bool readOnly, Type symbolReaderProvider, Type symbolWriterProvider) { Test = test; Verify = verify; ReadOnly = readOnly; SymbolReaderProvider = symbolReaderProvider; SymbolWriterProvider = symbolWriterProvider; } } class ModuleTestCase : TestCase { public readonly string Module; public ModuleTestCase (string module, Action<ModuleDefinition> test, bool verify, bool readOnly, Type symbolReaderProvider, Type symbolWriterProvider) : base (test, verify, readOnly, symbolReaderProvider, symbolWriterProvider) { Module = module; } public override string ModuleLocation { get { return BaseTestFixture.GetAssemblyResourcePath (Module, Assembly); } } } class CSharpTestCase : TestCase { public readonly string File; public CSharpTestCase (string file, Action<ModuleDefinition> test, bool verify, bool readOnly, Type symbolReaderProvider, Type symbolWriterProvider) : base (test, verify, readOnly, symbolReaderProvider, symbolWriterProvider) { File = file; } public override string ModuleLocation { get { return CompilationService.CompileResource (BaseTestFixture.GetCSharpResourcePath (File, Assembly)); } } } class ILTestCase : TestCase { public readonly string File; public ILTestCase (string file, Action<ModuleDefinition> test, bool verify, bool readOnly, Type symbolReaderProvider, Type symbolWriterProvider) : base (test, verify, readOnly, symbolReaderProvider, symbolWriterProvider) { File = file; } public override string ModuleLocation { get { return CompilationService.CompileResource (BaseTestFixture.GetILResourcePath (File, Assembly)); ; } } } class TestRunner { readonly TestCase test_case; readonly TestCaseType type; public TestRunner (TestCase testCase, TestCaseType type) { this.test_case = testCase; this.type = type; } ModuleDefinition GetModule () { var location = test_case.ModuleLocation; var directory = Path.GetDirectoryName (location); var resolver = new DefaultAssemblyResolver (); resolver.AddSearchDirectory (directory); var parameters = new ReaderParameters { SymbolReaderProvider = GetSymbolReaderProvider (), AssemblyResolver = resolver, }; switch (type) { case TestCaseType.ReadImmediate: parameters.ReadingMode = ReadingMode.Immediate; return ModuleDefinition.ReadModule (location, parameters); case TestCaseType.ReadDeferred: parameters.ReadingMode = ReadingMode.Deferred; return ModuleDefinition.ReadModule (location, parameters); case TestCaseType.WriteFromImmediate: parameters.ReadingMode = ReadingMode.Immediate; return RoundTrip (location, parameters, "cecil-irt"); case TestCaseType.WriteFromDeferred: parameters.ReadingMode = ReadingMode.Deferred; return RoundTrip (location, parameters, "cecil-drt"); default: return null; } } ISymbolReaderProvider GetSymbolReaderProvider () { if (test_case.SymbolReaderProvider == null) return null; return (ISymbolReaderProvider) Activator.CreateInstance (test_case.SymbolReaderProvider); } ISymbolWriterProvider GetSymbolWriterProvider () { if (test_case.SymbolReaderProvider == null) return null; return (ISymbolWriterProvider) Activator.CreateInstance (test_case.SymbolWriterProvider); } ModuleDefinition RoundTrip (string location, ReaderParameters reader_parameters, string folder) { var module = ModuleDefinition.ReadModule (location, reader_parameters); var rt_folder = Path.Combine (Path.GetTempPath (), folder); if (!Directory.Exists (rt_folder)) Directory.CreateDirectory (rt_folder); var rt_module = Path.Combine (rt_folder, Path.GetFileName (location)); var writer_parameters = new WriterParameters { SymbolWriterProvider = GetSymbolWriterProvider (), }; test_case.Test (module); module.Write (rt_module, writer_parameters); if (test_case.Verify) CompilationService.Verify (rt_module); return ModuleDefinition.ReadModule (rt_module, reader_parameters); } public void RunTest () { var module = GetModule (); if (module == null) return; test_case.Test(module); } } enum TestCaseType { ReadImmediate, ReadDeferred, WriteFromImmediate, WriteFromDeferred, } }
// 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.InteropServices; namespace System.Threading { // // Implementation of ThreadPoolBoundHandle that sits on top of the CLR's ThreadPool and Overlapped infrastructure // /// <summary> /// Represents an I/O handle that is bound to the system thread pool and enables low-level /// components to receive notifications for asynchronous I/O operations. /// </summary> public sealed partial class ThreadPoolBoundHandle : IDisposable { private readonly SafeHandle _handle; private bool _isDisposed; private ThreadPoolBoundHandle(SafeHandle handle) { _handle = handle; } /// <summary> /// Gets the bound operating system handle. /// </summary> /// <value> /// A <see cref="SafeHandle"/> object that holds the bound operating system handle. /// </value> public SafeHandle Handle => _handle; /// <summary> /// Returns a <see cref="ThreadPoolBoundHandle"/> for the specific handle, /// which is bound to the system thread pool. /// </summary> /// <param name="handle"> /// A <see cref="SafeHandle"/> object that holds the operating system handle. The /// handle must have been opened for overlapped I/O on the unmanaged side. /// </param> /// <returns> /// <see cref="ThreadPoolBoundHandle"/> for <paramref name="handle"/>, which /// is bound to the system thread pool. /// </returns> /// <exception cref="ArgumentNullException"> /// <paramref name="handle"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="handle"/> has been disposed. /// <para> /// -or- /// </para> /// <paramref name="handle"/> does not refer to a valid I/O handle. /// <para> /// -or- /// </para> /// <paramref name="handle"/> refers to a handle that has not been opened /// for overlapped I/O. /// <para> /// -or- /// </para> /// <paramref name="handle"/> refers to a handle that has already been bound. /// </exception> /// <remarks> /// This method should be called once per handle. /// <para> /// -or- /// </para> /// <see cref="ThreadPoolBoundHandle"/> does not take ownership of <paramref name="handle"/>, /// it remains the responsibility of the caller to call <see cref="SafeHandle.Dispose()"/>. /// </remarks> public static ThreadPoolBoundHandle BindHandle(SafeHandle handle) { if (handle == null) throw new ArgumentNullException(nameof(handle)); if (handle.IsClosed || handle.IsInvalid) throw new ArgumentException(SR.Argument_InvalidHandle, nameof(handle)); return BindHandleCore(handle); } /// <summary> /// Returns an unmanaged pointer to a <see cref="NativeOverlapped"/> structure, specifying /// a delegate that is invoked when the asynchronous I/O operation is complete, a user-provided /// object providing context, and managed objects that serve as buffers. /// </summary> /// <param name="callback"> /// An <see cref="IOCompletionCallback"/> delegate that represents the callback method /// invoked when the asynchronous I/O operation completes. /// </param> /// <param name="state"> /// A user-provided object that distinguishes this <see cref="NativeOverlapped"/> from other /// <see cref="NativeOverlapped"/> instances. Can be <see langword="null"/>. /// </param> /// <param name="pinData"> /// An object or array of objects representing the input or output buffer for the operation. Each /// object represents a buffer, for example an array of bytes. Can be <see langword="null"/>. /// </param> /// <returns> /// An unmanaged pointer to a <see cref="NativeOverlapped"/> structure. /// </returns> /// <remarks> /// <para> /// The unmanaged pointer returned by this method can be passed to the operating system in /// overlapped I/O operations. The <see cref="NativeOverlapped"/> structure is fixed in /// physical memory until <see cref="FreeNativeOverlapped(NativeOverlapped*)"/> is called. /// </para> /// <para> /// The buffer or buffers specified in <paramref name="pinData"/> must be the same as those passed /// to the unmanaged operating system function that performs the asynchronous I/O. /// </para> /// <note> /// The buffers specified in <paramref name="pinData"/> are pinned for the duration of /// the I/O operation. /// </note> /// </remarks> /// <exception cref="ArgumentNullException"> /// <paramref name="callback"/> is <see langword="null"/>. /// </exception> /// <exception cref="ObjectDisposedException"> /// This method was called after the <see cref="ThreadPoolBoundHandle"/> was disposed. /// </exception> [CLSCompliant(false)] public unsafe NativeOverlapped* AllocateNativeOverlapped(IOCompletionCallback callback, object? state, object? pinData) { if (callback == null) throw new ArgumentNullException(nameof(callback)); EnsureNotDisposed(); ThreadPoolBoundHandleOverlapped overlapped = new ThreadPoolBoundHandleOverlapped(callback, state, pinData, preAllocated: null); overlapped._boundHandle = this; return overlapped._nativeOverlapped; } /// <summary> /// Returns an unmanaged pointer to a <see cref="NativeOverlapped"/> structure, using the callback, /// state, and buffers associated with the specified <see cref="PreAllocatedOverlapped"/> object. /// </summary> /// <param name="preAllocated"> /// A <see cref="PreAllocatedOverlapped"/> object from which to create the NativeOverlapped pointer. /// </param> /// <returns> /// An unmanaged pointer to a <see cref="NativeOverlapped"/> structure. /// </returns> /// <remarks> /// <para> /// The unmanaged pointer returned by this method can be passed to the operating system in /// overlapped I/O operations. The <see cref="NativeOverlapped"/> structure is fixed in /// physical memory until <see cref="FreeNativeOverlapped(NativeOverlapped*)"/> is called. /// </para> /// </remarks> /// <exception cref="ArgumentNullException"> /// <paramref name="preAllocated"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="preAllocated"/> is currently in use for another I/O operation. /// </exception> /// <exception cref="ObjectDisposedException"> /// This method was called after the <see cref="ThreadPoolBoundHandle"/> was disposed, or /// this method was called after <paramref name="preAllocated"/> was disposed. /// </exception> /// <seealso cref="PreAllocatedOverlapped"/> [CLSCompliant(false)] public unsafe NativeOverlapped* AllocateNativeOverlapped(PreAllocatedOverlapped preAllocated) { if (preAllocated == null) throw new ArgumentNullException(nameof(preAllocated)); EnsureNotDisposed(); preAllocated.AddRef(); try { ThreadPoolBoundHandleOverlapped overlapped = preAllocated._overlapped; if (overlapped._boundHandle != null) throw new ArgumentException(SR.Argument_PreAllocatedAlreadyAllocated, nameof(preAllocated)); overlapped._boundHandle = this; return overlapped._nativeOverlapped; } catch { preAllocated.Release(); throw; } } /// <summary> /// Frees the unmanaged memory associated with a <see cref="NativeOverlapped"/> structure /// allocated by the <see cref="AllocateNativeOverlapped"/> method. /// </summary> /// <param name="overlapped"> /// An unmanaged pointer to the <see cref="NativeOverlapped"/> structure to be freed. /// </param> /// <remarks> /// <note type="caution"> /// You must call the <see cref="FreeNativeOverlapped(NativeOverlapped*)"/> method exactly once /// on every <see cref="NativeOverlapped"/> unmanaged pointer allocated using the /// <see cref="AllocateNativeOverlapped"/> method. /// If you do not call the <see cref="FreeNativeOverlapped(NativeOverlapped*)"/> method, you will /// leak memory. If you call the <see cref="FreeNativeOverlapped(NativeOverlapped*)"/> method more /// than once on the same <see cref="NativeOverlapped"/> unmanaged pointer, memory will be corrupted. /// </note> /// </remarks> /// <exception cref="ArgumentNullException"> /// <paramref name="overlapped"/> is <see langword="null"/>. /// </exception> /// <exception cref="ObjectDisposedException"> /// This method was called after the <see cref="ThreadPoolBoundHandle"/> was disposed. /// </exception> [CLSCompliant(false)] public unsafe void FreeNativeOverlapped(NativeOverlapped* overlapped) { if (overlapped == null) throw new ArgumentNullException(nameof(overlapped)); // Note: we explicitly allow FreeNativeOverlapped calls after the ThreadPoolBoundHandle has been Disposed. ThreadPoolBoundHandleOverlapped wrapper = GetOverlappedWrapper(overlapped); if (wrapper._boundHandle != this) throw new ArgumentException(SR.Argument_NativeOverlappedWrongBoundHandle, nameof(overlapped)); if (wrapper._preAllocated != null) wrapper._preAllocated.Release(); else Overlapped.Free(overlapped); } /// <summary> /// Returns the user-provided object specified when the <see cref="NativeOverlapped"/> instance was /// allocated using the <see cref="AllocateNativeOverlapped(IOCompletionCallback, object, object)"/>. /// </summary> /// <param name="overlapped"> /// An unmanaged pointer to the <see cref="NativeOverlapped"/> structure from which to return the /// associated user-provided object. /// </param> /// <returns> /// A user-provided object that distinguishes this <see cref="NativeOverlapped"/> /// from other <see cref="NativeOverlapped"/> instances, otherwise, <see langword="null"/> if one was /// not specified when the instance was allocated using <see cref="AllocateNativeOverlapped"/>. /// </returns> /// <exception cref="ArgumentNullException"> /// <paramref name="overlapped"/> is <see langword="null"/>. /// </exception> [CLSCompliant(false)] public static unsafe object? GetNativeOverlappedState(NativeOverlapped* overlapped) { if (overlapped == null) throw new ArgumentNullException(nameof(overlapped)); ThreadPoolBoundHandleOverlapped wrapper = GetOverlappedWrapper(overlapped); Debug.Assert(wrapper._boundHandle != null); return wrapper._userState; } private static unsafe ThreadPoolBoundHandleOverlapped GetOverlappedWrapper(NativeOverlapped* overlapped) { ThreadPoolBoundHandleOverlapped wrapper; try { wrapper = (ThreadPoolBoundHandleOverlapped)Overlapped.Unpack(overlapped); } catch (NullReferenceException ex) { throw new ArgumentException(SR.Argument_NativeOverlappedAlreadyFree, nameof(overlapped), ex); } return wrapper; } public void Dispose() { // .NET Native's version of ThreadPoolBoundHandle that wraps the Win32 ThreadPool holds onto // native resources so it needs to be disposable. To match the contract, we are also disposable. // We also implement a disposable state to mimic behavior between this implementation and // .NET Native's version (code written against us, will also work against .NET Native's version). _isDisposed = true; } private void EnsureNotDisposed() { if (_isDisposed) throw new ObjectDisposedException(GetType().ToString()); } } }
namespace Raccoon.Input { public struct GamepadCapabilities { #region Public Members public static readonly GamepadCapabilities Empty = new GamepadCapabilities(); public int Id; public bool IsGamepadConnected; public XboxInputLabel.Buttons AvailableButtons; public XboxInputLabel.Triggers AvailableTriggers; public GamepadFeature AvailableFeatures; public GamepadKind Kind; #endregion Public Members #region Constructors public GamepadCapabilities(int gamepadIndex) { if (gamepadIndex < 0 || gamepadIndex >= Input.MaxGamePads) { throw new System.ArgumentException($"Gamepad index '{gamepadIndex}' is out of valid range [0, {Input.MaxGamePads - 1}]"); } Microsoft.Xna.Framework.Input.GamePadCapabilities capabilities = Microsoft.Xna.Framework.Input.GamePad.GetCapabilities((Microsoft.Xna.Framework.PlayerIndex) gamepadIndex); Id = gamepadIndex; IsGamepadConnected = capabilities.IsConnected; Kind = (GamepadKind) ((int) capabilities.GamePadType + ((int) GamepadKind.Unknown - (int) Microsoft.Xna.Framework.Input.GamePadType.Unknown)); #region Buttons AvailableButtons = XboxInputLabel.Buttons.None; if (capabilities.HasAButton) { AvailableButtons |= XboxInputLabel.Buttons.A; } if (capabilities.HasBButton) { AvailableButtons |= XboxInputLabel.Buttons.B; } if (capabilities.HasXButton) { AvailableButtons |= XboxInputLabel.Buttons.X; } if (capabilities.HasYButton) { AvailableButtons |= XboxInputLabel.Buttons.Y; } if (capabilities.HasLeftShoulderButton) { AvailableButtons |= XboxInputLabel.Buttons.LB; } if (capabilities.HasRightShoulderButton) { AvailableButtons |= XboxInputLabel.Buttons.RB; } if (capabilities.HasDPadUpButton) { AvailableButtons |= XboxInputLabel.Buttons.DUp; } if (capabilities.HasDPadRightButton) { AvailableButtons |= XboxInputLabel.Buttons.DRight; } if (capabilities.HasDPadDownButton) { AvailableButtons |= XboxInputLabel.Buttons.DDown; } if (capabilities.HasDPadLeftButton) { AvailableButtons |= XboxInputLabel.Buttons.DLeft; } if (capabilities.HasBackButton) { AvailableButtons |= XboxInputLabel.Buttons.Back; } if (capabilities.HasStartButton) { AvailableButtons |= XboxInputLabel.Buttons.Start; } if (capabilities.HasBigButton) { AvailableButtons |= XboxInputLabel.Buttons.BigButton; } #endregion Buttons #region Triggers AvailableTriggers = XboxInputLabel.Triggers.None; if (capabilities.HasLeftTrigger) { AvailableTriggers |= XboxInputLabel.Triggers.LT; } if (capabilities.HasRightTrigger) { AvailableTriggers |= XboxInputLabel.Triggers.RT; } #endregion Triggers #region Features AvailableFeatures = GamepadFeature.None; if (capabilities.HasLeftXThumbStick) { AvailableFeatures |= GamepadFeature.LeftThumbStickHorizontalAxis; } if (capabilities.HasLeftYThumbStick) { AvailableFeatures |= GamepadFeature.LeftThumbStickVerticalAxis; } if (capabilities.HasRightXThumbStick) { AvailableFeatures |= GamepadFeature.RightThumbStickHorizontalAxis; } if (capabilities.HasRightYThumbStick) { AvailableFeatures |= GamepadFeature.RightThumbStickVerticalAxis; } if (capabilities.HasLeftVibrationMotor) { AvailableFeatures |= GamepadFeature.LeftVibrationMotor; } if (capabilities.HasRightVibrationMotor) { AvailableFeatures |= GamepadFeature.RightVibrationMotor; } if (capabilities.HasVoiceSupport) { AvailableFeatures |= GamepadFeature.VoiceSupport; } if (capabilities.HasLightBarEXT) { AvailableFeatures |= GamepadFeature.LightBar; } if (capabilities.HasTriggerVibrationMotorsEXT) { AvailableFeatures |= GamepadFeature.TriggerVibrationMotors; } if (capabilities.HasMisc1EXT) { AvailableFeatures |= GamepadFeature.Misc1; } if (capabilities.HasPaddle1EXT) { AvailableFeatures |= GamepadFeature.Paddle1; } if (capabilities.HasPaddle2EXT) { AvailableFeatures |= GamepadFeature.Paddle2; } if (capabilities.HasPaddle3EXT) { AvailableFeatures |= GamepadFeature.Paddle3; } if (capabilities.HasPaddle4EXT) { AvailableFeatures |= GamepadFeature.Paddle4; } if (capabilities.HasTouchPadEXT) { AvailableFeatures |= GamepadFeature.TouchPad; } if (capabilities.HasGyroEXT) { AvailableFeatures |= GamepadFeature.Gyro; } if (capabilities.HasAccelerometerEXT) { AvailableFeatures |= GamepadFeature.Accelerometer; } #endregion Features } public GamepadCapabilities(GamepadIndex index) : this((int) index) { } #endregion Constructors #region Public Properties public GamepadIndex Index { get { if (Id < 0 || Id > (int) GamepadIndex.Sixteen) { return GamepadIndex.Other; } return (GamepadIndex) Id; } } #endregion Public Properties #region Public Methods public bool HasButton(XboxInputLabel.Buttons button) { return (AvailableButtons & button) == button; } public bool HasTrigger(XboxInputLabel.Triggers trigger) { return (AvailableTriggers & trigger) == trigger; } public bool HasDirectional(XboxInputLabel.DPad directional) { return HasButton(directional.ToButton()); } public bool HasFeature(GamepadFeature feature) { return (AvailableFeatures & feature) == feature; } #endregion Public Methods } }
//css_dbg /t:winexe; //css_imp VSAddIn.cs; using System; using System.IO; using System.Drawing; using System.Diagnostics; using System.Windows.Forms.VisualStyles; using System.Windows.Forms; namespace Scripting { public class Form1 : System.Windows.Forms.Form { const string installCaption = "Install"; const string insertCaption = "Insert"; const string importCaption = "Import"; const string removeCaption = "Remove"; const string naCaption = ""; const int ideNameCol = 0; const int ideInstalledCol = 1; const int addinActionCol = 2; const int toolbarInstalledCol = 3; const int toolbarInsertActionCol = 4; const int toolbarImportActiondCol = 5; const int toolbarRemoveActiondCol = 6; private DataGridView dataGridView1; private Button help; private Button close; private Timer timer1; private System.ComponentModel.IContainer components; delegate void addColumnDlgt(DataGridViewButtonColumn column, DataGridView grid); public Form1() { InitializeComponent(); dataGridView1.Columns.Add(new DataGridViewTextBoxColumn()); dataGridView1.Columns.Add(new DataGridViewCheckBoxColumn()); dataGridView1.Columns.Add(new DataGridViewDisableButtonColumn()); dataGridView1.Columns.Add(new DataGridViewCheckBoxColumn()); dataGridView1.Columns.Add(new DataGridViewDisableButtonColumn()); dataGridView1.Columns.Add(new DataGridViewDisableButtonColumn()); dataGridView1.Columns.Add(new DataGridViewDisableButtonColumn()); //dataGridView1.Columns.Add(new DataGridViewDisableButtonColumn()); dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; dataGridView1.Columns[ideNameCol].HeaderText = "IDE version"; dataGridView1.Columns[ideInstalledCol].HeaderText = "IDE installed"; dataGridView1.Columns[addinActionCol].HeaderText = "VS Extension\n(Add-in)"; dataGridView1.Columns[toolbarInstalledCol].HeaderText = "Toolbar\nis integrated"; dataGridView1.Columns[toolbarInsertActionCol].HeaderText = "Toolbar\nSetup Action"; dataGridView1.Columns[toolbarImportActiondCol].HeaderText = "Toolbar\nSetup Action"; dataGridView1.Columns[toolbarRemoveActiondCol].HeaderText = "Toolbar\nSetup Action"; //dataGridView1.Columns[7].HeaderText = "Code Snippets\nSetup Action"; dataGridView1.Columns[ideInstalledCol].Width = 90; dataGridView1.Columns[addinActionCol].Width = 90; dataGridView1.Columns[toolbarInstalledCol].Width = 90; dataGridView1.Columns[toolbarInsertActionCol].Width = 90; dataGridView1.Columns[toolbarImportActiondCol].Width = 90; dataGridView1.Columns[toolbarRemoveActiondCol].Width = 90; dataGridView1.RowCount = 6; dataGridView1.Rows[0].Cells[ideNameCol].Value = "VS 2005"; dataGridView1.Rows[0].Cells[ideInstalledCol].Value = vsToolbar.IsIdeInstalled; dataGridView1.Rows[0].Cells[addinActionCol].Value = naCaption; dataGridView1.Rows[0].Cells[toolbarInstalledCol].Value = false; dataGridView1.Rows[0].Cells[toolbarInsertActionCol].Value = insertCaption; dataGridView1.Rows[0].Cells[toolbarImportActiondCol].Value = importCaption; dataGridView1.Rows[0].Cells[toolbarRemoveActiondCol].Value = removeCaption; //dataGridView1.Rows[0].Cells[7].Value = installCaption; //dataGridView1.Rows[0].Cells[7].Tag = vsCodeSnippet; dataGridView1.Rows[1].Cells[ideNameCol].Value = "VS 2005 Express"; dataGridView1.Rows[1].Cells[ideInstalledCol].Value = vsExpressToolbar.IsIdeInstalled; dataGridView1.Rows[1].Cells[addinActionCol].Value = naCaption; dataGridView1.Rows[1].Cells[toolbarInstalledCol].Value = false; dataGridView1.Rows[1].Cells[toolbarInsertActionCol].Value = insertCaption; dataGridView1.Rows[1].Cells[toolbarImportActiondCol].Value = importCaption; dataGridView1.Rows[1].Cells[toolbarRemoveActiondCol].Value = removeCaption; //dataGridView1.Rows[1].Cells[7].Value = installCaption; //dataGridView1.Rows[1].Cells[7].Tag = vsExpressCodeSnippet; dataGridView1.Rows[2].Cells[ideNameCol].Value = "VS 2008"; dataGridView1.Rows[2].Cells[ideInstalledCol].Value = vs9Toolbar.IsIdeInstalled; dataGridView1.Rows[2].Cells[addinActionCol].Value = naCaption; dataGridView1.Rows[2].Cells[toolbarInstalledCol].Value = vs9Toolbar.IsIdeInstalled; dataGridView1.Rows[2].Cells[toolbarInsertActionCol].Value = insertCaption; dataGridView1.Rows[2].Cells[toolbarImportActiondCol].Value = importCaption; dataGridView1.Rows[2].Cells[toolbarRemoveActiondCol].Value = removeCaption; //dataGridView1.Rows[2].Cells[7].Value = installCaption; //dataGridView1.Rows[2].Cells[7].Tag = vs9CodeSnippet; dataGridView1.Rows[3].Cells[ideNameCol].Value = "VS 2008 Express"; dataGridView1.Rows[3].Cells[ideInstalledCol].Value = vsExpress9Toolbar.IsIdeInstalled; dataGridView1.Rows[3].Cells[addinActionCol].Value = naCaption; dataGridView1.Rows[3].Cells[toolbarInstalledCol].Value = false; dataGridView1.Rows[3].Cells[toolbarInsertActionCol].Value = insertCaption; dataGridView1.Rows[3].Cells[toolbarImportActiondCol].Value = importCaption; dataGridView1.Rows[3].Cells[toolbarRemoveActiondCol].Value = removeCaption; //dataGridView1.Rows[3].Cells[7].Value = installCaption; //dataGridView1.Rows[3].Cells[7].Tag = vsExpress9CodeSnippet; dataGridView1.Rows[4].Cells[ideNameCol].Value = "VS 2010"; dataGridView1.Rows[4].Cells[ideInstalledCol].Value = vs10Toolbar.IsIdeInstalled; dataGridView1.Rows[4].Cells[addinActionCol].Value = installCaption; dataGridView1.Rows[4].Cells[addinActionCol].Tag = vs10Toolbar; dataGridView1.Rows[4].Cells[toolbarInstalledCol].Value = false; dataGridView1.Rows[4].Cells[toolbarInsertActionCol].Value = naCaption; dataGridView1.Rows[4].Cells[toolbarImportActiondCol].Value = naCaption; dataGridView1.Rows[4].Cells[toolbarRemoveActiondCol].Value = naCaption; //dataGridView1.Rows[4].Cells[7].Value = naCaption; dataGridView1.Rows[5].Cells[ideNameCol].Value = "VS 2010 Express"; dataGridView1.Rows[5].Cells[ideInstalledCol].Value = vsExpress10Toolbar.IsIdeInstalled; dataGridView1.Rows[5].Cells[addinActionCol].Value = naCaption; dataGridView1.Rows[5].Cells[toolbarInstalledCol].Value = vsExpress10Toolbar.IsIdeInstalled; dataGridView1.Rows[5].Cells[toolbarInsertActionCol].Value = insertCaption; dataGridView1.Rows[5].Cells[toolbarImportActiondCol].Value = importCaption; dataGridView1.Rows[5].Cells[toolbarRemoveActiondCol].Value = removeCaption; //dataGridView1.Rows[5].Cells[7].Value = naCaption; //dataGridView1.Rows[5].Cells[7].Tag = vsExpress10CodeSnippet; dataGridView1.BorderStyle = BorderStyle.None; dataGridView1.ShowCellToolTips = true; RefreshLayout(); } void RefreshLayout() { CSSToolbar[] toolbars = new CSSToolbar[] { vsToolbar, vsExpressToolbar, vs9Toolbar, vsExpress9Toolbar, vs10Toolbar, vsExpress10Toolbar }; IVSCodeSnippet[] snippets = new IVSCodeSnippet[] { vsCodeSnippet, vsExpressCodeSnippet, vs9CodeSnippet, vsExpress9CodeSnippet, vs10CodeSnippet, vsExpress10CodeSnippet }; for (int i = 0; i < 6; i++) { CSSToolbar toolbar = toolbars[i]; IVSCodeSnippet snippet = snippets[i]; bool installed = toolbar.IsInstalled; dataGridView1.Rows[i].Cells[toolbarInstalledCol].Value = installed; (dataGridView1.Rows[i].Cells[toolbarInsertActionCol] as DataGridViewDisableButtonCell).Enabled = toolbar.IsIdeInstalled && !installed; (dataGridView1.Rows[i].Cells[toolbarImportActiondCol] as DataGridViewDisableButtonCell).Enabled = toolbar.IsIdeInstalled && !installed; (dataGridView1.Rows[i].Cells[toolbarRemoveActiondCol] as DataGridViewDisableButtonCell).Enabled = toolbar.IsIdeInstalled && installed && toolbar.IsRestoreAvailable; //(dataGridView1.Rows[i].Cells[7] as DataGridViewDisableButtonCell).Enabled = toolbar.IsIdeInstalled; //if (!(dataGridView1.Rows[i].Cells[7] as DataGridViewDisableButtonCell).Enabled) // dataGridView1.Rows[i].Cells[7].Value = ""; //else // dataGridView1.Rows[i].Cells[7].Value = snippet.IsInstalled ? removeCaption : installCaption; for (int j = 0; j < 7; j++) if (dataGridView1.Rows[i].Cells[j].Value.ToString() == naCaption && dataGridView1.Rows[i].Cells[j] is DataGridViewDisableButtonCell) (dataGridView1.Rows[i].Cells[j] as DataGridViewDisableButtonCell).Enabled = false; dataGridView1.Rows[i].Cells[toolbarInsertActionCol].ToolTipText = "Insert CS-Script toolbar by modifying IDE settings (.vssettings file) directly.\nYou will be able to undo this action by pressing Remove button."; dataGridView1.Rows[i].Cells[toolbarImportActiondCol].ToolTipText = "Insert CS-Script toolbar by importing (custom .vssettings file). Safer but less reliable option.\nYou will be able to undo this action by pressing Remove button"; //dataGridView1.Rows[i].Cells[6].ToolTipText = "Install CS-Script Code Snippet"; } Refresh(); } VSToolbar vsToolbar = new VSToolbar(); VSEToolbar vsExpressToolbar = new VSEToolbar(); VS9Toolbar vs9Toolbar = new VS9Toolbar(); VSE9Toolbar vsExpress9Toolbar = new VSE9Toolbar(); VS10Toolbar vs10Toolbar = new VS10Toolbar(); VSE10Toolbar vsExpress10Toolbar = new VSE10Toolbar(); VSCodeSnippet vsCodeSnippet = new VSCodeSnippet(); VSECodeSnippet vsExpressCodeSnippet = new VSECodeSnippet(); VS9CodeSnippet vs9CodeSnippet = new VS9CodeSnippet(); VSE9CodeSnippet vsExpress9CodeSnippet = new VSE9CodeSnippet(); VS10CodeSnippet vs10CodeSnippet = new VS10CodeSnippet(); VSE10CodeSnippet vsExpress10CodeSnippet = new VSE10CodeSnippet(); protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } #region Windows Form Designer generated code private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.dataGridView1 = new System.Windows.Forms.DataGridView(); this.help = new System.Windows.Forms.Button(); this.close = new System.Windows.Forms.Button(); this.timer1 = new System.Windows.Forms.Timer(this.components); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); this.SuspendLayout(); // // dataGridView1 // this.dataGridView1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.dataGridView1.BackgroundColor = System.Drawing.SystemColors.Control; this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridView1.EditMode = System.Windows.Forms.DataGridViewEditMode.EditProgrammatically; this.dataGridView1.Location = new System.Drawing.Point(12, 12); this.dataGridView1.MultiSelect = false; this.dataGridView1.Name = "dataGridView1"; this.dataGridView1.ReadOnly = true; this.dataGridView1.RowHeadersVisible = false; this.dataGridView1.Size = new System.Drawing.Size(645, 196); this.dataGridView1.TabIndex = 0; this.dataGridView1.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellClick); this.dataGridView1.KeyDown += new System.Windows.Forms.KeyEventHandler(this.dataGridView1_KeyDown); // // help // this.help.Anchor = System.Windows.Forms.AnchorStyles.Bottom; this.help.Location = new System.Drawing.Point(344, 214); this.help.Name = "help"; this.help.Size = new System.Drawing.Size(84, 27); this.help.TabIndex = 1; this.help.Text = "Help"; this.help.Click += new System.EventHandler(this.help_Click); // // close // this.close.Anchor = System.Windows.Forms.AnchorStyles.Bottom; this.close.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.close.Location = new System.Drawing.Point(241, 214); this.close.Name = "close"; this.close.Size = new System.Drawing.Size(84, 27); this.close.TabIndex = 1; this.close.Text = "Close"; this.close.Click += new System.EventHandler(this.close_Click); // // timer1 // this.timer1.Enabled = true; this.timer1.Interval = 5000; this.timer1.Tick += new System.EventHandler(this.timer1_Tick); // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.CancelButton = this.close; this.ClientSize = new System.Drawing.Size(671, 253); this.Controls.Add(this.close); this.Controls.Add(this.help); this.Controls.Add(this.dataGridView1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.SizableToolWindow; this.KeyPreview = true; this.Name = "Form1"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "CS-Script Visual Studio Add-ins"; this.TopMost = true; this.Load += new System.EventHandler(this.Form1_Load); this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyDown); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); this.ResumeLayout(false); } #endregion private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) { if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex] is DataGridViewDisableButtonCell) { DataGridViewDisableButtonCell buttonCell = (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex] as DataGridViewDisableButtonCell); if (buttonCell.Enabled) { Cursor.Current = Cursors.WaitCursor; if (buttonCell.Tag is VSCodeSnippet) { if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString() == removeCaption) (buttonCell.Tag as VSCodeSnippet).Remove(); else (buttonCell.Tag as VSCodeSnippet).Install(); } else if (buttonCell.Tag is VSECodeSnippet) { if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString() == removeCaption) (buttonCell.Tag as VSECodeSnippet).Remove(); else (buttonCell.Tag as VSECodeSnippet).Install(); } else if (buttonCell.Tag is VSE9CodeSnippet) { if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString() == removeCaption) (buttonCell.Tag as VSE9CodeSnippet).Remove(); else (buttonCell.Tag as VSE9CodeSnippet).Install(); } else if (buttonCell.Tag is VS10Toolbar) { (buttonCell.Tag as VS10Toolbar).Install(); } else { CSSToolbar toolbar; if (e.RowIndex == 0) toolbar = vsToolbar; else if (e.RowIndex == 1) toolbar = vsExpressToolbar; else if (e.RowIndex == 2) toolbar = vs9Toolbar; else if (e.RowIndex == 3) toolbar = vsExpress9Toolbar; else if (e.RowIndex == 4) toolbar = vs10Toolbar; else toolbar = vsExpress10Toolbar; if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString() == removeCaption && toolbar.IsRestoreAvailable) { toolbar.RestoreOldSettings(); } else if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString() == insertCaption && !toolbar.IsInstalled) { toolbar.Install(); } else if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString() == importCaption && !toolbar.IsInstalled) { toolbar.Import(); } } RefreshLayout(); Cursor.Current = Cursors.Default; } } } private void help_Click(object sender, EventArgs e) { string homeDir = Environment.GetEnvironmentVariable("CSSCRIPT_DIR"); if (homeDir != null) { Help.ShowHelp(this, Path.Combine(homeDir, @"Docs\Help\CSScript.chm"), "ConfigUtils.html#_vs_integration"); } } private void close_Click(object sender, EventArgs e) { Close(); } private void Form1_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.F5) RefreshLayout(); } private void timer1_Tick(object sender, EventArgs e) { RefreshLayout(); } private void Form1_Load(object sender, EventArgs e) { timer1.Enabled = true; } private void dataGridView1_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Escape) Close(); } } class Script { const string usage = "Usage: cscscript VSIntegration ...\nCS-Script Visual Studio toolbar configuration console.\n"; static public void Main(string[] args) { if (args.Length == 1 && (args[0] == "?" || args[0] == "/?" || args[0] == "-?" || args[0].ToLower() == "help")) { Console.WriteLine(usage); } else { Application.EnableVisualStyles(); Application.Run(new Form1()); } } } public class DataGridViewDisableButtonColumn : DataGridViewButtonColumn { public DataGridViewDisableButtonColumn() { this.CellTemplate = new DataGridViewDisableButtonCell(); } } public class DataGridViewDisableButtonCell : DataGridViewButtonCell { private bool enabledValue; public bool Enabled { get { return enabledValue; } set { enabledValue = value; } } // Override the Clone method so that the Enabled property is copied. public override object Clone() { DataGridViewDisableButtonCell cell = (DataGridViewDisableButtonCell)base.Clone(); cell.Enabled = this.Enabled; return cell; } // By default, enable the button cell. public DataGridViewDisableButtonCell() { this.enabledValue = true; } protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex, DataGridViewElementStates elementState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts) { // The button cell is disabled, so paint the border, // background, and disabled button for the cell. if (!this.enabledValue) { // Draw the cell background, if specified. if ((paintParts & DataGridViewPaintParts.Background) == DataGridViewPaintParts.Background) { SolidBrush cellBackground = new SolidBrush(cellStyle.BackColor); graphics.FillRectangle(cellBackground, cellBounds); cellBackground.Dispose(); } // Draw the cell borders, if specified. if ((paintParts & DataGridViewPaintParts.Border) == DataGridViewPaintParts.Border) { PaintBorder(graphics, clipBounds, cellBounds, cellStyle, advancedBorderStyle); } // Calculate the area in which to draw the button. Rectangle buttonArea = cellBounds; Rectangle buttonAdjustment = this.BorderWidths(advancedBorderStyle); buttonArea.X += buttonAdjustment.X; buttonArea.Y += buttonAdjustment.Y; buttonArea.Height -= buttonAdjustment.Height; buttonArea.Width -= buttonAdjustment.Width; // Draw the disabled button. ButtonRenderer.DrawButton(graphics, buttonArea, PushButtonState.Disabled); // Draw the disabled button text. if (this.FormattedValue is String) { TextRenderer.DrawText(graphics, (string)this.FormattedValue, this.DataGridView.Font, buttonArea, enabledValue ? SystemColors.ControlText : SystemColors.GrayText); } } else { // The button cell is enabled, so let the base class // handle the painting. base.Paint(graphics, clipBounds, cellBounds, rowIndex, elementState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts); } } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Reflection; using System.Management.Automation.Host; using Dbg = System.Management.Automation.Diagnostics; using InternalHostUserInterface = System.Management.Automation.Internal.Host.InternalHostUserInterface; namespace System.Management.Automation.Remoting { /// <summary> /// Executes methods; can be encoded and decoded for transmission over the /// wire. /// </summary> internal class RemoteHostCall { /// <summary> /// Method name. /// </summary> internal string MethodName { get { return _methodInfo.Name; } } /// <summary> /// Method id. /// </summary> internal RemoteHostMethodId MethodId { get; } /// <summary> /// Parameters. /// </summary> internal object[] Parameters { get; } /// <summary> /// Method info. /// </summary> private RemoteHostMethodInfo _methodInfo; /// <summary> /// Call id. /// </summary> private long _callId; /// <summary> /// Call id. /// </summary> internal long CallId { get { return _callId; } } /// <summary> /// Computer name to be used in messages /// </summary> private string _computerName; /// <summary> /// Constructor for RemoteHostCall. /// </summary> internal RemoteHostCall(long callId, RemoteHostMethodId methodId, object[] parameters) { Dbg.Assert(parameters != null, "Expected parameters != null"); _callId = callId; MethodId = methodId; Parameters = parameters; _methodInfo = RemoteHostMethodInfo.LookUp(methodId); } /// <summary> /// Encode parameters. /// </summary> private static PSObject EncodeParameters(object[] parameters) { // Encode the parameters and wrap the array into an ArrayList and then into a PSObject. ArrayList parameterList = new ArrayList(); for (int i = 0; i < parameters.Length; ++i) { object parameter = parameters[i] == null ? null : RemoteHostEncoder.EncodeObject(parameters[i]); parameterList.Add(parameter); } return new PSObject(parameterList); } /// <summary> /// Decode parameters. /// </summary> private static object[] DecodeParameters(PSObject parametersPSObject, Type[] parameterTypes) { // Extract the ArrayList and decode the parameters. ArrayList parameters = (ArrayList)parametersPSObject.BaseObject; List<object> decodedParameters = new List<object>(); Dbg.Assert(parameters.Count == parameterTypes.Length, "Expected parameters.Count == parameterTypes.Length"); for (int i = 0; i < parameters.Count; ++i) { object parameter = parameters[i] == null ? null : RemoteHostEncoder.DecodeObject(parameters[i], parameterTypes[i]); decodedParameters.Add(parameter); } return decodedParameters.ToArray(); } /// <summary> /// Encode. /// </summary> internal PSObject Encode() { // Add all host information as data. PSObject data = RemotingEncoder.CreateEmptyPSObject(); // Encode the parameters for transport. PSObject parametersPSObject = EncodeParameters(Parameters); // Embed everything into the main PSobject. data.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.CallId, _callId)); data.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.MethodId, MethodId)); data.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.MethodParameters, parametersPSObject)); return data; } /// <summary> /// Decode. /// </summary> internal static RemoteHostCall Decode(PSObject data) { Dbg.Assert(data != null, "Expected data != null"); // Extract all the fields from data. long callId = RemotingDecoder.GetPropertyValue<long>(data, RemoteDataNameStrings.CallId); PSObject parametersPSObject = RemotingDecoder.GetPropertyValue<PSObject>(data, RemoteDataNameStrings.MethodParameters); RemoteHostMethodId methodId = RemotingDecoder.GetPropertyValue<RemoteHostMethodId>(data, RemoteDataNameStrings.MethodId); // Look up all the info related to the method. RemoteHostMethodInfo methodInfo = RemoteHostMethodInfo.LookUp(methodId); // Decode the parameters. object[] parameters = DecodeParameters(parametersPSObject, methodInfo.ParameterTypes); // Create and return the RemoteHostCall. return new RemoteHostCall(callId, methodId, parameters); } /// <summary> /// Is void method. /// </summary> internal bool IsVoidMethod { get { return _methodInfo.ReturnType == typeof(void); } } /// <summary> /// Execute void method. /// </summary> internal void ExecuteVoidMethod(PSHost clientHost) { // The clientHost can be null if the user creates a runspace object without providing // a host parameter. if (clientHost == null) { return; } RemoteRunspace remoteRunspaceToClose = null; if (this.IsSetShouldExitOrPopRunspace) { remoteRunspaceToClose = GetRemoteRunspaceToClose(clientHost); } try { object targetObject = this.SelectTargetObject(clientHost); MyMethodBase.Invoke(targetObject, Parameters); } finally { if (remoteRunspaceToClose != null) { remoteRunspaceToClose.Close(); } } } /// <summary> /// Get remote runspace to close. /// </summary> private RemoteRunspace GetRemoteRunspaceToClose(PSHost clientHost) { // Figure out if we need to close the remote runspace. Return null if we don't. // Are we a Start-PSSession enabled host? IHostSupportsInteractiveSession host = clientHost as IHostSupportsInteractiveSession; if (host == null || !host.IsRunspacePushed) { return null; } // Now inspect the runspace. RemoteRunspace remoteRunspace = host.Runspace as RemoteRunspace; if (remoteRunspace == null || !remoteRunspace.ShouldCloseOnPop) { return null; } // At this point it is clear we have to close the remote runspace, so return it. return remoteRunspace; } /// <summary> /// My method base. /// </summary> private MethodBase MyMethodBase { get { return (MethodBase)_methodInfo.InterfaceType.GetMethod(_methodInfo.Name, _methodInfo.ParameterTypes); } } /// <summary> /// Execute non void method. /// </summary> internal RemoteHostResponse ExecuteNonVoidMethod(PSHost clientHost) { // The clientHost can be null if the user creates a runspace object without providing // a host parameter. if (clientHost == null) { throw RemoteHostExceptions.NewNullClientHostException(); } object targetObject = this.SelectTargetObject(clientHost); RemoteHostResponse remoteHostResponse = this.ExecuteNonVoidMethodOnObject(targetObject); return remoteHostResponse; } /// <summary> /// Execute non void method on object. /// </summary> private RemoteHostResponse ExecuteNonVoidMethodOnObject(object instance) { // Create variables to store result of execution. Exception exception = null; object returnValue = null; // Invoke the method and store its return values. try { if (MethodId == RemoteHostMethodId.GetBufferContents) { throw new PSRemotingDataStructureException(RemotingErrorIdStrings.RemoteHostGetBufferContents, _computerName.ToUpper()); } returnValue = MyMethodBase.Invoke(instance, Parameters); } catch (Exception e) { // Catch-all OK, 3rd party callout. CommandProcessorBase.CheckForSevereException(e); exception = e.InnerException; } // Create a RemoteHostResponse object to store the return value and exceptions. return new RemoteHostResponse(_callId, MethodId, returnValue, exception); } /// <summary> /// Get the object that this method should be invoked on. /// </summary> private object SelectTargetObject(PSHost host) { if (host == null || host.UI == null) { return null; } if (_methodInfo.InterfaceType == typeof(PSHost)) { return host; } if (_methodInfo.InterfaceType == typeof(IHostSupportsInteractiveSession)) { return host; } if (_methodInfo.InterfaceType == typeof(PSHostUserInterface)) { return host.UI; } if (_methodInfo.InterfaceType == typeof(IHostUISupportsMultipleChoiceSelection)) { return host.UI; } if (_methodInfo.InterfaceType == typeof(PSHostRawUserInterface)) { return host.UI.RawUI; } throw RemoteHostExceptions.NewUnknownTargetClassException(_methodInfo.InterfaceType.ToString()); } /// <summary> /// Is set should exit. /// </summary> internal bool IsSetShouldExit { get { return MethodId == RemoteHostMethodId.SetShouldExit; } } /// <summary> /// Is set should exit or pop runspace. /// </summary> internal bool IsSetShouldExitOrPopRunspace { get { return MethodId == RemoteHostMethodId.SetShouldExit || MethodId == RemoteHostMethodId.PopRunspace; } } /// <summary> /// This message performs various security checks on the /// remote host call message. If there is a need to modify /// the message or discard it for security reasons then /// such modifications will be made here /// </summary> /// <param name="computerName">computer name to use in /// warning messages</param> /// <returns>a collection of remote host calls which will /// have to be executed before this host call can be /// executed</returns> internal Collection<RemoteHostCall> PerformSecurityChecksOnHostMessage(String computerName) { Dbg.Assert(!String.IsNullOrEmpty(computerName), "Computer Name must be passed for use in warning messages"); _computerName = computerName; Collection<RemoteHostCall> prerequisiteCalls = new Collection<RemoteHostCall>(); // check if the incoming message is a PromptForCredential message // if so, do the following: // (a) prepend "Windows PowerShell Credential Request" in the title // (b) prepend "Message from Server XXXXX" to the text message if (MethodId == RemoteHostMethodId.PromptForCredential1 || MethodId == RemoteHostMethodId.PromptForCredential2) { // modify the caption which is _parameters[0] string modifiedCaption = ModifyCaption((string)Parameters[0]); // modify the message which is _parameters[1] string modifiedMessage = ModifyMessage((string)Parameters[1], computerName); Parameters[0] = modifiedCaption; Parameters[1] = modifiedMessage; } // Check if the incoming message is a Prompt message // if so, then do the following: // (a) check if any of the field descriptions // correspond to PSCredential // (b) if field descriptions correspond to // PSCredential modify the caption and // message as in the previous case above else if (MethodId == RemoteHostMethodId.Prompt) { // check if any of the field descriptions is for type // PSCredential if (Parameters.Length == 3) { Collection<FieldDescription> fieldDescs = (Collection<FieldDescription>)Parameters[2]; bool havePSCredential = false; foreach (FieldDescription fieldDesc in fieldDescs) { fieldDesc.IsFromRemoteHost = true; Type fieldType = InternalHostUserInterface.GetFieldType(fieldDesc); if (fieldType != null) { if (fieldType == typeof(PSCredential)) { havePSCredential = true; fieldDesc.ModifiedByRemotingProtocol = true; } else if (fieldType == typeof(System.Security.SecureString)) { prerequisiteCalls.Add(ConstructWarningMessageForSecureString( computerName, RemotingErrorIdStrings.RemoteHostPromptSecureStringPrompt)); } } }// end of foreach if (havePSCredential) { // modify the caption which is parameter[0] string modifiedCaption = ModifyCaption((string)Parameters[0]); // modify the message which is parameter[1] string modifiedMessage = ModifyMessage((string)Parameters[1], computerName); Parameters[0] = modifiedCaption; Parameters[1] = modifiedMessage; } }// end of if (parameters ... }// if (remoteHostCall.MethodId ... // Check if the incoming message is a readline as secure string // if so do the following: // (a) Specify a warning message that the server is // attempting to read something securely on the client else if (MethodId == RemoteHostMethodId.ReadLineAsSecureString) { prerequisiteCalls.Add(ConstructWarningMessageForSecureString( computerName, RemotingErrorIdStrings.RemoteHostReadLineAsSecureStringPrompt)); } // check if the incoming call is GetBufferContents // if so do the following: // (a) Specify a warning message that the server is // attemping to read the screen buffer contents // on screen and it has been blocked // (b) Modify the message so that call is not executed else if (MethodId == RemoteHostMethodId.GetBufferContents) { prerequisiteCalls.Add(ConstructWarningMessageForGetBufferContents(computerName)); } return prerequisiteCalls; } /// <summary> /// Provides the modified caption for the given caption /// Used in ensuring that remote prompt messages are /// tagged with "Windows PowerShell Credential Request" /// </summary> /// <param name="caption">caption to modify</param> /// <returns>new modified caption</returns> private String ModifyCaption(string caption) { string pscaption = CredUI.PromptForCredential_DefaultCaption; if (!caption.Equals(pscaption, StringComparison.OrdinalIgnoreCase)) { string modifiedCaption = PSRemotingErrorInvariants.FormatResourceString( RemotingErrorIdStrings.RemoteHostPromptForCredentialModifiedCaption, caption); return modifiedCaption; } return caption; } /// <summary> /// Provides the modified message for the given one /// Used in ensuring that remote prompt messages /// contain a warning that they originate from a /// different computer /// </summary> /// <param name="message">original message to modify</param> /// <param name="computerName">computername to include in the /// message</param> /// <returns>message which contains a warning as well</returns> private String ModifyMessage(string message, string computerName) { string modifiedMessage = PSRemotingErrorInvariants.FormatResourceString( RemotingErrorIdStrings.RemoteHostPromptForCredentialModifiedMessage, computerName.ToUpper(), message); return modifiedMessage; } /// <summary> /// Creates a warning message which displays to the user a /// warning stating that the remote host computer is /// actually attempting to read a line as a secure string /// </summary> /// <param name="computerName">computer name to include /// in warning</param> /// <param name="resourceString">resource string to use</param> /// <returns>a constructed remote host call message /// which will display the warning</returns> private RemoteHostCall ConstructWarningMessageForSecureString(string computerName, string resourceString) { string warning = PSRemotingErrorInvariants.FormatResourceString( resourceString, computerName.ToUpper()); return new RemoteHostCall(ServerDispatchTable.VoidCallId, RemoteHostMethodId.WriteWarningLine, new object[] { warning }); } /// <summary> /// Creates a warning message which displays to the user a /// warning stating that the remote host computer is /// attempting to read the host's buffer contents and that /// it was suppressed /// </summary> /// <param name="computerName">computer name to include /// in warning</param> /// <returns>a constructed remote host call message /// which will display the warning</returns> private RemoteHostCall ConstructWarningMessageForGetBufferContents(string computerName) { string warning = PSRemotingErrorInvariants.FormatResourceString( RemotingErrorIdStrings.RemoteHostGetBufferContents, computerName.ToUpper()); return new RemoteHostCall(ServerDispatchTable.VoidCallId, RemoteHostMethodId.WriteWarningLine, new object[] { warning }); } } /// <summary> /// Encapsulates the method response semantics. Method responses are generated when /// RemoteHostCallPacket objects are executed. They can contain both the return values of /// the execution as well as exceptions that were thrown in the RemoteHostCallPacket /// execution. They can be encoded and decoded for transporting over the wire. A /// method response can be used to transport the result of an execution and then to /// simulate the execution on the other end. /// </summary> internal class RemoteHostResponse { /// <summary> /// Call id. /// </summary> private long _callId; /// <summary> /// Call id. /// </summary> internal long CallId { get { return _callId; } } /// <summary> /// Method id. /// </summary> private RemoteHostMethodId _methodId; /// <summary> /// Return value. /// </summary> private object _returnValue; /// <summary> /// Exception. /// </summary> private Exception _exception; /// <summary> /// Constructor for RemoteHostResponse. /// </summary> internal RemoteHostResponse(long callId, RemoteHostMethodId methodId, object returnValue, Exception exception) { _callId = callId; _methodId = methodId; _returnValue = returnValue; _exception = exception; } /// <summary> /// Simulate execution. /// </summary> internal object SimulateExecution() { if (_exception != null) { throw _exception; } return _returnValue; } /// <summary> /// Encode and add return value. /// </summary> private static void EncodeAndAddReturnValue(PSObject psObject, object returnValue) { // Do nothing if the return value is null. if (returnValue == null) { return; } // Otherwise add the property. RemoteHostEncoder.EncodeAndAddAsProperty(psObject, RemoteDataNameStrings.MethodReturnValue, returnValue); } /// <summary> /// Decode return value. /// </summary> private static object DecodeReturnValue(PSObject psObject, Type returnType) { object returnValue = RemoteHostEncoder.DecodePropertyValue(psObject, RemoteDataNameStrings.MethodReturnValue, returnType); return returnValue; } /// <summary> /// Encode and add exception. /// </summary> private static void EncodeAndAddException(PSObject psObject, Exception exception) { RemoteHostEncoder.EncodeAndAddAsProperty(psObject, RemoteDataNameStrings.MethodException, exception); } /// <summary> /// Decode exception. /// </summary> private static Exception DecodeException(PSObject psObject) { object result = RemoteHostEncoder.DecodePropertyValue(psObject, RemoteDataNameStrings.MethodException, typeof(Exception)); if (result == null) { return null; } if (result is Exception) { return (Exception)result; } throw RemoteHostExceptions.NewDecodingFailedException(); } /// <summary> /// Encode. /// </summary> internal PSObject Encode() { // Create a data object and put everything in that and return it. PSObject data = RemotingEncoder.CreateEmptyPSObject(); EncodeAndAddReturnValue(data, _returnValue); EncodeAndAddException(data, _exception); data.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.CallId, _callId)); data.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.MethodId, _methodId)); return data; } /// <summary> /// Decode. /// </summary> internal static RemoteHostResponse Decode(PSObject data) { Dbg.Assert(data != null, "Expected data != null"); // Extract all the fields from data. long callId = RemotingDecoder.GetPropertyValue<long>(data, RemoteDataNameStrings.CallId); RemoteHostMethodId methodId = RemotingDecoder.GetPropertyValue<RemoteHostMethodId>(data, RemoteDataNameStrings.MethodId); // Decode the return value and the exception. RemoteHostMethodInfo methodInfo = RemoteHostMethodInfo.LookUp(methodId); object returnValue = DecodeReturnValue(data, methodInfo.ReturnType); Exception exception = DecodeException(data); // Use these values to create a RemoteHostResponse and return it. return new RemoteHostResponse(callId, methodId, returnValue, exception); } } /// <summary> /// The RemoteHostExceptions class. /// </summary> internal static class RemoteHostExceptions { /// <summary> /// New remote runspace does not support push runspace exception. /// </summary> internal static Exception NewRemoteRunspaceDoesNotSupportPushRunspaceException() { string resourceString = PSRemotingErrorInvariants.FormatResourceString( RemotingErrorIdStrings.RemoteRunspaceDoesNotSupportPushRunspace); return new PSRemotingDataStructureException(resourceString); } /// <summary> /// New decoding failed exception. /// </summary> internal static Exception NewDecodingFailedException() { string resourceString = PSRemotingErrorInvariants.FormatResourceString( RemotingErrorIdStrings.RemoteHostDecodingFailed); return new PSRemotingDataStructureException(resourceString); } /// <summary> /// New not implemented exception. /// </summary> internal static Exception NewNotImplementedException(RemoteHostMethodId methodId) { RemoteHostMethodInfo methodInfo = RemoteHostMethodInfo.LookUp(methodId); string resourceString = PSRemotingErrorInvariants.FormatResourceString( RemotingErrorIdStrings.RemoteHostMethodNotImplemented, methodInfo.Name); return new PSRemotingDataStructureException(resourceString, new PSNotImplementedException()); } /// <summary> /// New remote host call failed exception. /// </summary> internal static Exception NewRemoteHostCallFailedException(RemoteHostMethodId methodId) { RemoteHostMethodInfo methodInfo = RemoteHostMethodInfo.LookUp(methodId); string resourceString = PSRemotingErrorInvariants.FormatResourceString( RemotingErrorIdStrings.RemoteHostCallFailed, methodInfo.Name); return new PSRemotingDataStructureException(resourceString); } /// <summary> /// New decoding error for error record exception. /// </summary> internal static Exception NewDecodingErrorForErrorRecordException() { return new PSRemotingDataStructureException(RemotingErrorIdStrings.DecodingErrorForErrorRecord); } /// <summary> /// New remote host data encoding not supported exception. /// </summary> internal static Exception NewRemoteHostDataEncodingNotSupportedException(Type type) { Dbg.Assert(type != null, "Expected type != null"); return new PSRemotingDataStructureException( RemotingErrorIdStrings.RemoteHostDataEncodingNotSupported, type.ToString()); } /// <summary> /// New remote host data decoding not supported exception. /// </summary> internal static Exception NewRemoteHostDataDecodingNotSupportedException(Type type) { Dbg.Assert(type != null, "Expected type != null"); return new PSRemotingDataStructureException( RemotingErrorIdStrings.RemoteHostDataDecodingNotSupported, type.ToString()); } /// <summary> /// New unknown target class exception. /// </summary> internal static Exception NewUnknownTargetClassException(string className) { Dbg.Assert(className != null, "Expected className != null"); return new PSRemotingDataStructureException(RemotingErrorIdStrings.UnknownTargetClass, className); } internal static Exception NewNullClientHostException() { return new PSRemotingDataStructureException(RemotingErrorIdStrings.RemoteHostNullClientHost); } } }
using J2N.Collections.Generic.Extensions; using Lucene.Net.Diagnostics; using Lucene.Net.Search; using Lucene.Net.Search.Similarities; using Lucene.Net.Util; using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; namespace Lucene.Net.Index.Memory { /* * 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. */ public partial class MemoryIndex { /////////////////////////////////////////////////////////////////////////////// // Nested classes: /////////////////////////////////////////////////////////////////////////////// /// <summary> /// Search support for Lucene framework integration; implements all methods /// required by the Lucene IndexReader contracts. /// </summary> private sealed class MemoryIndexReader : AtomicReader { private readonly MemoryIndex outerInstance; internal IndexSearcher searcher; // needed to find searcher.getSimilarity() internal MemoryIndexReader(MemoryIndex outerInstance) : base() // avoid as much superclass baggage as possible { this.outerInstance = outerInstance; } internal Info GetInfo(string fieldName) { return outerInstance.fields[fieldName]; } internal Info GetInfo(int pos) { return outerInstance.sortedFields[pos].Value; } public override IBits LiveDocs => null; public override FieldInfos FieldInfos => new FieldInfos(outerInstance.fieldInfos.Values.ToArray(/*new FieldInfo[outerInstance.fieldInfos.Count]*/)); public override NumericDocValues GetNumericDocValues(string field) { return null; } public override BinaryDocValues GetBinaryDocValues(string field) { return null; } public override SortedDocValues GetSortedDocValues(string field) { return null; } public override SortedSetDocValues GetSortedSetDocValues(string field) { return null; } public override IBits GetDocsWithField(string field) { return null; } public override void CheckIntegrity() { // no-op } private class MemoryFields : Fields { private readonly MemoryIndex.MemoryIndexReader outerInstance; public MemoryFields(MemoryIndex.MemoryIndexReader outerInstance) { this.outerInstance = outerInstance; } public override IEnumerator<string> GetEnumerator() { return new IteratorAnonymousInnerClassHelper(this); } private class IteratorAnonymousInnerClassHelper : IEnumerator<string> { private readonly MemoryFields outerInstance; public IteratorAnonymousInnerClassHelper(MemoryFields outerInstance) { this.outerInstance = outerInstance; upto = -1; } internal int upto; private string current; public string Current => this.current; object IEnumerator.Current => Current; public void Dispose() { // Nothing to do } public bool MoveNext() { if (upto + 1 >= outerInstance.outerInstance.outerInstance.sortedFields.Length) { return false; } upto++; current = outerInstance.outerInstance.outerInstance.sortedFields[upto].Key; return true; } public void Reset() { throw new NotSupportedException(); } } public override Terms GetTerms(string field) { var searchField = new KeyValuePair<string, Info>(field, null); int i = Array.BinarySearch(outerInstance.outerInstance.sortedFields, searchField, new TermComparer<string, Info>()); if (i < 0) { return null; } else { Info info = outerInstance.GetInfo(i); info.SortTerms(); return new TermsAnonymousInnerClassHelper(this, info); } } private class TermsAnonymousInnerClassHelper : Terms { private readonly MemoryFields outerInstance; private MemoryIndex.Info info; public TermsAnonymousInnerClassHelper(MemoryFields outerInstance, MemoryIndex.Info info) { this.outerInstance = outerInstance; this.info = info; } public override TermsEnum GetEnumerator() { return new MemoryTermsEnum(outerInstance.outerInstance, info); } public override IComparer<BytesRef> Comparer => BytesRef.UTF8SortedAsUnicodeComparer; public override long Count => info.terms.Count; public override long SumTotalTermFreq => info.SumTotalTermFreq; public override long SumDocFreq => // each term has df=1 info.terms.Count; public override int DocCount => info.terms.Count > 0 ? 1 : 0; public override bool HasFreqs => true; public override bool HasOffsets => outerInstance.outerInstance.outerInstance.storeOffsets; public override bool HasPositions => true; public override bool HasPayloads => false; } public override int Count => outerInstance.outerInstance.sortedFields.Length; } public override Fields Fields { get { outerInstance.SortFields(); return new MemoryFields(this); } } private class MemoryTermsEnum : TermsEnum { private readonly MemoryIndex.MemoryIndexReader outerInstance; internal readonly Info info; internal readonly BytesRef br = new BytesRef(); internal int termUpto = -1; public MemoryTermsEnum(MemoryIndex.MemoryIndexReader outerInstance, Info info) { this.outerInstance = outerInstance; this.info = info; info.SortTerms(); } internal int BinarySearch(BytesRef b, BytesRef bytesRef, int low, int high, BytesRefHash hash, int[] ords, IComparer<BytesRef> comparer) { int mid = 0; while (low <= high) { mid = (int)((uint)(low + high) >> 1); hash.Get(ords[mid], bytesRef); int cmp = comparer.Compare(bytesRef, b); if (cmp < 0) { low = mid + 1; } else if (cmp > 0) { high = mid - 1; } else { return mid; } } if (Debugging.AssertsEnabled) Debugging.Assert(comparer.Compare(bytesRef, b) != 0); return -(low + 1); } public override bool SeekExact(BytesRef text) { termUpto = BinarySearch(text, br, 0, info.terms.Count - 1, info.terms, info.sortedTerms, BytesRef.UTF8SortedAsUnicodeComparer); return termUpto >= 0; } public override SeekStatus SeekCeil(BytesRef text) { termUpto = BinarySearch(text, br, 0, info.terms.Count - 1, info.terms, info.sortedTerms, BytesRef.UTF8SortedAsUnicodeComparer); if (termUpto < 0) // not found; choose successor { termUpto = -termUpto - 1; if (termUpto >= info.terms.Count) { return SeekStatus.END; } else { info.terms.Get(info.sortedTerms[termUpto], br); return SeekStatus.NOT_FOUND; } } else { return SeekStatus.FOUND; } } public override void SeekExact(long ord) { if (Debugging.AssertsEnabled) Debugging.Assert(ord < info.terms.Count); termUpto = (int)ord; } public override bool MoveNext() { termUpto++; if (termUpto >= info.terms.Count) { return false; } else { info.terms.Get(info.sortedTerms[termUpto], br); return true; } } [Obsolete("Use MoveNext() and Term instead. This method will be removed in 4.8.0 release candidate."), System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public override BytesRef Next() { if (MoveNext()) return br; return null; } public override BytesRef Term => br; public override long Ord => termUpto; public override int DocFreq => 1; public override long TotalTermFreq => info.sliceArray.freq[info.sortedTerms[termUpto]]; public override DocsEnum Docs(IBits liveDocs, DocsEnum reuse, DocsFlags flags) { if (reuse is null || !(reuse is MemoryDocsEnum toReuse)) toReuse = new MemoryDocsEnum(outerInstance); return toReuse.Reset(liveDocs, info.sliceArray.freq[info.sortedTerms[termUpto]]); } public override DocsAndPositionsEnum DocsAndPositions(IBits liveDocs, DocsAndPositionsEnum reuse, DocsAndPositionsFlags flags) { if (reuse is null || !(reuse is MemoryDocsAndPositionsEnum toReuse)) toReuse = new MemoryDocsAndPositionsEnum(outerInstance); int ord = info.sortedTerms[termUpto]; return toReuse.Reset(liveDocs, info.sliceArray.start[ord], info.sliceArray.end[ord], info.sliceArray.freq[ord]); } public override IComparer<BytesRef> Comparer => BytesRef.UTF8SortedAsUnicodeComparer; public override void SeekExact(BytesRef term, TermState state) { if (Debugging.AssertsEnabled) Debugging.Assert(state != null); this.SeekExact(((OrdTermState)state).Ord); } public override TermState GetTermState() { OrdTermState ts = new OrdTermState(); ts.Ord = termUpto; return ts; } } private class MemoryDocsEnum : DocsEnum { private readonly MemoryIndex.MemoryIndexReader outerInstance; public MemoryDocsEnum(MemoryIndex.MemoryIndexReader outerInstance) { this.outerInstance = outerInstance; } internal bool hasNext; internal IBits liveDocs; internal int doc = -1; internal int freq; public virtual DocsEnum Reset(IBits liveDocs, int freq) { this.liveDocs = liveDocs; hasNext = true; doc = -1; this.freq = freq; return this; } public override int DocID => doc; public override int NextDoc() { if (hasNext && (liveDocs == null || liveDocs.Get(0))) { hasNext = false; return doc = 0; } else { return doc = NO_MORE_DOCS; } } public override int Advance(int target) { return SlowAdvance(target); } public override int Freq => freq; public override long GetCost() { return 1; } } private class MemoryDocsAndPositionsEnum : DocsAndPositionsEnum { private readonly MemoryIndex.MemoryIndexReader outerInstance; internal int posUpto; // for assert internal bool hasNext; internal IBits liveDocs; internal int doc = -1; internal Int32BlockPool.SliceReader sliceReader; internal int freq; internal int startOffset; internal int endOffset; public MemoryDocsAndPositionsEnum(MemoryIndex.MemoryIndexReader outerInstance) { this.outerInstance = outerInstance; this.sliceReader = new Int32BlockPool.SliceReader(outerInstance.outerInstance.intBlockPool); } public virtual DocsAndPositionsEnum Reset(IBits liveDocs, int start, int end, int freq) { this.liveDocs = liveDocs; this.sliceReader.Reset(start, end); posUpto = 0; // for assert hasNext = true; doc = -1; this.freq = freq; return this; } public override int DocID => doc; public override int NextDoc() { if (hasNext && (liveDocs == null || liveDocs.Get(0))) { hasNext = false; return doc = 0; } else { return doc = NO_MORE_DOCS; } } public override int Advance(int target) { return SlowAdvance(target); } public override int Freq => freq; public override int NextPosition() { if (Debugging.AssertsEnabled) { Debugging.Assert(posUpto++ < freq); Debugging.Assert(!sliceReader.IsEndOfSlice, () => " stores offsets : " + startOffset); } if (outerInstance.outerInstance.storeOffsets) { int pos = sliceReader.ReadInt32(); startOffset = sliceReader.ReadInt32(); endOffset = sliceReader.ReadInt32(); return pos; } else { return sliceReader.ReadInt32(); } } public override int StartOffset => startOffset; public override int EndOffset => endOffset; public override BytesRef GetPayload() { return null; } public override long GetCost() { return 1; } } public override Fields GetTermVectors(int docID) { if (docID == 0) { return Fields; } else { return null; } } internal Similarity Similarity { get { if (searcher != null) { return searcher.Similarity; } return IndexSearcher.DefaultSimilarity; } } internal IndexSearcher Searcher { get => this.searcher; // LUCENENET specific: added getter per MSDN guidelines set => this.searcher = value; } public override int NumDocs { get { #if DEBUG Debug.WriteLine("MemoryIndexReader.NumDocs"); #endif return 1; } } public override int MaxDoc { get { #if DEBUG Debug.WriteLine("MemoryIndexReader.MaxDoc"); #endif return 1; } } public override void Document(int docID, StoredFieldVisitor visitor) { #if DEBUG Debug.WriteLine("MemoryIndexReader.Document"); #endif // no-op: there are no stored fields } protected internal override void DoClose() { #if DEBUG Debug.WriteLine("MemoryIndexReader.DoClose"); #endif } /// <summary> /// performance hack: cache norms to avoid repeated expensive calculations </summary> internal NumericDocValues cachedNormValues; internal string cachedFieldName; internal Similarity cachedSimilarity; public override NumericDocValues GetNormValues(string field) { FieldInfo fieldInfo; if (!outerInstance.fieldInfos.TryGetValue(field, out fieldInfo) || fieldInfo.OmitsNorms) { return null; } NumericDocValues norms = cachedNormValues; Similarity sim = Similarity; if (!field.Equals(cachedFieldName, StringComparison.Ordinal) || sim != cachedSimilarity) // not cached? { Info info = GetInfo(field); int numTokens = info != null ? info.numTokens : 0; int numOverlapTokens = info != null ? info.numOverlapTokens : 0; float boost = info != null ? info.Boost : 1.0f; FieldInvertState invertState = new FieldInvertState(field, 0, numTokens, numOverlapTokens, 0, boost); long value = sim.ComputeNorm(invertState); norms = new MemoryIndexNormDocValues(value); // cache it for future reuse cachedNormValues = norms; cachedFieldName = field; cachedSimilarity = sim; #if DEBUG Debug.WriteLine("MemoryIndexReader.norms: " + field + ":" + value + ":" + numTokens); #endif } return norms; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.ComponentModel.Composition.Primitives; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.Internal; namespace System.ComponentModel.Composition.Hosting { /// <summary> /// A mutable collection of <see cref="ComposablePartCatalog"/>s. /// </summary> /// <remarks> /// This type is thread safe. /// </remarks> public class AggregateCatalog : ComposablePartCatalog, INotifyComposablePartCatalogChanged { private ComposablePartCatalogCollection _catalogs = null; private volatile int _isDisposed = 0; /// <summary> /// Initializes a new instance of the <see cref="AggregateCatalog"/> class. /// </summary> public AggregateCatalog() : this((IEnumerable<ComposablePartCatalog>)null) { } /// <summary> /// Initializes a new instance of the <see cref="AggregateCatalog"/> class /// with the specified catalogs. /// </summary> /// <param name="catalogs"> /// An <see cref="Array"/> of <see cref="ComposablePartCatalog"/> objects to add to the /// <see cref="AggregateCatalog"/>. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="catalogs"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="catalogs"/> contains an element that is <see langword="null"/>. /// </exception> public AggregateCatalog(params ComposablePartCatalog[] catalogs) : this((IEnumerable<ComposablePartCatalog>)catalogs) { } /// <summary> /// Initializes a new instance of the <see cref="AggregateCatalog"/> class /// with the specified catalogs. /// </summary> /// <param name="catalogs"> /// An <see cref="IEnumerable{T}"/> of <see cref="ComposablePartCatalog"/> objects to add /// to the <see cref="AggregateCatalog"/>; or <see langword="null"/> to /// create an <see cref="AggregateCatalog"/> that is empty. /// </param> /// <exception cref="ArgumentException"> /// <paramref name="catalogs"/> contains an element that is <see langword="null"/>. /// </exception> public AggregateCatalog(IEnumerable<ComposablePartCatalog> catalogs) { Requires.NullOrNotNullElements(catalogs, nameof(catalogs)); _catalogs = new ComposablePartCatalogCollection(catalogs, OnChanged, OnChanging); } /// <summary> /// Notify when the contents of the Catalog has changed. /// </summary> public event EventHandler<ComposablePartCatalogChangeEventArgs> Changed { add { _catalogs.Changed += value; } remove { _catalogs.Changed -= value; } } /// <summary> /// Notify when the contents of the Catalog has changing. /// </summary> public event EventHandler<ComposablePartCatalogChangeEventArgs> Changing { add { _catalogs.Changing += value; } remove { _catalogs.Changing -= value; } } /// <summary> /// Returns the export definitions that match the constraint defined by the specified definition. /// </summary> /// <param name="definition"> /// The <see cref="ImportDefinition"/> that defines the conditions of the /// <see cref="ExportDefinition"/> objects to return. /// </param> /// <returns> /// An <see cref="IEnumerable{T}"/> of <see cref="Tuple{T1, T2}"/> containing the /// <see cref="ExportDefinition"/> objects and their associated /// <see cref="ComposablePartDefinition"/> for objects that match the constraint defined /// by <paramref name="definition"/>. /// </returns> /// <exception cref="ArgumentNullException"> /// <paramref name="definition"/> is <see langword="null"/>. /// </exception> /// <exception cref="ObjectDisposedException"> /// The <see cref="AggregateCatalog"/> has been disposed of. /// </exception> public override IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> GetExports(ImportDefinition definition) { ThrowIfDisposed(); Requires.NotNull(definition, nameof(definition)); // We optimize for the case where the result is comparible with the requested cardinality, though we do remain correct in all cases. // We do so to avoid any unnecessary allocations IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> result = null; List<Tuple<ComposablePartDefinition, ExportDefinition>> aggregateResult = null; foreach (var catalog in _catalogs) { var catalogExports = catalog.GetExports(definition); if (catalogExports != ComposablePartCatalog._EmptyExportsList) { // ideally this is is the case we will always hit if (result == null) { result = catalogExports; } else { // sadly the result has already been assigned, which means we are in the aggregate case if (aggregateResult == null) { aggregateResult = new List<Tuple<ComposablePartDefinition, ExportDefinition>>(result); result = aggregateResult; } aggregateResult.AddRange(catalogExports); } } } return result ?? ComposablePartCatalog._EmptyExportsList; } /// <summary> /// Gets the underlying catalogs of the catalog. /// </summary> /// <value> /// An <see cref="ICollection{T}"/> of underlying <see cref="ComposablePartCatalog"/> objects /// of the <see cref="AggregateCatalog"/>. /// </value> /// <exception cref="ObjectDisposedException"> /// The <see cref="AggregateCatalog"/> has been disposed of. /// </exception> public ICollection<ComposablePartCatalog> Catalogs { get { ThrowIfDisposed(); Debug.Assert(_catalogs != null); return _catalogs; } } protected override void Dispose(bool disposing) { try { if (disposing) { if (Interlocked.CompareExchange(ref _isDisposed, 1, 0) == 0) { _catalogs.Dispose(); } } } finally { base.Dispose(disposing); } } public override IEnumerator<ComposablePartDefinition> GetEnumerator() { return _catalogs.SelectMany(catalog => catalog).GetEnumerator(); } /// <summary> /// Raises the <see cref="INotifyComposablePartCatalogChanged.Changed"/> event. /// </summary> /// <param name="e"> /// An <see cref="ComposablePartCatalogChangeEventArgs"/> containing the data for the event. /// </param> protected virtual void OnChanged(ComposablePartCatalogChangeEventArgs e) { _catalogs.OnChanged(this, e); } /// <summary> /// Raises the <see cref="INotifyComposablePartCatalogChanged.Changing"/> event. /// </summary> /// <param name="e"> /// An <see cref="ComposablePartCatalogChangeEventArgs"/> containing the data for the event. /// </param> protected virtual void OnChanging(ComposablePartCatalogChangeEventArgs e) { _catalogs.OnChanging(this, e); } [DebuggerStepThrough] private void ThrowIfDisposed() { if (_isDisposed == 1) { throw ExceptionBuilder.CreateObjectDisposed(this); } } } }
/* * 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 Apache.Ignite.Core.Tests.Process { using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading; using Apache.Ignite.Core.Impl.Common; /// <summary> /// Defines forked Ignite node. /// </summary> public class IgniteProcess { /** Executable file name. */ private static readonly string ExeName = "Apache.Ignite.exe"; /** Executable process name. */ private static readonly string ExeProcName = ExeName.Substring(0, ExeName.LastIndexOf('.')); /** Executable configuration file name. */ private static readonly string ExeCfgName = ExeName + ".config"; /** Executable backup configuration file name. */ private static readonly string ExeCfgBakName = ExeCfgName + ".bak"; /** Directory where binaries are stored. */ private static readonly string ExeDir; /** Full path to executable. */ private static readonly string ExePath; /** Full path to executable configuration file. */ private static readonly string ExeCfgPath; /** Full path to executable configuration file backup. */ private static readonly string ExeCfgBakPath; /** Default process output reader. */ private static readonly IIgniteProcessOutputReader DfltOutReader = new IgniteProcessConsoleOutputReader(); /** Process. */ private readonly Process _proc; /// <summary> /// Static initializer. /// </summary> static IgniteProcess() { // 1. Locate executable file and related stuff. DirectoryInfo dir = new FileInfo(new Uri(typeof(IgniteProcess).Assembly.CodeBase).LocalPath).Directory; // ReSharper disable once PossibleNullReferenceException ExeDir = dir.FullName; var exe = dir.GetFiles(ExeName); if (exe.Length == 0) throw new Exception(ExeName + " is not found in test output directory: " + dir.FullName); ExePath = exe[0].FullName; var exeCfg = dir.GetFiles(ExeCfgName); if (exeCfg.Length == 0) throw new Exception(ExeCfgName + " is not found in test output directory: " + dir.FullName); ExeCfgPath = exeCfg[0].FullName; ExeCfgBakPath = Path.Combine(ExeDir, ExeCfgBakName); File.Delete(ExeCfgBakPath); } /// <summary> /// Save current configuration to backup. /// </summary> public static void SaveConfigurationBackup() { File.Copy(ExeCfgPath, ExeCfgBakPath, true); } /// <summary> /// Restore configuration from backup. /// </summary> public static void RestoreConfigurationBackup() { File.Copy(ExeCfgBakPath, ExeCfgPath, true); } /// <summary> /// Replace application configuration with another one. /// </summary> /// <param name="relPath">Path to config relative to executable directory.</param> public static void ReplaceConfiguration(string relPath) { File.Copy(Path.Combine(ExeDir, relPath), ExeCfgPath, true); } /// <summary> /// Kill all Ignite processes. /// </summary> public static void KillAll() { foreach (Process proc in Process.GetProcesses()) { if (proc.ProcessName.Equals(ExeProcName)) { proc.Kill(); proc.WaitForExit(); } } } /// <summary> /// Construector. /// </summary> /// <param name="args">Arguments</param> public IgniteProcess(params string[] args) : this(DfltOutReader, args) { } /// <summary> /// Construector. /// </summary> /// <param name="outReader">Output reader.</param> /// <param name="args">Arguments.</param> public IgniteProcess(IIgniteProcessOutputReader outReader, params string[] args) { // Add test dll path args = args.Concat(new[] {"-assembly=" + GetType().Assembly.Location}).ToArray(); _proc = Start(ExePath, IgniteHome.Resolve(null), outReader, args); } /// <summary> /// Starts a grid process. /// </summary> /// <param name="exePath">Exe path.</param> /// <param name="ggHome">Ignite home.</param> /// <param name="outReader">Output reader.</param> /// <param name="args">Arguments.</param> /// <returns>Started process.</returns> public static Process Start(string exePath, string ggHome, IIgniteProcessOutputReader outReader = null, params string[] args) { Debug.Assert(!string.IsNullOrEmpty(exePath)); // 1. Define process start configuration. var sb = new StringBuilder(); foreach (string arg in args) sb.Append('\"').Append(arg).Append("\" "); var procStart = new ProcessStartInfo { FileName = exePath, Arguments = sb.ToString(), CreateNoWindow = true, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true }; if (ggHome != null) procStart.EnvironmentVariables[IgniteHome.EnvIgniteHome] = ggHome; procStart.EnvironmentVariables[Classpath.EnvIgniteNativeTestClasspath] = "true"; var workDir = Path.GetDirectoryName(exePath); if (workDir != null) procStart.WorkingDirectory = workDir; Console.WriteLine("About to run Apache.Ignite.exe process [exePath=" + exePath + ", arguments=" + sb + ']'); // 2. Start. var proc = Process.Start(procStart); Debug.Assert(proc != null); // 3. Attach output readers to avoid hangs. outReader = outReader ?? DfltOutReader; Attach(proc, proc.StandardOutput, outReader, false); Attach(proc, proc.StandardError, outReader, true); return proc; } /// <summary> /// Whether the process is still alive. /// </summary> public bool Alive { get { return !_proc.HasExited; } } /// <summary> /// Kill process. /// </summary> public void Kill() { _proc.Kill(); } /// <summary> /// Suspends the process. /// </summary> public void Suspend() { _proc.Suspend(); } /// <summary> /// Resumes the process. /// </summary> public void Resume() { _proc.Resume(); } /// <summary> /// Join process. /// </summary> /// <returns>Exit code.</returns> public int Join() { _proc.WaitForExit(); return _proc.ExitCode; } /// <summary> /// Join process with timeout. /// </summary> /// <param name="timeout">Timeout in milliseconds.</param> /// <returns><c>True</c> if process exit occurred before timeout.</returns> public bool Join(int timeout) { return _proc.WaitForExit(timeout); } /// <summary> /// Join process with timeout. /// </summary> /// <param name="timeout">Timeout in milliseconds.</param> /// <param name="exitCode">Exit code.</param> /// <returns><c>True</c> if process exit occurred before timeout.</returns> public bool Join(int timeout, out int exitCode) { if (_proc.WaitForExit(timeout)) { exitCode = _proc.ExitCode; return true; } exitCode = 0; return false; } /// <summary> /// Attach output reader to the process. /// </summary> /// <param name="proc">Process.</param> /// <param name="reader">Process stream reader.</param> /// <param name="outReader">Output reader.</param> /// <param name="err">Whether this is error stream.</param> private static void Attach(Process proc, StreamReader reader, IIgniteProcessOutputReader outReader, bool err) { new Thread(() => { while (!proc.HasExited) outReader.OnOutput(proc, reader.ReadLine(), err); }) {IsBackground = true}.Start(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Runtime.Serialization; using System.Threading; #if WINRT using System.Reflection; #endif #if Smartphone using TweetSharp.Core.Attributes; #endif #if SILVERLIGHT using System.Reflection; #endif namespace TweetSharp { #if !SILVERLIGHT && !WINRT /// <summary> /// Represents a normalized date from the Twitter API. /// </summary> [Serializable] #endif #if !Smartphone && !NET20 [DataContract] #endif public class TwitterDateTime : ITwitterModel { private static readonly IDictionary<string, string> _map = new Dictionary<string, string>(); /// <summary> /// Gets or sets the Twitter-based date format. /// </summary> /// <value>The format.</value> public virtual TwitterDateFormat Format { get; private set; } /// <summary> /// Gets or sets the actual date time. /// </summary> /// <value>The date time.</value> public virtual DateTime DateTime { get; private set; } #if !SILVERLIGHT && !Smartphone && !NET20 static readonly ReaderWriterLockSlim _readerWriterLock = new ReaderWriterLockSlim(); #else private static readonly object _lock = new object(); #endif /// <summary> /// Initializes a new instance of the <see cref="TwitterDateTime"/> class. /// </summary> /// <param name="dateTime">The date time.</param> /// <param name="format">The format.</param> public TwitterDateTime(DateTime dateTime, TwitterDateFormat format) { Format = format; DateTime = dateTime; } #if Smartphone || SILVERLIGHT private static readonly IList<string> _names = new List<string>(); #endif /// <summary> /// Converts from date time. /// </summary> /// <param name="input">The input.</param> /// <param name="format">The format.</param> /// <returns></returns> public static string ConvertFromDateTime(DateTime input, TwitterDateFormat format) { EnsureDateFormatsAreMapped(); #if !SILVERLIGHT && !Smartphone var name = Enum.GetName(typeof(TwitterDateFormat), format); #else EnsureEnumNamesAreMapped(typeof (TwitterDateFormat)); var name = _names[_names.IndexOf(format.ToString())]; #endif GetReadLockOnMap(); var value = _map[name]; ReleaseReadLockOnMap(); value = value.Replace(" zzzzz", " +0000"); var converted = input.ToString(value, CultureInfo.InvariantCulture); return converted; } /// <summary> /// Converts to date time. /// </summary> /// <param name="input">The input.</param> /// <returns></returns> public static DateTime ConvertToDateTime(string input) { EnsureDateFormatsAreMapped(); GetReadLockOnMap(); var formats = _map.Values; ReleaseReadLockOnMap(); foreach (var format in formats) { DateTime date; #if !Smartphone if (DateTime.TryParseExact(input, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out date)) #else if (TryParseDateTime(input, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out date)) #endif { return date; } } return default(DateTime); } /// <summary> /// Converts to twitter date time. /// </summary> /// <param name="input">The input.</param> /// <returns></returns> public static TwitterDateTime ConvertToTwitterDateTime(string input) { EnsureDateFormatsAreMapped(); GetReadLockOnMap(); try { foreach (var format in _map) { DateTime date; #if !Smartphone if (DateTime.TryParseExact(input, format.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out date)) #else if (TryParseDateTime(input, format.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out date)) #endif { var kind = Enum.Parse(typeof (TwitterDateFormat), format.Key, true); return new TwitterDateTime(date, (TwitterDateFormat) kind); } } return default(TwitterDateTime); } finally { ReleaseReadLockOnMap(); } } private static void EnsureDateFormatsAreMapped() { var type = typeof (TwitterDateFormat); #if !SILVERLIGHT && !Smartphone var names = Enum.GetNames(type); #else EnsureEnumNamesAreMapped(type); var names = _names; #endif GetReadLockOnMap(); try { foreach (var name in names) { if (_map.ContainsKey(name)) { continue; } GetWriteLockOnMap(); try { #if !WINRT var fi = typeof (TwitterDateFormat).GetField(name); var attributes = fi.GetCustomAttributes(typeof(DescriptionAttribute), false); #else var fi = typeof(TwitterDateFormat).GetTypeInfo().GetDeclaredField(name); var attributes = System.Linq.Enumerable.ToArray(fi.GetCustomAttributes(typeof(DescriptionAttribute), false)); #endif var format = (DescriptionAttribute)attributes[0]; _map.Add(name, format.Description); } finally { ReleaseWriteLockOnMap(); } } } finally { ReleaseReadLockOnMap(); } } private static void GetReadLockOnMap() { #if !SILVERLIGHT && !Smartphone && !NET20 _readerWriterLock.EnterUpgradeableReadLock(); #else Monitor.Enter(_lock); #endif } private static void ReleaseReadLockOnMap() { #if !SILVERLIGHT && !Smartphone && !NET20 _readerWriterLock.ExitUpgradeableReadLock(); #else Monitor.Exit(_lock); #endif } private static void GetWriteLockOnMap() { #if !SILVERLIGHT && !Smartphone && !NET20 _readerWriterLock.EnterWriteLock(); #else //already have exclusive access #endif } private static void ReleaseWriteLockOnMap() { #if !SILVERLIGHT && !Smartphone && !NET20 _readerWriterLock.ExitWriteLock(); #else //will exit when we give up read lock #endif } #if Smartphone || SILVERLIGHT private static bool TryParseDateTime(string input, string format, IFormatProvider provider, DateTimeStyles styles, out DateTime result) { try { result = DateTime.ParseExact(input, format, provider, styles); return true; } catch (Exception) { result = default(DateTime); return false; } } private static void EnsureEnumNamesAreMapped(Type type) { GetReadLockOnMap(); GetWriteLockOnMap(); try { var fields = type.GetFields(BindingFlags.Public | BindingFlags.Static); foreach (var field in fields) { if (_names.Contains(field.Name)) { continue; } _names.Add(field.Name); } } finally { ReleaseWriteLockOnMap(); ReleaseReadLockOnMap(); } } #endif /// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> public override string ToString() { return ConvertFromDateTime(DateTime, Format); } #if !Smartphone && !NET20 [DataMember] #endif public virtual string RawSource { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using LanguageExt; using static LanguageExt.Prelude; using static LanguageExt.Parsec.Common; using static LanguageExt.Parsec.Internal; using static LanguageExt.Parsec.Char; using static LanguageExt.Parsec.ParserResult; namespace LanguageExt.Parsec { /// <summary> /// The primitive parser combinators /// </summary> public static class Prim { static Prim() { unitp = inp => EmptyOK(unit, inp); getPos = (PString inp) => ConsumedOK(inp.Pos, inp); getIndex = (PString inp) => ConsumedOK(inp.Index, inp); eof = notFollowedBy(satisfy(_ => true)).label("end of input"); } /// <summary> /// Run the parser p with the input provided /// </summary> public static ParserResult<T> parse<T>(Parser<T> p, PString input) => p.Parse(input); /// <summary> /// Run the parser p with the input provided /// </summary> public static ParserResult<T> parse<T>(Parser<T> p, string input) => p.Parse(input); /// <summary> /// Lazy parser - useful in recursive scenarios. /// </summary> public static Parser<T> lazyp<T>(Func<Parser<T>> fn) => inp => fn()(inp); /// <summary> /// This parser is useful to put at the top of LINQ expressions, it /// makes it easier to put breakpoints on the actual first parser /// in an expression. It returns unit /// </summary> public static readonly Parser<Unit> unitp; /// <summary> /// Special parser for setting user-state that propagates /// through the computation. /// </summary> public static Parser<Unit> setState<T>(T state) => inp => ConsumedOK(unit, inp.SetUserState(state)); /// <summary> /// Special parser for getting user-state that was previously /// set with setState /// </summary> public static Parser<T> getState<T>() => inp => match(inp.UserState, Some: x => x is T ? ConsumedOK((T)x, inp) : EmptyError<T>(ParserError.Message(inp.Pos, "User state type-mismatch")), None: () => EmptyError<T>(ParserError.Message(inp.Pos, "No user state set"))); /// <summary> /// Get the current position of the parser in the source as a line /// and column index (starting at 1 for both) /// </summary> public static readonly Parser<Pos> getPos; /// <summary> /// Get the current index into the source /// </summary> public static readonly Parser<int> getIndex; /// <summary> /// The parser unexpected(msg) always fails with an Unexpect error /// message msg without consuming any input. /// </summary> /// <remarks> /// The parsers 'failure', 'label' and 'unexpected' are the three parsers /// used to generate error messages. Of these, only 'label' is commonly /// used. For an example of the use of unexpected, see the definition /// of 'Text.Parsec.Combinator.notFollowedBy'. /// </remarks> /// <param name="msg">Error message to use when parsed</param> public static Parser<T> unexpected<T>(string msg) => inp => EmptyError<T>(ParserError.Unexpect(inp.Pos, msg)); /// <summary> /// The parser failure(msg) always fails with a Message error /// without consuming any input. /// /// The parsers 'failure', 'label' and 'unexpected' are the three parsers /// used to generate error messages. Of these, only 'label' is commonly /// used. For an example of the use of unexpected, see the definition /// of 'Text.Parsec.Combinator.notFollowedBy'. /// </summary> /// <param name="msg">Error message to use when parsed</param> public static Parser<T> failure<T>(string msg) => inp => EmptyError<T>(ParserError.Message(inp.Pos, msg)); /// <summary> /// Always success parser. Returns the value provided. /// This is monad return for the Parser monad /// </summary> public static Parser<T> result<T>(T value) => inp => EmptyOK(value, inp); /// <summary> /// Always fails (with an Unknown error) without consuming any input /// </summary> public static Parser<T> zero<T>() => inp => EmptyError<T>(ParserError.Unknown(inp.Pos)); /// <summary> /// This combinator implements choice. The parser either(p,q) first /// applies p. If it succeeds, the value of p is returned. If p /// fails /without consuming any input/, parser q is tried. /// </summary> /// <remarks> /// This combinator is the mplus behaviour of the Parser monad. /// /// The parser is called /predictive/ since q is only tried when /// parser p didn't consume any input (i.e.. the look ahead is 1). /// /// This non-backtracking behaviour allows for both an efficient /// implementation of the parser combinators and the generation of good /// error messages. /// </remarks> public static Parser<T> either<T>(Parser<T> p, Parser<T> q) => inp => { var m = p(inp); // meerr if (m.Tag == ResultTag.Empty && m.Reply.Tag == ReplyTag.Error) { var n = q(inp); // neok if (n.Tag == ResultTag.Empty && n.Reply.Tag == ReplyTag.OK) { return EmptyOK(n.Reply.Result, n.Reply.State, mergeError(m.Reply.Error, n.Reply.Error)); } // nerr if (n.Tag == ResultTag.Empty && n.Reply.Tag == ReplyTag.Error) { return EmptyError<T>(mergeError(m.Reply.Error, n.Reply.Error)); } // cerr, cok return n; } // cok, cerr, eok return m; }; /// <summary> /// choice(ps) tries to apply the parsers in the list ps in order, until one /// of them succeeds. /// </summary> /// <returns> /// The value of the succeeding parser. /// </returns> public static Parser<T> choice<T>(params Parser<T>[] ps) => choicei(Seq(ps)); /// <summary> /// choice(ps) tries to apply the parsers in the list ps in order, until one /// of them succeeds. /// </summary> /// <returns> /// The value of the succeeding parser. /// </returns> public static Parser<T> choice<T>(Seq<Parser<T>> ps) => choicei(ps); /// <summary> /// Runs a sequence of parsers, if any fail then the failure state is /// returned immediately and subsequence parsers are not run. /// </summary> /// <returns> /// The result of each parser as an enumerable. /// </returns> public static Parser<Seq<T>> chain<T>(params Parser<T>[] ps) => chaini(Seq(ps)); /// <summary> /// Runs a sequence of parsers, if any fail then the failure state is /// returned immediately and subsequence parsers are not run. /// </summary> /// <returns> /// The result of each parser as an enumerable. /// </returns> public static Parser<Seq<T>> chain<T>(Seq<Parser<T>> ps) => chaini(ps); /// <summary> /// Cons for parser results /// </summary> /// <param name="p"></param> /// <param name="ps"></param> /// <typeparam name="T"></typeparam> /// <returns></returns> public static Parser<Seq<T>> cons<T>(Parser<T> p, Parser<Seq<T>> ps) => from x in p from xs in ps select x.Cons(xs); /// <summary> /// Flattens parser result: Seq of Seq of T => Seq of T /// </summary> /// <returns>Parser with flattened result sequence</returns> public static Parser<Seq<T>> flatten<T>(Parser<Seq<Seq<T>>> ssp) => from xss in ssp select xss.Flatten(); /// <summary> /// The parser attempt(p) behaves like parser p, except that it /// pretends that it hasn't consumed any input when an error occurs. /// /// This combinator is used whenever arbitrary look ahead is needed. /// Since it pretends that it hasn't consumed any input when p fails, /// the either combinator will try its second alternative even when the /// first parser failed while consuming input. /// /// See remarks. /// </summary> /// <remarks> /// The attempt combinator can for example be used to distinguish /// identifiers and reserved words. Both reserved words and identifiers /// are a sequence of letters. Whenever we expect a certain reserved /// word where we can also expect an identifier we have to use the attempt /// combinator. Suppose we write: /// /// var expr = either(letExpr, identifier).label("expression"); /// /// var letExpr = from x in str("let") /// ... /// select ...; /// /// var identifier = many1(letter); /// /// If the user writes "lexical", the parser fails with: unexpected /// "x", expecting "t" in "let". Indeed, since the either combinator /// only tries alternatives when the first alternative hasn't consumed /// input, the identifier parser is never tried (because the prefix /// "le" of the str("let") parser is already consumed). The right behaviour /// can be obtained by adding the attempt combinator: /// /// var expr = either(letExpr, identifier).label("expression"); /// /// var letExpr = from x in attempt(str("let")) /// ... /// select ...; /// /// var identifier = many1(letter); /// /// </remarks> public static Parser<T> attempt<T>(Parser<T> p) => inp => { var res = p(inp); if (res.Tag == ResultTag.Consumed && res.Reply.Tag == ReplyTag.Error) { return EmptyError<T>(res.Reply.Error); } else { return res; } }; /// <summary> /// lookAhead(p) parses p without consuming any input. /// /// If p fails and consumes some input, so does lookAhead(p). Combine with /// 'attempt' if this is undesirable. /// </summary> public static Parser<T> lookAhead<T>(Parser<T> p) => inp => { var res = p(inp); if (res.Reply.Tag == ReplyTag.OK) { return EmptyOK(res.Reply.Result, inp); } else { return res; } }; /// <summary> /// many(p) applies the parser p zero or more times. /// </summary> /// <example> /// var identifier = from c in letter /// from cs in many(letterOrDigit) /// select c.Cons(cs) /// </example> /// <returns> /// Enumerable of the returned values of p. /// </returns> public static Parser<Seq<T>> many<T>(Parser<T> p) => inp => { var current = inp; var results = new List<T>(); ParserError error = null; while(true) { var t = p(current); // cok if (t.Tag == ResultTag.Consumed && t.Reply.Tag == ReplyTag.OK) { results.Add(t.Reply.Result); current = t.Reply.State; error = t.Reply.Error; continue; } // eok if (t.Tag == ResultTag.Empty && t.Reply.Tag == ReplyTag.OK) { // eok, eerr return EmptyError<Seq<T>>(new ParserError(ParserErrorTag.SysUnexpect, current.Pos, "many: combinator 'many' is applied to a parser that accepts an empty string.", List.empty<string>())); } // cerr if (t.Tag == ResultTag.Consumed && t.Reply.Tag == ReplyTag.Error) { return ConsumedError<Seq<T>>(mergeError(error, t.Reply.Error)); } // eerr return EmptyOK(Seq(results), current, mergeError(error, t.Reply.Error)); } }; /// <summary> /// manyn(p, n) applies the parser p n times. /// </summary> /// <example> /// var identifier = from c in letter /// from cs in manyn(letterOrDigit, 4) /// select c.Cons(cs) /// </example> /// <returns> /// Enumerable of the returned values of p. /// </returns> public static Parser<Seq<T>> manyn<T>(Parser<T> p, int n) => inp => { var current = inp; var results = new List<T>(); ParserError error = null; int count = 0; while (true) { var t = p(current); count++; // cok if (t.Tag == ResultTag.Consumed && t.Reply.Tag == ReplyTag.OK) { results.Add(t.Reply.Result); current = t.Reply.State; error = t.Reply.Error; if (count == n) { return EmptyOK(Seq(results), current, mergeError(error, t.Reply.Error)); } continue; } // eok if (t.Tag == ResultTag.Empty && t.Reply.Tag == ReplyTag.OK) { // eok, eerr return EmptyError<Seq<T>>(new ParserError(ParserErrorTag.SysUnexpect, current.Pos, "many: combinator 'manyn' is applied to a parser that accepts an empty string.", List.empty<string>())); } // cerr if (t.Tag == ResultTag.Consumed && t.Reply.Tag == ReplyTag.Error) { return ConsumedError<Seq<T>>(mergeError(error, t.Reply.Error)); } // eerr return EmptyError<Seq<T>>(mergeError(error, t.Reply.Error)); } }; /// <summary> /// manyn0(p) applies the parser p zero or up to a maximum of n times. /// </summary> /// <example> /// var identifier = from c in letter /// from cs in manyn0(letterOrDigit, 4) /// select c.Cons(cs) /// </example> /// <returns> /// Enumerable of the returned values of p. /// </returns> public static Parser<Seq<T>> manyn0<T>(Parser<T> p, int n) => n <= 0 ? result(Seq<T>.Empty) : inp => { var current = inp; var results = new List<T>(); ParserError error = null; int count = 0; while (true) { var t = p(current); count++; // cok if (t.Tag == ResultTag.Consumed && t.Reply.Tag == ReplyTag.OK) { results.Add(t.Reply.Result); current = t.Reply.State; error = t.Reply.Error; if (count == n) { return EmptyOK(Seq(results), current, mergeError(error, t.Reply.Error)); } continue; } // eok if (t.Tag == ResultTag.Empty && t.Reply.Tag == ReplyTag.OK) { // eok, eerr return EmptyError<Seq<T>>(new ParserError(ParserErrorTag.SysUnexpect, current.Pos, "many: combinator 'manyn0' is applied to a parser that accepts an empty string.", List.empty<string>())); } // cerr if (t.Tag == ResultTag.Consumed && t.Reply.Tag == ReplyTag.Error) { return ConsumedError<Seq<T>>(mergeError(error, t.Reply.Error)); } // eerr return EmptyOK(Seq(results), current, mergeError(error, t.Reply.Error)); } }; /// <summary> /// manyn1(p) applies the parser p one or up to a maximum of n times. /// </summary> /// <returns> /// Enumerable of the returned values of p. /// </returns> public static Parser<Seq<T>> manyn1<T>(Parser<T> p, int n) => from x in p from xs in manyn0(p, n - 1) select x.Cons(xs); /// <summary> /// many1(p) applies the parser p one or more times. /// </summary> /// <returns> /// Enumerable of the returned values of p. /// </returns> public static Parser<Seq<T>> many1<T>(Parser<T> p) => from x in p from xs in many(p) select x.Cons(xs); /// <summary> /// skipMany(p) applies the parser p zero or more times, skipping /// its result. /// </summary> public static Parser<Unit> skipMany<T>(Parser<T> p) => either(skipMany1(p), result(unit)); /// <summary> /// skipMany(p) applies the parser p one or more times, skipping /// its result. /// </summary> public static Parser<Unit> skipMany1<T>(Parser<T> p) => from x in p from xs in many(p) select unit; /// <summary> /// optionOrElse(x, p) tries to apply parser p. If p fails without /// consuming input, it returns the value x, otherwise the value /// returned by p. /// </summary> public static Parser<T> optionOrElse<T>(T x, Parser<T> p) => either(p, result(x)); /// <summary> /// optional(p) tries to apply parser p. If p fails without /// consuming input, it return 'None', otherwise it returns /// 'Some' the value returned by p. /// </summary> public static Parser<Option<T>> optional<T>(Parser<T> p) => inp => { var r = p.Map(x => Option<T>.Some(x))(inp); return r.Reply.Tag == ReplyTag.OK ? r : EmptyOK(Option<T>.None, inp); }; /// <summary> /// optionalList(p) tries to apply parser p. If p fails without /// consuming input, it return [], otherwise it returns a one /// item Lst with the result of p. /// </summary> /// <returns>A list of 0 or 1 parsed items</returns> public static Parser<Lst<T>> optionalList<T>(Parser<T> p) => inp => { var r = p.Map(x => List.create(x))(inp); return r.Reply.Tag == ReplyTag.OK ? r : EmptyOK(List.empty<T>(), inp); }; /// <summary> /// optionalSeq(p) tries to apply parser p. If p fails without /// consuming input, it return an empty IEnumerable, otherwise it returns /// a one item IEnumerable with the result of p. /// </summary> /// <returns>A list of 0 or 1 parsed items</returns> public static Parser<Seq<T>> optionalSeq<T>(Parser<T> p) => inp => { var r = p.Map(x => x.Cons())(inp); return r.Reply.Tag == ReplyTag.OK ? r : EmptyOK(Seq<T>.Empty, inp); }; /// <summary> /// optionalArray(p) tries to apply parser p. If p fails without /// consuming input, it return [], otherwise it returns a one /// item array with the result of p. /// </summary> /// <returns>A list of 0 or 1 parsed items</returns> public static Parser<T[]> optionalArray<T>(Parser<T> p) => inp => { var r = p.Map(x => new[] { x })(inp); return r.Reply.Tag == ReplyTag.OK ? r : EmptyOK(new T [0], inp); }; /// <summary> /// between(open,close,p) parses open, followed by p and close. /// </summary> /// <returns> /// The value returned by p. /// </returns> public static Parser<T> between<L, R, T>(Parser<L> open, Parser<R> close, Parser<T> inner) => from l in open from v in inner from r in close select v; /// <summary> /// sepBy1(p,sep) parses one or more occurrences of p, separated /// by sep. /// </summary> /// <returns> /// A list of values returned by p. /// </returns> public static Parser<Seq<T>> sepBy1<S, T>(Parser<T> p, Parser<S> sep) => from x in p from xs in many(from _ in sep from y in p select y) select x.Cons(xs); /// <summary> /// sepBy(p,sep) parses zero or more occurrences of p, separated /// by sep. /// </summary> /// <returns> /// A list of values returned by p. /// </returns> public static Parser<Seq<T>> sepBy<S, T>(Parser<T> p, Parser<S> sep) => either(sepBy1(p, sep), result(Seq<T>.Empty)); /// <summary> /// sepEndBy1(p,sep) parses one or more occurrences of p, /// separated and optionally ended by sep. /// </summary> /// <returns> /// A list of values returned by p. /// </returns> public static Parser<Seq<T>> sepEndBy1<S, T>(Parser<T> p, Parser<S> sep) => from x in p from xs in either(from _ in sep from ys in sepEndBy(p, sep) select ys, result(Seq<T>.Empty)) select x.Cons(xs); /// <summary> /// sepEndBy(p,sep) parses zero or more occurrences of p, /// separated and optionally ended by sep. /// </summary> /// <returns> /// A list of values returned by p. /// </returns> public static Parser<Seq<T>> sepEndBy<S, T>(Parser<T> p, Parser<S> sep) => either(sepEndBy1(p, sep), result(Seq<T>.Empty)); /// <summary> /// endBy1(p,sep) parses one or more occurrences of p, separated /// and ended by sep. /// </summary> /// <returns> /// A list of values returned by p. /// </returns> public static Parser<Seq<T>> endBy1<S, T>(Parser<T> p, Parser<S> sep) => many1(from x in p from _ in sep select x); /// <summary> /// endBy(p,sep) parses zero or more occurrences of p, separated /// and ended by sep. /// </summary> /// <returns> /// A list of values returned by p. /// </returns> public static Parser<Seq<T>> endBy<S, T>(Parser<T> p, Parser<S> sep) => many(from x in p from _ in sep select x); /// <summary> /// count(n,p) parses n occurrences of p. If n is smaller or /// equal to zero, the parser equals to result([]). /// </summary> /// <returns> /// A list of values returned by p. /// </returns> public static Parser<Seq<T>> count<T>(int n, Parser<T> p) => counti(n, p); /// <summary> /// chainr(p,op,x) parses zero or more occurrences of p, separated by op /// </summary> /// <returns> /// a value obtained by a right associative application of all functions /// returned by op to the values returned by p. If there are no occurrences /// of p, the value x is returned.</returns> public static Parser<T> chainr<T>(Parser<T> p, Parser<Func<T, T, T>> op, T x) => either(chainr1(p, op), result(x)); /// <summary> /// chainl(p,op,x) parses zero or more occurrences of p, separated by op /// </summary> /// <returns> /// a value obtained by a left associative application of all functions /// returned by op to the values returned by p. If there are no occurrences /// of p, the value x is returned.</returns> public static Parser<T> chainl<T>(Parser<T> p, Parser<Func<T, T, T>> op, T x) => either(chainr1(p, op), result(x)); /// <summary> /// chainr1(p,op) parses one or more occurrences of p, separated by op. /// </summary> /// <returns> /// A value obtained by a right associative application of all functions /// returned by op to the values returned by p /// </returns> public static Parser<T> chainr1<T>(Parser<T> p, Parser<Func<T, T, T>> op) { Parser<T> scan = null; var rest = fun((T x) => either(from f in op from y in scan select f(x, y), result(x))); scan = from x in p from y in rest(x) select y; return scan; } /// <summary> /// chainl1(p,op) parses one or more occurrences of p, separated by op. /// </summary> /// <returns> /// A value obtained by a left associative application of all functions /// returned by op to the values returned by p /// </returns> public static Parser<T> chainl1<T>(Parser<T> p, Parser<Func<T, T, T>> op) { Func<T, Parser<T>> rest = null; rest = fun((T x) => either(from f in op from y in p from r in rest(f(x, y)) select r, result(x))); return from x in p from y in rest(x) select y; } /// <summary> /// This parser only succeeds at the end of the input. This is not a /// primitive parser but it is defined using 'notFollowedBy'. /// </summary> public readonly static Parser<Unit> eof; /// <summary> /// notFollowedBy(p) only succeeds when parser p fails. This parser /// does not consume any input.This parser can be used to implement the /// 'longest match' rule. /// </summary> /// <example>For example, when recognizing keywords (for /// example 'let'), we want to make sure that a keyword is not followed /// by a legal identifier character, in which case the keyword is /// actually an identifier(for example 'lets'). We can program this /// behaviour as follows: /// /// var keywordLet = attempt (from x in str("let") /// from _ in notFollowedBy letterOrDigit /// select x); /// /// </example> public static Parser<Unit> notFollowedBy<T>(Parser<T> p) => attempt( either(from c in attempt(p) from u in unexpected<Unit>(c.ToString()) select u, result(unit))); /// <summary> /// Parse a char list and convert into a string /// </summary> public static Parser<string> asString(Parser<Seq<char>> p) => p.Select(x => new string(x.ToArray())); /// <summary> /// Parse a char list and convert into an integer /// </summary> public static Parser<Option<int>> asInteger(Parser<Seq<char>> p) => p.Select(x => parseInt(new string(x.ToArray()))); /// <summary> /// Parse a char list and convert into an integer /// </summary> public static Parser<Option<int>> asInteger(Parser<Seq<char>> p, int fromBase) => p.Select(x => parseInt(new string(x.ToArray()), fromBase)); /// <summary> /// Parse a char list and convert into an double precision floating point value /// </summary> public static Parser<Option<double>> asDouble(Parser<Seq<char>> p) => p.Select(x => parseDouble(new string(x.ToArray()))); /// <summary> /// Parse a char list and convert into an double precision floating point value /// </summary> public static Parser<Option<float>> asFloat(Parser<Seq<char>> p) => p.Select(x => parseFloat(new string(x.ToArray()))); public static Parser<Seq<T>> manyUntil<T, U>(Parser<T> p, Parser<U> end) { Parser<Seq<T>> scan = null; scan = either( from _ in end select Seq<T>.Empty, from x in p from xs in scan select x.Cons(xs)); return scan; } } }
using System; using System.Linq; using NUnit.Framework; using Braintree; using Braintree.Exceptions; using Braintree.Test; using Params = System.Collections.Generic.Dictionary<string, object>; namespace Braintree.Tests { [TestFixture] public class PayPalAccountTest { private BraintreeGateway gateway; [SetUp] public void Setup() { gateway = new BraintreeGateway { Environment = Environment.DEVELOPMENT, MerchantId = "integration_merchant_id", PublicKey = "integration_public_key", PrivateKey = "integration_private_key" }; } [Test] [Category("Integration")] public void Find_ReturnsPayPalAccountByToken() { Result<Customer> customerResult = gateway.Customer.Create(new CustomerRequest()); Assert.IsTrue(customerResult.IsSuccess()); var request = new PaymentMethodRequest { CustomerId = customerResult.Target.Id, PaymentMethodNonce = Nonce.PayPalFuturePayment }; Result<PaymentMethod> result = gateway.PaymentMethod.Create(request); Assert.IsTrue(result.IsSuccess()); Assert.IsNotNull(result.Target.ImageUrl); PayPalAccount found = gateway.PayPalAccount.Find(result.Target.Token); Assert.IsNotNull(found); Assert.IsNotNull(found.Email); Assert.IsNotNull(found.ImageUrl); Assert.IsNotNull(found.CreatedAt); Assert.IsNotNull(found.UpdatedAt); Assert.AreEqual(found.Email, ((PayPalAccount) result.Target).Email); } [Test] [Category("Integration")] [ExpectedException(typeof(NotFoundException))] public void Find_RaisesNotFoundErrorForUnknownToken() { gateway.PayPalAccount.Find(" "); } [Test] [Category("Integration")] [ExpectedException(typeof(NotFoundException))] public void Find_RaisesNotFoundErrorForCreditCardToken() { var createRequest = new CustomerRequest { CreditCard = new CreditCardRequest { Number = "5105105105105100", ExpirationDate = "05/12", CVV = "123", } }; Customer customer = gateway.Customer.Create(createRequest).Target; gateway.PayPalAccount.Find(customer.CreditCards[0].Token); } [Test] [Category("Integration")] public void Delete_ReturnsPayPalAccountByToken() { Result<Customer> customerResult = gateway.Customer.Create(new CustomerRequest()); Assert.IsTrue(customerResult.IsSuccess()); var request = new PaymentMethodRequest { CustomerId = customerResult.Target.Id, PaymentMethodNonce = Nonce.PayPalFuturePayment }; Result<PaymentMethod> result = gateway.PaymentMethod.Create(request); Assert.IsTrue(result.IsSuccess()); gateway.PayPalAccount.Delete(result.Target.Token); } [Test] [Category("Integration")] [ExpectedException(typeof(NotFoundException))] public void Delete_RaisesNotFoundErrorForUnknownToken() { gateway.PayPalAccount.Delete(" "); } [Test] [Category("Integration")] public void Update_CanUpdateToken() { Result<Customer> customerResult = gateway.Customer.Create(new CustomerRequest()); Assert.IsTrue(customerResult.IsSuccess()); var request = new PaymentMethodRequest { CustomerId = customerResult.Target.Id, PaymentMethodNonce = Nonce.PayPalFuturePayment }; Result<PaymentMethod> result = gateway.PaymentMethod.Create(request); Assert.IsTrue(result.IsSuccess()); string newToken = Guid.NewGuid().ToString(); var updateRequest = new PayPalAccountRequest { Token = newToken }; var updateResult = gateway.PayPalAccount.Update(result.Target.Token, updateRequest); Assert.IsTrue(updateResult.IsSuccess()); Assert.AreEqual(newToken, updateResult.Target.Token); } [Test] [Category("Integration")] public void Update_CanMakeDefault() { Result<Customer> customerResult = gateway.Customer.Create(new CustomerRequest()); Assert.IsTrue(customerResult.IsSuccess()); var creditCardRequest = new CreditCardRequest { CustomerId = customerResult.Target.Id, Number = "5105105105105100", ExpirationDate = "05/12" }; CreditCard creditCard = gateway.CreditCard.Create(creditCardRequest).Target; Assert.IsTrue(creditCard.IsDefault.Value); var request = new PaymentMethodRequest { CustomerId = customerResult.Target.Id, PaymentMethodNonce = Nonce.PayPalFuturePayment }; Result<PaymentMethod> result = gateway.PaymentMethod.Create(request); Assert.IsTrue(result.IsSuccess()); var updateRequest = new PayPalAccountRequest { Options = new PayPalOptionsRequest { MakeDefault = true } }; var updateResult = gateway.PayPalAccount.Update(result.Target.Token, updateRequest); Assert.IsTrue(updateResult.IsSuccess()); Assert.IsTrue(updateResult.Target.IsDefault.Value); } [Test] [Category("Integration")] public void ReturnsSubscriptionsAssociatedWithPayPalAccount() { var customer = gateway.Customer.Create().Target; var paymentMethodToken = string.Format("paypal-account-{0}", DateTime.Now.Ticks); var nonce = TestHelper.GetNonceForPayPalAccount( gateway, new Params { { "consent_code", "consent-code" }, { "token", paymentMethodToken } }); var result = gateway.PaymentMethod.Create(new PaymentMethodRequest { PaymentMethodNonce = nonce, CustomerId = customer.Id }); Assert.IsTrue(result.IsSuccess()); var token = result.Target.Token; var subscription1 = gateway.Subscription.Create(new SubscriptionRequest { PaymentMethodToken = token, PlanId = PlanFixture.PLAN_WITHOUT_TRIAL.Id }).Target; var subscription2 = gateway.Subscription.Create(new SubscriptionRequest { PaymentMethodToken = token, PlanId = PlanFixture.PLAN_WITHOUT_TRIAL.Id }).Target; var paypalAccount = gateway.PayPalAccount.Find(token); Assert.IsNotNull(paypalAccount); var ids = from s in new Subscription[] { subscription1, subscription2 } orderby s.Id select s.Id; var accountSubscriptionIds = from s in paypalAccount.Subscriptions orderby s.Id select s.Id; Assert.IsTrue(ids.SequenceEqual(accountSubscriptionIds)); } [Test] [Category("Integration")] public void ReturnsBillingAgreementIdWithPayPalAccount() { var customer = gateway.Customer.Create().Target; var result = gateway.PaymentMethod.Create(new PaymentMethodRequest { PaymentMethodNonce = Nonce.PayPalBillingAgreement, CustomerId = customer.Id }); Assert.IsTrue(result.IsSuccess()); Assert.IsFalse(string.IsNullOrEmpty(result.Target.Token)); var paypalAccount = gateway.PayPalAccount.Find(result.Target.Token); Assert.IsNotNull(paypalAccount.BillingAgreementId); } } }
/* * Magix - A Web Application Framework for Humans * Copyright 2010 - 2014 - [email protected] * Magix is licensed as MITx11, see enclosed License.txt File for Details. */ using System; using System.Globalization; using System.Collections.Generic; namespace Magix.Core { /* * implements expressions */ public class Expressions { /* * returns expression value */ public static T GetExpressionValue<T>(string expression, Node dp, Node ip, bool createPath, T defaultValue) { T retVal = GetExpressionValue<T>(expression, dp, ip, createPath); if (retVal == null || retVal.Equals(default(T))) return defaultValue; return retVal; } /* * returns expression value */ public static T GetExpressionValue<T>(string expression, Node dp, Node ip, bool createPath) { object retVal = GetExpressionValue(expression, dp, ip, createPath); if (retVal == null) return default(T); if (typeof(T) != retVal.GetType()) { switch (typeof(T).FullName) { case "System.Int32": return (T)(object)int.Parse(GetString(retVal), CultureInfo.InvariantCulture); case "System.Boolean": return (T)(object)bool.Parse(GetString(retVal)); case "System.Decimal": return (T)(object)decimal.Parse(GetString(retVal), CultureInfo.InvariantCulture); case "System.DateTime": return (T)(object)DateTime.ParseExact(GetString(retVal), "yyyy.MM.dd HH:mm:ss", CultureInfo.InvariantCulture); case "System.String": return (T)(object)GetString(retVal); default: if (retVal is T) return (T)retVal; throw new ArgumentException("cannot convert expression to given type; " + typeof(T).Name); } } return (T)retVal; } /* * helper for above */ private static string GetString(object value) { switch (value.GetType().FullName) { case "System.Int32": return value.ToString(); case "System.Boolean": return value.ToString(); case "System.Decimal": return ((decimal)value).ToString(CultureInfo.InvariantCulture); case "System.DateTime": return ((DateTime)value).ToString("yyyy.MM.dd HH:mm:ss", CultureInfo.InvariantCulture); default: return value.ToString(); } } /* * returns expression value */ private static object GetExpressionValue(string expression, Node dp, Node ip, bool createPath) { if (expression == null) return null; // Checking to see if this is an escaped expression if (expression.StartsWith("\\") && expression.Length > 1 && expression[1] == '[') return expression.Substring(1); if (!expression.TrimStart().StartsWith("[")) return expression; string lastEntity = ""; Node x = GetNode(expression, dp, ip, ref lastEntity, createPath); if (x == null) return null; object retVal = null; if (lastEntity.StartsWith(".value")) retVal = x.Value; else if (lastEntity.StartsWith(".name")) retVal = x.Name; else if (lastEntity.StartsWith(".count")) retVal = x.Count; else if (lastEntity.StartsWith(".dna")) retVal = x.Dna; else if (lastEntity == "") retVal = x; return retVal; } /* * returns the formatted value of an expression, if the expression exist, or else defaultValue */ public static string GetFormattedExpression(string childName, Node pars, string defaultValue) { Node ip = pars; if (pars.ContainsValue("_ip")) ip = pars["_ip"].Get<Node>(); Node dp = pars; if (pars.ContainsValue("_dp")) dp = pars["_dp"].Get<Node>(); return GetFormattedExpression(childName, dp, ip, defaultValue); } /* * returns the formatted value of an expression, if the expression exist, or else defaultValue */ private static string GetFormattedExpression(string childName, Node dp, Node ip, string defaultValue) { if (ip.ContainsValue(childName)) { string expressionValue = GetExpressionValue<string>(ip[childName].Get<string>(), dp, ip, false); if (ip[childName].Count > 0) { return FormatString(dp, ip, ip[childName], expressionValue); } return expressionValue; } return defaultValue; } /* * formats a string with its children nodes */ public static string FormatString(Node dp, Node ip, Node contentNode, string valueToSet) { object[] arrs = new object[contentNode.Count]; int idxNo = 0; foreach (Node idx in contentNode) { if (idx.Count > 0) arrs[idxNo++] = FormatString(dp, ip, idx, idx.Get<string>()); else arrs[idxNo++] = Expressions.GetExpressionValue<string>(idx.Get<string>(), dp, ip, false); } return string.Format(CultureInfo.InvariantCulture, valueToSet.ToString(), arrs); } /* * sets an expression */ public static void SetNodeValue( string destinationExpression, string sourceExpression, Node dp, Node ip, bool noRemove) { object valueToSet = GetExpressionValue(sourceExpression, dp, ip, false); // checking to see if this is a string.Format expression if (ip.Contains("value") && ip["value"].Count > 0) { valueToSet = FormatString(dp, ip, ip["value"], valueToSet.ToString()); } if (valueToSet == null && !noRemove) { // Removing node or value string lastEntity = ""; Node destinationNode = GetNode(destinationExpression, dp, ip, ref lastEntity, false); if (destinationNode == null) return; if (lastEntity == ".value") destinationNode.Value = null; else if (lastEntity == ".name") destinationNode.Name = ""; else if (lastEntity == "") destinationNode.UnTie(); else if (lastEntity == ".dna") throw new ArgumentException("you cannot change a node's dna"); else throw new ArgumentException("couldn't understand the last parts of your expression '" + lastEntity + "'"); } else { string lastEntity = ".value"; Node destinationNode = ip; if (destinationExpression != null) destinationNode = GetNode(destinationExpression, dp, ip, ref lastEntity, true); if (lastEntity.StartsWith(".value")) { if (valueToSet is Node) { valueToSet = (valueToSet as Node).Clone(); // to make sure we can add nodes as values into the same nodes, recursively ... // we must create a root node, to conform with the api for serializing nodes // such that when we assign a node's value to be another node, we actually add a // non-existing parent node, and not the node itself in fact Node tmpNode = new Node(); tmpNode.Add(valueToSet as Node); valueToSet = tmpNode; } destinationNode.Value = valueToSet; } else if (lastEntity.StartsWith(".name")) { if (!(valueToSet is string)) throw new ArgumentException("cannot set the name of a node to something which is not a string literal"); destinationNode.Name = valueToSet.ToString(); } else if (lastEntity.StartsWith(".dna")) { throw new ArgumentException("cannot change the dna of a node"); } else if (lastEntity == "") { if (!(valueToSet is Node)) throw new ArgumentException("you can only set a node-list to another node-list, and not a string or some other constant value"); Node clone = (valueToSet as Node).Clone(); destinationNode.Clear(); destinationNode.AddRange(clone); destinationNode.Name = clone.Name; destinationNode.Value = clone.Value; } else throw new ArgumentException("couldn't understand the last parts of your expression '" + lastEntity + "'"); } } // Helper for finding nodes private static Node GetNode( string expr, Node dp, Node ip, ref string lastEntity, bool forcePath) { Node idxNode = dp; bool isInside = false; int noBraces = 0; string bufferNodeName = null; lastEntity = null; for (int idx = 0; idx < expr.Length; idx++) { char tmp = expr[idx]; if (isInside) { if (tmp == '[' && string.IsNullOrEmpty(bufferNodeName)) { // Nested statement // Spooling forward to end of nested statement string entireSubStatement = ""; int braceIndex = 0; for (; idx < expr.Length; idx++) { if (expr[idx] == '[') braceIndex += 1; else if (expr[idx] == ']') braceIndex -= 1; if (braceIndex == -1) break; entireSubStatement += expr[idx]; } object innerVal = GetExpressionValue(entireSubStatement, dp, ip, false); if (innerVal == null) throw new ArgumentException("subexpression failed, expression was; " + entireSubStatement); tmp = ']'; // to sucker into ending of logic bufferNodeName = innerVal.ToString(); } if (tmp == '[') noBraces += 1; if (tmp == ']' && --noBraces == 0) { isInside = false; lastEntity = ""; bool allNumber = !string.IsNullOrEmpty(bufferNodeName); if (bufferNodeName == "..") { // One up! if (idxNode.Parent == null) return null; idxNode = idxNode.Parent; } else if (bufferNodeName == "/") { idxNode = idxNode.RootNode(); } else if (bufferNodeName == ">last") { idxNode = idxNode[idxNode.Count - 1]; } else if (bufferNodeName == "$") { if (forcePath) idxNode = dp.RootNode()["$"]; else { if (dp.RootNode().Contains("$")) idxNode = dp.RootNode()["$"]; else return null; } } else if (bufferNodeName == ".ip") { idxNode = ip; } else if (bufferNodeName == "@") { idxNode = ip.Parent; } else if (bufferNodeName == ".") { idxNode = dp; } else if (bufferNodeName.StartsWith(":>")) { // dna reference string dna = bufferNodeName.Substring(2); idxNode = idxNode.RootNode().FindDna(dna); } else if (bufferNodeName.StartsWith(":")) { // active event reference string activeEvent = bufferNodeName.Substring(1); Node newDataNode = null; if (activeEvent.Contains("[")) { string acNodeExpression = activeEvent.Substring(activeEvent.IndexOf('[')); newDataNode = GetExpressionValue(acNodeExpression, dp, ip, false) as Node; if (newDataNode == null) throw new ArgumentException("cannot pass a null node into an expression active event"); newDataNode = newDataNode.Clone(); activeEvent = activeEvent.Substring(0, activeEvent.IndexOf('[')); } Node exeNode = new Node(null, null); if (newDataNode != null) exeNode[activeEvent].AddRange(newDataNode); else exeNode[activeEvent].Value = null; Node invokeNode = new Node(); invokeNode["_ip"].Value = exeNode; invokeNode["_dp"].Value = exeNode; ActiveEvents.Instance.RaiseActiveEvent( typeof(Expressions), "magix.execute", invokeNode); idxNode = exeNode[activeEvent]; } else if (bufferNodeName.StartsWith("**")) { // deep wildcard search string searchValue = null; string searchName = null; if (bufferNodeName.Contains("=>")) { if (bufferNodeName.IndexOf("=>") > 2) { searchName = bufferNodeName.Substring(2).Split(new string[] { "=>" }, StringSplitOptions.RemoveEmptyEntries)[0]; if (searchName.StartsWith("[")) { // inner expression, fetching result searchName = GetExpressionValue<string>(searchName, dp, ip, false); } } else searchName = ""; if (bufferNodeName.IndexOf("=>") < bufferNodeName.Length - 2) { searchValue = bufferNodeName.Split(new string[] { "=>" }, StringSplitOptions.RemoveEmptyEntries)[1]; if (searchValue.StartsWith("[")) { // inner expression, fetching result searchValue = GetExpressionValue<string>(searchValue, dp, ip, false); } } else searchValue = ""; } else { if (bufferNodeName.Length > 2) { searchName = bufferNodeName.Substring(2); if (searchName.StartsWith("[")) { // inner expression, fetching result searchName = GetExpressionValue<string>(searchName, dp, ip, false); } } } Node searchNode = FindNode(idxNode, searchName, searchValue); if (searchNode == null && forcePath) { if (searchName == "?") searchName = ""; if (searchValue == "?") searchValue = ""; idxNode.Add(new Node(searchName ?? "", searchValue)); idxNode = idxNode[idxNode.Count - 1]; } else if (searchNode == null) throw new ArgumentException("couldn't find node in expression"); else idxNode = searchNode; } else if (bufferNodeName.StartsWith("?")) { // wildcard search string searchValue = null; if (bufferNodeName.Contains("=>")) { string[] tmpSearch = bufferNodeName.Split(new string[] { "=>" }, StringSplitOptions.RemoveEmptyEntries); if (tmpSearch.Length == 1) searchValue = ""; else { searchValue = tmpSearch[1]; if (searchValue.StartsWith("[")) { // inner expression, fetching result searchValue = GetExpressionValue<string>(searchValue, dp, ip, false); } } } bool found = false; foreach (Node idxInnerNode in idxNode) { if (searchValue == idxInnerNode.Get<string>()) { found = true; idxNode = idxInnerNode; break; } } if (!found && forcePath) { idxNode.Add(new Node("", searchValue)); idxNode = idxNode[idxNode.Count - 1]; } else if (!found) throw new ArgumentException("couldn't find node in expression"); } else if (bufferNodeName.Contains("=>")) { string[] splits = bufferNodeName.Split(new string[] { "=>" }, StringSplitOptions.None); string name = splits[0]; if (name.StartsWith("[")) { // inner expression, fetching result name = GetExpressionValue<string>(name, dp, ip, false); } string value = splits[1]; if (value.StartsWith("[")) { // inner expression, fetching result value = GetExpressionValue<string>(value, dp, ip, false); } bool foundNode = false; foreach (Node idxInnerNode in idxNode) { if (idxInnerNode.Name == name && idxInnerNode.Get<string>() == value) { idxNode = idxInnerNode; foundNode = true; break; } } if (!foundNode) { // didn't find criteria if (!forcePath) return null; // creating node with given value idxNode.Add(new Node(name, value)); idxNode = idxNode[idxNode.Count - 1]; } } else if (bufferNodeName.Contains(":")) { int idxNo = int.Parse(bufferNodeName.Split(':')[1].TrimStart()); int curNo = 0; int totIdx = 0; bool found = false; bufferNodeName = bufferNodeName.Split(':')[0].TrimEnd(); foreach (Node idxInnerNode in idxNode) { if (idxInnerNode.Name == bufferNodeName) { if (curNo++ == idxNo) { found = true; idxNode = idxNode[totIdx]; break; } } totIdx += 1; } if (!found) { if (forcePath) { while (idxNo >= curNo++) { idxNode.Add(new Node(bufferNodeName)); } idxNode = idxNode[idxNode.Count - 1]; } else return null; } } else { foreach (char idxC in bufferNodeName) { if (("0123456789").IndexOf(idxC) == -1) { allNumber = false; break; } } if (allNumber) { int intIdx = int.Parse(bufferNodeName); if (idxNode.Count > intIdx) idxNode = idxNode[intIdx]; else if (forcePath) { while (idxNode.Count <= intIdx) { idxNode.Add(new Node("item")); } idxNode = idxNode[intIdx]; } else return null; } else { if (idxNode.Contains(bufferNodeName)) idxNode = idxNode[bufferNodeName]; else if (forcePath) { idxNode = idxNode[bufferNodeName]; } else { return null; } } } bufferNodeName = ""; } else bufferNodeName += tmp; } else { if (tmp == '[' && string.IsNullOrEmpty(lastEntity)) { if (++noBraces == 1) isInside = true; else bufferNodeName += tmp; } else lastEntity += tmp; } } if (lastEntity.StartsWith(".value") && lastEntity.Length > 6) { // this is a concatenated expression, returning a Node list, where we wish to directly // access another node inside of the node by reference string innerLastReference = ""; Node x2 = idxNode.Get<Node>(); if (x2 == null) { // value of node is probably a string, try to convert it to a node first Node tmpNode = new Node(); tmpNode["code"].Value = idxNode.Get<string>(); ActiveEvents.Instance.RaiseActiveEvent( typeof (Expressions), "magix.execute.code-2-node", tmpNode); x2 = tmpNode["node"].Clone(); } idxNode = GetNode(lastEntity.Substring(6), x2, x2, ref innerLastReference, forcePath); lastEntity = innerLastReference; } return idxNode; } private static Node FindNode(Node currentNode, string searchName, string searchValue) { bool foundName = false; if (searchName == "?") foundName = true; else if (currentNode.Name == searchName) foundName = true; bool foundValue = false; if (searchValue == "?") foundValue = true; else if (searchValue == currentNode.Get<string>()) foundValue = true; if (foundValue && foundName) return currentNode; foreach (Node idx in currentNode) { Node tmp = FindNode(idx, searchName, searchValue); if (tmp != null) return tmp; } return null; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Globalization; using System.Runtime.InteropServices; using Xunit; namespace System.Numerics.Tests { public class QuaternionTests { // A test for Dot (Quaternion, Quaternion) [Fact] public void QuaternionDotTest() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); Quaternion b = new Quaternion(5.0f, 6.0f, 7.0f, 8.0f); float expected = 70.0f; float actual; actual = Quaternion.Dot(a, b); Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Dot did not return the expected value."); } // A test for Length () [Fact] public void QuaternionLengthTest() { Vector3 v = new Vector3(1.0f, 2.0f, 3.0f); float w = 4.0f; Quaternion target = new Quaternion(v, w); float expected = 5.477226f; float actual; actual = target.Length(); Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Length did not return the expected value."); } // A test for LengthSquared () [Fact] public void QuaternionLengthSquaredTest() { Vector3 v = new Vector3(1.0f, 2.0f, 3.0f); float w = 4.0f; Quaternion target = new Quaternion(v, w); float expected = 30.0f; float actual; actual = target.LengthSquared(); Assert.True(MathHelper.Equal(expected, actual), "Quaternion.LengthSquared did not return the expected value."); } // A test for Lerp (Quaternion, Quaternion, float) [Fact] public void QuaternionLerpTest() { Vector3 axis = Vector3.Normalize(new Vector3(1.0f, 2.0f, 3.0f)); Quaternion a = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(10.0f)); Quaternion b = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(30.0f)); float t = 0.5f; Quaternion expected = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(20.0f)); Quaternion actual; actual = Quaternion.Lerp(a, b, t); Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Lerp did not return the expected value."); // Case a and b are same. expected = a; actual = Quaternion.Lerp(a, a, t); Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Lerp did not return the expected value."); } // A test for Lerp (Quaternion, Quaternion, float) // Lerp test when t = 0 [Fact] public void QuaternionLerpTest1() { Vector3 axis = Vector3.Normalize(new Vector3(1.0f, 2.0f, 3.0f)); Quaternion a = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(10.0f)); Quaternion b = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(30.0f)); float t = 0.0f; Quaternion expected = new Quaternion(a.X, a.Y, a.Z, a.W); Quaternion actual = Quaternion.Lerp(a, b, t); Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Lerp did not return the expected value."); } // A test for Lerp (Quaternion, Quaternion, float) // Lerp test when t = 1 [Fact] public void QuaternionLerpTest2() { Vector3 axis = Vector3.Normalize(new Vector3(1.0f, 2.0f, 3.0f)); Quaternion a = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(10.0f)); Quaternion b = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(30.0f)); float t = 1.0f; Quaternion expected = new Quaternion(b.X, b.Y, b.Z, b.W); Quaternion actual = Quaternion.Lerp(a, b, t); Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Lerp did not return the expected value."); } // A test for Lerp (Quaternion, Quaternion, float) // Lerp test when the two quaternions are more than 90 degree (dot product <0) [Fact] public void QuaternionLerpTest3() { Vector3 axis = Vector3.Normalize(new Vector3(1.0f, 2.0f, 3.0f)); Quaternion a = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(10.0f)); Quaternion b = Quaternion.Negate(a); float t = 1.0f; Quaternion actual = Quaternion.Lerp(a, b, t); // Note that in quaternion world, Q == -Q. In the case of quaternions dot product is zero, // one of the quaternion will be flipped to compute the shortest distance. When t = 1, we // expect the result to be the same as quaternion b but flipped. Assert.True(actual == a, "Quaternion.Lerp did not return the expected value."); } // A test for Conjugate(Quaternion) [Fact] public void QuaternionConjugateTest1() { Quaternion a = new Quaternion(1, 2, 3, 4); Quaternion expected = new Quaternion(-1, -2, -3, 4); Quaternion actual; actual = Quaternion.Conjugate(a); Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Conjugate did not return the expected value."); } // A test for Normalize (Quaternion) [Fact] public void QuaternionNormalizeTest() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); Quaternion expected = new Quaternion(0.182574168f, 0.365148336f, 0.5477225f, 0.7302967f); Quaternion actual; actual = Quaternion.Normalize(a); Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Normalize did not return the expected value."); } // A test for Normalize (Quaternion) // Normalize zero length quaternion [Fact] public void QuaternionNormalizeTest1() { Quaternion a = new Quaternion(0.0f, 0.0f, -0.0f, 0.0f); Quaternion actual = Quaternion.Normalize(a); Assert.True(float.IsNaN(actual.X) && float.IsNaN(actual.Y) && float.IsNaN(actual.Z) && float.IsNaN(actual.W) , "Quaternion.Normalize did not return the expected value."); } // A test for Concatenate(Quaternion, Quaternion) [Fact] public void QuaternionConcatenateTest1() { Quaternion b = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); Quaternion a = new Quaternion(5.0f, 6.0f, 7.0f, 8.0f); Quaternion expected = new Quaternion(24.0f, 48.0f, 48.0f, -6.0f); Quaternion actual; actual = Quaternion.Concatenate(a, b); Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Concatenate did not return the expected value."); } // A test for operator - (Quaternion, Quaternion) [Fact] public void QuaternionSubtractionTest() { Quaternion a = new Quaternion(1.0f, 6.0f, 7.0f, 4.0f); Quaternion b = new Quaternion(5.0f, 2.0f, 3.0f, 8.0f); Quaternion expected = new Quaternion(-4.0f, 4.0f, 4.0f, -4.0f); Quaternion actual; actual = a - b; Assert.True(MathHelper.Equal(expected, actual), "Quaternion.operator - did not return the expected value."); } // A test for operator * (Quaternion, float) [Fact] public void QuaternionMultiplyTest() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); float factor = 0.5f; Quaternion expected = new Quaternion(0.5f, 1.0f, 1.5f, 2.0f); Quaternion actual; actual = a * factor; Assert.True(MathHelper.Equal(expected, actual), "Quaternion.operator * did not return the expected value."); } // A test for operator * (Quaternion, Quaternion) [Fact] public void QuaternionMultiplyTest1() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); Quaternion b = new Quaternion(5.0f, 6.0f, 7.0f, 8.0f); Quaternion expected = new Quaternion(24.0f, 48.0f, 48.0f, -6.0f); Quaternion actual; actual = a * b; Assert.True(MathHelper.Equal(expected, actual), "Quaternion.operator * did not return the expected value."); } // A test for operator / (Quaternion, Quaternion) [Fact] public void QuaternionDivisionTest1() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); Quaternion b = new Quaternion(5.0f, 6.0f, 7.0f, 8.0f); Quaternion expected = new Quaternion(-0.045977015f, -0.09195402f, -7.450581E-9f, 0.402298868f); Quaternion actual; actual = a / b; Assert.True(MathHelper.Equal(expected, actual), "Quaternion.operator / did not return the expected value."); } // A test for operator + (Quaternion, Quaternion) [Fact] public void QuaternionAdditionTest() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); Quaternion b = new Quaternion(5.0f, 6.0f, 7.0f, 8.0f); Quaternion expected = new Quaternion(6.0f, 8.0f, 10.0f, 12.0f); Quaternion actual; actual = a + b; Assert.True(MathHelper.Equal(expected, actual), "Quaternion.operator + did not return the expected value."); } // A test for Quaternion (float, float, float, float) [Fact] public void QuaternionConstructorTest() { float x = 1.0f; float y = 2.0f; float z = 3.0f; float w = 4.0f; Quaternion target = new Quaternion(x, y, z, w); Assert.True(MathHelper.Equal(target.X, x) && MathHelper.Equal(target.Y, y) && MathHelper.Equal(target.Z, z) && MathHelper.Equal(target.W, w), "Quaternion.constructor (x,y,z,w) did not return the expected value."); } // A test for Quaternion (Vector3f, float) [Fact] public void QuaternionConstructorTest1() { Vector3 v = new Vector3(1.0f, 2.0f, 3.0f); float w = 4.0f; Quaternion target = new Quaternion(v, w); Assert.True(MathHelper.Equal(target.X, v.X) && MathHelper.Equal(target.Y, v.Y) && MathHelper.Equal(target.Z, v.Z) && MathHelper.Equal(target.W, w), "Quaternion.constructor (Vector3f,w) did not return the expected value."); } // A test for CreateFromAxisAngle (Vector3f, float) [Fact] public void QuaternionCreateFromAxisAngleTest() { Vector3 axis = Vector3.Normalize(new Vector3(1.0f, 2.0f, 3.0f)); float angle = MathHelper.ToRadians(30.0f); Quaternion expected = new Quaternion(0.0691723f, 0.1383446f, 0.207516879f, 0.9659258f); Quaternion actual; actual = Quaternion.CreateFromAxisAngle(axis, angle); Assert.True(MathHelper.Equal(expected, actual), "Quaternion.CreateFromAxisAngle did not return the expected value."); } // A test for CreateFromAxisAngle (Vector3f, float) // CreateFromAxisAngle of zero vector [Fact] public void QuaternionCreateFromAxisAngleTest1() { Vector3 axis = new Vector3(); float angle = MathHelper.ToRadians(-30.0f); float cos = (float)System.Math.Cos(angle / 2.0f); Quaternion actual = Quaternion.CreateFromAxisAngle(axis, angle); Assert.True(actual.X == 0.0f && actual.Y == 0.0f && actual.Z == 0.0f && MathHelper.Equal(cos, actual.W) , "Quaternion.CreateFromAxisAngle did not return the expected value."); } // A test for CreateFromAxisAngle (Vector3f, float) // CreateFromAxisAngle of angle = 30 && 750 [Fact] public void QuaternionCreateFromAxisAngleTest2() { Vector3 axis = new Vector3(1, 0, 0); float angle1 = MathHelper.ToRadians(30.0f); float angle2 = MathHelper.ToRadians(750.0f); Quaternion actual1 = Quaternion.CreateFromAxisAngle(axis, angle1); Quaternion actual2 = Quaternion.CreateFromAxisAngle(axis, angle2); Assert.True(MathHelper.Equal(actual1, actual2), "Quaternion.CreateFromAxisAngle did not return the expected value."); } // A test for CreateFromAxisAngle (Vector3f, float) // CreateFromAxisAngle of angle = 30 && 390 [Fact] public void QuaternionCreateFromAxisAngleTest3() { Vector3 axis = new Vector3(1, 0, 0); float angle1 = MathHelper.ToRadians(30.0f); float angle2 = MathHelper.ToRadians(390.0f); Quaternion actual1 = Quaternion.CreateFromAxisAngle(axis, angle1); Quaternion actual2 = Quaternion.CreateFromAxisAngle(axis, angle2); actual1.X = -actual1.X; actual1.W = -actual1.W; Assert.True(MathHelper.Equal(actual1, actual2), "Quaternion.CreateFromAxisAngle did not return the expected value."); } [Fact] public void QuaternionCreateFromYawPitchRollTest1() { float yawAngle = MathHelper.ToRadians(30.0f); float pitchAngle = MathHelper.ToRadians(40.0f); float rollAngle = MathHelper.ToRadians(50.0f); Quaternion yaw = Quaternion.CreateFromAxisAngle(Vector3.UnitY, yawAngle); Quaternion pitch = Quaternion.CreateFromAxisAngle(Vector3.UnitX, pitchAngle); Quaternion roll = Quaternion.CreateFromAxisAngle(Vector3.UnitZ, rollAngle); Quaternion expected = yaw * pitch * roll; Quaternion actual = Quaternion.CreateFromYawPitchRoll(yawAngle, pitchAngle, rollAngle); Assert.True(MathHelper.Equal(expected, actual)); } // Covers more numeric rigions [Fact] public void QuaternionCreateFromYawPitchRollTest2() { const float step = 35.0f; for (float yawAngle = -720.0f; yawAngle <= 720.0f; yawAngle += step) { for (float pitchAngle = -720.0f; pitchAngle <= 720.0f; pitchAngle += step) { for (float rollAngle = -720.0f; rollAngle <= 720.0f; rollAngle += step) { float yawRad = MathHelper.ToRadians(yawAngle); float pitchRad = MathHelper.ToRadians(pitchAngle); float rollRad = MathHelper.ToRadians(rollAngle); Quaternion yaw = Quaternion.CreateFromAxisAngle(Vector3.UnitY, yawRad); Quaternion pitch = Quaternion.CreateFromAxisAngle(Vector3.UnitX, pitchRad); Quaternion roll = Quaternion.CreateFromAxisAngle(Vector3.UnitZ, rollRad); Quaternion expected = yaw * pitch * roll; Quaternion actual = Quaternion.CreateFromYawPitchRoll(yawRad, pitchRad, rollRad); Assert.True(MathHelper.Equal(expected, actual), String.Format("Yaw:{0} Pitch:{1} Roll:{2}", yawAngle, pitchAngle, rollAngle)); } } } } // A test for Slerp (Quaternion, Quaternion, float) [Fact] public void QuaternionSlerpTest() { Vector3 axis = Vector3.Normalize(new Vector3(1.0f, 2.0f, 3.0f)); Quaternion a = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(10.0f)); Quaternion b = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(30.0f)); float t = 0.5f; Quaternion expected = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(20.0f)); Quaternion actual; actual = Quaternion.Slerp(a, b, t); Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Slerp did not return the expected value."); // Case a and b are same. expected = a; actual = Quaternion.Slerp(a, a, t); Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Slerp did not return the expected value."); } // A test for Slerp (Quaternion, Quaternion, float) // Slerp test where t = 0 [Fact] public void QuaternionSlerpTest1() { Vector3 axis = Vector3.Normalize(new Vector3(1.0f, 2.0f, 3.0f)); Quaternion a = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(10.0f)); Quaternion b = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(30.0f)); float t = 0.0f; Quaternion expected = new Quaternion(a.X, a.Y, a.Z, a.W); Quaternion actual = Quaternion.Slerp(a, b, t); Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Slerp did not return the expected value."); } // A test for Slerp (Quaternion, Quaternion, float) // Slerp test where t = 1 [Fact] public void QuaternionSlerpTest2() { Vector3 axis = Vector3.Normalize(new Vector3(1.0f, 2.0f, 3.0f)); Quaternion a = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(10.0f)); Quaternion b = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(30.0f)); float t = 1.0f; Quaternion expected = new Quaternion(b.X, b.Y, b.Z, b.W); Quaternion actual = Quaternion.Slerp(a, b, t); Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Slerp did not return the expected value."); } // A test for Slerp (Quaternion, Quaternion, float) // Slerp test where dot product is < 0 [Fact] public void QuaternionSlerpTest3() { Vector3 axis = Vector3.Normalize(new Vector3(1.0f, 2.0f, 3.0f)); Quaternion a = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(10.0f)); Quaternion b = -a; float t = 1.0f; Quaternion expected = a; Quaternion actual = Quaternion.Slerp(a, b, t); // Note that in quaternion world, Q == -Q. In the case of quaternions dot product is zero, // one of the quaternion will be flipped to compute the shortest distance. When t = 1, we // expect the result to be the same as quaternion b but flipped. Assert.True(actual == expected, "Quaternion.Slerp did not return the expected value."); } // A test for Slerp (Quaternion, Quaternion, float) // Slerp test where the quaternion is flipped [Fact] public void QuaternionSlerpTest4() { Vector3 axis = Vector3.Normalize(new Vector3(1.0f, 2.0f, 3.0f)); Quaternion a = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(10.0f)); Quaternion b = -Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(30.0f)); float t = 0.0f; Quaternion expected = new Quaternion(a.X, a.Y, a.Z, a.W); Quaternion actual = Quaternion.Slerp(a, b, t); Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Slerp did not return the expected value."); } // A test for operator - (Quaternion) [Fact] public void QuaternionUnaryNegationTest() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); Quaternion expected = new Quaternion(-1.0f, -2.0f, -3.0f, -4.0f); Quaternion actual; actual = -a; Assert.True(MathHelper.Equal(expected, actual), "Quaternion.operator - did not return the expected value."); } // A test for Inverse (Quaternion) [Fact] public void QuaternionInverseTest() { Quaternion a = new Quaternion(5.0f, 6.0f, 7.0f, 8.0f); Quaternion expected = new Quaternion(-0.0287356321f, -0.03448276f, -0.0402298868f, 0.04597701f); Quaternion actual; actual = Quaternion.Inverse(a); Assert.Equal(expected, actual); } // A test for Inverse (Quaternion) // Invert zero length quaternion [Fact] public void QuaternionInverseTest1() { Quaternion a = new Quaternion(); Quaternion actual = Quaternion.Inverse(a); Assert.True(float.IsNaN(actual.X) && float.IsNaN(actual.Y) && float.IsNaN(actual.Z) && float.IsNaN(actual.W) ); } // A test for ToString () [Fact] public void QuaternionToStringTest() { Quaternion target = new Quaternion(-1.0f, 2.2f, 3.3f, -4.4f); string expected = string.Format(CultureInfo.CurrentCulture , "{{X:{0} Y:{1} Z:{2} W:{3}}}" , -1.0f, 2.2f, 3.3f, -4.4f); string actual = target.ToString(); Assert.Equal(expected, actual); } // A test for Add (Quaternion, Quaternion) [Fact] public void QuaternionAddTest() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); Quaternion b = new Quaternion(5.0f, 6.0f, 7.0f, 8.0f); Quaternion expected = new Quaternion(6.0f, 8.0f, 10.0f, 12.0f); Quaternion actual; actual = Quaternion.Add(a, b); Assert.Equal(expected, actual); } // A test for Divide (Quaternion, Quaternion) [Fact] public void QuaternionDivideTest() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); Quaternion b = new Quaternion(5.0f, 6.0f, 7.0f, 8.0f); Quaternion expected = new Quaternion(-0.045977015f, -0.09195402f, -7.450581E-9f, 0.402298868f); Quaternion actual; actual = Quaternion.Divide(a, b); Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Divide did not return the expected value."); } // A test for Equals (object) [Fact] public void QuaternionEqualsTest() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); Quaternion b = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); // case 1: compare between same values object obj = b; bool expected = true; bool actual = a.Equals(obj); Assert.Equal(expected, actual); // case 2: compare between different values b.X = 10.0f; obj = b; expected = false; actual = a.Equals(obj); Assert.Equal(expected, actual); // case 3: compare between different types. obj = new Vector4(); expected = false; actual = a.Equals(obj); Assert.Equal(expected, actual); // case 3: compare against null. obj = null; expected = false; actual = a.Equals(obj); Assert.Equal(expected, actual); } // A test for GetHashCode () [Fact] public void QuaternionGetHashCodeTest() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); int expected = a.X.GetHashCode() + a.Y.GetHashCode() + a.Z.GetHashCode() + a.W.GetHashCode(); int actual = a.GetHashCode(); Assert.Equal(expected, actual); } // A test for Multiply (Quaternion, float) [Fact] public void QuaternionMultiplyTest2() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); float factor = 0.5f; Quaternion expected = new Quaternion(0.5f, 1.0f, 1.5f, 2.0f); Quaternion actual; actual = Quaternion.Multiply(a, factor); Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Multiply did not return the expected value."); } // A test for Multiply (Quaternion, Quaternion) [Fact] public void QuaternionMultiplyTest3() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); Quaternion b = new Quaternion(5.0f, 6.0f, 7.0f, 8.0f); Quaternion expected = new Quaternion(24.0f, 48.0f, 48.0f, -6.0f); Quaternion actual; actual = Quaternion.Multiply(a, b); Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Multiply did not return the expected value."); } // A test for Negate (Quaternion) [Fact] public void QuaternionNegateTest() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); Quaternion expected = new Quaternion(-1.0f, -2.0f, -3.0f, -4.0f); Quaternion actual; actual = Quaternion.Negate(a); Assert.Equal(expected, actual); } // A test for Subtract (Quaternion, Quaternion) [Fact] public void QuaternionSubtractTest() { Quaternion a = new Quaternion(1.0f, 6.0f, 7.0f, 4.0f); Quaternion b = new Quaternion(5.0f, 2.0f, 3.0f, 8.0f); Quaternion expected = new Quaternion(-4.0f, 4.0f, 4.0f, -4.0f); Quaternion actual; actual = Quaternion.Subtract(a, b); Assert.Equal(expected, actual); } // A test for operator != (Quaternion, Quaternion) [Fact] public void QuaternionInequalityTest() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); Quaternion b = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); // case 1: compare between same values bool expected = false; bool actual = a != b; Assert.Equal(expected, actual); // case 2: compare between different values b.X = 10.0f; expected = true; actual = a != b; Assert.Equal(expected, actual); } // A test for operator == (Quaternion, Quaternion) [Fact] public void QuaternionEqualityTest() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); Quaternion b = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); // case 1: compare between same values bool expected = true; bool actual = a == b; Assert.Equal(expected, actual); // case 2: compare between different values b.X = 10.0f; expected = false; actual = a == b; Assert.Equal(expected, actual); } // A test for CreateFromRotationMatrix (Matrix4x4) // Convert Identity matrix test [Fact] public void QuaternionFromRotationMatrixTest1() { Matrix4x4 matrix = Matrix4x4.Identity; Quaternion expected = new Quaternion(0.0f, 0.0f, 0.0f, 1.0f); Quaternion actual = Quaternion.CreateFromRotationMatrix(matrix); Assert.True(MathHelper.Equal(expected, actual), "Quaternion.CreateFromRotationMatrix did not return the expected value."); // make sure convert back to matrix is same as we passed matrix. Matrix4x4 m2 = Matrix4x4.CreateFromQuaternion(actual); Assert.True(MathHelper.Equal(matrix, m2), "Quaternion.CreateFromRotationMatrix did not return the expected value."); } // A test for CreateFromRotationMatrix (Matrix4x4) // Convert X axis rotation matrix [Fact] public void QuaternionFromRotationMatrixTest2() { for (float angle = 0.0f; angle < 720.0f; angle += 10.0f) { Matrix4x4 matrix = Matrix4x4.CreateRotationX(angle); Quaternion expected = Quaternion.CreateFromAxisAngle(Vector3.UnitX, angle); Quaternion actual = Quaternion.CreateFromRotationMatrix(matrix); Assert.True(MathHelper.EqualRotation(expected, actual), string.Format("Quaternion.CreateFromRotationMatrix did not return the expected value. angle:{0} expected:{1} actual:{2}", angle.ToString(), expected.ToString(), actual.ToString())); // make sure convert back to matrix is same as we passed matrix. Matrix4x4 m2 = Matrix4x4.CreateFromQuaternion(actual); Assert.True(MathHelper.Equal(matrix, m2), string.Format("Quaternion.CreateFromRotationMatrix did not return the expected value. angle:{0} expected:{1} actual:{2}", angle.ToString(), matrix.ToString(), m2.ToString())); } } // A test for CreateFromRotationMatrix (Matrix4x4) // Convert Y axis rotation matrix [Fact] public void QuaternionFromRotationMatrixTest3() { for (float angle = 0.0f; angle < 720.0f; angle += 10.0f) { Matrix4x4 matrix = Matrix4x4.CreateRotationY(angle); Quaternion expected = Quaternion.CreateFromAxisAngle(Vector3.UnitY, angle); Quaternion actual = Quaternion.CreateFromRotationMatrix(matrix); Assert.True(MathHelper.EqualRotation(expected, actual), string.Format("Quaternion.CreateFromRotationMatrix did not return the expected value. angle:{0}", angle.ToString())); // make sure convert back to matrix is same as we passed matrix. Matrix4x4 m2 = Matrix4x4.CreateFromQuaternion(actual); Assert.True(MathHelper.Equal(matrix, m2), string.Format("Quaternion.CreateFromRotationMatrix did not return the expected value. angle:{0}", angle.ToString())); } } // A test for CreateFromRotationMatrix (Matrix4x4) // Convert Z axis rotation matrix [Fact] public void QuaternionFromRotationMatrixTest4() { for (float angle = 0.0f; angle < 720.0f; angle += 10.0f) { Matrix4x4 matrix = Matrix4x4.CreateRotationZ(angle); Quaternion expected = Quaternion.CreateFromAxisAngle(Vector3.UnitZ, angle); Quaternion actual = Quaternion.CreateFromRotationMatrix(matrix); Assert.True(MathHelper.EqualRotation(expected, actual), string.Format("Quaternion.CreateFromRotationMatrix did not return the expected value. angle:{0} expected:{1} actual:{2}", angle.ToString(), expected.ToString(), actual.ToString())); // make sure convert back to matrix is same as we passed matrix. Matrix4x4 m2 = Matrix4x4.CreateFromQuaternion(actual); Assert.True(MathHelper.Equal(matrix, m2), string.Format("Quaternion.CreateFromRotationMatrix did not return the expected value. angle:{0} expected:{1} actual:{2}", angle.ToString(), matrix.ToString(), m2.ToString())); } } // A test for CreateFromRotationMatrix (Matrix4x4) // Convert XYZ axis rotation matrix [Fact] public void QuaternionFromRotationMatrixTest5() { for (float angle = 0.0f; angle < 720.0f; angle += 10.0f) { Matrix4x4 matrix = Matrix4x4.CreateRotationX(angle) * Matrix4x4.CreateRotationY(angle) * Matrix4x4.CreateRotationZ(angle); Quaternion expected = Quaternion.CreateFromAxisAngle(Vector3.UnitZ, angle) * Quaternion.CreateFromAxisAngle(Vector3.UnitY, angle) * Quaternion.CreateFromAxisAngle(Vector3.UnitX, angle); Quaternion actual = Quaternion.CreateFromRotationMatrix(matrix); Assert.True(MathHelper.EqualRotation(expected, actual), string.Format("Quaternion.CreateFromRotationMatrix did not return the expected value. angle:{0} expected:{1} actual:{2}", angle.ToString(), expected.ToString(), actual.ToString())); // make sure convert back to matrix is same as we passed matrix. Matrix4x4 m2 = Matrix4x4.CreateFromQuaternion(actual); Assert.True(MathHelper.Equal(matrix, m2), string.Format("Quaternion.CreateFromRotationMatrix did not return the expected value. angle:{0} expected:{1} actual:{2}", angle.ToString(), matrix.ToString(), m2.ToString())); } } // A test for CreateFromRotationMatrix (Matrix4x4) // X axis is most large axis case [Fact] public void QuaternionFromRotationMatrixWithScaledMatrixTest1() { float angle = MathHelper.ToRadians(180.0f); Matrix4x4 matrix = Matrix4x4.CreateRotationY(angle) * Matrix4x4.CreateRotationZ(angle); Quaternion expected = Quaternion.CreateFromAxisAngle(Vector3.UnitZ, angle) * Quaternion.CreateFromAxisAngle(Vector3.UnitY, angle); Quaternion actual = Quaternion.CreateFromRotationMatrix(matrix); Assert.True(MathHelper.EqualRotation(expected, actual), "Quaternion.CreateFromRotationMatrix did not return the expected value."); // make sure convert back to matrix is same as we passed matrix. Matrix4x4 m2 = Matrix4x4.CreateFromQuaternion(actual); Assert.True(MathHelper.Equal(matrix, m2), "Quaternion.CreateFromRotationMatrix did not return the expected value."); } // A test for CreateFromRotationMatrix (Matrix4x4) // Y axis is most large axis case [Fact] public void QuaternionFromRotationMatrixWithScaledMatrixTest2() { float angle = MathHelper.ToRadians(180.0f); Matrix4x4 matrix = Matrix4x4.CreateRotationX(angle) * Matrix4x4.CreateRotationZ(angle); Quaternion expected = Quaternion.CreateFromAxisAngle(Vector3.UnitZ, angle) * Quaternion.CreateFromAxisAngle(Vector3.UnitX, angle); Quaternion actual = Quaternion.CreateFromRotationMatrix(matrix); Assert.True(MathHelper.EqualRotation(expected, actual), "Quaternion.CreateFromRotationMatrix did not return the expected value."); // make sure convert back to matrix is same as we passed matrix. Matrix4x4 m2 = Matrix4x4.CreateFromQuaternion(actual); Assert.True(MathHelper.Equal(matrix, m2), "Quaternion.CreateFromRotationMatrix did not return the expected value."); } // A test for CreateFromRotationMatrix (Matrix4x4) // Z axis is most large axis case [Fact] public void QuaternionFromRotationMatrixWithScaledMatrixTest3() { float angle = MathHelper.ToRadians(180.0f); Matrix4x4 matrix = Matrix4x4.CreateRotationX(angle) * Matrix4x4.CreateRotationY(angle); Quaternion expected = Quaternion.CreateFromAxisAngle(Vector3.UnitY, angle) * Quaternion.CreateFromAxisAngle(Vector3.UnitX, angle); Quaternion actual = Quaternion.CreateFromRotationMatrix(matrix); Assert.True(MathHelper.EqualRotation(expected, actual), "Quaternion.CreateFromRotationMatrix did not return the expected value."); // make sure convert back to matrix is same as we passed matrix. Matrix4x4 m2 = Matrix4x4.CreateFromQuaternion(actual); Assert.True(MathHelper.Equal(matrix, m2), "Quaternion.CreateFromRotationMatrix did not return the expected value."); } // A test for Equals (Quaternion) [Fact] public void QuaternionEqualsTest1() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); Quaternion b = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); // case 1: compare between same values bool expected = true; bool actual = a.Equals(b); Assert.Equal(expected, actual); // case 2: compare between different values b.X = 10.0f; expected = false; actual = a.Equals(b); Assert.Equal(expected, actual); } // A test for Identity [Fact] public void QuaternionIdentityTest() { Quaternion val = new Quaternion(0, 0, 0, 1); Assert.Equal(val, Quaternion.Identity); } // A test for IsIdentity [Fact] public void QuaternionIsIdentityTest() { Assert.True(Quaternion.Identity.IsIdentity); Assert.True(new Quaternion(0, 0, 0, 1).IsIdentity); Assert.False(new Quaternion(1, 0, 0, 1).IsIdentity); Assert.False(new Quaternion(0, 1, 0, 1).IsIdentity); Assert.False(new Quaternion(0, 0, 1, 1).IsIdentity); Assert.False(new Quaternion(0, 0, 0, 0).IsIdentity); } // A test for Quaternion comparison involving NaN values [Fact] public void QuaternionEqualsNanTest() { Quaternion a = new Quaternion(float.NaN, 0, 0, 0); Quaternion b = new Quaternion(0, float.NaN, 0, 0); Quaternion c = new Quaternion(0, 0, float.NaN, 0); Quaternion d = new Quaternion(0, 0, 0, float.NaN); Assert.False(a == new Quaternion(0, 0, 0, 0)); Assert.False(b == new Quaternion(0, 0, 0, 0)); Assert.False(c == new Quaternion(0, 0, 0, 0)); Assert.False(d == new Quaternion(0, 0, 0, 0)); Assert.True(a != new Quaternion(0, 0, 0, 0)); Assert.True(b != new Quaternion(0, 0, 0, 0)); Assert.True(c != new Quaternion(0, 0, 0, 0)); Assert.True(d != new Quaternion(0, 0, 0, 0)); Assert.False(a.Equals(new Quaternion(0, 0, 0, 0))); Assert.False(b.Equals(new Quaternion(0, 0, 0, 0))); Assert.False(c.Equals(new Quaternion(0, 0, 0, 0))); Assert.False(d.Equals(new Quaternion(0, 0, 0, 0))); Assert.False(a.IsIdentity); Assert.False(b.IsIdentity); Assert.False(c.IsIdentity); Assert.False(d.IsIdentity); // Counterintuitive result - IEEE rules for NaN comparison are weird! Assert.False(a.Equals(a)); Assert.False(b.Equals(b)); Assert.False(c.Equals(c)); Assert.False(d.Equals(d)); } // A test to make sure these types are blittable directly into GPU buffer memory layouts [Fact] public unsafe void QuaternionSizeofTest() { Assert.Equal(16, sizeof(Quaternion)); Assert.Equal(32, sizeof(Quaternion_2x)); Assert.Equal(20, sizeof(QuaternionPlusFloat)); Assert.Equal(40, sizeof(QuaternionPlusFloat_2x)); } [StructLayout(LayoutKind.Sequential)] struct Quaternion_2x { private Quaternion _a; private Quaternion _b; } [StructLayout(LayoutKind.Sequential)] struct QuaternionPlusFloat { private Quaternion _v; private float _f; } [StructLayout(LayoutKind.Sequential)] struct QuaternionPlusFloat_2x { private QuaternionPlusFloat _a; private QuaternionPlusFloat _b; } // A test to make sure the fields are laid out how we expect [Fact] public unsafe void QuaternionFieldOffsetTest() { Quaternion quat = new Quaternion(); float* basePtr = &quat.X; // Take address of first element Quaternion* quatPtr = &quat; // Take address of whole Quaternion Assert.Equal(new IntPtr(basePtr), new IntPtr(quatPtr)); Assert.Equal(new IntPtr(basePtr + 0), new IntPtr(&quat.X)); Assert.Equal(new IntPtr(basePtr + 1), new IntPtr(&quat.Y)); Assert.Equal(new IntPtr(basePtr + 2), new IntPtr(&quat.Z)); Assert.Equal(new IntPtr(basePtr + 3), new IntPtr(&quat.W)); } } }
// 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.13.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// ExpressRouteCircuitsOperations operations. /// </summary> public partial interface IExpressRouteCircuitsOperations { /// <summary> /// The delete ExpressRouteCircuit operation deletes the specified /// ExpressRouteCircuit. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route Circuit. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string circuitName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The delete ExpressRouteCircuit operation deletes the specified /// ExpressRouteCircuit. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route Circuit. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string circuitName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The Get ExpressRouteCircuit operation retreives information about /// the specified ExpressRouteCircuit. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the circuit. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<ExpressRouteCircuit>> GetWithHttpMessagesAsync(string resourceGroupName, string circuitName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The Put ExpressRouteCircuit operation creates/updates a /// ExpressRouteCircuit /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the circuit. /// </param> /// <param name='parameters'> /// Parameters supplied to the create/delete ExpressRouteCircuit /// operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<ExpressRouteCircuit>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string circuitName, ExpressRouteCircuit parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The Put ExpressRouteCircuit operation creates/updates a /// ExpressRouteCircuit /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the circuit. /// </param> /// <param name='parameters'> /// Parameters supplied to the create/delete ExpressRouteCircuit /// operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<ExpressRouteCircuit>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string circuitName, ExpressRouteCircuit parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The ListArpTable from ExpressRouteCircuit opertion retrieves the /// currently advertised arp table associated with the /// ExpressRouteCircuits in a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the circuit. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<ExpressRouteCircuitArpTable>>> ListArpTableWithHttpMessagesAsync(string resourceGroupName, string circuitName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The ListRoutesTable from ExpressRouteCircuit opertion retrieves /// the currently advertised routes table associated with the /// ExpressRouteCircuits in a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the circuit. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<ExpressRouteCircuitRoutesTable>>> ListRoutesTableWithHttpMessagesAsync(string resourceGroupName, string circuitName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The Liststats ExpressRouteCircuit opertion retrieves all the stats /// from a ExpressRouteCircuits in a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the loadBalancer. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<ExpressRouteCircuitStats>>> ListStatsWithHttpMessagesAsync(string resourceGroupName, string circuitName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The List ExpressRouteCircuit opertion retrieves all the /// ExpressRouteCircuits in a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<ExpressRouteCircuit>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The List ExpressRouteCircuit opertion retrieves all the /// ExpressRouteCircuits in a subscription. /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<ExpressRouteCircuit>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The ListArpTable from ExpressRouteCircuit opertion retrieves the /// currently advertised arp table associated with the /// ExpressRouteCircuits in a resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<ExpressRouteCircuitArpTable>>> ListArpTableNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The ListRoutesTable from ExpressRouteCircuit opertion retrieves /// the currently advertised routes table associated with the /// ExpressRouteCircuits in a resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<ExpressRouteCircuitRoutesTable>>> ListRoutesTableNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The Liststats ExpressRouteCircuit opertion retrieves all the stats /// from a ExpressRouteCircuits in a resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<ExpressRouteCircuitStats>>> ListStatsNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The List ExpressRouteCircuit opertion retrieves all the /// ExpressRouteCircuits in a resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<ExpressRouteCircuit>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The List ExpressRouteCircuit opertion retrieves all the /// ExpressRouteCircuits in a subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<ExpressRouteCircuit>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace Sam.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
// 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.IO; using System.Linq; using System.Threading; using Microsoft.AspNetCore.Razor.Language.Legacy; using Xunit; using Xunit.Sdk; namespace Microsoft.AspNetCore.Razor.Language.IntegrationTests { [IntializeTestFile] public abstract class RazorBaselineIntegrationTestBase : RazorIntegrationTestBase { private static readonly AsyncLocal<string> _directoryPath = new AsyncLocal<string>(); protected RazorBaselineIntegrationTestBase(bool? generateBaselines = null) { TestProjectRoot = TestProject.GetProjectDirectory(GetType()); if (generateBaselines.HasValue) { GenerateBaselines = generateBaselines.Value; } } // Used by the test framework to set the directory for test files. public static string DirectoryPath { get { return _directoryPath.Value; } set { _directoryPath.Value = value; } } #if GENERATE_BASELINES protected bool GenerateBaselines { get; } = true; #else protected bool GenerateBaselines { get; } = false; #endif protected string TestProjectRoot { get; } // For consistent line endings because the character counts are going to be recorded in files. internal override string LineEnding => "\r\n"; internal override bool NormalizeSourceLineEndings => true; internal override string PathSeparator => "\\"; // Force consistent paths since they are going to be recorded in files. internal override string WorkingDirectory => ArbitraryWindowsPath; [Fact] public void GenerateBaselinesMustBeFalse() { Assert.False(GenerateBaselines, "GenerateBaselines should be set back to false before you check in!"); } protected void AssertDocumentNodeMatchesBaseline(RazorCodeDocument codeDocument) { var document = codeDocument.GetDocumentIntermediateNode(); var baselineFilePath = GetBaselineFilePath(codeDocument, ".ir.txt"); if (GenerateBaselines) { var baselineFullPath = Path.Combine(TestProjectRoot, baselineFilePath); Directory.CreateDirectory(Path.GetDirectoryName(baselineFullPath)); WriteBaseline(IntermediateNodeSerializer.Serialize(document), baselineFullPath); return; } var irFile = TestFile.Create(baselineFilePath, GetType().Assembly); if (!irFile.Exists()) { throw new XunitException($"The resource {baselineFilePath} was not found."); } // Normalize newlines by splitting into an array. var baseline = irFile.ReadAllText().Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); IntermediateNodeVerifier.Verify(document, baseline); } protected void AssertCSharpDocumentMatchesBaseline(RazorCodeDocument codeDocument) { var document = codeDocument.GetCSharpDocument(); // Normalize newlines to match those in the baseline. var actualCode = document.GeneratedCode.Replace("\r", "").Replace("\n", "\r\n"); var baselineFilePath = GetBaselineFilePath(codeDocument, ".codegen.cs"); var baselineDiagnosticsFilePath = GetBaselineFilePath(codeDocument, ".diagnostics.txt"); var baselineMappingsFilePath = GetBaselineFilePath(codeDocument, ".mappings.txt"); var serializedMappings = SourceMappingsSerializer.Serialize(document, codeDocument.Source); if (GenerateBaselines) { var baselineFullPath = Path.Combine(TestProjectRoot, baselineFilePath); Directory.CreateDirectory(Path.GetDirectoryName(baselineFullPath)); WriteBaseline(actualCode, baselineFullPath); var baselineDiagnosticsFullPath = Path.Combine(TestProjectRoot, baselineDiagnosticsFilePath); var lines = document.Diagnostics.Select(RazorDiagnosticSerializer.Serialize).ToArray(); if (lines.Any()) { WriteBaseline(lines, baselineDiagnosticsFullPath); } else if (File.Exists(baselineDiagnosticsFullPath)) { File.Delete(baselineDiagnosticsFullPath); } var baselineMappingsFullPath = Path.Combine(TestProjectRoot, baselineMappingsFilePath); var text = SourceMappingsSerializer.Serialize(document, codeDocument.Source); if (!string.IsNullOrEmpty(text)) { WriteBaseline(text, baselineMappingsFullPath); } else if (File.Exists(baselineMappingsFullPath)) { File.Delete(baselineMappingsFullPath); } return; } var codegenFile = TestFile.Create(baselineFilePath, GetType().Assembly); if (!codegenFile.Exists()) { throw new XunitException($"The resource {baselineFilePath} was not found."); } var baseline = codegenFile.ReadAllText(); Assert.Equal(baseline, actualCode); var baselineDiagnostics = string.Empty; var diagnosticsFile = TestFile.Create(baselineDiagnosticsFilePath, GetType().Assembly); if (diagnosticsFile.Exists()) { baselineDiagnostics = diagnosticsFile.ReadAllText(); } var actualDiagnostics = string.Concat(document.Diagnostics.Select(d => RazorDiagnosticSerializer.Serialize(d) + "\r\n")); Assert.Equal(baselineDiagnostics, actualDiagnostics); var baselineMappings = string.Empty; var mappingsFile = TestFile.Create(baselineMappingsFilePath, GetType().Assembly); if (mappingsFile.Exists()) { baselineMappings = mappingsFile.ReadAllText(); } var actualMappings = SourceMappingsSerializer.Serialize(document, codeDocument.Source); actualMappings = actualMappings.Replace("\r", "").Replace("\n", "\r\n"); Assert.Equal(baselineMappings, actualMappings); AssertLinePragmas(codeDocument); } protected void AssertLinePragmas(RazorCodeDocument codeDocument) { var csharpDocument = codeDocument.GetCSharpDocument(); Assert.NotNull(csharpDocument); var linePragmas = csharpDocument.LinePragmas; if (DesignTime) { var sourceMappings = csharpDocument.SourceMappings; foreach (var sourceMapping in sourceMappings) { var foundMatchingPragma = false; foreach (var linePragma in linePragmas) { if (sourceMapping.OriginalSpan.LineIndex >= linePragma.StartLineIndex && sourceMapping.OriginalSpan.LineIndex <= linePragma.EndLineIndex) { // Found a match. foundMatchingPragma = true; break; } } Assert.True(foundMatchingPragma, $"No line pragma found for code at line {sourceMapping.OriginalSpan.LineIndex + 1}."); } } else { var syntaxTree = codeDocument.GetSyntaxTree(); var sourceBuffer = new char[syntaxTree.Source.Length]; syntaxTree.Source.CopyTo(0, sourceBuffer, 0, syntaxTree.Source.Length); var sourceContent = new string(sourceBuffer); var classifiedSpans = syntaxTree.GetClassifiedSpans(); foreach (var classifiedSpan in classifiedSpans) { var content = sourceContent.Substring(classifiedSpan.Span.AbsoluteIndex, classifiedSpan.Span.Length); if (!string.IsNullOrWhiteSpace(content) && classifiedSpan.BlockKind != BlockKindInternal.Directive && classifiedSpan.SpanKind == SpanKindInternal.Code) { var foundMatchingPragma = false; foreach (var linePragma in linePragmas) { if (classifiedSpan.Span.LineIndex >= linePragma.StartLineIndex && classifiedSpan.Span.LineIndex <= linePragma.EndLineIndex) { // Found a match. foundMatchingPragma = true; break; } } Assert.True(foundMatchingPragma, $"No line pragma found for code '{content}' at line {classifiedSpan.Span.LineIndex + 1}."); } } } } private string GetBaselineFilePath(RazorCodeDocument codeDocument, string extension) { if (codeDocument == null) { throw new ArgumentNullException(nameof(codeDocument)); } if (extension == null) { throw new ArgumentNullException(nameof(extension)); } var lastSlash = codeDocument.Source.FilePath.LastIndexOfAny(new []{ '/', '\\' }); var fileName = lastSlash == -1 ? null : codeDocument.Source.FilePath.Substring(lastSlash + 1); if (string.IsNullOrEmpty(fileName)) { var message = "Integration tests require a filename"; throw new InvalidOperationException(message); } if (DirectoryPath == null) { var message = $"{nameof(AssertDocumentNodeMatchesBaseline)} should only be called from an integration test.."; throw new InvalidOperationException(message); } return Path.Combine(DirectoryPath, Path.ChangeExtension(fileName, extension)); } private static void WriteBaseline(string text, string filePath) { var lines = text.Replace("\r", "").Replace("\n", "\r\n"); File.WriteAllText(filePath, text); } private static void WriteBaseline(string[] lines, string filePath) { using (var writer = new StreamWriter(File.Open(filePath, FileMode.Create))) { // Force windows-style line endings so that we're consistent. This isn't // required for correctness, but will prevent churn when developing on OSX. writer.NewLine = "\r\n"; for (var i = 0; i < lines.Length; i++) { writer.WriteLine(lines[i]); } } } } }
//Origin : https://www.ghielectronics.com/community/codeshare/entry/464 using System; using System.Collections; using System.Ext.Xml; using System.IO; using System.Reflection; using System.Text; namespace System.Xml.Serialization { public class XmlSerializer { private readonly Type typeToSerialize; public XmlSerializer(Type type) { this.typeToSerialize = type; } public void Serialize(Stream stream, object instance) { using (XmlWriter xmlWriter = XmlWriter.Create(stream)) { xmlWriter.WriteRaw("<?xml version=\"1.0\"?>"); xmlWriter.WriteStartElement(this.typeToSerialize.Name); foreach (FieldInfo fieldInfo in this.typeToSerialize.GetFields()) { Type fieldType = fieldInfo.FieldType; if (fieldType.IsEnum) { SerializeEnum(instance, xmlWriter, fieldInfo); continue; } if (fieldType.IsArray) { SerializeArray(instance, xmlWriter, fieldInfo); continue; } if (fieldType.IsClass && fieldType.Name != "String") { // TODO: what about embedded classes? recursive call?? continue; } if (!fieldType.IsValueType && fieldType.Name != "String") { // TODO: throw or raise event for unsupported type continue; } object fieldValue = fieldInfo.GetValue(instance); if (fieldValue != null) { switch (fieldType.Name) { case "Boolean": // these need to be lowercase xmlWriter.WriteElementString(fieldInfo.Name, fieldValue.ToString().ToLower()); break; case "Char": xmlWriter.WriteElementString(fieldInfo.Name, Encoding.UTF8.GetBytes(fieldValue.ToString())[0].ToString()); break; case "DateTime": xmlWriter.WriteElementString(fieldInfo.Name, ((DateTime)fieldValue).ToString("s")); break; default: // TODO: structs fall through to here xmlWriter.WriteElementString(fieldInfo.Name, fieldValue.ToString()); break; } } } xmlWriter.WriteEndElement(); } } private static void SerializeEnum(object instance, XmlWriter xmlWriter, FieldInfo fieldInfo) { // TODO: desktop .NET serializes enums with their .ToString() value ("Two") in the case below // NETMF does not have the ability to parse an enum and only serializes the base value (1) in the case below } private static void SerializeArray(object instance, XmlWriter xmlWriter, FieldInfo fieldInfo) { object array = fieldInfo.GetValue(instance); string typeName = array.GetType().GetElementType().Name; switch (typeName) { case "Boolean": typeName = "boolean"; break; case "Byte": // TODO: this is not an array but a base64 encoded string but have not figured out how to decode it //xmlWriter.WriteElementString(fieldInfo.Name, Convert.ToBase64String((byte[])array)); return; case "SByte": typeName = "byte"; break; case "Char": typeName = "char"; break; case "DateTime": typeName = "dateTime"; break; case "Double": typeName = "double"; break; case "Guid": typeName = "guid"; break; case "Int16": typeName = "short"; break; case "UInt16": typeName = "unsignedShort"; break; case "Int32": typeName = "int"; break; case "UInt32": typeName = "unsignedInt"; break; case "Int64": typeName = "long"; break; case "UInt64": typeName = "unsignedLong"; break; case "Single": typeName = "float"; break; case "String": typeName = "string"; break; } xmlWriter.WriteStartElement(fieldInfo.Name); foreach (var item in (IEnumerable)array) { switch (typeName) { case "boolean": // these need to be lowercase xmlWriter.WriteElementString(typeName, item.ToString().ToLower()); break; case "char": xmlWriter.WriteElementString(typeName, Encoding.UTF8.GetBytes(item.ToString())[0].ToString()); break; case "dateTime": xmlWriter.WriteElementString(typeName, ((DateTime)item).ToString("s")); break; default: xmlWriter.WriteElementString(typeName, item.ToString()); break; } } xmlWriter.WriteEndElement(); } public object Deserialize(Stream stream) { object instance = this.typeToSerialize.GetConstructor(new Type[0]).Invoke(null); using (XmlReader xmlReader = XmlReader.Create(stream, new XmlReaderSettings() { IgnoreComments = true, IgnoreWhitespace = true })) { while (xmlReader.Read()) { if (xmlReader.NodeType == XmlNodeType.Element) { foreach (FieldInfo fieldInfo in this.typeToSerialize.GetFields()) { if (xmlReader.Name == fieldInfo.Name) { Type fieldType = fieldInfo.FieldType; if (fieldType.IsEnum) { fieldInfo.SetValue(instance, DeserializeEnum(xmlReader)); continue; } if (fieldType.IsArray) { fieldInfo.SetValue(instance, DeserializeArray(xmlReader)); continue; } if (fieldType.IsClass && fieldType.Name != "String") { // TODO: what about embedded classes? recursive call?? continue; } if (!fieldType.IsValueType && fieldType.Name != "String") { // TODO: throw or raise event for unsupported type continue; } string tempValue = xmlReader.ReadElementString(fieldInfo.Name); switch (fieldType.Name) { case "Boolean": fieldInfo.SetValue(instance, tempValue == "true"); break; case "Byte": fieldInfo.SetValue(instance, Convert.ToByte(tempValue)); break; case "SByte": fieldInfo.SetValue(instance, Convert.ToSByte(tempValue)); break; case "Char": fieldInfo.SetValue(instance, Convert.ToChar(Convert.ToByte(tempValue))); break; case "DateTime": fieldInfo.SetValue(instance, GetDateTimeFromString(tempValue)); break; case "Double": fieldInfo.SetValue(instance, Convert.ToDouble(tempValue)); break; case "Guid": fieldInfo.SetValue(instance, GetGuidFromString(tempValue)); break; case "Int16": fieldInfo.SetValue(instance, Convert.ToInt16(tempValue)); break; case "UInt16": fieldInfo.SetValue(instance, Convert.ToUInt16(tempValue)); break; case "Int32": fieldInfo.SetValue(instance, Convert.ToInt32(tempValue)); break; case "UInt32": fieldInfo.SetValue(instance, Convert.ToUInt32(tempValue)); break; case "Int64": fieldInfo.SetValue(instance, Convert.ToInt64(tempValue)); break; case "UInt64": fieldInfo.SetValue(instance, Convert.ToUInt64(tempValue)); break; case "Single": fieldInfo.SetValue(instance, (Single)Convert.ToDouble(tempValue)); break; case "String": fieldInfo.SetValue(instance, tempValue); break; default: break; } continue; } } } } } return instance; } private static object DeserializeEnum(XmlReader xmlReader) { // TODO: desktop .NET serializes enums with their .ToString() value ("Two") in the case below // NETMF does not have the ability to parse an enum and only serializes the base value (1) in the case below return null; } private static object DeserializeArray(XmlReader xmlReader) { string startingElementName = xmlReader.Name; xmlReader.Read(); string arrayType = xmlReader.Name; ArrayList array = new ArrayList(); Type returnType = null; while (xmlReader.Name != startingElementName) { string tempValue = xmlReader.ReadElementString(); switch (arrayType) { case "boolean": returnType = returnType ?? typeof(bool); array.Add(tempValue == "true"); break; // TODO: this is not an array but a base64 encoded string //case "byte": // //returnType = returnType ?? typeof(bool); // //return Convert.FromBase64String(tempValue); // //throw new Exception("Should never reach this"); // break; case "byte": returnType = returnType ?? typeof(sbyte); array.Add(Convert.ToSByte(tempValue)); break; case "char": returnType = returnType ?? typeof(char); array.Add(Convert.ToChar(Convert.ToByte(tempValue))); break; case "dateTime": returnType = returnType ?? typeof(DateTime); array.Add(GetDateTimeFromString(tempValue)); break; case "double": returnType = returnType ?? typeof(double); array.Add(Convert.ToDouble(tempValue)); break; case "guid": returnType = returnType ?? typeof(Guid); array.Add(GetGuidFromString(tempValue)); break; case "short": returnType = returnType ?? typeof(short); array.Add(Convert.ToInt16(tempValue)); break; case "unsignedShort": returnType = returnType ?? typeof(ushort); array.Add(Convert.ToUInt16(tempValue)); break; case "int": returnType = returnType ?? typeof(int); array.Add(Convert.ToInt32(tempValue)); break; case "unsignedInt": returnType = returnType ?? typeof(uint); array.Add(Convert.ToUInt32(tempValue)); break; case "long": returnType = returnType ?? typeof(long); array.Add(Convert.ToInt64(tempValue)); break; case "unsignedLong": returnType = returnType ?? typeof(ulong); array.Add(Convert.ToUInt64(tempValue)); break; case "float": returnType = returnType ?? typeof(float); array.Add((Single)Convert.ToDouble(tempValue)); break; case "string": returnType = returnType ?? typeof(string); array.Add(tempValue); break; default: returnType = returnType ?? typeof(object); break; } } return array.ToArray(returnType); } private static object GetGuidFromString(string tempValue) { byte[] guidBytes = new byte[16]; string[] split = tempValue.Split('-'); int location = 0; for (int i = 0; i < split.Length; i++) { byte[] tempArray = HexToBytes(split[i]); // TODO: is this needed or will it always need to be reversed //bool temp = Microsoft.SPOT.Hardware.SystemInfo.IsBigEndian; if (i < 3) { int end = tempArray.Length - 1; for (int start = 0; start < end; start++) { byte b = tempArray[start]; tempArray[start] = tempArray[end]; tempArray[end] = b; end--; } } Array.Copy(tempArray, 0, guidBytes, location, tempArray.Length); location += split[i].Length / 2; } return new Guid(guidBytes); } private static byte[] HexToBytes(string hexString) { // Based on http://stackoverflow.com/a/3974535 if (hexString.Length == 0 || hexString.Length % 2 != 0) return new byte[0]; byte[] buffer = new byte[hexString.Length / 2]; char c; for (int bx = 0, sx = 0; bx < buffer.Length; ++bx, ++sx) { // Convert first half of byte c = hexString[sx]; byte b = (byte)((c > '9' ? (c > 'Z' ? (c - 'a' + 10) : (c - 'A' + 10)) : (c - '0')) << 4); // Convert second half of byte c = hexString[++sx]; b |= (byte)(c > '9' ? (c > 'Z' ? (c - 'a' + 10) : (c - 'A' + 10)) : (c - '0')); buffer[bx] = b; } return buffer; } private static DateTime GetDateTimeFromString(string tempValue) { int year; int month; int day; int hour; int minute; int second; int millisecond; year = int.Parse(tempValue.Substring(0, 4)); month = int.Parse(tempValue.Substring(5, 2)); day = int.Parse(tempValue.Substring(8, 2)); hour = int.Parse(tempValue.Substring(11, 2)); minute = int.Parse(tempValue.Substring(14, 2)); second = int.Parse(tempValue.Substring(17, 2)); // NETMF serializes out to this //2012-06-27T20:02:40 // .NET does this //2012-06-27T20:36:57.995-07:00 // ^ ^^^^^^ // | | // milliseconds timezone (-7 from GMT) (sometimes) //millisecond = tempValue.Length == 19 ? 0 : int.Parse(tempValue.Substring(20, 2)); millisecond = 0; return new DateTime(year, month, day, hour, minute, second, millisecond); } } }
using System; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Configuration.Provider; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Web; using System.Web.Configuration; using System.Web.Hosting; using System.Web.Security; using Umbraco.Core.Configuration; using Umbraco.Core.Logging; using Umbraco.Core.Models; namespace Umbraco.Core.Security { /// <summary> /// A base membership provider class offering much of the underlying functionality for initializing and password encryption/hashing. /// </summary> public abstract class MembershipProviderBase : MembershipProvider { public string HashPasswordForStorage(string password) { string salt; var hashed = EncryptOrHashNewPassword(password, out salt); return FormatPasswordForStorage(hashed, salt); } public bool VerifyPassword(string password, string hashedPassword) { if (string.IsNullOrWhiteSpace(hashedPassword)) throw new ArgumentException("Value cannot be null or whitespace.", "hashedPassword"); return CheckPassword(password, hashedPassword); } /// <summary> /// Providers can override this setting, default is 10 /// </summary> public virtual int DefaultMinPasswordLength { get { return 10; } } /// <summary> /// Providers can override this setting, default is 0 /// </summary> public virtual int DefaultMinNonAlphanumericChars { get { return 0; } } /// <summary> /// Providers can override this setting, default is false to use better security /// </summary> public virtual bool DefaultUseLegacyEncoding { get { return false; } } /// <summary> /// Providers can override this setting, by default this is false which means that the provider will /// authenticate the username + password when ChangePassword is called. This property exists purely for /// backwards compatibility. /// </summary> public virtual bool AllowManuallyChangingPassword { get { return false; } } /// <summary> /// Returns the raw password value for a given user /// </summary> /// <param name="username"></param> /// <returns></returns> /// <remarks> /// By default this will return an invalid attempt, inheritors will need to override this to support it /// </remarks> protected virtual Attempt<string> GetRawPassword(string username) { return Attempt<string>.Fail(); } private string _applicationName; private bool _enablePasswordReset; private bool _enablePasswordRetrieval; private int _maxInvalidPasswordAttempts; private int _minRequiredNonAlphanumericCharacters; private int _minRequiredPasswordLength; private int _passwordAttemptWindow; private MembershipPasswordFormat _passwordFormat; private string _passwordStrengthRegularExpression; private bool _requiresQuestionAndAnswer; private bool _requiresUniqueEmail; private string _customHashAlgorithmType ; public bool UseLegacyEncoding { get; private set; } #region Properties /// <summary> /// Indicates whether the membership provider is configured to allow users to reset their passwords. /// </summary> /// <value></value> /// <returns>true if the membership provider supports password reset; otherwise, false. The default is true.</returns> public override bool EnablePasswordReset { get { return _enablePasswordReset; } } /// <summary> /// Indicates whether the membership provider is configured to allow users to retrieve their passwords. /// </summary> /// <value></value> /// <returns>true if the membership provider is configured to support password retrieval; otherwise, false. The default is false.</returns> public override bool EnablePasswordRetrieval { get { return _enablePasswordRetrieval; } } /// <summary> /// Gets the number of invalid password or password-answer attempts allowed before the membership user is locked out. /// </summary> /// <value></value> /// <returns>The number of invalid password or password-answer attempts allowed before the membership user is locked out.</returns> public override int MaxInvalidPasswordAttempts { get { return _maxInvalidPasswordAttempts; } } /// <summary> /// Gets the minimum number of special characters that must be present in a valid password. /// </summary> /// <value></value> /// <returns>The minimum number of special characters that must be present in a valid password.</returns> public override int MinRequiredNonAlphanumericCharacters { get { return _minRequiredNonAlphanumericCharacters; } } /// <summary> /// Gets the minimum length required for a password. /// </summary> /// <value></value> /// <returns>The minimum length required for a password. </returns> public override int MinRequiredPasswordLength { get { return _minRequiredPasswordLength; } } /// <summary> /// Gets the number of minutes in which a maximum number of invalid password or password-answer attempts are allowed before the membership user is locked out. /// </summary> /// <value></value> /// <returns>The number of minutes in which a maximum number of invalid password or password-answer attempts are allowed before the membership user is locked out.</returns> public override int PasswordAttemptWindow { get { return _passwordAttemptWindow; } } /// <summary> /// Gets a value indicating the format for storing passwords in the membership data store. /// </summary> /// <value></value> /// <returns>One of the <see cref="T:System.Web.Security.MembershipPasswordFormat"></see> values indicating the format for storing passwords in the data store.</returns> public override MembershipPasswordFormat PasswordFormat { get { return _passwordFormat; } } /// <summary> /// Gets the regular expression used to evaluate a password. /// </summary> /// <value></value> /// <returns>A regular expression used to evaluate a password.</returns> public override string PasswordStrengthRegularExpression { get { return _passwordStrengthRegularExpression; } } /// <summary> /// Gets a value indicating whether the membership provider is configured to require the user to answer a password question for password reset and retrieval. /// </summary> /// <value></value> /// <returns>true if a password answer is required for password reset and retrieval; otherwise, false. The default is true.</returns> public override bool RequiresQuestionAndAnswer { get { return _requiresQuestionAndAnswer; } } /// <summary> /// Gets a value indicating whether the membership provider is configured to require a unique e-mail address for each user name. /// </summary> /// <value></value> /// <returns>true if the membership provider requires a unique e-mail address; otherwise, false. The default is true.</returns> public override bool RequiresUniqueEmail { get { return _requiresUniqueEmail; } } /// <summary> /// The name of the application using the custom membership provider. /// </summary> /// <value></value> /// <returns>The name of the application using the custom membership provider.</returns> public override string ApplicationName { get { return _applicationName; } set { if (string.IsNullOrEmpty(value)) throw new ProviderException("ApplicationName cannot be empty."); if (value.Length > 0x100) throw new ProviderException("Provider application name too long."); _applicationName = value; } } #endregion /// <summary> /// Initializes the provider. /// </summary> /// <param name="name">The friendly name of the provider.</param> /// <param name="config">A collection of the name/value pairs representing the provider-specific attributes specified in the configuration for this provider.</param> /// <exception cref="T:System.ArgumentNullException">The name of the provider is null.</exception> /// <exception cref="T:System.InvalidOperationException">An attempt is made to call /// <see cref="M:System.Configuration.Provider.ProviderBase.Initialize(System.String,System.Collections.Specialized.NameValueCollection)"></see> on a provider after the provider /// has already been initialized.</exception> /// <exception cref="T:System.ArgumentException">The name of the provider has a length of zero.</exception> public override void Initialize(string name, NameValueCollection config) { // Initialize base provider class base.Initialize(name, config); _enablePasswordRetrieval = config.GetValue("enablePasswordRetrieval", false); _enablePasswordReset = config.GetValue("enablePasswordReset", true); _requiresQuestionAndAnswer = config.GetValue("requiresQuestionAndAnswer", false); _requiresUniqueEmail = config.GetValue("requiresUniqueEmail", true); _maxInvalidPasswordAttempts = GetIntValue(config, "maxInvalidPasswordAttempts", 5, false, 0); _passwordAttemptWindow = GetIntValue(config, "passwordAttemptWindow", 10, false, 0); _minRequiredPasswordLength = GetIntValue(config, "minRequiredPasswordLength", DefaultMinPasswordLength, true, 0x80); _minRequiredNonAlphanumericCharacters = GetIntValue(config, "minRequiredNonalphanumericCharacters", DefaultMinNonAlphanumericChars, true, 0x80); _passwordStrengthRegularExpression = config["passwordStrengthRegularExpression"]; _applicationName = config["applicationName"]; if (string.IsNullOrEmpty(_applicationName)) _applicationName = GetDefaultAppName(); //by default we will continue using the legacy encoding. UseLegacyEncoding = config.GetValue("useLegacyEncoding", DefaultUseLegacyEncoding); // make sure password format is Hashed by default. string str = config["passwordFormat"] ?? "Hashed"; switch (str.ToLower()) { case "clear": _passwordFormat = MembershipPasswordFormat.Clear; break; case "encrypted": _passwordFormat = MembershipPasswordFormat.Encrypted; break; case "hashed": _passwordFormat = MembershipPasswordFormat.Hashed; break; default: throw new ProviderException("Provider bad password format"); } if ((PasswordFormat == MembershipPasswordFormat.Hashed) && EnablePasswordRetrieval) { var ex = new ProviderException("Provider can not retrieve a hashed password"); LogHelper.Error<MembershipProviderBase>("Cannot specify a Hashed password format with the enabledPasswordRetrieval option set to true", ex); throw ex; } _customHashAlgorithmType = config.GetValue("hashAlgorithmType", string.Empty); } /// <summary> /// Override this method to ensure the password is valid before raising the event /// </summary> /// <param name="e"></param> protected override void OnValidatingPassword(ValidatePasswordEventArgs e) { var attempt = IsPasswordValid(e.Password, MinRequiredNonAlphanumericCharacters, PasswordStrengthRegularExpression, MinRequiredPasswordLength); if (attempt.Success == false) { e.Cancel = true; return; } base.OnValidatingPassword(e); } protected internal enum PasswordValidityError { Ok, Length, AlphanumericChars, Strength } /// <summary> /// Processes a request to update the password for a membership user. /// </summary> /// <param name="username">The user to update the password for.</param> /// <param name="oldPassword">Required to change a user password if the user is not new and AllowManuallyChangingPassword is false</param> /// <param name="newPassword">The new password for the specified user.</param> /// <returns> /// true if the password was updated successfully; otherwise, false. /// </returns> /// <remarks> /// Checks to ensure the AllowManuallyChangingPassword rule is adhered to /// </remarks> public override bool ChangePassword(string username, string oldPassword, string newPassword) { string rawPasswordValue = string.Empty; if (oldPassword.IsNullOrWhiteSpace() && AllowManuallyChangingPassword == false) { //we need to lookup the member since this could be a brand new member without a password set var rawPassword = GetRawPassword(username); rawPasswordValue = rawPassword.Success ? rawPassword.Result : string.Empty; if (rawPassword.Success == false || rawPasswordValue.StartsWith(Constants.Security.EmptyPasswordPrefix) == false) { //If the old password is empty and AllowManuallyChangingPassword is false, than this provider cannot just arbitrarily change the password throw new NotSupportedException("This provider does not support manually changing the password"); } } var args = new ValidatePasswordEventArgs(username, newPassword, false); OnValidatingPassword(args); if (args.Cancel) { if (args.FailureInformation != null) throw args.FailureInformation; throw new MembershipPasswordException("Change password canceled due to password validation failure."); } //Special cases to allow changing password without validating existing credentials // * the member is new and doesn't have a password set // * during installation to set the admin password if (AllowManuallyChangingPassword == false && (rawPasswordValue.StartsWith(Constants.Security.EmptyPasswordPrefix) || (ApplicationContext.Current != null && ApplicationContext.Current.IsConfigured == false && oldPassword == "default"))) { return PerformChangePassword(username, oldPassword, newPassword); } if (AllowManuallyChangingPassword == false) { if (ValidateUser(username, oldPassword) == false) return false; } return PerformChangePassword(username, oldPassword, newPassword); } /// <summary> /// Processes a request to update the password for a membership user. /// </summary> /// <param name="username">The user to update the password for.</param> /// <param name="oldPassword">This property is ignore for this provider</param> /// <param name="newPassword">The new password for the specified user.</param> /// <returns> /// true if the password was updated successfully; otherwise, false. /// </returns> protected abstract bool PerformChangePassword(string username, string oldPassword, string newPassword); /// <summary> /// Processes a request to update the password question and answer for a membership user. /// </summary> /// <param name="username">The user to change the password question and answer for.</param> /// <param name="password">The password for the specified user.</param> /// <param name="newPasswordQuestion">The new password question for the specified user.</param> /// <param name="newPasswordAnswer">The new password answer for the specified user.</param> /// <returns> /// true if the password question and answer are updated successfully; otherwise, false. /// </returns> /// <remarks> /// Performs the basic validation before passing off to PerformChangePasswordQuestionAndAnswer /// </remarks> public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer) { if (RequiresQuestionAndAnswer == false) { throw new NotSupportedException("Updating the password Question and Answer is not available if requiresQuestionAndAnswer is not set in web.config"); } if (AllowManuallyChangingPassword == false) { if (ValidateUser(username, password) == false) { return false; } } return PerformChangePasswordQuestionAndAnswer(username, password, newPasswordQuestion, newPasswordAnswer); } /// <summary> /// Processes a request to update the password question and answer for a membership user. /// </summary> /// <param name="username">The user to change the password question and answer for.</param> /// <param name="password">The password for the specified user.</param> /// <param name="newPasswordQuestion">The new password question for the specified user.</param> /// <param name="newPasswordAnswer">The new password answer for the specified user.</param> /// <returns> /// true if the password question and answer are updated successfully; otherwise, false. /// </returns> protected abstract bool PerformChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer); /// <summary> /// Adds a new membership user to the data source. /// </summary> /// <param name="username">The user name for the new user.</param> /// <param name="password">The password for the new user.</param> /// <param name="email">The e-mail address for the new user.</param> /// <param name="passwordQuestion">The password question for the new user.</param> /// <param name="passwordAnswer">The password answer for the new user</param> /// <param name="isApproved">Whether or not the new user is approved to be validated.</param> /// <param name="providerUserKey">The unique identifier from the membership data source for the user.</param> /// <param name="status">A <see cref="T:System.Web.Security.MembershipCreateStatus"></see> enumeration value indicating whether the user was created successfully.</param> /// <returns> /// A <see cref="T:System.Web.Security.MembershipUser"></see> object populated with the information for the newly created user. /// </returns> /// <remarks> /// Ensures the ValidatingPassword event is executed before executing PerformCreateUser and performs basic membership provider validation of values. /// </remarks> public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status) { var valStatus = ValidateNewUser(username, password, email, passwordQuestion, passwordAnswer, isApproved, providerUserKey); if (valStatus != MembershipCreateStatus.Success) { status = valStatus; return null; } return PerformCreateUser(username, password, email, passwordQuestion, passwordAnswer, isApproved, providerUserKey, out status); } /// <summary> /// Performs the validation of the information for creating a new user /// </summary> /// <param name="username"></param> /// <param name="password"></param> /// <param name="email"></param> /// <param name="passwordQuestion"></param> /// <param name="passwordAnswer"></param> /// <param name="isApproved"></param> /// <param name="providerUserKey"></param> /// <returns></returns> protected MembershipCreateStatus ValidateNewUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey) { var args = new ValidatePasswordEventArgs(username, password, true); OnValidatingPassword(args); if (args.Cancel) { return MembershipCreateStatus.InvalidPassword; } // Validate password var passwordValidAttempt = IsPasswordValid(password, MinRequiredNonAlphanumericCharacters, PasswordStrengthRegularExpression, MinRequiredPasswordLength); if (passwordValidAttempt.Success == false) { return MembershipCreateStatus.InvalidPassword; } // Validate email if (IsEmailValid(email) == false) { return MembershipCreateStatus.InvalidEmail; } // Make sure username isn't all whitespace if (string.IsNullOrWhiteSpace(username.Trim())) { return MembershipCreateStatus.InvalidUserName; } // Check password question if (string.IsNullOrWhiteSpace(passwordQuestion) && RequiresQuestionAndAnswer) { return MembershipCreateStatus.InvalidQuestion; } // Check password answer if (string.IsNullOrWhiteSpace(passwordAnswer) && RequiresQuestionAndAnswer) { return MembershipCreateStatus.InvalidAnswer; } return MembershipCreateStatus.Success; } /// <summary> /// Adds a new membership user to the data source. /// </summary> /// <param name="username">The user name for the new user.</param> /// <param name="password">The password for the new user.</param> /// <param name="email">The e-mail address for the new user.</param> /// <param name="passwordQuestion">The password question for the new user.</param> /// <param name="passwordAnswer">The password answer for the new user</param> /// <param name="isApproved">Whether or not the new user is approved to be validated.</param> /// <param name="providerUserKey">The unique identifier from the membership data source for the user.</param> /// <param name="status">A <see cref="T:System.Web.Security.MembershipCreateStatus"></see> enumeration value indicating whether the user was created successfully.</param> /// <returns> /// A <see cref="T:System.Web.Security.MembershipUser"></see> object populated with the information for the newly created user. /// </returns> protected abstract MembershipUser PerformCreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status); /// <summary> /// Gets the members password if password retreival is enabled /// </summary> /// <param name="username"></param> /// <param name="answer"></param> /// <returns></returns> public override string GetPassword(string username, string answer) { if (EnablePasswordRetrieval == false) throw new ProviderException("Password Retrieval Not Enabled."); if (PasswordFormat == MembershipPasswordFormat.Hashed) throw new ProviderException("Cannot retrieve Hashed passwords."); return PerformGetPassword(username, answer); } /// <summary> /// Gets the members password if password retreival is enabled /// </summary> /// <param name="username"></param> /// <param name="answer"></param> /// <returns></returns> protected abstract string PerformGetPassword(string username, string answer); public override string ResetPassword(string username, string answer) { var userService = ApplicationContext.Current == null ? null : ApplicationContext.Current.Services.UserService; var canReset = this.CanResetPassword(userService); if (canReset == false) { throw new NotSupportedException("Password reset is not supported"); } var newPassword = Membership.GeneratePassword(MinRequiredPasswordLength, MinRequiredNonAlphanumericCharacters); var args = new ValidatePasswordEventArgs(username, newPassword, true); OnValidatingPassword(args); if (args.Cancel) { if (args.FailureInformation != null) { throw args.FailureInformation; } throw new MembershipPasswordException("Reset password canceled due to password validation failure."); } return PerformResetPassword(username, answer, newPassword); } protected abstract string PerformResetPassword(string username, string answer, string generatedPassword); protected internal static Attempt<PasswordValidityError> IsPasswordValid(string password, int minRequiredNonAlphanumericChars, string strengthRegex, int minLength) { if (minRequiredNonAlphanumericChars > 0) { var nonAlphaNumeric = Regex.Replace(password, "[a-zA-Z0-9]", "", RegexOptions.Multiline | RegexOptions.IgnoreCase); if (nonAlphaNumeric.Length < minRequiredNonAlphanumericChars) { return Attempt.Fail(PasswordValidityError.AlphanumericChars); } } if (string.IsNullOrEmpty(strengthRegex) == false) { if (Regex.IsMatch(password, strengthRegex, RegexOptions.Compiled) == false) { return Attempt.Fail(PasswordValidityError.Strength); } } if (password.Length < minLength) { return Attempt.Fail(PasswordValidityError.Length); } return Attempt.Succeed(PasswordValidityError.Ok); } /// <summary> /// Gets the name of the default app. /// </summary> /// <returns></returns> internal static string GetDefaultAppName() { try { string applicationVirtualPath = HostingEnvironment.ApplicationVirtualPath; if (string.IsNullOrEmpty(applicationVirtualPath)) { return "/"; } return applicationVirtualPath; } catch { return "/"; } } internal static int GetIntValue(NameValueCollection config, string valueName, int defaultValue, bool zeroAllowed, int maxValueAllowed) { int num; string s = config[valueName]; if (s == null) { return defaultValue; } if (!int.TryParse(s, out num)) { if (zeroAllowed) { throw new ProviderException("Value must be non negative integer"); } throw new ProviderException("Value must be positive integer"); } if (zeroAllowed && (num < 0)) { throw new ProviderException("Value must be non negativeinteger"); } if (!zeroAllowed && (num <= 0)) { throw new ProviderException("Value must be positive integer"); } if ((maxValueAllowed > 0) && (num > maxValueAllowed)) { throw new ProviderException("Value too big"); } return num; } /// <summary> /// If the password format is a hashed keyed algorithm then we will pre-pend the salt used to hash the password /// to the hashed password itself. /// </summary> /// <param name="pass"></param> /// <param name="salt"></param> /// <returns></returns> protected internal string FormatPasswordForStorage(string pass, string salt) { if (UseLegacyEncoding) { return pass; } if (PasswordFormat == MembershipPasswordFormat.Hashed) { //the better way, we use salt per member return salt + pass; } return pass; } internal static bool IsEmailValid(string email) { return new EmailAddressAttribute().IsValid(email); } protected internal string EncryptOrHashPassword(string pass, string salt) { //if we are doing it the old way if (UseLegacyEncoding) { return LegacyEncodePassword(pass); } //This is the correct way to implement this (as per the sql membership provider) if (PasswordFormat == MembershipPasswordFormat.Clear) return pass; var bytes = Encoding.Unicode.GetBytes(pass); var saltBytes = Convert.FromBase64String(salt); byte[] inArray; if (PasswordFormat == MembershipPasswordFormat.Hashed) { var hashAlgorithm = GetHashAlgorithm(pass); var algorithm = hashAlgorithm as KeyedHashAlgorithm; if (algorithm != null) { var keyedHashAlgorithm = algorithm; if (keyedHashAlgorithm.Key.Length == saltBytes.Length) { //if the salt bytes is the required key length for the algorithm, use it as-is keyedHashAlgorithm.Key = saltBytes; } else if (keyedHashAlgorithm.Key.Length < saltBytes.Length) { //if the salt bytes is too long for the required key length for the algorithm, reduce it var numArray2 = new byte[keyedHashAlgorithm.Key.Length]; Buffer.BlockCopy(saltBytes, 0, numArray2, 0, numArray2.Length); keyedHashAlgorithm.Key = numArray2; } else { //if the salt bytes is too long for the required key length for the algorithm, extend it var numArray2 = new byte[keyedHashAlgorithm.Key.Length]; var dstOffset = 0; while (dstOffset < numArray2.Length) { var count = Math.Min(saltBytes.Length, numArray2.Length - dstOffset); Buffer.BlockCopy(saltBytes, 0, numArray2, dstOffset, count); dstOffset += count; } keyedHashAlgorithm.Key = numArray2; } inArray = keyedHashAlgorithm.ComputeHash(bytes); } else { var buffer = new byte[saltBytes.Length + bytes.Length]; Buffer.BlockCopy(saltBytes, 0, buffer, 0, saltBytes.Length); Buffer.BlockCopy(bytes, 0, buffer, saltBytes.Length, bytes.Length); inArray = hashAlgorithm.ComputeHash(buffer); } } else { //this code is copied from the sql membership provider - pretty sure this could be nicely re-written to completely // ignore the salt stuff since we are not salting the password when encrypting. var password = new byte[saltBytes.Length + bytes.Length]; Buffer.BlockCopy(saltBytes, 0, password, 0, saltBytes.Length); Buffer.BlockCopy(bytes, 0, password, saltBytes.Length, bytes.Length); inArray = EncryptPassword(password, MembershipPasswordCompatibilityMode.Framework40); } return Convert.ToBase64String(inArray); } /// <summary> /// Checks the password. /// </summary> /// <param name="password">The password.</param> /// <param name="dbPassword">The dbPassword.</param> /// <returns></returns> protected internal bool CheckPassword(string password, string dbPassword) { if (string.IsNullOrWhiteSpace(dbPassword)) throw new ArgumentException("Value cannot be null or whitespace.", "dbPassword"); switch (PasswordFormat) { case MembershipPasswordFormat.Encrypted: var decrypted = DecryptPassword(dbPassword); return decrypted == password; case MembershipPasswordFormat.Hashed: string salt; var storedHashedPass = StoredPassword(dbPassword, out salt); var hashed = EncryptOrHashPassword(password, salt); return storedHashedPass == hashed; case MembershipPasswordFormat.Clear: return password == dbPassword; default: throw new ArgumentOutOfRangeException(); } } /// <summary> /// Encrypt/hash a new password with a new salt /// </summary> /// <param name="newPassword"></param> /// <param name="salt"></param> /// <returns></returns> protected internal string EncryptOrHashNewPassword(string newPassword, out string salt) { salt = GenerateSalt(); return EncryptOrHashPassword(newPassword, salt); } protected internal string DecryptPassword(string pass) { //if we are doing it the old way if (UseLegacyEncoding) { return LegacyUnEncodePassword(pass); } //This is the correct way to implement this (as per the sql membership provider) switch (PasswordFormat) { case MembershipPasswordFormat.Clear: return pass; case MembershipPasswordFormat.Hashed: throw new ProviderException("Provider can not decrypt hashed password"); case MembershipPasswordFormat.Encrypted: default: var bytes = DecryptPassword(Convert.FromBase64String(pass)); return bytes == null ? null : Encoding.Unicode.GetString(bytes, 16, bytes.Length - 16); } } /// <summary> /// Returns the hashed password without the salt if it is hashed /// </summary> /// <param name="storedString"></param> /// <param name="salt">returns the salt</param> /// <returns></returns> internal string StoredPassword(string storedString, out string salt) { if (string.IsNullOrWhiteSpace(storedString)) throw new ArgumentException("Value cannot be null or whitespace.", "storedString"); if (UseLegacyEncoding) { salt = string.Empty; return storedString; } switch (PasswordFormat) { case MembershipPasswordFormat.Hashed: var saltLen = GenerateSalt(); salt = storedString.Substring(0, saltLen.Length); return storedString.Substring(saltLen.Length); case MembershipPasswordFormat.Clear: case MembershipPasswordFormat.Encrypted: default: salt = string.Empty; return storedString; } } protected internal static string GenerateSalt() { var numArray = new byte[16]; new RNGCryptoServiceProvider().GetBytes(numArray); return Convert.ToBase64String(numArray); } protected internal HashAlgorithm GetHashAlgorithm(string password) { if (UseLegacyEncoding) { //before we were never checking for an algorithm type so we were always using HMACSHA1 // for any SHA specified algorithm :( so we'll need to keep doing that for backwards compat support. if (Membership.HashAlgorithmType.InvariantContains("SHA")) { return new HMACSHA1 { //the legacy salt was actually the password :( Key = Encoding.Unicode.GetBytes(password) }; } } //get the algorithm by name if (_customHashAlgorithmType.IsNullOrWhiteSpace()) { _customHashAlgorithmType = Membership.HashAlgorithmType; } var alg = HashAlgorithm.Create(_customHashAlgorithmType); if (alg == null) { throw new InvalidOperationException("The hash algorithm specified " + Membership.HashAlgorithmType + " cannot be resolved"); } return alg; } /// <summary> /// Encodes the password. /// </summary> /// <param name="password">The password.</param> /// <returns>The encoded password.</returns> protected string LegacyEncodePassword(string password) { string encodedPassword = password; switch (PasswordFormat) { case MembershipPasswordFormat.Clear: break; case MembershipPasswordFormat.Encrypted: encodedPassword = Convert.ToBase64String(EncryptPassword(Encoding.Unicode.GetBytes(password))); break; case MembershipPasswordFormat.Hashed: var hashAlgorith = GetHashAlgorithm(password); encodedPassword = Convert.ToBase64String(hashAlgorith.ComputeHash(Encoding.Unicode.GetBytes(password))); break; default: throw new ProviderException("Unsupported password format."); } return encodedPassword; } /// <summary> /// Unencode password. /// </summary> /// <param name="encodedPassword">The encoded password.</param> /// <returns>The unencoded password.</returns> protected string LegacyUnEncodePassword(string encodedPassword) { string password = encodedPassword; switch (PasswordFormat) { case MembershipPasswordFormat.Clear: break; case MembershipPasswordFormat.Encrypted: password = Encoding.Unicode.GetString(DecryptPassword(Convert.FromBase64String(password))); break; case MembershipPasswordFormat.Hashed: throw new ProviderException("Cannot unencode a hashed password."); default: throw new ProviderException("Unsupported password format."); } return password; } public override string ToString() { var result = base.ToString(); var sb = new StringBuilder(result); sb.AppendLine("Name =" + Name); sb.AppendLine("_applicationName =" + _applicationName); sb.AppendLine("_enablePasswordReset=" + _enablePasswordReset); sb.AppendLine("_enablePasswordRetrieval=" + _enablePasswordRetrieval); sb.AppendLine("_maxInvalidPasswordAttempts=" + _maxInvalidPasswordAttempts); sb.AppendLine("_minRequiredNonAlphanumericCharacters=" + _minRequiredNonAlphanumericCharacters); sb.AppendLine("_minRequiredPasswordLength=" + _minRequiredPasswordLength); sb.AppendLine("_passwordAttemptWindow=" + _passwordAttemptWindow); sb.AppendLine("_passwordFormat=" + _passwordFormat); sb.AppendLine("_passwordStrengthRegularExpression=" + _passwordStrengthRegularExpression); sb.AppendLine("_requiresQuestionAndAnswer=" + _requiresQuestionAndAnswer); sb.AppendLine("_requiresUniqueEmail=" + _requiresUniqueEmail); return sb.ToString(); } /// <summary> /// Returns the current request IP address for logging if there is one /// </summary> /// <returns></returns> protected string GetCurrentRequestIpAddress() { var httpContext = HttpContext.Current == null ? (HttpContextBase) null : new HttpContextWrapper(HttpContext.Current); return httpContext.GetCurrentRequestIpAddress(); } } }
using Serilog.Core; using Serilog.Core.Enrichers; using Serilog.Core.Pipeline; using Serilog.Events; using Serilog.Tests.Support; using System; using System.Collections.Generic; using System.Linq; using TestDummies; using Xunit; #pragma warning disable Serilog004 // Constant MessageTemplate verifier #pragma warning disable Serilog003 // Property binding verifier namespace Serilog.Tests.Core { public class LoggerTests { [Theory] [InlineData(typeof(Logger))] #if FEATURE_DEFAULT_INTERFACE [InlineData(typeof(DelegatingLogger))] #endif public void AnExceptionThrownByAnEnricherIsNotPropagated(Type loggerType) { var thrown = false; var l = CreateLogger(loggerType, lc => lc .WriteTo.Sink(new StringSink()) .Enrich.With(new DelegatingEnricher((_, _) => { thrown = true; throw new Exception("No go, pal."); }))); l.Information(Some.String()); Assert.True(thrown); } [Fact] public void AContextualLoggerAddsTheSourceTypeName() { var evt = DelegatingSink.GetLogEvent(l => l.ForContext<LoggerTests>() .Information(Some.String())); var lv = evt.Properties[Constants.SourceContextPropertyName].LiteralValue(); Assert.Equal(typeof(LoggerTests).FullName, lv); } [Fact] public void PropertiesInANestedContextOverrideParentContextValues() { var name = Some.String(); var v1 = Some.Int(); var v2 = Some.Int(); var evt = DelegatingSink.GetLogEvent(l => l.ForContext(name, v1) .ForContext(name, v2) .Write(Some.InformationEvent())); var pActual = evt.Properties[name]; Assert.Equal(v2, pActual.LiteralValue()); } [Fact] public void ParametersForAnEmptyTemplateAreIgnored() { var e = DelegatingSink.GetLogEvent(l => l.Error("message", new object())); Assert.Equal("message", e.RenderMessage()); } [Theory] [InlineData(typeof(Logger))] #if FEATURE_DEFAULT_INTERFACE [InlineData(typeof(DelegatingLogger))] #endif public void LoggingLevelSwitchDynamicallyChangesLevel(Type loggerType) { var events = new List<LogEvent>(); var sink = new DelegatingSink(events.Add); var levelSwitch = new LoggingLevelSwitch(); var log = CreateLogger(loggerType, lc => lc .MinimumLevel.ControlledBy(levelSwitch) .WriteTo.Sink(sink)) .ForContext<LoggerTests>(); log.Debug("Suppressed"); log.Information("Emitted"); log.Warning("Emitted"); // Change the level levelSwitch.MinimumLevel = LogEventLevel.Error; log.Warning("Suppressed"); log.Error("Emitted"); log.Fatal("Emitted"); Assert.Equal(4, events.Count); Assert.True(events.All(evt => evt.RenderMessage() == "Emitted")); } [Theory] [InlineData(typeof(Logger))] #if FEATURE_DEFAULT_INTERFACE [InlineData(typeof(DelegatingLogger))] #endif public void MessageTemplatesCanBeBound(Type loggerType) { var log = CreateLogger(loggerType, lc => lc); Assert.True(log.BindMessageTemplate("Hello, {Name}!", new object[] { "World" }, out var template, out var properties)); Assert.Equal("Hello, {Name}!", template!.Text); Assert.Equal("World", properties!.Single().Value.LiteralValue()); } [Theory] [InlineData(typeof(Logger))] #if FEATURE_DEFAULT_INTERFACE [InlineData(typeof(DelegatingLogger))] #endif public void PropertiesCanBeBound(Type loggerType) { var log = CreateLogger(loggerType, lc => lc); Assert.True(log.BindProperty("Name", "World", false, out var property)); Assert.Equal("Name", property!.Name); Assert.Equal("World", property.Value.LiteralValue()); } [Fact] public void TheNoneLoggerIsSilent() { Assert.IsType<SilentLogger>(Logger.None); } [Fact] public void TheNoneLoggerIsAConstant() { var firstCall = Logger.None; var secondCall = Logger.None; Assert.Equal(firstCall, secondCall); } [Fact] public void TheNoneLoggerIsSingleton() { lock (new object()) { Log.CloseAndFlush(); Assert.Same(Log.Logger, Logger.None); } } static ILogger CreateLogger(Type loggerType, Func<LoggerConfiguration, LoggerConfiguration> configureLogger) { var lc = new LoggerConfiguration(); return loggerType switch { _ when loggerType == typeof(Logger) => configureLogger(lc).CreateLogger(), #if FEATURE_DEFAULT_INTERFACE _ when loggerType == typeof(DelegatingLogger) => new DelegatingLogger(configureLogger(lc).CreateLogger()), #endif _ => throw new NotSupportedException() }; } #if FEATURE_DEFAULT_INTERFACE [Fact] public void DelegatingLoggerShouldDelegateCallsToInnerLogger() { var collectingSink = new CollectingSink(); var levelSwitch = new LoggingLevelSwitch(); var innerLogger = new LoggerConfiguration() .MinimumLevel.ControlledBy(levelSwitch) .WriteTo.Sink(collectingSink) .CreateLogger(); var delegatingLogger = new DelegatingLogger(innerLogger); var log = ((ILogger)delegatingLogger).ForContext("number", 42) .ForContext(new PropertyEnricher("type", "string")); log.Debug("suppressed"); Assert.Empty(collectingSink.Events); log.Write(LogEventLevel.Warning, new Exception("warn"), "emit some {prop} with {values}", "message", new[] { 1, 2, 3 }); Assert.Single(collectingSink.Events); Assert.Equal(LogEventLevel.Warning, collectingSink.SingleEvent.Level); Assert.Equal("warn", collectingSink.SingleEvent.Exception?.Message); Assert.Equal("string", collectingSink.SingleEvent.Properties["type"].LiteralValue()); Assert.Equal("message", collectingSink.SingleEvent.Properties["prop"].LiteralValue()); Assert.Equal(42, collectingSink.SingleEvent.Properties["number"].LiteralValue()); Assert.Equal( expected: new SequenceValue(new[] { new ScalarValue(1), new ScalarValue(2), new ScalarValue(3) }), actual: (SequenceValue)collectingSink.SingleEvent.Properties["values"], comparer: new LogEventPropertyValueComparer()); levelSwitch.MinimumLevel = LogEventLevel.Fatal; collectingSink.Events.Clear(); log.Error("error"); Assert.Empty(collectingSink.Events); innerLogger.Dispose(); Assert.False(delegatingLogger.Disposed); } #endif [Fact] public void ASingleSinkIsDisposedWhenLoggerIsDisposed() { var sink = new DisposeTrackingSink(); var log = new LoggerConfiguration() .WriteTo.Sink(sink) .CreateLogger(); log.Dispose(); Assert.True(sink.IsDisposed); } [Fact] public void AggregatedSinksAreDisposedWhenLoggerIsDisposed() { var sinkA = new DisposeTrackingSink(); var sinkB = new DisposeTrackingSink(); var log = new LoggerConfiguration() .WriteTo.Sink(sinkA) .WriteTo.Sink(sinkB) .CreateLogger(); log.Dispose(); Assert.True(sinkA.IsDisposed); Assert.True(sinkB.IsDisposed); } [Fact] public void WrappedSinksAreDisposedWhenLoggerIsDisposed() { var sink = new DisposeTrackingSink(); var log = new LoggerConfiguration() .WriteTo.Dummy(wrapped => wrapped.Sink(sink)) .CreateLogger(); log.Dispose(); Assert.True(sink.IsDisposed); } [Fact] public void WrappedAggregatedSinksAreDisposedWhenLoggerIsDisposed() { var sinkA = new DisposeTrackingSink(); var sinkB = new DisposeTrackingSink(); var log = new LoggerConfiguration() .WriteTo.Dummy(wrapped => wrapped.Sink(sinkA).WriteTo.Sink(sinkB)) .CreateLogger(); log.Dispose(); Assert.True(sinkA.IsDisposed); Assert.True(sinkB.IsDisposed); } } }
using System; using System.Globalization; namespace FluentAssertions.Specs.Types { /// <summary> /// Type assertion specs. /// </summary> public partial class TypeAssertionSpecs { } #region Internal classes used in unit tests [DummyClass("Expected", true)] public class ClassWithAttribute { } public class ClassWithInheritedAttribute : ClassWithAttribute { } public class ClassWithoutAttribute { } public class OtherClassWithoutAttribute { } [AttributeUsage(AttributeTargets.Class, Inherited = true)] public class DummyClassAttribute : Attribute { public string Name { get; } public bool IsEnabled { get; } public DummyClassAttribute(string name, bool isEnabled) { Name = name; IsEnabled = isEnabled; } } public interface IDummyInterface { } public interface IDummyInterface<T> { } public class ClassThatImplementsInterface : IDummyInterface, IDummyInterface<IDummyInterface> { } public class ClassThatDoesNotImplementInterface { } public class DummyBaseType<T> : IDummyInterface<IDummyInterface> { } public class ClassWithGenericBaseType : DummyBaseType<ClassWithGenericBaseType> { } public class ClassWithMembers { protected internal ClassWithMembers() { } private ClassWithMembers(string _) { } protected string PrivateWriteProtectedReadProperty { get => null; private set { } } internal string this[string str] { private get => str; set { } } protected internal string this[int i] { get => i.ToString(CultureInfo.InvariantCulture); private set { } } private void VoidMethod() { } private void VoidMethod(string _) { } } public class ClassExplicitlyImplementingInterface : IExplicitInterface { public string ImplicitStringProperty { get => null; private set { } } string IExplicitInterface.ExplicitStringProperty { set { } } public string ExplicitImplicitStringProperty { get; set; } string IExplicitInterface.ExplicitImplicitStringProperty { get; set; } public void ImplicitMethod() { } public void ImplicitMethod(string overload) { } void IExplicitInterface.ExplicitMethod() { } void IExplicitInterface.ExplicitMethod(string overload) { } public void ExplicitImplicitMethod() { } public void ExplicitImplicitMethod(string _) { } void IExplicitInterface.ExplicitImplicitMethod() { } void IExplicitInterface.ExplicitImplicitMethod(string overload) { } } public interface IExplicitInterface { string ImplicitStringProperty { get; } string ExplicitStringProperty { set; } string ExplicitImplicitStringProperty { get; set; } void ImplicitMethod(); void ImplicitMethod(string overload); void ExplicitMethod(); void ExplicitMethod(string overload); void ExplicitImplicitMethod(); void ExplicitImplicitMethod(string overload); } public class ClassWithoutMembers { } public interface IPublicInterface { } internal interface IInternalInterface { } internal class InternalClass { } internal struct InternalStruct { } internal enum InternalEnum { Value1, Value2 } internal class Nested { private class PrivateClass { } protected enum ProtectedEnum { } public interface IPublicInterface { } internal class InternalClass { } protected internal interface IProtectedInternalInterface { } } internal readonly struct TypeWithConversionOperators { private readonly int value; private TypeWithConversionOperators(int value) { this.value = value; } public static implicit operator int(TypeWithConversionOperators typeWithConversionOperators) => typeWithConversionOperators.value; public static explicit operator byte(TypeWithConversionOperators typeWithConversionOperators) => (byte)typeWithConversionOperators.value; } internal sealed class Sealed { } internal abstract class Abstract { } internal static class Static { } internal struct Struct { } public delegate void ExampleDelegate(); internal class ClassNotInDummyNamespace { } internal class OtherClassNotInDummyNamespace { } #endregion } namespace AssemblyB { #pragma warning disable 436 // disable the warning on conflicting types, as this is the intention for the spec /// <summary> /// A class that intentionally has the exact same name and namespace as the ClassC from the AssemblyB /// assembly. This class is used to test the behavior of comparisons on such types. /// </summary> internal class ClassC { } #pragma warning restore 436 } #region Internal classes used in unit tests namespace DummyNamespace { internal class ClassInDummyNamespace { } namespace InnerDummyNamespace { internal class ClassInInnerDummyNamespace { } } } namespace DummyNamespaceTwo { internal class ClassInDummyNamespaceTwo { } } #endregion
using System; using System.Collections.Generic; using Newtonsoft.Json; /* * AvaTax API Client Library * * (c) 2004-2019 Avalara, Inc. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @author Genevieve Conty * @author Greg Hester * Swagger name: AvaTaxClient */ namespace Avalara.AvaTax.RestClient { /// <summary> /// Create a transaction /// </summary> public class CreateTransactionModel { /// <summary> /// The internal reference code used by the client application. This is used for operations such as /// Get, Adjust, Settle, and Void. If you leave the transaction code blank, a GUID will be assigned to each transaction. /// </summary> public String code { get; set; } /// <summary> /// A list of line items that will appear on this transaction. /// </summary> public List<LineItemModel> lines { get; set; } /// <summary> /// Specifies the type of document to create. A document type ending with `Invoice` is a permanent transaction /// that will be recorded in AvaTax. A document type ending with `Order` is a temporary estimate that will not /// be preserved. /// /// If you omit this value, the API will assume you want to create a `SalesOrder`. /// </summary> public DocumentType? type { get; set; } /// <summary> /// Company Code - Specify the code of the company creating this transaction here. If you leave this value null, /// your account's default company will be used instead. /// </summary> public String companyCode { get; set; } /// <summary> /// Transaction Date - The date on the invoice, purchase order, etc. /// /// By default, this date will be used to calculate the tax rates for the transaction. If you wish to use a /// different date to calculate tax rates, please specify a `taxOverride` of type `taxDate`. /// </summary> public DateTime date { get; set; } /// <summary> /// Salesperson Code - The client application salesperson reference code. /// </summary> public String salespersonCode { get; set; } /// <summary> /// Customer Code - The client application customer reference code. /// Note: This field is case sensitive. To have exemption certificates apply, this value should /// be the same as the one passed to create a customer. /// </summary> public String customerCode { get; set; } /// <summary> /// DEPRECATED - Date: 10/16/2017, Version: 17.11, Message: Please use entityUseCode instead. /// Customer Usage Type - The client application customer or usage type. /// </summary> public String customerUsageType { get; set; } /// <summary> /// Entity Use Code - The client application customer or usage type. For a list of /// available usage types, use [ListEntityUseCodes](https://developer.avalara.com/api-reference/avatax/rest/v2/methods/Definitions/ListEntityUseCodes/) API. /// </summary> public String entityUseCode { get; set; } /// <summary> /// Discount - The discount amount to apply to the document. This value will be applied only to lines /// that have the `discounted` flag set to true. If no lines have `discounted` set to true, this discount /// cannot be applied. /// </summary> public Decimal? discount { get; set; } /// <summary> /// Purchase Order Number for this document. /// /// This is required for single use exemption certificates to match the order and invoice with the certificate. /// </summary> public String purchaseOrderNo { get; set; } /// <summary> /// Exemption Number for this document. /// /// If you specify an exemption number for this document, this document will be considered exempt, and you /// may be asked to provide proof of this exemption certificate in the event that you are asked by an auditor /// to verify your exemptions. /// Note: This is same as 'exemptNo' in TransactionModel. /// </summary> public String exemptionNo { get; set; } /// <summary> /// /// </summary> public AddressesModel addresses { get; set; } /// <summary> /// Special parameters for this transaction. /// /// To get a full list of available parameters, please use the [ListParameters](https://developer.avalara.com/api-reference/avatax/rest/v2/methods/Definitions/ListParameters/) endpoint. /// </summary> public List<TransactionParameterModel> parameters { get; set; } /// <summary> /// Custom user fields/flex fields for this transaction. /// </summary> public List<TransactionUserDefinedFieldModel> userDefinedFields { get; set; } /// <summary> /// Customer-provided Reference Code with information about this transaction. /// /// This field could be used to reference the original document for a return invoice, or for any other /// reference purpose. /// </summary> public String referenceCode { get; set; } /// <summary> /// Sets the sale location code (Outlet ID) for reporting this document to the tax authority. /// /// This value is used by Avalara Managed Returns to group documents together by reporting locations /// for tax authorities that require location-based reporting. /// </summary> public String reportingLocationCode { get; set; } /// <summary> /// Causes the document to be committed if true. This option is only applicable for invoice document /// types, not orders. /// </summary> public Boolean? commit { get; set; } /// <summary> /// BatchCode for batch operations. /// </summary> public String batchCode { get; set; } /// <summary> /// /// </summary> public TaxOverrideModel taxOverride { get; set; } /// <summary> /// The three-character ISO 4217 currency code for this transaction. /// </summary> public String currencyCode { get; set; } /// <summary> /// Specifies whether the tax calculation is handled Local, Remote, or Automatic (default). This only /// applies when using an AvaLocal server. /// </summary> public ServiceMode? serviceMode { get; set; } /// <summary> /// Currency exchange rate from this transaction to the company base currency. /// /// This only needs to be set if the transaction currency is different than the company base currency. /// It defaults to 1.0. /// </summary> public Decimal? exchangeRate { get; set; } /// <summary> /// Effective date of the exchange rate. /// </summary> public DateTime? exchangeRateEffectiveDate { get; set; } /// <summary> /// Optional three-character ISO 4217 reporting exchange rate currency code for this transaction. The default value is USD. /// </summary> public String exchangeRateCurrencyCode { get; set; } /// <summary> /// Sets the Point of Sale Lane Code sent by the User for this document. /// </summary> public String posLaneCode { get; set; } /// <summary> /// VAT business identification number for the customer for this transaction. This number will be used for all lines /// in the transaction, except for those lines where you have defined a different business identification number. /// /// If you specify a VAT business identification number for the customer in this transaction and you have also set up /// a business identification number for your company during company setup, this transaction will be treated as a /// business-to-business transaction for VAT purposes and it will be calculated according to VAT tax rules. /// </summary> public String businessIdentificationNo { get; set; } /// <summary> /// Specifies if the transaction should have value-added and cross-border taxes calculated with the seller as the importer of record. /// /// Some taxes only apply if the seller is the importer of record for a product. In cases where companies are working together to /// ship products, there may be mutual agreement as to which company is the entity designated as importer of record. The importer /// of record will then be the company designated to pay taxes marked as being obligated to the importer of record. /// /// Set this value to `true` to consider your company as the importer of record and collect these taxes. /// /// This value may also be set at the Nexus level. See `NexusModel` for more information. /// </summary> public Boolean? isSellerImporterOfRecord { get; set; } /// <summary> /// User-supplied description for this transaction. /// </summary> public String description { get; set; } /// <summary> /// User-supplied email address relevant for this transaction. /// </summary> public String email { get; set; } /// <summary> /// If the user wishes to request additional debug information from this transaction, specify a level higher than `normal`. /// </summary> public TaxDebugLevel? debugLevel { get; set; } /// <summary> /// The name of the supplier / exporter / seller. /// For sales doctype enter the name of your own company for which you are reporting. /// For purchases doctype enter the name of the supplier you have purchased from. /// </summary> public String customerSupplierName { get; set; } /// <summary> /// The Id of the datasource from which this transaction originated. /// This value will be overridden by the system to take the datasource Id from the call header. /// </summary> public Int32? dataSourceId { get; set; } /// <summary> /// The Delivery Terms is a field used in conjunction with Importer of Record to influence whether AvaTax includes Import Duty and Tax values in the transaction totals or not. /// Delivered at Place (DAP) and Delivered Duty Paid (DDP) are two delivery terms that indicate that Import Duty and Tax should be included in the transaction total. /// This field is also used for reports. /// This field is used for future feature support. This field is not currently in use. /// </summary> public DeliveryTerms? deliveryTerms { get; set; } /// <summary> /// Convert this object to a JSON string of itself /// </summary> /// <returns>A JSON string of this object</returns> public override string ToString() { return JsonConvert.SerializeObject(this, new JsonSerializerSettings() { Formatting = Formatting.Indented }); } } }
// <copyright file="InternetExplorerDriver.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 OpenQA.Selenium.Internal; using OpenQA.Selenium.Remote; namespace OpenQA.Selenium.IE { /// <summary> /// Provides a way to access Internet Explorer to run your tests by creating a InternetExplorerDriver instance /// </summary> /// <remarks> /// When the WebDriver object has been instantiated the browser will load. The test can then navigate to the URL under test and /// start your test. /// </remarks> /// <example> /// <code> /// [TestFixture] /// public class Testing /// { /// private IWebDriver driver; /// <para></para> /// [SetUp] /// public void SetUp() /// { /// driver = new InternetExplorerDriver(); /// } /// <para></para> /// [Test] /// public void TestGoogle() /// { /// driver.Navigate().GoToUrl("http://www.google.co.uk"); /// /* /// * Rest of the test /// */ /// } /// <para></para> /// [TearDown] /// public void TearDown() /// { /// driver.Quit(); /// driver.Dispose(); /// } /// } /// </code> /// </example> public class InternetExplorerDriver : RemoteWebDriver { /// <summary> /// Initializes a new instance of the <see cref="InternetExplorerDriver"/> class. /// </summary> public InternetExplorerDriver() : this(new InternetExplorerOptions()) { } /// <summary> /// Initializes a new instance of the <see cref="InternetExplorerDriver"/> class with the desired /// options. /// </summary> /// <param name="options">The <see cref="InternetExplorerOptions"/> used to initialize the driver.</param> public InternetExplorerDriver(InternetExplorerOptions options) : this(InternetExplorerDriverService.CreateDefaultService(), options) { } /// <summary> /// Initializes a new instance of the <see cref="InternetExplorerDriver"/> class using the specified driver service. /// </summary> /// <param name="service">The <see cref="InternetExplorerDriverService"/> used to initialize the driver.</param> public InternetExplorerDriver(InternetExplorerDriverService service) : this(service, new InternetExplorerOptions()) { } /// <summary> /// Initializes a new instance of the <see cref="InternetExplorerDriver"/> class using the specified path /// to the directory containing IEDriverServer.exe. /// </summary> /// <param name="internetExplorerDriverServerDirectory">The full path to the directory containing IEDriverServer.exe.</param> public InternetExplorerDriver(string internetExplorerDriverServerDirectory) : this(internetExplorerDriverServerDirectory, new InternetExplorerOptions()) { } /// <summary> /// Initializes a new instance of the <see cref="InternetExplorerDriver"/> class using the specified path /// to the directory containing IEDriverServer.exe and options. /// </summary> /// <param name="internetExplorerDriverServerDirectory">The full path to the directory containing IEDriverServer.exe.</param> /// <param name="options">The <see cref="InternetExplorerOptions"/> used to initialize the driver.</param> public InternetExplorerDriver(string internetExplorerDriverServerDirectory, InternetExplorerOptions options) : this(internetExplorerDriverServerDirectory, options, RemoteWebDriver.DefaultCommandTimeout) { } /// <summary> /// Initializes a new instance of the <see cref="InternetExplorerDriver"/> class using the specified path /// to the directory containing IEDriverServer.exe, options, and command timeout. /// </summary> /// <param name="internetExplorerDriverServerDirectory">The full path to the directory containing IEDriverServer.exe.</param> /// <param name="options">The <see cref="InternetExplorerOptions"/> used to initialize the driver.</param> /// <param name="commandTimeout">The maximum amount of time to wait for each command.</param> public InternetExplorerDriver(string internetExplorerDriverServerDirectory, InternetExplorerOptions options, TimeSpan commandTimeout) : this(InternetExplorerDriverService.CreateDefaultService(internetExplorerDriverServerDirectory), options, commandTimeout) { } /// <summary> /// Initializes a new instance of the <see cref="InternetExplorerDriver"/> class using the specified /// <see cref="InternetExplorerDriverService"/> and options. /// </summary> /// <param name="service">The <see cref="DriverService"/> to use.</param> /// <param name="options">The <see cref="InternetExplorerOptions"/> used to initialize the driver.</param> public InternetExplorerDriver(InternetExplorerDriverService service, InternetExplorerOptions options) : this(service, options, RemoteWebDriver.DefaultCommandTimeout) { } /// <summary> /// Initializes a new instance of the <see cref="InternetExplorerDriver"/> class using the specified /// <see cref="DriverService"/>, <see cref="InternetExplorerOptions"/>, and command timeout. /// </summary> /// <param name="service">The <see cref="InternetExplorerDriverService"/> to use.</param> /// <param name="options">The <see cref="InternetExplorerOptions"/> used to initialize the driver.</param> /// <param name="commandTimeout">The maximum amount of time to wait for each command.</param> public InternetExplorerDriver(InternetExplorerDriverService service, InternetExplorerOptions options, TimeSpan commandTimeout) : base(new DriverServiceCommandExecutor(service, commandTimeout), ConvertOptionsToCapabilities(options)) { } /// <summary> /// Gets or sets the <see cref="IFileDetector"/> responsible for detecting /// sequences of keystrokes representing file paths and names. /// </summary> /// <remarks>The IE driver does not allow a file detector to be set, /// as the server component of the IE driver (IEDriverServer.exe) only /// allows uploads from the local computer environment. Attempting to set /// this property has no effect, but does not throw an exception. If you /// are attempting to run the IE driver remotely, use <see cref="RemoteWebDriver"/> /// in conjunction with a standalone WebDriver server.</remarks> public override IFileDetector FileDetector { get { return base.FileDetector; } set { } } /// <summary> /// Gets the capabilities as a dictionary supporting legacy drivers. /// </summary> /// <param name="legacyCapabilities">The dictionary to return.</param> /// <returns>A Dictionary consisting of the capabilities requested.</returns> /// <remarks>This method is only transitional. Do not rely on it. It will be removed /// once browser driver capability formats stabilize.</remarks> protected override Dictionary<string, object> GetLegacyCapabilitiesDictionary(ICapabilities legacyCapabilities) { // Flatten the dictionary, if required to support old versions of the IE driver. Dictionary<string, object> capabilitiesDictionary = new Dictionary<string, object>(); IHasCapabilitiesDictionary capabilitiesObject = legacyCapabilities as IHasCapabilitiesDictionary; foreach (KeyValuePair<string, object> entry in capabilitiesObject.CapabilitiesDictionary) { if (entry.Key == InternetExplorerOptions.Capability) { Dictionary<string, object> internetExplorerOptions = entry.Value as Dictionary<string, object>; foreach (KeyValuePair<string, object> option in internetExplorerOptions) { capabilitiesDictionary.Add(option.Key, option.Value); } } else { capabilitiesDictionary.Add(entry.Key, entry.Value); } } return capabilitiesDictionary; } private static ICapabilities ConvertOptionsToCapabilities(InternetExplorerOptions options) { if (options == null) { throw new ArgumentNullException("options", "options must not be null"); } return options.ToCapabilities(); } } }
#region License /* * Copyright (C) 2002-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion using System; using System.Collections.Generic; using System.Threading; namespace Java.Util.Concurrent.Locks { /// <author>Doug Lea</author> /// <author>Griffin Caprio (.NET)</author> /// <author>Kenneth Xu</author> [Serializable] internal class ConditionVariable : ICondition // BACKPORT_3_1 { private const string _notSupportedMessage = "Use FAIR version"; protected internal IExclusiveLock _lock; /// <summary> /// Create a new <see cref="ConditionVariable"/> that relies on the given mutual /// exclusion lock. /// </summary> /// <param name="lock"> /// A non-reentrant mutual exclusion lock. /// </param> internal ConditionVariable(IExclusiveLock @lock) { _lock = @lock; } protected internal virtual IExclusiveLock Lock { get { return _lock; } } protected internal virtual int WaitQueueLength { get { throw new NotSupportedException(_notSupportedMessage); } } protected internal virtual ICollection<Thread> WaitingThreads { get { throw new NotSupportedException(_notSupportedMessage); } } protected internal virtual bool HasWaiters { get { throw new NotSupportedException(_notSupportedMessage); } } #region ICondition Members public virtual void AwaitUninterruptibly() { int holdCount = _lock.HoldCount; if (holdCount == 0) { throw new SynchronizationLockException(); } bool wasInterrupted = false; try { lock (this) { for (int i = holdCount; i > 0; i--) _lock.Unlock(); try { Monitor.Wait(this); } catch (ThreadInterruptedException) { wasInterrupted = true; // may have masked the signal and there is no way // to tell; we must wake up spuriously. } } } finally { for (int i = holdCount; i > 0; i--) _lock.Lock(); if (wasInterrupted) { Thread.CurrentThread.Interrupt(); } } } public virtual void Await() { int holdCount = _lock.HoldCount; if (holdCount == 0) { throw new SynchronizationLockException(); } // This requires sleep(0) to implement in .Net, too expensive! // if (Thread.interrupted()) throw new InterruptedException(); try { lock (this) { for (int i = holdCount; i > 0; i--) _lock.Unlock(); try { Monitor.Wait(this); } catch (ThreadInterruptedException e) { Monitor.Pulse(this); throw SystemExtensions.PreserveStackTrace(e); } } } finally { for (int i = holdCount; i > 0; i--) _lock.Lock(); } } public virtual bool Await(TimeSpan durationToWait) { int holdCount = _lock.HoldCount; if (holdCount == 0) { throw new SynchronizationLockException(); } // This requires sleep(0) to implement in .Net, too expensive! // if (Thread.interrupted()) throw new InterruptedException(); try { lock (this) { for (int i = holdCount; i > 0; i--) _lock.Unlock(); try { // .Net implementation is a little different than backport 3.1 // by taking advantage of the return value from Monitor.Wait. return (durationToWait.Ticks > 0) && Monitor.Wait(this, durationToWait); } catch (ThreadInterruptedException e) { Monitor.Pulse(this); throw SystemExtensions.PreserveStackTrace(e); } } } finally { for (int i = holdCount; i > 0; i--) _lock.Lock(); } } public virtual bool AwaitUntil(DateTime deadline) { int holdCount = _lock.HoldCount; if (holdCount == 0) { throw new SynchronizationLockException(); } if ((deadline.Subtract(DateTime.UtcNow)).Ticks <= 0) return false; // This requires sleep(0) to implement in .Net, too expensive! // if (Thread.interrupted()) throw new InterruptedException(); try { lock (this) { for (int i = holdCount; i > 0; i--) _lock.Unlock(); try { // .Net has DateTime precision issue so we need to retry. TimeSpan durationToWait; while ((durationToWait = deadline.Subtract(DateTime.UtcNow)).Ticks > 0) { // .Net implementation is different than backport 3.1 // by taking advantage of the return value from Monitor.Wait. if (Monitor.Wait(this, durationToWait)) return true; } } catch (ThreadInterruptedException e) { Monitor.Pulse(this); throw SystemExtensions.PreserveStackTrace(e); } } } finally { for (int i = holdCount; i > 0; i--) _lock.Lock(); } return false; } public virtual void Signal() { lock (this) { AssertOwnership(); Monitor.Pulse(this); } } public virtual void SignalAll() { lock (this) { AssertOwnership(); Monitor.PulseAll(this); } } #endregion protected void AssertOwnership() { if (!_lock.IsHeldByCurrentThread) { throw new SynchronizationLockException(); } } internal interface IExclusiveLock : ILock { bool IsHeldByCurrentThread { get; } int HoldCount { get; } } } }
// 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 Microsoft.CodeAnalysis.Editor.CSharp.SignatureHelp; using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp { public class ObjectCreationExpressionSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests { public ObjectCreationExpressionSignatureHelpProviderTests(CSharpTestWorkspaceFixture workspaceFixture) : base(workspaceFixture) { } internal override ISignatureHelpProvider CreateSignatureHelpProvider() { return new ObjectCreationExpressionSignatureHelpProvider(); } #region "Regular tests" [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationWithoutParameters() { var markup = @" class C { void foo() { var c = [|new C($$|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C()", string.Empty, null, currentParameterIndex: 0)); Test(markup, expectedOrderedItems); } [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationWithoutParametersMethodXmlComments() { var markup = @" class C { /// <summary> /// Summary for C /// </summary> C() { } void Foo() { C c = [|new C($$|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C()", "Summary for C", null, currentParameterIndex: 0)); Test(markup, expectedOrderedItems); } [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationWithParametersOn1() { var markup = @" class C { C(int a, int b) { } void Foo() { C c = [|new C($$2, 3|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 0)); Test(markup, expectedOrderedItems); } [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationWithParametersXmlCommentsOn1() { var markup = @" class C { /// <summary> /// Summary for C /// </summary> /// <param name=""a"">Param a</param> /// <param name=""b"">Param b</param> C(int a, int b) { } void Foo() { C c = [|new C($$2, 3|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, int b)", "Summary for C", "Param a", currentParameterIndex: 0)); Test(markup, expectedOrderedItems); } [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationWithParametersOn2() { var markup = @" class C { C(int a, int b) { } void Foo() { C c = [|new C(2, $$3|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1)); Test(markup, expectedOrderedItems); } [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationWithParametersXmlComentsOn2() { var markup = @" class C { /// <summary> /// Summary for C /// </summary> /// <param name=""a"">Param a</param> /// <param name=""b"">Param b</param> C(int a, int b) { } void Foo() { C c = [|new C(2, $$3|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, int b)", "Summary for C", "Param b", currentParameterIndex: 1)); Test(markup, expectedOrderedItems); } [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationWithoutClosingParen() { var markup = @" class C { void foo() { var c = [|new C($$ |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C()", string.Empty, null, currentParameterIndex: 0)); Test(markup, expectedOrderedItems); } [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationWithoutClosingParenWithParameters() { var markup = @" class C { C(int a, int b) { } void Foo() { C c = [|new C($$2, 3 |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 0)); Test(markup, expectedOrderedItems); } [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationWithoutClosingParenWithParametersOn2() { var markup = @" class C { C(int a, int b) { } void Foo() { C c = [|new C(2, $$3 |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1)); Test(markup, expectedOrderedItems); } [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationOnLambda() { var markup = @" using System; class C { void foo() { var bar = [|new Action<int, int>($$ |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("Action<int, int>(void (int, int) target)", string.Empty, string.Empty, currentParameterIndex: 0)); Test(markup, expectedOrderedItems); } #endregion #region "Current Parameter Name" [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestCurrentParameterName() { var markup = @" class C { C(int a, string b) { } void foo() { var c = [|new C(b: string.Empty, $$a: 2|]); } }"; VerifyCurrentParameterName(markup, "a"); } #endregion #region "Trigger tests" [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationOnTriggerParens() { var markup = @" class C { void foo() { var c = [|new C($$|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C()", string.Empty, null, currentParameterIndex: 0)); Test(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationOnTriggerComma() { var markup = @" class C { C(int a, string b) { } void foo() { var c = [|new C(2,$$string.Empty|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, string b)", string.Empty, string.Empty, currentParameterIndex: 1)); Test(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestNoInvocationOnSpace() { var markup = @" class C { C(int a, string b) { } void foo() { var c = [|new C(2, $$string.Empty|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); Test(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestTriggerCharacters() { char[] expectedCharacters = { ',', '(' }; char[] unexpectedCharacters = { ' ', '[', '<' }; VerifyTriggerCharacters(expectedCharacters, unexpectedCharacters); } #endregion #region "EditorBrowsable tests" [WorkItem(7336, "DevDiv_Projects/Roslyn")] [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void EditorBrowsable_Constructor_BrowsableAlways() { var markup = @" class Program { void M() { new Foo($$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public Foo(int x) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("Foo(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); TestSignatureHelpInEditorBrowsableContexts(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void EditorBrowsable_Constructor_BrowsableNever() { var markup = @" class Program { void M() { new Foo($$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public Foo(int x) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("Foo(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); TestSignatureHelpInEditorBrowsableContexts(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void EditorBrowsable_Constructor_BrowsableAdvanced() { var markup = @" class Program { void M() { new Foo($$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public Foo() { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("Foo()", string.Empty, null, currentParameterIndex: 0)); TestSignatureHelpInEditorBrowsableContexts(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); TestSignatureHelpInEditorBrowsableContexts(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void EditorBrowsable_Constructor_BrowsableMixed() { var markup = @" class Program { void M() { new Foo($$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public Foo(int x) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public Foo(long y) { } }"; var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>(); expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("Foo(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>(); expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("Foo(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("Foo(long y)", string.Empty, string.Empty, currentParameterIndex: 0)); TestSignatureHelpInEditorBrowsableContexts(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference, expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } #endregion [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void FieldUnavailableInOneLinkedFile() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if FOO class D { } #endif void foo() { var x = new D($$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = new SignatureHelpTestItem($"D()\r\n\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj2", FeaturesResources.NotAvailable)}\r\n\r\n{FeaturesResources.UseTheNavigationBarToSwitchContext}", currentParameterIndex: 0); VerifyItemWithReferenceWorker(markup, new[] { expectedDescription }, false); } [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void ExcludeFilesWithInactiveRegions() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO,BAR""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if FOO class D { } #endif #if BAR void foo() { var x = new D($$ } #endif } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument"" /> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = new SignatureHelpTestItem($"D()\r\n\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj3", FeaturesResources.NotAvailable)}\r\n\r\n{FeaturesResources.UseTheNavigationBarToSwitchContext}", currentParameterIndex: 0); VerifyItemWithReferenceWorker(markup, new[] { expectedDescription }, false); } [WorkItem(1067933)] [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void InvokedWithNoToken() { var markup = @" // new foo($$"; Test(markup); } [WorkItem(1078993)] [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestSigHelpInIncorrectObjectCreationExpression() { var markup = @" class C { void foo(C c) { foo([|new C{$$|] } }"; Test(markup); } } }
// 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. //////////////////////////////////////////////////////////////////////////// // // // // Purpose: This class represents the software preferences of a particular // culture or community. It includes information such as the // language, writing system, and a calendar used by the culture // as well as methods for common operations such as printing // dates and sorting strings. // // // // !!!! NOTE WHEN CHANGING THIS CLASS !!!! // // If adding or removing members to this class, please update CultureInfoBaseObject // in ndp/clr/src/vm/object.h. Note, the "actual" layout of the class may be // different than the order in which members are declared. For instance, all // reference types will come first in the class before value types (like ints, bools, etc) // regardless of the order in which they are declared. The best way to see the // actual order of the class is to do a !dumpobj on an instance of the managed // object inside of the debugger. // //////////////////////////////////////////////////////////////////////////// using System.Collections.Generic; using System.Diagnostics; using System.Threading; namespace System.Globalization { /// <summary> /// This class represents the software preferences of a particular culture /// or community. It includes information such as the language, writing /// system and a calendar used by the culture as well as methods for /// common operations such as printing dates and sorting strings. /// </summary> /// <remarks> /// !!!! NOTE WHEN CHANGING THIS CLASS !!!! /// If adding or removing members to this class, please update /// CultureInfoBaseObject in ndp/clr/src/vm/object.h. Note, the "actual" /// layout of the class may be different than the order in which members /// are declared. For instance, all reference types will come first in the /// class before value types (like ints, bools, etc) regardless of the /// order in which they are declared. The best way to see the actual /// order of the class is to do a !dumpobj on an instance of the managed /// object inside of the debugger. /// </remarks> public partial class CultureInfo : IFormatProvider, ICloneable { // We use an RFC4646 type string to construct CultureInfo. // This string is stored in _name and is authoritative. // We use the _cultureData to get the data for our object private bool _isReadOnly; private CompareInfo? _compareInfo; private TextInfo? _textInfo; internal NumberFormatInfo? _numInfo; internal DateTimeFormatInfo? _dateTimeInfo; private Calendar? _calendar; // // The CultureData instance that we are going to read data from. // For supported culture, this will be the CultureData instance that read data from mscorlib assembly. // For customized culture, this will be the CultureData instance that read data from user customized culture binary file. // internal CultureData _cultureData; internal bool _isInherited; private CultureInfo? _consoleFallbackCulture; // Names are confusing. Here are 3 names we have: // // new CultureInfo() _name _nonSortName _sortName // en-US en-US en-US en-US // de-de_phoneb de-DE_phoneb de-DE de-DE_phoneb // fj-fj (custom) fj-FJ fj-FJ en-US (if specified sort is en-US) // en en // // Note that in Silverlight we ask the OS for the text and sort behavior, so the // textinfo and compareinfo names are the same as the name // This has a de-DE, de-DE_phoneb or fj-FJ style name internal string _name; // This will hold the non sorting name to be returned from CultureInfo.Name property. // This has a de-DE style name even for de-DE_phoneb type cultures private string? _nonSortName; // This will hold the sorting name to be returned from CultureInfo.SortName property. // This might be completely unrelated to the culture name if a custom culture. Ie en-US for fj-FJ. // Otherwise its the sort name, ie: de-DE or de-DE_phoneb private string? _sortName; // Get the current user default culture. This one is almost always used, so we create it by default. private static volatile CultureInfo? s_userDefaultCulture; // The culture used in the user interface. This is mostly used to load correct localized resources. private static volatile CultureInfo? s_userDefaultUICulture; // WARNING: We allow diagnostic tools to directly inspect these three members (s_InvariantCultureInfo, s_DefaultThreadCurrentUICulture and s_DefaultThreadCurrentCulture) // See https://github.com/dotnet/corert/blob/master/Documentation/design-docs/diagnostics/diagnostics-tools-contract.md for more details. // Please do not change the type, the name, or the semantic usage of this member without understanding the implication for tools. // Get in touch with the diagnostics team if you have questions. // The Invariant culture; private static readonly CultureInfo s_InvariantCultureInfo = new CultureInfo(CultureData.Invariant, isReadOnly: true); // These are defaults that we use if a thread has not opted into having an explicit culture private static volatile CultureInfo? s_DefaultThreadCurrentUICulture; private static volatile CultureInfo? s_DefaultThreadCurrentCulture; [ThreadStatic] private static CultureInfo? s_currentThreadCulture; [ThreadStatic] private static CultureInfo? s_currentThreadUICulture; private static AsyncLocal<CultureInfo>? s_asyncLocalCurrentCulture; private static AsyncLocal<CultureInfo>? s_asyncLocalCurrentUICulture; private static void AsyncLocalSetCurrentCulture(AsyncLocalValueChangedArgs<CultureInfo> args) { s_currentThreadCulture = args.CurrentValue; } private static void AsyncLocalSetCurrentUICulture(AsyncLocalValueChangedArgs<CultureInfo> args) { s_currentThreadUICulture = args.CurrentValue; } private static volatile Dictionary<string, CultureInfo>? s_cachedCulturesByName; private static volatile Dictionary<int, CultureInfo>? s_cachedCulturesByLcid; // The parent culture. private CultureInfo? _parent; // LOCALE constants of interest to us internally and privately for LCID functions // (ie: avoid using these and use names if possible) internal const int LOCALE_NEUTRAL = 0x0000; private const int LOCALE_USER_DEFAULT = 0x0400; private const int LOCALE_SYSTEM_DEFAULT = 0x0800; internal const int LOCALE_CUSTOM_UNSPECIFIED = 0x1000; internal const int LOCALE_CUSTOM_DEFAULT = 0x0c00; internal const int LOCALE_INVARIANT = 0x007F; private static CultureInfo InitializeUserDefaultCulture() { Interlocked.CompareExchange(ref s_userDefaultCulture, GetUserDefaultCulture(), null); return s_userDefaultCulture!; } private static CultureInfo InitializeUserDefaultUICulture() { Interlocked.CompareExchange(ref s_userDefaultUICulture, GetUserDefaultUICulture(), null); return s_userDefaultUICulture!; } public CultureInfo(string name) : this(name, true) { } public CultureInfo(string name, bool useUserOverride) { if (name == null) { throw new ArgumentNullException(nameof(name)); } // Get our data providing record CultureData? cultureData = CultureData.GetCultureData(name, useUserOverride); if (cultureData == null) { throw new CultureNotFoundException(nameof(name), name, SR.Argument_CultureNotSupported); } _cultureData = cultureData; _name = _cultureData.CultureName; _isInherited = GetType() != typeof(CultureInfo); } private CultureInfo(CultureData cultureData, bool isReadOnly = false) { Debug.Assert(cultureData != null); _cultureData = cultureData; _name = cultureData.CultureName; _isInherited = false; _isReadOnly = isReadOnly; } private static CultureInfo? CreateCultureInfoNoThrow(string name, bool useUserOverride) { Debug.Assert(name != null); CultureData? cultureData = CultureData.GetCultureData(name, useUserOverride); if (cultureData == null) { return null; } return new CultureInfo(cultureData); } public CultureInfo(int culture) : this(culture, true) { } public CultureInfo(int culture, bool useUserOverride) { // We don't check for other invalid LCIDS here... if (culture < 0) { throw new ArgumentOutOfRangeException(nameof(culture), SR.ArgumentOutOfRange_NeedPosNum); } switch (culture) { case LOCALE_CUSTOM_DEFAULT: case LOCALE_SYSTEM_DEFAULT: case LOCALE_NEUTRAL: case LOCALE_USER_DEFAULT: case LOCALE_CUSTOM_UNSPECIFIED: // Can't support unknown custom cultures and we do not support neutral or // non-custom user locales. throw new CultureNotFoundException(nameof(culture), culture, SR.Argument_CultureNotSupported); default: // Now see if this LCID is supported in the system default CultureData table. _cultureData = CultureData.GetCultureData(culture, useUserOverride); break; } _isInherited = GetType() != typeof(CultureInfo); _name = _cultureData.CultureName; } /// <summary> /// Constructor called by SQL Server's special munged culture - creates a culture with /// a TextInfo and CompareInfo that come from a supplied alternate source. This object /// is ALWAYS read-only. /// Note that we really cannot use an LCID version of this override as the cached /// name we create for it has to include both names, and the logic for this is in /// the GetCultureInfo override *only*. /// </summary> internal CultureInfo(string cultureName, string textAndCompareCultureName) { if (cultureName == null) { throw new ArgumentNullException(nameof(cultureName), SR.ArgumentNull_String); } CultureData? cultureData = CultureData.GetCultureData(cultureName, false) ?? throw new CultureNotFoundException(nameof(cultureName), cultureName, SR.Argument_CultureNotSupported); _cultureData = cultureData; _name = _cultureData.CultureName; CultureInfo altCulture = GetCultureInfo(textAndCompareCultureName); _compareInfo = altCulture.CompareInfo; _textInfo = altCulture.TextInfo; } /// <summary> /// We do this to try to return the system UI language and the default user languages /// This method will fallback if this fails (like Invariant) /// </summary> private static CultureInfo GetCultureByName(string name) { try { return new CultureInfo(name) { _isReadOnly = true }; } catch (ArgumentException) { return InvariantCulture; } } /// <summary> /// Return a specific culture. A tad irrelevent now since we always /// return valid data for neutral locales. /// /// Note that there's interesting behavior that tries to find a /// smaller name, ala RFC4647, if we can't find a bigger name. /// That doesn't help with things like "zh" though, so the approach /// is of questionable value /// </summary> public static CultureInfo CreateSpecificCulture(string name) { CultureInfo? culture; try { culture = new CultureInfo(name); } catch (ArgumentException) { // When CultureInfo throws this exception, it may be because someone passed the form // like "az-az" because it came out of an http accept lang. We should try a little // parsing to perhaps fall back to "az" here and use *it* to create the neutral. culture = null; for (int idx = 0; idx < name.Length; idx++) { if ('-' == name[idx]) { try { culture = new CultureInfo(name.Substring(0, idx)); break; } catch (ArgumentException) { // throw the original exception so the name in the string will be right throw; } } } if (culture == null) { // nothing to save here; throw the original exception throw; } } // In the most common case, they've given us a specific culture, so we'll just return that. if (!culture.IsNeutralCulture) { return culture; } return new CultureInfo(culture._cultureData.SpecificCultureName); } internal static bool VerifyCultureName(string cultureName, bool throwException) { // This function is used by ResourceManager.GetResourceFileName(). // ResourceManager searches for resource using CultureInfo.Name, // so we should check against CultureInfo.Name. for (int i = 0; i < cultureName.Length; i++) { char c = cultureName[i]; // TODO: Names can only be RFC4646 names (ie: a-zA-Z0-9) while this allows any unicode letter/digit if (char.IsLetterOrDigit(c) || c == '-' || c == '_') { continue; } if (throwException) { throw new ArgumentException(SR.Format(SR.Argument_InvalidResourceCultureName, cultureName)); } return false; } return true; } internal static bool VerifyCultureName(CultureInfo culture, bool throwException) { // If we have an instance of one of our CultureInfos, the user can't have changed the // name and we know that all names are valid in files. if (!culture._isInherited) { return true; } return VerifyCultureName(culture.Name, throwException); } /// <summary> /// This instance provides methods based on the current user settings. /// These settings are volatile and may change over the lifetime of the /// thread. /// </summary> /// <remarks> /// We use the following order to return CurrentCulture and CurrentUICulture /// o Use WinRT to return the current user profile language /// o use current thread culture if the user already set one using CurrentCulture/CurrentUICulture /// o use thread culture if the user already set one using DefaultThreadCurrentCulture /// or DefaultThreadCurrentUICulture /// o Use NLS default user culture /// o Use NLS default system culture /// o Use Invariant culture /// </remarks> public static CultureInfo CurrentCulture { get { return s_currentThreadCulture ?? s_DefaultThreadCurrentCulture ?? s_userDefaultCulture ?? InitializeUserDefaultCulture(); } set { if (value == null) { throw new ArgumentNullException(nameof(value)); } if (s_asyncLocalCurrentCulture == null) { Interlocked.CompareExchange(ref s_asyncLocalCurrentCulture, new AsyncLocal<CultureInfo>(AsyncLocalSetCurrentCulture), null); } s_asyncLocalCurrentCulture!.Value = value; } } public static CultureInfo CurrentUICulture { get { return s_currentThreadUICulture ?? s_DefaultThreadCurrentUICulture ?? UserDefaultUICulture; } set { if (value == null) { throw new ArgumentNullException(nameof(value)); } CultureInfo.VerifyCultureName(value, true); if (s_asyncLocalCurrentUICulture == null) { Interlocked.CompareExchange(ref s_asyncLocalCurrentUICulture, new AsyncLocal<CultureInfo>(AsyncLocalSetCurrentUICulture), null); } // this one will set s_currentThreadUICulture too s_asyncLocalCurrentUICulture!.Value = value; } } internal static CultureInfo UserDefaultUICulture => s_userDefaultUICulture ?? InitializeUserDefaultUICulture(); public static CultureInfo InstalledUICulture => s_userDefaultCulture ?? InitializeUserDefaultCulture(); public static CultureInfo? DefaultThreadCurrentCulture { get => s_DefaultThreadCurrentCulture; set => // If you add pre-conditions to this method, check to see if you also need to // add them to Thread.CurrentCulture.set. s_DefaultThreadCurrentCulture = value; } public static CultureInfo? DefaultThreadCurrentUICulture { get => s_DefaultThreadCurrentUICulture; set { // If they're trying to use a Culture with a name that we can't use in resource lookup, // don't even let them set it on the thread. // If you add more pre-conditions to this method, check to see if you also need to // add them to Thread.CurrentUICulture.set. if (value != null) { CultureInfo.VerifyCultureName(value, true); } s_DefaultThreadCurrentUICulture = value; } } /// <summary> /// This instance provides methods, for example for casing and sorting, /// that are independent of the system and current user settings. It /// should be used only by processes such as some system services that /// require such invariant results (eg. file systems). In general, /// the results are not linguistically correct and do not match any /// culture info. /// </summary> public static CultureInfo InvariantCulture { get { Debug.Assert(s_InvariantCultureInfo != null); return s_InvariantCultureInfo; } } /// <summary> /// Return the parent CultureInfo for the current instance. /// </summary> public virtual CultureInfo Parent { get { if (_parent == null) { CultureInfo culture; string parentName = _cultureData.ParentName; if (string.IsNullOrEmpty(parentName)) { culture = InvariantCulture; } else { culture = CreateCultureInfoNoThrow(parentName, _cultureData.UseUserOverride) ?? // For whatever reason our IPARENT or SPARENT wasn't correct, so use invariant // We can't allow ourselves to fail. In case of custom cultures the parent of the // current custom culture isn't installed. InvariantCulture; } Interlocked.CompareExchange<CultureInfo?>(ref _parent, culture, null); } return _parent!; } } public virtual int LCID => _cultureData.LCID; public virtual int KeyboardLayoutId => _cultureData.KeyboardLayoutId; public static CultureInfo[] GetCultures(CultureTypes types) { // internally we treat UserCustomCultures as Supplementals but v2 // treats as Supplementals and Replacements if ((types & CultureTypes.UserCustomCulture) == CultureTypes.UserCustomCulture) { types |= CultureTypes.ReplacementCultures; } return CultureData.GetCultures(types); } /// <summary> /// Returns the full name of the CultureInfo. The name is in format like /// "en-US" This version does NOT include sort information in the name. /// </summary> public virtual string Name => _nonSortName ??= (_cultureData.Name ?? string.Empty); /// <summary> /// This one has the sort information (ie: de-DE_phoneb) /// </summary> internal string SortName => _sortName ??= _cultureData.SortName; public string IetfLanguageTag => // special case the compatibility cultures Name switch { "zh-CHT" => "zh-Hant", "zh-CHS" => "zh-Hans", _ => Name, }; /// <summary> /// Returns the full name of the CultureInfo in the localized language. /// For example, if the localized language of the runtime is Spanish and the CultureInfo is /// US English, "Ingles (Estados Unidos)" will be returned. /// </summary> public virtual string DisplayName { get { Debug.Assert(_name != null, "[CultureInfo.DisplayName] Always expect _name to be set"); return _cultureData.DisplayName; } } /// <summary> /// Returns the full name of the CultureInfo in the native language. /// For example, if the CultureInfo is US English, "English /// (United States)" will be returned. /// </summary> public virtual string NativeName => _cultureData.NativeName; /// <summary> /// Returns the full name of the CultureInfo in English. /// For example, if the CultureInfo is US English, "English /// (United States)" will be returned. /// </summary> public virtual string EnglishName => _cultureData.EnglishName; /// <summary> /// ie: en /// </summary> public virtual string TwoLetterISOLanguageName => _cultureData.TwoLetterISOLanguageName; /// <summary> /// ie: eng /// </summary> public virtual string ThreeLetterISOLanguageName => _cultureData.ThreeLetterISOLanguageName; /// <summary> /// Returns the 3 letter windows language name for the current instance. eg: "ENU" /// The ISO names are much preferred /// </summary> public virtual string ThreeLetterWindowsLanguageName => _cultureData.ThreeLetterWindowsLanguageName; /// <summary> /// Gets the CompareInfo for this culture. /// </summary> public virtual CompareInfo CompareInfo => _compareInfo ??= // Since CompareInfo's don't have any overrideable properties, get the CompareInfo from // the Non-Overridden CultureInfo so that we only create one CompareInfo per culture (UseUserOverride ? GetCultureInfo(_name).CompareInfo : new CompareInfo(this)); /// <summary> /// Gets the TextInfo for this culture. /// </summary> public virtual TextInfo TextInfo { get { if (_textInfo == null) { // Make a new textInfo TextInfo tempTextInfo = new TextInfo(_cultureData); tempTextInfo.SetReadOnlyState(_isReadOnly); _textInfo = tempTextInfo; } return _textInfo; } } public override bool Equals(object? value) { if (object.ReferenceEquals(this, value)) { return true; } if (value is CultureInfo that) { // using CompareInfo to verify the data passed through the constructor // CultureInfo(String cultureName, String textAndCompareCultureName) return Name.Equals(that.Name) && CompareInfo.Equals(that.CompareInfo); } return false; } public override int GetHashCode() { return Name.GetHashCode() + CompareInfo.GetHashCode(); } /// <summary> /// Implements object.ToString(). Returns the name of the CultureInfo, /// eg. "de-DE_phoneb", "en-US", or "fj-FJ". /// </summary> public override string ToString() => _name; public virtual object? GetFormat(Type? formatType) { if (formatType == typeof(NumberFormatInfo)) { return NumberFormat; } if (formatType == typeof(DateTimeFormatInfo)) { return DateTimeFormat; } return null; } public virtual bool IsNeutralCulture => _cultureData.IsNeutralCulture; public CultureTypes CultureTypes { get { CultureTypes types = _cultureData.IsNeutralCulture ? CultureTypes.NeutralCultures : CultureTypes.SpecificCultures; if (_cultureData.IsWin32Installed) { types |= CultureTypes.InstalledWin32Cultures; } if (_cultureData.IsSupplementalCustomCulture) { types |= CultureTypes.UserCustomCulture; } if (_cultureData.IsReplacementCulture) { types |= CultureTypes.ReplacementCultures; } return types; } } public virtual NumberFormatInfo NumberFormat { get { if (_numInfo == null) { NumberFormatInfo temp = new NumberFormatInfo(_cultureData); temp._isReadOnly = _isReadOnly; Interlocked.CompareExchange(ref _numInfo, temp, null); } return _numInfo!; } set { if (value == null) { throw new ArgumentNullException(nameof(value)); } VerifyWritable(); _numInfo = value; } } /// <summary> /// Create a DateTimeFormatInfo, and fill in the properties according to /// the CultureID. /// </summary> public virtual DateTimeFormatInfo DateTimeFormat { get { if (_dateTimeInfo == null) { // Change the calendar of DTFI to the specified calendar of this CultureInfo. DateTimeFormatInfo temp = new DateTimeFormatInfo(_cultureData, this.Calendar); temp._isReadOnly = _isReadOnly; Interlocked.CompareExchange(ref _dateTimeInfo, temp, null); } return _dateTimeInfo!; } set { if (value == null) { throw new ArgumentNullException(nameof(value)); } VerifyWritable(); _dateTimeInfo = value; } } public void ClearCachedData() { // reset the default culture values s_userDefaultCulture = GetUserDefaultCulture(); s_userDefaultUICulture = GetUserDefaultUICulture(); RegionInfo.s_currentRegionInfo = null; #pragma warning disable 0618 // disable the obsolete warning TimeZone.ResetTimeZone(); #pragma warning restore 0618 TimeZoneInfo.ClearCachedData(); s_cachedCulturesByLcid = null; s_cachedCulturesByName = null; CultureData.ClearCachedData(); } /// <summary> /// Map a Win32 CALID to an instance of supported calendar. /// </summary> /// <remarks> /// Shouldn't throw exception since the calType value is from our data /// table or from Win32 registry. /// If we are in trouble (like getting a weird value from Win32 /// registry), just return the GregorianCalendar. /// </remarks> internal static Calendar GetCalendarInstance(CalendarId calType) { if (calType == CalendarId.GREGORIAN) { return new GregorianCalendar(); } return GetCalendarInstanceRare(calType); } /// <summary> /// This function exists as a shortcut to prevent us from loading all of the non-gregorian /// calendars unless they're required. /// </summary> internal static Calendar GetCalendarInstanceRare(CalendarId calType) { Debug.Assert(calType != CalendarId.GREGORIAN, "calType!=CalendarId.GREGORIAN"); switch (calType) { case CalendarId.GREGORIAN_US: // Gregorian (U.S.) calendar case CalendarId.GREGORIAN_ME_FRENCH: // Gregorian Middle East French calendar case CalendarId.GREGORIAN_ARABIC: // Gregorian Arabic calendar case CalendarId.GREGORIAN_XLIT_ENGLISH: // Gregorian Transliterated English calendar case CalendarId.GREGORIAN_XLIT_FRENCH: // Gregorian Transliterated French calendar return new GregorianCalendar((GregorianCalendarTypes)calType); case CalendarId.TAIWAN: // Taiwan Era calendar return new TaiwanCalendar(); case CalendarId.JAPAN: // Japanese Emperor Era calendar return new JapaneseCalendar(); case CalendarId.KOREA: // Korean Tangun Era calendar return new KoreanCalendar(); case CalendarId.THAI: // Thai calendar return new ThaiBuddhistCalendar(); case CalendarId.HIJRI: // Hijri (Arabic Lunar) calendar return new HijriCalendar(); case CalendarId.HEBREW: // Hebrew (Lunar) calendar return new HebrewCalendar(); case CalendarId.UMALQURA: return new UmAlQuraCalendar(); case CalendarId.PERSIAN: return new PersianCalendar(); } return new GregorianCalendar(); } /// <summary> /// Return/set the default calendar used by this culture. /// This value can be overridden by regional option if this is a current culture. /// </summary> public virtual Calendar Calendar { get { if (_calendar == null) { Debug.Assert(_cultureData.CalendarIds.Length > 0, "_cultureData.CalendarIds.Length > 0"); // Get the default calendar for this culture. Note that the value can be // from registry if this is a user default culture. Calendar newObj = _cultureData.DefaultCalendar; Interlocked.MemoryBarrier(); newObj.SetReadOnlyState(_isReadOnly); _calendar = newObj; } return _calendar; } } /// <summary> /// Return an array of the optional calendar for this culture. /// </summary> public virtual Calendar[] OptionalCalendars { get { // This property always returns a new copy of the calendar array. CalendarId[] calID = _cultureData.CalendarIds; Calendar[] cals = new Calendar[calID.Length]; for (int i = 0; i < cals.Length; i++) { cals[i] = GetCalendarInstance(calID[i]); } return cals; } } public bool UseUserOverride => _cultureData.UseUserOverride; public CultureInfo GetConsoleFallbackUICulture() { CultureInfo? temp = _consoleFallbackCulture; if (temp == null) { temp = CreateSpecificCulture(_cultureData.SCONSOLEFALLBACKNAME); temp._isReadOnly = true; _consoleFallbackCulture = temp; } return temp; } public virtual object Clone() { CultureInfo ci = (CultureInfo)MemberwiseClone(); ci._isReadOnly = false; // If this is exactly our type, we can make certain optimizations so that we don't allocate NumberFormatInfo or DTFI unless // they've already been allocated. If this is a derived type, we'll take a more generic codepath. if (!_isInherited) { if (_dateTimeInfo != null) { ci._dateTimeInfo = (DateTimeFormatInfo)_dateTimeInfo.Clone(); } if (_numInfo != null) { ci._numInfo = (NumberFormatInfo)_numInfo.Clone(); } } else { ci.DateTimeFormat = (DateTimeFormatInfo)this.DateTimeFormat.Clone(); ci.NumberFormat = (NumberFormatInfo)this.NumberFormat.Clone(); } if (_textInfo != null) { ci._textInfo = (TextInfo)_textInfo.Clone(); } if (_dateTimeInfo != null && _dateTimeInfo.Calendar == _calendar) { // Usually when we access CultureInfo.DateTimeFormat first time, we create the DateTimeFormatInfo object // using CultureInfo.Calendar. i.e. CultureInfo.DateTimeInfo.Calendar == CultureInfo.calendar. // When cloning CultureInfo, if we know it's still the case that CultureInfo.DateTimeInfo.Calendar == CultureInfo.calendar // then we can keep the same behavior for the cloned object and no need to create another calendar object. ci._calendar = ci.DateTimeFormat.Calendar; } else if (_calendar != null) { ci._calendar = (Calendar)_calendar.Clone(); } return ci; } public static CultureInfo ReadOnly(CultureInfo ci) { if (ci == null) { throw new ArgumentNullException(nameof(ci)); } if (ci.IsReadOnly) { return ci; } CultureInfo newInfo = (CultureInfo)(ci.MemberwiseClone()); if (!ci.IsNeutralCulture) { // If this is exactly our type, we can make certain optimizations so that we don't allocate NumberFormatInfo or DTFI unless // they've already been allocated. If this is a derived type, we'll take a more generic codepath. if (!ci._isInherited) { if (ci._dateTimeInfo != null) { newInfo._dateTimeInfo = DateTimeFormatInfo.ReadOnly(ci._dateTimeInfo); } if (ci._numInfo != null) { newInfo._numInfo = NumberFormatInfo.ReadOnly(ci._numInfo); } } else { newInfo.DateTimeFormat = DateTimeFormatInfo.ReadOnly(ci.DateTimeFormat); newInfo.NumberFormat = NumberFormatInfo.ReadOnly(ci.NumberFormat); } } if (ci._textInfo != null) { newInfo._textInfo = TextInfo.ReadOnly(ci._textInfo); } if (ci._calendar != null) { newInfo._calendar = Calendar.ReadOnly(ci._calendar); } // Don't set the read-only flag too early. // We should set the read-only flag here. Otherwise, info.DateTimeFormat will not be able to set. newInfo._isReadOnly = true; return newInfo; } public bool IsReadOnly => _isReadOnly; private void VerifyWritable() { if (_isReadOnly) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } } /// <summary> /// For resource lookup, we consider a culture the invariant culture by name equality. /// We perform this check frequently during resource lookup, so adding a property for /// improved readability. /// </summary> internal bool HasInvariantCultureName => Name == InvariantCulture.Name; /// <summary> /// Gets a cached copy of the specified culture from an internal /// hashtable (or creates it if not found). (LCID version) /// </summary> public static CultureInfo GetCultureInfo(int culture) { if (culture <= 0) { throw new ArgumentOutOfRangeException(nameof(culture), SR.ArgumentOutOfRange_NeedPosNum); } Dictionary<int, CultureInfo> lcidTable = CachedCulturesByLcid; CultureInfo? result; lock (lcidTable) { if (lcidTable.TryGetValue(culture, out result)) { return result; } } try { result = new CultureInfo(culture, useUserOverride: false) { _isReadOnly = true }; } catch (ArgumentException) { throw new CultureNotFoundException(nameof(culture), culture, SR.Argument_CultureNotSupported); } lock (lcidTable) { lcidTable[culture] = result; } return result; } /// <summary> /// Gets a cached copy of the specified culture from an internal /// hashtable (or creates it if not found). (Named version) /// </summary> public static CultureInfo GetCultureInfo(string name) { // Make sure we have a valid, non-zero length string as name if (name is null) { throw new ArgumentNullException(nameof(name)); } name = CultureData.AnsiToLower(name); Dictionary<string, CultureInfo> nameTable = CachedCulturesByName; CultureInfo? result; lock (nameTable) { if (nameTable.TryGetValue(name, out result)) { return result; } } result = CreateCultureInfoNoThrow(name, useUserOverride: false) ?? throw new CultureNotFoundException(nameof(name), name, SR.Argument_CultureNotSupported); result._isReadOnly = true; // Remember our name as constructed. Do NOT use alternate sort name versions because // we have internal state representing the sort (so someone would get the wrong cached version). name = CultureData.AnsiToLower(result._name); lock (nameTable) { nameTable[name] = result; } return result; } /// <summary> /// Gets a cached copy of the specified culture from an internal /// hashtable (or creates it if not found). /// </summary> public static CultureInfo GetCultureInfo(string name, string altName) { if (name is null) { throw new ArgumentNullException(nameof(name)); } if (altName is null) { throw new ArgumentNullException(nameof(altName)); } name = CultureData.AnsiToLower(name); altName = CultureData.AnsiToLower(altName); string nameAndAltName = name + "\xfffd" + altName; Dictionary<string, CultureInfo> nameTable = CachedCulturesByName; CultureInfo? result; lock (nameTable) { if (nameTable.TryGetValue(nameAndAltName, out result)) { return result; } } try { result = new CultureInfo(name, altName) { _isReadOnly = true }; result.TextInfo.SetReadOnlyState(readOnly: true); // TextInfo object is already created; we need to set it as read only. } catch (ArgumentException) { throw new CultureNotFoundException("name/altName", SR.Format(SR.Argument_OneOfCulturesNotSupported, name, altName)); } lock (nameTable) { nameTable[nameAndAltName] = result; } return result; } private static Dictionary<string, CultureInfo> CachedCulturesByName { get { Dictionary<string, CultureInfo>? cache = s_cachedCulturesByName; if (cache is null) { cache = new Dictionary<string, CultureInfo>(); cache = Interlocked.CompareExchange(ref s_cachedCulturesByName, cache, null) ?? cache; } return cache; } } private static Dictionary<int, CultureInfo> CachedCulturesByLcid { get { Dictionary<int, CultureInfo>? cache = s_cachedCulturesByLcid; if (cache is null) { cache = new Dictionary<int, CultureInfo>(); cache = Interlocked.CompareExchange(ref s_cachedCulturesByLcid, cache, null) ?? cache; } return cache; } } public static CultureInfo GetCultureInfoByIetfLanguageTag(string name) { // Disallow old zh-CHT/zh-CHS names if (name == "zh-CHT" || name == "zh-CHS") { throw new CultureNotFoundException(nameof(name), SR.Format(SR.Argument_CultureIetfNotSupported, name)); } CultureInfo ci = GetCultureInfo(name); // Disallow alt sorts and es-es_TS if (ci.LCID > 0xffff || ci.LCID == 0x040a) { throw new CultureNotFoundException(nameof(name), SR.Format(SR.Argument_CultureIetfNotSupported, name)); } return ci; } } }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using NUnit.Framework; using VersionOne.SDK.APIClient; using VersionOne.SDK.ObjectModel.Filters; using VersionOne.SDK.Utility; namespace VersionOne.SDK.ObjectModel.Tests { public abstract class BaseSDKTester { private Oid defaultSchemeOid; private EntityFactory entityFactory; private V1Instance instance; protected virtual string ApplicationPath { get { const string settingName = "TEST_URL"; var url = System.Environment.GetEnvironmentVariable(settingName); if (string.IsNullOrWhiteSpace(url)) { url = System.Configuration.ConfigurationManager.AppSettings[settingName]; if (string.IsNullOrWhiteSpace(url)) { url = "http://localhost/V1SDKTests/"; } } url = url.Trim(); return url; } } protected virtual string Username { get { return System.Environment.GetEnvironmentVariable("TEST_USER") ?? "admin"; } } protected virtual string Password { get { return System.Environment.GetEnvironmentVariable("TEST_PASSWORD") ?? "admin"; } } protected Oid DefaultSchemeOid { get { return defaultSchemeOid ?? (defaultSchemeOid = GetFirstAvailableScheme().Oid); } } internal EntityFactory EntityFactory { get { return entityFactory ?? (entityFactory = new EntityFactory(Instance)); } } protected V1Instance Instance { get { if (instance == null) { //var oauth2dir = System.Environment.GetEnvironmentVariable("OAUTH2_DIR"); string oauth2dir = null; if (oauth2dir != null) { instance = new V1Instance(ApplicationPath, new OAuth2Client.Storage.JsonFileStorage(oauth2dir + @"\client_secrets.json", oauth2dir + @"\stored_credentials.json")); } else { instance = new V1Instance(ApplicationPath, Username, Password); } instance.Validate(); } return instance; } } #region Sandbox /// <summary> /// The name to be used when creating your sandbox projects and teams. Override to specify a special name. I like to call mine Fred. /// </summary> protected virtual string SandboxName { get { return GetType().Name; } } #region Schedule private AssetID sandboxScheduleID; /// <summary> /// The ID of your sandbox Schedule, so you can get it again yourself, Elvis. /// </summary> protected AssetID SandboxScheduleID { get { if (sandboxScheduleID == null) { var sandbox = CreateSandboxSchedule(); sandboxScheduleID = sandbox.ID; } return sandboxScheduleID; } } /// <summary> /// A sandbox for you to play in. The Entity is retrieved from the Instance on every call (so ResetInstance will force a re-query). You don't need to do anything to initialize it. Just use it, Mort. /// </summary> protected Schedule SandboxSchedule { get { return Instance.Get.ScheduleByID(SandboxScheduleID); } } protected void NewSandboxSchedule() { sandboxScheduleID = null; } /// <summary> /// Override to create your sandbox with properties other than the defaults (today as the start date, child of Scope:0, no schedule). You go, Einstein. /// </summary> /// <returns></returns> protected virtual Schedule CreateSandboxSchedule() { return Instance.Create.Schedule(SandboxName, TimeSpan.FromDays(14), TimeSpan.FromDays(0) ); } #endregion #region Project private AssetID sandboxProjectID; /// <summary> /// The ID of your sandbox project, so you can get it again yourself, Elvis. /// </summary> protected AssetID SandboxProjectID { get { if (sandboxProjectID == null) { var rootProject = Instance.Get.ProjectByID("Scope:0"); var sandbox = CreateSandboxProject(rootProject); sandboxProjectID = sandbox.ID; } return sandboxProjectID; } } /// <summary> /// A sandbox for you to play in. The Entity is retrieved from the Instance on every call (so ResetInstance will force a re-query). You don't need to do anything to initialize it. Just use it, Mort. /// </summary> protected Project SandboxProject { get { return Instance.Get.ProjectByID(SandboxProjectID); } } protected void NewSandboxProject() { sandboxProjectID = null; } /// <summary> /// Override to create your sandbox with properties other than the defaults (today as the start date, child of Scope:0, no schedule). You go, Einstein. /// </summary> /// <param name="rootProject"></param> /// <returns></returns> protected virtual Project CreateSandboxProject(Project rootProject) { var mandatoryAttributes = new Dictionary<string, object>(1) {{"Scheme", DefaultSchemeOid}}; return Instance.Create.Project(SandboxName, rootProject, DateTime.Now, null, mandatoryAttributes); } #endregion #region Iteration private AssetID sandboxIterationID; /// <summary> /// The ID of your sandbox iteration, so you can get it again yourself, Elvis. /// </summary> protected AssetID SandboxIterationID { get { return sandboxIterationID ?? (sandboxIterationID = SandboxProject.CreateIteration().ID); } } /// <summary> /// A sandbox for you to play in. The Entity is retrieved from the Instance on every call (so ResetInstance will force a re-query). You don't need to do anything to initialize it. Just use it, Mort. /// </summary> protected Iteration SandboxIteration { get { return Instance.Get.IterationByID(SandboxIterationID); } } protected void NewSandboxIteration() { sandboxIterationID = null; } #endregion #region Team private AssetID sandboxTeamID; /// <summary> /// The ID of your sandbox team, so you can get it again yourself, Elvis. /// </summary> protected AssetID SandboxTeamID { get { if (sandboxTeamID == null) { var sanboxTeam = EntityFactory.Create(() => Instance.Create.Team(SandboxName)); sandboxTeamID = sanboxTeam.ID; } return sandboxTeamID; } } /// <summary> /// A sandbox for you to play in. The Entity is retrieved from the Instance on every call (so ResetInstance will force a re-query). You don't need to do anything to initialize it. Just use it, Mort. /// </summary> protected Team SandboxTeam { get { return Instance.Get.TeamByID(SandboxTeamID); } } protected void NewSandboxTeam() { sandboxTeamID = null; } #endregion #region Member private AssetID sandboxMemberID; /// <summary> /// The ID of your sandbox member, so you can get it again yourself, Elvis. /// </summary> protected AssetID SandboxMemberID { get { return sandboxMemberID ?? (sandboxMemberID = Instance.Create.Member(SandboxName, SandboxName).ID); } } /// <summary> /// A sandbox for you to play in. The Entity is retrieved from the Instance on every call (so ResetInstance will force a re-query). You don't need to do anything to initialize it. Just use it, Mort. /// </summary> protected Member SandboxMember { get { return Instance.Get.MemberByID(SandboxMemberID); } } protected void NewSandboxMember() { sandboxMemberID = null; } #endregion protected Story CreateStory(string name, Project project, Iteration iteration) { var story = EntityFactory.CreateStory(name, project); story.Iteration = iteration; story.Save(); return story; } protected Defect CreateDefect(string name, Project project, Iteration iteration) { var defect = EntityFactory.CreateDefect(name, project); defect.Iteration = iteration; defect.Save(); return defect; } #endregion protected Environment CreateEnvironment(string name, IDictionary<string, object> attributes) { //return Instance.Create.Environment(name, SandboxProject, attributes); return EntityFactory.CreateEnvironment(name, SandboxProject, attributes); } protected void ResetInstance() { instance = null; } protected static bool FindRelated<T>(T needle, IEnumerable<T> haystack) { return haystack.Contains(needle); } internal static T First<T>(IEnumerable<T> list) { var enumerator = list.GetEnumerator(); return enumerator.MoveNext() ? enumerator.Current : default(T); } private Asset GetFirstAvailableScheme() { var schemaType = Instance.ApiClient.MetaModel.GetAssetType("Scheme"); var nameDefinition = schemaType.GetAttributeDefinition("Name"); var schemaQuery = new Query(schemaType); schemaQuery.Selection.Add(nameDefinition); var result = Instance.ApiClient.Services.Retrieve(schemaQuery); return result.Assets[0]; } internal Environment GetEnvironment() { const string name = "Testing env abv123"; var filter = new EnvironmentFilter(); filter.Name.Add(name); var env = Instance.Get.Environments(filter); if (env.Count == 0) { return CreateEnvironment(name, null); } var environments = new List<Environment>(env); return environments[0]; } [TearDown] public void TearDown() { EntityFactory.Dispose(); } protected class EntityToAssetIDTransformer<T> : ITransformer where T : Entity { public object Transform(object input) { return ((T)input).ID.Token; } } protected class EntityToNameTransformer<T> : ITransformer where T : BaseAsset { public object Transform(object input) { return ((T)input).Name; } } public IEnumerable DeriveListOfNamesFromAssets(IEnumerable baseAssets) { var names = new List<string> {}; foreach (BaseAsset asset in baseAssets) { names.Add(asset.Name); } return names; } public IEnumerable DeriveListOfIdsFromAssets(IEnumerable assets) { var ids = new List<string> {}; foreach (BaseAsset asset in assets) { ids.Add(asset.ID.Token); } return ids; } } }
namespace ConsoleApplication16 { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading; /// <summary> /// A reusable low precision timer with approximate scheduling /// </summary> /// <remarks> /// <para> /// Timeout actions are executed on a ThreadPool thread supplied by the system. If you need to execute blocking /// operations, /// it is recommended that you start a new Task using a TaskScheduler. /// </para> /// Based on George Varghese and Tony Lauck's paper, /// <a href="http://cseweb.ucsd.edu/users/varghese/PAPERS/twheel.ps.Z"> /// Hashed and Hierarchical Timing Wheels: data structures to efficiently implement a timer facility /// </a> /// </remarks> sealed class HashedWheelTimer<T> : IDisposable where T : IRunnable { const int InitState = 0; const int ExpiredState = 1; const int CancelledState = 2; readonly Bucket[] wheel; readonly Timer timer; int isDisposed; readonly int tickDuration; readonly ConcurrentQueue<ValueTuple<TimeoutItem, long>> pendingToAdd = new ConcurrentQueue<ValueTuple<TimeoutItem, long>>(); readonly ConcurrentQueue<TimeoutItem> cancelledTimeouts = new ConcurrentQueue<TimeoutItem>(); /// <summary> /// Represents the index of the next tick /// </summary> internal int Index { get; set; } public HashedWheelTimer(int tickDuration = 100, int ticksPerWheel = 512) { if (ticksPerWheel < 1) { throw new ArgumentOutOfRangeException(nameof(ticksPerWheel)); } if (tickDuration < 20) { throw new ArgumentOutOfRangeException(nameof(tickDuration), "Timer resolution is system dependant, you should not use this class for tick durations lower than 20 ms"); } //Create the wheel this.wheel = new Bucket[ticksPerWheel]; for (int i = 0; i < ticksPerWheel; i++) { this.wheel[i] = new Bucket(); } //Create the timer this.tickDuration = tickDuration; this.timer = new Timer(this.TimerTick, null, this.tickDuration, Timeout.Infinite); } void TimerTick(object state) { this.AddPending(); this.RemoveCancelled(); //go through the timeouts in the current bucket and subtract the round //or expire Bucket bucket = this.wheel[this.Index]; for (int index = bucket.Count - 1; index >= 0; index--) { TimeoutItem timeout = bucket[index]; if (!timeout.IsAssigned) { continue; } if (timeout.Rounds == 0) { timeout.Expire(); bucket.RemoveAt(index, timeout); } else if (timeout.IsCancelled) { bucket.RemoveAt(index, timeout); } else { timeout.Rounds--; } } bucket.Compact(); //while (timeout != null) //{ // if (timeout.Rounds == 0) // { // timeout.Expire(); // bucket.Remove(timeout); // } // else if (timeout.IsCancelled) // { // bucket.Remove(timeout); // } // else // { // timeout.Rounds--; // } // timeout = timeout.Next; //} //Setup the next tick this.Index = (this.Index + 1) % this.wheel.Length; try { this.timer.Change(this.tickDuration, Timeout.Infinite); } catch (ObjectDisposedException) { //the _timer might already have been disposed of } } /// <summary> /// Releases the underlying timer instance. /// </summary> public void Dispose() { //Allow multiple calls to dispose if (Interlocked.Increment(ref this.isDisposed) != 1) { return; } this.timer.Dispose(); } /// <summary> /// Adds a new action to be executed with a delay /// </summary> /// <param name="action"> /// Action to be executed. Consider that the action is going to be invoked in an IO thread. /// </param> /// <param name="delay">Delay in milliseconds</param> public TimeoutItem NewTimeout(T action, long delay) { if (delay < this.tickDuration) { delay = this.tickDuration; } var item = new TimeoutItem(this, action); this.pendingToAdd.Enqueue(ValueTuple.Create(item, delay)); return item; } /// <summary> /// Adds the timeouts to each bucket /// </summary> void AddPending() { ValueTuple<TimeoutItem, long> pending; while (this.pendingToAdd.TryDequeue(out pending)) { this.AddTimeout(pending.Item1, pending.Item2); } } void AddTimeout(TimeoutItem item, long delay) { if (item.IsCancelled) { //It has been cancelled since then return; } //delay expressed in tickets long ticksDelay = delay / this.tickDuration + //As index is for the current tick and it was added since the last tick this.Index - 1; int bucketIndex = Convert.ToInt32(ticksDelay % this.wheel.Length); long rounds = ticksDelay / this.wheel.Length; if (rounds > 0 && bucketIndex < this.Index) { rounds--; } item.Rounds = rounds; this.wheel[bucketIndex].Add(item); } /// <summary> /// Removes all cancelled timeouts from the buckets /// </summary> void RemoveCancelled() { TimeoutItem timeout; while (this.cancelledTimeouts.TryDequeue(out timeout)) { timeout.Bucket.Remove(timeout); } } /// <summary> /// Linked list of Timeouts to allow easy removal of HashedWheelTimeouts in the middle. /// Methods are not thread safe. /// </summary> internal sealed class Bucket : List<TimeoutItem> { public Bucket() : base(4096) { } internal new void Add(TimeoutItem item) { item.Bucket = this; base.Add(item); } internal void RemoveAt(int index, TimeoutItem item) { this[index] = default(TimeoutItem); // soft delete //item.Dispose(); } public void Compact() { // todo: chunk copy strategy int shift = 0; for (int i = 0; i < this.Count; i++) { TimeoutItem item = this[i]; if (item.Bucket == null) { shift++; } else { if (shift > 0) { this[i - shift] = item; } } } if (shift > 0) { this.RemoveRange(this.Count - shift, shift); } } } internal struct TimeoutItem { //Use fields instead of properties as micro optimization //More 100 thousand timeout items could be created and GC collected each second readonly T action; int state; readonly HashedWheelTimer<T> timer; internal long Rounds; internal Bucket Bucket; public bool IsCancelled => this.state == CancelledState; public bool IsAssigned => this.Bucket != null; internal TimeoutItem(HashedWheelTimer<T> timer, T action) { this.action = action; this.timer = timer; this.state = InitState; this.Rounds = 0; this.Bucket = null; } public bool Cancel() { if (Interlocked.CompareExchange(ref this.state, CancelledState, InitState) == InitState) { if (this.IsAssigned) { //Mark this to be removed from the bucket on the next tick this.timer.cancelledTimeouts.Enqueue(this); } return true; } return false; } /// <summary> /// Execute the timeout action /// </summary> public void Expire() { if (Interlocked.CompareExchange(ref this.state, ExpiredState, InitState) != InitState) { //Its already cancelled return; } this.action.Run(); } } } interface IRunnable { void Run(); } }
using Newtonsoft.Json.Linq; using ReactNative.Reflection; using ReactNative.UIManager; using ReactNative.UIManager.Annotations; using ReactNative.Views.Text; using System; using System.Collections.Generic; using Windows.System; using Windows.UI; using Windows.UI.Text; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; namespace ReactNative.Views.TextInput { /// <summary> /// View manager for <see cref="PasswordBox"/>. /// </summary> class ReactPasswordBoxManager : BaseViewManager<PasswordBox, ReactPasswordBoxShadowNode> { private const uint DefaultTextControlForeground = 0xFF000000; private const uint DefaultTextControlForegroundPointerOver = 0xFF000000; private const uint DefaultTextControlForegroundFocused = 0xFF000000; private const uint DefaultTextControlForegroundDisabled = 0xFF7A7A7A; private const uint DefaultTextControlBackground = 0x66FFFFFF; private const uint DefaultTextControlBackgroundPointerOver = 0xFFFFFFFF; private const uint DefaultTextControlBackgroundFocused = 0xFFFFFFFF; private const uint DefaultTextControlBackgroundDisabled = 0x33000000; private const uint DefaultTextControlPlaceholderForeground = 0x99000000; private const uint DefaultTextControlPlaceholderForegroundPointerOver = 0x99000000; private const uint DefaultTextControlPlaceholderForegroundFocused = 0x66000000; private const uint DefaultTextControlPlaceholderForegroundDisabled = 0xFF7A7A7A; private const uint DefaultTextControlBorderBrush = 0xFF7A7A7A; private const uint DefaultTextControlBorderBrushPointerOver = 0xFF171717; private const uint DefaultTextControlBorderBrushFocused = 0xFF298FCC; private const uint DefaultTextControlBorderBrushDisabled = 0x33000000; /// <summary> /// The name of the view manager. /// </summary> public override string Name { get { return "PasswordBoxWindows"; } } /// <summary> /// The exported custom bubbling event types. /// </summary> public override IReadOnlyDictionary<string, object> ExportedCustomBubblingEventTypeConstants { get { return new Dictionary<string, object>() { { "topSubmitEditing", new Dictionary<string, object>() { { "phasedRegistrationNames", new Dictionary<string, string>() { { "bubbled" , "onSubmitEditing" }, { "captured" , "onSubmitEditingCapture" } } } } }, { "topEndEditing", new Dictionary<string, object>() { { "phasedRegistrationNames", new Dictionary<string, string>() { { "bubbled" , "onEndEditing" }, { "captured" , "onEndEditingCapture" } } } } }, { "topFocus", new Dictionary<string, object>() { { "phasedRegistrationNames", new Dictionary<string, string>() { { "bubbled" , "onFocus" }, { "captured" , "onFocusCapture" } } } } }, { "topBlur", new Dictionary<string, object>() { { "phasedRegistrationNames", new Dictionary<string, string>() { { "bubbled" , "onBlur" }, { "captured" , "onBlurCapture" } } } } }, }; } } /// <summary> /// Sets the password character on the <see cref="PasswordBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="passwordCharString">The password masking character to set.</param> [ReactProp("passwordChar")] public void SetPasswordChar(PasswordBox view, string passwordCharString) { view.PasswordChar = passwordCharString; } /// <summary> /// Sets the password reveal mode on the <see cref="PasswordBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="revealModeString">The reveal mode, either Hidden, Peek, or Visibile.</param> [ReactProp("passwordRevealMode")] public void SetPasswordRevealMode(PasswordBox view, string revealModeString) { var revealMode = EnumHelpers.ParseNullable<PasswordRevealMode>(revealModeString); view.PasswordRevealMode = revealMode ?? PasswordRevealMode.Peek; } /// <summary> /// Sets the font size on the <see cref="PasswordBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="fontSize">The font size.</param> [ReactProp(ViewProps.FontSize)] public void SetFontSize(PasswordBox view, double fontSize) { view.FontSize = fontSize; } /// <summary> /// Sets the font color for the node. /// </summary> /// <param name="view">The view instance.</param> /// <param name="color">The masked color value.</param> [ReactProp(ViewProps.Color, CustomType = "Color")] public void SetColor(PasswordBox view, uint? color) { if (color.HasValue) { var brush = new SolidColorBrush(ColorHelpers.Parse(color.Value)); view.Resources["TextControlForeground"] = brush; view.Resources["TextControlForegroundPointerOver"] = brush; view.Resources["TextControlForegroundFocused"] = brush; view.Resources["TextControlForegroundDisabled"] = brush; } else { view.Resources["TextControlForeground"] = new SolidColorBrush(ColorHelpers.Parse(DefaultTextControlForeground)); view.Resources["TextControlForegroundPointerOver"] = new SolidColorBrush(ColorHelpers.Parse(DefaultTextControlForegroundPointerOver)); view.Resources["TextControlForegroundFocused"] = new SolidColorBrush(ColorHelpers.Parse(DefaultTextControlForegroundFocused)); view.Resources["TextControlForegroundDisabled"] = new SolidColorBrush(ColorHelpers.Parse(DefaultTextControlForegroundDisabled)); } } /// <summary> /// Sets the font family for the node. /// </summary> /// <param name="view">The view instance.</param> /// <param name="familyName">The font family.</param> [ReactProp(ViewProps.FontFamily)] public void SetFontFamily(PasswordBox view, string familyName) { view.FontFamily = familyName != null ? new FontFamily(familyName) : FontFamily.XamlAutoFontFamily; } /// <summary> /// Sets the font weight for the node. /// </summary> /// <param name="view">The view instance.</param> /// <param name="fontWeightString">The font weight string.</param> [ReactProp(ViewProps.FontWeight)] public void SetFontWeight(PasswordBox view, string fontWeightString) { var fontWeight = FontStyleHelpers.ParseFontWeight(fontWeightString); view.FontWeight = fontWeight ?? FontWeights.Normal; } /// <summary> /// Sets the font style for the node. /// </summary> /// <param name="view">The view instance.</param> /// <param name="fontStyleString">The font style string.</param> [ReactProp(ViewProps.FontStyle)] public void SetFontStyle(PasswordBox view, string fontStyleString) { var fontStyle = EnumHelpers.ParseNullable<FontStyle>(fontStyleString); view.FontStyle = fontStyle ?? FontStyle.Normal; } /// <summary> /// Sets the default text placeholder property on the <see cref="PasswordBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="placeholder">The placeholder text.</param> [ReactProp("placeholder")] public void SetPlaceholder(PasswordBox view, string placeholder) { view.PlaceholderText = placeholder; } /// <summary> /// Sets the placeholderTextColor property on the <see cref="ReactTextBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="color">The placeholder text color.</param> [ReactProp("placeholderTextColor", CustomType = "Color")] public void SetPlaceholderTextColor(PasswordBox view, uint? color) { if (color.HasValue) { var brush = new SolidColorBrush(ColorHelpers.Parse(color.Value)); view.Resources["TextControlPlaceholderForeground"] = brush; view.Resources["TextControlPlaceholderForegroundPointerOver"] = brush; view.Resources["TextControlPlaceholderForegroundFocused"] = brush; view.Resources["TextControlPlaceholderForegroundDisabled"] = brush; } else { view.Resources["TextControlPlaceholderForeground"] = new SolidColorBrush(ColorHelpers.Parse(DefaultTextControlPlaceholderForeground)); view.Resources["TextControlPlaceholderForegroundPointerOver"] = new SolidColorBrush(ColorHelpers.Parse(DefaultTextControlPlaceholderForegroundPointerOver)); view.Resources["TextControlPlaceholderForegroundFocused"] = new SolidColorBrush(ColorHelpers.Parse(DefaultTextControlPlaceholderForegroundFocused)); view.Resources["TextControlPlaceholderForegroundDisabled"] = new SolidColorBrush(ColorHelpers.Parse(DefaultTextControlPlaceholderForegroundDisabled)); } } /// <summary> /// Sets the border color for the <see cref="ReactTextBox"/>. /// </summary> /// <param name="view">The view instance</param> /// <param name="color">The masked color value.</param> [ReactProp("borderColor", CustomType = "Color")] public void SetBorderColor(PasswordBox view, uint? color) { if (color.HasValue) { var brush = new SolidColorBrush(ColorHelpers.Parse(color.Value)); view.Resources["TextControlBorderBrush"] = brush; view.Resources["TextControlBorderBrushPointerOver"] = brush; view.Resources["TextControlBorderBrushFocused"] = brush; view.Resources["TextControlBorderBrushDisabled"] = brush; } else { view.Resources["TextControlBorderBrush"] = new SolidColorBrush(ColorHelpers.Parse(DefaultTextControlBorderBrush)); view.Resources["TextControlBorderBrushPointerOver"] = new SolidColorBrush(ColorHelpers.Parse(DefaultTextControlBorderBrushPointerOver)); view.Resources["TextControlBorderBrushFocused"] = new SolidColorBrush(ColorHelpers.Parse(DefaultTextControlBorderBrushFocused)); view.Resources["TextControlBorderBrushDisabled"] = new SolidColorBrush(ColorHelpers.Parse(DefaultTextControlBorderBrushDisabled)); } } /// <summary> /// Sets the background color for the <see cref="ReactTextBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="color">The masked color value.</param> [ReactProp(ViewProps.BackgroundColor, CustomType = "Color")] public void SetBackgroundColor(PasswordBox view, uint? color) { if (color.HasValue) { var brush = new SolidColorBrush(ColorHelpers.Parse(color.Value)); view.Resources["TextControlBackground"] = brush; view.Resources["TextControlBackgroundPointerOver"] = brush; view.Resources["TextControlBackgroundFocused"] = brush; view.Resources["TextControlBackgroundDisabled"] = brush; } else { view.Resources["TextControlBackground"] = new SolidColorBrush(ColorHelpers.Parse(DefaultTextControlBackground)); view.Resources["TextControlBackgroundPointerOver"] = new SolidColorBrush(ColorHelpers.Parse(DefaultTextControlBackgroundPointerOver)); view.Resources["TextControlBackgroundFocused"] = new SolidColorBrush(ColorHelpers.Parse(DefaultTextControlBackgroundFocused)); view.Resources["TextControlBackgroundDisabled"] = new SolidColorBrush(ColorHelpers.Parse(DefaultTextControlBackgroundDisabled)); } } /// <summary> /// Sets the selection color for the <see cref="PasswordBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="color">The masked color value.</param> [ReactProp("selectionColor", CustomType = "Color")] public void SetSelectionColor(PasswordBox view, uint color) { view.SelectionHighlightColor = new SolidColorBrush(ColorHelpers.Parse(color)); } /// <summary> /// Sets the text alignment property on the <see cref="PasswordBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="alignment">The text alignment.</param> [ReactProp(ViewProps.TextAlignVertical)] public void SetTextVerticalAlign(PasswordBox view, string alignment) { view.VerticalContentAlignment = EnumHelpers.Parse<VerticalAlignment>(alignment); } /// <summary> /// Sets the editablity property on the <see cref="PasswordBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="editable">The editable flag.</param> [ReactProp("editable")] public void SetEditable(PasswordBox view, bool editable) { view.IsEnabled = editable; } /// <summary> /// Sets the max character length property on the <see cref="PasswordBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="maxCharLength">The max length.</param> [ReactProp("maxLength")] public void SetMaxLength(PasswordBox view, int maxCharLength) { view.MaxLength = maxCharLength; } /// <summary> /// Sets the keyboard type on the <see cref="PasswordBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="keyboardType">The keyboard type.</param> [ReactProp("keyboardType")] public void SetKeyboardType(PasswordBox view, string keyboardType) { var inputScope = new InputScope(); var nameValue = keyboardType != null ? InputScopeHelpers.FromStringForPasswordBox(keyboardType) : InputScopeNameValue.Password; inputScope.Names.Add(new InputScopeName(nameValue)); view.InputScope = inputScope; } /// <summary> /// Sets the border width for a <see cref="PasswordBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="width">The border width.</param> [ReactProp(ViewProps.BorderWidth)] public void SetBorderWidth(PasswordBox view, int width) { view.BorderThickness = new Thickness(width); } public override ReactPasswordBoxShadowNode CreateShadowNodeInstance() { return new ReactPasswordBoxShadowNode(); } /// <summary> /// Update the view with extra data. /// </summary> /// <param name="view">The view instance.</param> /// <param name="extraData">The extra data.</param> public override void UpdateExtraData(PasswordBox view, object extraData) { var paddings = extraData as float[]; if (paddings != null) { view.Padding = new Thickness( paddings[0], paddings[1], paddings[2], paddings[3]); } } /// <summary> /// Returns the view instance for <see cref="PasswordBox"/>. /// </summary> /// <param name="reactContext">The themed React Context</param> /// <returns>A new initialized <see cref="PasswordBox"/></returns> protected override PasswordBox CreateViewInstance(ThemedReactContext reactContext) { return new PasswordBox(); } /// <summary> /// Implement this method to receive events/commands directly from /// JavaScript through the <see cref="PasswordBox"/>. /// </summary> /// <param name="view"> /// The view instance that should receive the command. /// </param> /// <param name="commandId">Identifer for the command.</param> /// <param name="args">Optional arguments for the command.</param> public override void ReceiveCommand(PasswordBox view, int commandId, JArray args) { if (commandId == ReactTextInputManager.FocusTextInput) { view.Focus(FocusState.Programmatic); } else if (commandId == ReactTextInputManager.BlurTextInput) { if (FocusManager.GetFocusedElement() == view) { var frame = Window.Current?.Content as Frame; frame?.Focus(FocusState.Programmatic); } } } /// <summary> /// Installing the textchanged event emitter on the <see cref="TextInput"/> Control. /// </summary> /// <param name="reactContext">The React context.</param> /// <param name="view">The <see cref="PasswordBox"/> view instance.</param> protected override void AddEventEmitters(ThemedReactContext reactContext, PasswordBox view) { base.AddEventEmitters(reactContext, view); view.PasswordChanged += OnPasswordChanged; view.GotFocus += OnGotFocus; view.LostFocus += OnLostFocus; view.KeyDown += OnKeyDown; } /// <summary> /// Called when view is detached from view hierarchy and allows for /// additional cleanup by the <see cref="ReactTextInputManager"/>. /// subclass. Unregister all event handlers for the <see cref="PasswordBox"/>. /// </summary> /// <param name="reactContext">The React context.</param> /// <param name="view">The <see cref="PasswordBox"/>.</param> public override void OnDropViewInstance(ThemedReactContext reactContext, PasswordBox view) { base.OnDropViewInstance(reactContext, view); view.KeyDown -= OnKeyDown; view.LostFocus -= OnLostFocus; view.GotFocus -= OnGotFocus; view.PasswordChanged -= OnPasswordChanged; } /// <summary> /// Sets the dimensions of the view. /// </summary> /// <param name="view">The view.</param> /// <param name="dimensions">The output buffer.</param> public override void SetDimensions(PasswordBox view, Dimensions dimensions) { base.SetDimensions(view, dimensions); view.MinWidth = dimensions.Width; view.MinHeight = dimensions.Height; } private void OnPasswordChanged(object sender, RoutedEventArgs e) { var textBox = (PasswordBox)sender; textBox.GetReactContext() .GetNativeModule<UIManagerModule>() .EventDispatcher .DispatchEvent( new ReactTextChangedEvent( textBox.GetTag(), textBox.Password, 0)); } private void OnGotFocus(object sender, RoutedEventArgs e) { var textBox = (PasswordBox)sender; textBox.GetReactContext() .GetNativeModule<UIManagerModule>() .EventDispatcher .DispatchEvent( new ReactTextInputFocusEvent(textBox.GetTag())); } private void OnLostFocus(object sender, RoutedEventArgs e) { var textBox = (PasswordBox)sender; var eventDispatcher = textBox.GetReactContext() .GetNativeModule<UIManagerModule>() .EventDispatcher; eventDispatcher.DispatchEvent( new ReactTextInputBlurEvent(textBox.GetTag())); eventDispatcher.DispatchEvent( new ReactTextInputEndEditingEvent( textBox.GetTag(), textBox.Password)); } private void OnKeyDown(object sender, KeyRoutedEventArgs e) { if (e.Key == VirtualKey.Enter) { var textBox = (PasswordBox)sender; e.Handled = true; textBox.GetReactContext() .GetNativeModule<UIManagerModule>() .EventDispatcher .DispatchEvent( new ReactTextInputSubmitEditingEvent( textBox.GetTag(), textBox.Password)); } } } }
// // https://github.com/NServiceKit/NServiceKit.Redis/ // NServiceKit.Redis: ECMA CLI Binding to the Redis key-value storage system // // Authors: // Demis Bellot ([email protected]) // // Copyright 2013 ServiceStack. // // Licensed under the same terms of Redis and ServiceStack: new BSD license. // using System; using System.Collections.Generic; namespace NServiceKit.Redis { /// <summary>Interface for redis native client.</summary> public interface IRedisNativeClient : IDisposable { //Redis utility operations /// <summary> /// Info /// </summary> Dictionary<string, string> Info { get; } /// <summary>Gets or sets the database.</summary> /// /// <value>The database.</value> long Db { get; set; } /// <summary>Gets the size of the database.</summary> /// /// <value>The size of the database.</value> long DbSize { get; } /// <summary>Gets the Date/Time of the last save.</summary> /// /// <value>The last save.</value> DateTime LastSave { get; } /// <summary>Saves this object.</summary> void Save(); /// <summary>Background save.</summary> void BgSave(); /// <summary>Shuts down this object and frees any resources it is using.</summary> void Shutdown(); /// <summary>Background rewrite aof.</summary> void BgRewriteAof(); /// <summary>Quits this object.</summary> void Quit(); /// <summary>Flushes the database.</summary> void FlushDb(); /// <summary>Flushes all.</summary> void FlushAll(); /// <summary>Pings this object.</summary> /// /// <returns>true if it succeeds, false if it fails.</returns> bool Ping(); /// <summary>Echoes.</summary> /// /// <param name="text">The text.</param> /// /// <returns>A string.</returns> string Echo(string text); /// <summary>Slave of.</summary> /// /// <param name="hostname">The hostname.</param> /// <param name="port"> The port.</param> void SlaveOf(string hostname, int port); /// <summary>Slave of no one.</summary> void SlaveOfNoOne(); /// <summary>Configuration get.</summary> /// /// <param name="pattern">Specifies the pattern.</param> /// /// <returns>A byte[][].</returns> byte[][] ConfigGet(string pattern); /// <summary>Configuration set.</summary> /// /// <param name="item"> The item.</param> /// <param name="value">The value.</param> void ConfigSet(string item, byte[] value); /// <summary>Configuration reset stat.</summary> void ConfigResetStat(); /// <summary>Gets the time.</summary> /// /// <returns>A byte[][].</returns> byte[][] Time(); /// <summary>Debug segfault.</summary> void DebugSegfault(); /// <summary>Dumps.</summary> /// /// <param name="key">The key.</param> /// /// <returns>A byte[].</returns> byte[] Dump(string key); /// <summary>Restores.</summary> /// /// <param name="key"> The key.</param> /// <param name="expireMs"> The expire in milliseconds.</param> /// <param name="dumpValue">The dump value.</param> /// /// <returns>A byte[].</returns> byte[] Restore(string key, long expireMs, byte[] dumpValue); /// <summary>Migrates.</summary> /// /// <param name="host"> The host.</param> /// <param name="port"> The port.</param> /// <param name="destinationDb">Destination database.</param> /// <param name="timeoutMs"> The timeout in milliseconds.</param> void Migrate(string host, int port, int destinationDb, long timeoutMs); /// <summary>Moves.</summary> /// /// <param name="key">The key.</param> /// <param name="db"> The database.</param> /// /// <returns>true if it succeeds, false if it fails.</returns> bool Move(string key, int db); /// <summary>Object idle time.</summary> /// /// <param name="key">The key.</param> /// /// <returns>A long.</returns> long ObjectIdleTime(string key); /// <summary>Keys.</summary> /// /// <param name="pattern">Specifies the pattern.</param> /// /// <returns>A byte[][].</returns> byte[][] Keys(string pattern); /// <summary>Exists.</summary> /// /// <param name="key">The key.</param> /// /// <returns>A long.</returns> long Exists(string key); /// <summary>String lens.</summary> /// /// <param name="key">The key.</param> /// /// <returns>A long.</returns> long StrLen(string key); /// <summary>Sets.</summary> /// /// <param name="key"> The key.</param> /// <param name="value">The value.</param> void Set(string key, byte[] value); /// <summary>Sets an ex.</summary> /// /// <param name="key"> The key.</param> /// <param name="expireInSeconds">The expire in seconds.</param> /// <param name="value"> The value.</param> void SetEx(string key, int expireInSeconds, byte[] value); /// <summary>Persists.</summary> /// /// <param name="key">The key.</param> /// /// <returns>true if it succeeds, false if it fails.</returns> bool Persist(string key); /// <summary>Sets an ex.</summary> /// /// <param name="key"> The key.</param> /// <param name="expireInMs">The expire in milliseconds.</param> /// <param name="value"> The value.</param> void PSetEx(string key, long expireInMs, byte[] value); /// <summary>Sets a nx.</summary> /// /// <param name="key"> The key.</param> /// <param name="value">The value.</param> /// /// <returns>A long.</returns> long SetNX(string key, byte[] value); /// <summary>Sets.</summary> /// /// <param name="keys"> The keys.</param> /// <param name="values">The values.</param> void MSet(byte[][] keys, byte[][] values); /// <summary>Sets.</summary> /// /// <param name="keys"> The keys.</param> /// <param name="values">The values.</param> void MSet(string[] keys, byte[][] values); /// <summary>Sets a nx.</summary> /// /// <param name="keys"> The keys.</param> /// <param name="values">The values.</param> /// /// <returns>true if it succeeds, false if it fails.</returns> bool MSetNx(byte[][] keys, byte[][] values); /// <summary>Sets a nx.</summary> /// /// <param name="keys"> The keys.</param> /// <param name="values">The values.</param> /// /// <returns>true if it succeeds, false if it fails.</returns> bool MSetNx(string[] keys, byte[][] values); /// <summary>Gets.</summary> /// /// <param name="key">The key.</param> /// /// <returns>A byte[].</returns> byte[] Get(string key); /// <summary>Gets a set.</summary> /// /// <param name="key"> The key.</param> /// <param name="value">The value.</param> /// /// <returns>An array of byte.</returns> byte[] GetSet(string key, byte[] value); /// <summary>Gets the given keys.</summary> /// /// <param name="keysAndArgs">A variable-length parameters list containing keys and arguments.</param> /// /// <returns>A byte[][].</returns> byte[][] MGet(params byte[][] keysAndArgs); /// <summary>Gets the given keys.</summary> /// /// <param name="keys">The keys.</param> /// /// <returns>A byte[][].</returns> byte[][] MGet(params string[] keys); /// <summary>Deletes the given keys.</summary> /// /// <param name="key">The key.</param> /// /// <returns>A long.</returns> long Del(string key); /// <summary>Deletes the given keys.</summary> /// /// <param name="keys">The keys.</param> /// /// <returns>A long.</returns> long Del(params string[] keys); /// <summary>Incrs.</summary> /// /// <param name="key">The key.</param> /// /// <returns>A long.</returns> long Incr(string key); /// <summary>Increment by.</summary> /// /// <param name="key"> The key.</param> /// <param name="incrBy">Amount to increment by.</param> /// /// <returns>A long.</returns> long IncrBy(string key, int incrBy); /// <summary>Increment by float.</summary> /// /// <param name="key"> The key.</param> /// <param name="incrBy">Amount to increment by.</param> /// /// <returns>A double.</returns> double IncrByFloat(string key, double incrBy); /// <summary>Decrs.</summary> /// /// <param name="key">The key.</param> /// /// <returns>A long.</returns> long Decr(string key); /// <summary>Decrement by.</summary> /// /// <param name="key"> The key.</param> /// <param name="decrBy">Amount to decrement by.</param> /// /// <returns>A long.</returns> long DecrBy(string key, int decrBy); /// <summary>Appends a key.</summary> /// /// <param name="key"> The key.</param> /// <param name="value">The value.</param> /// /// <returns>A long.</returns> long Append(string key, byte[] value); /// <summary>(This method is obsolete) substrs.</summary> /// /// <param name="key"> The key.</param> /// <param name="fromIndex">Zero-based index of from.</param> /// <param name="toIndex"> Zero-based index of to.</param> /// /// <returns>A byte[].</returns> [Obsolete("Was renamed to GetRange in 2.4")] byte[] Substr(string key, int fromIndex, int toIndex); /// <summary>Finds the range of the given arguments.</summary> /// /// <param name="key"> The key.</param> /// <param name="fromIndex">Zero-based index of from.</param> /// <param name="toIndex"> Zero-based index of to.</param> /// /// <returns>The calculated range.</returns> byte[] GetRange(string key, int fromIndex, int toIndex); /// <summary>Sets a range.</summary> /// /// <param name="key"> The key.</param> /// <param name="offset">The offset.</param> /// <param name="value"> The value.</param> /// /// <returns>A long.</returns> long SetRange(string key, int offset, byte[] value); /// <summary>Gets a bit.</summary> /// /// <param name="key"> The key.</param> /// <param name="offset">The offset.</param> /// /// <returns>The bit.</returns> long GetBit(string key, int offset); /// <summary>Sets a bit.</summary> /// /// <param name="key"> The key.</param> /// <param name="offset">The offset.</param> /// <param name="value"> The value.</param> /// /// <returns>A long.</returns> long SetBit(string key, int offset, int value); /// <summary>Random key.</summary> /// /// <returns>A string.</returns> string RandomKey(); /// <summary>Renames.</summary> /// /// <param name="oldKeyname">The old keyname.</param> /// <param name="newKeyname">The new keyname.</param> void Rename(string oldKeyname, string newKeyname); /// <summary>Rename nx.</summary> /// /// <param name="oldKeyname">The old keyname.</param> /// <param name="newKeyname">The new keyname.</param> /// /// <returns>true if it succeeds, false if it fails.</returns> bool RenameNx(string oldKeyname, string newKeyname); /// <summary>Expires.</summary> /// /// <param name="key"> The key.</param> /// <param name="seconds">The seconds.</param> /// /// <returns>true if it succeeds, false if it fails.</returns> bool Expire(string key, int seconds); /// <summary>Expires.</summary> /// /// <param name="key"> The key.</param> /// <param name="ttlMs">The TTL in milliseconds.</param> /// /// <returns>true if it succeeds, false if it fails.</returns> bool PExpire(string key, long ttlMs); /// <summary>Expire at.</summary> /// /// <param name="key"> The key.</param> /// <param name="unixTime">The unix time.</param> /// /// <returns>true if it succeeds, false if it fails.</returns> bool ExpireAt(string key, long unixTime); /// <summary>Expire at.</summary> /// /// <param name="key"> The key.</param> /// <param name="unixTimeMs">The unix time in milliseconds.</param> /// /// <returns>true if it succeeds, false if it fails.</returns> bool PExpireAt(string key, long unixTimeMs); /// <summary>Ttls.</summary> /// /// <param name="key">The key.</param> /// /// <returns>A long.</returns> long Ttl(string key); /// <summary>Ttls.</summary> /// /// <param name="key">The key.</param> /// /// <returns>A long.</returns> long PTtl(string key); /// <summary>Sorts.</summary> /// /// <param name="listOrSetId">Identifier for the list or set.</param> /// <param name="sortOptions">Options for controlling the sort.</param> /// /// <returns>The sorted values.</returns> byte[][] Sort(string listOrSetId, SortOptions sortOptions); /// <summary>Ranges.</summary> /// /// <param name="listId"> Identifier for the list.</param> /// <param name="startingFrom">The starting from.</param> /// <param name="endingAt"> The ending at.</param> /// /// <returns>A byte[][].</returns> byte[][] LRange(string listId, int startingFrom, int endingAt); /// <summary>Pushes an object onto this stack.</summary> /// /// <param name="listId">Identifier for the list.</param> /// <param name="value"> The value.</param> /// /// <returns>A long.</returns> long RPush(string listId, byte[] value); /// <summary>Pushes an x coordinate.</summary> /// /// <param name="listId">Identifier for the list.</param> /// <param name="value"> The value.</param> /// /// <returns>A long.</returns> long RPushX(string listId, byte[] value); /// <summary>Pushes an object onto this stack.</summary> /// /// <param name="listId">Identifier for the list.</param> /// <param name="value"> The value.</param> /// /// <returns>A long.</returns> long LPush(string listId, byte[] value); /// <summary>Pushes an x coordinate.</summary> /// /// <param name="listId">Identifier for the list.</param> /// <param name="value"> The value.</param> /// /// <returns>A long.</returns> long LPushX(string listId, byte[] value); /// <summary>Trims.</summary> /// /// <param name="listId"> Identifier for the list.</param> /// <param name="keepStartingFrom">The keep starting from.</param> /// <param name="keepEndingAt"> The keep ending at.</param> void LTrim(string listId, int keepStartingFrom, int keepEndingAt); /// <summary>Rems.</summary> /// /// <param name="listId"> Identifier for the list.</param> /// <param name="removeNoOfMatches">The remove no of matches.</param> /// <param name="value"> The value.</param> /// /// <returns>A long.</returns> long LRem(string listId, int removeNoOfMatches, byte[] value); /// <summary>Lens.</summary> /// /// <param name="listId">Identifier for the list.</param> /// /// <returns>A long.</returns> long LLen(string listId); /// <summary>Indexes.</summary> /// /// <param name="listId"> Identifier for the list.</param> /// <param name="listIndex">Zero-based index of the list.</param> /// /// <returns>A byte[].</returns> byte[] LIndex(string listId, int listIndex); /// <summary>Inserts.</summary> /// /// <param name="listId"> Identifier for the list.</param> /// <param name="insertBefore">true to insert before.</param> /// <param name="pivot"> The pivot.</param> /// <param name="value"> The value.</param> void LInsert(string listId, bool insertBefore, byte[] pivot, byte[] value); /// <summary>Sets.</summary> /// /// <param name="listId"> Identifier for the list.</param> /// <param name="listIndex">Zero-based index of the list.</param> /// <param name="value"> The value.</param> void LSet(string listId, int listIndex, byte[] value); /// <summary>Removes and returns the top-of-stack object.</summary> /// /// <param name="listId">Identifier for the list.</param> /// /// <returns>The previous top-of-stack object.</returns> byte[] LPop(string listId); /// <summary>Removes and returns the top-of-stack object.</summary> /// /// <param name="listId">Identifier for the list.</param> /// /// <returns>The previous top-of-stack object.</returns> byte[] RPop(string listId); /// <summary>Bl pop.</summary> /// /// <param name="listId"> Identifier for the list.</param> /// <param name="timeOutSecs">The time out in seconds.</param> /// /// <returns>A byte[][].</returns> byte[][] BLPop(string listId, int timeOutSecs); /// <summary>Bl pop.</summary> /// /// <param name="listIds"> List of identifiers for the lists.</param> /// <param name="timeOutSecs">The time out in seconds.</param> /// /// <returns>A byte[][].</returns> byte[][] BLPop(string[] listIds, int timeOutSecs); /// <summary>Bl pop value.</summary> /// /// <param name="listId"> Identifier for the list.</param> /// <param name="timeOutSecs">The time out in seconds.</param> /// /// <returns>A byte[][].</returns> byte[] BLPopValue(string listId, int timeOutSecs); /// <summary>Bl pop value.</summary> /// /// <param name="listIds"> List of identifiers for the lists.</param> /// <param name="timeOutSecs">The time out in seconds.</param> /// /// <returns>A byte[][].</returns> byte[][] BLPopValue(string[] listIds, int timeOutSecs); /// <summary>Line break pop.</summary> /// /// <param name="listId"> Identifier for the list.</param> /// <param name="timeOutSecs">The time out in seconds.</param> /// /// <returns>A byte[][].</returns> byte[][] BRPop(string listId, int timeOutSecs); /// <summary>Line break pop.</summary> /// /// <param name="listIds"> List of identifiers for the lists.</param> /// <param name="timeOutSecs">The time out in seconds.</param> /// /// <returns>A byte[][].</returns> byte[][] BRPop(string[] listIds, int timeOutSecs); /// <summary>Pops the l push.</summary> /// /// <param name="fromListId">Identifier for from list.</param> /// <param name="toListId"> Identifier for to list.</param> /// /// <returns>A byte[].</returns> byte[] RPopLPush(string fromListId, string toListId); /// <summary>Line break pop value.</summary> /// /// <param name="listId"> Identifier for the list.</param> /// <param name="timeOutSecs">The time out in seconds.</param> /// /// <returns>A byte[][].</returns> byte[] BRPopValue(string listId, int timeOutSecs); /// <summary>Line break pop value.</summary> /// /// <param name="listIds"> List of identifiers for the lists.</param> /// <param name="timeOutSecs">The time out in seconds.</param> /// /// <returns>A byte[][].</returns> byte[][] BRPopValue(string[] listIds, int timeOutSecs); /// <summary>Line break pop l push.</summary> /// /// <param name="fromListId"> Identifier for from list.</param> /// <param name="toListId"> Identifier for to list.</param> /// <param name="timeOutSecs">The time out in seconds.</param> /// /// <returns>A byte[].</returns> byte[] BRPopLPush(string fromListId, string toListId, int timeOutSecs); /// <summary>Members.</summary> /// /// <param name="setId">Identifier for the set.</param> /// /// <returns>A byte[][].</returns> byte[][] SMembers(string setId); /// <summary>Adds setId.</summary> /// /// <param name="setId">Identifier for the set.</param> /// <param name="value">The value.</param> /// /// <returns>A long.</returns> long SAdd(string setId, byte[] value); /// <summary>Adds setId.</summary> /// /// <param name="setId"> Identifier for the set.</param> /// <param name="values">The values.</param> /// /// <returns>A long.</returns> long SAdd(string setId, byte[][] values); /// <summary>Rems.</summary> /// /// <param name="setId">Identifier for the set.</param> /// <param name="value">The value.</param> /// /// <returns>A long.</returns> long SRem(string setId, byte[] value); /// <summary>Removes and returns the top-of-stack object.</summary> /// /// <param name="setId">Identifier for the set.</param> /// /// <returns>The previous top-of-stack object.</returns> byte[] SPop(string setId); /// <summary>Moves.</summary> /// /// <param name="fromSetId">Identifier for from set.</param> /// <param name="toSetId"> Identifier for to set.</param> /// <param name="value"> The value.</param> void SMove(string fromSetId, string toSetId, byte[] value); /// <summary>Cards.</summary> /// /// <param name="setId">Identifier for the set.</param> /// /// <returns>A long.</returns> long SCard(string setId); /// <summary>Is member.</summary> /// /// <param name="setId">Identifier for the set.</param> /// <param name="value">The value.</param> /// /// <returns>A long.</returns> long SIsMember(string setId, byte[] value); /// <summary>Inters the given set identifiers.</summary> /// /// <param name="setIds">List of identifiers for the sets.</param> /// /// <returns>A byte[][].</returns> byte[][] SInter(params string[] setIds); /// <summary>Inter store.</summary> /// /// <param name="intoSetId">Identifier for the into set.</param> /// <param name="setIds"> List of identifiers for the sets.</param> void SInterStore(string intoSetId, params string[] setIds); /// <summary>Unions the given set identifiers.</summary> /// /// <param name="setIds">List of identifiers for the sets.</param> /// /// <returns>A byte[][].</returns> byte[][] SUnion(params string[] setIds); /// <summary>Union store.</summary> /// /// <param name="intoSetId">Identifier for the into set.</param> /// <param name="setIds"> List of identifiers for the sets.</param> void SUnionStore(string intoSetId, params string[] setIds); /// <summary>Compares two string objects to determine their relative ordering.</summary> /// /// <param name="fromSetId"> Identifier for from set.</param> /// <param name="withSetIds">List of identifiers for the with sets.</param> /// /// <returns>A byte[][].</returns> byte[][] SDiff(string fromSetId, params string[] withSetIds); /// <summary>Difference store.</summary> /// /// <param name="intoSetId"> Identifier for the into set.</param> /// <param name="fromSetId"> Identifier for from set.</param> /// <param name="withSetIds">List of identifiers for the with sets.</param> void SDiffStore(string intoSetId, string fromSetId, params string[] withSetIds); /// <summary>Random member.</summary> /// /// <param name="setId">Identifier for the set.</param> /// /// <returns>A byte[].</returns> byte[] SRandMember(string setId); /// <summary>Adds setId.</summary> /// /// <param name="setId">Identifier for the set.</param> /// <param name="score">The score.</param> /// <param name="value">The value.</param> /// /// <returns>A long.</returns> long ZAdd(string setId, double score, byte[] value); /// <summary>Adds setId.</summary> /// /// <param name="setId">Identifier for the set.</param> /// <param name="score">The score.</param> /// <param name="value">The value.</param> /// /// <returns>A long.</returns> long ZAdd(string setId, long score, byte[] value); /// <summary>Z coordinate rems.</summary> /// /// <param name="setId">Identifier for the set.</param> /// <param name="value">The value.</param> /// /// <returns>A long.</returns> long ZRem(string setId, byte[] value); /// <summary>Increment by.</summary> /// /// <param name="setId"> Identifier for the set.</param> /// <param name="incrBy">Amount to increment by.</param> /// <param name="value"> The value.</param> /// /// <returns>A double.</returns> double ZIncrBy(string setId, double incrBy, byte[] value); /// <summary>Increment by.</summary> /// /// <param name="setId"> Identifier for the set.</param> /// <param name="incrBy">Amount to increment by.</param> /// <param name="value"> The value.</param> /// /// <returns>A double.</returns> double ZIncrBy(string setId, long incrBy, byte[] value); /// <summary>Z coordinate ranks.</summary> /// /// <param name="setId">Identifier for the set.</param> /// <param name="value">The value.</param> /// /// <returns>A long.</returns> long ZRank(string setId, byte[] value); /// <summary>Reverse rank.</summary> /// /// <param name="setId">Identifier for the set.</param> /// <param name="value">The value.</param> /// /// <returns>A long.</returns> long ZRevRank(string setId, byte[] value); /// <summary>Z coordinate ranges.</summary> /// /// <param name="setId">Identifier for the set.</param> /// <param name="min"> The minimum.</param> /// <param name="max"> The maximum.</param> /// /// <returns>A byte[][].</returns> byte[][] ZRange(string setId, int min, int max); /// <summary>Range with scores.</summary> /// /// <param name="setId">Identifier for the set.</param> /// <param name="min"> The minimum.</param> /// <param name="max"> The maximum.</param> /// /// <returns>A byte[][].</returns> byte[][] ZRangeWithScores(string setId, int min, int max); /// <summary>Reverse range.</summary> /// /// <param name="setId">Identifier for the set.</param> /// <param name="min"> The minimum.</param> /// <param name="max"> The maximum.</param> /// /// <returns>A byte[][].</returns> byte[][] ZRevRange(string setId, int min, int max); /// <summary>Reverse range with scores.</summary> /// /// <param name="setId">Identifier for the set.</param> /// <param name="min"> The minimum.</param> /// <param name="max"> The maximum.</param> /// /// <returns>A byte[][].</returns> byte[][] ZRevRangeWithScores(string setId, int min, int max); /// <summary>Range by score.</summary> /// /// <param name="setId">Identifier for the set.</param> /// <param name="min"> The minimum.</param> /// <param name="max"> The maximum.</param> /// <param name="skip"> The skip.</param> /// <param name="take"> The take.</param> /// /// <returns>A byte[][].</returns> byte[][] ZRangeByScore(string setId, double min, double max, int? skip, int? take); /// <summary>Range by score.</summary> /// /// <param name="setId">Identifier for the set.</param> /// <param name="min"> The minimum.</param> /// <param name="max"> The maximum.</param> /// <param name="skip"> The skip.</param> /// <param name="take"> The take.</param> /// /// <returns>A byte[][].</returns> byte[][] ZRangeByScore(string setId, long min, long max, int? skip, int? take); /// <summary>Range by score with scores.</summary> /// /// <param name="setId">Identifier for the set.</param> /// <param name="min"> The minimum.</param> /// <param name="max"> The maximum.</param> /// <param name="skip"> The skip.</param> /// <param name="take"> The take.</param> /// /// <returns>A byte[][].</returns> byte[][] ZRangeByScoreWithScores(string setId, double min, double max, int? skip, int? take); /// <summary>Range by score with scores.</summary> /// /// <param name="setId">Identifier for the set.</param> /// <param name="min"> The minimum.</param> /// <param name="max"> The maximum.</param> /// <param name="skip"> The skip.</param> /// <param name="take"> The take.</param> /// /// <returns>A byte[][].</returns> byte[][] ZRangeByScoreWithScores(string setId, long min, long max, int? skip, int? take); /// <summary>Reverse range by score.</summary> /// /// <param name="setId">Identifier for the set.</param> /// <param name="min"> The minimum.</param> /// <param name="max"> The maximum.</param> /// <param name="skip"> The skip.</param> /// <param name="take"> The take.</param> /// /// <returns>A byte[][].</returns> byte[][] ZRevRangeByScore(string setId, double min, double max, int? skip, int? take); /// <summary>Reverse range by score.</summary> /// /// <param name="setId">Identifier for the set.</param> /// <param name="min"> The minimum.</param> /// <param name="max"> The maximum.</param> /// <param name="skip"> The skip.</param> /// <param name="take"> The take.</param> /// /// <returns>A byte[][].</returns> byte[][] ZRevRangeByScore(string setId, long min, long max, int? skip, int? take); /// <summary>Reverse range by score with scores.</summary> /// /// <param name="setId">Identifier for the set.</param> /// <param name="min"> The minimum.</param> /// <param name="max"> The maximum.</param> /// <param name="skip"> The skip.</param> /// <param name="take"> The take.</param> /// /// <returns>A byte[][].</returns> byte[][] ZRevRangeByScoreWithScores(string setId, double min, double max, int? skip, int? take); /// <summary>Reverse range by score with scores.</summary> /// /// <param name="setId">Identifier for the set.</param> /// <param name="min"> The minimum.</param> /// <param name="max"> The maximum.</param> /// <param name="skip"> The skip.</param> /// <param name="take"> The take.</param> /// /// <returns>A byte[][].</returns> byte[][] ZRevRangeByScoreWithScores(string setId, long min, long max, int? skip, int? take); /// <summary>Rem range by rank.</summary> /// /// <param name="setId">Identifier for the set.</param> /// <param name="min"> The minimum.</param> /// <param name="max"> The maximum.</param> /// /// <returns>A long.</returns> long ZRemRangeByRank(string setId, int min, int max); /// <summary>Rem range by score.</summary> /// /// <param name="setId"> Identifier for the set.</param> /// <param name="fromScore">from score.</param> /// <param name="toScore"> to score.</param> /// /// <returns>A long.</returns> long ZRemRangeByScore(string setId, double fromScore, double toScore); /// <summary>Rem range by score.</summary> /// /// <param name="setId"> Identifier for the set.</param> /// <param name="fromScore">from score.</param> /// <param name="toScore"> to score.</param> /// /// <returns>A long.</returns> long ZRemRangeByScore(string setId, long fromScore, long toScore); /// <summary>Z coordinate cards.</summary> /// /// <param name="setId">Identifier for the set.</param> /// /// <returns>A long.</returns> long ZCard(string setId); /// <summary>Z coordinate scores.</summary> /// /// <param name="setId">Identifier for the set.</param> /// <param name="value">The value.</param> /// /// <returns>A double.</returns> double ZScore(string setId, byte[] value); /// <summary>Union store.</summary> /// /// <param name="intoSetId">Identifier for the into set.</param> /// <param name="setIds"> List of identifiers for the sets.</param> /// /// <returns>A long.</returns> long ZUnionStore(string intoSetId, params string[] setIds); /// <summary>Union store with weights.</summary> /// /// <param name="intoSetId">Identifier for the into set.</param> /// <param name="setIdWithWeightPairs"> List of identifiers for the sets along with the weight to multiply the scores with.</param> /// /// <returns>A long.</returns> long ZUnionStoreWithWeights(string intoSetId, params KeyValuePair<string, double>[] setIdWithWeightPairs); /// <summary>Inter store.</summary> /// /// <param name="intoSetId">Identifier for the into set.</param> /// <param name="setIds"> List of identifiers for the sets.</param> /// /// <returns>A long.</returns> long ZInterStore(string intoSetId, params string[] setIds); /// <summary>Inter store with weights.</summary> /// /// <param name="intoSetId">Identifier for the into set.</param> /// <param name="setIdWithWeightPairs"> List of identifiers for the sets along with the weight to multiply the scores with.</param> /// /// <returns>A long.</returns> long ZInterStoreWithWeights(string intoSetId, params KeyValuePair<string, double>[] setIdWithWeightPairs); /// <summary>Sets.</summary> /// /// <param name="hashId">Identifier for the hash.</param> /// <param name="key"> The key.</param> /// <param name="value"> The value.</param> /// /// <returns>A long.</returns> long HSet(string hashId, byte[] key, byte[] value); /// <summary>Hm set.</summary> /// /// <param name="hashId">Identifier for the hash.</param> /// <param name="keys"> The keys.</param> /// <param name="values">The values.</param> void HMSet(string hashId, byte[][] keys, byte[][] values); /// <summary>Sets a nx.</summary> /// /// <param name="hashId">Identifier for the hash.</param> /// <param name="key"> The key.</param> /// <param name="value"> The value.</param> /// /// <returns>A long.</returns> long HSetNX(string hashId, byte[] key, byte[] value); /// <summary>Incrbies.</summary> /// /// <param name="hashId"> Identifier for the hash.</param> /// <param name="key"> The key.</param> /// <param name="incrementBy">Amount to increment by.</param> /// /// <returns>A long.</returns> long HIncrby(string hashId, byte[] key, int incrementBy); /// <summary>Incrby float.</summary> /// /// <param name="hashId"> Identifier for the hash.</param> /// <param name="key"> The key.</param> /// <param name="incrementBy">Amount to increment by.</param> /// /// <returns>A double.</returns> double HIncrbyFloat(string hashId, byte[] key, double incrementBy); /// <summary>Gets.</summary> /// /// <param name="hashId">Identifier for the hash.</param> /// <param name="key"> The key.</param> /// /// <returns>A byte[].</returns> byte[] HGet(string hashId, byte[] key); /// <summary>Hm get.</summary> /// /// <param name="hashId"> Identifier for the hash.</param> /// <param name="keysAndArgs">A variable-length parameters list containing keys and arguments.</param> /// /// <returns>A byte[][].</returns> byte[][] HMGet(string hashId, params byte[][] keysAndArgs); /// <summary>Deletes this object.</summary> /// /// <param name="hashId">Identifier for the hash.</param> /// <param name="key"> The key.</param> /// /// <returns>A long.</returns> long HDel(string hashId, byte[] key); /// <summary>Exists.</summary> /// /// <param name="hashId">Identifier for the hash.</param> /// <param name="key"> The key.</param> /// /// <returns>A long.</returns> long HExists(string hashId, byte[] key); /// <summary>Lens.</summary> /// /// <param name="hashId">Identifier for the hash.</param> /// /// <returns>A long.</returns> long HLen(string hashId); /// <summary>Keys.</summary> /// /// <param name="hashId">Identifier for the hash.</param> /// /// <returns>A byte[][].</returns> byte[][] HKeys(string hashId); /// <summary>Vals.</summary> /// /// <param name="hashId">Identifier for the hash.</param> /// /// <returns>A byte[][].</returns> byte[][] HVals(string hashId); /// <summary>Gets all.</summary> /// /// <param name="hashId">Identifier for the hash.</param> /// /// <returns>An array of byte[].</returns> byte[][] HGetAll(string hashId); /// <summary>Watches the given keys.</summary> /// /// <param name="keys">The keys.</param> void Watch(params string[] keys); /// <summary>Un watch.</summary> void UnWatch(); /// <summary>Publishes.</summary> /// /// <param name="toChannel">to channel.</param> /// <param name="message"> The message.</param> /// /// <returns>A long.</returns> long Publish(string toChannel, byte[] message); /// <summary>Subscribes the given to channels.</summary> /// /// <param name="toChannels">A variable-length parameters list containing to channels.</param> /// /// <returns>A byte[][].</returns> byte[][] Subscribe(params string[] toChannels); /// <summary>Un subscribe.</summary> /// /// <param name="toChannels">A variable-length parameters list containing to channels.</param> /// /// <returns>A byte[][].</returns> byte[][] UnSubscribe(params string[] toChannels); /// <summary>Subscribes the given to channels matching patterns.</summary> /// /// <param name="toChannelsMatchingPatterns">A variable-length parameters list containing to channels matching patterns.</param> /// /// <returns>A byte[][].</returns> byte[][] PSubscribe(params string[] toChannelsMatchingPatterns); /// <summary>Un subscribe.</summary> /// /// <param name="toChannelsMatchingPatterns">A variable-length parameters list containing to channels matching patterns.</param> /// /// <returns>A byte[][].</returns> byte[][] PUnSubscribe(params string[] toChannelsMatchingPatterns); /// <summary>Receive messages.</summary> /// /// <returns>A byte[][].</returns> byte[][] ReceiveMessages(); /// <summary>Redis LUA support.</summary> /// /// <param name="luaBody"> The lua body.</param> /// <param name="numberOfKeys">Number of keys.</param> /// <param name="keysAndArgs"> A variable-length parameters list containing keys and arguments.</param> /// /// <returns>A long.</returns> long EvalInt(string luaBody, int numberOfKeys, params byte[][] keysAndArgs); /// <summary>Eval sha int.</summary> /// /// <param name="sha1"> The first sha.</param> /// <param name="numberOfKeys">Number of keys.</param> /// <param name="keysAndArgs"> A variable-length parameters list containing keys and arguments.</param> /// /// <returns>A long.</returns> long EvalShaInt(string sha1, int numberOfKeys, params byte[][] keysAndArgs); /// <summary>Eval string.</summary> /// /// <param name="luaBody"> The lua body.</param> /// <param name="numberOfKeys">Number of keys.</param> /// <param name="keysAndArgs"> A variable-length parameters list containing keys and arguments.</param> /// /// <returns>A string.</returns> string EvalStr(string luaBody, int numberOfKeys, params byte[][] keysAndArgs); /// <summary>Eval sha string.</summary> /// /// <param name="sha1"> The first sha.</param> /// <param name="numberOfKeys">Number of keys.</param> /// <param name="keysAndArgs"> A variable-length parameters list containing keys and arguments.</param> /// /// <returns>A string.</returns> string EvalShaStr(string sha1, int numberOfKeys, params byte[][] keysAndArgs); /// <summary>Evals.</summary> /// /// <param name="luaBody"> The lua body.</param> /// <param name="numberOfKeys">Number of keys.</param> /// <param name="keysAndArgs"> A variable-length parameters list containing keys and arguments.</param> /// /// <returns>A byte[][].</returns> byte[][] Eval(string luaBody, int numberOfKeys, params byte[][] keysAndArgs); /// <summary>Eval sha.</summary> /// /// <param name="sha1"> The first sha.</param> /// <param name="numberOfKeys">Number of keys.</param> /// <param name="keysAndArgs"> A variable-length parameters list containing keys and arguments.</param> /// /// <returns>A byte[][].</returns> byte[][] EvalSha(string sha1, int numberOfKeys, params byte[][] keysAndArgs); /// <summary>Calculates the sha 1.</summary> /// /// <param name="luaBody">The lua body.</param> /// /// <returns>The calculated sha 1.</returns> string CalculateSha1(string luaBody); /// <summary>Queries if a given script exists.</summary> /// /// <param name="sha1Refs">A variable-length parameters list containing sha 1 references.</param> /// /// <returns>A byte[][].</returns> byte[][] ScriptExists(params byte[][] sha1Refs); /// <summary>Script flush.</summary> void ScriptFlush(); /// <summary>Script kill.</summary> void ScriptKill(); /// <summary>Script load.</summary> /// /// <param name="body">The body.</param> /// /// <returns>A byte[].</returns> byte[] ScriptLoad(string body); } }
using System.Linq; using System.Runtime.CompilerServices; using AutoMapper.Mappers; namespace AutoMapper { using System; using System.Collections.Generic; using System.Reflection; using Configuration; using Configuration.Conventions; using IMemberConfiguration = Configuration.Conventions.IMemberConfiguration; /// <summary> /// Provides a named configuration for maps. Naming conventions become scoped per profile. /// </summary> public abstract class Profile : IProfileExpression, IProfileConfiguration { private readonly ConditionalObjectMapper _mapMissingTypes = new ConditionalObjectMapper {Conventions = {tp => true}}; private readonly List<string> _globalIgnore = new List<string>(); private readonly List<Action<TypeMap, IMappingExpression>> _allTypeMapActions = new List<Action<TypeMap, IMappingExpression>>(); private readonly List<ITypeMapConfiguration> _typeMapConfigs = new List<ITypeMapConfiguration>(); private readonly TypeMapFactory _typeMapFactory = new TypeMapFactory(); protected Profile(string profileName) :this() { ProfileName = profileName; } protected Profile() { ProfileName = GetType().FullName; IncludeSourceExtensionMethods(typeof(Enumerable)); _memberConfigurations.Add(new MemberConfiguration().AddMember<NameSplitMember>().AddName<PrePostfixName>(_ => _.AddStrings(p => p.Prefixes, "Get"))); } [Obsolete("Use the constructor instead. Will be removed in 6.0")] protected virtual void Configure() { } internal void Initialize() => Configure(); public virtual string ProfileName { get; } public void DisableConstructorMapping() { ConstructorMappingEnabled = false; } public bool AllowNullDestinationValues { get; set; } = true; public bool AllowNullCollections { get; set; } public IEnumerable<string> GlobalIgnores => _globalIgnore; public INamingConvention SourceMemberNamingConvention { get { INamingConvention convention = null; DefaultMemberConfig.AddMember<NameSplitMember>(_ => convention = _.SourceMemberNamingConvention); return convention; } set { DefaultMemberConfig.AddMember<NameSplitMember>(_ => _.SourceMemberNamingConvention = value); } } public INamingConvention DestinationMemberNamingConvention { get { INamingConvention convention = null; DefaultMemberConfig.AddMember<NameSplitMember>(_ => convention = _.DestinationMemberNamingConvention); return convention; } set { DefaultMemberConfig.AddMember<NameSplitMember>(_ => _.DestinationMemberNamingConvention = value); } } public bool CreateMissingTypeMaps { get { return _createMissingTypeMaps; } set { _createMissingTypeMaps = value; if (value) _typeConfigurations.Add(_mapMissingTypes); else _typeConfigurations.Remove(_mapMissingTypes); } } public void ForAllMaps(Action<TypeMap, IMappingExpression> configuration) { _allTypeMapActions.Add(configuration); } public IMappingExpression<TSource, TDestination> CreateMap<TSource, TDestination>() { return CreateMap<TSource, TDestination>(MemberList.Destination); } public IMappingExpression<TSource, TDestination> CreateMap<TSource, TDestination>(MemberList memberList) { return CreateMappingExpression<TSource, TDestination>(memberList); } public IMappingExpression CreateMap(Type sourceType, Type destinationType) { return CreateMap(sourceType, destinationType, MemberList.Destination); } public IMappingExpression CreateMap(Type sourceType, Type destinationType, MemberList memberList) { var map = new MappingExpression(new TypePair(sourceType, destinationType), memberList); _typeMapConfigs.Add(map); return map; } private IMappingExpression<TSource, TDestination> CreateMappingExpression<TSource, TDestination>(MemberList memberList) { var mappingExp = new MappingExpression<TSource, TDestination>(memberList); _typeMapConfigs.Add(mappingExp); return mappingExp; } public void ClearPrefixes() { DefaultMemberConfig.AddName<PrePostfixName>(_ => _.Prefixes.Clear()); } public void RecognizeAlias(string original, string alias) { DefaultMemberConfig.AddName<ReplaceName>(_ => _.AddReplace(original, alias)); } public void ReplaceMemberName(string original, string newValue) { DefaultMemberConfig.AddName<ReplaceName>(_ => _.AddReplace(original, newValue)); } public void RecognizePrefixes(params string[] prefixes) { DefaultMemberConfig.AddName<PrePostfixName>(_ => _.AddStrings(p => p.Prefixes, prefixes)); } public void RecognizePostfixes(params string[] postfixes) { DefaultMemberConfig.AddName<PrePostfixName>(_ => _.AddStrings(p => p.Postfixes, postfixes)); } public void RecognizeDestinationPrefixes(params string[] prefixes) { DefaultMemberConfig.AddName<PrePostfixName>(_ => _.AddStrings(p => p.DestinationPrefixes, prefixes)); } public void RecognizeDestinationPostfixes(params string[] postfixes) { DefaultMemberConfig.AddName<PrePostfixName>(_ => _.AddStrings(p => p.DestinationPostfixes, postfixes)); } public void AddGlobalIgnore(string propertyNameStartingWith) { _globalIgnore.Add(propertyNameStartingWith); } private readonly List<MethodInfo> _sourceExtensionMethods = new List<MethodInfo>(); private readonly IList<IMemberConfiguration> _memberConfigurations = new List<IMemberConfiguration>(); public IMemberConfiguration DefaultMemberConfig => _memberConfigurations.First(); public IEnumerable<IMemberConfiguration> MemberConfigurations => _memberConfigurations; public IMemberConfiguration AddMemberConfiguration() { var condition = new MemberConfiguration(); _memberConfigurations.Add(condition); return condition; } private readonly IList<ConditionalObjectMapper> _typeConfigurations = new List<ConditionalObjectMapper>(); private bool _createMissingTypeMaps; public IEnumerable<IConditionalObjectMapper> TypeConfigurations => _typeConfigurations; public IConditionalObjectMapper AddConditionalObjectMapper() { var condition = new ConditionalObjectMapper(); _typeConfigurations.Add(condition); return condition; } public bool ConstructorMappingEnabled { get; private set; } = true; public IEnumerable<MethodInfo> SourceExtensionMethods => _sourceExtensionMethods; public Func<PropertyInfo, bool> ShouldMapProperty { get; set; } = p => p.IsPublic(); public Func<FieldInfo, bool> ShouldMapField { get; set; } = f => f.IsPublic(); public void IncludeSourceExtensionMethods(Type type) { _sourceExtensionMethods.AddRange(type.GetDeclaredMethods().Where(m => m.IsStatic && m.IsDefined(typeof(ExtensionAttribute), false) && m.GetParameters().Length == 1)); } void IProfileConfiguration.Register(TypeMapRegistry typeMapRegistry) { foreach (var config in _typeMapConfigs) { BuildTypeMap(typeMapRegistry, config); if (config.ReverseTypeMap != null) { BuildTypeMap(typeMapRegistry, config.ReverseTypeMap); } } } void IProfileConfiguration.Configure(TypeMapRegistry typeMapRegistry) { foreach (var typeMap in _typeMapConfigs.Select(config => typeMapRegistry.GetTypeMap(config.Types))) { Configure(typeMapRegistry, typeMap); } } TypeMap IProfileConfiguration.ConfigureConventionTypeMap(TypeMapRegistry typeMapRegistry, TypePair types) { if (! TypeConfigurations.Any(c => c.IsMatch(types))) return null; var typeMap = _typeMapFactory.CreateTypeMap(types.SourceType, types.DestinationType, this, MemberList.Destination); var config = new MappingExpression(typeMap.Types, typeMap.ConfiguredMemberList); config.Configure(this, typeMap); Configure(typeMapRegistry, typeMap); return typeMap; } TypeMap IProfileConfiguration.ConfigureClosedGenericTypeMap(TypeMapRegistry typeMapRegistry, TypePair closedTypes, TypePair requestedTypes) { var openMapConfig = _typeMapConfigs .Where(tm => tm.Types.SourceType.GetGenericTypeDefinitionIfGeneric() == closedTypes.SourceType.GetGenericTypeDefinitionIfGeneric() && tm.Types.DestinationType.GetGenericTypeDefinitionIfGeneric() == closedTypes.DestinationType.GetGenericTypeDefinitionIfGeneric()) .OrderByDescending(tm => tm.DestinationType == closedTypes.DestinationType) // Favor more specific destination matches, .ThenByDescending(tm => tm.SourceType == closedTypes.SourceType) // then more specific source matches .FirstOrDefault(); if (openMapConfig == null) return null; var closedMap = _typeMapFactory.CreateTypeMap(requestedTypes.SourceType, requestedTypes.DestinationType, this, openMapConfig.MemberList); openMapConfig.Configure(this, closedMap); Configure(typeMapRegistry, closedMap); if (closedMap.TypeConverterType != null) { var typeParams = (openMapConfig.SourceType.IsGenericTypeDefinition() ? closedTypes.SourceType.GetGenericArguments() : new Type[0]) .Concat (openMapConfig.DestinationType.IsGenericTypeDefinition() ? closedTypes.DestinationType.GetGenericArguments() : new Type[0]); var neededParameters = closedMap.TypeConverterType.GetGenericParameters().Length; closedMap.TypeConverterType = closedMap.TypeConverterType.MakeGenericType(typeParams.Take(neededParameters).ToArray()); } return closedMap; } private void Configure(TypeMapRegistry typeMapRegistry, TypeMap typeMap) { foreach(var action in _allTypeMapActions) { var expression = new MappingExpression(typeMap.Types, typeMap.ConfiguredMemberList); action(typeMap, expression); expression.Configure(this, typeMap); } ApplyBaseMaps(typeMapRegistry, typeMap, typeMap); ApplyDerivedMaps(typeMapRegistry, typeMap, typeMap); } private static void ApplyBaseMaps(TypeMapRegistry typeMapRegistry, TypeMap derivedMap, TypeMap currentMap) { foreach(var baseMap in currentMap.IncludedBaseTypes.Select(typeMapRegistry.GetTypeMap).Where(baseMap => baseMap != null)) { baseMap.IncludeDerivedTypes(currentMap.SourceType, currentMap.DestinationType); derivedMap.ApplyInheritedMap(baseMap); ApplyBaseMaps(typeMapRegistry, derivedMap, baseMap); } } private void ApplyDerivedMaps(TypeMapRegistry typeMapRegistry, TypeMap baseMap, TypeMap typeMap) { foreach (var inheritedTypeMap in typeMap.IncludedDerivedTypes.Select(typeMapRegistry.GetTypeMap).Where(map => map != null)) { inheritedTypeMap.ApplyInheritedMap(baseMap); ApplyDerivedMaps(typeMapRegistry, baseMap, inheritedTypeMap); } } private void BuildTypeMap(TypeMapRegistry typeMapRegistry, ITypeMapConfiguration config) { var typeMap = _typeMapFactory.CreateTypeMap(config.SourceType, config.DestinationType, this, config.MemberList); config.Configure(this, typeMap); typeMapRegistry.RegisterTypeMap(typeMap); } } }
// 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. // This RegexFCD class is internal to the Regex package. // It builds a bunch of FC information (RegexFC) about // the regex for optimization purposes. // Implementation notes: // // This step is as simple as walking the tree and emitting // sequences of codes. using System; using System.Globalization; using System.Text; namespace Flatbox.RegularExpressions { internal sealed class RegexFCD { private int[] _intStack; private int _intDepth; private RegexFC[] _fcStack; private int _fcDepth; private bool _skipAllChildren; // don't process any more children at the current level private bool _skipchild; // don't process the current child. private bool _failed = false; private const int BeforeChild = 64; private const int AfterChild = 128; // where the regex can be pegged internal const int Beginning = 0x0001; internal const int Bol = 0x0002; internal const int Start = 0x0004; internal const int Eol = 0x0008; internal const int EndZ = 0x0010; internal const int End = 0x0020; internal const int Boundary = 0x0040; internal const int ECMABoundary = 0x0080; /* * This is the one of the only two functions that should be called from outside. * It takes a RegexTree and computes the set of chars that can start it. */ internal static RegexPrefix FirstChars(RegexTree t) { RegexFCD s = new RegexFCD(); RegexFC fc = s.RegexFCFromRegexTree(t); if (fc == null || fc._nullable) return null; CultureInfo culture = ((t._options & RegexOptions.CultureInvariant) != 0) ? CultureInfo.InvariantCulture : CultureInfo.CurrentCulture; return new RegexPrefix(fc.GetFirstChars(culture), fc.IsCaseInsensitive()); } /* * This is a related computation: it takes a RegexTree and computes the * leading substring if it see one. It's quite trivial and gives up easily. */ internal static RegexPrefix Prefix(RegexTree tree) { RegexNode curNode; RegexNode concatNode = null; int nextChild = 0; curNode = tree._root; for (; ;) { switch (curNode._type) { case RegexNode.Concatenate: if (curNode.ChildCount() > 0) { concatNode = curNode; nextChild = 0; } break; case RegexNode.Greedy: case RegexNode.Capture: curNode = curNode.Child(0); concatNode = null; continue; case RegexNode.Oneloop: case RegexNode.Onelazy: if (curNode._m > 0) { string pref = string.Empty.PadRight(curNode._m, curNode._ch); return new RegexPrefix(pref, 0 != (curNode._options & RegexOptions.IgnoreCase)); } else return RegexPrefix.Empty; case RegexNode.One: return new RegexPrefix(curNode._ch.ToString(), 0 != (curNode._options & RegexOptions.IgnoreCase)); case RegexNode.Multi: return new RegexPrefix(curNode._str, 0 != (curNode._options & RegexOptions.IgnoreCase)); case RegexNode.Bol: case RegexNode.Eol: case RegexNode.Boundary: case RegexNode.ECMABoundary: case RegexNode.Beginning: case RegexNode.Start: case RegexNode.EndZ: case RegexNode.End: case RegexNode.Empty: case RegexNode.Require: case RegexNode.Prevent: break; default: return RegexPrefix.Empty; } if (concatNode == null || nextChild >= concatNode.ChildCount()) return RegexPrefix.Empty; curNode = concatNode.Child(nextChild++); } } /* * Yet another related computation: it takes a RegexTree and computes the * leading anchors that it encounters. */ internal static int Anchors(RegexTree tree) { RegexNode curNode; RegexNode concatNode = null; int nextChild = 0; int result = 0; curNode = tree._root; for (; ;) { switch (curNode._type) { case RegexNode.Concatenate: if (curNode.ChildCount() > 0) { concatNode = curNode; nextChild = 0; } break; case RegexNode.Greedy: case RegexNode.Capture: curNode = curNode.Child(0); concatNode = null; continue; case RegexNode.Bol: case RegexNode.Eol: case RegexNode.Boundary: case RegexNode.ECMABoundary: case RegexNode.Beginning: case RegexNode.Start: case RegexNode.EndZ: case RegexNode.End: return result | AnchorFromType(curNode._type); case RegexNode.Empty: case RegexNode.Require: case RegexNode.Prevent: break; default: return result; } if (concatNode == null || nextChild >= concatNode.ChildCount()) return result; curNode = concatNode.Child(nextChild++); } } /* * Convert anchor type to anchor bit. */ private static int AnchorFromType(int type) { switch (type) { case RegexNode.Bol: return Bol; case RegexNode.Eol: return Eol; case RegexNode.Boundary: return Boundary; case RegexNode.ECMABoundary: return ECMABoundary; case RegexNode.Beginning: return Beginning; case RegexNode.Start: return Start; case RegexNode.EndZ: return EndZ; case RegexNode.End: return End; default: return 0; } } #if DEBUG internal static string AnchorDescription(int anchors) { StringBuilder sb = new StringBuilder(); if (0 != (anchors & Beginning)) sb.Append(", Beginning"); if (0 != (anchors & Start)) sb.Append(", Start"); if (0 != (anchors & Bol)) sb.Append(", Bol"); if (0 != (anchors & Boundary)) sb.Append(", Boundary"); if (0 != (anchors & ECMABoundary)) sb.Append(", ECMABoundary"); if (0 != (anchors & Eol)) sb.Append(", Eol"); if (0 != (anchors & End)) sb.Append(", End"); if (0 != (anchors & EndZ)) sb.Append(", EndZ"); if (sb.Length >= 2) return (sb.ToString(2, sb.Length - 2)); return "None"; } #endif /* * private constructor; can't be created outside */ private RegexFCD() { _fcStack = new RegexFC[32]; _intStack = new int[32]; } /* * To avoid recursion, we use a simple integer stack. * This is the push. */ private void PushInt(int I) { if (_intDepth >= _intStack.Length) { int[] expanded = new int[_intDepth * 2]; Array.Copy(_intStack, 0, expanded, 0, _intDepth); _intStack = expanded; } _intStack[_intDepth++] = I; } /* * True if the stack is empty. */ private bool IntIsEmpty() { return _intDepth == 0; } /* * This is the pop. */ private int PopInt() { return _intStack[--_intDepth]; } /* * We also use a stack of RegexFC objects. * This is the push. */ private void PushFC(RegexFC fc) { if (_fcDepth >= _fcStack.Length) { RegexFC[] expanded = new RegexFC[_fcDepth * 2]; Array.Copy(_fcStack, 0, expanded, 0, _fcDepth); _fcStack = expanded; } _fcStack[_fcDepth++] = fc; } /* * True if the stack is empty. */ private bool FCIsEmpty() { return _fcDepth == 0; } /* * This is the pop. */ private RegexFC PopFC() { return _fcStack[--_fcDepth]; } /* * This is the top. */ private RegexFC TopFC() { return _fcStack[_fcDepth - 1]; } /* * The main FC computation. It does a shortcutted depth-first walk * through the tree and calls CalculateFC to emits code before * and after each child of an interior node, and at each leaf. */ private RegexFC RegexFCFromRegexTree(RegexTree tree) { RegexNode curNode; int curChild; curNode = tree._root; curChild = 0; for (; ;) { if (curNode._children == null) { // This is a leaf node CalculateFC(curNode._type, curNode, 0); } else if (curChild < curNode._children.Count && !_skipAllChildren) { // This is an interior node, and we have more children to analyze CalculateFC(curNode._type | BeforeChild, curNode, curChild); if (!_skipchild) { curNode = curNode._children[curChild]; // this stack is how we get a depth first walk of the tree. PushInt(curChild); curChild = 0; } else { curChild++; _skipchild = false; } continue; } // This is an interior node where we've finished analyzing all the children, or // the end of a leaf node. _skipAllChildren = false; if (IntIsEmpty()) break; curChild = PopInt(); curNode = curNode._next; CalculateFC(curNode._type | AfterChild, curNode, curChild); if (_failed) return null; curChild++; } if (FCIsEmpty()) return null; return PopFC(); } /* * Called in Beforechild to prevent further processing of the current child */ private void SkipChild() { _skipchild = true; } /* * FC computation and shortcut cases for each node type */ private void CalculateFC(int NodeType, RegexNode node, int CurIndex) { bool ci = false; bool rtl = false; if (NodeType <= RegexNode.Ref) { if ((node._options & RegexOptions.IgnoreCase) != 0) ci = true; if ((node._options & RegexOptions.RightToLeft) != 0) rtl = true; } switch (NodeType) { case RegexNode.Concatenate | BeforeChild: case RegexNode.Alternate | BeforeChild: case RegexNode.Testref | BeforeChild: case RegexNode.Loop | BeforeChild: case RegexNode.Lazyloop | BeforeChild: break; case RegexNode.Testgroup | BeforeChild: if (CurIndex == 0) SkipChild(); break; case RegexNode.Empty: PushFC(new RegexFC(true)); break; case RegexNode.Concatenate | AfterChild: if (CurIndex != 0) { RegexFC child = PopFC(); RegexFC cumul = TopFC(); _failed = !cumul.AddFC(child, true); } if (!TopFC()._nullable) _skipAllChildren = true; break; case RegexNode.Testgroup | AfterChild: if (CurIndex > 1) { RegexFC child = PopFC(); RegexFC cumul = TopFC(); _failed = !cumul.AddFC(child, false); } break; case RegexNode.Alternate | AfterChild: case RegexNode.Testref | AfterChild: if (CurIndex != 0) { RegexFC child = PopFC(); RegexFC cumul = TopFC(); _failed = !cumul.AddFC(child, false); } break; case RegexNode.Loop | AfterChild: case RegexNode.Lazyloop | AfterChild: if (node._m == 0) TopFC()._nullable = true; break; case RegexNode.Group | BeforeChild: case RegexNode.Group | AfterChild: case RegexNode.Capture | BeforeChild: case RegexNode.Capture | AfterChild: case RegexNode.Greedy | BeforeChild: case RegexNode.Greedy | AfterChild: break; case RegexNode.Require | BeforeChild: case RegexNode.Prevent | BeforeChild: SkipChild(); PushFC(new RegexFC(true)); break; case RegexNode.Require | AfterChild: case RegexNode.Prevent | AfterChild: break; case RegexNode.One: case RegexNode.Notone: PushFC(new RegexFC(node._ch, NodeType == RegexNode.Notone, false, ci)); break; case RegexNode.Oneloop: case RegexNode.Onelazy: PushFC(new RegexFC(node._ch, false, node._m == 0, ci)); break; case RegexNode.Notoneloop: case RegexNode.Notonelazy: PushFC(new RegexFC(node._ch, true, node._m == 0, ci)); break; case RegexNode.Multi: if (node._str.Length == 0) PushFC(new RegexFC(true)); else if (!rtl) PushFC(new RegexFC(node._str[0], false, false, ci)); else PushFC(new RegexFC(node._str[node._str.Length - 1], false, false, ci)); break; case RegexNode.Set: PushFC(new RegexFC(node._str, false, ci)); break; case RegexNode.Setloop: case RegexNode.Setlazy: PushFC(new RegexFC(node._str, node._m == 0, ci)); break; case RegexNode.Ref: PushFC(new RegexFC(RegexCharClass.AnyClass, true, false)); break; case RegexNode.Nothing: case RegexNode.Bol: case RegexNode.Eol: case RegexNode.Boundary: case RegexNode.Nonboundary: case RegexNode.ECMABoundary: case RegexNode.NonECMABoundary: case RegexNode.Beginning: case RegexNode.Start: case RegexNode.EndZ: case RegexNode.End: PushFC(new RegexFC(true)); break; default: throw new ArgumentException(""); } } } internal sealed class RegexFC { internal RegexCharClass _cc; internal bool _nullable; internal bool _caseInsensitive; internal RegexFC(bool nullable) { _cc = new RegexCharClass(); _nullable = nullable; } internal RegexFC(char ch, bool not, bool nullable, bool caseInsensitive) { _cc = new RegexCharClass(); if (not) { if (ch > 0) _cc.AddRange('\0', (char)(ch - 1)); if (ch < 0xFFFF) _cc.AddRange((char)(ch + 1), '\uFFFF'); } else { _cc.AddRange(ch, ch); } _caseInsensitive = caseInsensitive; _nullable = nullable; } internal RegexFC(string charClass, bool nullable, bool caseInsensitive) { _cc = RegexCharClass.Parse(charClass); _nullable = nullable; _caseInsensitive = caseInsensitive; } internal bool AddFC(RegexFC fc, bool concatenate) { if (!_cc.CanMerge || !fc._cc.CanMerge) { return false; } if (concatenate) { if (!_nullable) return true; if (!fc._nullable) _nullable = false; } else { if (fc._nullable) _nullable = true; } _caseInsensitive |= fc._caseInsensitive; _cc.AddCharClass(fc._cc); return true; } internal String GetFirstChars(CultureInfo culture) { if (_caseInsensitive) _cc.AddLowercase(culture); return _cc.ToStringClass(); } internal bool IsCaseInsensitive() { return _caseInsensitive; } } internal sealed class RegexPrefix { internal string _prefix; internal bool _caseInsensitive; internal static RegexPrefix _empty = new RegexPrefix(string.Empty, false); internal RegexPrefix(string prefix, bool ci) { _prefix = prefix; _caseInsensitive = ci; } internal string Prefix { get { return _prefix; } } internal bool CaseInsensitive { get { return _caseInsensitive; } } internal static RegexPrefix Empty { get { return _empty; } } } }
// Copyright 2006 Alp Toker <[email protected]> // Copyright 2016 Tom Deseyn <[email protected]> // This software is made available under the MIT License // See COPYING for details using System; using System.Text; using System.Collections.Generic; using System.Linq; using System.Reflection; using Tmds.DBus.CodeGen; using Tmds.DBus.Protocol; namespace Tmds.DBus { /// <summary> /// D-Bus type signature. /// </summary> public struct Signature { internal static readonly Signature Empty = new Signature (String.Empty); internal static readonly Signature ArraySig = Allocate (DType.Array); internal static readonly Signature ByteSig = Allocate (DType.Byte); internal static readonly Signature DictEntryBegin = Allocate (DType.DictEntryBegin); internal static readonly Signature DictEntryEnd = Allocate (DType.DictEntryEnd); internal static readonly Signature Int32Sig = Allocate (DType.Int32); internal static readonly Signature UInt16Sig = Allocate (DType.UInt16); internal static readonly Signature UInt32Sig = Allocate (DType.UInt32); internal static readonly Signature StringSig = Allocate (DType.String); internal static readonly Signature StructBegin = Allocate (DType.StructBegin); internal static readonly Signature StructEnd = Allocate (DType.StructEnd); internal static readonly Signature ObjectPathSig = Allocate (DType.ObjectPath); internal static readonly Signature SignatureSig = Allocate (DType.Signature); internal static readonly Signature SignatureUnixFd = Allocate (DType.UnixFd); internal static readonly Signature VariantSig = Allocate (DType.Variant); internal static readonly Signature BoolSig = Allocate(DType.Boolean); internal static readonly Signature DoubleSig = Allocate(DType.Double); internal static readonly Signature Int16Sig = Allocate(DType.Int16); internal static readonly Signature Int64Sig = Allocate(DType.Int64); internal static readonly Signature SingleSig = Allocate(DType.Single); internal static readonly Signature UInt64Sig = Allocate(DType.UInt64); internal static readonly Signature StructBeginSig = Allocate(DType.StructBegin); internal static readonly Signature StructEndSig = Allocate(DType.StructEnd); internal static readonly Signature DictEntryBeginSig = Allocate(DType.DictEntryBegin); internal static readonly Signature DictEntryEndSig = Allocate(DType.DictEntryEnd); private byte[] _data; /// <summary> /// Determines whether two specified Signatures have the same value. /// </summary> public static bool operator== (Signature a, Signature b) { if (a._data == b._data) return true; if (a._data == null) return false; if (b._data == null) return false; if (a._data.Length != b._data.Length) return false; for (int i = 0 ; i != a._data.Length ; i++) if (a._data[i] != b._data[i]) return false; return true; } /// <summary> /// Determines whether two specified Signatures have different values. /// </summary> public static bool operator!=(Signature a, Signature b) { return !(a == b); } /// <summary> /// Determines whether the specified object is equal to the current object. /// </summary> public override bool Equals (object o) { if (o == null) return false; if (!(o is Signature)) return false; return this == (Signature)o; } /// <summary> /// Returns the hash code for this Signature. /// </summary> public override int GetHashCode() { if (_data == null) { return 0; } int hash = 17; for(int i = 0; i < _data.Length; i++) { hash = hash * 31 + _data[i].GetHashCode(); } return hash; } internal static Signature Concat (Signature s1, Signature s2) { if (s1._data == null && s2._data == null) return Signature.Empty; if (s1._data == null) return s2; if (s2._data == null) return s1; if (s1.Length + s2.Length == 0) return Signature.Empty; byte[] data = new byte[s1._data.Length + s2._data.Length]; s1._data.CopyTo (data, 0); s2._data.CopyTo (data, s1._data.Length); return Signature.Take (data); } /// <summary> /// Creates a new Signature. /// </summary> /// <param name="value">signature.</param> public Signature(string value) { if (value == null) throw new ArgumentNullException ("value"); if (!IsValid (value)) throw new ArgumentException (string.Format ("'{0}' is not a valid signature", value), "value"); foreach (var c in value) if (!Enum.IsDefined (typeof (DType), (byte) c)) throw new ArgumentException (string.Format ("{0} is not a valid dbus type", c)); if (value.Length == 0) { _data = Array.Empty<byte>(); } else if (value.Length == 1) { _data = DataForDType ((DType)value[0]); } else { _data = Encoding.ASCII.GetBytes (value); } } /// <summary> /// Creates a new Signature. /// </summary> /// <param name="value">signature.</param> public static implicit operator Signature(string value) { return new Signature(value); } // Basic validity is to check that every "opening" DType has a corresponding closing DType internal static bool IsValid (string strSig) { int structCount = 0; int dictCount = 0; foreach (char c in strSig) { switch ((DType)c) { case DType.StructBegin: structCount++; break; case DType.StructEnd: structCount--; break; case DType.DictEntryBegin: dictCount++; break; case DType.DictEntryEnd: dictCount--; break; } } return structCount == 0 && dictCount == 0; } internal static Signature Take (byte[] value) { Signature sig; if (value.Length == 0) { sig._data = Empty._data; return sig; } if (value.Length == 1) { sig._data = DataForDType ((DType)value[0]); return sig; } sig._data = value; return sig; } internal static byte[] DataForDType (DType value) { switch (value) { case DType.Byte: return ByteSig._data; case DType.Boolean: return BoolSig._data; case DType.Int16: return Int16Sig._data; case DType.UInt16: return UInt16Sig._data; case DType.Int32: return Int32Sig._data; case DType.UInt32: return UInt32Sig._data; case DType.Int64: return Int64Sig._data; case DType.UInt64: return UInt64Sig._data; case DType.Single: return SingleSig._data; case DType.Double: return DoubleSig._data; case DType.String: return StringSig._data; case DType.ObjectPath: return ObjectPathSig._data; case DType.Signature: return SignatureSig._data; case DType.Array: return ArraySig._data; case DType.Variant: return VariantSig._data; case DType.StructBegin: return StructBeginSig._data; case DType.StructEnd: return StructEndSig._data; case DType.DictEntryBegin: return DictEntryBeginSig._data; case DType.DictEntryEnd: return DictEntryEndSig._data; default: return new byte[] {(byte)value}; } } private static Signature Allocate (DType value) { Signature sig; sig._data = new byte[] {(byte)value}; return sig; } internal Signature (DType value) { this._data = DataForDType (value); } internal byte[] GetBuffer () { return _data; } internal DType this[int index] { get { return (DType)_data[index]; } } /// <summary> /// Length of the Signature. /// </summary> public int Length { get { return _data != null ? _data.Length : 0; } } internal string Value { get { if (_data == null) return String.Empty; return Encoding.ASCII.GetString (_data); } } /// <summary> /// Returns a string that represents the current object. /// </summary> public override string ToString () { return Value; } internal static Signature MakeArray (Signature signature) { if (!signature.IsSingleCompleteType) throw new ArgumentException ("The type of an array must be a single complete type", "signature"); return Concat(Signature.ArraySig, signature); } internal static Signature MakeStruct (Signature signature) { if (signature == Signature.Empty) throw new ArgumentException ("Cannot create a struct with no fields", "signature"); return Concat(Concat(Signature.StructBegin, signature), Signature.StructEnd); } internal static Signature MakeDictEntry (Signature keyType, Signature valueType) { if (!keyType.IsSingleCompleteType) throw new ArgumentException ("Signature must be a single complete type", "keyType"); if (!valueType.IsSingleCompleteType) throw new ArgumentException ("Signature must be a single complete type", "valueType"); return Concat(Concat(Concat(Signature.DictEntryBegin, keyType), valueType), Signature.DictEntryEnd); } internal static Signature MakeDict (Signature keyType, Signature valueType) { return MakeArray (MakeDictEntry (keyType, valueType)); } internal int Alignment { get { if (_data.Length == 0) return 0; return ProtocolInformation.GetAlignment (this[0]); } } internal int GetSize (DType dtype) { switch (dtype) { case DType.Byte: return 1; case DType.Boolean: return 4; case DType.Int16: case DType.UInt16: return 2; case DType.Int32: case DType.UInt32: case DType.UnixFd: return 4; case DType.Int64: case DType.UInt64: return 8; case DType.Single: return 4; case DType.Double: return 8; case DType.String: case DType.ObjectPath: case DType.Signature: case DType.Array: case DType.StructBegin: case DType.Variant: case DType.DictEntryBegin: return -1; case DType.Invalid: default: throw new ProtocolException("Cannot determine size of unknown D-Bus type: " + dtype); } } internal bool GetFixedSize (ref int size) { if (size < 0) return false; if (_data.Length == 0) return true; // Sensible? size = ProtocolInformation.Padded (size, Alignment); if (_data.Length == 1) { int valueSize = GetSize (this[0]); if (valueSize == -1) return false; size += valueSize; return true; } if (IsStructlike) { foreach (Signature sig in GetParts ()) if (!sig.GetFixedSize (ref size)) return false; return true; } if (IsArray || IsDict) return false; if (IsStruct) { foreach (Signature sig in GetFieldSignatures ()) if (!sig.GetFixedSize (ref size)) return false; return true; } // Any other cases? throw new Exception (); } internal bool IsSingleCompleteType { get { if (_data.Length == 0) return true; var checker = new SignatureChecker (_data); return checker.CheckSignature (); } } internal bool IsStruct { get { if (Length < 2) return false; if (this[0] != DType.StructBegin) return false; // FIXME: Incorrect! What if this is in fact a Structlike starting and finishing with structs? if (this[Length - 1] != DType.StructEnd) return false; return true; } } internal bool IsStructlike { get { if (Length < 2) return false; if (IsArray) return false; if (IsDict) return false; if (IsStruct) return false; return true; } } internal bool IsDict { get { if (Length < 3) return false; if (!IsArray) return false; // 0 is 'a' if (this[1] != DType.DictEntryBegin) return false; return true; } } internal bool IsArray { get { if (Length < 2) return false; if (this[0] != DType.Array) return false; return true; } } internal Type ToType () { int pos = 0; Type ret = ToType (ref pos); if (pos != _data.Length) throw new ProtocolException("Signature '" + Value + "' is not a single complete type"); return ret; } internal IEnumerable<Signature> GetFieldSignatures () { if (this == Signature.Empty || this[0] != DType.StructBegin) throw new ProtocolException("Not a struct"); for (int pos = 1 ; pos < _data.Length - 1 ;) yield return GetNextSignature (ref pos); } internal void GetDictEntrySignatures (out Signature sigKey, out Signature sigValue) { if (this == Signature.Empty || this[0] != DType.DictEntryBegin) throw new ProtocolException("Not a DictEntry"); int pos = 1; sigKey = GetNextSignature (ref pos); sigValue = GetNextSignature (ref pos); } internal IEnumerable<Signature> GetParts () { if (_data == null) yield break; for (int pos = 0 ; pos < _data.Length ;) { yield return GetNextSignature (ref pos); } } internal Signature GetNextSignature (ref int pos) { if (_data == null) return Signature.Empty; DType dtype = (DType)_data[pos++]; switch (dtype) { //case DType.Invalid: // return typeof (void); case DType.Array: //peek to see if this is in fact a dictionary if ((DType)_data[pos] == DType.DictEntryBegin) { //skip over the { pos++; Signature keyType = GetNextSignature (ref pos); Signature valueType = GetNextSignature (ref pos); //skip over the } pos++; return Signature.MakeDict (keyType, valueType); } else { Signature elementType = GetNextSignature (ref pos); return MakeArray (elementType); } //case DType.DictEntryBegin: // FIXME: DictEntries should be handled separately. case DType.StructBegin: //List<Signature> fieldTypes = new List<Signature> (); Signature fieldsSig = Signature.Empty; while ((DType)_data[pos] != DType.StructEnd) { fieldsSig = Concat(fieldsSig, GetNextSignature (ref pos)); } //skip over the ) pos++; return Signature.MakeStruct (fieldsSig); //return fieldsSig; case DType.DictEntryBegin: Signature sigKey = GetNextSignature (ref pos); Signature sigValue = GetNextSignature (ref pos); //skip over the } pos++; return Signature.MakeDictEntry (sigKey, sigValue); default: return new Signature (dtype); } } internal Type ToType (ref int pos) { if (_data == null) return typeof (void); DType dtype = (DType)_data[pos++]; switch (dtype) { case DType.Invalid: return typeof (void); case DType.Byte: return typeof (byte); case DType.Boolean: return typeof (bool); case DType.Int16: return typeof (short); case DType.UInt16: return typeof (ushort); case DType.Int32: return typeof (int); case DType.UInt32: return typeof (uint); case DType.Int64: return typeof (long); case DType.UInt64: return typeof (ulong); case DType.Single: ////not supported by libdbus at time of writing return typeof (float); case DType.Double: return typeof (double); case DType.String: return typeof (string); case DType.ObjectPath: return typeof (ObjectPath); case DType.Signature: return typeof (Signature); case DType.UnixFd: return typeof (CloseSafeHandle); case DType.Array: //peek to see if this is in fact a dictionary if ((DType)_data[pos] == DType.DictEntryBegin) { //skip over the { pos++; Type keyType = ToType (ref pos); Type valueType = ToType (ref pos); //skip over the } pos++; return typeof(IDictionary<,>).MakeGenericType (new [] { keyType, valueType}); } else { return ToType (ref pos).MakeArrayType (); } case DType.StructBegin: List<Type> innerTypes = new List<Type> (); while (((DType)_data[pos]) != DType.StructEnd) innerTypes.Add (ToType (ref pos)); // go over the struct end pos++; return TypeOfValueTupleOf(innerTypes.ToArray ()); case DType.DictEntryBegin: return typeof (System.Collections.Generic.KeyValuePair<,>); case DType.Variant: return typeof (object); default: throw new NotSupportedException ("Parsing or converting this signature is not yet supported (signature was '" + Value + "'), at DType." + dtype); } } internal static Signature GetSig (object[] objs) { return GetSig (objs.Select(o => o.GetType()).ToArray(), isCompileTimeType: true); } internal static Signature GetSig (Type[] types, bool isCompileTimeType) { if (types == null) throw new ArgumentNullException ("types"); Signature sig = Signature.Empty; foreach (Type type in types) { sig = Concat(sig, GetSig (type, isCompileTimeType)); } return sig; } internal static Signature GetSig (Type type, bool isCompileTimeType) { if (type == null) throw new ArgumentNullException ("type"); if (type.GetTypeInfo().IsEnum) { type = Enum.GetUnderlyingType(type); } if (type == typeof(bool)) { return BoolSig; } else if (type == typeof(byte)) { return ByteSig; } else if (type == typeof(double)) { return DoubleSig; } else if (type == typeof(short)) { return Int16Sig; } else if (type == typeof(int)) { return Int32Sig; } else if (type == typeof(long)) { return Int64Sig; } else if (type == typeof(ObjectPath)) { return ObjectPathSig; } else if (type == typeof(Signature)) { return SignatureSig; } else if (type == typeof(string)) { return StringSig; } else if (type == typeof(float)) { return SingleSig; } else if (type == typeof(ushort)) { return UInt16Sig; } else if (type == typeof(uint)) { return UInt32Sig; } else if (type == typeof(ulong)) { return UInt64Sig; } else if (type == typeof(object)) { return VariantSig; } else if (type == typeof(IDBusObject)) { return ObjectPathSig; } if (ArgTypeInspector.IsDBusObjectType(type, isCompileTimeType)) { return ObjectPathSig; } Type elementType; var enumerableType = ArgTypeInspector.InspectEnumerableType(type, out elementType, isCompileTimeType); if (enumerableType != ArgTypeInspector.EnumerableType.NotEnumerable) { if ((enumerableType == ArgTypeInspector.EnumerableType.EnumerableKeyValuePair) || (enumerableType == ArgTypeInspector.EnumerableType.GenericDictionary) || (enumerableType == ArgTypeInspector.EnumerableType.AttributeDictionary)) { Type keyType = elementType.GenericTypeArguments[0]; Type valueType = elementType.GenericTypeArguments[1]; return Signature.MakeDict(GetSig(keyType, isCompileTimeType: true), GetSig(valueType, isCompileTimeType: true)); } else // Enumerable { return MakeArray(GetSig(elementType, isCompileTimeType: true)); } } bool isValueTuple; if (ArgTypeInspector.IsStructType(type, out isValueTuple)) { Signature sig = Signature.Empty; var fields = ArgTypeInspector.GetStructFields(type, isValueTuple); for (int i = 0; i < fields.Length;) { var fi = fields[i]; if (i == 7 && isValueTuple) { fields = ArgTypeInspector.GetStructFields(fi.FieldType, isValueTuple); i = 0; } else { sig = Concat(sig, GetSig(fi.FieldType, isCompileTimeType: true)); i++; } } return Signature.MakeStruct(sig); } if (ArgTypeInspector.IsSafeHandleType(type)) { return Signature.SignatureUnixFd; } throw new ArgumentException($"Cannot (de)serialize Type '{type.FullName}'"); } private static Type TypeOfValueTupleOf(Type[] innerTypes) { if (innerTypes == null || innerTypes.Length == 0) throw new NotSupportedException($"ValueTuple of length {innerTypes?.Length} is not supported"); if (innerTypes.Length > 7) { innerTypes = new [] { innerTypes[0], innerTypes[1], innerTypes[2], innerTypes[3], innerTypes[4], innerTypes[5], innerTypes[6], TypeOfValueTupleOf(innerTypes.Skip(7).ToArray()) }; } Type structType = null; switch (innerTypes.Length) { case 1: structType = typeof(ValueTuple<>); break; case 2: structType = typeof(ValueTuple<,>); break; case 3: structType = typeof(ValueTuple<,,>); break; case 4: structType = typeof(ValueTuple<,,,>); break; case 5: structType = typeof(ValueTuple<,,,,>); break; case 6: structType = typeof(ValueTuple<,,,,,>); break; case 7: structType = typeof(ValueTuple<,,,,,,>); break; case 8: structType = typeof(ValueTuple<,,,,,,,>); break; } return structType.MakeGenericType(innerTypes); } class SignatureChecker { byte[] data; int pos; internal SignatureChecker (byte[] data) { this.data = data; } internal bool CheckSignature () { return SingleType () ? pos == data.Length : false; } bool SingleType () { if (pos >= data.Length) return false; //Console.WriteLine ((DType)data[pos]); switch ((DType)data[pos]) { // Simple Type case DType.Byte: case DType.Boolean: case DType.Int16: case DType.UInt16: case DType.Int32: case DType.UInt32: case DType.Int64: case DType.UInt64: case DType.Single: case DType.Double: case DType.String: case DType.ObjectPath: case DType.Signature: case DType.Variant: pos += 1; return true; case DType.Array: pos += 1; return ArrayType (); case DType.StructBegin: pos += 1; return StructType (); case DType.DictEntryBegin: pos += 1; return DictType (); } return false; } bool ArrayType () { return SingleType (); } bool DictType () { bool result = SingleType () && SingleType () && ((DType)data[pos]) == DType.DictEntryEnd; if (result) pos += 1; return result; } bool StructType () { if (pos >= data.Length) return false; while (((DType)data[pos]) != DType.StructEnd) { if (!SingleType ()) return false; if (pos >= data.Length) return false; } pos += 1; return true; } } } }
//------------------------------------------------------------------------------ // <copyright file="ClientRoleProvider.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.ClientServices.Providers { using System; using System.Web.Security; using System.Threading; using System.Security.Principal; using System.Data; using System.Data.OleDb; using System.IO; using System.Windows.Forms; using System.Collections.Specialized; using System.Net; using System.Web.ClientServices; using System.Web.Resources; using System.Configuration; using System.Globalization; using System.Collections; using System.Text; using System.Runtime.InteropServices; using System.Data.Common; using System.Security; using System.Security.Permissions; using System.Security.AccessControl; using System.Diagnostics.CodeAnalysis; public class ClientRoleProvider : RoleProvider { private string _ConnectionString = null; private string _ConnectionStringProvider = null; private string _ServiceUri = null; private string[] _Roles = null; private string _CurrentUser = null; private int _CacheTimeout = 1440; // 1 day in minutes private DateTime _CacheExpiryDate = DateTime.UtcNow; private bool _HonorCookieExpiry = false; private bool _UsingFileSystemStore = false; private bool _UsingIsolatedStore = false; private bool _UsingWFCService = false; ///////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// public override void Initialize(string name, NameValueCollection config) { if (config == null) throw new ArgumentNullException("config"); base.Initialize(name, config); ServiceUri = config["serviceUri"]; string temp = config["cacheTimeout"]; if (!string.IsNullOrEmpty(temp)) _CacheTimeout = int.Parse(temp, CultureInfo.InvariantCulture); _ConnectionString = config["connectionStringName"]; if (string.IsNullOrEmpty(_ConnectionString)) { _ConnectionString = SqlHelper.GetDefaultConnectionString(); } else { if (ConfigurationManager.ConnectionStrings[_ConnectionString] != null) { _ConnectionStringProvider = ConfigurationManager.ConnectionStrings[_ConnectionString].ProviderName; _ConnectionString = ConfigurationManager.ConnectionStrings[_ConnectionString].ConnectionString; } } switch(SqlHelper.IsSpecialConnectionString(_ConnectionString)) { case 1: _UsingFileSystemStore = true; break; case 2: _UsingIsolatedStore = true; break; default: break; } temp = config["honorCookieExpiry"]; if (!string.IsNullOrEmpty(temp)) _HonorCookieExpiry = (string.Compare(temp, "true", StringComparison.OrdinalIgnoreCase) == 0); config.Remove("name"); config.Remove("description"); config.Remove("cacheTimeout"); config.Remove("connectionStringName"); config.Remove("serviceUri"); config.Remove("honorCookieExpiry"); foreach (string attribUnrecognized in config.Keys) if (!String.IsNullOrEmpty(attribUnrecognized)) throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, AtlasWeb.AttributeNotRecognized, attribUnrecognized)); } ///////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// public override bool IsUserInRole(string username, string roleName) { string[] roles = GetRolesForUser(username); foreach (string role in roles) if (string.Compare(role, roleName, StringComparison.OrdinalIgnoreCase) == 0) return true; return false; } ///////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// public override string[] GetRolesForUser(string username) { lock (this) { IPrincipal p = Thread.CurrentPrincipal; if (p == null || p.Identity == null || !p.Identity.IsAuthenticated) return new string[0]; if (!string.IsNullOrEmpty(username) && string.Compare(username, p.Identity.Name, StringComparison.OrdinalIgnoreCase) != 0) throw new ArgumentException(AtlasWeb.ArgumentMustBeCurrentUser, "username"); // Serve from memory cache if it is for the last-user, and the roles are fresh if (string.Compare(_CurrentUser, p.Identity.Name, StringComparison.OrdinalIgnoreCase) == 0 && DateTime.UtcNow < _CacheExpiryDate) return _Roles; // Fetch from database, cache it, and serve it if (GetRolesFromDBForUser(p.Identity.Name)) // Return true, only if the roles are fresh. Also, sets _CurrentUser, _Roles and _CacheExpiryDate return _Roles; if (ConnectivityStatus.IsOffline) return new string[0]; // Reset variables _Roles = null; _CacheExpiryDate = DateTime.UtcNow; _CurrentUser = p.Identity.Name; GetRolesForUserCore(p.Identity); if (!_HonorCookieExpiry && _Roles.Length < 1 && (p.Identity is ClientFormsIdentity)) { ((ClientFormsIdentity)p.Identity).RevalidateUser(); GetRolesForUserCore(p.Identity); } StoreRolesForCurrentUser(); return _Roles; } } ///////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// public void ResetCache() { lock (this){ _Roles = null; _CacheExpiryDate = DateTime.UtcNow; RemoveRolesFromDB(); } } ///////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// // Private methods [SuppressMessage("Microsoft.Security", "CA2116:AptcaMethodsShouldOnlyCallAptcaMethods", Justification="Reviewed and approved by feature crew")] private void GetRolesForUserCore(IIdentity identity) { // (new PermissionSet(PermissionState.Unrestricted)).Assert(); // CookieContainer cookies = null; if (identity is ClientFormsIdentity) cookies = ((ClientFormsIdentity)identity).AuthenticationCookies; if (_UsingWFCService) { throw new NotImplementedException(); // CustomBinding binding = ProxyHelper.GetBinding(); // ChannelFactory<RolesService> channelFactory = new ChannelFactory<RolesService>(binding, new EndpointAddress(GetServiceUri())); //(@"http://localhost/AuthSvc/service.svc")); // RolesService clientService = channelFactory.CreateChannel(); // using (new OperationContextScope((IContextChannel)clientService)) { // ProxyHelper.AddCookiesToWCF(cookies, GetServiceUri(), _CurrentUser, _ConnectionString, _ConnectionStringProvider); // _Roles = clientService.GetRolesForCurrentUser(); // if (_Roles == null) // _Roles = new string[0]; // ProxyHelper.GetCookiesFromWCF(cookies, GetServiceUri(), _CurrentUser, _ConnectionString, _ConnectionStringProvider); // } } else { object o = ProxyHelper.CreateWebRequestAndGetResponse(GetServiceUri() + "/GetRolesForCurrentUser", ref cookies, identity.Name, _ConnectionString, _ConnectionStringProvider, null, null, typeof(string [])); if (o != null) _Roles = (string []) o; else _Roles = new string[0]; } _CacheExpiryDate = DateTime.UtcNow.AddMinutes(_CacheTimeout); } ///////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// private void RemoveRolesFromDB() { // if (MustAssertForSql) // (new PermissionSet(PermissionState.Unrestricted)).Assert(); if (string.IsNullOrEmpty(_CurrentUser)) return; if (_UsingFileSystemStore || _UsingIsolatedStore) { ClientData cd = ClientDataManager.GetUserClientData(_CurrentUser, _UsingIsolatedStore); cd.Roles = null; cd.Save(); return; } using (DbConnection conn = SqlHelper.GetConnection(_CurrentUser, _ConnectionString, _ConnectionStringProvider)) { DbTransaction trans = null; try { trans = conn.BeginTransaction(); DbCommand cmd = conn.CreateCommand(); cmd.CommandText = "DELETE FROM Roles WHERE UserName = @UserName"; SqlHelper.AddParameter(conn, cmd, "@UserName", _CurrentUser); cmd.Transaction = trans; cmd.ExecuteNonQuery(); cmd = conn.CreateCommand(); cmd.CommandText = "DELETE FROM UserProperties WHERE PropertyName = @RolesCachedDate"; SqlHelper.AddParameter(conn, cmd, "@RolesCachedDate", "RolesCachedDate_" + _CurrentUser); cmd.Transaction = trans; cmd.ExecuteNonQuery(); } catch { if (trans != null) { trans.Rollback(); trans = null; } throw; } finally { if (trans != null) trans.Commit(); } } } ///////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// private void StoreRolesForCurrentUser() { if (_UsingFileSystemStore || _UsingIsolatedStore) { ClientData cd = ClientDataManager.GetUserClientData(_CurrentUser, _UsingIsolatedStore); cd.Roles = _Roles; cd.RolesCachedDateUtc = DateTime.UtcNow; cd.Save(); return; } // if (MustAssertForSql) // (new PermissionSet(PermissionState.Unrestricted)).Assert(); RemoveRolesFromDB(); // Remove all old roles DbTransaction trans = null; using (DbConnection conn = SqlHelper.GetConnection(_CurrentUser, _ConnectionString, _ConnectionStringProvider)) { try { trans = conn.BeginTransaction(); // Add the roles DbCommand cmd = null; foreach(string role in _Roles) { cmd = conn.CreateCommand(); cmd.CommandText = "INSERT INTO Roles(UserName, RoleName) VALUES(@UserName, @RoleName)"; SqlHelper.AddParameter(conn, cmd, "@UserName", _CurrentUser); SqlHelper.AddParameter(conn, cmd, "@RoleName", role); cmd.Transaction = trans; cmd.ExecuteNonQuery(); } cmd = conn.CreateCommand(); cmd.CommandText = "INSERT INTO UserProperties (PropertyName, PropertyValue) VALUES(@RolesCachedDate, @Date)"; SqlHelper.AddParameter(conn, cmd, "@RolesCachedDate", "RolesCachedDate_" + _CurrentUser); SqlHelper.AddParameter(conn, cmd, "@Date", DateTime.UtcNow.ToFileTimeUtc().ToString(CultureInfo.InvariantCulture)); cmd.Transaction = trans; cmd.ExecuteNonQuery(); } catch { if (trans != null) { trans.Rollback(); trans = null; } throw; } finally { if (trans != null) trans.Commit(); } } } ///////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// private bool GetRolesFromDBForUser(string username) { _Roles = null; _CacheExpiryDate = DateTime.UtcNow; _CurrentUser = username; // if (MustAssertForSql) // (new PermissionSet(PermissionState.Unrestricted)).Assert(); if (_UsingFileSystemStore || _UsingIsolatedStore) { ClientData cd = ClientDataManager.GetUserClientData(username, _UsingIsolatedStore); if (cd.Roles == null) return false; _Roles = cd.Roles; _CacheExpiryDate = cd.RolesCachedDateUtc.AddMinutes(_CacheTimeout); if (!ConnectivityStatus.IsOffline && _CacheExpiryDate < DateTime.UtcNow) // expired roles return false; return true; } using (DbConnection conn = SqlHelper.GetConnection(_CurrentUser, _ConnectionString, _ConnectionStringProvider)) { DbTransaction trans = null; try { trans = conn.BeginTransaction(); DbCommand cmd = conn.CreateCommand(); cmd.Transaction = trans; cmd.CommandText = "SELECT PropertyValue FROM UserProperties WHERE PropertyName = @RolesCachedDate"; SqlHelper.AddParameter(conn, cmd, "@RolesCachedDate", "RolesCachedDate_" + _CurrentUser); string date = cmd.ExecuteScalar() as string; if (date == null) // not cached return false; long filetime = long.Parse(date, CultureInfo.InvariantCulture); _CacheExpiryDate = DateTime.FromFileTimeUtc(filetime).AddMinutes(_CacheTimeout); if (!ConnectivityStatus.IsOffline && _CacheExpiryDate < DateTime.UtcNow) // expired roles return false; cmd = conn.CreateCommand(); cmd.Transaction = trans; cmd.CommandText = "SELECT RoleName FROM Roles WHERE UserName = @UserName ORDER BY RoleName"; SqlHelper.AddParameter(conn, cmd, "@UserName", _CurrentUser); ArrayList al = new ArrayList(); using (DbDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) al.Add(reader.GetString(0)); } _Roles = new string[al.Count]; for (int iter = 0; iter < al.Count; iter++) _Roles[iter] = (string)al[iter]; return true; } catch { if (trans != null) { trans.Rollback(); trans = null; } throw; } finally { if (trans != null) trans.Commit(); } } } ///////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// private string GetServiceUri() { if (string.IsNullOrEmpty(_ServiceUri)) throw new ArgumentException(AtlasWeb.ServiceUriNotFound); return _ServiceUri; } [SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings", Justification = "Reviewed and approved by feature crew")] public string ServiceUri { [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "2#", Justification = "Reviewed and approved by feature crew")] get { return _ServiceUri; } [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "2#", Justification = "Reviewed and approved by feature crew")] set { _ServiceUri = value; if (string.IsNullOrEmpty(_ServiceUri)) { _UsingWFCService = false; } else { _UsingWFCService = _ServiceUri.EndsWith(".svc", StringComparison.OrdinalIgnoreCase); } } } ///////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// // private bool _MustAssertForSqlDecided = false; // private bool _MustAssertForSql = false; // private bool MustAssertForSql { // get { // if (!_MustAssertForSqlDecided) { // _MustAssertForSql = (_ConnectionString == "Data Source = |SQL\\CE|"); // _MustAssertForSqlDecided = true; // } // return _MustAssertForSql; // } // } public override string ApplicationName { get { return ""; } set { } } public override void CreateRole(string roleName) { throw new NotSupportedException(); } public override bool DeleteRole(string roleName, bool throwOnPopulatedRole) { throw new NotSupportedException(); } public override bool RoleExists(string roleName) { throw new NotSupportedException(); } public override void AddUsersToRoles(string[] usernames, string[] roleNames) { throw new NotSupportedException(); } public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames) { throw new NotSupportedException(); } public override string[] GetUsersInRole(string roleName) { throw new NotSupportedException(); } public override string[] GetAllRoles() { throw new NotSupportedException(); } public override string[] FindUsersInRole(string roleName, string usernameToMatch) { throw new NotSupportedException(); } } }
/* * ****************************************************************************** * Copyright 2014-2017 Spectra Logic Corporation. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * **************************************************************************** */ // This code is auto-generated, do not modify using Ds3.Models; using System; using System.Net; namespace Ds3.Calls { public class GetSuspectBlobTapesSpectraS3Request : Ds3Request { private string _blobId; public string BlobId { get { return _blobId; } set { WithBlobId(value); } } private bool? _lastPage; public bool? LastPage { get { return _lastPage; } set { WithLastPage(value); } } private int? _pageLength; public int? PageLength { get { return _pageLength; } set { WithPageLength(value); } } private int? _pageOffset; public int? PageOffset { get { return _pageOffset; } set { WithPageOffset(value); } } private string _pageStartMarker; public string PageStartMarker { get { return _pageStartMarker; } set { WithPageStartMarker(value); } } private string _tapeId; public string TapeId { get { return _tapeId; } set { WithTapeId(value); } } public GetSuspectBlobTapesSpectraS3Request WithBlobId(Guid? blobId) { this._blobId = blobId.ToString(); if (blobId != null) { this.QueryParams.Add("blob_id", blobId.ToString()); } else { this.QueryParams.Remove("blob_id"); } return this; } public GetSuspectBlobTapesSpectraS3Request WithBlobId(string blobId) { this._blobId = blobId; if (blobId != null) { this.QueryParams.Add("blob_id", blobId); } else { this.QueryParams.Remove("blob_id"); } return this; } public GetSuspectBlobTapesSpectraS3Request WithLastPage(bool? lastPage) { this._lastPage = lastPage; if (lastPage != null) { this.QueryParams.Add("last_page", lastPage.ToString()); } else { this.QueryParams.Remove("last_page"); } return this; } public GetSuspectBlobTapesSpectraS3Request WithPageLength(int? pageLength) { this._pageLength = pageLength; if (pageLength != null) { this.QueryParams.Add("page_length", pageLength.ToString()); } else { this.QueryParams.Remove("page_length"); } return this; } public GetSuspectBlobTapesSpectraS3Request WithPageOffset(int? pageOffset) { this._pageOffset = pageOffset; if (pageOffset != null) { this.QueryParams.Add("page_offset", pageOffset.ToString()); } else { this.QueryParams.Remove("page_offset"); } return this; } public GetSuspectBlobTapesSpectraS3Request WithPageStartMarker(Guid? pageStartMarker) { this._pageStartMarker = pageStartMarker.ToString(); if (pageStartMarker != null) { this.QueryParams.Add("page_start_marker", pageStartMarker.ToString()); } else { this.QueryParams.Remove("page_start_marker"); } return this; } public GetSuspectBlobTapesSpectraS3Request WithPageStartMarker(string pageStartMarker) { this._pageStartMarker = pageStartMarker; if (pageStartMarker != null) { this.QueryParams.Add("page_start_marker", pageStartMarker); } else { this.QueryParams.Remove("page_start_marker"); } return this; } public GetSuspectBlobTapesSpectraS3Request WithTapeId(Guid? tapeId) { this._tapeId = tapeId.ToString(); if (tapeId != null) { this.QueryParams.Add("tape_id", tapeId.ToString()); } else { this.QueryParams.Remove("tape_id"); } return this; } public GetSuspectBlobTapesSpectraS3Request WithTapeId(string tapeId) { this._tapeId = tapeId; if (tapeId != null) { this.QueryParams.Add("tape_id", tapeId); } else { this.QueryParams.Remove("tape_id"); } return this; } public GetSuspectBlobTapesSpectraS3Request() { } internal override HttpVerb Verb { get { return HttpVerb.GET; } } internal override string Path { get { return "/_rest_/suspect_blob_tape"; } } } }
#region License // Copyright (c) K2 Workflow (SourceCode Technology Holdings Inc.). All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. #endregion using System; using System.Buffers; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Runtime.CompilerServices; using System.Security; using System.Security.Cryptography; using System.Text; using System.Threading; namespace SourceCode.Chasm { /// <summary> /// Represents a <see cref="Sha1"/> value. /// </summary> /// <seealso cref="SHA1" /> /// <seealso cref="System.IEquatable{T}" /> /// <seealso cref="System.IComparable{T}" /> [DebuggerDisplay("{ToString(\"D\"),nq,ac}")] public struct Sha1 : IEquatable<Sha1>, IComparable<Sha1> { #region Constants // Use a thread-local instance of the underlying crypto algorithm. private static readonly ThreadLocal<SHA1> _sha1 = new ThreadLocal<SHA1>(SHA1.Create); /// <summary> /// The fixed byte length of a <see cref="Sha1"/> value. /// </summary> public const byte ByteLen = 20; /// <summary> /// The number of hex characters required to represent a <see cref="Sha1"/> value. /// </summary> public const byte CharLen = ByteLen * 2; /// <summary> /// A singleton representing an empty <see cref="Sha1"/> value. /// </summary> /// <value> /// The empty. /// </value> public static Sha1 Empty { get; } // 40 #endregion #region Properties // We choose to use value types for primary storage so that we can live on the stack // Using byte[] or String means a dereference to the heap (& fixed byte would require unsafe) public ulong Blit0 { get; } public ulong Blit1 { get; } public uint Blit2 { get; } /// <summary> /// Returns a <see cref="Memory{T}"/> from the <see cref="Sha1"/>. /// </summary> public Memory<byte> Memory { get { var buffer = new byte[ByteLen]; unsafe { fixed (byte* ptr = buffer) { // Code is valid per BitConverter.ToInt32|64 (see #1 elsewhere in this class) *(ulong*)(&ptr[0 + 0]) = Blit0; *(ulong*)(&ptr[0 + 8]) = Blit1; *(uint*)(&ptr[0 + 16]) = Blit2; } } var mem = new Memory<byte>(buffer); return mem; } } #endregion #region De/Constructors /// <summary> /// Deserializes a <see cref="Sha1"/> value from the provided blits. /// </summary> /// <param name="blit0">The blit0.</param> /// <param name="blit1">The blit1.</param> /// <param name="blit2">The blit2.</param> public Sha1(ulong blit0, ulong blit1, uint blit2) { Blit0 = blit0; Blit1 = blit1; Blit2 = blit2; } /// <summary> /// Deserializes a <see cref="Sha1"/> value from the provided <see cref="Byte[]"/> starting at the specified position. /// </summary> /// <param name="buffer">The buffer.</param> /// <param name="offset">The offset.</param> /// <exception cref="ArgumentNullException">buffer</exception> /// <exception cref="ArgumentOutOfRangeException"> /// buffer - buffer /// or /// offset - buffer /// </exception> [SecuritySafeCritical] public Sha1(byte[] buffer, int offset) { if (buffer == null) throw new ArgumentNullException(nameof(buffer)); if (buffer.Length < ByteLen) throw new ArgumentOutOfRangeException(nameof(buffer), $"{nameof(buffer)} must have length at least {ByteLen}"); if (offset < 0 || offset + ByteLen > buffer.Length) throw new ArgumentOutOfRangeException(nameof(offset), $"{nameof(buffer)} must have length at least {ByteLen}"); unsafe { fixed (byte* ptr = buffer) { // Code is valid per BitConverter.ToInt32|64 (see #1 elsewhere in this class) Blit0 = *(ulong*)(&ptr[offset + 0]); Blit1 = *(ulong*)(&ptr[offset + 8]); Blit2 = *(uint*)(&ptr[offset + 16]); } } } /// <summary> /// Deserializes a <see cref="Sha1"/> value from the provided <see cref="ReadOnlyMemory{T}"/>. /// </summary> /// <param name="span">The buffer.</param> /// <exception cref="ArgumentOutOfRangeException">buffer - buffer</exception> [SecuritySafeCritical] public Sha1(ReadOnlySpan<byte> span) { if (span.IsEmpty || span.Length < ByteLen) throw new ArgumentOutOfRangeException(nameof(span), $"{nameof(span)} must have length at least {ByteLen}"); unsafe { fixed (byte* ptr = &span.DangerousGetPinnableReference()) { // Code is valid per BitConverter.ToInt32|64 (see #1 elsewhere in this class) Blit0 = *(ulong*)(&ptr[0]); Blit1 = *(ulong*)(&ptr[8]); Blit2 = *(uint*)(&ptr[16]); } } } /// <summary> /// Deconstructs the specified <see cref="Sha1"/>. /// </summary> /// <param name="blit0">The blit0.</param> /// <param name="blit1">The blit1.</param> /// <param name="blit2">The blit2.</param> public void Deconstruct(out ulong blit0, out ulong blit1, out uint blit2) { blit0 = Blit0; blit1 = Blit1; blit2 = Blit2; } #endregion #region Factory /// <summary> /// Hashes the specified value using utf8 encoding. /// </summary> /// <param name="value">The string to hash.</param> /// <returns></returns> public static Sha1 Hash(string value) { if (value == null) return Empty; // Note that length=0 should not short-circuit // Rent buffer var maxLen = Encoding.UTF8.GetMaxByteCount(value.Length); // Utf8 is 1-4 bpc var rented = ArrayPool<byte>.Shared.Rent(maxLen); var count = Encoding.UTF8.GetBytes(value, 0, value.Length, rented, 0); var hash = _sha1.Value.ComputeHash(rented, 0, count); var sha1 = new Sha1(hash); // Return buffer ArrayPool<byte>.Shared.Return(rented); return sha1; } /// <summary> /// Hashes the specified bytes. /// </summary> /// <param name="bytes">The bytes to hash.</param> /// <returns></returns> public static Sha1 Hash(byte[] bytes) { if (bytes == null) return Empty; // Note that length=0 should not short-circuit var hash = _sha1.Value.ComputeHash(bytes); var sha1 = new Sha1(hash); return sha1; } /// <summary> /// Hashes the specified bytes, starting at the specified offset and count. /// </summary> /// <param name="bytes">The bytes to hash.</param> /// <param name="offset">The offset.</param> /// <param name="count">The count.</param> /// <returns></returns> public static Sha1 Hash(byte[] bytes, int offset, int count) { if (bytes == null) return Empty; // Note that length=0 should not short-circuit if (count < 0) throw new ArgumentOutOfRangeException(nameof(count)); if (offset < 0 || offset + count > bytes.Length) throw new ArgumentOutOfRangeException(nameof(offset)); var hash = _sha1.Value.ComputeHash(bytes, offset, count); var sha1 = new Sha1(hash); return sha1; } /// <summary> /// Hashes the specified bytes. /// </summary> /// <param name="bytes">The bytes to hash.</param> /// <returns></returns> public static Sha1 Hash(ArraySegment<byte> bytes) { if (bytes.Array == null) return Empty; // Note that length=0 should not short-circuit var hash = _sha1.Value.ComputeHash(bytes.Array, bytes.Offset, bytes.Count); var sha1 = new Sha1(hash); return sha1; } /// <summary> /// Hashes the specified stream. /// </summary> /// <param name="stream">The stream to hash.</param> /// <returns></returns> public static Sha1 Hash(Stream stream) { if (stream == null) return Empty; // Note that length=0 should not short-circuit var hash = _sha1.Value.ComputeHash(stream); var sha1 = new Sha1(hash); return sha1; } #endregion #region Methods /// <summary> /// Copies the <see cref="Sha1"/> value to the provided buffer. /// </summary> /// <param name="buffer">The buffer to copy to.</param> /// <param name="offset">The offset.</param> /// <returns></returns> /// <exception cref="ArgumentNullException">buffer</exception> /// <exception cref="ArgumentOutOfRangeException">offset - buffer</exception> [SecuritySafeCritical] public int CopyTo(byte[] buffer, int offset) { if (buffer == null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0 || checked(offset + ByteLen) > buffer.Length) throw new ArgumentOutOfRangeException(nameof(offset), $"{nameof(buffer)} must have length at least {ByteLen}"); unsafe { fixed (byte* ptr = buffer) { // Code is valid per BitConverter.ToInt32|64 (see #1 elsewhere in this class) *(ulong*)(&ptr[offset + 0]) = Blit0; *(ulong*)(&ptr[offset + 8]) = Blit1; *(uint*)(&ptr[offset + 16]) = Blit2; } } return ByteLen; } #endregion #region ToString private const char FormatN = (char)0; [SecuritySafeCritical] private char[] ToChars(char separator) { Debug.Assert(separator == FormatN || separator == '-' || separator == ' '); var sep = 0; char[] chars; // Text is treated as 5 groups of 8 chars (4 bytes); 4 separators optional if (separator == FormatN) { chars = new char[CharLen]; } else { sep = 8; chars = new char[CharLen + 4]; } unsafe { var bytes = stackalloc byte[ByteLen]; // TODO: https://github.com/dotnet/corefx/pull/24212 { // Code is valid per BitConverter.ToInt32|64 (see #1 elsewhere in this class) *(ulong*)(&bytes[0]) = Blit0; *(ulong*)(&bytes[8]) = Blit1; *(uint*)(&bytes[16]) = Blit2; } var pos = 0; for (var i = 0; i < ByteLen; i++) // 20 { // Each byte is two hexits (convention is lowercase) var b = bytes[i] >> 4; // == b / 16 chars[pos++] = (char)(b < 10 ? b + '0' : b - 10 + 'a'); b = bytes[i] - (b << 4); // == b % 16 chars[pos++] = (char)(b < 10 ? b + '0' : b - 10 + 'a'); // Append a separator if required if (pos == sep) // pos >= 2, sep = 0|N { chars[pos++] = separator; sep = pos + 8; if (sep >= chars.Length) sep = 0; } } } return chars; } /// <summary> /// Returns a string representation of the <see cref="Sha1"/> instance using the 'N' format. /// </summary> /// <returns></returns> public override string ToString() { var chars = ToChars(FormatN); return new string(chars); } /// <summary> /// Returns a string representation of the <see cref="Sha1"/> instance. /// N: a9993e364706816aba3e25717850c26c9cd0d89d, /// D: a9993e36-4706816a-ba3e2571-7850c26c-9cd0d89d, /// S: a9993e36 4706816a ba3e2571 7850c26c 9cd0d89d /// </summary> /// <param name="format"></param> /// <returns></returns> public string ToString(string format) { if (string.IsNullOrWhiteSpace(format)) throw new FormatException($"Empty format specification"); if (format.Length != 1) throw new FormatException($"Invalid format specification length {format.Length}"); switch (format[0]) { // a9993e364706816aba3e25717850c26c9cd0d89d case 'n': case 'N': { var chars = ToChars(FormatN); return new string(chars); } // a9993e36-4706816a-ba3e2571-7850c26c-9cd0d89d case 'd': case 'D': { var chars = ToChars('-'); return new string(chars); } // a9993e36 4706816a ba3e2571 7850c26c 9cd0d89d case 's': case 'S': { var chars = ToChars(' '); return new string(chars); } } throw new FormatException($"Invalid format specification '{format}'"); } /// <summary> /// Converts the <see cref="Sha1"/> instance to a string using the 'N' format, /// and returns the value split into two tokens. /// </summary> /// <param name="prefixLength">The length of the first token.</param> /// <returns></returns> public KeyValuePair<string, string> Split(int prefixLength) { var chars = ToChars(FormatN); if (prefixLength <= 0) return new KeyValuePair<string, string>(string.Empty, new string(chars)); if (prefixLength >= CharLen) return new KeyValuePair<string, string>(new string(chars), string.Empty); var key = new string(chars, 0, prefixLength); var val = new string(chars, prefixLength, chars.Length - prefixLength); var kvp = new KeyValuePair<string, string>(key, val); return kvp; } #endregion #region Parse // Sentinel value for n/a (128) private const byte __ = 0b1000_0000; // '0'=48, '9'=57 // 'A'=65, 'F'=70 // 'a'=97, 'f'=102 private static readonly byte[] Hexits = new byte['f' - '0' + 1] // 102 - 48 + 1 = 55 { 00, 01, 02, 03, 04, 05, 06, 07, 08, 09, // [00-09] = 48..57 = '0'..'9' __, __, __, __, __, __, __, 10, 11, 12, // [10-16,17-19] = 65..67 = 'A'..'C' 13, 14, 15, __, __, __, __, __, __, __, // [20-22,23-29] = 68..70 = 'D'..'F' __, __, __, __, __, __, __, __, __, __, // [30-39] __, __, __, __, __, __, __, __, __, 10, // [40-48,49] = 97..97 = 'a' 11, 12, 13, 14, 15 // [50-54] = 98..102= 'b'..'f' }; [SecuritySafeCritical] private static bool TryParseImpl(string hex, int startIndex, out Sha1 value) { Debug.Assert(hex != null); Debug.Assert(startIndex >= 0); Debug.Assert(hex.Length >= CharLen + startIndex); value = Empty; unsafe { var bytes = stackalloc byte[ByteLen]; // TODO: https://github.com/dotnet/corefx/pull/24212 // Text is treated as 5 groups of 8 chars (4 bytes); 4 separators optional // "34aa973c-d4c4daa4-f61eeb2b-dbad2731-6534016f" var pos = startIndex; for (var i = 0; i < 5; i++) { for (var j = 0; j < 4; j++) { // Two hexits per byte: aaaa bbbb if (!TryParseHexit(hex[pos++], out byte h1) || !TryParseHexit(hex[pos++], out byte h2)) return false; bytes[i * 4 + j] = (byte)((h1 << 4) | h2); } if (pos < CharLen && (hex[pos] == '-' || hex[pos] == ' ')) pos++; } // If the string is not fully consumed, it had an invalid length if (pos != hex.Length) return false; // Code is valid per BitConverter.ToInt32|64 (see #1 elsewhere in this class) var blit0 = *(ulong*)(&bytes[0]); var blit1 = *(ulong*)(&bytes[8]); var blit2 = *(uint*)(&bytes[16]); value = new Sha1(blit0, blit1, blit2); return true; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool TryParseHexit(char c, out byte b) { b = 0; if (c < '0' || c > 'f') return false; var bex = Hexits[c - '0']; if (bex == __) // Sentinel value for n/a (128) return false; b = bex; return true; } /// <summary> /// Parses the specified hexadecimal. /// </summary> /// <param name="hex">The hexadecimal.</param> /// <returns></returns> /// <exception cref="FormatException">Sha1</exception> public static Sha1 Parse(string hex) { if (!TryParse(hex, out Sha1 sha1)) throw new FormatException($"String was not recognized as a valid {nameof(Sha1)}"); return sha1; } /// <summary> /// Tries to parse the specified hexadecimal. /// </summary> /// <param name="hex">The hexadecimal.</param> /// <param name="value">The value.</param> /// <returns></returns> public static bool TryParse(string hex, out Sha1 value) { value = Empty; // Length must be at least 40 if (hex == null || hex.Length < CharLen) return false; var startIndex = 0; // Check if the hex specifier '0x' is present if (hex[0] == '0' && (hex[1] == 'x' || hex[1] == 'X')) { // Length must be at least 42 if (hex.Length < 2 + CharLen) return false; // Skip '0x' startIndex = 2; } if (!TryParseImpl(hex, startIndex, out Sha1 sha1)) return false; value = sha1; return true; } #endregion #region IEquatable public bool Equals(Sha1 other) => Sha1Comparer.Default.Equals(this, other); public override bool Equals(object obj) => obj is Sha1 sha1 && Sha1Comparer.Default.Equals(this, sha1); public override int GetHashCode() => Sha1Comparer.Default.GetHashCode(this); #endregion #region IComparable public int CompareTo(Sha1 other) => Sha1Comparer.Default.Compare(this, other); #endregion #region Operators public static bool operator ==(Sha1 x, Sha1 y) => Sha1Comparer.Default.Equals(x, y); public static bool operator !=(Sha1 x, Sha1 y) => !(x == y); public static bool operator >=(Sha1 x, Sha1 y) => Sha1Comparer.Default.Compare(x, y) >= 0; public static bool operator >(Sha1 x, Sha1 y) => Sha1Comparer.Default.Compare(x, y) > 0; public static bool operator <=(Sha1 x, Sha1 y) => Sha1Comparer.Default.Compare(x, y) <= 0; public static bool operator <(Sha1 x, Sha1 y) => Sha1Comparer.Default.Compare(x, y) < 0; #endregion } }
/*- * Automatically built by dist/s_java_csharp. * * See the file LICENSE for redistribution information. * * Copyright (c) 2002, 2013 Oracle and/or its affiliates. All rights reserved. */ using System; using System.Runtime.InteropServices; namespace BerkeleyDB.Internal { [StructLayout(LayoutKind.Sequential)] internal struct BTreeStatStruct { internal uint bt_magic; internal uint bt_version; internal uint bt_metaflags; internal uint bt_nkeys; internal uint bt_ndata; internal uint bt_pagecnt; internal uint bt_pagesize; internal uint bt_minkey; internal uint bt_re_len; internal uint bt_re_pad; internal uint bt_levels; internal uint bt_int_pg; internal uint bt_leaf_pg; internal uint bt_dup_pg; internal uint bt_over_pg; internal uint bt_empty_pg; internal uint bt_free; internal ulong bt_int_pgfree; internal ulong bt_leaf_pgfree; internal ulong bt_dup_pgfree; internal ulong bt_over_pgfree; } [StructLayout(LayoutKind.Sequential)] internal struct HashStatStruct { internal uint hash_magic; internal uint hash_version; internal uint hash_metaflags; internal uint hash_nkeys; internal uint hash_ndata; internal uint hash_pagecnt; internal uint hash_pagesize; internal uint hash_ffactor; internal uint hash_buckets; internal uint hash_free; internal ulong hash_bfree; internal uint hash_bigpages; internal ulong hash_big_bfree; internal uint hash_overflows; internal ulong hash_ovfl_free; internal uint hash_dup; internal ulong hash_dup_free; } [StructLayout(LayoutKind.Sequential)] internal struct HeapStatStruct { internal uint heap_magic; internal uint heap_version; internal uint heap_metaflags; internal uint heap_nrecs; internal uint heap_pagecnt; internal uint heap_pagesize; internal uint heap_nregions; internal uint heap_regionsize; } [StructLayout(LayoutKind.Sequential)] internal struct LockStatStruct { internal uint st_id; internal uint st_cur_maxid; internal uint st_initlocks; internal uint st_initlockers; internal uint st_initobjects; internal uint st_locks; internal uint st_lockers; internal uint st_objects; internal uint st_maxlocks; internal uint st_maxlockers; internal uint st_maxobjects; internal uint st_partitions; internal uint st_tablesize; internal int st_nmodes; internal uint st_nlockers; internal uint st_nlocks; internal uint st_maxnlocks; internal uint st_maxhlocks; internal ulong st_locksteals; internal ulong st_maxlsteals; internal uint st_maxnlockers; internal uint st_nobjects; internal uint st_maxnobjects; internal uint st_maxhobjects; internal ulong st_objectsteals; internal ulong st_maxosteals; internal ulong st_nrequests; internal ulong st_nreleases; internal ulong st_nupgrade; internal ulong st_ndowngrade; internal ulong st_lock_wait; internal ulong st_lock_nowait; internal ulong st_ndeadlocks; internal uint st_locktimeout; internal ulong st_nlocktimeouts; internal uint st_txntimeout; internal ulong st_ntxntimeouts; internal ulong st_part_wait; internal ulong st_part_nowait; internal ulong st_part_max_wait; internal ulong st_part_max_nowait; internal ulong st_objs_wait; internal ulong st_objs_nowait; internal ulong st_lockers_wait; internal ulong st_lockers_nowait; internal ulong st_region_wait; internal ulong st_region_nowait; internal uint st_hash_len; internal IntPtr st_regsize; } [StructLayout(LayoutKind.Sequential)] internal struct LogStatStruct { internal uint st_magic; internal uint st_version; internal int st_mode; internal uint st_lg_bsize; internal uint st_lg_size; internal uint st_wc_bytes; internal uint st_wc_mbytes; internal uint st_fileid_init; internal uint st_nfileid; internal uint st_maxnfileid; internal ulong st_record; internal uint st_w_bytes; internal uint st_w_mbytes; internal ulong st_wcount; internal ulong st_wcount_fill; internal ulong st_rcount; internal ulong st_scount; internal ulong st_region_wait; internal ulong st_region_nowait; internal uint st_cur_file; internal uint st_cur_offset; internal uint st_disk_file; internal uint st_disk_offset; internal uint st_maxcommitperflush; internal uint st_mincommitperflush; internal IntPtr st_regsize; } [StructLayout(LayoutKind.Sequential)] internal struct MPoolFileStatStruct { internal uint st_pagesize; internal uint st_map; internal ulong st_cache_hit; internal ulong st_cache_miss; internal ulong st_page_create; internal ulong st_page_in; internal ulong st_page_out; internal ulong st_backup_spins; internal string file_name; } [StructLayout(LayoutKind.Sequential)] internal struct MPoolStatStruct { internal uint st_gbytes; internal uint st_bytes; internal uint st_ncache; internal uint st_max_ncache; internal IntPtr st_mmapsize; internal int st_maxopenfd; internal int st_maxwrite; internal uint st_maxwrite_sleep; internal uint st_pages; internal uint st_map; internal ulong st_cache_hit; internal ulong st_cache_miss; internal ulong st_page_create; internal ulong st_page_in; internal ulong st_page_out; internal ulong st_ro_evict; internal ulong st_rw_evict; internal ulong st_page_trickle; internal uint st_page_clean; internal uint st_page_dirty; internal uint st_hash_buckets; internal uint st_hash_mutexes; internal uint st_pagesize; internal uint st_hash_searches; internal uint st_hash_longest; internal ulong st_hash_examined; internal ulong st_hash_nowait; internal ulong st_hash_wait; internal ulong st_hash_max_nowait; internal ulong st_hash_max_wait; internal ulong st_region_nowait; internal ulong st_region_wait; internal ulong st_mvcc_frozen; internal ulong st_mvcc_thawed; internal ulong st_mvcc_freed; internal ulong st_alloc; internal ulong st_alloc_buckets; internal ulong st_alloc_max_buckets; internal ulong st_alloc_pages; internal ulong st_alloc_max_pages; internal ulong st_io_wait; internal ulong st_sync_interrupted; internal IntPtr st_regsize; internal IntPtr st_regmax; } internal struct MempStatStruct { internal MPoolStatStruct st; internal MPoolFileStatStruct[] files; } [StructLayout(LayoutKind.Sequential)] internal struct MutexStatStruct { internal uint st_mutex_align; internal uint st_mutex_tas_spins; internal uint st_mutex_init; internal uint st_mutex_cnt; internal uint st_mutex_max; internal uint st_mutex_free; internal uint st_mutex_inuse; internal uint st_mutex_inuse_max; internal ulong st_region_wait; internal ulong st_region_nowait; internal IntPtr st_regsize; internal IntPtr st_regmax; } [StructLayout(LayoutKind.Sequential)] internal struct QueueStatStruct { internal uint qs_magic; internal uint qs_version; internal uint qs_metaflags; internal uint qs_nkeys; internal uint qs_ndata; internal uint qs_pagesize; internal uint qs_extentsize; internal uint qs_pages; internal uint qs_re_len; internal uint qs_re_pad; internal uint qs_pgfree; internal uint qs_first_recno; internal uint qs_cur_recno; } [StructLayout(LayoutKind.Sequential)] internal struct RecnoStatStruct { internal uint bt_magic; internal uint bt_version; internal uint bt_metaflags; internal uint bt_nkeys; internal uint bt_ndata; internal uint bt_pagecnt; internal uint bt_pagesize; internal uint bt_minkey; internal uint bt_re_len; internal uint bt_re_pad; internal uint bt_levels; internal uint bt_int_pg; internal uint bt_leaf_pg; internal uint bt_dup_pg; internal uint bt_over_pg; internal uint bt_empty_pg; internal uint bt_free; internal ulong bt_int_pgfree; internal ulong bt_leaf_pgfree; internal ulong bt_dup_pgfree; internal ulong bt_over_pgfree; } [StructLayout(LayoutKind.Sequential)] internal struct RepMgrStatStruct { internal ulong st_perm_failed; internal ulong st_msgs_queued; internal ulong st_msgs_dropped; internal ulong st_connection_drop; internal ulong st_connect_fail; internal ulong st_elect_threads; internal ulong st_max_elect_threads; } [StructLayout(LayoutKind.Sequential)] internal struct ReplicationStatStruct { /* !!! * Many replication statistics fields cannot be protected by a mutex * without an unacceptable performance penalty, since most message * processing is done without the need to hold a region-wide lock. * Fields whose comments end with a '+' may be updated without holding * the replication or log mutexes (as appropriate), and thus may be * off somewhat (or, on unreasonable architectures under unlucky * circumstances, garbaged). */ internal uint st_startup_complete; internal ulong st_log_queued; internal uint st_status; internal DB_LSN_STRUCT st_next_lsn; internal DB_LSN_STRUCT st_waiting_lsn; internal DB_LSN_STRUCT st_max_perm_lsn; internal uint st_next_pg; internal uint st_waiting_pg; internal uint st_dupmasters; internal IntPtr st_env_id; internal uint st_env_priority; internal ulong st_bulk_fills; internal ulong st_bulk_overflows; internal ulong st_bulk_records; internal ulong st_bulk_transfers; internal ulong st_client_rerequests; internal ulong st_client_svc_req; internal ulong st_client_svc_miss; internal uint st_gen; internal uint st_egen; internal ulong st_lease_chk; internal ulong st_lease_chk_misses; internal ulong st_lease_chk_refresh; internal ulong st_lease_sends; internal ulong st_log_duplicated; internal ulong st_log_queued_max; internal ulong st_log_queued_total; internal ulong st_log_records; internal ulong st_log_requested; internal IntPtr st_master; internal ulong st_master_changes; internal ulong st_msgs_badgen; internal ulong st_msgs_processed; internal ulong st_msgs_recover; internal ulong st_msgs_send_failures; internal ulong st_msgs_sent; internal ulong st_newsites; internal uint st_nsites; internal ulong st_nthrottles; internal ulong st_outdated; internal ulong st_pg_duplicated; internal ulong st_pg_records; internal ulong st_pg_requested; internal ulong st_txns_applied; internal ulong st_startsync_delayed; internal ulong st_elections; internal ulong st_elections_won; internal IntPtr st_election_cur_winner; internal uint st_election_gen; internal uint st_election_datagen; internal DB_LSN_STRUCT st_election_lsn; internal uint st_election_nsites; internal uint st_election_nvotes; internal uint st_election_priority; internal int st_election_status; internal uint st_election_tiebreaker; internal uint st_election_votes; internal uint st_election_sec; internal uint st_election_usec; internal uint st_max_lease_sec; internal uint st_max_lease_usec; } [StructLayout(LayoutKind.Sequential)] internal struct SequenceStatStruct { internal ulong st_wait; internal ulong st_nowait; internal long st_current; internal long st_value; internal long st_last_value; internal long st_min; internal long st_max; internal int st_cache_size; internal uint st_flags; } [StructLayout(LayoutKind.Sequential)] internal struct TransactionStatStruct { internal uint st_nrestores; internal DB_LSN_STRUCT st_last_ckp; internal long st_time_ckp; internal uint st_last_txnid; internal uint st_inittxns; internal uint st_maxtxns; internal ulong st_naborts; internal ulong st_nbegins; internal ulong st_ncommits; internal uint st_nactive; internal uint st_nsnapshot; internal uint st_maxnactive; internal uint st_maxnsnapshot; internal ulong st_region_wait; internal ulong st_region_nowait; internal IntPtr st_regsize; internal IntPtr st_txnarray; } [StructLayout(LayoutKind.Sequential)] internal struct DB_LSN_STRUCT { internal uint file; internal uint offset; } [StructLayout(LayoutKind.Sequential)] internal struct DB_TXN_ACTIVE { internal uint txnid; internal uint parentid; internal int pid; internal uint tid; internal DB_LSN_STRUCT lsn; internal DB_LSN_STRUCT read_lsn; internal uint mvcc_ref; internal uint priority; internal uint status; internal uint xa_status; } internal struct TxnStatStruct { internal TransactionStatStruct st; internal DB_TXN_ACTIVE[] st_txnarray; internal byte[][] st_txngids; internal string[] st_txnnames; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; using System; using System.Collections; using System.Collections.Specialized; using GenStrings; namespace System.Collections.Specialized.Tests { public class ContainsKeyStrTests { public const int MAX_LEN = 50; // max length of random strings [Fact] public void Test01() { IntlStrings intl; StringDictionary sd; string ind; // simple string values string[] values = { "", " ", "a", "aa", "text", " spaces", "1", "$%^#", "2222222222222222222222222", System.DateTime.Today.ToString(), Int32.MaxValue.ToString() }; // keys for simple string values string[] keys = { "zero", "one", " ", "", "aa", "1", System.DateTime.Today.ToString(), "$%^#", Int32.MaxValue.ToString(), " spaces", "2222222222222222222222222" }; int cnt = 0; // Count // initialize IntStrings intl = new IntlStrings(); // [] StringDictionary is constructed as expected //----------------------------------------------------------------- sd = new StringDictionary(); // [] check for empty dictionary // for (int i = 0; i < values.Length; i++) { if (sd.ContainsKey(keys[i])) { Assert.False(true, string.Format("Error, returned true for empty dictionary", i)); } } // [] add simple strings and verify ContainsKey() // cnt = values.Length; for (int i = 0; i < cnt; i++) { sd.Add(keys[i], values[i]); } if (sd.Count != cnt) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", sd.Count, cnt)); } for (int i = 0; i < cnt; i++) { // verify that collection contains all added items // if (!sd.ContainsValue(values[i])) { Assert.False(true, string.Format("Error, collection doesn't contain value \"{1}\"", i, values[i])); } if (!sd.ContainsKey(keys[i])) { Assert.False(true, string.Format("Error, collection doesn't contain key \"{1}\"", i, keys[i])); } } // // Intl strings // [] add Intl strings and verify ContainsKey() // int len = values.Length; string[] intlValues = new string[len * 2]; // fill array with unique strings // for (int i = 0; i < len * 2; i++) { string val = intl.GetRandomString(MAX_LEN); while (Array.IndexOf(intlValues, val) != -1) val = intl.GetRandomString(MAX_LEN); intlValues[i] = val; } Boolean caseInsensitive = false; for (int i = 0; i < len * 2; i++) { if (intlValues[i].Length != 0 && intlValues[i].ToLowerInvariant() == intlValues[i].ToUpperInvariant()) caseInsensitive = true; } // // will use first half of array as values and second half as keys // for (int i = 0; i < len; i++) { cnt = sd.Count; sd.Add(intlValues[i + len], intlValues[i]); if (sd.Count != cnt + 1) { Assert.False(true, string.Format("Error, count is {1} instead of {2}", i, sd.Count, cnt + 1)); } // verify that collection contains newly added item // if (!sd.ContainsValue(intlValues[i])) { Assert.False(true, string.Format("Error, collection doesn't contain value of new item", i)); } if (!sd.ContainsKey(intlValues[i + len])) { Assert.False(true, string.Format("Error, collection doesn't contain key of new item", i)); } // access the item // ind = intlValues[i + len]; if (String.Compare(sd[ind], intlValues[i]) != 0) { Assert.False(true, string.Format("Error, returned item \"{1}\" instead of \"{2}\"", i, sd[ind], intlValues[i])); } } // // add null string with non-null key // [] add null string with non-null key and verify ContainsKey() // cnt = sd.Count; string k = "keykey"; sd.Add(k, null); if (sd.Count != cnt + 1) { Assert.False(true, string.Format("Error, count is {1} instead of {2}", sd.Count, cnt + 1)); } // verify that collection contains newly added item // if (!sd.ContainsKey(k)) { Assert.False(true, string.Format("Error, dictionary doesn't contain new key")); } // // [] Case sensitivity: search should be case-sensitive // sd.Clear(); if (sd.Count != 0) { Assert.False(true, string.Format("Error, count is {1} instead of {2} after Clear()", sd.Count, 0)); } string[] intlValuesLower = new string[len * 2]; // fill array with unique strings // for (int i = 0; i < len * 2; i++) { intlValues[i] = intlValues[i].ToUpperInvariant(); } for (int i = 0; i < len * 2; i++) { intlValuesLower[i] = intlValues[i].ToLowerInvariant(); } sd.Clear(); // // will use first half of array as values and second half as keys // for (int i = 0; i < len; i++) { cnt = sd.Count; sd.Add(intlValues[i + len], intlValues[i]); // adding uppercase strings if (sd.Count != cnt + 1) { Assert.False(true, string.Format("Error, count is {1} instead of {2}", i, sd.Count, cnt + 1)); } // verify that collection contains newly added uppercase item // if (!sd.ContainsValue(intlValues[i])) { Assert.False(true, string.Format("Error, collection doesn't contain value of new item", i)); } if (!sd.ContainsKey(intlValues[i + len])) { Assert.False(true, string.Format("Error, collection doesn't contain key of new item", i)); } // verify that collection doesn't contains lowercase item // if (!caseInsensitive && sd.ContainsValue(intlValuesLower[i])) { Assert.False(true, string.Format("Error, collection contains lowercase value of new item", i)); } // key is case insensitive if (!sd.ContainsKey(intlValuesLower[i + len])) { Assert.False(true, string.Format("Error, collection doesn't contain lowercase key of new item", i)); } } // // call ContainsKey with null - ArgumentNullException expected // [] ContainsKey (null) // Assert.Throws<ArgumentNullException>(() => { sd.ContainsKey(null); }); } } }
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2010-2018 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion -- License Terms -- #if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT #define UNITY #define AOT #endif using System; #if !UNITY || MSGPACK_UNITY_FULL using System.ComponentModel; #endif // !UNITY || MSGPACK_UNITY_FULL #if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; #endif // FEATURE_MPCONTRACT using System.Globalization; #if !UNITY using System.Reflection; #endif // !UNITY using System.Runtime.Serialization; using MsgPack.Serialization.CollectionSerializers; using MsgPack.Serialization.Reflection; namespace MsgPack.Serialization { /// <summary> /// <strong>This is intended to MsgPack for CLI internal use. Do not use this type from application directly.</strong> /// Defines common exception factory methods. /// </summary> #if !UNITY || MSGPACK_UNITY_FULL [EditorBrowsable( EditorBrowsableState.Never )] #endif // !UNITY || MSGPACK_UNITY_FULL public static class SerializationExceptions { #if !AOT internal static readonly MethodInfo ThrowValueTypeCannotBeNull3Method = typeof( SerializationExceptions ).GetMethod( nameof( ThrowValueTypeCannotBeNull ), new[] { typeof( string ), typeof( Type ), typeof( Type ) } ); #endif // !AOT /// <summary> /// <strong>This is intended to MsgPack for CLI internal use. Do not use this type from application directly.</strong> /// Returns new exception to notify that value type cannot be <c>null</c> on deserialization. /// </summary> /// <param name="name">The name of the member.</param> /// <param name="memberType">The type of the member.</param> /// <param name="declaringType">The type that declares the member.</param> /// <returns><see cref="Exception"/> instance. It will not be <c>null</c>.</returns> public static Exception NewValueTypeCannotBeNull( string name, Type memberType, Type declaringType ) { #if DEBUG Contract.Requires( !String.IsNullOrEmpty( name ) ); Contract.Requires( memberType != null ); Contract.Requires( declaringType != null ); Contract.Ensures( Contract.Result<Exception>() != null ); #endif // DEBUG return new SerializationException( String.Format( CultureInfo.CurrentCulture, "Member '{0}' of type '{1}' cannot be null because it is value type('{2}').", name, declaringType, memberType ) ); } /// <summary> /// <strong>This is intended to MsgPack for CLI internal use. Do not use this type from application directly.</strong> /// Throws an exception to notify that value type cannot be <c>null</c> on deserialization. /// </summary> /// <param name="name">The name of the member.</param> /// <param name="memberType">The type of the member.</param> /// <param name="declaringType">The type that declares the member.</param> /// <exception cref="Exception">Always thrown.</exception> /// <returns><see cref="Exception"/> instance. It will not be <c>null</c>.</returns> public static void ThrowValueTypeCannotBeNull( string name, Type memberType, Type declaringType ) { throw NewValueTypeCannotBeNull( name, memberType, declaringType ); } /// <summary> /// <strong>This is intended to MsgPack for CLI internal use. Do not use this type from application directly.</strong> /// Returns new exception to notify that value type cannot be <c>null</c> on deserialization. /// </summary> /// <param name="type">The target type.</param> /// <returns><see cref="Exception"/> instance. It will not be <c>null</c>.</returns> public static Exception NewValueTypeCannotBeNull( Type type ) { #if DEBUG Contract.Requires( type != null ); Contract.Ensures( Contract.Result<Exception>() != null ); #endif // DEBUG return new SerializationException( String.Format( CultureInfo.CurrentCulture, "Cannot be null '{0}' type value.", type ) ); } /// <summary> /// <strong>This is intended to MsgPack for CLI internal use. Do not use this type from application directly.</strong> /// Returns new exception to notify that value type cannot serialize. /// </summary> /// <param name="type">The target type.</param> /// <returns><see cref="Exception"/> instance. It will not be <c>null</c>.</returns> public static Exception NewTypeCannotSerialize( Type type ) { #if DEBUG Contract.Requires( type != null ); Contract.Ensures( Contract.Result<Exception>() != null ); #endif // DEBUG return new SerializationException( String.Format( CultureInfo.CurrentCulture, "Cannot serialize '{0}' type.", type ) ); } /// <summary> /// <strong>This is intended to MsgPack for CLI internal use. Do not use this type from application directly.</strong> /// Returns new exception to notify that value type cannot deserialize. /// </summary> /// <param name="type">The target type.</param> /// <returns><see cref="Exception"/> instance. It will not be <c>null</c>.</returns> public static Exception NewTypeCannotDeserialize( Type type ) { #if DEBUG Contract.Requires( type != null ); Contract.Ensures( Contract.Result<Exception>() != null ); #endif // DEBUG return new SerializationException( String.Format( CultureInfo.CurrentCulture, "Cannot deserialize '{0}' type.", type ) ); } /// <summary> /// <strong>This is intended to MsgPack for CLI internal use. Do not use this type from application directly.</strong> /// Returns new exception to notify that value type cannot deserialize. /// </summary> /// <param name="type">The target type.</param> /// <param name="memberName">The name of deserializing member.</param> /// <param name="inner">The inner exception.</param> /// <returns><see cref="Exception"/> instance. It will not be <c>null</c>.</returns> public static Exception NewTypeCannotDeserialize( Type type, string memberName, Exception inner ) { #if DEBUG Contract.Requires( type != null ); Contract.Requires( !String.IsNullOrEmpty( memberName ) ); Contract.Requires( inner != null ); Contract.Ensures( Contract.Result<Exception>() != null ); #endif // DEBUG return new SerializationException( String.Format( CultureInfo.CurrentCulture, "Cannot deserialize member '{1}' of type '{0}'.", type, memberName ), inner ); } /// <summary> /// <strong>This is intended to MsgPack for CLI internal use. Do not use this type from application directly.</strong> /// Returns new exception to notify that item is not found on the unpacking stream. /// </summary> /// <param name="index">The index to be unpacking.</param> /// <returns><see cref="Exception"/> instance. It will not be <c>null</c>.</returns> #if DEBUG [Obsolete( "Use ThrowMissingItem(int, Unpacker) instead." )] #endif public static Exception NewMissingItem( int index ) // For compatibility only. { #if DEBUG Contract.Requires( index >= 0 ); Contract.Ensures( Contract.Result<Exception>() != null ); #endif // DEBUG return new InvalidMessagePackStreamException( String.Format( CultureInfo.CurrentCulture, "Items at index '{0}' is missing.", index ) ); } /// <summary> /// <strong>This is intended to MsgPack for CLI internal use. Do not use this type from application directly.</strong> /// Throws a exception to notify that item is not found on the unpacking stream. /// </summary> /// <param name="index">The index to be unpacking.</param> /// <param name="unpacker">The unpacker for pretty message.</param> /// <exception cref="Exception">Always thrown.</exception> public static void ThrowMissingItem( int index, Unpacker unpacker ) { ThrowMissingItem( index, null, unpacker ); } /// <summary> /// <strong>This is intended to MsgPack for CLI internal use. Do not use this type from application directly.</strong> /// Throws a exception to notify that item is not found on the unpacking stream. /// </summary> /// <param name="index">The index to be unpacking.</param> /// <param name="name">The name of the item to be unpacking.</param> /// <param name="unpacker">The unpacker for pretty message.</param> /// <exception cref="Exception">Always thrown.</exception> public static void ThrowMissingItem( int index, string name, Unpacker unpacker ) { long offsetOrPosition = -1; bool isRealPosition = false; if ( unpacker != null ) { isRealPosition = unpacker.GetPreviousPosition( out offsetOrPosition ); } if ( String.IsNullOrEmpty( name ) ) { if ( offsetOrPosition >= 0L ) { if ( isRealPosition ) { throw new InvalidMessagePackStreamException( String.Format( CultureInfo.CurrentCulture, "Value for '{0}' at index {1} is missing, at position {2}", name, index, offsetOrPosition ) ); } else { throw new InvalidMessagePackStreamException( String.Format( CultureInfo.CurrentCulture, "Value for '{0}' at index {1} is missing, at offset {2}", name, index, offsetOrPosition ) ); } } else { throw new InvalidMessagePackStreamException( String.Format( CultureInfo.CurrentCulture, "Value for '{0}' at index {1} is missing.", name, index ) ); } } else { if ( offsetOrPosition >= 0L ) { if ( isRealPosition ) { throw new InvalidMessagePackStreamException( String.Format( CultureInfo.CurrentCulture, "Item at index {0} is missing, at position {1}", index, offsetOrPosition ) ); } else { throw new InvalidMessagePackStreamException( String.Format( CultureInfo.CurrentCulture, "Item at index {0} is missing, at offset {1}", index, offsetOrPosition ) ); } } else { throw new InvalidMessagePackStreamException( String.Format( CultureInfo.CurrentCulture, "Item at index '{0}' is missing.", index ) ); } } } internal static void ThrowMissingKey( int index, Unpacker unpacker ) { long offsetOrPosition; var isRealPosition = unpacker.GetPreviousPosition( out offsetOrPosition ); if ( offsetOrPosition >= 0L ) { if ( isRealPosition ) { throw new InvalidMessagePackStreamException( String.Format( CultureInfo.CurrentCulture, "Key of map entry at index {0} is missing, at position {1}", index, offsetOrPosition ) ); } else { throw new InvalidMessagePackStreamException( String.Format( CultureInfo.CurrentCulture, "Key of map entry at index {0} is missing, at offset {1}", index, offsetOrPosition ) ); } } else { throw new InvalidMessagePackStreamException( String.Format( CultureInfo.CurrentCulture, "Key of map entry at index {0} is missing.", index ) ); } } /// <summary> /// <strong>This is intended to MsgPack for CLI internal use. Do not use this type from application directly.</strong> /// Returns new exception to notify that target type is not serializable because it does not have public default constructor. /// </summary> /// <param name="type">The target type.</param> /// <returns><see cref="Exception"/> instance. It will not be <c>null</c>.</returns> internal static Exception NewTargetDoesNotHavePublicDefaultConstructor( Type type ) { #if DEBUG Contract.Requires( type != null ); Contract.Ensures( Contract.Result<Exception>() != null ); #endif // DEBUG return new SerializationException( String.Format( CultureInfo.CurrentCulture, "Type '{0}' does not have default (parameterless) public constructor.", type ) ); } /// <summary> /// <strong>This is intended to MsgPack for CLI internal use. Do not use this type from application directly.</strong> /// Returns new exception to notify that target type is not serializable because it does not have both of public default constructor and public constructor with an Int32 parameter. /// </summary> /// <param name="type">The target type.</param> /// <returns><see cref="Exception"/> instance. It will not be <c>null</c>.</returns> internal static Exception NewTargetDoesNotHavePublicDefaultConstructorNorInitialCapacity( Type type ) { #if DEBUG Contract.Requires( type != null ); Contract.Ensures( Contract.Result<Exception>() != null ); #endif // DEBUG return new SerializationException( String.Format( CultureInfo.CurrentCulture, "Type '{0}' does not have both of default (parameterless) public constructor and public constructor with an Int32 parameter.", type ) ); } internal static void ThrowTargetDoesNotHavePublicDefaultConstructorNorInitialCapacity( Type type ) { throw NewTargetDoesNotHavePublicDefaultConstructorNorInitialCapacity( type ); } /// <summary> /// <strong>This is intended to MsgPack for CLI internal use. Do not use this type from application directly.</strong> /// Returns new exception to notify that required field is not found on the unpacking stream. /// </summary> /// <param name="name">The name of the property.</param> /// <returns><see cref="Exception"/> instance. It will not be <c>null</c>.</returns> public static Exception NewMissingProperty( string name ) { #if DEBUG Contract.Requires( !String.IsNullOrEmpty( name ) ); Contract.Ensures( Contract.Result<Exception>() != null ); #endif // DEBUG return new SerializationException( String.Format( CultureInfo.CurrentCulture, "Property '{0}' is missing.", name ) ); } internal static void ThrowMissingProperty( string name ) { #pragma warning disable 612 throw NewMissingProperty( name ); #pragma warning restore 612 } /// <summary> /// <strong>This is intended to MsgPack for CLI internal use. Do not use this type from application directly.</strong> /// Returns new exception to notify that unpacking stream ends on unexpectedly position. /// </summary> /// <returns><see cref="Exception"/> instance. It will not be <c>null</c>.</returns> [Obsolete( "This method is no longer used internally. So this internal API will be removed in future." )] public static Exception NewUnexpectedEndOfStream() { #if DEBUG Contract.Ensures( Contract.Result<Exception>() != null ); #endif // DEBUG return new SerializationException( "Stream unexpectedly ends." ); } internal static void ThrowUnexpectedEndOfStream( Unpacker unpacker ) { long offsetOrPosition; var isRealPosition = unpacker.GetPreviousPosition( out offsetOrPosition ); if ( offsetOrPosition >= 0L ) { if ( isRealPosition ) { throw new InvalidMessagePackStreamException( String.Format( CultureInfo.CurrentCulture, "Stream unexpectedly ends at position {0}", offsetOrPosition ) ); } else { throw new InvalidMessagePackStreamException( String.Format( CultureInfo.CurrentCulture, "Stream unexpectedly ends at offset {0}", offsetOrPosition ) ); } } else { throw new InvalidMessagePackStreamException( "Stream unexpectedly ends." ); } } /// <summary> /// <strong>This is intended to MsgPack for CLI internal use. Do not use this type from application directly.</strong> /// Returns new exception to notify that target collection type does not declare appropriate Add(T) method. /// </summary> /// <param name="type">The target type.</param> /// <returns><see cref="Exception"/> instance. It will not be <c>null</c>.</returns> public static Exception NewMissingAddMethod( Type type ) { #if DEBUG Contract.Requires( type != null ); Contract.Ensures( Contract.Result<Exception>() != null ); #endif // DEBUG return new SerializationException( String.Format( CultureInfo.CurrentCulture, "Type '{0}' does not have appropriate Add method.", type ) ); } #if !AOT internal static readonly MethodInfo ThrowIsNotArrayHeaderMethod = typeof( SerializationExceptions ).GetMethod( nameof( ThrowIsNotArrayHeader ), new[] { typeof( Unpacker ) } ); #endif // !AOT /// <summary> /// <strong>This is intended to MsgPack for CLI internal use. Do not use this type from application directly.</strong> /// Returns new exception to notify that unpacker is not in the array header, that is the state is invalid. /// </summary> /// <returns><see cref="Exception"/> instance. It will not be <c>null</c>.</returns> [Obsolete( "This method is no longer used internally. So this internal API will be removed in future." )] public static Exception NewIsNotArrayHeader() { return new SerializationException( "Unpacker is not in the array header. The stream may not be array." ); } /// <summary> /// <strong>This is intended to MsgPack for CLI internal use. Do not use this type from application directly.</strong> /// Throws an exception to notify that unpacker is not in the array header, that is the state is invalid. /// </summary> /// <param name="unpacker">The unpacker for pretty message.</param> /// <exception cref="Exception">Always thrown.</exception> public static void ThrowIsNotArrayHeader( Unpacker unpacker ) { long offsetOrPosition; if ( unpacker != null ) { if ( unpacker.GetPreviousPosition( out offsetOrPosition ) ) { throw new SerializationException( String.Format( CultureInfo.CurrentCulture, "Unpacker is not in the array header at position {0}. The stream may not be array.", offsetOrPosition ) ); } else { throw new SerializationException( String.Format( CultureInfo.CurrentCulture, "Unpacker is not in the array header at offset {0}. The stream may not be array.", offsetOrPosition ) ); } } else { throw new SerializationException( "Unpacker is not in the array header. The stream may not be array." ); } } #if !AOT internal static readonly MethodInfo ThrowIsNotMapHeaderMethod = typeof( SerializationExceptions ).GetMethod( nameof( ThrowIsNotMapHeader ), new[] { typeof( Unpacker ) } ); #endif // !AOT /// <summary> /// <strong>This is intended to MsgPack for CLI internal use. Do not use this type from application directly.</strong> /// Returns new exception to notify that unpacker is not in the array header, that is the state is invalid. /// </summary> /// <returns><see cref="Exception"/> instance. It will not be <c>null</c>.</returns> #if DEBUG [Obsolete] #endif // DEBUG public static Exception NewIsNotMapHeader() { #if DEBUG Contract.Ensures( Contract.Result<Exception>() != null ); #endif // DEBUG return new SerializationException( "Unpacker is not in the map header. The stream may not be map." ); } /// <summary> /// <strong>This is intended to MsgPack for CLI internal use. Do not use this type from application directly.</strong> /// Throws an exception to notify that unpacker is not in the map header, that is the state is invalid. /// </summary> /// <param name="unpacker">The unpacker for pretty message.</param> /// <exception cref="Exception">Always thrown.</exception> public static void ThrowIsNotMapHeader( Unpacker unpacker ) { long offsetOrPosition; if ( unpacker != null ) { if ( unpacker.GetPreviousPosition( out offsetOrPosition ) ) { throw new SerializationException( String.Format( CultureInfo.CurrentCulture, "Unpacker is not in the map header at position {0}. The stream may not be map.", offsetOrPosition ) ); } else { throw new SerializationException( String.Format( CultureInfo.CurrentCulture, "Unpacker is not in the map header at offset {0}. The stream may not be map.", offsetOrPosition ) ); } } else { throw new SerializationException( "Unpacker is not in the map header. The stream may not be map." ); } } /// <summary> /// <strong>This is intended to MsgPack for CLI internal use. Do not use this type from application directly.</strong> /// Returns new exception to notify that operation is not supported because <paramref name="type"/> cannot be instanciated. /// </summary> /// <param name="type">Type.</param> /// <returns><see cref="Exception"/> instance. It will not be <c>null</c>.</returns> public static Exception NewNotSupportedBecauseCannotInstanciateAbstractType( Type type ) { #if DEBUG Contract.Requires( type != null ); Contract.Ensures( Contract.Result<Exception>() != null ); #endif // DEBUG return new NotSupportedException( String.Format( CultureInfo.CurrentCulture, "This operation is not supported because '{0}' cannot be instanciated.", type ) ); } #if !AOT /// <summary> /// <see cref="ThrowTupleCardinarityIsNotMatch(int,long,Unpacker)"/> /// </summary> internal static readonly MethodInfo ThrowTupleCardinarityIsNotMatchMethod = typeof( SerializationExceptions ).GetMethod( nameof( ThrowTupleCardinarityIsNotMatch ), new[] { typeof( int ), typeof( long ), typeof( Unpacker ) } ); #endif // !AOT /// <summary> /// <strong>This is intended to MsgPack for CLI internal use. Do not use this type from application directly.</strong> /// Returns new exception to notify that the array length does not match to expected tuple cardinality. /// </summary> /// <param name="expectedTupleCardinality">The expected cardinality of the tuple.</param> /// <param name="actualArrayLength">The actual serialized array length.</param> /// <returns><see cref="Exception"/> instance. It will not be <c>null</c>.</returns> #if DEBUG [Obsolete] #endif // DEBUG public static Exception NewTupleCardinarityIsNotMatch( int expectedTupleCardinality, int actualArrayLength ) { #if DEBUG Contract.Requires( expectedTupleCardinality > 0 ); Contract.Ensures( Contract.Result<Exception>() != null ); #endif // DEBUG return new SerializationException( String.Format( CultureInfo.CurrentCulture, "The length of array ({0}) does not match to tuple cardinality ({1}).", actualArrayLength, expectedTupleCardinality ) ); } /// <summary> /// <strong>This is intended to MsgPack for CLI internal use. Do not use this type from application directly.</strong> /// Throws an exception to notify that the array length does not match to expected tuple cardinality. /// </summary> /// <param name="expectedTupleCardinality">The expected cardinality of the tuple.</param> /// <param name="actualArrayLength">The actual serialized array length.</param> /// <param name="unpacker">The unpacker for pretty message.</param> /// <exception cref="Exception">Always thrown.</exception> /// <returns><see cref="Exception"/> instance. It will not be <c>null</c>.</returns> public static void ThrowTupleCardinarityIsNotMatch( int expectedTupleCardinality, long actualArrayLength, Unpacker unpacker ) { #if DEBUG Contract.Requires( expectedTupleCardinality > 0 ); #endif // DEBUG long offsetOrPosition = -1; bool isRealPosition = false; if ( unpacker != null ) { isRealPosition = unpacker.GetPreviousPosition( out offsetOrPosition ); } if ( offsetOrPosition >= 0L ) { if ( isRealPosition ) { throw new InvalidMessagePackStreamException( String.Format( CultureInfo.CurrentCulture, "The length of array ({0}) does not match to tuple cardinality ({1}), at position {2}", actualArrayLength, expectedTupleCardinality, offsetOrPosition ) ); } else { throw new InvalidMessagePackStreamException( String.Format( CultureInfo.CurrentCulture, "The length of array ({0}) does not match to tuple cardinality ({1}), at offset {2}", actualArrayLength, expectedTupleCardinality, offsetOrPosition ) ); } } else { throw new InvalidMessagePackStreamException( String.Format( CultureInfo.CurrentCulture, "The length of array ({0}) does not match to tuple cardinality ({1}).", actualArrayLength, expectedTupleCardinality ) ); } } /// <summary> /// <strong>This is intended to MsgPack for CLI internal use. Do not use this type from application directly.</strong> /// Returns new exception to notify that the underlying stream is not correct semantically because failed to unpack items count of array/map. /// </summary> /// <param name="innerException">The inner exception for the debug. The value is implementation specific.</param> /// <returns><see cref="Exception"/> instance. It will not be <c>null</c>.</returns> public static Exception NewIsIncorrectStream( Exception innerException ) { #if DEBUG Contract.Ensures( Contract.Result<Exception>() != null ); #endif // DEBUG return new SerializationException( "Failed to unpack items count of the collection.", innerException ); } internal static void ThrowIsIncorrectStream( Exception innerException ) { throw NewIsIncorrectStream( innerException ); } /// <summary> /// <strong>This is intended to MsgPack for CLI internal use. Do not use this type from application directly.</strong> /// Returns new exception to notify that the unpacking collection is too large to represents in the current runtime environment. /// </summary> /// <returns><see cref="Exception"/> instance. It will not be <c>null</c>.</returns> public static Exception NewIsTooLargeCollection() { #if DEBUG Contract.Ensures( Contract.Result<Exception>() != null ); #endif // DEBUG return new MessageNotSupportedException( "The collection which has more than Int32.MaxValue items is not supported." ); } internal static void ThrowIsTooLargeCollection() { throw NewIsTooLargeCollection(); } #if !AOT internal static readonly MethodInfo ThrowNullIsProhibitedMethod = typeof( SerializationExceptions ).GetMethod( nameof( ThrowNullIsProhibited ), new[] { typeof( string ) } ); #endif // !AOT /// <summary> /// <strong>This is intended to MsgPack for CLI internal use. Do not use this type from application directly.</strong> /// Returns new exception to notify that the member cannot be <c>null</c> or the unpacking value cannot be nil because nil value is explicitly prohibitted. /// </summary> /// <param name="memberName">The name of the member.</param> /// <returns><see cref="Exception"/> instance. It will not be <c>null</c>.</returns> public static Exception NewNullIsProhibited( string memberName ) { #if DEBUG Contract.Requires( !String.IsNullOrEmpty( memberName ) ); Contract.Ensures( Contract.Result<Exception>() != null ); #endif // DEBUG return new SerializationException( String.Format( CultureInfo.CurrentCulture, "The member '{0}' cannot be nil.", memberName ) ); } /// <summary> /// <strong>This is intended to MsgPack for CLI internal use. Do not use this type from application directly.</strong> /// Throws an exception to notify that the member cannot be <c>null</c> or the unpacking value cannot be nil because nil value is explicitly prohibitted. /// </summary> /// <param name="memberName">The name of the member.</param> /// <exception cref="Exception">Always thrown.</exception> public static void ThrowNullIsProhibited( string memberName ) { throw NewNullIsProhibited( memberName ); } /// <summary> /// <strong>This is intended to MsgPack for CLI internal use. Do not use this type from application directly.</strong> /// Returns new exception to notify that the unpacking value cannot be nil because the target member is read only and its type is collection. /// </summary> /// <param name="memberName">The name of the member.</param> /// <returns><see cref="Exception"/> instance. It will not be <c>null</c>.</returns> public static Exception NewReadOnlyMemberItemsMustNotBeNull( string memberName ) { #if DEBUG Contract.Requires( !String.IsNullOrEmpty( memberName ) ); Contract.Ensures( Contract.Result<Exception>() != null ); #endif // DEBUG return new SerializationException( String.Format( CultureInfo.CurrentCulture, "The member '{0}' cannot be nil because it is read only member.", memberName ) ); } /// <summary> /// <strong>This is intended to MsgPack for CLI internal use. Do not use this type from application directly.</strong> /// Returns new exception to notify that the unpacking collection value is not a collection. /// </summary> /// <param name="memberName">The name of the member.</param> /// <returns><see cref="Exception"/> instance. It will not be <c>null</c>.</returns> public static Exception NewStreamDoesNotContainCollectionForMember( string memberName ) { #if DEBUG Contract.Requires( !String.IsNullOrEmpty( memberName ) ); Contract.Ensures( Contract.Result<Exception>() != null ); #endif // DEBUG return new SerializationException( String.Format( CultureInfo.CurrentCulture, "Cannot deserialize member '{0}' because the underlying stream does not contain collection.", memberName ) ); } /// <summary> /// <strong>This is intended to MsgPack for CLI internal use. Do not use this type from application directly.</strong> /// Returns new exception to notify that the unpacking array size is not expected length. /// </summary> /// <param name="expectedLength">Expected, required for deserialization array length.</param> /// <param name="actualLength">Actual array length.</param> /// <returns><see cref="Exception"/> instance. It will not be <c>null</c>.</returns> public static Exception NewUnexpectedArrayLength( int expectedLength, int actualLength ) { #if DEBUG Contract.Requires( expectedLength >= 0 ); Contract.Requires( actualLength >= 0 ); Contract.Ensures( Contract.Result<Exception>() != null ); #endif // DEBUG return new SerializationException( String.Format( CultureInfo.CurrentCulture, "The MessagePack stream is invalid. Expected array length is {0}, but actual is {1}.", expectedLength, actualLength ) ); } /// <summary> /// <strong>This is intended to MsgPack for CLI internal use. Do not use this type from application directly.</strong> /// Returns new exception to notify that it is failed to deserialize member. /// </summary> /// <param name="targetType">Deserializing type.</param> /// <param name="memberName">The name of the deserializing member.</param> /// <param name="inner">The exception which caused current error.</param> /// <returns><see cref="Exception"/> instance. It will not be <c>null</c>.</returns> public static Exception NewFailedToDeserializeMember( Type targetType, string memberName, Exception inner ) { #if DEBUG Contract.Requires( targetType != null ); Contract.Requires( !String.IsNullOrEmpty( memberName ) ); Contract.Requires( inner != null ); Contract.Ensures( Contract.Result<Exception>() != null ); #endif // DEBUG return new SerializationException( String.Format( CultureInfo.CurrentCulture, "Cannot deserialize member '{0}' of type '{1}'.", memberName, targetType ), inner ); } /// <summary> /// Throws an exception to notify that it is failed to deserialize member. /// </summary> /// <param name="targetType">Deserializing type.</param> /// <param name="memberName">The name of the deserializing member.</param> /// <param name="inner">The exception which caused current error.</param> internal static void ThrowFailedToDeserializeMember( Type targetType, string memberName, Exception inner ) { throw NewFailedToDeserializeMember( targetType, memberName, inner ); } #if !AOT /// <summary> /// <see cref="NewUnpackFromIsNotSupported(Type)"/> /// </summary> internal static readonly MethodInfo NewUnpackFromIsNotSupportedMethod = typeof( SerializationExceptions ).GetMethod( nameof( NewUnpackFromIsNotSupported ), new[] { typeof( Type ) } ); #endif // !AOT /// <summary> /// Returns a new exception which represents <c>UnpackFrom</c> is not supported in this asymmetric serializer. /// </summary> /// <param name="targetType">Deserializing type.</param> /// <returns>The exception. This value will not be <c>null</c>.</returns> public static Exception NewUnpackFromIsNotSupported( Type targetType ) { #if DEBUG Contract.Requires( targetType != null ); #endif // DEBUG return new NotSupportedException( String.Format( CultureInfo.CurrentCulture, "This operation is not supported for '{0}' because the serializer does not support UnpackFrom method.", targetType ) ); } #if !AOT /// <summary> /// <see cref="NewCreateInstanceIsNotSupported(Type)"/> /// </summary> internal static readonly MethodInfo NewCreateInstanceIsNotSupportedMethod = typeof( SerializationExceptions ).GetMethod( nameof( NewCreateInstanceIsNotSupported ), new[] { typeof( Type ) } ); #endif // !AOT /// <summary> /// Returns a new exception which represents <c>UnpackFrom</c> is not supported in this asymmetric serializer. /// </summary> /// <param name="targetType">Deserializing type.</param> /// <returns>The exception. This value will not be <c>null</c>.</returns> public static Exception NewCreateInstanceIsNotSupported( Type targetType ) { #if DEBUG Contract.Requires( targetType != null ); #endif // DEBUG return new NotSupportedException( String.Format( CultureInfo.CurrentCulture, "This operation is not supported for '{0}' because the serializer does not support CreateInstance method.", targetType ) ); } internal static Exception NewUnpackToIsNotSupported( Type type, Exception inner ) { #if DEBUG Contract.Requires( type != null ); #endif // DEBUG return new NotSupportedException( String.Format( CultureInfo.CurrentCulture, "This operation is not supported for '{0}' because it does not have accesible Add(T) method.", type ), inner ); } internal static Exception NewValueTypeCannotBePolymorphic( Type type ) { return new SerializationException( String.Format( CultureInfo.CurrentCulture, "Value type '{0}' cannot be polymorphic.", type ) ); } internal static Exception NewUnknownTypeEmbedding() { return new SerializationException( "Cannot deserialize with type-embedding based serializer. Root object must be 3 element array." ); } internal static Exception NewIncompatibleCollectionSerializer( Type targetType, Type incompatibleType, Type exampleClass ) { return new SerializationException( String.Format( CultureInfo.CurrentCulture, "Cannot serialize type '{0}' because registered or generated serializer '{1}' does not implement '{2}', which is implemented by '{3}', for example.", targetType.GetFullName(), incompatibleType.GetFullName(), typeof( ICollectionInstanceFactory ), exampleClass.GetFullName() ) ); } internal static void ThrowArgumentNullException( string parameterName ) { throw new ArgumentNullException( parameterName ); } internal static void ThrowArgumentNullException( string parameterName, string fieldName ) { throw new ArgumentNullException( parameterName, String.Format( CultureInfo.CurrentCulture, "Field '{0}' of parameter '{1}' cannot be null.", fieldName, parameterName ) ); } internal static void ThrowArgumentCannotBeNegativeException( string parameterName ) { throw new ArgumentOutOfRangeException( parameterName, "The value cannot be negative number." ); } internal static void ThrowArgumentCannotBeNegativeException( string parameterName, string fieldName ) { throw new ArgumentOutOfRangeException( parameterName, String.Format( CultureInfo.CurrentCulture, "Field '{0}' of parameter '{1}' cannot be negative number.", fieldName, parameterName ) ); } internal static void ThrowArgumentException( string parameterName, string message ) { throw new ArgumentException( message, parameterName ); } internal static void ThrowSerializationException( string message ) { throw new SerializationException( message ); } internal static void ThrowSerializationException( string message, Exception innerException ) { throw new SerializationException( message, innerException ); } #if UNITY && DEBUG public #else internal #endif static void ThrowInvalidArrayItemsCount( Unpacker unpacker, Type targetType, int requiredCount ) { throw unpacker.IsCollectionHeader ? new SerializationException( String.Format( CultureInfo.CurrentCulture, "Cannot deserialize type '{0}' because stream is not {1} elements array. Current type is {2} and its element count is {3}.", targetType, requiredCount, unpacker.IsArrayHeader ? "array" : "map", unpacker.LastReadData.AsInt64() ) ) : new SerializationException( String.Format( CultureInfo.CurrentCulture, "Cannot deserialize type '{0}' because stream is not {1} elements array. Current type is {2}.", targetType, requiredCount, unpacker.LastReadData.UnderlyingType ) ); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using BTDB.Allocators; using BTDB.BTreeLib; using BTDB.Buffer; using BTDB.Collections; using BTDB.KVDBLayer.BTree; using BTDB.KVDBLayer.Implementation; using BTDB.StreamLayer; namespace BTDB.KVDBLayer { public class BTreeKeyValueDB : IHaveSubDB, IKeyValueDBInternal { const int MaxValueSizeInlineInMemory = 7; const int EndOfIndexFileMarker = 0x1234DEAD; IRootNode _lastCommitted; IRootNode? _listHead; // it is long only because Interlock.Read is just long capable, MaxValue means no preserving history long _preserveHistoryUpToCommitUlong; IRootNode? _nextRoot; BTreeKeyValueDBTransaction? _writingTransaction; readonly Queue<TaskCompletionSource<IKeyValueDBTransaction>> _writeWaitingQueue = new Queue<TaskCompletionSource<IKeyValueDBTransaction>>(); readonly object _writeLock = new object(); uint _fileIdWithTransactionLog; uint _fileIdWithPreviousTransactionLog; IFileCollectionFile? _fileWithTransactionLog; ISpanWriter? _writerWithTransactionLog; static readonly byte[] MagicStartOfTransaction = {(byte) 't', (byte) 'R'}; public long MaxTrLogFileSize { get; set; } public IEnumerable<IKeyValueDBTransaction> Transactions() { foreach (var keyValuePair in _transactions) { yield return keyValuePair.Key; } } public ulong CompactorReadBytesPerSecondLimit { get; } public ulong CompactorWriteBytesPerSecondLimit { get; } readonly IOffHeapAllocator _allocator; readonly ICompressionStrategy _compression; readonly ICompactorScheduler? _compactorScheduler; readonly IFileCollectionWithFileInfos _fileCollection; readonly Dictionary<long, object> _subDBs = new Dictionary<long, object>(); readonly Func<CancellationToken, bool>? _compactFunc; readonly bool _readOnly; readonly bool _lenientOpen; uint? _missingSomeTrlFiles; public BTreeKeyValueDB(IFileCollection fileCollection) : this(fileCollection, new SnappyCompressionStrategy()) { } public BTreeKeyValueDB(IFileCollection fileCollection, ICompressionStrategy compression, uint fileSplitSize = int.MaxValue) : this(fileCollection, compression, fileSplitSize, CompactorScheduler.Instance) { } public BTreeKeyValueDB(IFileCollection fileCollection, ICompressionStrategy compression, uint fileSplitSize, ICompactorScheduler? compactorScheduler) : this(new KeyValueDBOptions { Allocator = new HGlobalAllocator(), FileCollection = fileCollection, Compression = compression, FileSplitSize = fileSplitSize, CompactorScheduler = compactorScheduler }) { } public BTreeKeyValueDB(KeyValueDBOptions options) { if (options == null) throw new ArgumentNullException(nameof(options)); if (options.FileCollection == null) throw new ArgumentNullException(nameof(options.FileCollection)); if (options.FileSplitSize < 1024 || options.FileSplitSize > int.MaxValue) throw new ArgumentOutOfRangeException(nameof(options.FileSplitSize), "Allowed range 1024 - 2G"); Logger = options.Logger; _compactorScheduler = options.CompactorScheduler; MaxTrLogFileSize = options.FileSplitSize; _readOnly = options.ReadOnly; _lenientOpen = options.LenientOpen; _compression = options.Compression ?? throw new ArgumentNullException(nameof(options.Compression)); DurableTransactions = false; _fileCollection = new FileCollectionWithFileInfos(options.FileCollection); CompactorReadBytesPerSecondLimit = options.CompactorReadBytesPerSecondLimit ?? 0; CompactorWriteBytesPerSecondLimit = options.CompactorWriteBytesPerSecondLimit ?? 0; _allocator = options.Allocator ?? new HGlobalAllocator(); _lastCommitted = BTreeImpl12.CreateEmptyRoot(_allocator); _lastCommitted.Commit(); _listHead = _lastCommitted; _preserveHistoryUpToCommitUlong = (long) (options.PreserveHistoryUpToCommitUlong ?? ulong.MaxValue); LoadInfoAboutFiles(options.OpenUpToCommitUlong); if (!_readOnly) { _compactFunc = _compactorScheduler?.AddCompactAction(Compact); _compactorScheduler?.AdviceRunning(true); } } public ulong DistanceFromLastKeyIndex(IRootNodeInternal root) { return DistanceFromLastKeyIndex((IRootNode) root); } Span<KeyIndexInfo> IKeyValueDBInternal.BuildKeyIndexInfos() { return BuildKeyIndexInfos(); } uint IKeyValueDBInternal.CalculatePreserveKeyIndexKeyFromKeyIndexInfos(ReadOnlySpan<KeyIndexInfo> keyIndexes) { return CalculatePreserveKeyIndexKeyFromKeyIndexInfos(keyIndexes); } public uint GetTrLogFileId(IRootNodeInternal root) { return ((IRootNode) root).TrLogFileId; } public void IterateRoot(IRootNodeInternal root, ValuesIterateAction visit) { ((IRootNode) root).ValuesIterate(visit); } internal Span<KeyIndexInfo> BuildKeyIndexInfos() { var keyIndexes = new StructList<KeyIndexInfo>(); foreach (var fileInfo in _fileCollection.FileInfos) { var keyIndex = fileInfo.Value as IKeyIndex; if (keyIndex == null) continue; keyIndexes.Add(new KeyIndexInfo {Key = fileInfo.Key, Generation = keyIndex.Generation, CommitUlong = keyIndex.CommitUlong}); } if (keyIndexes.Count > 1) keyIndexes.Sort(Comparer<KeyIndexInfo>.Create((l, r) => Comparer<long>.Default.Compare(l.Generation, r.Generation))); return keyIndexes.AsSpan(); } void LoadInfoAboutFiles(ulong? openUpToCommitUlong) { long latestGeneration = -1; uint latestTrLogFileId = 0; foreach (var fileInfo in _fileCollection.FileInfos) { if (!(fileInfo.Value is IFileTransactionLog trLog)) continue; if (trLog.Generation > latestGeneration) { latestGeneration = trLog.Generation; latestTrLogFileId = fileInfo.Key; } } var keyIndexes = BuildKeyIndexInfos(); var preserveKeyIndexKey = CalculatePreserveKeyIndexKeyFromKeyIndexInfos(keyIndexes); var preserveKeyIndexGeneration = CalculatePreserveKeyIndexGeneration(preserveKeyIndexKey); var firstTrLogId = LinkTransactionLogFileIds(latestTrLogFileId); var firstTrLogOffset = 0u; var hasKeyIndex = false; try { while (keyIndexes.Length > 0) { var nearKeyIndex = keyIndexes.Length - 1; if (openUpToCommitUlong.HasValue) { while (nearKeyIndex >= 0) { if (keyIndexes[nearKeyIndex].CommitUlong <= openUpToCommitUlong.Value) break; nearKeyIndex--; } if (nearKeyIndex < 0) { // If we have all trl files we can replay from start if (GetGeneration(firstTrLogId) == 1) break; // Or we have to start with oldest kvi nearKeyIndex = 0; } } var keyIndex = keyIndexes[nearKeyIndex]; keyIndexes.Slice(nearKeyIndex + 1).CopyTo(keyIndexes.Slice(nearKeyIndex)); keyIndexes = keyIndexes.Slice(0, keyIndexes.Length - 1); var info = (IKeyIndex) _fileCollection.FileInfoByIdx(keyIndex.Key); _nextRoot = _lastCommitted.CreateWritableTransaction(); try { if (LoadKeyIndex(keyIndex.Key, info!) && firstTrLogId <= info.TrLogFileId) { _lastCommitted.Dispose(); _lastCommitted = _nextRoot!; _lastCommitted!.Commit(); _listHead = _lastCommitted; _nextRoot = null; firstTrLogId = info.TrLogFileId; firstTrLogOffset = info.TrLogOffset; hasKeyIndex = true; break; } } finally { if (_nextRoot != null) { _nextRoot.Dispose(); _nextRoot = null; } } // Corrupted kvi - could be removed MarkFileForRemoval(keyIndex.Key); } while (keyIndexes.Length > 0) { var keyIndex = keyIndexes[^1]; keyIndexes = keyIndexes.Slice(0, keyIndexes.Length - 1); if (keyIndex.Key != preserveKeyIndexKey) MarkFileForRemoval(keyIndex.Key); } if (!hasKeyIndex && _missingSomeTrlFiles.HasValue) { if (_lenientOpen) { Logger?.LogWarning("No valid Kvi and lowest Trl in chain is not first. Missing " + _missingSomeTrlFiles.Value + ". LenientOpen is true, recovering data."); LoadTransactionLogs(firstTrLogId, firstTrLogOffset, openUpToCommitUlong); } else { Logger?.LogWarning("No valid Kvi and lowest Trl in chain is not first. Missing " + _missingSomeTrlFiles.Value); if (!_readOnly) { foreach (var fileInfo in _fileCollection.FileInfos) { var trLog = fileInfo.Value as IFileTransactionLog; if (trLog == null) continue; MarkFileForRemoval(fileInfo.Key); } _fileCollection.DeleteAllUnknownFiles(); _fileIdWithTransactionLog = 0; firstTrLogId = 0; latestTrLogFileId = 0; } } } else { LoadTransactionLogs(firstTrLogId, firstTrLogOffset, openUpToCommitUlong); } if (!_readOnly) { if (openUpToCommitUlong.HasValue || latestTrLogFileId != firstTrLogId && firstTrLogId != 0 || !hasKeyIndex && _fileCollection.FileInfos.Any(p => p.Value.SubDBId == 0)) { // Need to create new trl if cannot append to last one so it is then written to kvi if (openUpToCommitUlong.HasValue && _fileIdWithTransactionLog == 0) { WriteStartOfNewTransactionLogFile(); _fileWithTransactionLog!.HardFlush(); _fileWithTransactionLog.Truncate(); UpdateTransactionLogInBTreeRoot(_lastCommitted); } // When not opening history commit KVI file will be created by compaction if (openUpToCommitUlong.HasValue) { CreateIndexFile(CancellationToken.None, preserveKeyIndexGeneration, true); } } if (_fileIdWithTransactionLog != 0) { if (_writerWithTransactionLog == null) { _fileWithTransactionLog = FileCollection.GetFile(_fileIdWithTransactionLog); _writerWithTransactionLog = _fileWithTransactionLog!.GetAppenderWriter(); } if (_writerWithTransactionLog.GetCurrentPositionWithoutWriter() > MaxTrLogFileSize) { WriteStartOfNewTransactionLogFile(); } } _fileCollection.DeleteAllUnknownFiles(); } foreach (var fileInfo in _fileCollection.FileInfos) { var ft = fileInfo.Value.FileType; if (ft == KVFileType.TransactionLog || ft == KVFileType.PureValuesWithId || ft == KVFileType.PureValues) { _fileCollection.GetFile(fileInfo.Key)?.AdvisePrefetch(); } } } finally { if (_nextRoot != null) { _nextRoot.Dispose(); _nextRoot = null; } } } void MarkFileForRemoval(uint fileId) { var file = _fileCollection.GetFile(fileId); if (file != null) Logger?.FileMarkedForDelete(file.Index); else Logger?.LogWarning($"Marking for delete file id {fileId} unknown in file collection."); _fileCollection.MakeIdxUnknown(fileId); } bool IKeyValueDBInternal.LoadUsedFilesFromKeyIndex(uint fileId, IKeyIndex info) { return LoadUsedFilesFromKeyIndex(fileId, info); } public long CalculatePreserveKeyIndexGeneration(uint preserveKeyIndexKey) { if (preserveKeyIndexKey <= 0) return -1; return preserveKeyIndexKey < uint.MaxValue ? GetGeneration(preserveKeyIndexKey) : long.MaxValue; } internal uint CalculatePreserveKeyIndexKeyFromKeyIndexInfos(ReadOnlySpan<KeyIndexInfo> keyIndexes) { var preserveKeyIndexKey = uint.MaxValue; var preserveHistoryUpToCommitUlong = (ulong) Interlocked.Read(ref _preserveHistoryUpToCommitUlong); if (preserveHistoryUpToCommitUlong != ulong.MaxValue) { var nearKeyIndex = keyIndexes.Length - 1; while (nearKeyIndex >= 0) { if (keyIndexes[nearKeyIndex].CommitUlong <= preserveHistoryUpToCommitUlong) { preserveKeyIndexKey = keyIndexes[nearKeyIndex].Key; break; } nearKeyIndex--; } if (nearKeyIndex < 0) preserveKeyIndexKey = 0; } return preserveKeyIndexKey; } long IKeyValueDBInternal.ReplaceBTreeValues(CancellationToken cancellation, Dictionary<ulong, ulong> newPositionMap) { return ReplaceBTreeValues(cancellation, newPositionMap); } long[] IKeyValueDBInternal.CreateIndexFile(CancellationToken cancellation, long preserveKeyIndexGeneration) { return CreateIndexFile(cancellation, preserveKeyIndexGeneration); } ISpanWriter IKeyValueDBInternal.StartPureValuesFile(out uint fileId) { return StartPureValuesFile(out fileId); } long[] CreateIndexFile(CancellationToken cancellation, long preserveKeyIndexGeneration, bool fullSpeed = false) { var root = ReferenceAndGetLastCommitted(); try { var idxFileId = CreateKeyIndexFile((IRootNode) root, cancellation, fullSpeed); MarkAsUnknown(_fileCollection.FileInfos.Where(p => p.Value.FileType == KVFileType.KeyIndex && p.Key != idxFileId && p.Value.Generation != preserveKeyIndexGeneration).Select(p => p.Key)); return ((FileKeyIndex)_fileCollection.FileInfoByIdx(idxFileId))!.UsedFilesInOlderGenerations!; } finally { DereferenceRootNodeInternal(root); } } internal bool LoadUsedFilesFromKeyIndex(uint fileId, IKeyIndex info) { try { var file = FileCollection.GetFile(fileId); var reader = new SpanReader(file!.GetExclusiveReader()); FileKeyIndex.SkipHeader(ref reader); var keyCount = info.KeyValueCount; var usedFileIds = new HashSet<uint>(); if (info.Compression == KeyIndexCompression.Old) { for (var i = 0; i < keyCount; i++) { var keyLength = reader.ReadVInt32(); reader.SkipBlock(keyLength); var vFileId = reader.ReadVUInt32(); if (vFileId > 0) usedFileIds.Add(vFileId); reader.SkipVUInt32(); reader.SkipVInt32(); } } else { if (info.Compression != KeyIndexCompression.None) return false; for (var i = 0; i < keyCount; i++) { reader.SkipVUInt32(); var keyLengthWithoutPrefix = (int) reader.ReadVUInt32(); reader.SkipBlock(keyLengthWithoutPrefix); var vFileId = reader.ReadVUInt32(); if (vFileId > 0) usedFileIds.Add(vFileId); reader.SkipVUInt32(); reader.SkipVInt32(); } } var trlGeneration = GetGeneration(info.TrLogFileId); info.UsedFilesInOlderGenerations = usedFileIds.Select(GetGenerationIgnoreMissing) .Where(gen => gen < trlGeneration).OrderBy(a => a).ToArray(); return TestKviMagicEndMarker(fileId, ref reader, file); } catch (Exception) { return false; } } bool LoadKeyIndex(uint fileId, IKeyIndex info) { try { var file = FileCollection.GetFile(fileId); var reader = new SpanReader(file!.GetExclusiveReader()); FileKeyIndex.SkipHeader(ref reader); var keyCount = info.KeyValueCount; _nextRoot!.TrLogFileId = info.TrLogFileId; _nextRoot.TrLogOffset = info.TrLogOffset; _nextRoot.CommitUlong = info.CommitUlong; if (info.Ulongs != null) for (var i = 0u; i < info.Ulongs.Length; i++) { _nextRoot.SetUlong(i, info.Ulongs[i]); } var usedFileIds = new HashSet<uint>(); var cursor = _nextRoot.CreateCursor(); if (info.Compression == KeyIndexCompression.Old) { cursor.BuildTree(keyCount, ref reader, (ref SpanReader reader2, ref ByteBuffer key, in Span<byte> trueValue) => { var keyLength = reader2.ReadVInt32(); key = ByteBuffer.NewAsync(new byte[Math.Abs(keyLength)]); reader2.ReadBlock(key); if (keyLength < 0) { _compression.DecompressKey(ref key); } trueValue.Clear(); var vFileId = reader2.ReadVUInt32(); if (vFileId > 0) usedFileIds.Add(vFileId); MemoryMarshal.Write(trueValue, ref vFileId); var valueOfs = reader2.ReadVUInt32(); var valueSize = reader2.ReadVInt32(); if (vFileId == 0) { var len = valueSize >> 24; trueValue[4] = (byte) len; switch (len) { case 7: trueValue[11] = (byte) (valueOfs >> 24); goto case 6; case 6: trueValue[10] = (byte) (valueOfs >> 16); goto case 5; case 5: trueValue[9] = (byte) (valueOfs >> 8); goto case 4; case 4: trueValue[8] = (byte) valueOfs; goto case 3; case 3: trueValue[7] = (byte) valueSize; goto case 2; case 2: trueValue[6] = (byte) (valueSize >> 8); goto case 1; case 1: trueValue[5] = (byte) (valueSize >> 16); break; case 0: break; default: throw new BTDBException("Corrupted DB"); } } else { MemoryMarshal.Write(trueValue.Slice(4), ref valueOfs); MemoryMarshal.Write(trueValue.Slice(8), ref valueSize); } }); } else { if (info.Compression != KeyIndexCompression.None) return false; var prevKey = ByteBuffer.NewEmpty(); cursor.BuildTree(keyCount, ref reader, (ref SpanReader reader2, ref ByteBuffer key, in Span<byte> trueValue) => { var prefixLen = (int) reader2.ReadVUInt32(); var keyLengthWithoutPrefix = (int) reader2.ReadVUInt32(); var keyLen = prefixLen + keyLengthWithoutPrefix; key.Expand(keyLen); Array.Copy(prevKey.Buffer!, prevKey.Offset, key.Buffer!, key.Offset, prefixLen); reader2.ReadBlock(key.Slice(prefixLen)); prevKey = key; var vFileId = reader2.ReadVUInt32(); if (vFileId > 0) usedFileIds.Add(vFileId); trueValue.Clear(); MemoryMarshal.Write(trueValue, ref vFileId); var valueOfs = reader2.ReadVUInt32(); var valueSize = reader2.ReadVInt32(); if (vFileId == 0) { var len = valueSize >> 24; trueValue[4] = (byte) len; switch (len) { case 7: trueValue[11] = (byte) (valueOfs >> 24); goto case 6; case 6: trueValue[10] = (byte) (valueOfs >> 16); goto case 5; case 5: trueValue[9] = (byte) (valueOfs >> 8); goto case 4; case 4: trueValue[8] = (byte) valueOfs; goto case 3; case 3: trueValue[7] = (byte) valueSize; goto case 2; case 2: trueValue[6] = (byte) (valueSize >> 8); goto case 1; case 1: trueValue[5] = (byte) (valueSize >> 16); break; case 0: break; default: throw new BTDBException("Corrupted DB"); } } else { MemoryMarshal.Write(trueValue.Slice(4), ref valueOfs); MemoryMarshal.Write(trueValue.Slice(8), ref valueSize); } }); } var trlGeneration = GetGeneration(info.TrLogFileId); info.UsedFilesInOlderGenerations = usedFileIds.Select(GetGenerationIgnoreMissing) .Where(gen => gen < trlGeneration).OrderBy(a => a).ToArray(); return TestKviMagicEndMarker(fileId, ref reader, file); } catch (Exception) { return false; } } bool TestKviMagicEndMarker(uint fileId, ref SpanReader reader, IFileCollectionFile file) { if (reader.Eof) return true; if ((ulong) reader.GetCurrentPosition() + 4 == file.GetSize() && reader.ReadInt32() == EndOfIndexFileMarker) return true; if (_lenientOpen) { Logger?.LogWarning("End of Kvi " + fileId + " had some garbage at " + (reader.GetCurrentPosition() - 4) + " ignoring that because of LenientOpen"); return true; } return false; } void LoadTransactionLogs(uint firstTrLogId, uint firstTrLogOffset, ulong? openUpToCommitUlong) { while (firstTrLogId != 0 && firstTrLogId != uint.MaxValue) { _fileIdWithTransactionLog = 0; if (LoadTransactionLog(firstTrLogId, firstTrLogOffset, openUpToCommitUlong)) { _fileIdWithTransactionLog = firstTrLogId; } firstTrLogOffset = 0; _fileIdWithPreviousTransactionLog = firstTrLogId; var fileInfo = _fileCollection.FileInfoByIdx(firstTrLogId); if (fileInfo == null) return; firstTrLogId = ((IFileTransactionLog) fileInfo).NextFileId; } } // Return true if it is suitable for continuing writing new transactions bool LoadTransactionLog(uint fileId, uint logOffset, ulong? openUpToCommitUlong) { if (openUpToCommitUlong.HasValue && _lastCommitted.CommitUlong >= openUpToCommitUlong) { return false; } Span<byte> trueValue = stackalloc byte[12]; var collectionFile = FileCollection.GetFile(fileId); var readerController = collectionFile!.GetExclusiveReader(); var reader = new SpanReader(readerController); try { if (logOffset == 0) { FileTransactionLog.SkipHeader(ref reader); } else { reader.SkipBlock(logOffset); } if (reader.Eof) return true; var afterTemporaryEnd = false; var finishReading = false; ICursor cursor; ICursor cursor2; if (_nextRoot != null) { cursor = _nextRoot.CreateCursor(); cursor2 = _nextRoot.CreateCursor(); } else { cursor = _lastCommitted.CreateCursor(); cursor2 = _lastCommitted.CreateCursor(); } while (!reader.Eof) { var command = (KVCommandType) reader.ReadUInt8(); if (command == 0 && afterTemporaryEnd) { collectionFile.SetSize(reader.GetCurrentPosition() - 1); return true; } if (finishReading) { return false; } afterTemporaryEnd = false; switch (command & KVCommandType.CommandMask) { case KVCommandType.CreateOrUpdateDeprecated: case KVCommandType.CreateOrUpdate: { if (_nextRoot == null) return false; var keyLen = reader.ReadVInt32(); var valueLen = reader.ReadVInt32(); var key = new byte[keyLen]; reader.ReadBlock(key); var keyBuf = ByteBuffer.NewAsync(key); if ((command & KVCommandType.FirstParamCompressed) != 0) { _compression.DecompressKey(ref keyBuf); } trueValue.Clear(); var valueOfs = (uint) reader.GetCurrentPosition(); var valueSize = (command & KVCommandType.SecondParamCompressed) != 0 ? -valueLen : valueLen; if (valueLen <= MaxValueSizeInlineInMemory && (command & KVCommandType.SecondParamCompressed) == 0) { trueValue[4] = (byte) valueLen; reader.ReadBlock(ref MemoryMarshal.GetReference(trueValue.Slice(5, valueLen)), (uint) valueLen); } else { MemoryMarshal.Write(trueValue, ref fileId); MemoryMarshal.Write(trueValue.Slice(4), ref valueOfs); MemoryMarshal.Write(trueValue.Slice(8), ref valueSize); reader.SkipBlock(valueLen); } cursor.Upsert(keyBuf.AsSyncReadOnlySpan(), trueValue); } break; case KVCommandType.EraseOne: { if (_nextRoot == null) return false; var keyLen = reader.ReadVInt32(); var key = new byte[keyLen]; reader.ReadBlock(key); var keyBuf = ByteBuffer.NewAsync(key); if ((command & KVCommandType.FirstParamCompressed) != 0) { _compression.DecompressKey(ref keyBuf); } if (cursor.FindExact(keyBuf.AsSyncReadOnlySpan())) { cursor.Erase(); } else if (!_lenientOpen) { _nextRoot = null; return false; } } break; case KVCommandType.EraseRange: { if (_nextRoot == null) return false; var keyLen1 = reader.ReadVInt32(); var keyLen2 = reader.ReadVInt32(); var key = new byte[keyLen1]; reader.ReadBlock(key); var keyBuf = ByteBuffer.NewAsync(key); if ((command & KVCommandType.FirstParamCompressed) != 0) { _compression.DecompressKey(ref keyBuf); } var findResult = cursor.Find(keyBuf.AsSyncReadOnlySpan()); if (findResult != FindResult.Exact && !_lenientOpen) { _nextRoot = null; return false; } if (findResult == FindResult.Previous) cursor.MoveNext(); key = new byte[keyLen2]; reader.ReadBlock(key); keyBuf = ByteBuffer.NewAsync(key); if ((command & KVCommandType.SecondParamCompressed) != 0) { _compression.DecompressKey(ref keyBuf); } findResult = cursor2.Find(keyBuf.AsSyncReadOnlySpan()); if (findResult != FindResult.Exact && !_lenientOpen) { _nextRoot = null; return false; } if (findResult == FindResult.Next) cursor2.MovePrevious(); cursor.EraseTo(cursor2); } break; case KVCommandType.DeltaUlongs: { if (_nextRoot == null) return false; var idx = reader.ReadVUInt32(); var delta = reader.ReadVUInt64(); // overflow is expected in case Ulong is decreasing but that should be rare _nextRoot.SetUlong(idx, unchecked(_nextRoot.GetUlong(idx) + delta)); } break; case KVCommandType.TransactionStart: if (!reader.CheckMagic(MagicStartOfTransaction)) return false; if (_nextRoot != null) { _nextRoot.Dispose(); _nextRoot = null; return false; } _nextRoot = _lastCommitted.CreateWritableTransaction(); cursor.SetNewRoot(_nextRoot); cursor2.SetNewRoot(_nextRoot); break; case KVCommandType.CommitWithDeltaUlong: if (_nextRoot == null) return false; unchecked // overflow is expected in case commitUlong is decreasing but that should be rare { _nextRoot.CommitUlong += reader.ReadVUInt64(); } goto case KVCommandType.Commit; case KVCommandType.Commit: if (_nextRoot == null) return false; _nextRoot.TrLogFileId = fileId; _nextRoot.TrLogOffset = (uint) reader.GetCurrentPosition(); _lastCommitted.Dispose(); _nextRoot.Commit(); _lastCommitted = _nextRoot; _listHead = _lastCommitted; _nextRoot = null; if (openUpToCommitUlong.HasValue && _lastCommitted.CommitUlong >= openUpToCommitUlong) { finishReading = true; } break; case KVCommandType.Rollback: _nextRoot.Dispose(); _nextRoot = null; break; case KVCommandType.EndOfFile: return false; case KVCommandType.TemporaryEndOfFile: _lastCommitted.TrLogFileId = fileId; _lastCommitted.TrLogOffset = (uint) reader.GetCurrentPosition(); afterTemporaryEnd = true; break; default: if (_nextRoot != null) { _nextRoot.Dispose(); _nextRoot = null; } return false; } } return afterTemporaryEnd; } catch (EndOfStreamException) { if (_nextRoot != null) { _nextRoot.Dispose(); _nextRoot = null; } return false; } } uint LinkTransactionLogFileIds(uint latestTrLogFileId) { var nextId = 0u; var currentId = latestTrLogFileId; while (currentId != 0) { var fileInfo = _fileCollection.FileInfoByIdx(currentId); var fileTransactionLog = fileInfo as IFileTransactionLog; if (fileTransactionLog == null) { _missingSomeTrlFiles = currentId; break; } fileTransactionLog.NextFileId = nextId; nextId = currentId; currentId = fileTransactionLog.PreviousFileId; } return nextId; } public void Dispose() { _compactorScheduler?.RemoveCompactAction(_compactFunc!); lock (_writeLock) { if (_writingTransaction != null) throw new BTDBException("Cannot dispose KeyValueDB when writing transaction still running"); while (_writeWaitingQueue.Count > 0) { _writeWaitingQueue.Dequeue().TrySetCanceled(); } _lastCommitted.Dereference(); FreeWaitingToDisposeUnsafe(); } if (_writerWithTransactionLog != null) { var writer = new SpanWriter(_writerWithTransactionLog); writer.WriteUInt8((byte) KVCommandType.TemporaryEndOfFile); writer.Sync(); _fileWithTransactionLog!.HardFlushTruncateSwitchToDisposedMode(); } } public bool DurableTransactions { get; set; } public IRootNodeInternal ReferenceAndGetLastCommitted() { while (true) { var node = _lastCommitted; // Memory barrier inside next statement if (!node.Reference()) { return node; } } } void IKeyValueDBInternal.MarkAsUnknown(IEnumerable<uint> fileIds) { MarkAsUnknown(fileIds); } IFileCollectionWithFileInfos IKeyValueDBInternal.FileCollection => FileCollection; bool IKeyValueDBInternal.ContainsValuesAndDoesNotTouchGeneration(uint fileKey, long dontTouchGeneration) { return ContainsValuesAndDoesNotTouchGeneration(fileKey, dontTouchGeneration); } public IFileCollectionWithFileInfos FileCollection => _fileCollection; bool IKeyValueDBInternal.AreAllTransactionsBeforeFinished(long transactionId) { return AreAllTransactionsBeforeFinished(transactionId); } public IRootNodeInternal ReferenceAndGetOldestRoot() { while (true) { var oldestRoot = _lastCommitted; var usedTransaction = _listHead; while (usedTransaction != null) { if (!usedTransaction.ShouldBeDisposed) { if (unchecked(usedTransaction.TransactionId - oldestRoot.TransactionId) < 0) { oldestRoot = usedTransaction; } } usedTransaction = usedTransaction.Next; } // Memory barrier inside next statement if (!oldestRoot.Reference()) { return oldestRoot; } } } public IKeyValueDBTransaction StartTransaction() { while (true) { var node = _lastCommitted; // Memory barrier inside next statement if (!node.Reference()) { var tr = new BTreeKeyValueDBTransaction(this, node, false, false); _transactions.Add(tr, null); return tr; } } } readonly ConditionalWeakTable<IKeyValueDBTransaction, object?> _transactions = new ConditionalWeakTable<IKeyValueDBTransaction, object?>(); public IKeyValueDBTransaction StartReadOnlyTransaction() { while (true) { var node = _lastCommitted; // Memory barrier inside next statement if (!node.Reference()) { var tr = new BTreeKeyValueDBTransaction(this, node, false, true); _transactions.Add(tr, null); return tr; } } } public ValueTask<IKeyValueDBTransaction> StartWritingTransaction() { lock (_writeLock) { if (_writingTransaction == null) { var tr = NewWritingTransactionUnsafe(); _transactions.Add(tr, null); return new ValueTask<IKeyValueDBTransaction>(tr); } var tcs = new TaskCompletionSource<IKeyValueDBTransaction>(); _writeWaitingQueue.Enqueue(tcs); return new ValueTask<IKeyValueDBTransaction>(tcs.Task); } } class FreqStats<K> : RefDictionary<K, uint> where K : IEquatable<K> { public void Inc(K key) { GetOrAddValueRef(key)++; } public void AddToStringBuilder(StringBuilder sb, string name) { sb.Append(name); sb.Append(" => Count\n"); var list = new KeyValuePair<K, uint>[Count]; CopyTo(list, 0); Array.Sort(list, Comparer<KeyValuePair<K, uint>>.Create((a, b) => Comparer<K>.Default.Compare(a.Key, b.Key))); foreach (var t in list) { sb.AppendFormat("{0} => {1}\n", t.Key, t.Value); } } } public string CalcStats() { var oldestRoot = (IRootNode) ReferenceAndGetOldestRoot(); var lastCommitted = (IRootNode) ReferenceAndGetLastCommitted(); try { var sb = new StringBuilder( $"KeyValueCount:{lastCommitted.GetCount()}\nFileCount:{FileCollection.GetCount()}\nFileGeneration:{FileCollection.LastFileGeneration}\n"); sb.Append( $"LastTrId:{lastCommitted.TransactionId},TRL:{lastCommitted.TrLogFileId},ComUlong:{lastCommitted.CommitUlong}\n"); sb.Append( $"OldestTrId:{oldestRoot.TransactionId},TRL:{oldestRoot.TrLogFileId},ComUlong:{oldestRoot.CommitUlong}\n"); foreach (var file in _fileCollection.FileInfos) { sb.AppendFormat("{0} Size:{1} Type:{2} Gen:{3}\n", file.Key, FileCollection.GetSize(file.Key), file.Value.FileType, file.Value.Generation); } return sb.ToString(); } finally { DereferenceRootNodeInternal(oldestRoot); DereferenceRootNodeInternal(lastCommitted); } } public bool Compact(CancellationToken cancellation) { return new Compactor(this, cancellation).Run(); } public void CreateKvi(CancellationToken cancellation) { CreateIndexFile(cancellation, 0); } public IKeyValueDBLogger? Logger { get; set; } public uint CompactorRamLimitInMb { get; set; } public ulong? PreserveHistoryUpToCommitUlong { get { var preserveHistoryUpToCommitUlong = (ulong) Interlocked.Read(ref _preserveHistoryUpToCommitUlong); return preserveHistoryUpToCommitUlong == ulong.MaxValue ? null : (ulong?) preserveHistoryUpToCommitUlong; } set => Interlocked.Exchange(ref _preserveHistoryUpToCommitUlong, (long) (value ?? ulong.MaxValue)); } internal IRootNode MakeWritableTransaction(BTreeKeyValueDBTransaction keyValueDBTransaction, IRootNode btreeRoot) { lock (_writeLock) { if (_writingTransaction != null) throw new BTDBTransactionRetryException("Another writing transaction already running"); if (_lastCommitted != btreeRoot) throw new BTDBTransactionRetryException("Another writing transaction already finished"); _writingTransaction = keyValueDBTransaction; var result = _lastCommitted.CreateWritableTransaction(); btreeRoot.Dereference(); return result; } } internal void CommitFromCompactor(IRootNode root) { lock (_writeLock) { _writingTransaction = null; _lastCommitted.Dereference(); _lastCommitted = root; root.Next = _listHead; _listHead = root; root.Commit(); TryDequeWaiterForWritingTransaction(); } } internal void CommitWritingTransaction(IRootNode root, bool temporaryCloseTransactionLog) { try { var writer = new SpanWriter(_writerWithTransactionLog!); WriteUlongsDiff(ref writer, root, _lastCommitted); var deltaUlong = unchecked(root.CommitUlong - _lastCommitted.CommitUlong); if (deltaUlong != 0) { writer.WriteUInt8((byte) KVCommandType.CommitWithDeltaUlong); writer.WriteVUInt64(deltaUlong); } else { writer.WriteUInt8((byte) KVCommandType.Commit); } writer.Sync(); if (DurableTransactions) { _fileWithTransactionLog!.HardFlush(); } else { _fileWithTransactionLog!.Flush(); } UpdateTransactionLogInBTreeRoot(root); if (temporaryCloseTransactionLog) { writer = new SpanWriter(_writerWithTransactionLog!); writer.WriteUInt8((byte) KVCommandType.TemporaryEndOfFile); writer.Sync(); _fileWithTransactionLog!.Flush(); _fileWithTransactionLog.Truncate(); } lock (_writeLock) { _writingTransaction = null; _lastCommitted.Dereference(); _lastCommitted = root; root.Next = _listHead; _listHead = root; root.Commit(); root = null; TryDequeWaiterForWritingTransaction(); } } finally { root?.Dispose(); } } void WriteUlongsDiff(ref SpanWriter writer, IRootNode newArray, IRootNode oldArray) { var newCount = newArray.GetUlongCount(); var oldCount = oldArray.GetUlongCount(); var maxCount = Math.Max(newCount, oldCount); for (var i = 0u; i < maxCount; i++) { var oldValue = i < oldCount ? oldArray.GetUlong(i) : 0; var newValue = i < newCount ? newArray.GetUlong(i) : 0; var deltaUlong = unchecked(newValue - oldValue); if (deltaUlong != 0) { writer.WriteUInt8((byte) KVCommandType.DeltaUlongs); writer.WriteVUInt32(i); writer.WriteVUInt64(deltaUlong); } } } void UpdateTransactionLogInBTreeRoot(IRootNode root) { if (root.TrLogFileId != _fileIdWithTransactionLog && root.TrLogFileId != 0) { _compactorScheduler?.AdviceRunning(false); } root.TrLogFileId = _fileIdWithTransactionLog; if (_writerWithTransactionLog != null) { root.TrLogOffset = (uint) _writerWithTransactionLog.GetCurrentPositionWithoutWriter(); } else { root.TrLogOffset = 0; } } void TryDequeWaiterForWritingTransaction() { FreeWaitingToDisposeUnsafe(); if (_writeWaitingQueue.Count == 0) return; var tcs = _writeWaitingQueue.Dequeue(); var tr = NewWritingTransactionUnsafe(); _transactions.Add(tr, null); tcs.SetResult(tr); } void TryFreeWaitingToDispose() { var taken = false; try { Monitor.TryEnter(_writeLock, ref taken); if (taken) { FreeWaitingToDisposeUnsafe(); } } finally { if (taken) Monitor.Exit(_writeLock); } } BTreeKeyValueDBTransaction NewWritingTransactionUnsafe() { if (_readOnly) throw new BTDBException("Database opened in readonly mode"); FreeWaitingToDisposeUnsafe(); var newTransactionRoot = _lastCommitted.CreateWritableTransaction(); try { var tr = new BTreeKeyValueDBTransaction(this, newTransactionRoot, true, false); _writingTransaction = tr; return tr; } catch { newTransactionRoot.Dispose(); throw; } } void FreeWaitingToDisposeUnsafe() { while (_listHead is { ShouldBeDisposed: true }) { _listHead.Dispose(); _listHead = _listHead.Next; } var cur = _listHead; var next = cur?.Next; while (next != null) { if (next.ShouldBeDisposed) { cur.Next = next.Next; next.Dispose(); } else { cur = next; } next = next.Next; } } internal void RevertWritingTransaction(IRootNode writtenToTransactionLog, bool nothingWrittenToTransactionLog) { writtenToTransactionLog.Dispose(); if (!nothingWrittenToTransactionLog) { var writer = new SpanWriter(_writerWithTransactionLog!); writer.WriteUInt8((byte) KVCommandType.Rollback); writer.Sync(); _fileWithTransactionLog!.Flush(); lock (_writeLock) { _writingTransaction = null; UpdateTransactionLogInBTreeRoot(_lastCommitted); TryDequeWaiterForWritingTransaction(); } } else { lock (_writeLock) { _writingTransaction = null; TryDequeWaiterForWritingTransaction(); } } } internal void WriteStartTransaction() { if (_fileIdWithTransactionLog == 0) { WriteStartOfNewTransactionLogFile(); } else { if (_writerWithTransactionLog == null) { _fileWithTransactionLog = FileCollection.GetFile(_fileIdWithTransactionLog); _writerWithTransactionLog = _fileWithTransactionLog!.GetAppenderWriter(); } if (_writerWithTransactionLog.GetCurrentPositionWithoutWriter() > MaxTrLogFileSize) { WriteStartOfNewTransactionLogFile(); } } var writer = new SpanWriter(_writerWithTransactionLog!); writer.WriteUInt8((byte) KVCommandType.TransactionStart); writer.WriteByteArrayRaw(MagicStartOfTransaction); writer.Sync(); } void WriteStartOfNewTransactionLogFile() { SpanWriter writer; if (_writerWithTransactionLog != null) { writer = new SpanWriter(_writerWithTransactionLog); writer.WriteUInt8((byte) KVCommandType.EndOfFile); writer.Sync(); _fileWithTransactionLog!.HardFlushTruncateSwitchToReadOnlyMode(); _fileIdWithPreviousTransactionLog = _fileIdWithTransactionLog; } _fileWithTransactionLog = FileCollection.AddFile("trl"); Logger?.TransactionLogCreated(_fileWithTransactionLog.Index); _fileIdWithTransactionLog = _fileWithTransactionLog.Index; var transactionLog = new FileTransactionLog(FileCollection.NextGeneration(), FileCollection.Guid, _fileIdWithPreviousTransactionLog); _writerWithTransactionLog = _fileWithTransactionLog.GetAppenderWriter(); writer = new SpanWriter(_writerWithTransactionLog); transactionLog.WriteHeader(ref writer); writer.Sync(); FileCollection.SetInfo(_fileIdWithTransactionLog, transactionLog); } public void WriteCreateOrUpdateCommand(in ReadOnlySpan<byte> key, in ReadOnlySpan<byte> value, in Span<byte> trueValue) { var trlPos = _writerWithTransactionLog!.GetCurrentPositionWithoutWriter(); if (trlPos > 256 && trlPos + key.Length + 16 + value.Length > MaxTrLogFileSize) { WriteStartOfNewTransactionLogFile(); } var writer = new SpanWriter(_writerWithTransactionLog!); writer.WriteUInt8((byte) KVCommandType.CreateOrUpdate); writer.WriteVInt32(key.Length); writer.WriteVInt32(value.Length); writer.WriteBlock(key); if (value.Length != 0) { if (value.Length <= MaxValueSizeInlineInMemory) { trueValue[4] = (byte) value.Length; Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(trueValue), 0); value.CopyTo(trueValue.Slice(5)); } else { Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(trueValue), _fileIdWithTransactionLog); var valueOfs = (uint) writer.GetCurrentPosition(); Unsafe.WriteUnaligned( ref Unsafe.AddByteOffset(ref MemoryMarshal.GetReference(trueValue), (IntPtr) 4), valueOfs); Unsafe.WriteUnaligned( ref Unsafe.AddByteOffset(ref MemoryMarshal.GetReference(trueValue), (IntPtr) 8), value.Length); } writer.WriteBlock(value); } else { trueValue.Clear(); } writer.Sync(); } public uint CalcValueSize(uint valueFileId, uint valueOfs, int valueSize) { if (valueFileId == 0) { return valueOfs & 0xff; } return (uint) Math.Abs(valueSize); } public ReadOnlySpan<byte> ReadValue(ReadOnlySpan<byte> trueValue) { var valueFileId = MemoryMarshal.Read<uint>(trueValue); if (valueFileId == 0) { var len = trueValue[4]; return trueValue.Slice(5, len); } var valueSize = MemoryMarshal.Read<int>(trueValue.Slice(8)); if (valueSize == 0) return new ReadOnlySpan<byte>(); var valueOfs = MemoryMarshal.Read<uint>(trueValue.Slice(4)); var compressed = false; if (valueSize < 0) { compressed = true; valueSize = -valueSize; } Span<byte> result = new byte[valueSize]; var file = FileCollection.GetFile(valueFileId); if (file == null) throw new BTDBException( $"ReadValue({valueFileId},{valueOfs},{valueSize}) compressed: {compressed} file does not exist in {CalcStats()}"); file.RandomRead(result, valueOfs, false); if (compressed) result = _compression.DecompressValue(result); return result; } public ReadOnlySpan<byte> ReadValue(ReadOnlySpan<byte> trueValue, ref byte buffer, int bufferLength) { var valueFileId = MemoryMarshal.Read<uint>(trueValue); if (valueFileId == 0) { var len = trueValue[4]; var res = trueValue.Slice(5, len); if (len <= bufferLength) { Unsafe.CopyBlockUnaligned(ref buffer, ref MemoryMarshal.GetReference(res), len); return MemoryMarshal.CreateReadOnlySpan(ref buffer, len); } return res.ToArray(); } var valueSize = MemoryMarshal.Read<int>(trueValue[8..]); if (valueSize == 0) return new ReadOnlySpan<byte>(); var valueOfs = MemoryMarshal.Read<uint>(trueValue[4..]); var compressed = false; if (valueSize < 0) { compressed = true; valueSize = -valueSize; } Span<byte> result = bufferLength < valueSize ? new byte[valueSize] : MemoryMarshal.CreateSpan(ref buffer, valueSize); var file = FileCollection.GetFile(valueFileId); if (file == null) throw new BTDBException( $"ReadValue({valueFileId},{valueOfs},{valueSize}) compressed: {compressed} file does not exist in {CalcStats()}"); file.RandomRead(result, valueOfs, false); if (compressed) result = _compression.DecompressValue(result); return result; } public void WriteEraseOneCommand(in ReadOnlySpan<byte> key) { if (_writerWithTransactionLog!.GetCurrentPositionWithoutWriter() > MaxTrLogFileSize) { WriteStartOfNewTransactionLogFile(); } var writer = new SpanWriter(_writerWithTransactionLog!); writer.WriteUInt8((byte) KVCommandType.EraseOne); writer.WriteVInt32(key.Length); writer.WriteBlock(key); writer.Sync(); } public void WriteEraseRangeCommand(in ReadOnlySpan<byte> firstKey, in ReadOnlySpan<byte> secondKey) { if (_writerWithTransactionLog!.GetCurrentPositionWithoutWriter() > MaxTrLogFileSize) { WriteStartOfNewTransactionLogFile(); } var writer = new SpanWriter(_writerWithTransactionLog!); writer.WriteUInt8((byte) KVCommandType.EraseRange); writer.WriteVInt32(firstKey.Length); writer.WriteVInt32(secondKey.Length); writer.WriteBlock(firstKey); writer.WriteBlock(secondKey); writer.Sync(); } uint CreateKeyIndexFile(IRootNode root, CancellationToken cancellation, bool fullSpeed) { var bytesPerSecondLimiter = new BytesPerSecondLimiter(fullSpeed ? 0 : CompactorWriteBytesPerSecondLimit); var file = FileCollection.AddFile("kvi"); var writerController = file.GetAppenderWriter(); var writer = new SpanWriter(writerController); var keyCount = root.GetCount(); if (root.TrLogFileId != 0) FileCollection.ConcurentTemporaryTruncate(root.TrLogFileId, root.TrLogOffset); var keyIndex = new FileKeyIndex(FileCollection.NextGeneration(), FileCollection.Guid, root.TrLogFileId, root.TrLogOffset, keyCount, root.CommitUlong, KeyIndexCompression.None, root.UlongsArray); keyIndex.WriteHeader(ref writer); var usedFileIds = new HashSet<uint>(); if (keyCount > 0) { var keyValueIterateCtx = new KeyValueIterateCtx {CancellationToken = cancellation, Writer = writer}; root.KeyValueIterate(ref keyValueIterateCtx, (ref KeyValueIterateCtx ctx) => { ref var writerReference = ref ctx.Writer; var memberValue = ctx.CurrentValue; writerReference.WriteVUInt32(ctx.PreviousCurrentCommonLength); writerReference.WriteVUInt32((uint) (ctx.CurrentPrefix.Length + ctx.CurrentSuffix.Length - ctx.PreviousCurrentCommonLength)); if (ctx.CurrentPrefix.Length <= ctx.PreviousCurrentCommonLength) { writerReference.WriteBlock( ctx.CurrentSuffix.Slice((int) ctx.PreviousCurrentCommonLength - ctx.CurrentPrefix.Length)); } else { writerReference.WriteBlock(ctx.CurrentPrefix.Slice((int) ctx.PreviousCurrentCommonLength)); writerReference.WriteBlock(ctx.CurrentSuffix); } var vFileId = MemoryMarshal.Read<uint>(memberValue); if (vFileId > 0) usedFileIds.Add(vFileId); writerReference.WriteVUInt32(vFileId); if (vFileId == 0) { uint valueOfs; int valueSize; var inlineValueBuf = memberValue[5..]; var valueLen = memberValue[4]; switch (valueLen) { case 0: valueOfs = 0; valueSize = 0; break; case 1: valueOfs = 0; valueSize = 0x1000000 | (inlineValueBuf[0] << 16); break; case 2: valueOfs = 0; valueSize = 0x2000000 | (inlineValueBuf[0] << 16) | (inlineValueBuf[1] << 8); break; case 3: valueOfs = 0; valueSize = 0x3000000 | (inlineValueBuf[0] << 16) | (inlineValueBuf[1] << 8) | inlineValueBuf[2]; break; case 4: valueOfs = inlineValueBuf[3]; valueSize = 0x4000000 | (inlineValueBuf[0] << 16) | (inlineValueBuf[1] << 8) | inlineValueBuf[2]; break; case 5: valueOfs = inlineValueBuf[3] | ((uint) inlineValueBuf[4] << 8); valueSize = 0x5000000 | (inlineValueBuf[0] << 16) | (inlineValueBuf[1] << 8) | inlineValueBuf[2]; break; case 6: valueOfs = inlineValueBuf[3] | ((uint) inlineValueBuf[4] << 8) | ((uint) inlineValueBuf[5] << 16); valueSize = 0x6000000 | (inlineValueBuf[0] << 16) | (inlineValueBuf[1] << 8) | inlineValueBuf[2]; break; case 7: valueOfs = inlineValueBuf[3] | ((uint) inlineValueBuf[4] << 8) | ((uint) inlineValueBuf[5] << 16) | ((uint) inlineValueBuf[6] << 24); valueSize = 0x7000000 | (inlineValueBuf[0] << 16) | (inlineValueBuf[1] << 8) | inlineValueBuf[2]; break; default: throw new ArgumentOutOfRangeException(); } writerReference.WriteVUInt32(valueOfs); writerReference.WriteVInt32(valueSize); } else { var valueOfs = MemoryMarshal.Read<uint>(memberValue.Slice(4)); var valueSize = MemoryMarshal.Read<int>(memberValue.Slice(8)); writerReference.WriteVUInt32(valueOfs); writerReference.WriteVInt32(valueSize); } bytesPerSecondLimiter.Limit((ulong) writerReference.GetCurrentPosition()); }); writer = keyValueIterateCtx.Writer; } writer.Sync(); file.HardFlush(); writer = new SpanWriter(writerController); writer.WriteInt32(EndOfIndexFileMarker); writer.Sync(); file.HardFlush(); file.Truncate(); var trlGeneration = GetGeneration(keyIndex.TrLogFileId); keyIndex.UsedFilesInOlderGenerations = usedFileIds.Select(GetGenerationIgnoreMissing) .Where(gen => gen < trlGeneration).OrderBy(a => a).ToArray(); FileCollection.SetInfo(file.Index, keyIndex); Logger?.KeyValueIndexCreated(file.Index, keyIndex.KeyValueCount, file.GetSize(), TimeSpan.FromMilliseconds(bytesPerSecondLimiter.TotalTimeInMs)); return file.Index; } internal bool ContainsValuesAndDoesNotTouchGeneration(uint fileId, long dontTouchGeneration) { var info = FileCollection.FileInfoByIdx(fileId); if (info == null) return false; if (info.Generation >= dontTouchGeneration) return false; return info.FileType == KVFileType.TransactionLog || info.FileType == KVFileType.PureValues; } internal ISpanWriter StartPureValuesFile(out uint fileId) { var fId = FileCollection.AddFile("pvl"); fileId = fId.Index; var pureValues = new FilePureValues(FileCollection.NextGeneration(), FileCollection.Guid); var writerController = fId.GetAppenderWriter(); FileCollection.SetInfo(fId.Index, pureValues); var writer = new SpanWriter(writerController); pureValues.WriteHeader(ref writer); writer.Sync(); return writerController; } long ReplaceBTreeValues(CancellationToken cancellation, Dictionary<ulong, ulong> newPositionMap) { byte[] restartKey = null; while (true) { var iterationTimeOut = DateTime.UtcNow + TimeSpan.FromMilliseconds(50); using (var tr = StartWritingTransaction().Result) { var newRoot = ((BTreeKeyValueDBTransaction) tr).BTreeRoot; var cursor = newRoot!.CreateCursor(); if (restartKey != null) { cursor.Find(restartKey); cursor.MovePrevious(); } else { cursor.MoveNext(); } var ctx = default(ValueReplacerCtx); ctx._operationTimeout = iterationTimeOut; ctx._interrupted = false; ctx._positionMap = newPositionMap; ctx._cancellation = cancellation; cursor.ValueReplacer(ref ctx); restartKey = ctx._interruptedKey; cancellation.ThrowIfCancellationRequested(); ((BTreeKeyValueDBTransaction) tr).CommitFromCompactor(); if (!ctx._interrupted) { return newRoot.TransactionId; } } Thread.Sleep(10); } } long IKeyValueDBInternal.GetGeneration(uint fileId) { return GetGeneration(fileId); } internal void MarkAsUnknown(IEnumerable<uint> fileIds) { foreach (var fileId in fileIds) { MarkFileForRemoval(fileId); } } internal long GetGeneration(uint fileId) { if (fileId == 0) return -1; var fileInfo = FileCollection.FileInfoByIdx(fileId); if (fileInfo == null) { throw new ArgumentOutOfRangeException(nameof(fileId)); } return fileInfo.Generation; } internal long GetGenerationIgnoreMissing(uint fileId) { if (fileId == 0) return -1; var fileInfo = FileCollection.FileInfoByIdx(fileId); if (fileInfo == null) { return -1; } return fileInfo.Generation; } internal bool AreAllTransactionsBeforeFinished(long transactionId) { var usedTransaction = _listHead; while (usedTransaction != null) { if (!usedTransaction.ShouldBeDisposed && usedTransaction.TransactionId - transactionId < 0) { return false; } usedTransaction = usedTransaction.Next; } return true; } internal ulong DistanceFromLastKeyIndex(IRootNode root) { var keyIndex = FileCollection.FileInfos.Where(p => p.Value.FileType == KVFileType.KeyIndex) .Select(p => (IKeyIndex) p.Value).FirstOrDefault(); if (keyIndex == null) { if (FileCollection.FileInfos.Count(p => p.Value.SubDBId == 0) > 1) return ulong.MaxValue; return root.TrLogOffset; } if (root.TrLogFileId != keyIndex.TrLogFileId) return ulong.MaxValue; return root.TrLogOffset - keyIndex.TrLogOffset; } public T? GetSubDB<T>(long id) where T : class { if (_subDBs.TryGetValue(id, out var subDB)) { if (!(subDB is T db)) throw new ArgumentException($"SubDB of id {id} is not type {typeof(T).FullName}"); return db; } if (typeof(T) == typeof(IChunkStorage)) { subDB = new ChunkStorageInKV(id, _fileCollection, MaxTrLogFileSize); } _subDBs.Add(id, subDB); return (T) subDB; } public void DereferenceRoot(IRootNode currentRoot) { if (currentRoot.Dereference()) { TryFreeWaitingToDispose(); } } public void DereferenceRootNodeInternal(IRootNodeInternal root) { DereferenceRoot((IRootNode) root); } } }
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 2009, 2010 Oracle and/or its affiliates. All rights reserved. * */ using System; using System.Collections.Generic; using System.Text; using BerkeleyDB.Internal; namespace BerkeleyDB { /// <summary> /// A class representing a SecondaryBTreeDatabase. The Btree format is a /// representation of a sorted, balanced tree structure. /// </summary> public class SecondaryBTreeDatabase : SecondaryDatabase { private EntryComparisonDelegate compareHandler; private EntryComparisonDelegate prefixCompareHandler; private EntryComparisonDelegate dupCompareHandler; private BDB_CompareDelegate doCompareRef; private BDB_CompareDelegate doPrefixCompareRef; private BDB_CompareDelegate doDupCompareRef; #region Constructors internal SecondaryBTreeDatabase(DatabaseEnvironment env, uint flags) : base(env, flags) { } private void Config(SecondaryBTreeDatabaseConfig cfg) { base.Config((SecondaryDatabaseConfig)cfg); db.set_flags(cfg.flags); if (cfg.Compare != null) Compare = cfg.Compare; if (cfg.PrefixCompare != null) PrefixCompare = cfg.PrefixCompare; if (cfg.DuplicateCompare != null) DupCompare = cfg.DuplicateCompare; if (cfg.minkeysIsSet) db.set_bt_minkey(cfg.MinKeysPerPage); } /// <summary> /// Instantiate a new SecondaryBTreeDatabase object, open the /// database represented by <paramref name="Filename"/> and associate /// the database with the /// <see cref="SecondaryDatabaseConfig.Primary">primary index</see>. /// </summary> /// <remarks> /// <para> /// If <paramref name="Filename"/> is null, the database is strictly /// temporary and cannot be opened by any other thread of control, thus /// the database can only be accessed by sharing the single database /// object that created it, in circumstances where doing so is safe. /// </para> /// <para> /// If <see cref="DatabaseConfig.AutoCommit"/> is set, the operation /// will be implicitly transaction protected. Note that transactionally /// protected operations on a datbase object requires the object itself /// be transactionally protected during its open. /// </para> /// </remarks> /// <param name="Filename"> /// The name of an underlying file that will be used to back the /// database. In-memory databases never intended to be preserved on disk /// may be created by setting this parameter to null. /// </param> /// <param name="cfg">The database's configuration</param> /// <returns>A new, open database object</returns> public static SecondaryBTreeDatabase Open( string Filename, SecondaryBTreeDatabaseConfig cfg) { return Open(Filename, null, cfg, null); } /// <summary> /// Instantiate a new SecondaryBTreeDatabase object, open the /// database represented by <paramref name="Filename"/> and associate /// the database with the /// <see cref="SecondaryDatabaseConfig.Primary">primary index</see>. /// </summary> /// <remarks> /// <para> /// If both <paramref name="Filename"/> and /// <paramref name="DatabaseName"/> are null, the database is strictly /// temporary and cannot be opened by any other thread of control, thus /// the database can only be accessed by sharing the single database /// object that created it, in circumstances where doing so is safe. If /// <paramref name="Filename"/> is null and /// <paramref name="DatabaseName"/> is non-null, the database can be /// opened by other threads of control and will be replicated to client /// sites in any replication group. /// </para> /// <para> /// If <see cref="DatabaseConfig.AutoCommit"/> is set, the operation /// will be implicitly transaction protected. Note that transactionally /// protected operations on a datbase object requires the object itself /// be transactionally protected during its open. /// </para> /// </remarks> /// <param name="Filename"> /// The name of an underlying file that will be used to back the /// database. In-memory databases never intended to be preserved on disk /// may be created by setting this parameter to null. /// </param> /// <param name="DatabaseName"> /// This parameter allows applications to have multiple databases in a /// single file. Although no DatabaseName needs to be specified, it is /// an error to attempt to open a second database in a file that was not /// initially created using a database name. /// </param> /// <param name="cfg">The database's configuration</param> /// <returns>A new, open database object</returns> public static SecondaryBTreeDatabase Open(string Filename, string DatabaseName, SecondaryBTreeDatabaseConfig cfg) { return Open(Filename, DatabaseName, cfg, null); } /// <summary> /// Instantiate a new SecondaryBTreeDatabase object, open the /// database represented by <paramref name="Filename"/> and associate /// the database with the /// <see cref="SecondaryDatabaseConfig.Primary">primary index</see>. /// </summary> /// <remarks> /// <para> /// If <paramref name="Filename"/> is null, the database is strictly /// temporary and cannot be opened by any other thread of control, thus /// the database can only be accessed by sharing the single database /// object that created it, in circumstances where doing so is safe. /// </para> /// <para> /// If <paramref name="txn"/> is null, but /// <see cref="DatabaseConfig.AutoCommit"/> is set, the operation will /// be implicitly transaction protected. Note that transactionally /// protected operations on a datbase object requires the object itself /// be transactionally protected during its open. Also note that the /// transaction must be committed before the object is closed. /// </para> /// </remarks> /// <param name="Filename"> /// The name of an underlying file that will be used to back the /// database. In-memory databases never intended to be preserved on disk /// may be created by setting this parameter to null. /// </param> /// <param name="cfg">The database's configuration</param> /// <param name="txn"> /// If the operation is part of an application-specified transaction, /// <paramref name="txn"/> is a Transaction object returned from /// <see cref="DatabaseEnvironment.BeginTransaction"/>; if /// the operation is part of a Berkeley DB Concurrent Data Store group, /// <paramref name="txn"/> is a handle returned from /// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null. /// </param> /// <returns>A new, open database object</returns> public static SecondaryBTreeDatabase Open(string Filename, SecondaryBTreeDatabaseConfig cfg, Transaction txn) { return Open(Filename, null, cfg, txn); } /// <summary> /// Instantiate a new SecondaryBTreeDatabase object, open the /// database represented by <paramref name="Filename"/> and associate /// the database with the /// <see cref="SecondaryDatabaseConfig.Primary">primary index</see>. /// </summary> /// <remarks> /// <para> /// If both <paramref name="Filename"/> and /// <paramref name="DatabaseName"/> are null, the database is strictly /// temporary and cannot be opened by any other thread of control, thus /// the database can only be accessed by sharing the single database /// object that created it, in circumstances where doing so is safe. If /// <paramref name="Filename"/> is null and /// <paramref name="DatabaseName"/> is non-null, the database can be /// opened by other threads of control and will be replicated to client /// sites in any replication group. /// </para> /// <para> /// If <paramref name="txn"/> is null, but /// <see cref="DatabaseConfig.AutoCommit"/> is set, the operation will /// be implicitly transaction protected. Note that transactionally /// protected operations on a datbase object requires the object itself /// be transactionally protected during its open. Also note that the /// transaction must be committed before the object is closed. /// </para> /// </remarks> /// <param name="Filename"> /// The name of an underlying file that will be used to back the /// database. In-memory databases never intended to be preserved on disk /// may be created by setting this parameter to null. /// </param> /// <param name="DatabaseName"> /// This parameter allows applications to have multiple databases in a /// single file. Although no DatabaseName needs to be specified, it is /// an error to attempt to open a second database in a file that was not /// initially created using a database name. /// </param> /// <param name="cfg">The database's configuration</param> /// <param name="txn"> /// If the operation is part of an application-specified transaction, /// <paramref name="txn"/> is a Transaction object returned from /// <see cref="DatabaseEnvironment.BeginTransaction"/>; if /// the operation is part of a Berkeley DB Concurrent Data Store group, /// <paramref name="txn"/> is a handle returned from /// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null. /// </param> /// <returns>A new, open database object</returns> public static SecondaryBTreeDatabase Open( string Filename, string DatabaseName, SecondaryBTreeDatabaseConfig cfg, Transaction txn) { SecondaryBTreeDatabase ret = new SecondaryBTreeDatabase(cfg.Env, 0); ret.Config(cfg); ret.db.open(Transaction.getDB_TXN(txn), Filename, DatabaseName, cfg.DbType.getDBTYPE(), cfg.openFlags, 0); ret.isOpen = true; ret.doAssocRef = new BDB_AssociateDelegate( SecondaryDatabase.doAssociate); cfg.Primary.db.associate(Transaction.getDB_TXN(null), ret.db, ret.doAssocRef, cfg.assocFlags); if (cfg.ForeignKeyDatabase != null) { if (cfg.OnForeignKeyDelete == ForeignKeyDeleteAction.NULLIFY) ret.doNullifyRef = new BDB_AssociateForeignDelegate(doNullify); else ret.doNullifyRef = null; cfg.ForeignKeyDatabase.db.associate_foreign( ret.db, ret.doNullifyRef, cfg.foreignFlags); } return ret; } #endregion Constructors #region Callbacks private static int doDupCompare( IntPtr dbp, IntPtr dbt1p, IntPtr dbt2p) { DB db = new DB(dbp, false); DBT dbt1 = new DBT(dbt1p, false); DBT dbt2 = new DBT(dbt2p, false); return ((SecondaryBTreeDatabase)(db.api_internal)).DupCompare( DatabaseEntry.fromDBT(dbt1), DatabaseEntry.fromDBT(dbt2)); } private static int doCompare(IntPtr dbp, IntPtr dbtp1, IntPtr dbtp2) { DB db = new DB(dbp, false); DBT dbt1 = new DBT(dbtp1, false); DBT dbt2 = new DBT(dbtp2, false); SecondaryBTreeDatabase tmp = (SecondaryBTreeDatabase)db.api_internal; return tmp.compareHandler( DatabaseEntry.fromDBT(dbt1), DatabaseEntry.fromDBT(dbt2)); } private static int doPrefixCompare( IntPtr dbp, IntPtr dbtp1, IntPtr dbtp2) { DB db = new DB(dbp, false); DBT dbt1 = new DBT(dbtp1, false); DBT dbt2 = new DBT(dbtp2, false); SecondaryBTreeDatabase tmp = (SecondaryBTreeDatabase)db.api_internal; return tmp.prefixCompareHandler( DatabaseEntry.fromDBT(dbt1), DatabaseEntry.fromDBT(dbt2)); } #endregion Callbacks #region Properties // Sorted alpha by property name /// <summary> /// The Btree key comparison function. The comparison function is called /// whenever it is necessary to compare a key specified by the /// application with a key currently stored in the tree. /// </summary> public EntryComparisonDelegate Compare { get { return compareHandler; } private set { if (value == null) db.set_bt_compare(null); else if (compareHandler == null) { if (doCompareRef == null) doCompareRef = new BDB_CompareDelegate(doCompare); db.set_bt_compare(doCompare); } compareHandler = value; } } /// <summary> /// The duplicate data item comparison function. /// </summary> public EntryComparisonDelegate DupCompare { get { return dupCompareHandler; } private set { /* Cannot be called after open. */ if (value == null) db.set_dup_compare(null); else if (dupCompareHandler == null) { if (doDupCompareRef == null) doDupCompareRef = new BDB_CompareDelegate(doDupCompare); db.set_dup_compare(doDupCompareRef); } dupCompareHandler = value; } } /// <summary> /// Whether the insertion of duplicate data items in the database is /// permitted, and whether duplicates items are sorted. /// </summary> public DuplicatesPolicy Duplicates { get { uint flags = 0; db.get_flags(ref flags); if ((flags & DbConstants.DB_DUPSORT) != 0) return DuplicatesPolicy.SORTED; else if ((flags & DbConstants.DB_DUP) != 0) return DuplicatesPolicy.UNSORTED; else return DuplicatesPolicy.NONE; } } /// <summary> /// The minimum number of key/data pairs intended to be stored on any /// single Btree leaf page. /// </summary> public uint MinKeysPerPage { get { uint ret = 0; db.get_bt_minkey(ref ret); return ret; } } /// <summary> /// If false, empty pages will not be coalesced into higher-level pages. /// </summary> public bool ReverseSplit { get { uint flags = 0; db.get_flags(ref flags); return (flags & DbConstants.DB_REVSPLITOFF) == 0; } } /// <summary> /// The Btree prefix function. The prefix function is used to determine /// the amount by which keys stored on the Btree internal pages can be /// safely truncated without losing their uniqueness. /// </summary> public EntryComparisonDelegate PrefixCompare { get { return prefixCompareHandler; } private set { if (value == null) db.set_bt_prefix(null); else if (prefixCompareHandler == null) { if (doPrefixCompareRef == null) doPrefixCompareRef = new BDB_CompareDelegate(doPrefixCompare); db.set_bt_prefix(doPrefixCompareRef); } prefixCompareHandler = value; } } /// <summary> /// If true, this object supports retrieval from the Btree using record /// numbers. /// </summary> public bool RecordNumbers { get { uint flags = 0; db.get_flags(ref flags); return (flags & DbConstants.DB_RECNUM) != 0; } } #endregion Properties } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Reflection; using System.Text; using System.Xml; using Orleans.GrainDirectory; using Orleans.Providers; using Orleans.Storage; using Orleans.Streams; using Orleans.LogConsistency; namespace Orleans.Runtime.Configuration { // helper utility class to handle default vs. explicitly set config value. [Serializable] internal class ConfigValue<T> { public T Value; public bool IsDefaultValue; public ConfigValue(T val, bool isDefaultValue) { Value = val; IsDefaultValue = isDefaultValue; } } /// <summary> /// Data object holding Silo global configuration parameters. /// </summary> [Serializable] public class GlobalConfiguration : MessagingConfiguration { /// <summary> /// Liveness configuration that controls the type of the liveness protocol that silo use for membership. /// </summary> public enum LivenessProviderType { /// <summary>Default value to allow discrimination of override values.</summary> NotSpecified, /// <summary>Grain is used to store membership information. /// This option is not reliable and thus should only be used in local development setting.</summary> MembershipTableGrain, /// <summary>AzureTable is used to store membership information. /// This option can be used in production.</summary> AzureTable, /// <summary>SQL Server is used to store membership information. /// This option can be used in production.</summary> SqlServer, /// <summary>Apache ZooKeeper is used to store membership information. /// This option can be used in production.</summary> ZooKeeper, /// <summary>Use custom provider from third-party assembly</summary> Custom } /// <summary> /// Reminders configuration that controls the type of the protocol that silo use to implement Reminders. /// </summary> public enum ReminderServiceProviderType { /// <summary>Default value to allow discrimination of override values.</summary> NotSpecified, /// <summary>Grain is used to store reminders information. /// This option is not reliable and thus should only be used in local development setting.</summary> ReminderTableGrain, /// <summary>AzureTable is used to store reminders information. /// This option can be used in production.</summary> AzureTable, /// <summary>SQL Server is used to store reminders information. /// This option can be used in production.</summary> SqlServer, /// <summary>Used for benchmarking; it simply delays for a specified delay during each operation.</summary> MockTable, /// <summary>Reminder Service is disabled.</summary> Disabled, /// <summary>Use custom Reminder Service from third-party assembly</summary> Custom } /// <summary> /// Configuration for Gossip Channels /// </summary> public enum GossipChannelType { /// <summary>Default value to allow discrimination of override values.</summary> NotSpecified, /// <summary>An Azure Table serving as a channel. </summary> AzureTable, } /// <summary> /// Gossip channel configuration. /// </summary> [Serializable] public class GossipChannelConfiguration { /// <summary>Gets or sets the gossip channel type.</summary> public GossipChannelType ChannelType { get; set; } /// <summary>Gets or sets the credential information used by the channel implementation.</summary> public string ConnectionString { get; set; } } /// <summary> /// Configuration type that controls the type of the grain directory caching algorithm that silo use. /// </summary> public enum DirectoryCachingStrategyType { /// <summary>Don't cache.</summary> None, /// <summary>Standard fixed-size LRU.</summary> LRU, /// <summary>Adaptive caching with fixed maximum size and refresh. This option should be used in production.</summary> Adaptive } public ApplicationConfiguration Application { get; private set; } /// <summary> /// SeedNodes are only used in local development setting with LivenessProviderType.MembershipTableGrain /// SeedNodes are never used in production. /// </summary> public IList<IPEndPoint> SeedNodes { get; private set; } /// <summary> /// The subnet on which the silos run. /// This option should only be used when running on multi-homed cluster. It should not be used when running in Azure. /// </summary> public byte[] Subnet { get; set; } /// <summary> /// Determines if primary node is required to be configured as a seed node. /// True if LivenessType is set to MembershipTableGrain, false otherwise. /// </summary> public bool PrimaryNodeIsRequired { get { return LivenessType == LivenessProviderType.MembershipTableGrain; } } /// <summary> /// Global switch to disable silo liveness protocol (should be used only for testing). /// The LivenessEnabled attribute, if provided and set to "false", suppresses liveness enforcement. /// If a silo is suspected to be dead, but this attribute is set to "false", the suspicions will not propagated to the system and enforced, /// This parameter is intended for use only for testing and troubleshooting. /// In production, liveness should always be enabled. /// Default is true (eanabled) /// </summary> public bool LivenessEnabled { get; set; } /// <summary> /// The number of seconds to periodically probe other silos for their liveness or for the silo to send "I am alive" heartbeat messages about itself. /// </summary> public TimeSpan ProbeTimeout { get; set; } /// <summary> /// The number of seconds to periodically fetch updates from the membership table. /// </summary> public TimeSpan TableRefreshTimeout { get; set; } /// <summary> /// Expiration time in seconds for death vote in the membership table. /// </summary> public TimeSpan DeathVoteExpirationTimeout { get; set; } /// <summary> /// The number of seconds to periodically write in the membership table that this silo is alive. Used ony for diagnostics. /// </summary> public TimeSpan IAmAliveTablePublishTimeout { get; set; } /// <summary> /// The number of seconds to attempt to join a cluster of silos before giving up. /// </summary> public TimeSpan MaxJoinAttemptTime { get; set; } /// <summary> /// The number of seconds to refresh the cluster grain interface map /// </summary> public TimeSpan TypeMapRefreshInterval { get; set; } internal ConfigValue<int> ExpectedClusterSizeConfigValue { get; set; } /// <summary> /// The expected size of a cluster. Need not be very accurate, can be an overestimate. /// </summary> public int ExpectedClusterSize { get { return ExpectedClusterSizeConfigValue.Value; } set { ExpectedClusterSizeConfigValue = new ConfigValue<int>(value, false); } } /// <summary> /// The number of missed "I am alive" heartbeat messages from a silo or number of un-replied probes that lead to suspecting this silo as dead. /// </summary> public int NumMissedProbesLimit { get; set; } /// <summary> /// The number of silos each silo probes for liveness. /// </summary> public int NumProbedSilos { get; set; } /// <summary> /// The number of non-expired votes that are needed to declare some silo as dead (should be at most NumMissedProbesLimit) /// </summary> public int NumVotesForDeathDeclaration { get; set; } /// <summary> /// The number of missed "I am alive" updates in the table from a silo that causes warning to be logged. Does not impact the liveness protocol. /// </summary> public int NumMissedTableIAmAliveLimit { get; set; } /// <summary> /// Whether to use the gossip optimization to speed up spreading liveness information. /// </summary> public bool UseLivenessGossip { get; set; } /// <summary> /// Whether new silo that joins the cluster has to validate the initial connectivity with all other Active silos. /// </summary> public bool ValidateInitialConnectivity { get; set; } /// <summary> /// Service Id. /// </summary> public Guid ServiceId { get; set; } /// <summary> /// Deployment Id. /// </summary> public string DeploymentId { get; set; } #region MultiClusterNetwork /// <summary> /// Whether this cluster is configured to be part of a multicluster network /// </summary> public bool HasMultiClusterNetwork { get { return !(string.IsNullOrEmpty(ClusterId)); } } /// <summary> /// Cluster id (one per deployment, unique across all the deployments/clusters) /// </summary> public string ClusterId { get; set; } /// <summary> ///A list of cluster ids, to be used if no multicluster configuration is found in gossip channels. /// </summary> public IReadOnlyList<string> DefaultMultiCluster { get; set; } /// <summary> /// The maximum number of silos per cluster should be designated to serve as gateways. /// </summary> public int MaxMultiClusterGateways { get; set; } /// <summary> /// The time between background gossips. /// </summary> public TimeSpan BackgroundGossipInterval { get; set; } /// <summary> /// Whether to use the global single instance protocol as the default /// multicluster registration strategy. /// </summary> public bool UseGlobalSingleInstanceByDefault { get; set; } /// <summary> /// The number of quick retries before going into DOUBTFUL state. /// </summary> public int GlobalSingleInstanceNumberRetries { get; set; } /// <summary> /// The time between the slow retries for DOUBTFUL activations. /// </summary> public TimeSpan GlobalSingleInstanceRetryInterval { get; set; } /// <summary> /// A list of connection strings for gossip channels. /// </summary> public IReadOnlyList<GossipChannelConfiguration> GossipChannels { get; set; } #endregion /// <summary> /// Connection string for the underlying data provider for liveness and reminders. eg. Azure Storage, ZooKeeper, SQL Server, ect. /// In order to override this value for reminders set <see cref="DataConnectionStringForReminders"/> /// </summary> public string DataConnectionString { get; set; } /// <summary> /// When using ADO, identifies the underlying data provider for liveness and reminders. This three-part naming syntax is also used /// when creating a new factory and for identifying the provider in an application configuration file so that the provider name, /// along with its associated connection string, can be retrieved at run time. https://msdn.microsoft.com/en-us/library/dd0w4a2z%28v=vs.110%29.aspx /// In order to override this value for reminders set <see cref="AdoInvariantForReminders"/> /// </summary> public string AdoInvariant { get; set; } /// <summary> /// Set this property to override <see cref="DataConnectionString"/> for reminders. /// </summary> public string DataConnectionStringForReminders { get { return string.IsNullOrWhiteSpace(dataConnectionStringForReminders) ? DataConnectionString : dataConnectionStringForReminders; } set { dataConnectionStringForReminders = value; } } /// <summary> /// Set this property to override <see cref="AdoInvariant"/> for reminders. /// </summary> public string AdoInvariantForReminders { get { return string.IsNullOrWhiteSpace(adoInvariantForReminders) ? AdoInvariant : adoInvariantForReminders; } set { adoInvariantForReminders = value; } } internal TimeSpan CollectionQuantum { get; set; } /// <summary> /// Specifies the maximum time that a request can take before the activation is reported as "blocked" /// </summary> public TimeSpan MaxRequestProcessingTime { get; set; } /// <summary> /// The CacheSize attribute specifies the maximum number of grains to cache directory information for. /// </summary> public int CacheSize { get; set; } /// <summary> /// The InitialTTL attribute specifies the initial (minimum) time, in seconds, to keep a cache entry before revalidating. /// </summary> public TimeSpan InitialCacheTTL { get; set; } /// <summary> /// The MaximumTTL attribute specifies the maximum time, in seconds, to keep a cache entry before revalidating. /// </summary> public TimeSpan MaximumCacheTTL { get; set; } /// <summary> /// The TTLExtensionFactor attribute specifies the factor by which cache entry TTLs should be extended when they are found to be stable. /// </summary> public double CacheTTLExtensionFactor { get; set; } /// <summary> /// Retry count for Azure Table operations. /// </summary> public int MaxStorageBusyRetries { get; private set; } /// <summary> /// The DirectoryCachingStrategy attribute specifies the caching strategy to use. /// The options are None, which means don't cache directory entries locally; /// LRU, which indicates that a standard fixed-size least recently used strategy should be used; and /// Adaptive, which indicates that an adaptive strategy with a fixed maximum size should be used. /// The Adaptive strategy is used by default. /// </summary> public DirectoryCachingStrategyType DirectoryCachingStrategy { get; set; } public bool UseVirtualBucketsConsistentRing { get; set; } public int NumVirtualBucketsConsistentRing { get; set; } /// <summary> /// The LivenessType attribute controls the liveness method used for silo reliability. /// </summary> private LivenessProviderType livenessServiceType; public LivenessProviderType LivenessType { get { return livenessServiceType; } set { if (value == LivenessProviderType.NotSpecified) throw new ArgumentException("Cannot set LivenessType to " + LivenessProviderType.NotSpecified, "LivenessType"); livenessServiceType = value; } } /// <summary> /// Assembly to use for custom MembershipTable implementation /// </summary> public string MembershipTableAssembly { get; set; } /// <summary> /// Assembly to use for custom ReminderTable implementation /// </summary> public string ReminderTableAssembly { get; set; } /// <summary> /// The ReminderServiceType attribute controls the type of the reminder service implementation used by silos. /// </summary> private ReminderServiceProviderType reminderServiceType; public ReminderServiceProviderType ReminderServiceType { get { return reminderServiceType; } set { SetReminderServiceType(value); } } // It's a separate function so we can clearly see when we set the value. // With property you can't seaprate getter from setter in intellicense. internal void SetReminderServiceType(ReminderServiceProviderType reminderType) { if (reminderType == ReminderServiceProviderType.NotSpecified) throw new ArgumentException("Cannot set ReminderServiceType to " + ReminderServiceProviderType.NotSpecified, "ReminderServiceType"); reminderServiceType = reminderType; } public TimeSpan MockReminderTableTimeout { get; set; } internal bool UseMockReminderTable; /// <summary> /// Configuration for various runtime providers. /// </summary> public IDictionary<string, ProviderCategoryConfiguration> ProviderConfigurations { get; set; } /// <summary> /// Configuration for grain services. /// </summary> public GrainServiceConfigurations GrainServiceConfigurations { get; set; } /// <summary> /// The time span between when we have added an entry for an activation to the grain directory and when we are allowed /// to conditionally remove that entry. /// Conditional deregistration is used for lazy clean-up of activations whose prompt deregistration failed for some reason (e.g., message failure). /// This should always be at least one minute, since we compare the times on the directory partition, so message delays and clcks skues have /// to be allowed. /// </summary> public TimeSpan DirectoryLazyDeregistrationDelay { get; set; } public TimeSpan ClientRegistrationRefresh { get; set; } internal bool PerformDeadlockDetection { get; set; } public string DefaultPlacementStrategy { get; set; } public TimeSpan DeploymentLoadPublisherRefreshTime { get; set; } public int ActivationCountBasedPlacementChooseOutOf { get; set; } public bool AssumeHomogenousSilosForTesting { get; set; } /// <summary> /// Determines if ADO should be used for storage of Membership and Reminders info. /// True if either or both of LivenessType and ReminderServiceType are set to SqlServer, false otherwise. /// </summary> internal bool UseSqlSystemStore { get { return !String.IsNullOrWhiteSpace(DataConnectionString) && ( (LivenessEnabled && LivenessType == LivenessProviderType.SqlServer) || ReminderServiceType == ReminderServiceProviderType.SqlServer); } } /// <summary> /// Determines if ZooKeeper should be used for storage of Membership and Reminders info. /// True if LivenessType is set to ZooKeeper, false otherwise. /// </summary> internal bool UseZooKeeperSystemStore { get { return !String.IsNullOrWhiteSpace(DataConnectionString) && ( (LivenessEnabled && LivenessType == LivenessProviderType.ZooKeeper)); } } /// <summary> /// Determines if Azure Storage should be used for storage of Membership and Reminders info. /// True if either or both of LivenessType and ReminderServiceType are set to AzureTable, false otherwise. /// </summary> internal bool UseAzureSystemStore { get { return !String.IsNullOrWhiteSpace(DataConnectionString) && !UseSqlSystemStore && !UseZooKeeperSystemStore; } } internal bool RunsInAzure { get { return UseAzureSystemStore && !String.IsNullOrWhiteSpace(DeploymentId); } } private static readonly TimeSpan DEFAULT_LIVENESS_PROBE_TIMEOUT = TimeSpan.FromSeconds(10); private static readonly TimeSpan DEFAULT_LIVENESS_TABLE_REFRESH_TIMEOUT = TimeSpan.FromSeconds(60); private static readonly TimeSpan DEFAULT_LIVENESS_DEATH_VOTE_EXPIRATION_TIMEOUT = TimeSpan.FromSeconds(120); private static readonly TimeSpan DEFAULT_LIVENESS_I_AM_ALIVE_TABLE_PUBLISH_TIMEOUT = TimeSpan.FromMinutes(5); private static readonly TimeSpan DEFAULT_LIVENESS_MAX_JOIN_ATTEMPT_TIME = TimeSpan.FromMinutes(5); // 5 min private static readonly TimeSpan DEFAULT_REFRESH_CLUSTER_INTERFACEMAP_TIME = TimeSpan.FromMinutes(1); private const int DEFAULT_LIVENESS_NUM_MISSED_PROBES_LIMIT = 3; private const int DEFAULT_LIVENESS_NUM_PROBED_SILOS = 3; private const int DEFAULT_LIVENESS_NUM_VOTES_FOR_DEATH_DECLARATION = 2; private const int DEFAULT_LIVENESS_NUM_TABLE_I_AM_ALIVE_LIMIT = 2; private const bool DEFAULT_LIVENESS_USE_LIVENESS_GOSSIP = true; private const bool DEFAULT_VALIDATE_INITIAL_CONNECTIVITY = true; private const int DEFAULT_MAX_MULTICLUSTER_GATEWAYS = 10; private const bool DEFAULT_USE_GLOBAL_SINGLE_INSTANCE = true; private static readonly TimeSpan DEFAULT_BACKGROUND_GOSSIP_INTERVAL = TimeSpan.FromSeconds(30); private static readonly TimeSpan DEFAULT_GLOBAL_SINGLE_INSTANCE_RETRY_INTERVAL = TimeSpan.FromSeconds(30); private const int DEFAULT_GLOBAL_SINGLE_INSTANCE_NUMBER_RETRIES = 10; private const int DEFAULT_LIVENESS_EXPECTED_CLUSTER_SIZE = 20; private const int DEFAULT_CACHE_SIZE = 1000000; private static readonly TimeSpan DEFAULT_INITIAL_CACHE_TTL = TimeSpan.FromSeconds(30); private static readonly TimeSpan DEFAULT_MAXIMUM_CACHE_TTL = TimeSpan.FromSeconds(240); private const double DEFAULT_TTL_EXTENSION_FACTOR = 2.0; private const DirectoryCachingStrategyType DEFAULT_DIRECTORY_CACHING_STRATEGY = DirectoryCachingStrategyType.Adaptive; internal static readonly TimeSpan DEFAULT_COLLECTION_QUANTUM = TimeSpan.FromMinutes(1); internal static readonly TimeSpan DEFAULT_COLLECTION_AGE_LIMIT = TimeSpan.FromHours(2); public static bool ENFORCE_MINIMUM_REQUIREMENT_FOR_AGE_LIMIT = true; private static readonly TimeSpan DEFAULT_UNREGISTER_RACE_DELAY = TimeSpan.FromMinutes(1); private static readonly TimeSpan DEFAULT_CLIENT_REGISTRATION_REFRESH = TimeSpan.FromMinutes(5); public const bool DEFAULT_PERFORM_DEADLOCK_DETECTION = false; public static readonly string DEFAULT_PLACEMENT_STRATEGY = typeof(RandomPlacement).Name; public static readonly string DEFAULT_MULTICLUSTER_REGISTRATION_STRATEGY = typeof(GlobalSingleInstanceRegistration).Name; private static readonly TimeSpan DEFAULT_DEPLOYMENT_LOAD_PUBLISHER_REFRESH_TIME = TimeSpan.FromSeconds(1); private const int DEFAULT_ACTIVATION_COUNT_BASED_PLACEMENT_CHOOSE_OUT_OF = 2; private const bool DEFAULT_USE_VIRTUAL_RING_BUCKETS = true; private const int DEFAULT_NUM_VIRTUAL_RING_BUCKETS = 30; private static readonly TimeSpan DEFAULT_MOCK_REMINDER_TABLE_TIMEOUT = TimeSpan.FromMilliseconds(50); private string dataConnectionStringForReminders; private string adoInvariantForReminders; internal GlobalConfiguration() : base(true) { Application = new ApplicationConfiguration(); SeedNodes = new List<IPEndPoint>(); livenessServiceType = LivenessProviderType.NotSpecified; LivenessEnabled = true; ProbeTimeout = DEFAULT_LIVENESS_PROBE_TIMEOUT; TableRefreshTimeout = DEFAULT_LIVENESS_TABLE_REFRESH_TIMEOUT; DeathVoteExpirationTimeout = DEFAULT_LIVENESS_DEATH_VOTE_EXPIRATION_TIMEOUT; IAmAliveTablePublishTimeout = DEFAULT_LIVENESS_I_AM_ALIVE_TABLE_PUBLISH_TIMEOUT; NumMissedProbesLimit = DEFAULT_LIVENESS_NUM_MISSED_PROBES_LIMIT; NumProbedSilos = DEFAULT_LIVENESS_NUM_PROBED_SILOS; NumVotesForDeathDeclaration = DEFAULT_LIVENESS_NUM_VOTES_FOR_DEATH_DECLARATION; NumMissedTableIAmAliveLimit = DEFAULT_LIVENESS_NUM_TABLE_I_AM_ALIVE_LIMIT; UseLivenessGossip = DEFAULT_LIVENESS_USE_LIVENESS_GOSSIP; ValidateInitialConnectivity = DEFAULT_VALIDATE_INITIAL_CONNECTIVITY; MaxJoinAttemptTime = DEFAULT_LIVENESS_MAX_JOIN_ATTEMPT_TIME; TypeMapRefreshInterval = DEFAULT_REFRESH_CLUSTER_INTERFACEMAP_TIME; MaxMultiClusterGateways = DEFAULT_MAX_MULTICLUSTER_GATEWAYS; BackgroundGossipInterval = DEFAULT_BACKGROUND_GOSSIP_INTERVAL; UseGlobalSingleInstanceByDefault = DEFAULT_USE_GLOBAL_SINGLE_INSTANCE; GlobalSingleInstanceRetryInterval = DEFAULT_GLOBAL_SINGLE_INSTANCE_RETRY_INTERVAL; GlobalSingleInstanceNumberRetries = DEFAULT_GLOBAL_SINGLE_INSTANCE_NUMBER_RETRIES; ExpectedClusterSizeConfigValue = new ConfigValue<int>(DEFAULT_LIVENESS_EXPECTED_CLUSTER_SIZE, true); ServiceId = Guid.Empty; DeploymentId = ""; DataConnectionString = ""; // Assume the ado invariant is for sql server storage if not explicitly specified AdoInvariant = Constants.INVARIANT_NAME_SQL_SERVER; MaxRequestProcessingTime = DEFAULT_COLLECTION_AGE_LIMIT; CollectionQuantum = DEFAULT_COLLECTION_QUANTUM; CacheSize = DEFAULT_CACHE_SIZE; InitialCacheTTL = DEFAULT_INITIAL_CACHE_TTL; MaximumCacheTTL = DEFAULT_MAXIMUM_CACHE_TTL; CacheTTLExtensionFactor = DEFAULT_TTL_EXTENSION_FACTOR; DirectoryCachingStrategy = DEFAULT_DIRECTORY_CACHING_STRATEGY; DirectoryLazyDeregistrationDelay = DEFAULT_UNREGISTER_RACE_DELAY; ClientRegistrationRefresh = DEFAULT_CLIENT_REGISTRATION_REFRESH; PerformDeadlockDetection = DEFAULT_PERFORM_DEADLOCK_DETECTION; reminderServiceType = ReminderServiceProviderType.NotSpecified; DefaultPlacementStrategy = DEFAULT_PLACEMENT_STRATEGY; DeploymentLoadPublisherRefreshTime = DEFAULT_DEPLOYMENT_LOAD_PUBLISHER_REFRESH_TIME; ActivationCountBasedPlacementChooseOutOf = DEFAULT_ACTIVATION_COUNT_BASED_PLACEMENT_CHOOSE_OUT_OF; UseVirtualBucketsConsistentRing = DEFAULT_USE_VIRTUAL_RING_BUCKETS; NumVirtualBucketsConsistentRing = DEFAULT_NUM_VIRTUAL_RING_BUCKETS; UseMockReminderTable = false; MockReminderTableTimeout = DEFAULT_MOCK_REMINDER_TABLE_TIMEOUT; AssumeHomogenousSilosForTesting = false; ProviderConfigurations = new Dictionary<string, ProviderCategoryConfiguration>(); GrainServiceConfigurations = new GrainServiceConfigurations(); } public override string ToString() { var sb = new StringBuilder(); sb.AppendFormat(" System Ids:").AppendLine(); sb.AppendFormat(" ServiceId: {0}", ServiceId).AppendLine(); sb.AppendFormat(" DeploymentId: {0}", DeploymentId).AppendLine(); sb.Append(" Subnet: ").Append(Subnet == null ? "" : Subnet.ToStrings(x => x.ToString(CultureInfo.InvariantCulture), ".")).AppendLine(); sb.Append(" Seed nodes: "); bool first = true; foreach (IPEndPoint node in SeedNodes) { if (!first) { sb.Append(", "); } sb.Append(node.ToString()); first = false; } sb.AppendLine(); sb.AppendFormat(base.ToString()); sb.AppendFormat(" Liveness:").AppendLine(); sb.AppendFormat(" LivenessEnabled: {0}", LivenessEnabled).AppendLine(); sb.AppendFormat(" LivenessType: {0}", LivenessType).AppendLine(); sb.AppendFormat(" ProbeTimeout: {0}", ProbeTimeout).AppendLine(); sb.AppendFormat(" TableRefreshTimeout: {0}", TableRefreshTimeout).AppendLine(); sb.AppendFormat(" DeathVoteExpirationTimeout: {0}", DeathVoteExpirationTimeout).AppendLine(); sb.AppendFormat(" NumMissedProbesLimit: {0}", NumMissedProbesLimit).AppendLine(); sb.AppendFormat(" NumProbedSilos: {0}", NumProbedSilos).AppendLine(); sb.AppendFormat(" NumVotesForDeathDeclaration: {0}", NumVotesForDeathDeclaration).AppendLine(); sb.AppendFormat(" UseLivenessGossip: {0}", UseLivenessGossip).AppendLine(); sb.AppendFormat(" ValidateInitialConnectivity: {0}", ValidateInitialConnectivity).AppendLine(); sb.AppendFormat(" IAmAliveTablePublishTimeout: {0}", IAmAliveTablePublishTimeout).AppendLine(); sb.AppendFormat(" NumMissedTableIAmAliveLimit: {0}", NumMissedTableIAmAliveLimit).AppendLine(); sb.AppendFormat(" MaxJoinAttemptTime: {0}", MaxJoinAttemptTime).AppendLine(); sb.AppendFormat(" ExpectedClusterSize: {0}", ExpectedClusterSize).AppendLine(); if (HasMultiClusterNetwork) { sb.AppendLine(" MultiClusterNetwork:"); sb.AppendFormat(" ClusterId: {0}", ClusterId ?? "").AppendLine(); sb.AppendFormat(" DefaultMultiCluster: {0}", DefaultMultiCluster != null ? string.Join(",", DefaultMultiCluster) : "null").AppendLine(); sb.AppendFormat(" MaxMultiClusterGateways: {0}", MaxMultiClusterGateways).AppendLine(); sb.AppendFormat(" BackgroundGossipInterval: {0}", BackgroundGossipInterval).AppendLine(); sb.AppendFormat(" UseGlobalSingleInstanceByDefault: {0}", UseGlobalSingleInstanceByDefault).AppendLine(); sb.AppendFormat(" GlobalSingleInstanceRetryInterval: {0}", GlobalSingleInstanceRetryInterval).AppendLine(); sb.AppendFormat(" GlobalSingleInstanceNumberRetries: {0}", GlobalSingleInstanceNumberRetries).AppendLine(); sb.AppendFormat(" GossipChannels: {0}", string.Join(",", GossipChannels.Select(conf => conf.ChannelType.ToString() + ":" + conf.ConnectionString))).AppendLine(); } else { sb.AppendLine(" MultiClusterNetwork: N/A"); } sb.AppendFormat(" SystemStore:").AppendLine(); // Don't print connection credentials in log files, so pass it through redactment filter string connectionStringForLog = ConfigUtilities.RedactConnectionStringInfo(DataConnectionString); sb.AppendFormat(" SystemStore ConnectionString: {0}", connectionStringForLog).AppendLine(); string remindersConnectionStringForLog = ConfigUtilities.RedactConnectionStringInfo(DataConnectionStringForReminders); sb.AppendFormat(" Reminders ConnectionString: {0}", remindersConnectionStringForLog).AppendLine(); sb.Append(Application.ToString()).AppendLine(); sb.Append(" PlacementStrategy: ").AppendLine(); sb.Append(" ").Append(" Default Placement Strategy: ").Append(DefaultPlacementStrategy).AppendLine(); sb.Append(" ").Append(" Deployment Load Publisher Refresh Time: ").Append(DeploymentLoadPublisherRefreshTime).AppendLine(); sb.Append(" ").Append(" Activation CountBased Placement Choose Out Of: ").Append(ActivationCountBasedPlacementChooseOutOf).AppendLine(); sb.AppendFormat(" Grain directory cache:").AppendLine(); sb.AppendFormat(" Maximum size: {0} grains", CacheSize).AppendLine(); sb.AppendFormat(" Initial TTL: {0}", InitialCacheTTL).AppendLine(); sb.AppendFormat(" Maximum TTL: {0}", MaximumCacheTTL).AppendLine(); sb.AppendFormat(" TTL extension factor: {0:F2}", CacheTTLExtensionFactor).AppendLine(); sb.AppendFormat(" Directory Caching Strategy: {0}", DirectoryCachingStrategy).AppendLine(); sb.AppendFormat(" Grain directory:").AppendLine(); sb.AppendFormat(" Lazy deregistration delay: {0}", DirectoryLazyDeregistrationDelay).AppendLine(); sb.AppendFormat(" Client registration refresh: {0}", ClientRegistrationRefresh).AppendLine(); sb.AppendFormat(" Reminder Service:").AppendLine(); sb.AppendFormat(" ReminderServiceType: {0}", ReminderServiceType).AppendLine(); if (ReminderServiceType == ReminderServiceProviderType.MockTable) { sb.AppendFormat(" MockReminderTableTimeout: {0}ms", MockReminderTableTimeout.TotalMilliseconds).AppendLine(); } sb.AppendFormat(" Consistent Ring:").AppendLine(); sb.AppendFormat(" Use Virtual Buckets Consistent Ring: {0}", UseVirtualBucketsConsistentRing).AppendLine(); sb.AppendFormat(" Num Virtual Buckets Consistent Ring: {0}", NumVirtualBucketsConsistentRing).AppendLine(); sb.AppendFormat(" Providers:").AppendLine(); sb.Append(ProviderConfigurationUtility.PrintProviderConfigurations(ProviderConfigurations)); return sb.ToString(); } internal override void Load(XmlElement root) { var logger = LogManager.GetLogger("OrleansConfiguration", LoggerType.Runtime); SeedNodes = new List<IPEndPoint>(); XmlElement child; foreach (XmlNode c in root.ChildNodes) { child = c as XmlElement; if (child != null && child.LocalName == "Networking") { Subnet = child.HasAttribute("Subnet") ? ConfigUtilities.ParseSubnet(child.GetAttribute("Subnet"), "Invalid Subnet") : null; } } foreach (XmlNode c in root.ChildNodes) { child = c as XmlElement; if (child == null) continue; // Skip comment lines switch (child.LocalName) { case "Liveness": if (child.HasAttribute("LivenessEnabled")) { LivenessEnabled = ConfigUtilities.ParseBool(child.GetAttribute("LivenessEnabled"), "Invalid boolean value for the LivenessEnabled attribute on the Liveness element"); } if (child.HasAttribute("ProbeTimeout")) { ProbeTimeout = ConfigUtilities.ParseTimeSpan(child.GetAttribute("ProbeTimeout"), "Invalid time value for the ProbeTimeout attribute on the Liveness element"); } if (child.HasAttribute("TableRefreshTimeout")) { TableRefreshTimeout = ConfigUtilities.ParseTimeSpan(child.GetAttribute("TableRefreshTimeout"), "Invalid time value for the TableRefreshTimeout attribute on the Liveness element"); } if (child.HasAttribute("DeathVoteExpirationTimeout")) { DeathVoteExpirationTimeout = ConfigUtilities.ParseTimeSpan(child.GetAttribute("DeathVoteExpirationTimeout"), "Invalid time value for the DeathVoteExpirationTimeout attribute on the Liveness element"); } if (child.HasAttribute("NumMissedProbesLimit")) { NumMissedProbesLimit = ConfigUtilities.ParseInt(child.GetAttribute("NumMissedProbesLimit"), "Invalid integer value for the NumMissedIAmAlive attribute on the Liveness element"); } if (child.HasAttribute("NumProbedSilos")) { NumProbedSilos = ConfigUtilities.ParseInt(child.GetAttribute("NumProbedSilos"), "Invalid integer value for the NumProbedSilos attribute on the Liveness element"); } if (child.HasAttribute("NumVotesForDeathDeclaration")) { NumVotesForDeathDeclaration = ConfigUtilities.ParseInt(child.GetAttribute("NumVotesForDeathDeclaration"), "Invalid integer value for the NumVotesForDeathDeclaration attribute on the Liveness element"); } if (child.HasAttribute("UseLivenessGossip")) { UseLivenessGossip = ConfigUtilities.ParseBool(child.GetAttribute("UseLivenessGossip"), "Invalid boolean value for the UseLivenessGossip attribute on the Liveness element"); } if (child.HasAttribute("ValidateInitialConnectivity")) { ValidateInitialConnectivity = ConfigUtilities.ParseBool(child.GetAttribute("ValidateInitialConnectivity"), "Invalid boolean value for the ValidateInitialConnectivity attribute on the Liveness element"); } if (child.HasAttribute("IAmAliveTablePublishTimeout")) { IAmAliveTablePublishTimeout = ConfigUtilities.ParseTimeSpan(child.GetAttribute("IAmAliveTablePublishTimeout"), "Invalid time value for the IAmAliveTablePublishTimeout attribute on the Liveness element"); } if (child.HasAttribute("NumMissedTableIAmAliveLimit")) { NumMissedTableIAmAliveLimit = ConfigUtilities.ParseInt(child.GetAttribute("NumMissedTableIAmAliveLimit"), "Invalid integer value for the NumMissedTableIAmAliveLimit attribute on the Liveness element"); } if (child.HasAttribute("MaxJoinAttemptTime")) { MaxJoinAttemptTime = ConfigUtilities.ParseTimeSpan(child.GetAttribute("MaxJoinAttemptTime"), "Invalid time value for the MaxJoinAttemptTime attribute on the Liveness element"); } if (child.HasAttribute("ExpectedClusterSize")) { int expectedClusterSize = ConfigUtilities.ParseInt(child.GetAttribute("ExpectedClusterSize"), "Invalid integer value for the ExpectedClusterSize attribute on the Liveness element"); ExpectedClusterSizeConfigValue = new ConfigValue<int>(expectedClusterSize, false); } break; case "Azure": case "SystemStore": if (child.LocalName == "Azure") { // Log warning about deprecated <Azure> element, but then continue on to parse it for connection string info logger.Warn(ErrorCode.SiloConfigDeprecated, "The Azure element has been deprecated -- use SystemStore element instead."); } if (child.HasAttribute("SystemStoreType")) { var sst = child.GetAttribute("SystemStoreType"); if (!"None".Equals(sst, StringComparison.OrdinalIgnoreCase)) { LivenessType = (LivenessProviderType)Enum.Parse(typeof(LivenessProviderType), sst); ReminderServiceProviderType reminderServiceProviderType; if (LivenessType == LivenessProviderType.MembershipTableGrain) { // Special case for MembershipTableGrain -> ReminderTableGrain since we use the same setting // for LivenessType and ReminderServiceType even if the enum are not 100% compatible reminderServiceProviderType = ReminderServiceProviderType.ReminderTableGrain; } else { // If LivenessType = ZooKeeper then we set ReminderServiceType to disabled reminderServiceProviderType = Enum.TryParse(sst, out reminderServiceProviderType) ? reminderServiceProviderType : ReminderServiceProviderType.Disabled; } SetReminderServiceType(reminderServiceProviderType); } } if (child.HasAttribute("MembershipTableAssembly")) { MembershipTableAssembly = child.GetAttribute("MembershipTableAssembly"); if (LivenessType != LivenessProviderType.Custom) throw new FormatException("SystemStoreType should be \"Custom\" when MembershipTableAssembly is specified"); if (MembershipTableAssembly.EndsWith(".dll")) throw new FormatException("Use fully qualified assembly name for \"MembershipTableAssembly\""); } if (child.HasAttribute("ReminderTableAssembly")) { ReminderTableAssembly = child.GetAttribute("ReminderTableAssembly"); if (ReminderServiceType != ReminderServiceProviderType.Custom) throw new FormatException("ReminderServiceType should be \"Custom\" when ReminderTableAssembly is specified"); if (ReminderTableAssembly.EndsWith(".dll")) throw new FormatException("Use fully qualified assembly name for \"ReminderTableAssembly\""); } if (LivenessType == LivenessProviderType.Custom && string.IsNullOrEmpty(MembershipTableAssembly)) throw new FormatException("MembershipTableAssembly should be set when SystemStoreType is \"Custom\""); if (ReminderServiceType == ReminderServiceProviderType.Custom && String.IsNullOrEmpty(ReminderTableAssembly)) { logger.Info("No ReminderTableAssembly specified with SystemStoreType set to Custom: ReminderService will be disabled"); SetReminderServiceType(ReminderServiceProviderType.Disabled); } if (child.HasAttribute("ServiceId")) { ServiceId = ConfigUtilities.ParseGuid(child.GetAttribute("ServiceId"), "Invalid Guid value for the ServiceId attribute on the Azure element"); } if (child.HasAttribute("DeploymentId")) { DeploymentId = child.GetAttribute("DeploymentId"); } if (child.HasAttribute(Constants.DATA_CONNECTION_STRING_NAME)) { DataConnectionString = child.GetAttribute(Constants.DATA_CONNECTION_STRING_NAME); if (String.IsNullOrWhiteSpace(DataConnectionString)) { throw new FormatException("SystemStore.DataConnectionString cannot be blank"); } } if (child.HasAttribute(Constants.DATA_CONNECTION_FOR_REMINDERS_STRING_NAME)) { DataConnectionStringForReminders = child.GetAttribute(Constants.DATA_CONNECTION_FOR_REMINDERS_STRING_NAME); if (String.IsNullOrWhiteSpace(DataConnectionStringForReminders)) { throw new FormatException("SystemStore.DataConnectionStringForReminders cannot be blank"); } } if (child.HasAttribute(Constants.ADO_INVARIANT_NAME)) { var adoInvariant = child.GetAttribute(Constants.ADO_INVARIANT_NAME); if (String.IsNullOrWhiteSpace(adoInvariant)) { throw new FormatException("SystemStore.AdoInvariant cannot be blank"); } AdoInvariant = adoInvariant; } if (child.HasAttribute(Constants.ADO_INVARIANT_FOR_REMINDERS_NAME)) { var adoInvariantForReminders = child.GetAttribute(Constants.ADO_INVARIANT_FOR_REMINDERS_NAME); if (String.IsNullOrWhiteSpace(adoInvariantForReminders)) { throw new FormatException("SystemStore.adoInvariantForReminders cannot be blank"); } AdoInvariantForReminders = adoInvariantForReminders; } if (child.HasAttribute("MaxStorageBusyRetries")) { MaxStorageBusyRetries = ConfigUtilities.ParseInt(child.GetAttribute("MaxStorageBusyRetries"), "Invalid integer value for the MaxStorageBusyRetries attribute on the SystemStore element"); } if (child.HasAttribute("UseMockReminderTable")) { MockReminderTableTimeout = ConfigUtilities.ParseTimeSpan(child.GetAttribute("UseMockReminderTable"), "Invalid timeout value"); UseMockReminderTable = true; } break; case "MultiClusterNetwork": ClusterId = child.GetAttribute("ClusterId"); // we always trim cluster ids to avoid surprises when parsing comma-separated lists if (ClusterId != null) ClusterId = ClusterId.Trim(); if (string.IsNullOrEmpty(ClusterId)) throw new FormatException("MultiClusterNetwork.ClusterId cannot be blank"); if (ClusterId.Contains(",")) throw new FormatException("MultiClusterNetwork.ClusterId cannot contain commas: " + ClusterId); if (child.HasAttribute("DefaultMultiCluster")) { var toparse = child.GetAttribute("DefaultMultiCluster").Trim(); if (string.IsNullOrEmpty(toparse)) { DefaultMultiCluster = new List<string>(); // empty cluster } else { DefaultMultiCluster = toparse.Split(',').Select(id => id.Trim()).ToList(); foreach (var id in DefaultMultiCluster) if (string.IsNullOrEmpty(id)) throw new FormatException("MultiClusterNetwork.DefaultMultiCluster cannot contain blank cluster ids: " + toparse); } } if (child.HasAttribute("BackgroundGossipInterval")) { BackgroundGossipInterval = ConfigUtilities.ParseTimeSpan(child.GetAttribute("BackgroundGossipInterval"), "Invalid time value for the BackgroundGossipInterval attribute on the MultiClusterNetwork element"); } if (child.HasAttribute("UseGlobalSingleInstanceByDefault")) { UseGlobalSingleInstanceByDefault = ConfigUtilities.ParseBool(child.GetAttribute("UseGlobalSingleInstanceByDefault"), "Invalid boolean for the UseGlobalSingleInstanceByDefault attribute on the MultiClusterNetwork element"); } if (child.HasAttribute("GlobalSingleInstanceRetryInterval")) { GlobalSingleInstanceRetryInterval = ConfigUtilities.ParseTimeSpan(child.GetAttribute("GlobalSingleInstanceRetryInterval"), "Invalid time value for the GlobalSingleInstanceRetryInterval attribute on the MultiClusterNetwork element"); } if (child.HasAttribute("GlobalSingleInstanceNumberRetries")) { GlobalSingleInstanceNumberRetries = ConfigUtilities.ParseInt(child.GetAttribute("GlobalSingleInstanceNumberRetries"), "Invalid value for the GlobalSingleInstanceRetryInterval attribute on the MultiClusterNetwork element"); } if (child.HasAttribute("MaxMultiClusterGateways")) { MaxMultiClusterGateways = ConfigUtilities.ParseInt(child.GetAttribute("MaxMultiClusterGateways"), "Invalid value for the MaxMultiClusterGateways attribute on the MultiClusterNetwork element"); } var channels = new List<GossipChannelConfiguration>(); foreach (XmlNode childchild in child.ChildNodes) { var channelspec = childchild as XmlElement; if (channelspec == null || channelspec.LocalName != "GossipChannel") continue; channels.Add(new GossipChannelConfiguration() { ChannelType = (GlobalConfiguration.GossipChannelType) Enum.Parse(typeof(GlobalConfiguration.GossipChannelType), channelspec.GetAttribute("Type")), ConnectionString = channelspec.GetAttribute("ConnectionString") }); } GossipChannels = channels; break; case "SeedNode": SeedNodes.Add(ConfigUtilities.ParseIPEndPoint(child, Subnet).GetResult()); break; case "Messaging": base.Load(child); break; case "Application": Application.Load(child, logger); break; case "PlacementStrategy": if (child.HasAttribute("DefaultPlacementStrategy")) DefaultPlacementStrategy = child.GetAttribute("DefaultPlacementStrategy"); if (child.HasAttribute("DeploymentLoadPublisherRefreshTime")) DeploymentLoadPublisherRefreshTime = ConfigUtilities.ParseTimeSpan(child.GetAttribute("DeploymentLoadPublisherRefreshTime"), "Invalid time span value for PlacementStrategy.DeploymentLoadPublisherRefreshTime"); if (child.HasAttribute("ActivationCountBasedPlacementChooseOutOf")) ActivationCountBasedPlacementChooseOutOf = ConfigUtilities.ParseInt(child.GetAttribute("ActivationCountBasedPlacementChooseOutOf"), "Invalid ActivationCountBasedPlacementChooseOutOf setting"); break; case "Caching": if (child.HasAttribute("CacheSize")) CacheSize = ConfigUtilities.ParseInt(child.GetAttribute("CacheSize"), "Invalid integer value for Caching.CacheSize"); if (child.HasAttribute("InitialTTL")) InitialCacheTTL = ConfigUtilities.ParseTimeSpan(child.GetAttribute("InitialTTL"), "Invalid time value for Caching.InitialTTL"); if (child.HasAttribute("MaximumTTL")) MaximumCacheTTL = ConfigUtilities.ParseTimeSpan(child.GetAttribute("MaximumTTL"), "Invalid time value for Caching.MaximumTTL"); if (child.HasAttribute("TTLExtensionFactor")) CacheTTLExtensionFactor = ConfigUtilities.ParseDouble(child.GetAttribute("TTLExtensionFactor"), "Invalid double value for Caching.TTLExtensionFactor"); if (CacheTTLExtensionFactor <= 1.0) { throw new FormatException("Caching.TTLExtensionFactor must be greater than 1.0"); } if (child.HasAttribute("DirectoryCachingStrategy")) DirectoryCachingStrategy = ConfigUtilities.ParseEnum<DirectoryCachingStrategyType>(child.GetAttribute("DirectoryCachingStrategy"), "Invalid value for Caching.Strategy"); break; case "Directory": if (child.HasAttribute("DirectoryLazyDeregistrationDelay")) { DirectoryLazyDeregistrationDelay = ConfigUtilities.ParseTimeSpan(child.GetAttribute("DirectoryLazyDeregistrationDelay"), "Invalid time span value for Directory.DirectoryLazyDeregistrationDelay"); } if (child.HasAttribute("ClientRegistrationRefresh")) { ClientRegistrationRefresh = ConfigUtilities.ParseTimeSpan(child.GetAttribute("ClientRegistrationRefresh"), "Invalid time span value for Directory.ClientRegistrationRefresh"); } break; default: if (child.LocalName.Equals("GrainServices", StringComparison.Ordinal)) { GrainServiceConfigurations = GrainServiceConfigurations.Load(child); } if (child.LocalName.EndsWith("Providers", StringComparison.Ordinal)) { var providerCategory = ProviderCategoryConfiguration.Load(child); if (ProviderConfigurations.ContainsKey(providerCategory.Name)) { var existingCategory = ProviderConfigurations[providerCategory.Name]; existingCategory.Merge(providerCategory); } else { ProviderConfigurations.Add(providerCategory.Name, providerCategory); } } break; } } } /// <summary> /// Registers a given type of <typeparamref name="T"/> where <typeparamref name="T"/> is bootstrap provider /// </summary> /// <typeparam name="T">Non-abstract type which implements <see cref="IBootstrapProvider"/> interface</typeparam> /// <param name="providerName">Name of the bootstrap provider</param> /// <param name="properties">Properties that will be passed to bootstrap provider upon initialization</param> public void RegisterBootstrapProvider<T>(string providerName, IDictionary<string, string> properties = null) where T : IBootstrapProvider { Type providerType = typeof(T); var providerTypeInfo = providerType.GetTypeInfo(); if (providerTypeInfo.IsAbstract || providerTypeInfo.IsGenericType || !typeof(IBootstrapProvider).IsAssignableFrom(providerType)) throw new ArgumentException("Expected non-generic, non-abstract type which implements IBootstrapProvider interface", "typeof(T)"); ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.BOOTSTRAP_PROVIDER_CATEGORY_NAME, providerTypeInfo.FullName, providerName, properties); } /// <summary> /// Registers a given bootstrap provider. /// </summary> /// <param name="providerTypeFullName">Full name of the bootstrap provider type</param> /// <param name="providerName">Name of the bootstrap provider</param> /// <param name="properties">Properties that will be passed to the bootstrap provider upon initialization </param> public void RegisterBootstrapProvider(string providerTypeFullName, string providerName, IDictionary<string, string> properties = null) { ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.BOOTSTRAP_PROVIDER_CATEGORY_NAME, providerTypeFullName, providerName, properties); } /// <summary> /// Registers a given type of <typeparamref name="T"/> where <typeparamref name="T"/> is stream provider /// </summary> /// <typeparam name="T">Non-abstract type which implements <see cref="IStreamProvider"/> stream</typeparam> /// <param name="providerName">Name of the stream provider</param> /// <param name="properties">Properties that will be passed to stream provider upon initialization</param> public void RegisterStreamProvider<T>(string providerName, IDictionary<string, string> properties = null) where T : Orleans.Streams.IStreamProvider { Type providerType = typeof(T); var providerTypeInfo = providerType.GetTypeInfo(); if (providerTypeInfo.IsAbstract || providerTypeInfo.IsGenericType || !typeof(Orleans.Streams.IStreamProvider).IsAssignableFrom(providerType)) throw new ArgumentException("Expected non-generic, non-abstract type which implements IStreamProvider interface", "typeof(T)"); ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.STREAM_PROVIDER_CATEGORY_NAME, providerType.FullName, providerName, properties); } /// <summary> /// Registers a given stream provider. /// </summary> /// <param name="providerTypeFullName">Full name of the stream provider type</param> /// <param name="providerName">Name of the stream provider</param> /// <param name="properties">Properties that will be passed to the stream provider upon initialization </param> public void RegisterStreamProvider(string providerTypeFullName, string providerName, IDictionary<string, string> properties = null) { ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.STREAM_PROVIDER_CATEGORY_NAME, providerTypeFullName, providerName, properties); } /// <summary> /// Registers a given type of <typeparamref name="T"/> where <typeparamref name="T"/> is storage provider /// </summary> /// <typeparam name="T">Non-abstract type which implements <see cref="IStorageProvider"/> storage</typeparam> /// <param name="providerName">Name of the storage provider</param> /// <param name="properties">Properties that will be passed to storage provider upon initialization</param> public void RegisterStorageProvider<T>(string providerName, IDictionary<string, string> properties = null) where T : IStorageProvider { Type providerType = typeof(T); var providerTypeInfo = providerType.GetTypeInfo(); if (providerTypeInfo.IsAbstract || providerTypeInfo.IsGenericType || !typeof(IStorageProvider).IsAssignableFrom(providerType)) throw new ArgumentException("Expected non-generic, non-abstract type which implements IStorageProvider interface", "typeof(T)"); ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.STORAGE_PROVIDER_CATEGORY_NAME, providerTypeInfo.FullName, providerName, properties); } /// <summary> /// Registers a given storage provider. /// </summary> /// <param name="providerTypeFullName">Full name of the storage provider type</param> /// <param name="providerName">Name of the storage provider</param> /// <param name="properties">Properties that will be passed to the storage provider upon initialization </param> public void RegisterStorageProvider(string providerTypeFullName, string providerName, IDictionary<string, string> properties = null) { ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.STORAGE_PROVIDER_CATEGORY_NAME, providerTypeFullName, providerName, properties); } public void RegisterStatisticsProvider<T>(string providerName, IDictionary<string, string> properties = null) where T : IStatisticsPublisher, ISiloMetricsDataPublisher { Type providerType = typeof(T); var providerTypeInfo = providerType.GetTypeInfo(); if (providerTypeInfo.IsAbstract || providerTypeInfo.IsGenericType || !( typeof(IStatisticsPublisher).IsAssignableFrom(providerType) && typeof(ISiloMetricsDataPublisher).IsAssignableFrom(providerType) )) throw new ArgumentException("Expected non-generic, non-abstract type which implements IStatisticsPublisher, ISiloMetricsDataPublisher interface", "typeof(T)"); ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.STATISTICS_PROVIDER_CATEGORY_NAME, providerTypeInfo.FullName, providerName, properties); } public void RegisterStatisticsProvider(string providerTypeFullName, string providerName, IDictionary<string, string> properties = null) { ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.STATISTICS_PROVIDER_CATEGORY_NAME, providerTypeFullName, providerName, properties); } /// <summary> /// Registers a given log-consistency provider. /// </summary> /// <param name="providerTypeFullName">Full name of the log-consistency provider type</param> /// <param name="providerName">Name of the log-consistency provider</param> /// <param name="properties">Properties that will be passed to the log-consistency provider upon initialization </param> public void RegisterLogConsistencyProvider(string providerTypeFullName, string providerName, IDictionary<string, string> properties = null) { ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.LOG_CONSISTENCY_PROVIDER_CATEGORY_NAME, providerTypeFullName, providerName, properties); } /// <summary> /// Registers a given type of <typeparamref name="T"/> where <typeparamref name="T"/> is a log-consistency provider /// </summary> /// <typeparam name="T">Non-abstract type which implements <see cref="ILogConsistencyProvider"/> a log-consistency storage interface</typeparam> /// <param name="providerName">Name of the log-consistency provider</param> /// <param name="properties">Properties that will be passed to log-consistency provider upon initialization</param> public void RegisterLogConsistencyProvider<T>(string providerName, IDictionary<string, string> properties = null) where T : ILogConsistencyProvider { Type providerType = typeof(T); var providerTypeInfo = providerType.GetTypeInfo(); if (providerTypeInfo.IsAbstract || providerTypeInfo.IsGenericType || !typeof(ILogConsistencyProvider).IsAssignableFrom(providerType)) throw new ArgumentException("Expected non-generic, non-abstract type which implements ILogConsistencyProvider interface", "typeof(T)"); ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.LOG_CONSISTENCY_PROVIDER_CATEGORY_NAME, providerType.FullName, providerName, properties); } /// <summary> /// Retrieves an existing provider configuration /// </summary> /// <param name="providerTypeFullName">Full name of the stream provider type</param> /// <param name="providerName">Name of the stream provider</param> /// <param name="config">The provider configuration, if exists</param> /// <returns>True if a configuration for this provider already exists, false otherwise.</returns> public bool TryGetProviderConfiguration(string providerTypeFullName, string providerName, out IProviderConfiguration config) { return ProviderConfigurationUtility.TryGetProviderConfiguration(ProviderConfigurations, providerTypeFullName, providerName, out config); } /// <summary> /// Retrieves an enumeration of all currently configured provider configurations. /// </summary> /// <returns>An enumeration of all currently configured provider configurations.</returns> public IEnumerable<IProviderConfiguration> GetAllProviderConfigurations() { return ProviderConfigurationUtility.GetAllProviderConfigurations(ProviderConfigurations); } public void RegisterGrainService(string serviceName, string serviceType, IDictionary<string, string> properties = null) { GrainServiceConfigurationsUtility.RegisterGrainService(GrainServiceConfigurations, serviceName, serviceType, properties); } } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.Linq; using System.Runtime.InteropServices; using DotSpatial.Serialization; using OSGeo.GDAL; namespace DotSpatial.Data.Rasters.GdalExtension { /// <summary> /// An image based on GDAL data. /// </summary> public class GdalImage : ImageData { #region Fields private Band _alpha; private Band _blue; private Dataset _dataset; private Band _green; private Bitmap _image; private bool _isOpened; private int _overview; private Band _red; #endregion #region Constructors static GdalImage() { GdalConfiguration.ConfigureGdal(); } /// <summary> /// Initializes a new instance of the <see cref="GdalImage"/> class, and gets much of the header /// information without actually reading any values from the file. /// </summary> /// <param name="fileName">File containing the GDAL image.</param> public GdalImage(string fileName) { Filename = fileName; WorldFile = new WorldFile { Affine = new double[6] }; ReadHeader(); } /// <summary> /// Initializes a new instance of the <see cref="GdalImage"/> class. /// </summary> public GdalImage() { } /// <summary> /// Initializes a new instance of the <see cref="GdalImage"/> class. /// </summary> /// <param name="fileName">File containing the GDAL image.</param> /// <param name="ds">The dataset.</param> /// <param name="band">The band type of the image.</param> internal GdalImage(string fileName, Dataset ds, ImageBandType band) { var setRsColor = (Action<int, ColorInterp>)((i, ci) => { using (var bnd = ds.GetRasterBand(i)) { bnd.SetRasterColorInterpretation(ci); } }); _dataset = ds; switch (band) { case ImageBandType.ARGB: setRsColor(1, ColorInterp.GCI_AlphaBand); setRsColor(2, ColorInterp.GCI_RedBand); setRsColor(3, ColorInterp.GCI_GreenBand); setRsColor(4, ColorInterp.GCI_BlueBand); break; case ImageBandType.RGB: setRsColor(1, ColorInterp.GCI_RedBand); setRsColor(2, ColorInterp.GCI_GreenBand); setRsColor(3, ColorInterp.GCI_BlueBand); break; case ImageBandType.PalletCoded: setRsColor(3, ColorInterp.GCI_PaletteIndex); break; default: setRsColor(3, ColorInterp.GCI_GrayIndex); break; } Filename = fileName; WorldFile = new WorldFile { Affine = new double[6] }; } #endregion #region Properties /// <summary> /// Gets or sets a value indicating whether the file is open. This is a simliar to calling Open/Close methods. /// </summary> [Serialize("IsOpened")] public bool IsOpened { get { return _isOpened; } set { if (_isOpened == value) return; _isOpened = value; if (value) { Open(); } else { Close(); } } } #endregion #region Methods /// <inheritdoc /> public override void Close() { _dataset.Dispose(); _dataset = null; _isOpened = false; } /// <summary> /// Reads the actual image values from the image file into the array /// of Values, which can be accessed by the Color property. /// </summary> public override void CopyBitmapToValues() { BitmapData bData = _image.LockBits(new Rectangle(0, 0, Width, Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); Stride = bData.Stride; Marshal.Copy(bData.Scan0, Values, 0, bData.Height * bData.Stride); _image.UnlockBits(bData); } /// <summary> /// Writes the byte values stored in the Bytes array into the bitmap image. /// </summary> public override void CopyValuesToBitmap() { Rectangle bnds = new Rectangle(0, 0, Width, Height); BitmapData bData = _image.LockBits(bnds, ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); Marshal.Copy(Values, 0, bData.Scan0, Values.Length); _image.UnlockBits(bData); } /// <summary> /// This needs to return the actual image and override the base /// behavior that handles the internal variables only. /// </summary> /// <param name="envelope">The envelope to grab image data for.</param> /// <param name="window">A Rectangle</param> /// <returns>The image.</returns> public override Bitmap GetBitmap(Extent envelope, Rectangle window) { if (window.Width == 0 || window.Height == 0) { return null; } var result = new Bitmap(window.Width, window.Height); using (var g = Graphics.FromImage(result)) { DrawGraphics(g, envelope, window); } return result; } /// <summary> /// This is only used in the palette indexed band type. /// </summary> /// <returns>The color palette.</returns> public override IEnumerable<Color> GetColorPalette() { if (ColorPalette == null) { _dataset = Helpers.Open(Filename); using (var first = _dataset.GetRasterBand(1)) using (var ct = first.GetRasterColorTable()) { int count = ct.GetCount(); var result = new List<Color>(count); for (int i = 0; i < count; i++) { using (var ce = ct.GetColorEntry(i)) result.Add(Color.FromArgb(ce.c4, ce.c1, ce.c2, ce.c3)); } ColorPalette = result; } } return ColorPalette; } /// <summary> /// Attempts to open the specified file into memory. /// </summary> public override void Open() { _dataset = Helpers.Open(Filename); int numBands = _dataset.RasterCount; _red = _dataset.GetRasterBand(1); BandType = ImageBandType.RGB; for (int i = 1; i <= numBands; i++) { var tempBand = _dataset.GetRasterBand(i); switch (tempBand.GetRasterColorInterpretation()) { case ColorInterp.GCI_GrayIndex: BandType = ImageBandType.Gray; _red = tempBand; break; case ColorInterp.GCI_PaletteIndex: BandType = ImageBandType.PalletCoded; _red = tempBand; break; case ColorInterp.GCI_RedBand: _red = tempBand; break; case ColorInterp.GCI_AlphaBand: _alpha = tempBand; BandType = ImageBandType.ARGB; break; case ColorInterp.GCI_BlueBand: _blue = tempBand; break; case ColorInterp.GCI_GreenBand: _green = tempBand; break; } } _isOpened = true; } /// <summary> /// Gets a block of data directly, converted into a bitmap. This always writes /// to the base layer, not the overviews. /// </summary> /// <param name="xOffset">The zero based integer column offset from the left</param> /// <param name="yOffset">The zero based integer row offset from the top</param> /// <param name="xSize">The integer number of pixel columns in the block. </param> /// <param name="ySize">The integer number of pixel rows in the block.</param> /// <returns>A Bitmap that is xSize, ySize.</returns> public override Bitmap ReadBlock(int xOffset, int yOffset, int xSize, int ySize) { if (_dataset == null) { _dataset = Helpers.Open(Filename); } Bitmap result = null; using (var first = _dataset.GetRasterBand(1)) { switch (first.GetRasterColorInterpretation()) { case ColorInterp.GCI_PaletteIndex: result = ReadPaletteBuffered(xOffset, yOffset, xSize, ySize, first); break; case ColorInterp.GCI_GrayIndex: result = ReadGrayIndex(xOffset, yOffset, xSize, ySize, first); break; case ColorInterp.GCI_RedBand: result = ReadRgb(xOffset, yOffset, xSize, ySize, first, _dataset); break; case ColorInterp.GCI_AlphaBand: result = ReadArgb(xOffset, yOffset, xSize, ySize, first, _dataset); break; } } // data set disposed on disposing this image return result; } /// <summary> /// This should update the palette cached and in the file. /// </summary> /// <param name="value">The color palette.</param> public override void SetColorPalette(IEnumerable<Color> value) { var colorPalette = value as IList<Color> ?? value.ToList(); ColorPalette = colorPalette; _dataset = Gdal.Open(Filename, Access.GA_Update); ColorTable ct = new ColorTable(PaletteInterp.GPI_RGB); int index = 0; foreach (var c in colorPalette) { ColorEntry ce = new ColorEntry { c4 = c.A, c3 = c.B, c2 = c.G, c1 = c.R }; ct.SetColorEntry(index, ce); index++; } using (Band first = _dataset.GetRasterBand(1)) { first.SetRasterColorTable(ct); } } /// <summary> /// Saves a bitmap of data as a continuous block into the specified location. /// This always writes to the base image, and not the overviews. /// </summary> /// <param name="value">The bitmap value to save.</param> /// <param name="xOffset">The zero based integer column offset from the left</param> /// <param name="yOffset">The zero based integer row offset from the top</param> public override void WriteBlock(Bitmap value, int xOffset, int yOffset) { if (_dataset == null) { // This will fail if write access is not allowed, but just pass the // exception back up the stack. _dataset = Gdal.Open(Filename, Access.GA_Update); } using (var first = _dataset.GetRasterBand(1)) { switch (BandType) { case ImageBandType.PalletCoded: WritePaletteBuffered(value, xOffset, yOffset, first); break; case ImageBandType.Gray: WriteGrayIndex(value, xOffset, yOffset, first); break; case ImageBandType.RGB: WriteRgb(value, xOffset, yOffset, first, _dataset); break; case ImageBandType.ARGB: WriteArgb(value, xOffset, yOffset, first, _dataset); break; } } } /// <inheritdoc /> protected override void Dispose(bool disposeManagedResources) { // All class variables are unmanaged. if (_dataset != null) { try { _dataset.FlushCache(); } catch (Exception e) { Console.WriteLine(e.Message); } _dataset.Dispose(); } _dataset = null; _image?.Dispose(); _image = null; _red?.Dispose(); _red = null; _blue?.Dispose(); _blue = null; _green?.Dispose(); _green = null; _alpha?.Dispose(); _alpha = null; base.Dispose(disposeManagedResources); } /// <summary> /// Finds the closest color in the table based on the hamming distance. /// </summary> /// <param name="vals">The values.</param> /// <param name="offset">The offset</param> /// <param name="colorTable">The color table.</param> /// <returns>The closest color.</returns> private static byte MatchColor(byte[] vals, int offset, byte[][] colorTable) { int shortestDistance = int.MaxValue; int index = 0; int result = 0; foreach (byte[] color in colorTable) { int dist = Math.Abs(vals[offset] - color[0]); dist += Math.Abs(vals[offset + 1] - color[1]); dist += Math.Abs(vals[offset + 2] - color[2]); dist += Math.Abs(vals[offset + 3] - color[0]); if (dist < shortestDistance) { shortestDistance = dist; result = index; } index++; } return Convert.ToByte(result); } private static void NormalizeSizeToBand(int xOffset, int yOffset, int xSize, int ySize, Band band, out int width, out int height) { width = xSize; height = ySize; if (xOffset + width > band.XSize) { width = band.XSize - xOffset; } if (yOffset + height > band.YSize) { height = band.YSize - yOffset; } } private static void WriteArgb(Bitmap value, int xOffset, int yOffset, Band first, Dataset set) { if (set.RasterCount < 4) { throw new GdalException("ARGB Format was indicated but there are only " + set.RasterCount + " bands!"); } int width = value.Width; int height = value.Height; BitmapData bData = value.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); int stride = Math.Abs(bData.Stride); byte[] vals = new byte[stride * height]; Marshal.Copy(bData.Scan0, vals, 0, vals.Length); value.UnlockBits(bData); byte[] a = new byte[width * height]; byte[] r = new byte[width * height]; byte[] g = new byte[width * height]; byte[] b = new byte[width * height]; for (int row = 0; row < height; row++) { for (int col = 0; col < width; col++) { b[(row * width) + col] = vals[(row * stride) + (col * 4)]; g[(row * width) + col] = vals[(row * stride) + (col * 4) + 1]; r[(row * width) + col] = vals[(row * stride) + (col * 4) + 2]; a[(row * width) + col] = vals[(row * stride) + (col * 4) + 3]; } } Band red = set.GetRasterBand(2); Band green = set.GetRasterBand(3); Band blue = set.GetRasterBand(4); first.WriteRaster(xOffset, yOffset, width, height, a, width, height, 0, 0); red.WriteRaster(xOffset, yOffset, width, height, r, width, height, 0, 0); green.WriteRaster(xOffset, yOffset, width, height, g, width, height, 0, 0); blue.WriteRaster(xOffset, yOffset, width, height, b, width, height, 0, 0); // first disposed in caller green.Dispose(); blue.Dispose(); } private static void WriteGrayIndex(Bitmap value, int xOffset, int yOffset, Band first) { int width = value.Width; int height = value.Height; BitmapData bData = value.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); int stride = Math.Abs(bData.Stride); byte[] r = new byte[stride * height * 4]; Marshal.Copy(bData.Scan0, r, 0, r.Length); byte[] vals = new byte[height * stride]; for (int row = 0; row < height; row++) { for (int col = 0; col < width; col++) { byte blue = r[(row * stride) + (col * 4)]; byte green = r[(row * stride) + (col * 4) + 1]; byte red = r[(row * stride) + (col * 4) + 2]; int gray = Convert.ToInt32((.3 * red) + (.59 * green) + (.11 * blue)); if (gray > 255) gray = 255; if (gray < 0) gray = 0; vals[(row * width) + col] = Convert.ToByte(gray); } } first.WriteRaster(xOffset, yOffset, width, height, vals, width, height, 0, 0); } private static void WritePaletteBuffered(Bitmap value, int xOffset, int yOffset, Band first) { ColorTable ct = first.GetRasterColorTable(); if (ct == null) { throw new GdalException("Image was stored with a palette interpretation but has no color table."); } if (ct.GetPaletteInterpretation() != PaletteInterp.GPI_RGB) { throw new GdalException("Only RGB palette interpretation is currently supported by this " + " plug-in, " + ct.GetPaletteInterpretation() + " is not supported."); } int width = value.Width; int height = value.Height; BitmapData bData = value.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); int stride = Math.Abs(bData.Stride); byte[] r = new byte[stride * height]; Marshal.Copy(bData.Scan0, r, 0, r.Length); value.UnlockBits(bData); byte[] vals = new byte[width * height]; byte[][] colorTable = new byte[ct.GetCount()][]; for (int i = 0; i < ct.GetCount(); i++) { ColorEntry ce = ct.GetColorEntry(i); colorTable[i] = new[] { (byte)ce.c3, (byte)ce.c2, (byte)ce.c1, (byte)ce.c4 }; } for (int row = 0; row < height; row++) { for (int col = 0; col < width; col++) { vals[(row * width) + col] = MatchColor(r, (row * stride) + (col * 4), colorTable); } } first.WriteRaster(xOffset, yOffset, width, height, vals, width, height, 0, 0); } private static void WriteRgb(Bitmap value, int xOffset, int yOffset, Band first, Dataset set) { if (set.RasterCount < 3) { throw new GdalException("RGB Format was indicated but there are only " + set.RasterCount + " bands!"); } int width = value.Width; int height = value.Height; BitmapData bData = value.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); int stride = Math.Abs(bData.Stride); byte[] vals = new byte[stride * height]; Marshal.Copy(bData.Scan0, vals, 0, vals.Length); value.UnlockBits(bData); byte[] r = new byte[width * height]; byte[] g = new byte[width * height]; byte[] b = new byte[width * height]; for (int row = 0; row < height; row++) { for (int col = 0; col < width; col++) { b[(row * width) + col] = vals[(row * stride) + (col * 4)]; g[(row * width) + col] = vals[(row * stride) + (col * 4) + 1]; r[(row * width) + col] = vals[(row * stride) + (col * 4) + 2]; } } Band green = set.GetRasterBand(2); Band blue = set.GetRasterBand(3); first.WriteRaster(xOffset, yOffset, width, height, r, width, height, 0, 0); first.FlushCache(); green.WriteRaster(xOffset, yOffset, width, height, g, width, height, 0, 0); green.FlushCache(); blue.WriteRaster(xOffset, yOffset, width, height, b, width, height, 0, 0); blue.FlushCache(); // first disposed in caller green.Dispose(); blue.Dispose(); } private void DrawGraphics(Graphics g, Extent envelope, Rectangle window) { // Gets the scaling factor for converting from geographic to pixel coordinates double dx = window.Width / envelope.Width; double dy = window.Height / envelope.Height; double[] a = Bounds.AffineCoefficients; // calculate inverse double p = 1 / ((a[1] * a[5]) - (a[2] * a[4])); double[] aInv = new double[4]; aInv[0] = a[5] * p; aInv[1] = -a[2] * p; aInv[2] = -a[4] * p; aInv[3] = a[1] * p; // estimate rectangle coordinates double tlx = ((envelope.MinX - a[0]) * aInv[0]) + ((envelope.MaxY - a[3]) * aInv[1]); double tly = ((envelope.MinX - a[0]) * aInv[2]) + ((envelope.MaxY - a[3]) * aInv[3]); double trx = ((envelope.MaxX - a[0]) * aInv[0]) + ((envelope.MaxY - a[3]) * aInv[1]); double trY = ((envelope.MaxX - a[0]) * aInv[2]) + ((envelope.MaxY - a[3]) * aInv[3]); double blx = ((envelope.MinX - a[0]) * aInv[0]) + ((envelope.MinY - a[3]) * aInv[1]); double bly = ((envelope.MinX - a[0]) * aInv[2]) + ((envelope.MinY - a[3]) * aInv[3]); double brx = ((envelope.MaxX - a[0]) * aInv[0]) + ((envelope.MinY - a[3]) * aInv[1]); double bry = ((envelope.MaxX - a[0]) * aInv[2]) + ((envelope.MinY - a[3]) * aInv[3]); // get absolute maximum and minimum coordinates to make a rectangle on projected coordinates // that overlaps all the visible area. double tLx = Math.Min(Math.Min(Math.Min(tlx, trx), blx), brx); double tLy = Math.Min(Math.Min(Math.Min(tly, trY), bly), bry); double bRx = Math.Max(Math.Max(Math.Max(tlx, trx), blx), brx); double bRy = Math.Max(Math.Max(Math.Max(tly, trY), bly), bry); // limit it to the available image // todo: why we compare NumColumns\Rows and X,Y coordinates?? if (tLx > Bounds.NumColumns) tLx = Bounds.NumColumns; if (tLy > Bounds.NumRows) tLy = Bounds.NumRows; if (bRx > Bounds.NumColumns) bRx = Bounds.NumColumns; if (bRy > Bounds.NumRows) bRy = Bounds.NumRows; if (tLx < 0) tLx = 0; if (tLy < 0) tLy = 0; if (bRx < 0) bRx = 0; if (bRy < 0) bRy = 0; // gets the affine scaling factors. float m11 = Convert.ToSingle(a[1] * dx); float m22 = Convert.ToSingle(a[5] * -dy); float m21 = Convert.ToSingle(a[2] * dx); float m12 = Convert.ToSingle(a[4] * -dy); float l = (float)(a[0] - (.5 * (a[1] + a[2]))); // Left of top left pixel float t = (float)(a[3] - (.5 * (a[4] + a[5]))); // top of top left pixel float xShift = (float)((l - envelope.MinX) * dx); float yShift = (float)((envelope.MaxY - t) * dy); g.PixelOffsetMode = PixelOffsetMode.Half; if (m11 > 1 || m22 > 1) { // out of pyramids g.InterpolationMode = InterpolationMode.NearestNeighbor; _overview = -1; // don't use overviews when zooming behind the max res. } else { // estimate the pyramids that we need. // when using unreferenced images m11 or m22 can be negative resulting on inf logarithm. // so the Math.abs _overview = (int)Math.Min(Math.Log(Math.Abs(1 / m11), 2), Math.Log(Math.Abs(1 / m22), 2)); // limit it to the available pyramids _overview = Math.Min(_overview, _red.GetOverviewCount() - 1); // additional test but probably not needed if (_overview < 0) { _overview = -1; } } var overviewPow = Math.Pow(2, _overview + 1); // witdh and height of the image var w = (bRx - tLx) / overviewPow; var h = (bRy - tLy) / overviewPow; using (var matrix = new Matrix(m11 * (float)overviewPow, m12 * (float)overviewPow, m21 * (float)overviewPow, m22 * (float)overviewPow, xShift, yShift)) { g.Transform = matrix; } int blockXsize, blockYsize; // get the optimal block size to request gdal. // if the image is stored line by line then ask for a 100px stripe. if (_overview >= 0 && _red.GetOverviewCount() > 0) { using (var overview = _red.GetOverview(_overview)) { overview.GetBlockSize(out blockXsize, out blockYsize); if (blockYsize == 1) { blockYsize = Math.Min(100, overview.YSize); } } } else { _red.GetBlockSize(out blockXsize, out blockYsize); if (blockYsize == 1) { blockYsize = Math.Min(100, _red.YSize); } } int nbX, nbY; // limit the block size to the viewable image. if (w < blockXsize) { blockXsize = (int)w; nbX = 1; } else { nbX = (int)(w / blockXsize) + 1; } if (h < blockYsize) { blockYsize = (int)h; nbY = 1; } else { nbY = (int)(h / blockYsize) + 1; } for (var i = 0; i < nbX; i++) { for (var j = 0; j < nbY; j++) { // The +1 is to remove the white stripes artifacts using (var bitmap = ReadBlock((int)(tLx / overviewPow) + (i * blockXsize), (int)(tLy / overviewPow) + (j * blockYsize), blockXsize + 1, blockYsize + 1)) { g.DrawImage(bitmap, (int)(tLx / overviewPow) + (i * blockXsize), (int)(tLy / overviewPow) + (j * blockYsize)); } } } } private Bitmap ReadArgb(int xOffset, int yOffset, int xSize, int ySize, Band first, Dataset set) { if (set.RasterCount < 4) { throw new GdalException("ARGB Format was indicated but there are only " + set.RasterCount + " bands!"); } Band firstO; Band redO; Band greenO; Band blueO; var disposeO = false; Band red = set.GetRasterBand(2); Band green = set.GetRasterBand(3); Band blue = set.GetRasterBand(4); if (_overview >= 0 && first.GetOverviewCount() > 0) { firstO = first.GetOverview(_overview); redO = red.GetOverview(_overview); greenO = green.GetOverview(_overview); blueO = blue.GetOverview(_overview); disposeO = true; } else { firstO = first; redO = red; greenO = green; blueO = blue; } int width, height; NormalizeSizeToBand(xOffset, yOffset, xSize, ySize, firstO, out width, out height); Bitmap result = new Bitmap(width, height, PixelFormat.Format32bppArgb); byte[] a = new byte[width * height]; byte[] r = new byte[width * height]; byte[] g = new byte[width * height]; byte[] b = new byte[width * height]; firstO.ReadRaster(0, 0, width, height, a, width, height, 0, 0); redO.ReadRaster(0, 0, width, height, r, width, height, 0, 0); greenO.ReadRaster(0, 0, width, height, g, width, height, 0, 0); blueO.ReadRaster(0, 0, width, height, b, width, height, 0, 0); if (disposeO) { firstO.Dispose(); redO.Dispose(); greenO.Dispose(); blueO.Dispose(); } // Alpha disposed in caller red.Dispose(); green.Dispose(); blue.Dispose(); BitmapData bData = result.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); int stride = Math.Abs(bData.Stride); byte[] vals = new byte[height * stride]; for (int row = 0; row < height; row++) { for (int col = 0; col < width; col++) { vals[(row * stride) + (col * 4)] = b[(row * width) + col]; vals[(row * stride) + (col * 4) + 1] = g[(row * width) + col]; vals[(row * stride) + (col * 4) + 2] = r[(row * width) + col]; vals[(row * stride) + (col * 4) + 3] = a[(row * width) + col]; } } Marshal.Copy(vals, 0, bData.Scan0, vals.Length); result.UnlockBits(bData); return result; } private Bitmap ReadGrayIndex(int xOffset, int yOffset, int xSize, int ySize, Band first) { Band firstO; var disposeO = false; if (_overview >= 0 && first.GetOverviewCount() > 0) { firstO = first.GetOverview(_overview); disposeO = true; } else { firstO = first; } int width, height; NormalizeSizeToBand(xOffset, yOffset, xSize, ySize, firstO, out width, out height); Bitmap result = new Bitmap(width, height, PixelFormat.Format32bppArgb); byte[] r = new byte[width * height]; firstO.ReadRaster(xOffset, yOffset, width, height, r, width, height, 0, 0); if (disposeO) { firstO.Dispose(); } BitmapData bData = result.LockBits(new Rectangle(0, 0, xSize, ySize), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); int stride = Math.Abs(bData.Stride); byte[] vals = new byte[height * stride]; for (int row = 0; row < height; row++) { for (int col = 0; col < width; col++) { byte value = r[(row * width) + col]; vals[(row * stride) + (col * 4)] = value; vals[(row * stride) + (col * 4) + 1] = value; vals[(row * stride) + (col * 4) + 2] = value; vals[(row * stride) + (col * 4) + 3] = 255; } } Marshal.Copy(vals, 0, bData.Scan0, vals.Length); result.UnlockBits(bData); return result; } /// <summary> /// Gets the size of the whole image, but doesn't keep the image open /// unless it was already open. /// </summary> private void ReadHeader() { _dataset = Helpers.Open(Filename); Width = _dataset.RasterXSize; Height = _dataset.RasterYSize; NumBands = _dataset.RasterCount; var test = new double[6]; _dataset.GetGeoTransform(test); test = new AffineTransform(test).TransfromToCorner(0.5, 0.5); // shift origin by half a cell ProjectionString = _dataset.GetProjection(); Bounds = new RasterBounds(Height, Width, test); WorldFile.Affine = test; Close(); } private Bitmap ReadPaletteBuffered(int xOffset, int yOffset, int xSize, int ySize, Band first) { ColorTable ct = first.GetRasterColorTable(); if (ct == null) { throw new GdalException("Image was stored with a palette interpretation but has no color table."); } if (ct.GetPaletteInterpretation() != PaletteInterp.GPI_RGB) { throw new GdalException("Only RGB palette interpretation is currently supported by this " + " plug-in, " + ct.GetPaletteInterpretation() + " is not supported."); } Band firstO; bool disposeO = false; if (_overview >= 0 && first.GetOverviewCount() > 0) { firstO = first.GetOverview(_overview); disposeO = true; } else { firstO = first; } int width, height; NormalizeSizeToBand(xOffset, yOffset, xSize, ySize, firstO, out width, out height); byte[] r = new byte[width * height]; firstO.ReadRaster(xOffset, yOffset, width, height, r, width, height, 0, 0); if (disposeO) { firstO.Dispose(); } Bitmap result = new Bitmap(width, height, PixelFormat.Format32bppArgb); BitmapData bData = result.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); int stride = Math.Abs(bData.Stride); const int Bpp = 4; byte[] vals = new byte[stride * height]; byte[][] colorTable = new byte[ct.GetCount()][]; for (int i = 0; i < ct.GetCount(); i++) { ColorEntry ce = ct.GetColorEntry(i); colorTable[i] = new[] { (byte)ce.c3, (byte)ce.c2, (byte)ce.c1, (byte)ce.c4 }; } for (int row = 0; row < height; row++) { for (int col = 0; col < width; col++) { Array.Copy(colorTable[r[col + (row * width)]], 0, vals, (row * stride) + (col * Bpp), 4); } } Marshal.Copy(vals, 0, bData.Scan0, vals.Length); result.UnlockBits(bData); return result; } private Bitmap ReadRgb(int xOffset, int yOffset, int xSize, int ySize, Band first, Dataset set) { if (set.RasterCount < 3) { throw new GdalException("RGB Format was indicated but there are only " + set.RasterCount + " bands!"); } Band firstO; Band greenO; Band blueO; var disposeO = false; var green = set.GetRasterBand(2); var blue = set.GetRasterBand(3); if (_overview >= 0 && first.GetOverviewCount() > 0) { firstO = first.GetOverview(_overview); greenO = green.GetOverview(_overview); blueO = blue.GetOverview(_overview); disposeO = true; } else { firstO = first; greenO = green; blueO = blue; } int width, height; NormalizeSizeToBand(xOffset, yOffset, xSize, ySize, firstO, out width, out height); Bitmap result = new Bitmap(width, height, PixelFormat.Format32bppArgb); byte[] r = new byte[width * height]; byte[] g = new byte[width * height]; byte[] b = new byte[width * height]; firstO.ReadRaster(xOffset, yOffset, width, height, r, width, height, 0, 0); greenO.ReadRaster(xOffset, yOffset, width, height, g, width, height, 0, 0); blueO.ReadRaster(xOffset, yOffset, width, height, b, width, height, 0, 0); if (disposeO) { // It's local copies, dispose them firstO.Dispose(); greenO.Dispose(); blueO.Dispose(); } green.Dispose(); blue.Dispose(); var bData = result.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); int stride = Math.Abs(bData.Stride); var vals = new byte[width * height * 4]; for (int row = 0; row < height; row++) { for (int col = 0; col < width; col++) { vals[(row * stride) + (col * 4)] = b[(row * width) + col]; vals[(row * stride) + (col * 4) + 1] = g[(row * width) + col]; vals[(row * stride) + (col * 4) + 2] = r[(row * width) + col]; vals[(row * stride) + (col * 4) + 3] = 255; } } Marshal.Copy(vals, 0, bData.Scan0, vals.Length); result.UnlockBits(bData); return result; } #endregion } }
//------------------------------------------------------------------------------ // <copyright file="PrintPreviewDialog.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Windows.Forms { using Microsoft.Win32; using System; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.Drawing.Design; using System.Drawing.Printing; using System.Runtime.Remoting; using System.Windows.Forms.Design; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Runtime.Versioning; /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog"]/*' /> /// <devdoc> /// <para> Represents a /// dialog box form that contains a <see cref='System.Windows.Forms.PrintPreviewControl'/>.</para> /// </devdoc> [ ComVisible(true), ClassInterface(ClassInterfaceType.AutoDispatch), Designer("System.ComponentModel.Design.ComponentDesigner, " + AssemblyRef.SystemDesign), DesignTimeVisible(true), DefaultProperty("Document"), ToolboxItemFilter("System.Windows.Forms.Control.TopLevel"), ToolboxItem(true), SRDescription(SR.DescriptionPrintPreviewDialog) ] public class PrintPreviewDialog : Form { PrintPreviewControl previewControl; private System.Windows.Forms.ToolStrip toolStrip1; private System.Windows.Forms.NumericUpDown pageCounter; private System.Windows.Forms.ToolStripButton printToolStripButton; private System.Windows.Forms.ToolStripSplitButton zoomToolStripSplitButton; private System.Windows.Forms.ToolStripMenuItem autoToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem2; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem3; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem4; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem5; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem6; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem7; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem8; private System.Windows.Forms.ToolStripSeparator separatorToolStripSeparator; private System.Windows.Forms.ToolStripButton onepageToolStripButton; private System.Windows.Forms.ToolStripButton twopagesToolStripButton; private System.Windows.Forms.ToolStripButton threepagesToolStripButton; private System.Windows.Forms.ToolStripButton fourpagesToolStripButton; private System.Windows.Forms.ToolStripButton sixpagesToolStripButton; private System.Windows.Forms.ToolStripSeparator separatorToolStripSeparator1; private System.Windows.Forms.ToolStripButton closeToolStripButton; private System.Windows.Forms.ToolStripLabel pageToolStripLabel; ImageList imageList; /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.PrintPreviewDialog"]/*' /> /// <devdoc> /// <para>Initializes a new instance of the <see cref='System.Windows.Forms.PrintPreviewDialog'/> class.</para> /// </devdoc> public PrintPreviewDialog() { #pragma warning disable 618 base.AutoScaleBaseSize = new Size(5, 13); #pragma warning restore 618 this.previewControl = new PrintPreviewControl(); this.imageList = new ImageList(); Bitmap bitmaps = new Bitmap(typeof(PrintPreviewDialog), "PrintPreviewStrip.bmp"); bitmaps.MakeTransparent(); imageList.Images.AddStrip(bitmaps); InitForm(); } //subhag addition //------------------------------------------------------------------------------------------------------------- /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.AcceptButton"]/*' /> /// <devdoc> /// <para>Indicates the <see cref='System.Windows.Forms.Button'/> control on the form that is clicked when /// the user presses the ENTER key.</para> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public IButtonControl AcceptButton { get { return base.AcceptButton; } set { base.AcceptButton = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.AutoScale"]/*' /> /// <devdoc> /// <para> /// Gets or sets a value indicating whether the form will adjust its size /// to fit the height of the font used on the form and scale /// its controls. /// </para> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public bool AutoScale { get { #pragma warning disable 618 return base.AutoScale; #pragma warning restore 618 } set { #pragma warning disable 618 base.AutoScale = value; #pragma warning restore 618 } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.AutoScroll"]/*' /> /// <devdoc> /// <para> /// Gets or sets a value indicating whether the form implements /// autoscrolling. /// </para> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public override bool AutoScroll { get { return base.AutoScroll; } set { base.AutoScroll = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.AutoSize"]/*' /> /// <devdoc> /// <para> /// Hide the property /// </para> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public override bool AutoSize { get { return base.AutoSize; } set { base.AutoSize = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.AutoSizeChanged"]/*' /> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public event EventHandler AutoSizeChanged { add { base.AutoSizeChanged += value; } remove { base.AutoSizeChanged -= value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.AutoValidate"]/*' /> /// <devdoc> /// <para> /// Hide the property /// </para> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public override AutoValidate AutoValidate { get { return base.AutoValidate; } set { base.AutoValidate = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.AutoValidateChanged"]/*' /> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new event EventHandler AutoValidateChanged { add { base.AutoValidateChanged += value; } remove { base.AutoValidateChanged -= value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.BackColor"]/*' /> /// <devdoc> /// The background color of this control. This is an ambient property and /// will always return a non-null value. /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public override Color BackColor { get { return base.BackColor; } set { base.BackColor = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.BackColorChanged"]/*' /> /// <internalonly/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public event EventHandler BackColorChanged { add { base.BackColorChanged += value; } remove { base.BackColorChanged -= value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.CancelButton"]/*' /> /// <devdoc> /// <para>Gets /// or /// sets the button control that will be clicked when the /// user presses the ESC key.</para> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public IButtonControl CancelButton { get { return base.CancelButton; } set { base.CancelButton = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.ControlBox"]/*' /> /// <devdoc> /// <para>Gets or sets a value indicating whether a control box is displayed in the /// caption bar of the form.</para> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public bool ControlBox { get { return base.ControlBox; } set { base.ControlBox = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.ContextMenuStrip"]/*' /> /// <devdoc> /// Hide the property /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public override ContextMenuStrip ContextMenuStrip { get { return base.ContextMenuStrip; } set { base.ContextMenuStrip = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.ContextMenuStripChanged"]/*' /> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new event EventHandler ContextMenuStripChanged { add { base.ContextMenuStripChanged += value; } remove { base.ContextMenuStripChanged -= value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.FormBorderStyle"]/*' /> /// <devdoc> /// <para> /// Gets or sets the border style of the form. /// </para> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public FormBorderStyle FormBorderStyle { get { return base.FormBorderStyle; } set { base.FormBorderStyle = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.HelpButton"]/*' /> /// <devdoc> /// <para> /// Gets or sets a value indicating whether a /// help button should be displayed in the caption box of the form. /// </para> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public bool HelpButton { get { return base.HelpButton; } set { base.HelpButton = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.Icon"]/*' /> /// <devdoc> /// <para> /// Gets or sets the icon for the form. /// </para> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public Icon Icon { [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] get { return base.Icon; } set { base.Icon = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.IsMdiContainer"]/*' /> /// <devdoc> /// <para> /// Gets or sets a value indicating whether the form is a container for multiple document interface /// (MDI) child forms. /// </para> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public bool IsMdiContainer { get { return base.IsMdiContainer; } set { base.IsMdiContainer = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.KeyPreview"]/*' /> /// <devdoc> /// <para> /// Gets or sets a value /// indicating whether the form will receive key events /// before the event is passed to the control that has focus. /// </para> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public bool KeyPreview { get { return base.KeyPreview; } set { base.KeyPreview = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.MaximumSize"]/*' /> /// <devdoc> /// <para> /// Gets or Sets the maximum size the dialog can be resized to. /// </para> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public Size MaximumSize { get { return base.MaximumSize; } set { base.MaximumSize = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.MaximumSizeChanged"]/*' /> /// <internalonly/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public event EventHandler MaximumSizeChanged { add { base.MaximumSizeChanged += value; } remove { base.MaximumSizeChanged -= value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.MaximizeBox"]/*' /> /// <devdoc> /// <para>Gets or sets a value indicating whether the maximize button is /// displayed in the caption bar of the form.</para> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public bool MaximizeBox { get { return base.MaximizeBox; } set { base.MaximizeBox = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.Margin"]/*' /> /// <devdoc> /// Hide the value /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public Padding Margin { get { return base.Margin; } set { base.Margin = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.MarginChanged"]/*' /> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new event EventHandler MarginChanged { add { base.MarginChanged += value; } remove { base.MarginChanged -= value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.Menu"]/*' /> /// <devdoc> /// <para> /// Gets or sets the <see cref='System.Windows.Forms.MainMenu'/> /// that is displayed in the form. /// </para> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public MainMenu Menu { get { return base.Menu; } set { base.Menu = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.MinimumSize"]/*' /> /// <devdoc> /// <para> /// Gets the minimum size the form can be resized to. /// </para> /// </devdoc> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), EditorBrowsable(EditorBrowsableState.Never)] new public Size MinimumSize { get { return base.MinimumSize; } set { base.MinimumSize = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.MinimumSizeChanged"]/*' /> /// <internalonly/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public event EventHandler MinimumSizeChanged { add { base.MinimumSizeChanged += value; } remove { base.MinimumSizeChanged -= value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.Padding"]/*' /> /// <devdoc> /// <para> /// Hide the value /// </para> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public Padding Padding { get { return base.Padding; } set { base.Padding = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.PaddingChanged"]/*' /> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new event EventHandler PaddingChanged { add { base.PaddingChanged += value; } remove { base.PaddingChanged -= value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.Size"]/*' /> /// <devdoc> /// <para> /// Gets or sets the size of the form. /// </para> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public Size Size { get { return base.Size; } set { base.Size = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.SizeChanged"]/*' /> /// <internalonly/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public event EventHandler SizeChanged { add { base.SizeChanged += value; } remove { base.SizeChanged -= value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.StartPosition"]/*' /> /// <devdoc> /// <para> /// Gets or sets the /// starting position of the form at run time. /// </para> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public FormStartPosition StartPosition { get { return base.StartPosition; } set { base.StartPosition = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.TopMost"]/*' /> /// <devdoc> /// <para>Gets or sets a value indicating whether the form should be displayed as the top-most /// form of your application.</para> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public bool TopMost { get { return base.TopMost; } set { base.TopMost = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.TransparencyKey"]/*' /> /// <devdoc> /// <para>Gets or sets the color that will represent transparent areas of the form.</para> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public Color TransparencyKey { get { return base.TransparencyKey; } set { base.TransparencyKey = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.UseWaitCursor"]/*' /> /// <devdoc> /// <para>Hide the value</para> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public bool UseWaitCursor{ get { return base.UseWaitCursor; } set { base.UseWaitCursor = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.WindowState"]/*' /> /// <devdoc> /// <para> Gets or sets the form's window state. /// </para> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public FormWindowState WindowState { get { return base.WindowState; } set { base.WindowState = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.AccessibleRole"]/*' /> /// <devdoc> /// The accessible role of the control /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public AccessibleRole AccessibleRole { get { return base.AccessibleRole; } set { base.AccessibleRole = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.AccessibleDescription"]/*' /> /// <devdoc> /// The accessible description of the control /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public string AccessibleDescription { get { return base.AccessibleDescription; } set { base.AccessibleDescription = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.AccessibleName"]/*' /> /// <devdoc> /// The accessible name of the control /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public string AccessibleName { get { return base.AccessibleName; } set { base.AccessibleName = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.CausesValidation"]/*' /> /// <devdoc> /// <para> /// Indicates whether entering the control causes validation on the controls requiring validation.</para> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public bool CausesValidation { get { return base.CausesValidation; } set { base.CausesValidation = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.CausesValidationChanged"]/*' /> /// <internalonly/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public event EventHandler CausesValidationChanged { add { base.CausesValidationChanged += value; } remove { base.CausesValidationChanged -= value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.DataBindings"]/*' /> /// <devdoc> /// Retrieves the bindings for this control. /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public ControlBindingsCollection DataBindings { get { return base.DataBindings; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.DefaultMinimumSize"]/*' /> protected override Size DefaultMinimumSize { get { return new Size(375, 250); } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.Enabled"]/*' /> /// <devdoc> /// <para>Indicates whether the control is currently enabled.</para> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public bool Enabled { get { return base.Enabled; } set { base.Enabled = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.EnabledChanged"]/*' /> /// <internalonly/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public event EventHandler EnabledChanged { add { base.EnabledChanged += value; } remove { base.EnabledChanged -= value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.Location"]/*' /> /// <devdoc> /// The location of this control. /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] new public Point Location { get { return base.Location; } set { base.Location = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.LocationChanged"]/*' /> /// <internalonly/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public event EventHandler LocationChanged { add { base.LocationChanged += value; } remove { base.LocationChanged -= value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.Tag"]/*' /> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public object Tag { get { return base.Tag; } set { base.Tag = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.AllowDrop"]/*' /> /// <devdoc> /// The AllowDrop property. If AllowDrop is set to true then /// this control will allow drag and drop operations and events to be used. /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public override bool AllowDrop { get { return base.AllowDrop; } set { base.AllowDrop = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.Cursor"]/*' /> /// <devdoc> /// Retrieves the cursor that will be displayed when the mouse is over this /// control. /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public override Cursor Cursor { get { return base.Cursor; } set { base.Cursor = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.CursorChanged"]/*' /> /// <internalonly/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public event EventHandler CursorChanged { add { base.CursorChanged += value; } remove { base.CursorChanged -= value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.BackgroundImage"]/*' /> /// <devdoc> /// The background image of the control. /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public override Image BackgroundImage { get { return base.BackgroundImage; } set { base.BackgroundImage = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.BackgroundImageChanged"]/*' /> /// <internalonly/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public event EventHandler BackgroundImageChanged { add { base.BackgroundImageChanged += value; } remove { base.BackgroundImageChanged -= value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.BackgroundImageLayout"]/*' /> /// <devdoc> /// The background image layout of the control. /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public override ImageLayout BackgroundImageLayout { get { return base.BackgroundImageLayout; } set { base.BackgroundImageLayout = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.BackgroundImageLayoutChanged"]/*' /> /// <internalonly/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public event EventHandler BackgroundImageLayoutChanged { add { base.BackgroundImageLayoutChanged += value; } remove { base.BackgroundImageLayoutChanged -= value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.ImeMode"]/*' /> /// <devdoc> /// Specifies a value that determines the IME (Input Method Editor) status of the /// object when that object is selected. /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public ImeMode ImeMode { get { return base.ImeMode; } set { base.ImeMode = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.ImeModeChanged"]/*' /> /// <internalonly/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new event EventHandler ImeModeChanged { add { base.ImeModeChanged += value; } remove { base.ImeModeChanged -= value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.AutoScrollMargin"]/*' /> /// <devdoc> /// <para> /// Gets or /// sets the size of the auto-scroll /// margin. /// </para> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public Size AutoScrollMargin { get { return base.AutoScrollMargin; } set { base.AutoScrollMargin = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.AutoScrollMinSize"]/*' /> /// <devdoc> /// <para>Gets or sets the mimimum size of the auto-scroll.</para> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public Size AutoScrollMinSize { get { return base.AutoScrollMinSize; } set { base.AutoScrollMinSize = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.Anchor"]/*' /> /// <devdoc> /// The current value of the anchor property. The anchor property /// determines which edges of the control are anchored to the container's /// edges. /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public override AnchorStyles Anchor { get { return base.Anchor; } set { base.Anchor = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.Visible"]/*' /> /// <devdoc> /// <para>Indicates whether the control is visible.</para> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public bool Visible { get { return base.Visible; } set { base.Visible = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.VisibleChanged"]/*' /> /// <internalonly/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public event EventHandler VisibleChanged { add { base.VisibleChanged += value; } remove { base.VisibleChanged -= value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.ForeColor"]/*' /> /// <devdoc> /// The foreground color of the control. /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public override Color ForeColor { get { return base.ForeColor; } set { base.ForeColor = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.ForeColorChanged"]/*' /> /// <internalonly/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public event EventHandler ForeColorChanged { add { base.ForeColorChanged += value; } remove { base.ForeColorChanged -= value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.RightToLeft"]/*' /> /// <devdoc> /// This is used for international applications where the language /// is written from RightToLeft. When this property is true, /// control placement and text will be from right to left. /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public override RightToLeft RightToLeft { get { return base.RightToLeft; } set { base.RightToLeft = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.RightToLeftLayout"]/*' /> /// <devdoc> /// This is used for international applications where the language /// is written from RightToLeft. When this property is true, // and the RightToLeft is true, mirroring will be turned on on the form, and /// control placement and text will be from right to left. /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public override bool RightToLeftLayout { get { return base.RightToLeftLayout; } set { base.RightToLeftLayout = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.RightToLeftChanged"]/*' /> /// <internalonly/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new event EventHandler RightToLeftChanged { add { base.RightToLeftChanged += value; } remove { base.RightToLeftChanged -= value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.RightToLeftLayoutChanged"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new event EventHandler RightToLeftLayoutChanged { add { base.RightToLeftLayoutChanged += value; } remove { base.RightToLeftLayoutChanged -= value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.TabStop"]/*' /> /// <devdoc> /// <para>Indicates whether the user can give the focus to this control using the TAB /// key. This property is read-only.</para> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public bool TabStop { get { return base.TabStop; } set { base.TabStop = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.TabStopChanged"]/*' /> /// <internalonly/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public event EventHandler TabStopChanged { add { base.TabStopChanged += value; } remove { base.TabStopChanged -= value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.Text"]/*' /> /// <devdoc> /// The current text associated with this control. /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public override string Text { get { return base.Text; } set { base.Text = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.TextChanged"]/*' /> /// <internalonly/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public event EventHandler TextChanged { add { base.TextChanged += value; } remove { base.TextChanged -= value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.Dock"]/*' /> /// <devdoc> /// The dock property. The dock property controls to which edge /// of the container this control is docked to. For example, when docked to /// the top of the container, the control will be displayed flush at the /// top of the container, extending the length of the container. /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public override DockStyle Dock { get { return base.Dock; } set { base.Dock = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.DockChanged"]/*' /> /// <internalonly/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public event EventHandler DockChanged { add { base.DockChanged += value; } remove { base.DockChanged -= value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.Font"]/*' /> /// <devdoc> /// Retrieves the current font for this control. This will be the font used /// by default for painting and text in the control. /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public override Font Font { get { return base.Font; } set { base.Font = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.FontChanged"]/*' /> /// <internalonly/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public event EventHandler FontChanged { add { base.FontChanged += value; } remove { base.FontChanged -= value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.ContextMenu"]/*' /> /// <devdoc> /// The contextMenu associated with this control. The contextMenu /// will be shown when the user right clicks the mouse on the control. /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public override ContextMenu ContextMenu { get { return base.ContextMenu; } set { base.ContextMenu = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.ContextMenuChanged"]/*' /> /// <internalonly/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new event EventHandler ContextMenuChanged { add { base.ContextMenuChanged += value; } remove { base.ContextMenuChanged -= value; } } // DockPadding is not relevant to UpDownBase /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.DockPadding"]/*' /> /// <internalonly/> /// <devdoc> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public DockPaddingEdges DockPadding { get { return base.DockPadding; } } //------------------------------------------------------------------------------------------------------------- //end addition /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.UseAntiAlias"]/*' /> [ SRCategory(SR.CatBehavior), DefaultValue(false), SRDescription(SR.PrintPreviewAntiAliasDescr) ] public bool UseAntiAlias { get { return PrintPreviewControl.UseAntiAlias; } set { PrintPreviewControl.UseAntiAlias = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.AutoScaleBaseSize"]/*' /> /// <devdoc> /// <para> /// PrintPreviewDialog does not support AutoScaleBaseSize. /// </para> /// </devdoc> /// Keeping implementation of obsoleted AutoScaleBaseSize API #pragma warning disable 618 // disable csharp compiler warning #0809: obsolete member overrides non-obsolete member #pragma warning disable 0809 [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("This property has been deprecated. Use the AutoScaleDimensions property instead. http://go.microsoft.com/fwlink/?linkid=14202")] public override Size AutoScaleBaseSize { get { return base.AutoScaleBaseSize; } set { // No-op } } #pragma warning restore 0809 #pragma warning restore 618 /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.Document"]/*' /> /// <devdoc> /// <para> /// Gets or sets the document to preview. /// </para> /// </devdoc> [ SRCategory(SR.CatBehavior), DefaultValue(null), SRDescription(SR.PrintPreviewDocumentDescr) ] public PrintDocument Document { get { return previewControl.Document; } set { previewControl.Document = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.MinimizeBox"]/*' /> [Browsable(false), DefaultValue(false), EditorBrowsable(EditorBrowsableState.Never)] public new bool MinimizeBox { get { return base.MinimizeBox; } set { base.MinimizeBox = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.PrintPreviewControl"]/*' /> /// <devdoc> /// <para>Gets or sets a value indicating the <see cref='System.Windows.Forms.PrintPreviewControl'/> /// contained in this form.</para> /// </devdoc> [ SRCategory(SR.CatBehavior), SRDescription(SR.PrintPreviewPrintPreviewControlDescr), Browsable(false) ] public PrintPreviewControl PrintPreviewControl { get { return previewControl;} } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.Opacity"]/*' /> /// <internalonly/> /// <devdoc> /// <para> /// Opacity does not apply to PrintPreviewDialogs. /// </para> /// </devdoc> [Browsable(false),EditorBrowsable(EditorBrowsableState.Advanced)] public new double Opacity { get { return base.Opacity; } set { base.Opacity = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.ShowInTaskbar"]/*' /> [Browsable(false), DefaultValue(false), EditorBrowsable(EditorBrowsableState.Never)] public new bool ShowInTaskbar { get { return base.ShowInTaskbar; } set { base.ShowInTaskbar = value; } } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.SizeGripStyle"]/*' /> [Browsable(false), DefaultValue(SizeGripStyle.Hide), EditorBrowsable(EditorBrowsableState.Never)] public new SizeGripStyle SizeGripStyle { get { return base.SizeGripStyle; } set { base.SizeGripStyle = value; } } [ SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters") // The default page count is 1. // So we don't have to localize it. ] void InitForm() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PrintPreviewDialog)); this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.printToolStripButton = new System.Windows.Forms.ToolStripButton(); this.zoomToolStripSplitButton = new System.Windows.Forms.ToolStripSplitButton(); this.autoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem3 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem4 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem5 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem6 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem7 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem8 = new System.Windows.Forms.ToolStripMenuItem(); this.separatorToolStripSeparator = new System.Windows.Forms.ToolStripSeparator(); this.onepageToolStripButton = new System.Windows.Forms.ToolStripButton(); this.twopagesToolStripButton = new System.Windows.Forms.ToolStripButton(); this.threepagesToolStripButton = new System.Windows.Forms.ToolStripButton(); this.fourpagesToolStripButton = new System.Windows.Forms.ToolStripButton(); this.sixpagesToolStripButton = new System.Windows.Forms.ToolStripButton(); this.separatorToolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.closeToolStripButton = new System.Windows.Forms.ToolStripButton(); this.pageCounter = new System.Windows.Forms.NumericUpDown(); this.pageToolStripLabel = new System.Windows.Forms.ToolStripLabel(); this.toolStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pageCounter)).BeginInit(); this.SuspendLayout(); // // toolStrip1 // resources.ApplyResources(this.toolStrip1, "toolStrip1"); this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.printToolStripButton, this.zoomToolStripSplitButton, this.separatorToolStripSeparator, this.onepageToolStripButton, this.twopagesToolStripButton, this.threepagesToolStripButton, this.fourpagesToolStripButton, this.sixpagesToolStripButton, this.separatorToolStripSeparator1, this.closeToolStripButton}); this.toolStrip1.Name = "toolStrip1"; this.toolStrip1.RenderMode = System.Windows.Forms.ToolStripRenderMode.System; this.toolStrip1.GripStyle = ToolStripGripStyle.Hidden; // // printToolStripButton // this.printToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.printToolStripButton.Name = "printToolStripButton"; resources.ApplyResources(this.printToolStripButton, "printToolStripButton"); // // zoomToolStripSplitButton // this.zoomToolStripSplitButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.zoomToolStripSplitButton.DoubleClickEnabled = true; this.zoomToolStripSplitButton.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.autoToolStripMenuItem, this.toolStripMenuItem1, this.toolStripMenuItem2, this.toolStripMenuItem3, this.toolStripMenuItem4, this.toolStripMenuItem5, this.toolStripMenuItem6, this.toolStripMenuItem7, this.toolStripMenuItem8}); this.zoomToolStripSplitButton.Name = "zoomToolStripSplitButton"; this.zoomToolStripSplitButton.SplitterWidth = 1; resources.ApplyResources(this.zoomToolStripSplitButton, "zoomToolStripSplitButton"); // // autoToolStripMenuItem // this.autoToolStripMenuItem.CheckOnClick = true; this.autoToolStripMenuItem.DoubleClickEnabled = true; this.autoToolStripMenuItem.Checked = true; this.autoToolStripMenuItem.Name = "autoToolStripMenuItem"; resources.ApplyResources(this.autoToolStripMenuItem, "autoToolStripMenuItem"); // // toolStripMenuItem1 // this.toolStripMenuItem1.CheckOnClick = true; this.toolStripMenuItem1.DoubleClickEnabled = true; this.toolStripMenuItem1.Name = "toolStripMenuItem1"; resources.ApplyResources(this.toolStripMenuItem1, "toolStripMenuItem1"); // // toolStripMenuItem2 // this.toolStripMenuItem2.CheckOnClick = true; this.toolStripMenuItem2.DoubleClickEnabled = true; this.toolStripMenuItem2.Name = "toolStripMenuItem2"; resources.ApplyResources(this.toolStripMenuItem2, "toolStripMenuItem2"); // // toolStripMenuItem3 // this.toolStripMenuItem3.CheckOnClick = true; this.toolStripMenuItem3.DoubleClickEnabled = true; this.toolStripMenuItem3.Name = "toolStripMenuItem3"; resources.ApplyResources(this.toolStripMenuItem3, "toolStripMenuItem3"); // // toolStripMenuItem4 // this.toolStripMenuItem4.CheckOnClick = true; this.toolStripMenuItem4.DoubleClickEnabled = true; this.toolStripMenuItem4.Name = "toolStripMenuItem4"; resources.ApplyResources(this.toolStripMenuItem4, "toolStripMenuItem4"); // // toolStripMenuItem5 // this.toolStripMenuItem5.CheckOnClick = true; this.toolStripMenuItem5.DoubleClickEnabled = true; this.toolStripMenuItem5.Name = "toolStripMenuItem5"; resources.ApplyResources(this.toolStripMenuItem5, "toolStripMenuItem5"); // // toolStripMenuItem6 // this.toolStripMenuItem6.CheckOnClick = true; this.toolStripMenuItem6.DoubleClickEnabled = true; this.toolStripMenuItem6.Name = "toolStripMenuItem6"; resources.ApplyResources(this.toolStripMenuItem6, "toolStripMenuItem6"); // // toolStripMenuItem7 // this.toolStripMenuItem7.CheckOnClick = true; this.toolStripMenuItem7.DoubleClickEnabled = true; this.toolStripMenuItem7.Name = "toolStripMenuItem7"; resources.ApplyResources(this.toolStripMenuItem7, "toolStripMenuItem7"); // // toolStripMenuItem8 // this.toolStripMenuItem8.CheckOnClick = true; this.toolStripMenuItem8.DoubleClickEnabled = true; this.toolStripMenuItem8.Name = "toolStripMenuItem8"; resources.ApplyResources(this.toolStripMenuItem8, "toolStripMenuItem8"); // // separatorToolStripSeparator // this.separatorToolStripSeparator.Name = "separatorToolStripSeparator"; // // onepageToolStripButton // this.onepageToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.onepageToolStripButton.Name = "onepageToolStripButton"; resources.ApplyResources(this.onepageToolStripButton, "onepageToolStripButton"); // // twopagesToolStripButton // this.twopagesToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.twopagesToolStripButton.Name = "twopagesToolStripButton"; resources.ApplyResources(this.twopagesToolStripButton, "twopagesToolStripButton"); // // threepagesToolStripButton // this.threepagesToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.threepagesToolStripButton.Name = "threepagesToolStripButton"; resources.ApplyResources(this.threepagesToolStripButton, "threepagesToolStripButton"); // // fourpagesToolStripButton // this.fourpagesToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.fourpagesToolStripButton.Name = "fourpagesToolStripButton"; resources.ApplyResources(this.fourpagesToolStripButton, "fourpagesToolStripButton"); // // sixpagesToolStripButton // this.sixpagesToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.sixpagesToolStripButton.Name = "sixpagesToolStripButton"; resources.ApplyResources(this.sixpagesToolStripButton, "sixpagesToolStripButton"); // // separatorToolStripSeparator1 // this.separatorToolStripSeparator1.Name = "separatorToolStripSeparator1"; // // closeToolStripButton // this.closeToolStripButton.DisplayStyle = ToolStripItemDisplayStyle.Text; this.closeToolStripButton.Name = "closeToolStripButton"; resources.ApplyResources(this.closeToolStripButton, "closeToolStripButton"); // // pageCounter // resources.ApplyResources(this.pageCounter, "pageCounter"); pageCounter.Text = "1"; pageCounter.TextAlign = HorizontalAlignment.Right; pageCounter.DecimalPlaces = 0; pageCounter.Minimum = new Decimal(0d); pageCounter.Maximum = new Decimal(1000d); pageCounter.ValueChanged += new EventHandler(UpdownMove); this.pageCounter.Name = "pageCounter"; // // pageToolStripLabel // this.pageToolStripLabel.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; this.pageToolStripLabel.Name = "pageToolStripLabel"; resources.ApplyResources(this.pageToolStripLabel, "pageToolStripLabel"); previewControl.Size = new Size(792, 610); previewControl.Location = new Point(0, 43); previewControl.Dock = DockStyle.Fill; previewControl.StartPageChanged += new EventHandler(previewControl_StartPageChanged); //EVENTS and Images ... this.printToolStripButton.Click += new System.EventHandler(this.OnprintToolStripButtonClick); this.autoToolStripMenuItem.Click += new System.EventHandler(ZoomAuto); this.toolStripMenuItem1.Click += new System.EventHandler(Zoom500); this.toolStripMenuItem2.Click += new System.EventHandler(Zoom250); this.toolStripMenuItem3.Click += new System.EventHandler(Zoom150); this.toolStripMenuItem4.Click += new System.EventHandler(Zoom100); this.toolStripMenuItem5.Click += new System.EventHandler(Zoom75); this.toolStripMenuItem6.Click += new System.EventHandler(Zoom50); this.toolStripMenuItem7.Click += new System.EventHandler(Zoom25); this.toolStripMenuItem8.Click += new System.EventHandler(Zoom10); this.onepageToolStripButton.Click += new System.EventHandler(this.OnonepageToolStripButtonClick); this.twopagesToolStripButton.Click += new System.EventHandler(this.OntwopagesToolStripButtonClick); this.threepagesToolStripButton.Click += new System.EventHandler(this.OnthreepagesToolStripButtonClick); this.fourpagesToolStripButton.Click += new System.EventHandler(this.OnfourpagesToolStripButtonClick); this.sixpagesToolStripButton.Click += new System.EventHandler(this.OnsixpagesToolStripButtonClick); this.closeToolStripButton.Click += new System.EventHandler(this.OncloseToolStripButtonClick); this.closeToolStripButton.Paint += new PaintEventHandler(this.OncloseToolStripButtonPaint); //Images this.toolStrip1.ImageList = imageList; this.printToolStripButton.ImageIndex = 0; this.zoomToolStripSplitButton.ImageIndex = 1; this.onepageToolStripButton.ImageIndex = 2; this.twopagesToolStripButton.ImageIndex = 3; this.threepagesToolStripButton.ImageIndex = 4; this.fourpagesToolStripButton.ImageIndex = 5; this.sixpagesToolStripButton.ImageIndex = 6; //tabIndex previewControl.TabIndex = 0; toolStrip1.TabIndex = 1; //DefaultItem on the Zoom SplitButton zoomToolStripSplitButton.DefaultItem = autoToolStripMenuItem; //ShowCheckMargin ToolStripDropDownMenu menu = this.zoomToolStripSplitButton.DropDown as ToolStripDropDownMenu; if (menu != null) { menu.ShowCheckMargin = true; menu.ShowImageMargin = false; menu.RenderMode = System.Windows.Forms.ToolStripRenderMode.System; } //Create the ToolStripControlHost ToolStripControlHost pageCounterItem = new ToolStripControlHost(pageCounter); pageCounterItem.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; this.toolStrip1.Items.Add(pageCounterItem); this.toolStrip1.Items.Add(this.pageToolStripLabel); // // Form1 // resources.ApplyResources(this, "$this"); this.Controls.Add(previewControl); this.Controls.Add(this.toolStrip1); this.ClientSize = new Size(400, 300); this.MinimizeBox = false; this.ShowInTaskbar = false; this.SizeGripStyle = SizeGripStyle.Hide; this.toolStrip1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.pageCounter)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.OnClosing"]/*' /> /// <internalonly/> /// <devdoc> /// <para> /// Forces the preview to be regenerated every time the dialog comes up /// </para> /// </devdoc> protected override void OnClosing(CancelEventArgs e) { base.OnClosing(e); previewControl.InvalidatePreview(); } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.CreateHandle"]/*' /> /// <devdoc> /// <para>Creates the handle for the PrintPreviewDialog. If a /// subclass overrides this function, /// it must call the base implementation.</para> /// </devdoc> protected override void CreateHandle() { // We want to check printer settings before we push the modal message loop, // so the user has a chance to catch the exception instead of letting go to // the windows forms exception dialog. if (Document != null && !Document.PrinterSettings.IsValid) throw new InvalidPrinterException(Document.PrinterSettings); base.CreateHandle(); } [UIPermission(SecurityAction.LinkDemand, Window=UIPermissionWindow.AllWindows)] protected override bool ProcessDialogKey(Keys keyData) { if ((keyData & (Keys.Alt | Keys.Control)) == Keys.None) { Keys keyCode = (Keys)keyData & Keys.KeyCode; switch (keyCode) { case Keys.Left: case Keys.Right: case Keys.Up: case Keys.Down: return false; } } return base.ProcessDialogKey(keyData); } /// <devdoc> /// <para> /// In Everett we used to TAB around the PrintPreviewDialog. Now since the PageCounter is added into the ToolStrip we dont /// This is breaking from Everett. /// </para> /// </devdoc> [UIPermission(SecurityAction.LinkDemand, Window=UIPermissionWindow.AllWindows)] protected override bool ProcessTabKey(bool forward) { if (this.ActiveControl == this.previewControl) { this.pageCounter.FocusInternal(); return true; } return false; } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.ShouldSerializeAutoScaleBaseSize"]/*' /> /// <internalonly/> /// <devdoc> /// <para> /// AutoScaleBaseSize should never be persisted for PrintPreviewDialogs. /// </para> /// </devdoc> internal override bool ShouldSerializeAutoScaleBaseSize() { // This method is called when the dialog is "contained" on another form. // We should use our own base size, not the base size of our container. return false; } /// <include file='doc\PrintPreviewDialog.uex' path='docs/doc[@for="PrintPreviewDialog.ShouldSerializeText"]/*' /> internal override bool ShouldSerializeText() { return !Text.Equals(SR.GetString(SR.PrintPreviewDialog_PrintPreview)); } void OncloseToolStripButtonClick(object sender, System.EventArgs e) { this.Close(); } void previewControl_StartPageChanged(object sender, EventArgs e) { pageCounter.Value = previewControl.StartPage + 1; } void CheckZoomMenu(ToolStripMenuItem toChecked) { foreach (ToolStripMenuItem item in zoomToolStripSplitButton.DropDownItems) { item.Checked = toChecked == item; } } void ZoomAuto(object sender, EventArgs eventargs) { ToolStripMenuItem item = sender as ToolStripMenuItem; CheckZoomMenu(item); previewControl.AutoZoom = true; } void Zoom500(object sender, EventArgs eventargs) { ToolStripMenuItem item = sender as ToolStripMenuItem; CheckZoomMenu(item); previewControl.Zoom = 5.00; } void Zoom250(object sender, EventArgs eventargs) { ToolStripMenuItem item = sender as ToolStripMenuItem; CheckZoomMenu(item); previewControl.Zoom = 2.50; } void Zoom150(object sender, EventArgs eventargs) { ToolStripMenuItem item = sender as ToolStripMenuItem; CheckZoomMenu(item); previewControl.Zoom = 1.50; } void Zoom100(object sender, EventArgs eventargs) { ToolStripMenuItem item = sender as ToolStripMenuItem; CheckZoomMenu(item); previewControl.Zoom = 1.00; } void Zoom75(object sender, EventArgs eventargs) { ToolStripMenuItem item = sender as ToolStripMenuItem; CheckZoomMenu(item); previewControl.Zoom = .75; } void Zoom50(object sender, EventArgs eventargs) { ToolStripMenuItem item = sender as ToolStripMenuItem; CheckZoomMenu(item); previewControl.Zoom = .50; } void Zoom25(object sender, EventArgs eventargs) { ToolStripMenuItem item = sender as ToolStripMenuItem; CheckZoomMenu(item); previewControl.Zoom = .25; } void Zoom10(object sender, EventArgs eventargs) { ToolStripMenuItem item = sender as ToolStripMenuItem; CheckZoomMenu(item); previewControl.Zoom = .10; } void OncloseToolStripButtonPaint(object sender, PaintEventArgs e) { ToolStripItem item = sender as ToolStripItem; if (item != null && !item.Selected) { Rectangle rect = new Rectangle (0, 0 , item.Bounds.Width - 1, item.Bounds.Height - 1); using (Pen pen = new Pen(SystemColors.ControlDark)) { e.Graphics.DrawRectangle(pen, rect); } } } void OnprintToolStripButtonClick(object sender, System.EventArgs e) { if (previewControl.Document != null) { previewControl.Document.Print(); } } void OnzoomToolStripSplitButtonClick(object sender, System.EventArgs e) { ZoomAuto(null, EventArgs.Empty); } //-------- void OnonepageToolStripButtonClick(object sender, System.EventArgs e) { previewControl.Rows = 1; previewControl.Columns = 1; } void OntwopagesToolStripButtonClick(object sender, System.EventArgs e) { previewControl.Rows = 1; previewControl.Columns = 2; } void OnthreepagesToolStripButtonClick(object sender, System.EventArgs e) { previewControl.Rows = 1; previewControl.Columns = 3; } void OnfourpagesToolStripButtonClick(object sender, System.EventArgs e) { previewControl.Rows = 2; previewControl.Columns = 2; } void OnsixpagesToolStripButtonClick(object sender, System.EventArgs e) { previewControl.Rows = 2; previewControl.Columns = 3; } //---------------------- void UpdownMove(object sender, EventArgs eventargs) { int pageNum = ((int)pageCounter.Value) - 1; if (pageNum >= 0) { // -1 because users like to count from one, and programmers from 0 previewControl.StartPage = pageNum; // And previewControl_PropertyChanged will change it again, // ensuring it stays within legal bounds. } else { pageCounter.Value = previewControl.StartPage + 1; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.ServiceModel.Security; using System.IdentityModel.Selectors; namespace System.ServiceModel { public abstract class MessageSecurityVersion { public static MessageSecurityVersion WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11 { get { return WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11MessageSecurityVersion.Instance; } } public static MessageSecurityVersion WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10 { get { return WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10MessageSecurityVersion.Instance; } } public static MessageSecurityVersion WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10 { get { return WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10MessageSecurityVersion.Instance; } } public static MessageSecurityVersion WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12 { get { return WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12MessageSecurityVersion.Instance; } } public static MessageSecurityVersion WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10 { get { return WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10MessageSecurityVersion.Instance; } } public static MessageSecurityVersion WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10 { get { return WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10MessageSecurityVersion.Instance; } } public static MessageSecurityVersion Default { get { return WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11MessageSecurityVersion.Instance; } } internal static MessageSecurityVersion WSSXDefault { get { return WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12MessageSecurityVersion.Instance; } } internal MessageSecurityVersion() { } public SecurityVersion SecurityVersion { get { return MessageSecurityTokenVersion.SecurityVersion; } } public TrustVersion TrustVersion { get { return MessageSecurityTokenVersion.TrustVersion; } } public SecureConversationVersion SecureConversationVersion { get { return MessageSecurityTokenVersion.SecureConversationVersion; } } public SecurityTokenVersion SecurityTokenVersion { get { return MessageSecurityTokenVersion; } } public abstract SecurityPolicyVersion SecurityPolicyVersion { get; } public abstract BasicSecurityProfileVersion BasicSecurityProfileVersion { get; } internal abstract MessageSecurityTokenVersion MessageSecurityTokenVersion { get; } internal class WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11MessageSecurityVersion : MessageSecurityVersion { private static MessageSecurityVersion s_instance = new WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11MessageSecurityVersion(); public static MessageSecurityVersion Instance { get { return s_instance; } } public override BasicSecurityProfileVersion BasicSecurityProfileVersion { get { return null; } } internal override MessageSecurityTokenVersion MessageSecurityTokenVersion { get { return MessageSecurityTokenVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005; } } public override SecurityPolicyVersion SecurityPolicyVersion { get { return SecurityPolicyVersion.WSSecurityPolicy11; } } public override string ToString() { return "WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11"; } } internal class WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10MessageSecurityVersion : MessageSecurityVersion { private static MessageSecurityVersion s_instance = new WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10MessageSecurityVersion(); public static MessageSecurityVersion Instance { get { return s_instance; } } public override BasicSecurityProfileVersion BasicSecurityProfileVersion { get { return BasicSecurityProfileVersion.BasicSecurityProfile10; } } internal override MessageSecurityTokenVersion MessageSecurityTokenVersion { get { return MessageSecurityTokenVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005BasicSecurityProfile10; } } public override SecurityPolicyVersion SecurityPolicyVersion { get { return SecurityPolicyVersion.WSSecurityPolicy11; } } public override string ToString() { return "WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10"; } } internal class WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10MessageSecurityVersion : MessageSecurityVersion { private static MessageSecurityVersion s_instance = new WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10MessageSecurityVersion(); public static MessageSecurityVersion Instance { get { return s_instance; } } public override SecurityPolicyVersion SecurityPolicyVersion { get { return SecurityPolicyVersion.WSSecurityPolicy11; } } public override BasicSecurityProfileVersion BasicSecurityProfileVersion { get { return BasicSecurityProfileVersion.BasicSecurityProfile10; } } internal override MessageSecurityTokenVersion MessageSecurityTokenVersion { get { return MessageSecurityTokenVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005BasicSecurityProfile10; } } public override string ToString() { return "WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10"; } } internal class WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10MessageSecurityVersion : MessageSecurityVersion { private static MessageSecurityVersion s_instance = new WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10MessageSecurityVersion(); public static MessageSecurityVersion Instance { get { return s_instance; } } public override SecurityPolicyVersion SecurityPolicyVersion { get { return SecurityPolicyVersion.WSSecurityPolicy12; } } public override BasicSecurityProfileVersion BasicSecurityProfileVersion { get { return null; } } internal override MessageSecurityTokenVersion MessageSecurityTokenVersion { get { return MessageSecurityTokenVersion.WSSecurity10WSTrust13WSSecureConversation13BasicSecurityProfile10; } } public override string ToString() { return "WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10"; } } internal class WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12MessageSecurityVersion : MessageSecurityVersion { private static MessageSecurityVersion s_instance = new WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12MessageSecurityVersion(); public static MessageSecurityVersion Instance { get { return s_instance; } } public override SecurityPolicyVersion SecurityPolicyVersion { get { return SecurityPolicyVersion.WSSecurityPolicy12; } } public override BasicSecurityProfileVersion BasicSecurityProfileVersion { get { return null; } } internal override MessageSecurityTokenVersion MessageSecurityTokenVersion { get { return MessageSecurityTokenVersion.WSSecurity11WSTrust13WSSecureConversation13; } } public override string ToString() { return "WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12"; } } internal class WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10MessageSecurityVersion : MessageSecurityVersion { private static MessageSecurityVersion s_instance = new WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10MessageSecurityVersion(); public static MessageSecurityVersion Instance { get { return s_instance; } } public override SecurityPolicyVersion SecurityPolicyVersion { get { return SecurityPolicyVersion.WSSecurityPolicy12; } } public override BasicSecurityProfileVersion BasicSecurityProfileVersion { get { return null; } } internal override MessageSecurityTokenVersion MessageSecurityTokenVersion { get { return MessageSecurityTokenVersion.WSSecurity11WSTrust13WSSecureConversation13BasicSecurityProfile10; } } public override string ToString() { return "WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10"; } } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Microsoft.TeamFoundation.DistributedTask.WebApi; using Microsoft.VisualStudio.Services.Agent.Worker; using Microsoft.VisualStudio.Services.Agent.Worker.LegacyTestResults; using TestRunContext = Microsoft.TeamFoundation.TestClient.PublishTestResults.TestRunContext; using Moq; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using Xunit; namespace Microsoft.VisualStudio.Services.Agent.Tests.Worker.TestResults { public class JunitResultReaderTests : IDisposable { private Mock<IExecutionContext> _ec; private static JUnitResultReader _jUnitReader; private static TestRunData _testRunData; private static string _fileName; private static string _junitResultsToBeRead; private const string _onlyTestSuiteNode = "<?xml version =\'1.0\' encoding=\'UTF-8\'?>" + "<testsuite errors =\"0\" failures=\"0\" hostname=\"IE11Win8_1\" name=\"Microsoft Comp\" tests=\"1\" time=\"5529.0\" timestamp=\"2015-11-17T16:35:38.756-08:00\" url=\"https://try.soasta.com/concerto/\">" + "<testcase classname =\"root\" name=\"Microsoft Comp\" resultID=\"27327\" time=\"5.529\" />" + "</testsuite>"; private const string _sampleJunitResultXml = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + "<testsuite errors = \"0\" failures=\"0\" hostname=\"achalla-dev\" name=\"test.AllTests\" skipped=\"0\" tests=\"1\" time=\"0.03\" timestamp=\"2015-09-01T10:19:04\">" + "<properties>" + "<property name = \"java.vendor\" value=\"Oracle Corporation\" />" + "<property name = \"lib.dir\" value=\"lib\" />" + "<property name = \"sun.java.launcher\" value=\"SUN_STANDARD\" />" + "</properties>" + "<testcase classname = \"test.ExampleTest\" name=\"Fact\" time=\"0.001\" />" + "<system-out><![CDATA[Set Up Complete." + "Sample test Successful" + "]]></system-out>" + "<system-err><![CDATA[]]></system-err>" + "</testsuite>"; private const string _jUnitNestedResultsXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<testsuites>" + "<testsuite name=\"com.contoso.billingservice.ConsoleMessageRendererTest\" errors=\"0\" failures=\"1\" skipped=\"0\" tests=\"2\" time=\"0.006\" timestamp=\"2015-04-06T21:56:24\">" + "<testsuite errors=\"0\" failures=\"1\" hostname=\"mghost\" name=\"com.contoso.billingservice.ConsoleMessageRendererTest\" skipped=\"0\" tests=\"2\" time=\"0.006\" timestamp=\"2015-04-06T21:56:24\">" + "<testcase classname=\"com.contoso.billingservice.ConsoleMessageRendererTest\" name=\"testRenderNullMessage\" testType=\"asdasdas\" time=\"0.001\" />" + "<testcase classname=\"com.contoso.billingservice.ConsoleMessageRendererTest\" name=\"testRenderMessage\" time=\"0.003\">" + "<failure type=\"junit.framework.AssertionFailedError\">junit.framework.AssertionFailedError at com.contoso.billingservice.ConsoleMessageRendererTest.testRenderMessage(ConsoleMessageRendererTest.java:11)" + "</failure>" + "</testcase >" + "<system-out><![CDATA[Hello World!]]>" + "</system-out>" + "<system-err><![CDATA[]]></system-err>" + "</testsuite>" + "</testsuite>" + "</testsuites>"; private const string _jUnitNestedResultsXmlWithEmptyNameAttribute = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<testsuites>" + "<testsuite name=\"\" errors=\"0\" failures=\"1\" skipped=\"0\" tests=\"2\" time=\"0.006\" timestamp=\"2015-04-06T21:56:24\">" + "<testsuite errors=\"0\" failures=\"1\" hostname=\"mghost\" name=\"com.contoso.billingservice.ConsoleMessageRendererTest\" skipped=\"0\" tests=\"2\" time=\"0.006\" timestamp=\"2015-04-06T21:56:24\">" + "<testcase classname=\"com.contoso.billingservice.ConsoleMessageRendererTest\" name=\"testRenderNullMessage\" testType=\"asdasdas\" time=\"0.001\" />" + "<testcase classname=\"com.contoso.billingservice.ConsoleMessageRendererTest\" name=\"testRenderMessage\" time=\"0.003\">" + "<failure type=\"junit.framework.AssertionFailedError\">junit.framework.AssertionFailedError at com.contoso.billingservice.ConsoleMessageRendererTest.testRenderMessage(ConsoleMessageRendererTest.java:11)" + "</failure>" + "</testcase >" + "<system-out><![CDATA[Hello World!]]>" + "</system-out>" + "<system-err><![CDATA[]]></system-err>" + "</testsuite>" + "</testsuite>" + "</testsuites>"; private const string _sampleJunitResultXmlInvalidTime = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + "<testsuite errors = \"0\" failures=\"0\" hostname=\"achalla-dev\" name=\"test.AllTests\" skipped=\"0\" tests=\"1\" time=\"NaN\" timestamp=\"2015-09-01T10:19:04\">" + "<properties>" + "<property name = \"java.vendor\" value=\"Oracle Corporation\" />" + "<property name = \"lib.dir\" value=\"lib\" />" + "<property name = \"sun.java.launcher\" value=\"SUN_STANDARD\" />" + "</properties>" + "<testcase classname = \"test.ExampleTest\" name=\"Fact\" time=\"NaN\" />" + "<testcase name =\"can be instantiated\" time=\"-Infinity\" classname=\"PhantomJS 2.0.0 (Windows 8).the Admin module\"/>" + "<system-out><![CDATA[Set Up Complete." + "Sample test Successful" + "]]></system-out>" + "<system-err><![CDATA[]]></system-err>" + "</testsuite>"; private const string _sampleJunitResultXmlWithOwner = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + "<testsuite errors = \"0\" failures=\"0\" hostname=\"achalla-dev\" name=\"test.AllTests\" skipped=\"0\" tests=\"1\" time=\"0.03\" timestamp=\"2015-09-01T10:19:04\">" + "<properties>" + "<property name = \"java.vendor\" value=\"Oracle Corporation\" />" + "<property name = \"lib.dir\" value=\"lib\" />" + "<property name = \"sun.java.launcher\" value=\"SUN_STANDARD\" />" + "</properties>" + "<testcase classname = \"test.ExampleTest\" name=\"Fact\" time=\"0.001\" owner=\"TestAuthorName\"/>" + "<system-out><![CDATA[Set Up Complete." + "Sample test Successful" + "]]></system-out>" + "<system-err><![CDATA[]]></system-err>" + "</testsuite>"; private const string _jUnitBasicResultsWithLogsXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<testsuite errors=\"0\" failures=\"1\" hostname=\"mghost\" name=\"com.contoso.billingservice.ConsoleMessageRendererTest\" skipped=\"0\" tests=\"2\" time=\"0.006\" timestamp=\"2015-04-06T21:56:24\">" + "<testcase classname=\"com.contoso.billingservice.ConsoleMessageRendererTest\" name=\"testRenderMessage\" time=\"0.003\">" + "<failure type=\"junit.framework.AssertionFailedError\">junit.framework.AssertionFailedError at com.contoso.billingservice.ConsoleMessageRendererTest.testRenderMessage(ConsoleMessageRendererTest.java:11)" + "</failure>" + "<system-out><![CDATA[system out...]]></system-out>" + "<system-err><![CDATA[system err...]]></system-err>" + "</testcase >" + "</testsuite>"; private const string _jUnitBasicResultsXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<testsuite errors=\"0\" failures=\"1\" hostname=\"mghost\" name=\"com.contoso.billingservice.ConsoleMessageRendererTest\" skipped=\"0\" tests=\"2\" time=\"0.006\" timestamp=\"2015-04-06T21:56:24\">" + "<testcase classname=\"com.contoso.billingservice.ConsoleMessageRendererTest\" name=\"testRenderNullMessage\" testType=\"asdasdas\" time=\"0.001\" />" + "<testcase classname=\"com.contoso.billingservice.ConsoleMessageRendererTest\" name=\"testRenderMessage\" time=\"0.003\">" + "<failure type=\"junit.framework.AssertionFailedError\">junit.framework.AssertionFailedError at com.contoso.billingservice.ConsoleMessageRendererTest.testRenderMessage(ConsoleMessageRendererTest.java:11)" + "</failure>" + "</testcase >" + "<system-out><![CDATA[Hello World!]]>" + "</system-out>" + "<system-err><![CDATA[]]></system-err>" + "</testsuite>"; private const string _jUnitMultiSuiteXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<testsuites>" + "<testsuite errors=\"0\" failures=\"1\" hostname=\"mghost\" name=\"com.contoso.billingservice.ConsoleMessageRendererTest\" skipped=\"0\" tests=\"2\" time=\"1.006\" timestamp=\"2015-04-06T21:56:24\">" + "<testcase classname=\"com.contoso.billingservice.ConsoleMessageRendererTest\" name=\"testRenderNullMessage\" time=\"1.001\" />" + "</testsuite>" + "<testsuite errors=\"0\" failures=\"1\" hostname=\"mghost\" name=\"com.contoso.billingservice.ConsoleMessageRendererTest1\" skipped=\"0\" tests=\"2\" time=\"1.006\" timestamp=\"2015-04-06T21:56:24\">" + "<testcase classname=\"com.contoso.billingservice.ConsoleMessageRendererTest\" name=\"testRenderNullMessage\" time=\"1.001\" />" + "</testsuite>" + "</testsuites>"; private const string _jUnitWithDefaultDateTime = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<testsuite errors=\"0\" failures=\"1\" hostname=\"mghost\" name=\"com.contoso.billingservice.ConsoleMessageRendererTest\" skipped=\"0\" tests=\"2\" time=\"0.000\" timestamp=\"0001-01-01T00:00:00\">" + "<testcase classname=\"com.contoso.billingservice.ConsoleMessageRendererTest\" name=\"testRenderNullMessage\" time=\"1.001\" />" + "</testsuite>"; private const string c_jUnitMultiSuiteParallelXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<testsuites>" + "<testsuite errors=\"0\" failures=\"1\" hostname=\"mghost\" name=\"com.contoso.billingservice.ConsoleMessageRendererTest\" skipped=\"0\" tests=\"2\" time=\"1.006\" timestamp=\"2015-04-06T21:56:24\">" + "<testcase classname=\"com.contoso.billingservice.ConsoleMessageRendererTest\" name=\"testRenderNullMessage\" time=\"1.001\" />" + "</testsuite>" + "<testsuite errors=\"0\" failures=\"1\" hostname=\"mghost\" name=\"com.contoso.billingservice.ConsoleMessageRendererTest1\" skipped=\"0\" tests=\"2\" time=\"3.058\" timestamp=\"2015-04-06T21:56:25\">" + "<testcase classname=\"com.contoso.billingservice.ConsoleMessageRendererTest\" name=\"testRenderNullMessage\" time=\"3.003\" />" + "</testsuite>" + "<testsuite errors=\"0\" failures=\"1\" hostname=\"mghost\" name=\"com.contoso.billingservice.ConsoleMessageRendererTest1\" skipped=\"0\" tests=\"2\" time=\"2.016\" timestamp=\"2015-04-06T21:56:25\">" + "<testcase classname=\"com.contoso.billingservice.ConsoleMessageRendererTest\" name=\"testRenderNullMessage\" time=\"2.002\" />" + "</testsuite>" + "</testsuites>"; private const string _jUnitKarmaResultsXml = "<?xml version =\"1.0\"?>" + "<testsuites>" + "<testsuite name =\"PhantomJS 2.0.0 (Windows 8)\" package=\"\" timestamp=\"2015-05-22T12:56:58\" id=\"0\" hostname=\"nirvana\" tests=\"56\" errors=\"0\" failures=\"0\" time=\"0.394\">" + "<properties>" + "<property name =\"browser.fullName\" value=\"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/538.1 (KHTML, like Gecko) PhantomJS/2.0.0 (development) Safari/538.1\"/>" + "</properties>" + "<testcase name =\"can be instantiated\" time=\"0.01\" classname=\"PhantomJS 2.0.0 (Windows 8).the Admin module\"/>" + "<testcase name =\"configures the router\" time=\"0.01\" classname=\"PhantomJS 2.0.0 (Windows 8).the Admin module\"/>" + "<testcase name =\"should activate correctly\" time=\"0.03\" classname=\"PhantomJS 2.0.0 (Windows 8).the Admin module\"/>" + "<testcase name =\"can be instantiated\" time=\"0.007\" classname=\"PhantomJS 2.0.0 (Windows 8).the App module\"/>" + "<testcase name =\"registers dependencies on session router and reportRouter\" time=\"0.001\" classname=\"PhantomJS 2.0.0 (Windows 8).the App module\"/>" + "<testcase name =\"configures the router\" time=\"0.009\" classname=\"PhantomJS 2.0.0 (Windows 8).the App module\"/>" + "<system-out><![CDATA[]]></system-out>" + "<system-err/>" + "</testsuite>" + "</testsuites>"; private const string _jUnitBasicResultsXmlWithoutMandatoryFields = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<testsuite errors=\"0\" failures=\"1\" hostname=\"mghost\" name=\"com.contoso.billingservice.ConsoleMessageRendererTest\" skipped=\"0\" tests=\"2\" time=\"0.006\" timestamp=\"2015-04-06T21:56:24\">" + "<testcase classname=\"com.contoso.billingservice.ConsoleMessageRendererTest\" time=\"0.001\" />" + "<testcase classname=\"com.contoso.billingservice.ConsoleMessageRendererTest\" name=\"\" time=\"0.001\" />" + "</testsuite>"; private const string _sampleJunitResultXmlWithDtd = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + "<!DOCTYPE report PUBLIC '-//JACOCO//DTD Report 1.0//EN' 'report.dtd'>" + "<testsuite errors = \"0\" failures=\"0\" hostname=\"achalla-dev\" name=\"test.AllTests\" skipped=\"0\" tests=\"1\" time=\"0.03\" timestamp=\"2015-09-01T10:19:04\">" + "<properties>" + "<property name = \"java.vendor\" value=\"Oracle Corporation\" />" + "<property name = \"lib.dir\" value=\"lib\" />" + "<property name = \"sun.java.launcher\" value=\"SUN_STANDARD\" />" + "</properties>" + "<testcase classname = \"test.ExampleTest\" name=\"Fact\" time=\"0.001\" />" + "<system-out><![CDATA[Set Up Complete." + "Sample test Successful" + "]]></system-out>" + "<system-err><![CDATA[]]></system-err>" + "</testsuite>"; [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void ResultsWithoutMandatoryFieldsAreSkipped() { SetupMocks(); _junitResultsToBeRead = _jUnitBasicResultsXmlWithoutMandatoryFields; ReadResults(new TestRunContext("owner", "platform", "configuration", 1, "buildUri", "releaseUri", "releaseEnvironmentUri")); Assert.NotNull(_testRunData); Assert.Equal(0, _testRunData.Results.Length); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void VerifyTestRunContextOwnerShouldNotBeUsedForTestCaseOwner() { SetupMocks(); _junitResultsToBeRead = _sampleJunitResultXml; ReadResults(new TestRunContext("owner", "platform", "configuration", 1, "buildUri", "releaseUri", "releaseEnvironmentUri")); Assert.Null(_testRunData.Results[0].Owner); Assert.True(_testRunData.Results[0].RunBy.DisplayName.Equals("owner", StringComparison.OrdinalIgnoreCase)); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void VerifyTestRunDurationWhenTotalTimeIsInMilliseconds() { SetupMocks(); _junitResultsToBeRead = _sampleJunitResultXml; ReadResults(); var timeSpan = DateTime.Parse(_testRunData.CompleteDate) - DateTime.Parse(_testRunData.StartDate); Assert.Equal(0.03, timeSpan.TotalSeconds); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void VerifyCompletedTimeWhenTimeIsInvalid() { SetupMocks(); _junitResultsToBeRead = _sampleJunitResultXmlInvalidTime; ReadResults(); Assert.Equal(_testRunData.StartDate, _testRunData.CompleteDate); Assert.Equal(_testRunData.Results[0].StartedDate, _testRunData.Results[0].CompletedDate); Assert.Equal(_testRunData.Results[1].StartedDate, _testRunData.Results[1].CompletedDate); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void VerifyTestCaseDurationWhenTestCaseTimeIsInMilliseconds() { SetupMocks(); _junitResultsToBeRead = _sampleJunitResultXml; ReadResults(); var time = TimeSpan.FromMilliseconds(_testRunData.Results[0].DurationInMs); Assert.Equal(0.001, time.TotalSeconds); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void VerifyBehaviorWhenDefaultDateTimePassed() { SetupMocks(); // case for duration = maxcompletedtime- minstarttime _junitResultsToBeRead = _jUnitWithDefaultDateTime; ReadResults(); Assert.Equal(null, _testRunData.StartDate); Assert.Equal(null, _testRunData.CompleteDate); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void VerifyDurationAsDiffBetweenMinStartAndMaxCompletedDate() { SetupMocks(); // case for duration = maxcompletedtime- minstarttime _junitResultsToBeRead = c_jUnitMultiSuiteParallelXml; ReadResults(); var timeSpan = DateTime.Parse(_testRunData.CompleteDate) - DateTime.Parse(_testRunData.StartDate); Assert.Equal(4.058, timeSpan.TotalSeconds); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void VerifyDurationAsSumOfAssemblyTimeWhenTimestampNotParseable() { SetupMocks(); // time stamp parsing failure: case for duration = summation of assembly run time _junitResultsToBeRead = c_jUnitMultiSuiteParallelXml.Replace("timestamp=\"2015-04-06T21:56:24\"", "timestamp =\"5-04ggg-06T21:56:24\""); ReadResults(); var timeSpan = DateTime.Parse(_testRunData.CompleteDate) - DateTime.Parse(_testRunData.StartDate); Assert.Equal(6.08, timeSpan.TotalSeconds); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void VerifyDurationAsSumOfAssemblyTimeWhenTimestampTagNotAvailable() { SetupMocks(); // timestamp attribute not present: case for duration = summation of assembly run time _junitResultsToBeRead = c_jUnitMultiSuiteParallelXml.Replace("timestamp", "ts"); ReadResults(); var timeSpan = DateTime.Parse(_testRunData.CompleteDate) - DateTime.Parse(_testRunData.StartDate); Assert.Equal(6.08, timeSpan.TotalSeconds); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void VerifyDurationAsSumOfTestCaseTimeWhenTestSuiteTimeTagNotAvailable() { SetupMocks(); // timestamp and time attribute not present in test suite tag : case for duration = summation of test cases run time _junitResultsToBeRead = c_jUnitMultiSuiteParallelXml.Replace("timestamp", "ts").Replace("time=\"2.016\"", "tm =\"2.016\""); ReadResults(); var timeSpan = DateTime.Parse(_testRunData.CompleteDate) - DateTime.Parse(_testRunData.StartDate); Assert.Equal(6.006, Math.Round(timeSpan.TotalSeconds, 3)); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void VerifyDurationsCalculationsInDifferentCulture() { SetupMocks(); CultureInfo current = CultureInfo.CurrentCulture; try { //German is used, as in this culture decimal separator is comma & thousand separator is dot CultureInfo.CurrentCulture = new CultureInfo("de-De"); //verify test case start date _junitResultsToBeRead = _sampleJunitResultXml; ReadResults(); Assert.Equal(_testRunData.StartDate, _testRunData.Results[0].StartedDate.ToString("o")); //verify test case completed date _junitResultsToBeRead = _sampleJunitResultXml; ReadResults(); Assert.Equal(_testRunData.StartDate, _testRunData.Results[0].StartedDate.ToString("o")); //verify duration as difference between min start time and max completed time _junitResultsToBeRead = _jUnitKarmaResultsXml; ReadResults(); var testCase1CompletedDate = _testRunData.Results[0].CompletedDate; var testCase2StartDate = _testRunData.Results[1].StartedDate; Assert.True(testCase1CompletedDate <= testCase2StartDate, "first test case end should be before second test case start time"); //verify duration as sum of assembly time when timestamp tag is not available _junitResultsToBeRead = c_jUnitMultiSuiteParallelXml.Replace("timestamp", "ts"); ReadResults(); var timeSpan = DateTime.Parse(_testRunData.CompleteDate) - DateTime.Parse(_testRunData.StartDate); Assert.Equal(6.08, timeSpan.TotalSeconds); //verify duration as sum of test case time when test suite time tag is not available _junitResultsToBeRead = c_jUnitMultiSuiteParallelXml.Replace("timestamp", "ts").Replace("time=\"2.016\"", "tm =\"2.016\""); ReadResults(); timeSpan = DateTime.Parse(_testRunData.CompleteDate) - DateTime.Parse(_testRunData.StartDate); Assert.Equal(6.006, Math.Round(timeSpan.TotalSeconds, 3)); } finally { CultureInfo.CurrentCulture = current; } } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void PublishBasicJUnitResults() { SetupMocks(); _junitResultsToBeRead = _jUnitBasicResultsXml; ReadResults(new TestRunContext("owner", "platform", "configuration", 1, "buildUri", "releaseUri", "releaseEnvironmentUri")); Assert.NotNull(_testRunData); Assert.Equal(2, _testRunData.Results.Length); Assert.Equal(1, _testRunData.Results.Count(r => r.Outcome.Equals("Passed"))); Assert.Equal(null, _testRunData.Results[0].AutomatedTestId); Assert.Equal(null, _testRunData.Results[0].AutomatedTestTypeId); Assert.Equal(1, _testRunData.Results.Count(r => r.Outcome.Equals("Failed"))); Assert.Equal("com.contoso.billingservice.ConsoleMessageRendererTest", _testRunData.Name); Assert.Equal("releaseUri", _testRunData.ReleaseUri); Assert.Equal("releaseEnvironmentUri", _testRunData.ReleaseEnvironmentUri); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void PublishBasicNestedJUnitResults() { SetupMocks(); _junitResultsToBeRead = _jUnitNestedResultsXml; ReadResults(new TestRunContext("owner", "platform", "configuration", 1, "buildUri", "releaseUri", "releaseEnvironmentUri")); Assert.NotNull(_testRunData); Assert.Equal(2, _testRunData.Results.Length); Assert.Equal(1, _testRunData.Results.Count(r => r.Outcome.Equals("Passed"))); Assert.Equal(null, _testRunData.Results[0].AutomatedTestId); Assert.Equal(null, _testRunData.Results[0].AutomatedTestTypeId); Assert.Equal(1, _testRunData.Results.Count(r => r.Outcome.Equals("Failed"))); Assert.Equal("com.contoso.billingservice.ConsoleMessageRendererTest", _testRunData.Name); Assert.Equal("releaseUri", _testRunData.ReleaseUri); Assert.Equal("releaseEnvironmentUri", _testRunData.ReleaseEnvironmentUri); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void PublishNestedJUnitResultsWithEmptyNameAttributeInTestSuite() { SetupMocks(); _junitResultsToBeRead = _jUnitNestedResultsXmlWithEmptyNameAttribute; ReadResults(new TestRunContext("owner", "platform", "configuration", 1, "buildUri", "releaseUri", "releaseEnvironmentUri")); Assert.NotNull(_testRunData); Assert.Equal(2, _testRunData.Results.Length); Assert.Equal(1, _testRunData.Results.Count(r => r.Outcome.Equals("Passed"))); Assert.Equal(null, _testRunData.Results[0].AutomatedTestId); Assert.Equal(null, _testRunData.Results[0].AutomatedTestTypeId); Assert.Equal(1, _testRunData.Results.Count(r => r.Outcome.Equals("Failed"))); Assert.Equal("JUnit", _testRunData.Name); Assert.Equal("releaseUri", _testRunData.ReleaseUri); Assert.Equal("releaseEnvironmentUri", _testRunData.ReleaseEnvironmentUri); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void VerifyPublishingStandardLogs() { SetupMocks(); _junitResultsToBeRead = _jUnitBasicResultsWithLogsXml; ReadResults(new TestRunContext("owner", "platform", "configuration", 1, "buildUri", "releaseUri", "releaseEnvironmentUri")); Assert.NotNull(_testRunData); Assert.Equal(1, _testRunData.Results.Length); Assert.Equal("system out...", _testRunData.Results[0].AttachmentData.ConsoleLog); Assert.Equal("system err...", _testRunData.Results[0].AttachmentData.StandardError); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void PublishBasicJUnitResultsAddsResultsFileByDefault() { SetupMocks(); _junitResultsToBeRead = _jUnitBasicResultsXml; ReadResults(new TestRunContext("owner", "platform", "configuration", 1, "buildUri", "releaseUri", "releaseEnvironmentUri")); Assert.True(_testRunData.Attachments.Length == 1, "the run level attachment is not present"); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void PublishBasicJUnitResultsSkipsAddingResultsFileWhenFlagged() { SetupMocks(); _junitResultsToBeRead = _jUnitBasicResultsXml; ReadResults(new TestRunContext("owner", "platform", "configuration", 1, "buildUri", "releaseUri", "releaseEnvironmentUri"), false); Assert.True(_testRunData.Attachments.Length == 0, "the run level attachment is present even though the flag was set to false"); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void CustomRunTitleIsHonoured() { SetupMocks(); _junitResultsToBeRead = _jUnitBasicResultsXml; ReadResults(new TestRunContext("owner", "platform", "configuration", 1, "buildUri", "releaseUri", "releaseEnvironmentUri", "MyRunTitle")); Assert.NotNull(_testRunData); Assert.Equal("MyRunTitle", _testRunData.Name); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void DefaultRunTitleIsHonouredForMultiSuiteRuns() { SetupMocks(); _junitResultsToBeRead = _jUnitMultiSuiteXml; ReadResults(); Assert.NotNull(_testRunData); Assert.Equal("JUnit_" + Path.GetFileName(_fileName), _testRunData.Name); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void PublishJUnitKarmaResultFile() { SetupMocks(); _junitResultsToBeRead = _jUnitKarmaResultsXml; ReadResults(new TestRunContext("owner", "platform", "configuration", 1, "buildUri", "releaseUri", "releaseEnvironmentUri")); Assert.NotNull(_testRunData); Assert.Equal(6, _testRunData.Results.Length); Assert.Equal(6, _testRunData.Results.Count(r => r.Outcome.Equals("Passed"))); Assert.Equal(0, _testRunData.Results.Count(r => r.Outcome.Equals("Failed"))); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void VerifyRunTypeIsSet() { SetupMocks(); _junitResultsToBeRead = _jUnitKarmaResultsXml; ReadResults(new TestRunContext("owner", "platform", "configuration", 1, "buildUri", "releaseUri", "releaseEnvironmentUri")); Assert.Equal(_jUnitReader.Name, _testRunData.Results[0].AutomatedTestType); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void VerifyTestCaseStartDate() { SetupMocks(); _junitResultsToBeRead = _sampleJunitResultXml; ReadResults(); Assert.Equal(_testRunData.StartDate, _testRunData.Results[0].StartedDate.ToString("o")); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void VerifyTestCaseCompletedDate() { SetupMocks(); _junitResultsToBeRead = _jUnitKarmaResultsXml; ReadResults(); var testCase1CompletedDate = _testRunData.Results[0].CompletedDate; var testCase2StartDate = _testRunData.Results[1].StartedDate; Assert.True(testCase1CompletedDate <= testCase2StartDate, "first test case end should be before second test case start time"); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void VerifyLastTestCaseEndDateNotGreaterThanTestRunTotalTime() { SetupMocks(); _junitResultsToBeRead = _sampleJunitResultXml; ReadResults(); var testCaseCompletedDate = _testRunData.Results[0].CompletedDate; var testRunCompletedDate = _testRunData.Results[0].StartedDate.AddTicks(DateTime.Parse(_testRunData.CompleteDate).Ticks); Assert.True(testCaseCompletedDate <= testRunCompletedDate, "first test case end should be within test run completed time"); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void VerifyWithJustTestSuite() { SetupMocks(); _junitResultsToBeRead = _onlyTestSuiteNode; ReadResults(new TestRunContext("owner", "platform", "configuration", 1, "buildUri", "releaseUri", "releaseEnvironmentUri")); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void Junit_DtdProhibitedXmlShouldReturnNull() { SetupMocks(); _junitResultsToBeRead = _sampleJunitResultXmlWithDtd; ReadResults(); Assert.NotNull(_testRunData); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void Junit_ShouldReadOwnerIfPresent() { string expectedOwnerName = "TestAuthorName"; SetupMocks(); _junitResultsToBeRead = _sampleJunitResultXmlWithOwner; ReadResults(); Assert.NotNull(_testRunData); Assert.True(expectedOwnerName.Equals(_testRunData.Results[0].Owner.DisplayName, StringComparison.OrdinalIgnoreCase)); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA2000:Dispose objects before losing scope", MessageId = "TestHostContext")] private void SetupMocks([CallerMemberName] string name = "") { TestHostContext hc = new TestHostContext(this, name); _ec = new Mock<IExecutionContext>(); List<string> warnings; var variables = new Variables(hc, new Dictionary<string, VariableValue>(), out warnings); _ec.Setup(x => x.Variables).Returns(variables); } private void ReadResults(TestRunContext runContext = null, bool attachRunLevelAttachments = true) { _fileName = Path.Combine(Path.GetTempPath(), Path.GetTempFileName()); File.WriteAllText(_fileName, _junitResultsToBeRead); _jUnitReader = new JUnitResultReader(); _jUnitReader.AddResultsFileToRunLevelAttachments = attachRunLevelAttachments; _testRunData = _jUnitReader.ReadResults(_ec.Object, _fileName, runContext); } public void Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (disposing) { _jUnitReader.AddResultsFileToRunLevelAttachments = true; try { File.Delete(_fileName); } catch { } } } } }
/* * 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 Apache.Ignite.Core.Impl { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading.Tasks; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cache.Configuration; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Compute; using Apache.Ignite.Core.Datastream; using Apache.Ignite.Core.DataStructures; using Apache.Ignite.Core.Events; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Cache; using Apache.Ignite.Core.Impl.Cluster; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Impl.Datastream; using Apache.Ignite.Core.Impl.DataStructures; using Apache.Ignite.Core.Impl.Handle; using Apache.Ignite.Core.Impl.Plugin; using Apache.Ignite.Core.Impl.Transactions; using Apache.Ignite.Core.Impl.Unmanaged; using Apache.Ignite.Core.Lifecycle; using Apache.Ignite.Core.Log; using Apache.Ignite.Core.Messaging; using Apache.Ignite.Core.Services; using Apache.Ignite.Core.Transactions; using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils; /// <summary> /// Native Ignite wrapper. /// </summary> internal class Ignite : IIgnite, ICluster { /** */ private readonly IgniteConfiguration _cfg; /** Grid name. */ private readonly string _name; /** Unmanaged node. */ private readonly IUnmanagedTarget _proc; /** Marshaller. */ private readonly Marshaller _marsh; /** Initial projection. */ private readonly ClusterGroupImpl _prj; /** Binary. */ private readonly Binary.Binary _binary; /** Binary processor. */ private readonly BinaryProcessor _binaryProc; /** Lifecycle handlers. */ private readonly IList<LifecycleHandlerHolder> _lifecycleHandlers; /** Local node. */ private IClusterNode _locNode; /** Transactions facade. */ private readonly Lazy<TransactionsImpl> _transactions; /** Callbacks */ private readonly UnmanagedCallbacks _cbs; /** Node info cache. */ private readonly ConcurrentDictionary<Guid, ClusterNodeImpl> _nodes = new ConcurrentDictionary<Guid, ClusterNodeImpl>(); /** Client reconnect task completion source. */ private volatile TaskCompletionSource<bool> _clientReconnectTaskCompletionSource = new TaskCompletionSource<bool>(); /** Plugin processor. */ private readonly PluginProcessor _pluginProcessor; /// <summary> /// Constructor. /// </summary> /// <param name="cfg">Configuration.</param> /// <param name="name">Grid name.</param> /// <param name="proc">Interop processor.</param> /// <param name="marsh">Marshaller.</param> /// <param name="lifecycleHandlers">Lifecycle beans.</param> /// <param name="cbs">Callbacks.</param> public Ignite(IgniteConfiguration cfg, string name, IUnmanagedTarget proc, Marshaller marsh, IList<LifecycleHandlerHolder> lifecycleHandlers, UnmanagedCallbacks cbs) { Debug.Assert(cfg != null); Debug.Assert(proc != null); Debug.Assert(marsh != null); Debug.Assert(lifecycleHandlers != null); Debug.Assert(cbs != null); _cfg = cfg; _name = name; _proc = proc; _marsh = marsh; _lifecycleHandlers = lifecycleHandlers; _cbs = cbs; marsh.Ignite = this; _prj = new ClusterGroupImpl(proc, UU.ProcessorProjection(proc), marsh, this, null); _binary = new Binary.Binary(marsh); _binaryProc = new BinaryProcessor(UU.ProcessorBinaryProcessor(proc), marsh); cbs.Initialize(this); // Grid is not completely started here, can't initialize interop transactions right away. _transactions = new Lazy<TransactionsImpl>( () => new TransactionsImpl(UU.ProcessorTransactions(proc), marsh, GetLocalNode().Id)); // Set reconnected task to completed state for convenience. _clientReconnectTaskCompletionSource.SetResult(false); SetCompactFooter(); _pluginProcessor = new PluginProcessor(this); } /// <summary> /// Sets the compact footer setting. /// </summary> private void SetCompactFooter() { if (!string.IsNullOrEmpty(_cfg.SpringConfigUrl)) { // If there is a Spring config, use setting from Spring, // since we ignore .NET config in legacy mode. var cfg0 = GetConfiguration().BinaryConfiguration; if (cfg0 != null) _marsh.CompactFooter = cfg0.CompactFooter; } } /// <summary> /// On-start routine. /// </summary> internal void OnStart() { PluginProcessor.OnIgniteStart(); foreach (var lifecycleBean in _lifecycleHandlers) lifecycleBean.OnStart(this); } /** <inheritdoc /> */ public string Name { get { return _name; } } /** <inheritdoc /> */ public ICluster GetCluster() { return this; } /** <inheritdoc /> */ IIgnite IClusterGroup.Ignite { get { return this; } } /** <inheritdoc /> */ public IClusterGroup ForLocal() { return _prj.ForNodes(GetLocalNode()); } /** <inheritdoc /> */ public ICompute GetCompute() { return _prj.ForServers().GetCompute(); } /** <inheritdoc /> */ public IClusterGroup ForNodes(IEnumerable<IClusterNode> nodes) { return ((IClusterGroup) _prj).ForNodes(nodes); } /** <inheritdoc /> */ public IClusterGroup ForNodes(params IClusterNode[] nodes) { return _prj.ForNodes(nodes); } /** <inheritdoc /> */ public IClusterGroup ForNodeIds(IEnumerable<Guid> ids) { return ((IClusterGroup) _prj).ForNodeIds(ids); } /** <inheritdoc /> */ public IClusterGroup ForNodeIds(ICollection<Guid> ids) { return _prj.ForNodeIds(ids); } /** <inheritdoc /> */ public IClusterGroup ForNodeIds(params Guid[] ids) { return _prj.ForNodeIds(ids); } /** <inheritdoc /> */ public IClusterGroup ForPredicate(Func<IClusterNode, bool> p) { IgniteArgumentCheck.NotNull(p, "p"); return _prj.ForPredicate(p); } /** <inheritdoc /> */ public IClusterGroup ForAttribute(string name, string val) { return _prj.ForAttribute(name, val); } /** <inheritdoc /> */ public IClusterGroup ForCacheNodes(string name) { return _prj.ForCacheNodes(name); } /** <inheritdoc /> */ public IClusterGroup ForDataNodes(string name) { return _prj.ForDataNodes(name); } /** <inheritdoc /> */ public IClusterGroup ForClientNodes(string name) { return _prj.ForClientNodes(name); } /** <inheritdoc /> */ public IClusterGroup ForRemotes() { return _prj.ForRemotes(); } /** <inheritdoc /> */ public IClusterGroup ForDaemons() { return _prj.ForDaemons(); } /** <inheritdoc /> */ public IClusterGroup ForHost(IClusterNode node) { IgniteArgumentCheck.NotNull(node, "node"); return _prj.ForHost(node); } /** <inheritdoc /> */ public IClusterGroup ForRandom() { return _prj.ForRandom(); } /** <inheritdoc /> */ public IClusterGroup ForOldest() { return _prj.ForOldest(); } /** <inheritdoc /> */ public IClusterGroup ForYoungest() { return _prj.ForYoungest(); } /** <inheritdoc /> */ public IClusterGroup ForDotNet() { return _prj.ForDotNet(); } /** <inheritdoc /> */ public IClusterGroup ForServers() { return _prj.ForServers(); } /** <inheritdoc /> */ public ICollection<IClusterNode> GetNodes() { return _prj.GetNodes(); } /** <inheritdoc /> */ public IClusterNode GetNode(Guid id) { return _prj.GetNode(id); } /** <inheritdoc /> */ public IClusterNode GetNode() { return _prj.GetNode(); } /** <inheritdoc /> */ public IClusterMetrics GetMetrics() { return _prj.GetMetrics(); } /** <inheritdoc /> */ [SuppressMessage("Microsoft.Usage", "CA1816:CallGCSuppressFinalizeCorrectly", Justification = "There is no finalizer.")] [SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed", MessageId = "_proxy", Justification = "Proxy does not need to be disposed.")] public void Dispose() { Ignition.Stop(Name, true); } /// <summary> /// Internal stop routine. /// </summary> /// <param name="cancel">Cancel flag.</param> internal unsafe void Stop(bool cancel) { UU.IgnitionStop(_proc.Context, Name, cancel); _cbs.Cleanup(); } /// <summary> /// Called before node has stopped. /// </summary> internal void BeforeNodeStop() { var handler = Stopping; if (handler != null) handler.Invoke(this, EventArgs.Empty); } /// <summary> /// Called after node has stopped. /// </summary> internal void AfterNodeStop() { foreach (var bean in _lifecycleHandlers) bean.OnLifecycleEvent(LifecycleEventType.AfterNodeStop); var handler = Stopped; if (handler != null) handler.Invoke(this, EventArgs.Empty); } /** <inheritdoc /> */ public ICache<TK, TV> GetCache<TK, TV>(string name) { IgniteArgumentCheck.NotNull(name, "name"); return Cache<TK, TV>(UU.ProcessorCache(_proc, name)); } /** <inheritdoc /> */ public ICache<TK, TV> GetOrCreateCache<TK, TV>(string name) { IgniteArgumentCheck.NotNull(name, "name"); return Cache<TK, TV>(UU.ProcessorGetOrCreateCache(_proc, name)); } /** <inheritdoc /> */ public ICache<TK, TV> GetOrCreateCache<TK, TV>(CacheConfiguration configuration) { return GetOrCreateCache<TK, TV>(configuration, null); } /** <inheritdoc /> */ public ICache<TK, TV> GetOrCreateCache<TK, TV>(CacheConfiguration configuration, NearCacheConfiguration nearConfiguration) { IgniteArgumentCheck.NotNull(configuration, "configuration"); IgniteArgumentCheck.NotNull(configuration.Name, "CacheConfiguration.Name"); configuration.Validate(Logger); using (var stream = IgniteManager.Memory.Allocate().GetStream()) { var writer = BinaryUtils.Marshaller.StartMarshal(stream); configuration.Write(writer); if (nearConfiguration != null) { writer.WriteBoolean(true); nearConfiguration.Write(writer); } else writer.WriteBoolean(false); stream.SynchronizeOutput(); return Cache<TK, TV>(UU.ProcessorGetOrCreateCache(_proc, stream.MemoryPointer)); } } /** <inheritdoc /> */ public ICache<TK, TV> CreateCache<TK, TV>(string name) { IgniteArgumentCheck.NotNull(name, "name"); return Cache<TK, TV>(UU.ProcessorCreateCache(_proc, name)); } /** <inheritdoc /> */ public ICache<TK, TV> CreateCache<TK, TV>(CacheConfiguration configuration) { return CreateCache<TK, TV>(configuration, null); } /** <inheritdoc /> */ public ICache<TK, TV> CreateCache<TK, TV>(CacheConfiguration configuration, NearCacheConfiguration nearConfiguration) { IgniteArgumentCheck.NotNull(configuration, "configuration"); IgniteArgumentCheck.NotNull(configuration.Name, "CacheConfiguration.Name"); configuration.Validate(Logger); using (var stream = IgniteManager.Memory.Allocate().GetStream()) { // Use system marshaller: full footers, always unregistered mode. var writer = BinaryUtils.Marshaller.StartMarshal(stream); configuration.Write(writer); if (nearConfiguration != null) { writer.WriteBoolean(true); nearConfiguration.Write(writer); } else writer.WriteBoolean(false); stream.SynchronizeOutput(); return Cache<TK, TV>(UU.ProcessorCreateCache(_proc, stream.MemoryPointer)); } } /** <inheritdoc /> */ public void DestroyCache(string name) { IgniteArgumentCheck.NotNull(name, "name"); UU.ProcessorDestroyCache(_proc, name); } /// <summary> /// Gets cache from specified native cache object. /// </summary> /// <param name="nativeCache">Native cache.</param> /// <param name="keepBinary">Keep binary flag.</param> /// <returns> /// New instance of cache wrapping specified native cache. /// </returns> public ICache<TK, TV> Cache<TK, TV>(IUnmanagedTarget nativeCache, bool keepBinary = false) { return new CacheImpl<TK, TV>(this, nativeCache, _marsh, false, keepBinary, false, false); } /** <inheritdoc /> */ public IClusterNode GetLocalNode() { return _locNode ?? (_locNode = GetNodes().FirstOrDefault(x => x.IsLocal) ?? ForDaemons().GetNodes().FirstOrDefault(x => x.IsLocal)); } /** <inheritdoc /> */ public bool PingNode(Guid nodeId) { return _prj.PingNode(nodeId); } /** <inheritdoc /> */ public long TopologyVersion { get { return _prj.TopologyVersion; } } /** <inheritdoc /> */ public ICollection<IClusterNode> GetTopology(long ver) { return _prj.Topology(ver); } /** <inheritdoc /> */ public void ResetMetrics() { _prj.ResetMetrics(); } /** <inheritdoc /> */ public Task<bool> ClientReconnectTask { get { return _clientReconnectTaskCompletionSource.Task; } } /** <inheritdoc /> */ public IDataStreamer<TK, TV> GetDataStreamer<TK, TV>(string cacheName) { IgniteArgumentCheck.NotNull(cacheName, "cacheName"); return new DataStreamerImpl<TK, TV>(UU.ProcessorDataStreamer(_proc, cacheName, false), _marsh, cacheName, false); } /** <inheritdoc /> */ public IBinary GetBinary() { return _binary; } /** <inheritdoc /> */ public ICacheAffinity GetAffinity(string cacheName) { IgniteArgumentCheck.NotNull(cacheName, "cacheName"); return new CacheAffinityImpl(UU.ProcessorAffinity(_proc, cacheName), _marsh, false, this); } /** <inheritdoc /> */ public ITransactions GetTransactions() { return _transactions.Value; } /** <inheritdoc /> */ public IMessaging GetMessaging() { return _prj.GetMessaging(); } /** <inheritdoc /> */ public IEvents GetEvents() { return _prj.GetEvents(); } /** <inheritdoc /> */ public IServices GetServices() { return _prj.ForServers().GetServices(); } /** <inheritdoc /> */ public IAtomicLong GetAtomicLong(string name, long initialValue, bool create) { IgniteArgumentCheck.NotNullOrEmpty(name, "name"); var nativeLong = UU.ProcessorAtomicLong(_proc, name, initialValue, create); if (nativeLong == null) return null; return new AtomicLong(nativeLong, Marshaller, name); } /** <inheritdoc /> */ public IAtomicSequence GetAtomicSequence(string name, long initialValue, bool create) { IgniteArgumentCheck.NotNullOrEmpty(name, "name"); var nativeSeq = UU.ProcessorAtomicSequence(_proc, name, initialValue, create); if (nativeSeq == null) return null; return new AtomicSequence(nativeSeq, Marshaller, name); } /** <inheritdoc /> */ public IAtomicReference<T> GetAtomicReference<T>(string name, T initialValue, bool create) { IgniteArgumentCheck.NotNullOrEmpty(name, "name"); var refTarget = GetAtomicReferenceUnmanaged(name, initialValue, create); return refTarget == null ? null : new AtomicReference<T>(refTarget, Marshaller, name); } /// <summary> /// Gets the unmanaged atomic reference. /// </summary> /// <param name="name">The name.</param> /// <param name="initialValue">The initial value.</param> /// <param name="create">Create flag.</param> /// <returns>Unmanaged atomic reference, or null.</returns> private IUnmanagedTarget GetAtomicReferenceUnmanaged<T>(string name, T initialValue, bool create) { IgniteArgumentCheck.NotNullOrEmpty(name, "name"); // Do not allocate memory when default is not used. if (!create) return UU.ProcessorAtomicReference(_proc, name, 0, false); using (var stream = IgniteManager.Memory.Allocate().GetStream()) { var writer = Marshaller.StartMarshal(stream); writer.Write(initialValue); Marshaller.FinishMarshal(writer); var memPtr = stream.SynchronizeOutput(); return UU.ProcessorAtomicReference(_proc, name, memPtr, true); } } /** <inheritdoc /> */ public IgniteConfiguration GetConfiguration() { using (var stream = IgniteManager.Memory.Allocate(1024).GetStream()) { UU.ProcessorGetIgniteConfiguration(_proc, stream.MemoryPointer); stream.SynchronizeInput(); return new IgniteConfiguration(BinaryUtils.Marshaller.StartUnmarshal(stream), _cfg); } } /** <inheritdoc /> */ public ICache<TK, TV> CreateNearCache<TK, TV>(string name, NearCacheConfiguration configuration) { return GetOrCreateNearCache0<TK, TV>(name, configuration, UU.ProcessorCreateNearCache); } /** <inheritdoc /> */ public ICache<TK, TV> GetOrCreateNearCache<TK, TV>(string name, NearCacheConfiguration configuration) { return GetOrCreateNearCache0<TK, TV>(name, configuration, UU.ProcessorGetOrCreateNearCache); } /** <inheritdoc /> */ public ICollection<string> GetCacheNames() { using (var stream = IgniteManager.Memory.Allocate(1024).GetStream()) { UU.ProcessorGetCacheNames(_proc, stream.MemoryPointer); stream.SynchronizeInput(); var reader = _marsh.StartUnmarshal(stream); var res = new string[stream.ReadInt()]; for (int i = 0; i < res.Length; i++) res[i] = reader.ReadString(); return res; } } /** <inheritdoc /> */ public ILogger Logger { get { return _cbs.Log; } } /** <inheritdoc /> */ public event EventHandler Stopping; /** <inheritdoc /> */ public event EventHandler Stopped; /** <inheritdoc /> */ public event EventHandler ClientDisconnected; /** <inheritdoc /> */ public event EventHandler<ClientReconnectEventArgs> ClientReconnected; /** <inheritdoc /> */ public T GetPlugin<T>(string name) where T : class { IgniteArgumentCheck.NotNullOrEmpty(name, "name"); return PluginProcessor.GetProvider(name).GetPlugin<T>(); } /** <inheritdoc /> */ public void ResetLostPartitions(IEnumerable<string> cacheNames) { IgniteArgumentCheck.NotNull(cacheNames, "cacheNames"); _prj.ResetLostPartitions(cacheNames); } /** <inheritdoc /> */ public void ResetLostPartitions(params string[] cacheNames) { ResetLostPartitions((IEnumerable<string>) cacheNames); } /** <inheritdoc /> */ public ICollection<IMemoryMetrics> GetMemoryMetrics() { return _prj.GetMemoryMetrics(); } /// <summary> /// Gets or creates near cache. /// </summary> private ICache<TK, TV> GetOrCreateNearCache0<TK, TV>(string name, NearCacheConfiguration configuration, Func<IUnmanagedTarget, string, long, IUnmanagedTarget> func) { IgniteArgumentCheck.NotNull(configuration, "configuration"); using (var stream = IgniteManager.Memory.Allocate().GetStream()) { var writer = BinaryUtils.Marshaller.StartMarshal(stream); configuration.Write(writer); stream.SynchronizeOutput(); return Cache<TK, TV>(func(_proc, name, stream.MemoryPointer)); } } /// <summary> /// Gets internal projection. /// </summary> /// <returns>Projection.</returns> internal ClusterGroupImpl ClusterGroup { get { return _prj; } } /// <summary> /// Marshaller. /// </summary> internal Marshaller Marshaller { get { return _marsh; } } /// <summary> /// Gets the binary processor. /// </summary> internal BinaryProcessor BinaryProcessor { get { return _binaryProc; } } /// <summary> /// Configuration. /// </summary> internal IgniteConfiguration Configuration { get { return _cfg; } } /// <summary> /// Handle registry. /// </summary> public HandleRegistry HandleRegistry { get { return _cbs.HandleRegistry; } } /// <summary> /// Updates the node information from stream. /// </summary> /// <param name="memPtr">Stream ptr.</param> public void UpdateNodeInfo(long memPtr) { var stream = IgniteManager.Memory.Get(memPtr).GetStream(); IBinaryRawReader reader = Marshaller.StartUnmarshal(stream, false); var node = new ClusterNodeImpl(reader); node.Init(this); _nodes[node.Id] = node; } /// <summary> /// Gets the node from cache. /// </summary> /// <param name="id">Node id.</param> /// <returns>Cached node.</returns> public ClusterNodeImpl GetNode(Guid? id) { return id == null ? null : _nodes[id.Value]; } /// <summary> /// Gets the interop processor. /// </summary> internal IUnmanagedTarget InteropProcessor { get { return _proc; } } /// <summary> /// Called when local client node has been disconnected from the cluster. /// </summary> internal void OnClientDisconnected() { _clientReconnectTaskCompletionSource = new TaskCompletionSource<bool>(); var handler = ClientDisconnected; if (handler != null) handler.Invoke(this, EventArgs.Empty); } /// <summary> /// Called when local client node has been reconnected to the cluster. /// </summary> /// <param name="clusterRestarted">Cluster restarted flag.</param> internal void OnClientReconnected(bool clusterRestarted) { _clientReconnectTaskCompletionSource.TrySetResult(clusterRestarted); var handler = ClientReconnected; if (handler != null) handler.Invoke(this, new ClientReconnectEventArgs(clusterRestarted)); } /// <summary> /// Gets the plugin processor. /// </summary> internal PluginProcessor PluginProcessor { get { return _pluginProcessor; } } } }
//--------------------------------------------------------------------- // <copyright file="EntityClassGenerator.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // @owner [....] // @backupOwner [....] //--------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Data; using System.Data.EntityModel.SchemaObjectModel; using System.Data.Metadata.Edm; using System.Data.EntityModel; using System.Data.Entity.Design.Common; using System.IO; using System.Xml; using System.Data.Entity.Design.SsdlGenerator; using Microsoft.Build.Utilities; using System.Runtime.Versioning; namespace System.Data.Entity.Design { /// <summary> /// Event handler for the OnTypeGenerated event /// </summary> /// <param name="sender">The source of the event</param> /// <param name="e">The event args</param> public delegate void TypeGeneratedEventHandler(object sender, TypeGeneratedEventArgs e); /// <summary> /// Event handler for the OnPropertyGenerated event /// </summary> /// <param name="sender">The source of the event</param> /// <param name="e">The event args</param> public delegate void PropertyGeneratedEventHandler(object sender, PropertyGeneratedEventArgs e); /// <summary> /// Summary description for CodeGenerator. /// </summary> public sealed class EntityClassGenerator { #region Instance Fields LanguageOption _languageOption = LanguageOption.GenerateCSharpCode; EdmToObjectNamespaceMap _edmToObjectNamespaceMap = new EdmToObjectNamespaceMap(); #endregion #region Events /// <summary> /// The event that is raised when a type is generated /// </summary> public event TypeGeneratedEventHandler OnTypeGenerated; /// <summary> /// The event that is raised when a property is generated /// </summary> public event PropertyGeneratedEventHandler OnPropertyGenerated; #endregion #region Public Methods /// <summary> /// /// </summary> public EntityClassGenerator() { } /// <summary> /// /// </summary> public EntityClassGenerator(LanguageOption languageOption) { _languageOption = EDesignUtil.CheckLanguageOptionArgument(languageOption, "languageOption"); } /// <summary> /// Gets and Sets the Language to use for code generation. /// </summary> public LanguageOption LanguageOption { get { return _languageOption; } set { _languageOption = EDesignUtil.CheckLanguageOptionArgument(value, "value"); } } /// <summary> /// Gets the map entries use to customize the namespace of .net types that are generated /// and referenced by the generated code /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Edm")] public EdmToObjectNamespaceMap EdmToObjectNamespaceMap { get { return _edmToObjectNamespaceMap; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Edm")] public IList<EdmSchemaError> GenerateCode(XmlReader sourceEdmSchema, TextWriter target) { EDesignUtil.CheckArgumentNull(sourceEdmSchema, "sourceEdmSchema"); EDesignUtil.CheckArgumentNull(target, "target"); return GenerateCode(sourceEdmSchema, target, new XmlReader[] { }); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Edm")] [ResourceExposure(ResourceScope.None)] //No resource is exposed since we pass in null as the target paath. [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] //For GenerateCodeCommon method call. Since we use null as the path, we have not changed the scope of the resource. public IList<EdmSchemaError> GenerateCode(XmlReader sourceEdmSchema, TextWriter target, IEnumerable<XmlReader> additionalEdmSchemas) { EDesignUtil.CheckArgumentNull(sourceEdmSchema, "sourceEdmSchema"); EDesignUtil.CheckArgumentNull(additionalEdmSchemas, "additionalEdmSchemas"); EDesignUtil.CheckArgumentNull(target, "target"); List<EdmSchemaError> errors = new List<EdmSchemaError>(); try { MetadataArtifactLoader sourceLoader = new MetadataArtifactLoaderXmlReaderWrapper(sourceEdmSchema); List<MetadataArtifactLoader> loaders = new List<MetadataArtifactLoader>(); loaders.Add(sourceLoader); int index = 0; foreach (XmlReader additionalEdmSchema in additionalEdmSchemas) { if (additionalEdmSchema == null) { throw EDesignUtil.Argument(Strings.NullAdditionalSchema("additionalEdmSchema", index)); } try { MetadataArtifactLoader loader = new MetadataArtifactLoaderXmlReaderWrapper(additionalEdmSchema); Debug.Assert(loader != null, "when is the loader ever null?"); loaders.Add(loader); } catch (Exception e) { if (MetadataUtil.IsCatchableExceptionType(e)) { errors.Add(new EdmSchemaError(e.Message, (int)ModelBuilderErrorCode.CodeGenAdditionalEdmSchemaIsInvalid, EdmSchemaErrorSeverity.Error)); } else { throw; } } index++; } ThrowOnAnyNonWarningErrors(errors); GenerateCodeCommon(sourceLoader, loaders, new LazyTextWriterCreator(target), null, // source path null, // target file path false, // dispose readers? errors); } catch (TerminalErrorException) { // do nothing // just a place to jump when errors are detected } return errors; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Edm")] [ResourceExposure(ResourceScope.Machine)] //Exposes the sourceEdmSchemaFilePath which is a Machine resource [ResourceConsumption(ResourceScope.Machine)] //For GenerateCode method call. But the path is not created in this method. public IList<EdmSchemaError> GenerateCode(string sourceEdmSchemaFilePath, string targetFilePath) { return GenerateCode(sourceEdmSchemaFilePath, targetFilePath, new string[] { }); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Edm")] [ResourceExposure(ResourceScope.Machine)] //Exposes the sourceEdmSchemaFilePath which is a Machine resource [ResourceConsumption(ResourceScope.Machine)] //For MetadataArtifactLoader.Create method call. But the path is not created in this method. public IList<EdmSchemaError> GenerateCode(string sourceEdmSchemaFilePath, string targetPath, IEnumerable<string> additionalEdmSchemaFilePaths) { EDesignUtil.CheckStringArgument(sourceEdmSchemaFilePath, "sourceEdmSchemaFilePath"); EDesignUtil.CheckArgumentNull(additionalEdmSchemaFilePaths, "additionalEdmSchemaFilePaths"); EDesignUtil.CheckStringArgument(targetPath, "targetPath"); List<EdmSchemaError> errors = new List<EdmSchemaError>(); try { // create a loader for the source HashSet<string> uriRegistry = new HashSet<string>(); MetadataArtifactLoader sourceLoader; try { sourceLoader = MetadataArtifactLoader.Create(sourceEdmSchemaFilePath, MetadataArtifactLoader.ExtensionCheck.Specific, XmlConstants.CSpaceSchemaExtension, uriRegistry); } catch (MetadataException e) { errors.Add(CreateErrorForException(ModelBuilderErrorCode.CodeGenSourceFilePathIsInvalid, e, sourceEdmSchemaFilePath)); return errors; } if (sourceLoader.IsComposite) { throw new ArgumentException(Strings.CodeGenSourceFilePathIsNotAFile, "sourceEdmSchemaPath"); } // create loaders for all the additional schemas List<MetadataArtifactLoader> loaders = new List<MetadataArtifactLoader>(); loaders.Add(sourceLoader); int index = 0; foreach (string additionalSchemaFilePath in additionalEdmSchemaFilePaths) { if (additionalSchemaFilePath == null) { throw EDesignUtil.Argument(Strings.NullAdditionalSchema("additionalEdmSchemaFilePaths", index)); } try { MetadataArtifactLoader loader = MetadataArtifactLoader.Create(additionalSchemaFilePath, MetadataArtifactLoader.ExtensionCheck.Specific, XmlConstants.CSpaceSchemaExtension, uriRegistry); Debug.Assert(loader != null, "when is the loader ever null?"); loaders.Add(loader); } catch (Exception e) { if(MetadataUtil.IsCatchableExceptionType(e)) { errors.Add(CreateErrorForException(ModelBuilderErrorCode.CodeGenAdditionalEdmSchemaIsInvalid, e, additionalSchemaFilePath)); } else { throw; } } index++; } ThrowOnAnyNonWarningErrors(errors); try { using (LazyTextWriterCreator target = new LazyTextWriterCreator(targetPath)) { GenerateCodeCommon(sourceLoader, loaders, target, sourceEdmSchemaFilePath, targetPath, true, // dispose readers errors); } } catch (System.IO.IOException ex) { errors.Add(CreateErrorForException(System.Data.EntityModel.SchemaObjectModel.ErrorCode.IOException, ex, targetPath)); return errors; } } catch (TerminalErrorException) { // do nothing // just a place to jump when errors are detected } return errors; } private void GenerateCodeCommon(MetadataArtifactLoader sourceLoader, List<MetadataArtifactLoader> loaders, LazyTextWriterCreator target, string sourceEdmSchemaFilePath, string targetFilePath, bool closeReaders, List<EdmSchemaError> errors) { MetadataArtifactLoaderComposite composite = new MetadataArtifactLoaderComposite(loaders); // create the schema manager from the xml readers Dictionary<MetadataArtifactLoader, XmlReader> readerSourceMap = new Dictionary<MetadataArtifactLoader, XmlReader>(); IList<Schema> schemas; List<XmlReader> readers = composite.GetReaders(readerSourceMap); try { IList<EdmSchemaError> schemaManagerErrors = SchemaManager.ParseAndValidate(readers, composite.GetPaths(), SchemaDataModelOption.EntityDataModel, EdmProviderManifest.Instance, out schemas); errors.AddRange(schemaManagerErrors); } finally { if (closeReaders) { MetadataUtil.DisposeXmlReaders(readers); } } ThrowOnAnyNonWarningErrors(errors); Debug.Assert(readerSourceMap.ContainsKey(sourceLoader), "the source loader didn't produce any of the xml readers..."); XmlReader sourceReader = readerSourceMap[sourceLoader]; // use the index of the "source" xml reader as the index of the "source" schema Debug.Assert(readers.Contains(sourceReader), "the source reader is not in the list of readers"); int index = readers.IndexOf(sourceReader); Debug.Assert(index >= 0, "couldn't find the source reader in the list of readers"); Debug.Assert(readers.Count == schemas.Count, "We have a different number of readers than schemas"); Schema sourceSchema = schemas[index]; Debug.Assert(sourceSchema != null, "sourceSchema is null"); // create the EdmItemCollection from the schemas EdmItemCollection itemCollection = new EdmItemCollection(schemas); if (EntityFrameworkVersionsUtil.ConvertToVersion(itemCollection.EdmVersion) >= EntityFrameworkVersions.Version2) { throw EDesignUtil.InvalidOperation(Strings.TargetEntityFrameworkVersionToNewForEntityClassGenerator); } // generate code ClientApiGenerator generator = new ClientApiGenerator(sourceSchema, itemCollection, this, errors); generator.GenerateCode(target, targetFilePath); } #endregion #region Private Methods private static EdmSchemaError CreateErrorForException(System.Data.EntityModel.SchemaObjectModel.ErrorCode errorCode, System.Exception exception, string sourceLocation) { Debug.Assert(exception != null); Debug.Assert(sourceLocation != null); return new EdmSchemaError(exception.Message, (int)errorCode, EdmSchemaErrorSeverity.Error, sourceLocation, 0, 0, exception); } internal static EdmSchemaError CreateErrorForException(ModelBuilderErrorCode errorCode, System.Exception exception, string sourceLocation) { Debug.Assert(exception != null); Debug.Assert(sourceLocation != null); return new EdmSchemaError(exception.Message, (int)errorCode, EdmSchemaErrorSeverity.Error, sourceLocation, 0, 0, exception); } internal static EdmSchemaError CreateErrorForException(ModelBuilderErrorCode errorCode, System.Exception exception) { Debug.Assert(exception != null); return new EdmSchemaError(exception.Message, (int)errorCode, EdmSchemaErrorSeverity.Error, null, 0, 0, exception); } private void ThrowOnAnyNonWarningErrors(List<EdmSchemaError> errors) { foreach (EdmSchemaError error in errors) { if (error.Severity != EdmSchemaErrorSeverity.Warning) { throw new TerminalErrorException(); } } } #endregion #region Event Helpers /// <summary> /// Helper method that raises the TypeGenerated event /// </summary> /// <param name="eventArgs">The event arguments passed to the subscriber</param> internal void RaiseTypeGeneratedEvent(TypeGeneratedEventArgs eventArgs) { if (this.OnTypeGenerated != null) { this.OnTypeGenerated(this, eventArgs); } } /// <summary> /// Helper method that raises the PropertyGenerated event /// </summary> /// <param name="eventArgs">The event arguments passed to the subscriber</param> internal void RaisePropertyGeneratedEvent(PropertyGeneratedEventArgs eventArgs) { if (this.OnPropertyGenerated != null) { this.OnPropertyGenerated(this, eventArgs); } } #endregion } }
// <copyright file="ChiTests.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // http://mathnetnumerics.codeplex.com // // Copyright (c) 2009-2014 Math.NET // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> using System; using System.Linq; using MathNet.Numerics.Distributions; using NUnit.Framework; namespace MathNet.Numerics.UnitTests.DistributionTests.Continuous { /// <summary> /// Chi distribution test /// </summary> [TestFixture, Category("Distributions")] public class ChiTests { /// <summary> /// Can create chi. /// </summary> /// <param name="dof">Degrees of freedom</param> [TestCase(1.0)] [TestCase(3.0)] [TestCase(Double.PositiveInfinity)] public void CanCreateChi(double dof) { var n = new Chi(dof); Assert.AreEqual(dof, n.DegreesOfFreedom); } /// <summary> /// Chi create fails with bad parameters. /// </summary> /// <param name="dof">Degrees of freedom.</param> [TestCase(0.0)] [TestCase(-1.0)] [TestCase(-100.0)] [TestCase(Double.NegativeInfinity)] [TestCase(Double.NaN)] public void ChiCreateFailsWithBadParameters(double dof) { Assert.That(() => new Chi(dof), Throws.ArgumentException); } /// <summary> /// Validate ToString. /// </summary> [Test] public void ValidateToString() { var n = new Chi(1.0); Assert.AreEqual("Chi(k = 1)", n.ToString()); } /// <summary> /// Validate mean. /// </summary> /// <param name="dof">Degrees of freedom.</param> [TestCase(1.0)] [TestCase(2.0)] [TestCase(2.5)] [TestCase(5.0)] [TestCase(Double.PositiveInfinity)] public void ValidateMean(double dof) { var n = new Chi(dof); Assert.AreEqual(Constants.Sqrt2 * (SpecialFunctions.Gamma((dof + 1.0) / 2.0) / SpecialFunctions.Gamma(dof / 2.0)), n.Mean); } /// <summary> /// Validate variance. /// </summary> /// <param name="dof">Degrees of freedom</param> [TestCase(1.0)] [TestCase(2.0)] [TestCase(2.5)] [TestCase(3.0)] [TestCase(Double.PositiveInfinity)] public void ValidateVariance(double dof) { var n = new Chi(dof); Assert.AreEqual(dof - (n.Mean * n.Mean), n.Variance); } /// <summary> /// Validate standard deviation /// </summary> /// <param name="dof">Degrees of freedom</param> [TestCase(1.0)] [TestCase(2.0)] [TestCase(2.5)] [TestCase(3.0)] [TestCase(Double.PositiveInfinity)] public void ValidateStdDev(double dof) { var n = new Chi(dof); Assert.AreEqual(Math.Sqrt(n.Variance), n.StdDev); } /// <summary> /// Validate mode. /// </summary> /// <param name="dof">Degrees of freedom</param> [TestCase(1.0)] [TestCase(2.0)] [TestCase(2.5)] [TestCase(3.0)] [TestCase(Double.PositiveInfinity)] public void ValidateMode(double dof) { var n = new Chi(dof); if (dof >= 1) { Assert.AreEqual(Math.Sqrt(dof - 1), n.Mode); } } /// <summary> /// Validate median throws <c>NotSupportedException</c>. /// </summary> [Test] public void ValidateMedianThrowsNotSupportedException() { var n = new Chi(1.0); Assert.Throws<NotSupportedException>(() => { var median = n.Median; }); } /// <summary> /// Validate minimum. /// </summary> [Test] public void ValidateMinimum() { var n = new Chi(1.0); Assert.AreEqual(0.0, n.Minimum); } /// <summary> /// Validate maximum. /// </summary> [Test] public void ValidateMaximum() { var n = new Chi(1.0); Assert.AreEqual(Double.PositiveInfinity, n.Maximum); } /// <summary> /// Validate density. /// </summary> /// <param name="dof">Degrees of freedom.</param> /// <param name="x">Input X value.</param> [TestCase(1.0, 0.0)] [TestCase(1.0, 0.1)] [TestCase(1.0, 1.0)] [TestCase(1.0, 5.5)] [TestCase(1.0, 110.1)] [TestCase(1.0, Double.PositiveInfinity)] [TestCase(2.0, 0.0)] [TestCase(2.0, 0.1)] [TestCase(2.0, 1.0)] [TestCase(2.0, 5.5)] [TestCase(2.0, 110.1)] [TestCase(2.0, Double.PositiveInfinity)] [TestCase(2.5, 0.0)] [TestCase(2.5, 0.1)] [TestCase(2.5, 1.0)] [TestCase(2.5, 5.5)] [TestCase(2.5, 110.1)] [TestCase(2.5, Double.PositiveInfinity)] [TestCase(Double.PositiveInfinity, 0.0)] [TestCase(Double.PositiveInfinity, 0.1)] [TestCase(Double.PositiveInfinity, 1.0)] [TestCase(Double.PositiveInfinity, 5.5)] [TestCase(Double.PositiveInfinity, 110.1)] [TestCase(Double.PositiveInfinity, Double.PositiveInfinity)] public void ValidateDensity(double dof, double x) { var n = new Chi(dof); double expected = (Math.Pow(2.0, 1.0 - (dof / 2.0)) * Math.Pow(x, dof - 1.0) * Math.Exp(-x * (x / 2.0))) / SpecialFunctions.Gamma(dof / 2.0); Assert.AreEqual(expected, n.Density(x)); Assert.AreEqual(expected, Chi.PDF(dof, x)); } /// <summary> /// Validate density log. /// </summary> /// <param name="dof">Degrees of freedom.</param> /// <param name="x">Input X value.</param> [TestCase(1.0, 0.0)] [TestCase(1.0, 0.1)] [TestCase(1.0, 1.0)] [TestCase(1.0, 5.5)] [TestCase(1.0, 110.1)] [TestCase(1.0, Double.PositiveInfinity)] [TestCase(2.0, 0.0)] [TestCase(2.0, 0.1)] [TestCase(2.0, 1.0)] [TestCase(2.0, 5.5)] [TestCase(2.0, 110.1)] [TestCase(2.0, Double.PositiveInfinity)] [TestCase(2.5, 0.0)] [TestCase(2.5, 0.1)] [TestCase(2.5, 1.0)] [TestCase(2.5, 5.5)] [TestCase(2.5, 110.1)] [TestCase(2.5, Double.PositiveInfinity)] [TestCase(Double.PositiveInfinity, 0.0)] [TestCase(Double.PositiveInfinity, 0.1)] [TestCase(Double.PositiveInfinity, 1.0)] [TestCase(Double.PositiveInfinity, 5.5)] [TestCase(Double.PositiveInfinity, 110.1)] [TestCase(Double.PositiveInfinity, Double.PositiveInfinity)] public void ValidateDensityLn(double dof, double x) { var n = new Chi(dof); double expected = ((1.0 - (dof / 2.0)) * Math.Log(2.0)) + ((dof - 1.0) * Math.Log(x)) - (x * (x / 2.0)) - SpecialFunctions.GammaLn(dof / 2.0); Assert.AreEqual(expected, n.DensityLn(x)); Assert.AreEqual(expected, Chi.PDFLn(dof, x)); } /// <summary> /// Can sample. /// </summary> [Test] public void CanSample() { var n = new Chi(1.0); n.Sample(); } /// <summary> /// Can sample sequence. /// </summary> [Test] public void CanSampleSequence() { var n = new Chi(1.0); var ied = n.Samples(); GC.KeepAlive(ied.Take(5).ToArray()); } /// <summary> /// Validate cumulative distribution. /// </summary> /// <param name="dof">Degrees of freedom.</param> /// <param name="x">Input X value.</param> [TestCase(1.0, 0.0)] [TestCase(1.0, 0.1)] [TestCase(1.0, 1.0)] [TestCase(1.0, 5.5)] [TestCase(1.0, 110.1)] [TestCase(1.0, Double.PositiveInfinity)] [TestCase(2.0, 0.0)] [TestCase(2.0, 0.1)] [TestCase(2.0, 1.0)] [TestCase(2.0, 5.5)] [TestCase(2.0, 110.1)] [TestCase(2.0, Double.PositiveInfinity)] [TestCase(2.5, 0.0)] [TestCase(2.5, 0.1)] [TestCase(2.5, 1.0)] [TestCase(2.5, 5.5)] [TestCase(2.5, 110.1)] [TestCase(2.5, Double.PositiveInfinity)] [TestCase(Double.PositiveInfinity, 0.0)] [TestCase(Double.PositiveInfinity, 0.1)] [TestCase(Double.PositiveInfinity, 1.0)] [TestCase(Double.PositiveInfinity, 5.5)] [TestCase(Double.PositiveInfinity, 110.1)] [TestCase(Double.PositiveInfinity, Double.PositiveInfinity)] public void ValidateCumulativeDistribution(double dof, double x) { var n = new Chi(dof); double expected = SpecialFunctions.GammaLowerIncomplete(dof / 2.0, x * x / 2.0) / SpecialFunctions.Gamma(dof / 2.0); Assert.AreEqual(expected, n.CumulativeDistribution(x)); Assert.AreEqual(expected, Chi.CDF(dof, x)); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class DynamicTests : CSharpResultProviderTestBase { [Fact] public void Simple() { var value = CreateDkmClrValue(new object()); var rootExpr = "d"; var evalResult = FormatResult(rootExpr, rootExpr, value, declaredType: new DkmClrType((TypeImpl)typeof(object)), declaredTypeInfo: MakeCustomTypeInfo(true)); Verify(evalResult, EvalResult(rootExpr, "{object}", "dynamic {object}", rootExpr)); } [Fact] public void Member() { var source = @" class C { dynamic F; dynamic P { get; set; } }"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(Activator.CreateInstance(type)); var rootExpr = "new C()"; var evalResult = FormatResult(rootExpr, value); Verify(evalResult, EvalResult(rootExpr, "{C}", "C", rootExpr, DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("F", "null", "dynamic {object}", "(new C()).F"), EvalResult("P", "null", "dynamic {object}", "(new C()).P")); } [Fact] public void Member_ConstructedType() { var source = @" class C<T, U> { T Simple; U[] Array; C<U, T> Constructed; C<C<C<object, T>, dynamic[]>, U[]>[] Complex; }"; var assembly = GetAssembly(source); var typeC = assembly.GetType("C`2"); var typeC_Constructed1 = typeC.MakeGenericType(typeof(object), typeof(object)); // C<object, dynamic> var typeC_Constructed2 = typeC.MakeGenericType(typeof(object), typeC_Constructed1); // C<dynamic, C<object, dynamic>> (i.e. T = dynamic, U = C<object, dynamic>) var value = CreateDkmClrValue(Activator.CreateInstance(typeC_Constructed2)); var rootExpr = "c"; var evalResult = FormatResult(rootExpr, rootExpr, value, new DkmClrType((TypeImpl)typeC_Constructed2), MakeCustomTypeInfo(false, true, false, false, true)); Verify(evalResult, EvalResult(rootExpr, "{C<object, C<object, object>>}", "C<dynamic, C<object, dynamic>> {C<object, C<object, object>>}", rootExpr, DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("Array", "null", "C<object, dynamic>[] {C<object, object>[]}", "c.Array"), EvalResult("Complex", "null", "C<C<C<object, dynamic>, dynamic[]>, C<object, dynamic>[]>[] {C<C<C<object, object>, object[]>, C<object, object>[]>[]}", "c.Complex"), EvalResult("Constructed", "null", "C<C<object, dynamic>, dynamic> {C<C<object, object>, object>}", "c.Constructed"), EvalResult("Simple", "null", "dynamic {object}", "c.Simple")); } [Fact] public void Member_NestedType() { var source = @" class Outer<T> { class Inner<U> { T Simple; U[] Array; Outer<U>.Inner<T> Constructed; } }"; var assembly = GetAssembly(source); var typeInner = assembly.GetType("Outer`1+Inner`1"); var typeInner_Constructed = typeInner.MakeGenericType(typeof(object), typeof(object)); // Outer<dynamic>.Inner<object> var value = CreateDkmClrValue(Activator.CreateInstance(typeInner_Constructed)); var rootExpr = "i"; var evalResult = FormatResult(rootExpr, rootExpr, value, new DkmClrType((TypeImpl)typeInner_Constructed), MakeCustomTypeInfo(false, true, false)); Verify(evalResult, EvalResult(rootExpr, "{Outer<object>.Inner<object>}", "Outer<dynamic>.Inner<object> {Outer<object>.Inner<object>}", rootExpr, DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("Array", "null", "object[]", "i.Array"), EvalResult("Constructed", "null", "Outer<object>.Inner<dynamic> {Outer<object>.Inner<object>}", "i.Constructed"), EvalResult("Simple", "null", "dynamic {object}", "i.Simple")); } [Fact] public void Member_ConstructedTypeMember() { var source = @" class C<T> where T : new() { T Simple = new T(); T[] Array = new[] { new T() }; D<T, object, dynamic> Constructed = new D<T, object, dynamic>(); } class D<T, U, V> { T TT; U UU; V VV; }"; var assembly = GetAssembly(source); var typeD = assembly.GetType("D`3"); var typeD_Constructed = typeD.MakeGenericType(typeof(object), typeof(object), typeof(int)); // D<object, dynamic, int> var typeC = assembly.GetType("C`1"); var typeC_Constructed = typeC.MakeGenericType(typeD_Constructed); // C<D<object, dynamic, int>> var value = CreateDkmClrValue(Activator.CreateInstance(typeC_Constructed)); var rootExpr = "c"; var evalResult = FormatResult(rootExpr, rootExpr, value, new DkmClrType((TypeImpl)typeC_Constructed), MakeCustomTypeInfo(false, false, false, true, false)); Verify(evalResult, EvalResult(rootExpr, "{C<D<object, object, int>>}", "C<D<object, dynamic, int>> {C<D<object, object, int>>}", rootExpr, DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("Array", "{D<object, object, int>[1]}", "D<object, dynamic, int>[] {D<object, object, int>[]}", "c.Array", DkmEvaluationResultFlags.Expandable), EvalResult("Constructed", "{D<D<object, object, int>, object, object>}", "D<D<object, dynamic, int>, object, dynamic> {D<D<object, object, int>, object, object>}", "c.Constructed", DkmEvaluationResultFlags.Expandable), EvalResult("Simple", "{D<object, object, int>}", "D<object, dynamic, int> {D<object, object, int>}", "c.Simple", DkmEvaluationResultFlags.Expandable)); Verify(GetChildren(children[0]), EvalResult("[0]", "{D<object, object, int>}", "D<object, dynamic, int> {D<object, object, int>}", "c.Array[0]", DkmEvaluationResultFlags.Expandable)); Verify(GetChildren(children[1]), EvalResult("TT", "null", "D<object, dynamic, int> {D<object, object, int>}", "c.Constructed.TT"), EvalResult("UU", "null", "object", "c.Constructed.UU"), EvalResult("VV", "null", "dynamic {object}", "c.Constructed.VV")); Verify(GetChildren(children[2]), EvalResult("TT", "null", "object", "c.Simple.TT"), EvalResult("UU", "null", "dynamic {object}", "c.Simple.UU"), EvalResult("VV", "0", "int", "c.Simple.VV")); } [Fact] public void Member_ExplicitInterfaceImplementation() { var source = @" interface I<V, W> { V P { get; set; } W Q { get; set; } } class C<T, U> : I<long, T>, I<bool, U> { long I<long, T>.P { get; set; } T I<long, T>.Q { get; set; } bool I<bool, U>.P { get; set; } U I<bool, U>.Q { get; set; } }"; var assembly = GetAssembly(source); var typeC = assembly.GetType("C`2"); var typeC_Constructed = typeC.MakeGenericType(typeof(object), typeof(object)); // C<dynamic, object> var value = CreateDkmClrValue(Activator.CreateInstance(typeC_Constructed)); var rootExpr = "c"; var evalResult = FormatResult(rootExpr, rootExpr, value, new DkmClrType((TypeImpl)typeC_Constructed), MakeCustomTypeInfo(false, true, false)); Verify(evalResult, EvalResult(rootExpr, "{C<object, object>}", "C<dynamic, object> {C<object, object>}", rootExpr, DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("I<bool, object>.P", "false", "bool", "((I<bool, object>)c).P", DkmEvaluationResultFlags.Boolean), EvalResult("I<bool, object>.Q", "null", "object", "((I<bool, object>)c).Q"), EvalResult("I<long, dynamic>.P", "0", "long", "((I<long, dynamic>)c).P"), EvalResult("I<long, dynamic>.Q", "null", "dynamic {object}", "((I<long, dynamic>)c).Q")); } [Fact] public void Member_BaseType() { var source = @" class Base<T, U, V, W> { public T P; public U Q; public V R; public W S; } class Derived<T, U> : Base<T, U, object, dynamic> { new public T[] P; new public U[] Q; new public dynamic[] R; new public object[] S; }"; var assembly = GetAssembly(source); var typeDerived = assembly.GetType("Derived`2"); var typeDerived_Constructed = typeDerived.MakeGenericType(typeof(object), typeof(object)); // Derived<dynamic, object> var value = CreateDkmClrValue(Activator.CreateInstance(typeDerived_Constructed)); var rootExpr = "d"; var evalResult = FormatResult(rootExpr, rootExpr, value, new DkmClrType((TypeImpl)typeDerived_Constructed), MakeCustomTypeInfo(false, true, false)); Verify(evalResult, EvalResult(rootExpr, "{Derived<object, object>}", "Derived<dynamic, object> {Derived<object, object>}", rootExpr, DkmEvaluationResultFlags.Expandable)); // CONSIDER: It would be nice to substitute "dynamic" where appropriate. var children = GetChildren(evalResult); Verify(children, EvalResult("P (Base<object, object, object, object>)", "null", "object", "((Base<object, object, object, object>)d).P"), EvalResult("P", "null", "dynamic[] {object[]}", "d.P"), EvalResult("Q (Base<object, object, object, object>)", "null", "object", "((Base<object, object, object, object>)d).Q"), EvalResult("Q", "null", "object[]", "d.Q"), EvalResult("R (Base<object, object, object, object>)", "null", "object", "((Base<object, object, object, object>)d).R"), EvalResult("R", "null", "dynamic[] {object[]}", "d.R"), EvalResult("S (Base<object, object, object, object>)", "null", "object", "((Base<object, object, object, object>)d).S"), EvalResult("S", "null", "object[]", "d.S")); } [Fact] public void ArrayElement() { var value = CreateDkmClrValue(new object[1]); var rootExpr = "d"; var evalResult = FormatResult(rootExpr, rootExpr, value, declaredType: new DkmClrType((TypeImpl)typeof(object[])), declaredTypeInfo: MakeCustomTypeInfo(false, true)); Verify(evalResult, EvalResult(rootExpr, "{object[1]}", "dynamic[] {object[]}", rootExpr, DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("[0]", "null", "dynamic {object}", "d[0]")); } [Fact] public void TypeVariables() { var intrinsicSource = @".class private abstract sealed beforefieldinit specialname '<>c__TypeVariables'<T,U,V> { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } }"; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; CommonTestBase.EmitILToArray(intrinsicSource, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var assembly = ReflectionUtilities.Load(assemblyBytes); var reflectionType = assembly.GetType(ExpressionCompilerConstants.TypeVariablesClassName).MakeGenericType(new[] { typeof(object), typeof(object), typeof(object[]) }); var value = CreateDkmClrValue(value: null, type: reflectionType, valueFlags: DkmClrValueFlags.Synthetic); var evalResult = FormatResult("typevars", "typevars", value, new DkmClrType((TypeImpl)reflectionType), MakeCustomTypeInfo(false, true, false, false, true)); Verify(evalResult, EvalResult("Type variables", "", "", null, DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); var children = GetChildren(evalResult); Verify(children, EvalResult("T", "dynamic", "dynamic", null, DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data), EvalResult("U", "object", "object", null, DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data), EvalResult("V", "dynamic[]", "dynamic[]", null, DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); } [WorkItem(13554, "https://github.com/dotnet/roslyn/issues/13554")] [Fact(Skip = "13554")] public void DynamicBaseTypeArgument() { var source = @"class A<T> { #pragma warning disable 0169 internal T F; #pragma warning restore 0169 } class B : A<dynamic> { B() { F = 1; } }"; var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib(GetAssembly(source))); using (runtime.Load()) { var type = runtime.GetType("B"); var value = type.Instantiate(); var evalResult = FormatResult("o", value); var children = GetChildren(evalResult); Verify(children, EvalResult("F", "1", "dynamic {int}", "o.F")); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; using Test.Cryptography; using Xunit; using Xunit.Abstractions; namespace System.Security.Cryptography.X509Certificates.Tests { public class CertTests { private const string PrivateKeySectionHeader = "[Private Key]"; private const string PublicKeySectionHeader = "[Public Key]"; private readonly ITestOutputHelper _log; public CertTests(ITestOutputHelper output) { _log = output; } [Fact] public static void X509CertTest() { string certSubject = @"CN=Microsoft Corporate Root Authority, OU=ITG, O=Microsoft, L=Redmond, S=WA, C=US, [email protected]"; string certSubjectObsolete = @"[email protected], C=US, S=WA, L=Redmond, O=Microsoft, OU=ITG, CN=Microsoft Corporate Root Authority"; using (X509Certificate cert = new X509Certificate(Path.Combine("TestData", "microsoft.cer"))) { Assert.Equal(certSubject, cert.Subject); Assert.Equal(certSubject, cert.Issuer); #pragma warning disable CS0618 // Type or member is obsolete Assert.Equal(certSubjectObsolete, cert.GetName()); Assert.Equal(certSubjectObsolete, cert.GetIssuerName()); #pragma warning restore CS0618 int snlen = cert.GetSerialNumber().Length; Assert.Equal(16, snlen); byte[] serialNumber = new byte[snlen]; Buffer.BlockCopy(cert.GetSerialNumber(), 0, serialNumber, 0, snlen); Assert.Equal(0xF6, serialNumber[0]); Assert.Equal(0xB3, serialNumber[snlen / 2]); Assert.Equal(0x2A, serialNumber[snlen - 1]); Assert.Equal("1.2.840.113549.1.1.1", cert.GetKeyAlgorithm()); int pklen = cert.GetPublicKey().Length; Assert.Equal(270, pklen); byte[] publicKey = new byte[pklen]; Buffer.BlockCopy(cert.GetPublicKey(), 0, publicKey, 0, pklen); Assert.Equal(0x30, publicKey[0]); Assert.Equal(0xB6, publicKey[9]); Assert.Equal(1, publicKey[pklen - 1]); } } [Fact] public static void X509Cert2Test() { string certName = @"[email protected], CN=ABA.ECOM Root CA, O=""ABA.ECOM, INC."", L=Washington, S=DC, C=US"; DateTime notBefore = new DateTime(1999, 7, 12, 17, 33, 53, DateTimeKind.Utc).ToLocalTime(); DateTime notAfter = new DateTime(2009, 7, 9, 17, 33, 53, DateTimeKind.Utc).ToLocalTime(); using (X509Certificate2 cert2 = new X509Certificate2(Path.Combine("TestData", "test.cer"))) { Assert.Equal(certName, cert2.IssuerName.Name); Assert.Equal(certName, cert2.SubjectName.Name); Assert.Equal("ABA.ECOM Root CA", cert2.GetNameInfo(X509NameType.DnsName, true)); PublicKey pubKey = cert2.PublicKey; Assert.Equal("RSA", pubKey.Oid.FriendlyName); Assert.Equal(notAfter, cert2.NotAfter); Assert.Equal(notBefore, cert2.NotBefore); Assert.Equal(notAfter.ToString(), cert2.GetExpirationDateString()); Assert.Equal(notBefore.ToString(), cert2.GetEffectiveDateString()); Assert.Equal("00D01E4090000046520000000100000004", cert2.SerialNumber); Assert.Equal("1.2.840.113549.1.1.5", cert2.SignatureAlgorithm.Value); Assert.Equal("7A74410FB0CD5C972A364B71BF031D88A6510E9E", cert2.Thumbprint); Assert.Equal(3, cert2.Version); } } [Fact] [OuterLoop("May require using the network, to download CRLs and intermediates")] public void TestVerify() { bool success; using (var microsoftDotCom = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes)) { // Fails because expired (NotAfter = 10/16/2016) Assert.False(microsoftDotCom.Verify(), "MicrosoftDotComSslCertBytes"); } using (var microsoftDotComIssuer = new X509Certificate2(TestData.MicrosoftDotComIssuerBytes)) { // NotAfter=10/31/2023 success = microsoftDotComIssuer.Verify(); if (!success) { LogVerifyErrors(microsoftDotComIssuer, "MicrosoftDotComIssuerBytes"); } Assert.True(success, "MicrosoftDotComIssuerBytes"); } // High Sierra fails to build a chain for a self-signed certificate with revocation enabled. // https://github.com/dotnet/corefx/issues/21875 if (!PlatformDetection.IsMacOsHighSierraOrHigher) { using (var microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes)) { // NotAfter=7/17/2036 success = microsoftDotComRoot.Verify(); if (!success) { LogVerifyErrors(microsoftDotComRoot, "MicrosoftDotComRootBytes"); } Assert.True(success, "MicrosoftDotComRootBytes"); } } } private void LogVerifyErrors(X509Certificate2 cert, string testName) { // Emulate cert.Verify() implementation in order to capture and log errors. try { using (var chain = new X509Chain()) { if (!chain.Build(cert)) { foreach (X509ChainStatus chainStatus in chain.ChainStatus) { _log.WriteLine(string.Format($"X509Certificate2.Verify error: {testName}, {chainStatus.Status}, {chainStatus.StatusInformation}")); } } else { _log.WriteLine(string.Format($"X509Certificate2.Verify expected error; received none: {testName}")); } } } catch (Exception e) { _log.WriteLine($"X509Certificate2.Verify exception: {testName}, {e}"); } } [Fact] public static void X509CertEmptyToString() { using (var c = new X509Certificate()) { string expectedResult = "System.Security.Cryptography.X509Certificates.X509Certificate"; Assert.Equal(expectedResult, c.ToString()); Assert.Equal(expectedResult, c.ToString(false)); Assert.Equal(expectedResult, c.ToString(true)); } } [Fact] public static void X509Cert2EmptyToString() { using (var c2 = new X509Certificate2()) { string expectedResult = "System.Security.Cryptography.X509Certificates.X509Certificate2"; Assert.Equal(expectedResult, c2.ToString()); Assert.Equal(expectedResult, c2.ToString(false)); Assert.Equal(expectedResult, c2.ToString(true)); } } [Fact] public static void X509Cert2ToStringVerbose() { using (X509Store store = new X509Store("My", StoreLocation.CurrentUser)) { store.Open(OpenFlags.ReadOnly); foreach (X509Certificate2 c in store.Certificates) { Assert.False(string.IsNullOrWhiteSpace(c.ToString(true))); c.Dispose(); } } } [Theory] [MemberData(nameof(StorageFlags))] public static void X509Certificate2ToStringVerbose_WithPrivateKey(X509KeyStorageFlags keyStorageFlags) { using (var cert = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, keyStorageFlags)) { string certToString = cert.ToString(true); Assert.Contains(PrivateKeySectionHeader, certToString); Assert.Contains(PublicKeySectionHeader, certToString); } } [Fact] public static void X509Certificate2ToStringVerbose_NoPrivateKey() { using (var cert = new X509Certificate2(TestData.MsCertificatePemBytes)) { string certToString = cert.ToString(true); Assert.DoesNotContain(PrivateKeySectionHeader, certToString); Assert.Contains(PublicKeySectionHeader, certToString); } } [Fact] public static void X509Cert2CreateFromEmptyPfx() { Assert.ThrowsAny<CryptographicException>(() => new X509Certificate2(TestData.EmptyPfx)); } [Fact] public static void X509Cert2CreateFromPfxFile() { using (X509Certificate2 cert2 = new X509Certificate2(Path.Combine("TestData", "DummyTcpServer.pfx"))) { // OID=RSA Encryption Assert.Equal("1.2.840.113549.1.1.1", cert2.GetKeyAlgorithm()); } } [Fact] public static void X509Cert2CreateFromPfxWithPassword() { using (X509Certificate2 cert2 = new X509Certificate2(Path.Combine("TestData", "test.pfx"), "test")) { // OID=RSA Encryption Assert.Equal("1.2.840.113549.1.1.1", cert2.GetKeyAlgorithm()); } } [Fact] public static void X509Certificate2FromPkcs7DerFile() { Assert.ThrowsAny<CryptographicException>(() => new X509Certificate2(Path.Combine("TestData", "singlecert.p7b"))); } [Fact] public static void X509Certificate2FromPkcs7PemFile() { Assert.ThrowsAny<CryptographicException>(() => new X509Certificate2(Path.Combine("TestData", "singlecert.p7c"))); } [Fact] public static void X509Certificate2FromPkcs7DerBlob() { Assert.ThrowsAny<CryptographicException>(() => new X509Certificate2(TestData.Pkcs7SingleDerBytes)); } [Fact] public static void X509Certificate2FromPkcs7PemBlob() { Assert.ThrowsAny<CryptographicException>(() => new X509Certificate2(TestData.Pkcs7SinglePemBytes)); } [Fact] public static void UseAfterDispose() { using (X509Certificate2 c = new X509Certificate2(TestData.MsCertificate)) { IntPtr h = c.Handle; // Do a couple of things that would only be true on a valid certificate, as a precondition. Assert.NotEqual(IntPtr.Zero, h); byte[] actualThumbprint = c.GetCertHash(); c.Dispose(); // For compat reasons, Dispose() acts like the now-defunct Reset() method rather than // causing ObjectDisposedExceptions. h = c.Handle; Assert.Equal(IntPtr.Zero, h); // State held on X509Certificate Assert.ThrowsAny<CryptographicException>(() => c.GetCertHash()); Assert.ThrowsAny<CryptographicException>(() => c.GetCertHashString()); #if HAVE_THUMBPRINT_OVERLOADS Assert.ThrowsAny<CryptographicException>(() => c.GetCertHash(HashAlgorithmName.SHA256)); Assert.ThrowsAny<CryptographicException>(() => c.GetCertHashString(HashAlgorithmName.SHA256)); #endif Assert.ThrowsAny<CryptographicException>(() => c.GetKeyAlgorithm()); Assert.ThrowsAny<CryptographicException>(() => c.GetKeyAlgorithmParameters()); Assert.ThrowsAny<CryptographicException>(() => c.GetKeyAlgorithmParametersString()); Assert.ThrowsAny<CryptographicException>(() => c.GetPublicKey()); Assert.ThrowsAny<CryptographicException>(() => c.GetSerialNumber()); Assert.ThrowsAny<CryptographicException>(() => c.Issuer); Assert.ThrowsAny<CryptographicException>(() => c.Subject); Assert.ThrowsAny<CryptographicException>(() => c.NotBefore); Assert.ThrowsAny<CryptographicException>(() => c.NotAfter); #if HAVE_THUMBPRINT_OVERLOADS Assert.ThrowsAny<CryptographicException>( () => c.TryGetCertHash(HashAlgorithmName.SHA256, Array.Empty<byte>(), out _)); #endif // State held on X509Certificate2 Assert.ThrowsAny<CryptographicException>(() => c.RawData); Assert.ThrowsAny<CryptographicException>(() => c.SignatureAlgorithm); Assert.ThrowsAny<CryptographicException>(() => c.Version); Assert.ThrowsAny<CryptographicException>(() => c.SubjectName); Assert.ThrowsAny<CryptographicException>(() => c.IssuerName); Assert.ThrowsAny<CryptographicException>(() => c.PublicKey); Assert.ThrowsAny<CryptographicException>(() => c.Extensions); Assert.ThrowsAny<CryptographicException>(() => c.PrivateKey); } } [Fact] public static void ExportPublicKeyAsPkcs12() { using (X509Certificate2 publicOnly = new X509Certificate2(TestData.MsCertificate)) { // Pre-condition: There's no private key Assert.False(publicOnly.HasPrivateKey); // macOS 10.12 (Sierra) fails to create a PKCS#12 blob if it has no private keys within it. bool shouldThrow = RuntimeInformation.IsOSPlatform(OSPlatform.OSX); try { byte[] pkcs12Bytes = publicOnly.Export(X509ContentType.Pkcs12); Assert.False(shouldThrow, "PKCS#12 export of a public-only certificate threw as expected"); // Read it back as a collection, there should be only one cert, and it should // be equal to the one we started with. using (ImportedCollection ic = Cert.Import(pkcs12Bytes)) { X509Certificate2Collection fromPfx = ic.Collection; Assert.Equal(1, fromPfx.Count); Assert.Equal(publicOnly, fromPfx[0]); } } catch (CryptographicException) { if (!shouldThrow) { throw; } } } } [Fact] public static void X509Certificate2WithT61String() { string certSubject = @"[email protected], OU=Engineering, O=Xamarin, S=Massachusetts, C=US, CN=test-server.local"; using (var cert = new X509Certificate2(TestData.T61StringCertificate)) { Assert.Equal(certSubject, cert.Subject); Assert.Equal(certSubject, cert.Issuer); Assert.Equal("9E7A5CCC9F951A8700", cert.GetSerialNumber().ByteArrayToHex()); Assert.Equal("1.2.840.113549.1.1.1", cert.GetKeyAlgorithm()); Assert.Equal(74, cert.GetPublicKey().Length); Assert.Equal("test-server.local", cert.GetNameInfo(X509NameType.SimpleName, false)); Assert.Equal("[email protected]", cert.GetNameInfo(X509NameType.EmailName, false)); } } public static IEnumerable<object> StorageFlags => CollectionImportTests.StorageFlags; } }
using System; using System.Collections.Generic; using System.IO; using System.IO.Abstractions; using System.Linq; using System.Reflection; using ReactiveUIMicro; using Squirrel.Core; namespace Squirrel.Client { [Serializable] class InstallerHookOperations { readonly IRxUIFullLogger log; readonly IFileSystemFactory fileSystem; readonly string applicationName; public InstallerHookOperations(IFileSystemFactory fileSystem, string applicationName) { // XXX: ALWAYS BE LOGGING this.log = new WrappingFullLogger(new FileLogger(applicationName), typeof(InstallerHookOperations)); this.fileSystem = fileSystem; this.applicationName = applicationName; } public IEnumerable<string> RunAppSetupInstallers(PostInstallInfo info) { var appSetups = default(IEnumerable<IAppSetup>); try { appSetups = findAppSetupsToRun(info.NewAppDirectoryRoot); } catch (UnauthorizedAccessException ex) { log.ErrorException("Failed to load IAppSetups in post-install due to access denied", ex); return new string[0]; } ResolveEventHandler resolveAssembly = (obj, args) => { var directory = fileSystem.GetDirectoryInfo(info.NewAppDirectoryRoot); return tryResolveAssembly(directory, args); }; AppDomain.CurrentDomain.AssemblyResolve += resolveAssembly; var results = appSetups .Select(app => installAppVersion(app, info.NewCurrentVersion, info.ShortcutRequestsToIgnore, info.IsFirstInstall)) .Where(x => x != null) .ToArray(); AppDomain.CurrentDomain.AssemblyResolve -= resolveAssembly; return results; } public IEnumerable<ShortcutCreationRequest> RunAppSetupCleanups(string fullDirectoryPath) { var dirName = Path.GetFileName(fullDirectoryPath); var ver = new Version(dirName.Replace("app-", "")); var apps = default(IEnumerable<IAppSetup>); try { apps = findAppSetupsToRun(fullDirectoryPath); } catch (UnauthorizedAccessException ex) { log.ErrorException("Couldn't run cleanups", ex); return Enumerable.Empty<ShortcutCreationRequest>(); } var ret = apps.SelectMany(app => uninstallAppVersion(app, ver)).ToArray(); return ret; } IEnumerable<ShortcutCreationRequest> uninstallAppVersion(IAppSetup app, Version ver) { try { app.OnVersionUninstalling(ver); } catch (Exception ex) { log.ErrorException("App threw exception on uninstall: " + app.GetType().FullName, ex); } var shortcuts = Enumerable.Empty<ShortcutCreationRequest>(); try { shortcuts = app.GetAppShortcutList(); } catch (Exception ex) { log.ErrorException("App threw exception on shortcut uninstall: " + app.GetType().FullName, ex); } // Get the list of shortcuts that *should've* been there, but aren't; // this means that the user deleted them by hand and that they should // stay dead return shortcuts.Aggregate(new List<ShortcutCreationRequest>(), (acc, x) => { var path = x.GetLinkTarget(applicationName); var fi = fileSystem.GetFileInfo(path); if (fi.Exists) { fi.Delete(); log.Info("Deleting shortcut: {0}", fi.FullName); } else { acc.Add(x); log.Info("Shortcut not found: {0}, capturing for future reference", fi.FullName); } return acc; }); } string installAppVersion(IAppSetup app, Version newCurrentVersion, IEnumerable<ShortcutCreationRequest> shortcutRequestsToIgnore, bool isFirstInstall) { try { if (isFirstInstall) { log.Info("installAppVersion: Doing first install for {0}", app.Target); app.OnAppInstall(); } log.Info("installAppVersion: Doing install for version {0} {1}", newCurrentVersion, app.Target); app.OnVersionInstalled(newCurrentVersion); } catch (Exception ex) { log.ErrorException("App threw exception on install: " + app.GetType().FullName, ex); throw; } var shortcutList = Enumerable.Empty<ShortcutCreationRequest>(); try { shortcutList = app.GetAppShortcutList(); shortcutList.ForEach(x => log.Info("installAppVersion: we have a shortcut {0}", x.TargetPath)); } catch (Exception ex) { log.ErrorException("App threw exception on shortcut uninstall: " + app.GetType().FullName, ex); throw; } shortcutList .Where(x => !shortcutRequestsToIgnore.Contains(x)) .ForEach(x => { var shortcut = x.GetLinkTarget(applicationName, true); var fi = fileSystem.GetFileInfo(shortcut); log.Info("installAppVersion: checking shortcut {0}", fi.FullName); if (fi.Exists) { log.Info("installAppVersion: deleting existing file"); fi.Delete(); } fileSystem.CreateDirectoryRecursive(fi.Directory.FullName); var sl = new ShellLink { Target = x.TargetPath, IconPath = x.IconLibrary, IconIndex = x.IconIndex, Arguments = x.Arguments, WorkingDirectory = x.WorkingDirectory, Description = x.Description, }; sl.Save(shortcut); }); return app.LaunchOnSetup ? app.Target : null; } IEnumerable<IAppSetup> findAppSetupsToRun(string appDirectory) { var allExeFiles = default(FileInfoBase[]); var directory = fileSystem.GetDirectoryInfo(appDirectory); if (!directory.Exists) { log.Warn("findAppSetupsToRun: the folder {0} does not exist", appDirectory); return Enumerable.Empty<IAppSetup>(); } try { allExeFiles = directory.GetFiles("*.exe"); } catch (UnauthorizedAccessException ex) { // NB: This can happen if we run into a MoveFileEx'd directory, // where we can't even get the list of files in it. log.WarnException("Couldn't search directory for IAppSetups: " + appDirectory, ex); return Enumerable.Empty<IAppSetup>(); } var locatedAppSetups = allExeFiles .Where(f => f.Exists) .Select(x => loadAssemblyOrWhine(x.FullName)).Where(x => x != null) .SelectMany(x => x.GetModules()) .SelectMany(x => { try { return x.GetTypes().Where(y => typeof (IAppSetup).IsAssignableFrom(y)); } catch (ReflectionTypeLoadException ex) { var message = String.Format("Couldn't load types from module {0}", x.FullyQualifiedName); log.WarnException(message, ex); ex.LoaderExceptions.ForEach(le => log.WarnException("LoaderException found", le)); return Enumerable.Empty<Type>(); } }) .Select(createInstanceOrWhine).Where(x => x != null) .ToArray(); if (!locatedAppSetups.Any()) { log.Warn("Could not find any AppSetup instances"); allExeFiles.ForEach(f => log.Info("We have an exe: {0}", f.FullName)); return allExeFiles.Select(x => new DidntFollowInstructionsAppSetup(x.FullName)) .ToArray(); } return locatedAppSetups; } public IEnumerable<ShortcutCreationRequest> RunAppUninstall(string fullDirectoryPath) { ResolveEventHandler resolveAssembly = (obj, args) => { var directory = fileSystem.GetDirectoryInfo(fullDirectoryPath); return tryResolveAssembly(directory, args); }; AppDomain.CurrentDomain.AssemblyResolve += resolveAssembly; var apps = default(IEnumerable<IAppSetup>); try { apps = findAppSetupsToRun(fullDirectoryPath); } catch (UnauthorizedAccessException ex) { log.ErrorException("Couldn't run cleanups", ex); return Enumerable.Empty<ShortcutCreationRequest>(); } var ret = apps.SelectMany(uninstallApp).ToArray(); AppDomain.CurrentDomain.AssemblyResolve -= resolveAssembly; return ret; } IEnumerable<ShortcutCreationRequest> uninstallApp(IAppSetup app) { try { app.OnAppUninstall(); } catch (Exception ex) { log.ErrorException("App threw exception on uninstall: " + app.GetType().FullName, ex); } var shortcuts = Enumerable.Empty<ShortcutCreationRequest>(); try { shortcuts = app.GetAppShortcutList(); } catch (Exception ex) { log.ErrorException("App threw exception on shortcut uninstall: " + app.GetType().FullName, ex); } // Get the list of shortcuts that *should've* been there, but aren't; // this means that the user deleted them by hand and that they should // stay dead return shortcuts.Aggregate(new List<ShortcutCreationRequest>(), (acc, x) => { var path = x.GetLinkTarget(applicationName); var fi = fileSystem.GetFileInfo(path); if (fi.Exists) { fi.Delete(); log.Info("Deleting shortcut: {0}", fi.FullName); } else { acc.Add(x); log.Info("Shortcut not found: {0}, capturing for future reference", fi.FullName); } return acc; }); } IAppSetup createInstanceOrWhine(Type typeToCreate) { try { return (IAppSetup) Activator.CreateInstance(typeToCreate); } catch (Exception ex) { log.WarnException("Post-install: Failed to create type " + typeToCreate.FullName, ex); return null; } } Assembly loadAssemblyOrWhine(string fileToLoad) { try { var ret = Assembly.LoadFile(fileToLoad); return ret; } catch (Exception ex) { log.WarnException("Post-install: load failed for " + fileToLoad, ex); return null; } } Assembly tryResolveAssembly(DirectoryInfoBase directory, ResolveEventArgs args) { try { if (directory.Exists) { var files = directory.GetFiles("*.dll") .Concat(directory.GetFiles("*.exe")); foreach (var f in files) { var assemblyName = AssemblyName.GetAssemblyName(f.FullName); if (assemblyName.FullName == args.Name) { return Assembly.Load(assemblyName); } } } } catch (Exception ex) { log.WarnException("Could not resolve assembly: " + args.Name, ex); } return 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.Diagnostics; using Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { internal partial class ExpressionBinder { // ---------------------------------------------------------------------------- // BindExplicitConversion // ---------------------------------------------------------------------------- private class ExplicitConversion { private ExpressionBinder _binder; private EXPR _exprSrc; private CType _typeSrc; private CType _typeDest; private EXPRTYPEORNAMESPACE _exprTypeDest; // This is for lambda error reporting. The reason we have this is because we // store errors for lambda conversions, and then we dont bind the conversion // again to report errors. Consider the following case: // // int? x = () => null; // // When we try to convert the lambda to the nullable type int?, we first // attempt the conversion to int. If that fails, then we know there is no // conversion to int?, since int is a predef type. We then look for UserDefined // conversions, and fail. When we report the errors, we ask the lambda for its // conversion errors. But since we attempted its conversion to int and not int?, // we report the wrong error. This field is to keep track of the right type // to report the error on, so that when the lambda conversion fails, it reports // errors on the correct type. private CType _pDestinationTypeForLambdaErrorReporting; private EXPR _exprDest; private bool _needsExprDest; private CONVERTTYPE _flags; // ---------------------------------------------------------------------------- // BindExplicitConversion // ---------------------------------------------------------------------------- public ExplicitConversion(ExpressionBinder binder, EXPR exprSrc, CType typeSrc, EXPRTYPEORNAMESPACE typeDest, CType pDestinationTypeForLambdaErrorReporting, bool needsExprDest, CONVERTTYPE flags) { _binder = binder; _exprSrc = exprSrc; _typeSrc = typeSrc; _typeDest = typeDest.TypeOrNamespace.AsType(); _pDestinationTypeForLambdaErrorReporting = pDestinationTypeForLambdaErrorReporting; _exprTypeDest = typeDest; _needsExprDest = needsExprDest; _flags = flags; _exprDest = null; } public EXPR ExprDest { get { return _exprDest; } } /* * BindExplicitConversion * * This is a complex routine with complex parameter. Generally, this should * be called through one of the helper methods that insulates you * from the complexity of the interface. This routine handles all the logic * associated with explicit conversions. * * Note that this function calls BindImplicitConversion first, so the main * logic is only concerned with conversions that can be made explicitly, but * not implicitly. */ public bool Bind() { // To test for a standard conversion, call canConvert(exprSrc, typeDest, STANDARDANDCONVERTTYPE.NOUDC) and // canConvert(typeDest, typeSrc, STANDARDANDCONVERTTYPE.NOUDC). Debug.Assert((_flags & CONVERTTYPE.STANDARD) == 0); // 13.2 Explicit conversions // // The following conversions are classified as explicit conversions: // // * All implicit conversions // * Explicit numeric conversions // * Explicit enumeration conversions // * Explicit reference conversions // * Explicit interface conversions // * Unboxing conversions // * Explicit type parameter conversions // * User-defined explicit conversions // * Explicit nullable conversions // * Lifted user-defined explicit conversions // // Explicit conversions can occur in cast expressions (14.6.6). // // The explicit conversions that are not implicit conversions are conversions that cannot be // proven always to succeed, conversions that are known possibly to lose information, and // conversions across domains of types sufficiently different to merit explicit notation. // The set of explicit conversions includes all implicit conversions. // Don't try user-defined conversions now because we'll try them again later. if (_binder.BindImplicitConversion(_exprSrc, _typeSrc, _exprTypeDest, _pDestinationTypeForLambdaErrorReporting, _needsExprDest, out _exprDest, _flags | CONVERTTYPE.ISEXPLICIT)) { return true; } if (_typeSrc == null || _typeDest == null || _typeSrc.IsErrorType() || _typeDest.IsErrorType() || _typeDest.IsNeverSameType()) { return false; } if (_typeDest.IsNullableType()) { // This is handled completely by BindImplicitConversion. return false; } if (_typeSrc.IsNullableType()) { return bindExplicitConversionFromNub(); } if (bindExplicitConversionFromArrayToIList()) { return true; } // if we were casting an integral constant to another constant type, // then, if the constant were in range, then the above call would have succeeded. // But it failed, and so we know that the constant is not in range switch (_typeDest.GetTypeKind()) { default: VSFAIL("Bad type kind"); return false; case TypeKind.TK_VoidType: return false; // Can't convert to a method group or anon method. case TypeKind.TK_NullType: return false; // Can never convert TO the null type. case TypeKind.TK_TypeParameterType: if (bindExplicitConversionToTypeVar()) { return true; } break; case TypeKind.TK_ArrayType: if (bindExplicitConversionToArray(_typeDest.AsArrayType())) { return true; } break; case TypeKind.TK_PointerType: if (bindExplicitConversionToPointer()) { return true; } break; case TypeKind.TK_AggregateType: { AggCastResult result = bindExplicitConversionToAggregate(_typeDest.AsAggregateType()); if (result == AggCastResult.Success) { return true; } if (result == AggCastResult.Abort) { return false; } break; } } // No built-in conversion was found. Maybe a user-defined conversion? if (0 == (_flags & CONVERTTYPE.NOUDC)) { return _binder.bindUserDefinedConversion(_exprSrc, _typeSrc, _typeDest, _needsExprDest, out _exprDest, false); } return false; } private bool bindExplicitConversionFromNub() { Debug.Assert(_typeSrc != null); Debug.Assert(_typeDest != null); // If S and T are value types and there is a builtin conversion from S => T then there is an // explicit conversion from S? => T that throws on null. if (_typeDest.IsValType() && _binder.BindExplicitConversion(null, _typeSrc.StripNubs(), _exprTypeDest, _pDestinationTypeForLambdaErrorReporting, _flags | CONVERTTYPE.NOUDC)) { if (_needsExprDest) { EXPR valueSrc = _exprSrc; // This is a holdover from the days when you could have nullable of nullable. // Can we remove this loop? while (valueSrc.type.IsNullableType()) { valueSrc = _binder.BindNubValue(valueSrc); } Debug.Assert(valueSrc.type == _typeSrc.StripNubs()); if (!_binder.BindExplicitConversion(valueSrc, valueSrc.type, _exprTypeDest, _pDestinationTypeForLambdaErrorReporting, _needsExprDest, out _exprDest, _flags | CONVERTTYPE.NOUDC)) { VSFAIL("BindExplicitConversion failed unexpectedly"); return false; } if (_exprDest.kind == ExpressionKind.EK_USERDEFINEDCONVERSION) { _exprDest.asUSERDEFINEDCONVERSION().Argument = _exprSrc; } } return true; } if ((_flags & CONVERTTYPE.NOUDC) == 0) { return _binder.bindUserDefinedConversion(_exprSrc, _typeSrc, _typeDest, _needsExprDest, out _exprDest, false); } return false; } private bool bindExplicitConversionFromArrayToIList() { // 13.2.2 // // The explicit reference conversions are: // // * From a one-dimensional array-type S[] to System.Collections.Generic.IList<T>, System.Collections.Generic.IReadOnlyList<T> and // their base interfaces, provided there is an explicit reference conversion from S to T. Debug.Assert(_typeSrc != null); Debug.Assert(_typeDest != null); if (!_typeSrc.IsArrayType() || _typeSrc.AsArrayType().rank != 1 || !_typeDest.isInterfaceType() || _typeDest.AsAggregateType().GetTypeArgsAll().Size != 1) { return false; } AggregateSymbol aggIList = GetSymbolLoader().GetOptPredefAgg(PredefinedType.PT_G_ILIST); AggregateSymbol aggIReadOnlyList = GetSymbolLoader().GetOptPredefAgg(PredefinedType.PT_G_IREADONLYLIST); if ((aggIList == null || !GetSymbolLoader().IsBaseAggregate(aggIList, _typeDest.AsAggregateType().getAggregate())) && (aggIReadOnlyList == null || !GetSymbolLoader().IsBaseAggregate(aggIReadOnlyList, _typeDest.AsAggregateType().getAggregate()))) { return false; } CType typeArr = _typeSrc.AsArrayType().GetElementType(); CType typeLst = _typeDest.AsAggregateType().GetTypeArgsAll().Item(0); if (!CConversions.FExpRefConv(GetSymbolLoader(), typeArr, typeLst)) { return false; } if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_REFCHECK); return true; } private bool bindExplicitConversionToTypeVar() { // 13.2.3 Explicit reference conversions // // For a type-parameter T that is known to be a reference type (25.7), the following // explicit reference conversions exist: // // * From the effective base class C of T to T and from any base class of C to T. // * From any interface-type to T. // * From a type-parameter U to T provided that T depends on U (25.7). Debug.Assert(_typeSrc != null); Debug.Assert(_typeDest != null); // NOTE: for the flags, we have to use EXPRFLAG.EXF_FORCE_UNBOX (not EXPRFLAG.EXF_REFCHECK) even when // we know that the type is a reference type. The verifier expects all code for // type parameters to behave as if the type parameter is a value type. // The jitter should be smart about it.... if (_typeSrc.isInterfaceType() || _binder.canConvert(_typeDest, _typeSrc, CONVERTTYPE.NOUDC)) { if (!_needsExprDest) { return true; } // There is an explicit, possibly unboxing, conversion from Object or any interface to // a type variable. This will involve a type check and possibly an unbox. // There is an explicit conversion from non-interface X to the type var iff there is an // implicit conversion from the type var to X. if (_typeSrc.IsTypeParameterType()) { // Need to box first before unboxing. EXPR exprT; EXPRCLASS exprObj = GetExprFactory().MakeClass(_binder.GetReqPDT(PredefinedType.PT_OBJECT)); _binder.bindSimpleCast(_exprSrc, exprObj, out exprT, EXPRFLAG.EXF_FORCE_BOX); _exprSrc = exprT; } if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_FORCE_UNBOX); return true; } return false; } private bool bindExplicitConversionFromIListToArray(ArrayType arrayDest) { // 13.2.2 // // The explicit reference conversions are: // // * From System.Collections.Generic.IList<T>, System.Collections.Generic.IReadOnlyList<T> and their base interfaces // to a one-dimensional array-type S[], provided there is an implicit or explicit reference conversion from // S[] to System.Collections.Generic.IList<T> or System.Collections.Generic.IReadOnlyList<T>. This is precisely when either S and T // are the same type or there is an implicit or explicit reference conversion from S to T. if (arrayDest.rank != 1 || !_typeSrc.isInterfaceType() || _typeSrc.AsAggregateType().GetTypeArgsAll().Size != 1) { return false; } AggregateSymbol aggIList = GetSymbolLoader().GetOptPredefAgg(PredefinedType.PT_G_ILIST); AggregateSymbol aggIReadOnlyList = GetSymbolLoader().GetOptPredefAgg(PredefinedType.PT_G_IREADONLYLIST); if ((aggIList == null || !GetSymbolLoader().IsBaseAggregate(aggIList, _typeSrc.AsAggregateType().getAggregate())) && (aggIReadOnlyList == null || !GetSymbolLoader().IsBaseAggregate(aggIReadOnlyList, _typeSrc.AsAggregateType().getAggregate()))) { return false; } CType typeArr = arrayDest.GetElementType(); CType typeLst = _typeSrc.AsAggregateType().GetTypeArgsAll().Item(0); Debug.Assert(!typeArr.IsNeverSameType()); if (typeArr != typeLst && !CConversions.FExpRefConv(GetSymbolLoader(), typeArr, typeLst)) { return false; } if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_REFCHECK); return true; } private bool bindExplicitConversionFromArrayToArray(ArrayType arraySrc, ArrayType arrayDest) { // 13.2.2 // // The explicit reference conversions are: // // * From an array-type S with an element type SE to an array-type T with an element type // TE, provided all of the following are true: // // * S and T differ only in element type. (In other words, S and T have the same number // of dimensions.) // // * An explicit reference conversion exists from SE to TE. if (arraySrc.rank != arrayDest.rank) { return false; // Ranks do not match. } if (CConversions.FExpRefConv(GetSymbolLoader(), arraySrc.GetElementType(), arrayDest.GetElementType())) { if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_REFCHECK); return true; } return false; } private bool bindExplicitConversionToArray(ArrayType arrayDest) { Debug.Assert(_typeSrc != null); Debug.Assert(arrayDest != null); if (_typeSrc.IsArrayType()) { return bindExplicitConversionFromArrayToArray(_typeSrc.AsArrayType(), arrayDest); } if (bindExplicitConversionFromIListToArray(arrayDest)) { return true; } // 13.2.2 // // The explicit reference conversions are: // // * From System.Array and the interfaces it implements, to any array-type. if (_binder.canConvert(_binder.GetReqPDT(PredefinedType.PT_ARRAY), _typeSrc, CONVERTTYPE.NOUDC)) { if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_REFCHECK); return true; } return false; } private bool bindExplicitConversionToPointer() { // 27.4 Pointer conversions // // in an unsafe context, the set of available explicit conversions (13.2) is extended to // include the following explicit pointer conversions: // // * From any pointer-type to any other pointer-type. // * From sbyte, byte, short, ushort, int, uint, long, or ulong to any pointer-type. if (_typeSrc.IsPointerType() || _typeSrc.fundType() <= FUNDTYPE.FT_LASTINTEGRAL && _typeSrc.isNumericType()) { if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest); return true; } return false; } // 13.2.2 Explicit enumeration conversions // // The explicit enumeration conversions are: // // * From sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, or // decimal to any enum-type. // // * From any enum-type to sbyte, byte, short, ushort, int, uint, long, ulong, char, // float, double, or decimal. // // * From any enum-type to any other enum-type. // // * An explicit enumeration conversion between two types is processed by treating any // participating enum-type as the underlying type of that enum-type, and then performing // an implicit or explicit numeric conversion between the resulting types. private AggCastResult bindExplicitConversionFromEnumToAggregate(AggregateType aggTypeDest) { Debug.Assert(_typeSrc != null); Debug.Assert(aggTypeDest != null); if (!_typeSrc.isEnumType()) { return AggCastResult.Failure; } AggregateSymbol aggDest = aggTypeDest.getAggregate(); if (aggDest.isPredefAgg(PredefinedType.PT_DECIMAL)) { return bindExplicitConversionFromEnumToDecimal(aggTypeDest); } if (!aggDest.getThisType().isNumericType() && !aggDest.IsEnum() && !(aggDest.IsPredefined() && aggDest.GetPredefType() == PredefinedType.PT_CHAR)) { return AggCastResult.Failure; } if (_exprSrc.GetConst() != null) { ConstCastResult result = _binder.bindConstantCast(_exprSrc, _exprTypeDest, _needsExprDest, out _exprDest, true); if (result == ConstCastResult.Success) { return AggCastResult.Success; } else if (result == ConstCastResult.CheckFailure) { return AggCastResult.Abort; } } if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest); return AggCastResult.Success; } private AggCastResult bindExplicitConversionFromDecimalToEnum(AggregateType aggTypeDest) { Debug.Assert(_typeSrc != null); Debug.Assert(_typeSrc.isPredefType(PredefinedType.PT_DECIMAL)); // There is an explicit conversion from decimal to all integral types. if (_exprSrc.GetConst() != null) { // Fold the constant cast if possible. ConstCastResult result = _binder.bindConstantCast(_exprSrc, _exprTypeDest, _needsExprDest, out _exprDest, true); if (result == ConstCastResult.Success) { return AggCastResult.Success; // else, don't fold and use a regular cast, below. } if (result == ConstCastResult.CheckFailure && 0 == (_flags & CONVERTTYPE.CHECKOVERFLOW)) { return AggCastResult.Abort; } } // All casts from decimal to integer types are bound as user-defined conversions. bool bIsConversionOK = true; if (_needsExprDest) { // According the language, this is a standard conversion, but it is implemented // through a user-defined conversion. Because it's a standard conversion, we don't // test the CONVERTTYPE.NOUDC flag here. CType underlyingType = aggTypeDest.underlyingType(); bIsConversionOK = _binder.bindUserDefinedConversion(_exprSrc, _typeSrc, underlyingType, _needsExprDest, out _exprDest, false); if (bIsConversionOK) { // upcast to the Enum type _binder.bindSimpleCast(_exprDest, _exprTypeDest, out _exprDest); } } return bIsConversionOK ? AggCastResult.Success : AggCastResult.Failure; } private AggCastResult bindExplicitConversionFromEnumToDecimal(AggregateType aggTypeDest) { Debug.Assert(_typeSrc != null); Debug.Assert(aggTypeDest != null); Debug.Assert(aggTypeDest.isPredefType(PredefinedType.PT_DECIMAL)); AggregateType underlyingType = _typeSrc.underlyingType().AsAggregateType(); // Need to first cast the source expr to its underlying type. EXPR exprCast; if (_exprSrc == null) { exprCast = null; } else { EXPRCLASS underlyingExpr = GetExprFactory().MakeClass(underlyingType); _binder.bindSimpleCast(_exprSrc, underlyingExpr, out exprCast); } // There is always an implicit conversion from any integral type to decimal. if (exprCast.GetConst() != null) { // Fold the constant cast if possible. ConstCastResult result = _binder.bindConstantCast(exprCast, _exprTypeDest, _needsExprDest, out _exprDest, true); if (result == ConstCastResult.Success) { return AggCastResult.Success; // else, don't fold and use a regular cast, below. } if (result == ConstCastResult.CheckFailure && 0 == (_flags & CONVERTTYPE.CHECKOVERFLOW)) { return AggCastResult.Abort; } } // Conversions from integral types to decimal are always bound as a user-defined conversion. if (_needsExprDest) { // According the language, this is a standard conversion, but it is implemented // through a user-defined conversion. Because it's a standard conversion, we don't // test the CONVERTTYPE.NOUDC flag here. bool ok = _binder.bindUserDefinedConversion(exprCast, underlyingType, aggTypeDest, _needsExprDest, out _exprDest, false); Debug.Assert(ok); } return AggCastResult.Success; } private AggCastResult bindExplicitConversionToEnum(AggregateType aggTypeDest) { Debug.Assert(_typeSrc != null); Debug.Assert(aggTypeDest != null); AggregateSymbol aggDest = aggTypeDest.getAggregate(); if (!aggDest.IsEnum()) { return AggCastResult.Failure; } if (_typeSrc.isPredefType(PredefinedType.PT_DECIMAL)) { return bindExplicitConversionFromDecimalToEnum(aggTypeDest); } if (_typeSrc.isNumericType() || (_typeSrc.isPredefined() && _typeSrc.getPredefType() == PredefinedType.PT_CHAR)) { // Transform constant to constant. if (_exprSrc.GetConst() != null) { ConstCastResult result = _binder.bindConstantCast(_exprSrc, _exprTypeDest, _needsExprDest, out _exprDest, true); if (result == ConstCastResult.Success) { return AggCastResult.Success; } if (result == ConstCastResult.CheckFailure) { return AggCastResult.Abort; } } if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest); return AggCastResult.Success; } else if (_typeSrc.isPredefined() && (_typeSrc.isPredefType(PredefinedType.PT_OBJECT) || _typeSrc.isPredefType(PredefinedType.PT_VALUE) || _typeSrc.isPredefType(PredefinedType.PT_ENUM))) { if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_UNBOX); return AggCastResult.Success; } return AggCastResult.Failure; } private AggCastResult bindExplicitConversionBetweenSimpleTypes(AggregateType aggTypeDest) { // 13.2.1 // // Because the explicit conversions include all implicit and explicit numeric conversions, // it is always possible to convert from any numeric-type to any other numeric-type using // a cast expression (14.6.6). Debug.Assert(_typeSrc != null); Debug.Assert(aggTypeDest != null); if (!_typeSrc.isSimpleType() || !aggTypeDest.isSimpleType()) { return AggCastResult.Failure; } AggregateSymbol aggDest = aggTypeDest.getAggregate(); Debug.Assert(_typeSrc.isPredefined() && aggDest.IsPredefined()); PredefinedType ptSrc = _typeSrc.getPredefType(); PredefinedType ptDest = aggDest.GetPredefType(); Debug.Assert((int)ptSrc < NUM_SIMPLE_TYPES && (int)ptDest < NUM_SIMPLE_TYPES); ConvKind convertKind = GetConvKind(ptSrc, ptDest); // Identity and implicit conversions should already have been handled. Debug.Assert(convertKind != ConvKind.Implicit); Debug.Assert(convertKind != ConvKind.Identity); if (convertKind != ConvKind.Explicit) { return AggCastResult.Failure; } if (_exprSrc.GetConst() != null) { // Fold the constant cast if possible. ConstCastResult result = _binder.bindConstantCast(_exprSrc, _exprTypeDest, _needsExprDest, out _exprDest, true); if (result == ConstCastResult.Success) { return AggCastResult.Success; // else, don't fold and use a regular cast, below. } if (result == ConstCastResult.CheckFailure && 0 == (_flags & CONVERTTYPE.CHECKOVERFLOW)) { return AggCastResult.Abort; } } bool bConversionOk = true; if (_needsExprDest) { // Explicit conversions involving decimals are bound as user-defined conversions. if (isUserDefinedConversion(ptSrc, ptDest)) { // According the language, this is a standard conversion, but it is implemented // through a user-defined conversion. Because it's a standard conversion, we don't // test the CONVERTTYPE.NOUDC flag here. bConversionOk = _binder.bindUserDefinedConversion(_exprSrc, _typeSrc, aggTypeDest, _needsExprDest, out _exprDest, false); } else { _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, (_flags & CONVERTTYPE.CHECKOVERFLOW) != 0 ? EXPRFLAG.EXF_CHECKOVERFLOW : 0); } } return bConversionOk ? AggCastResult.Success : AggCastResult.Failure; } private AggCastResult bindExplicitConversionBetweenAggregates(AggregateType aggTypeDest) { // 13.2.3 // // The explicit reference conversions are: // // * From object to any reference-type. // * From any class-type S to any class-type T, provided S is a base class of T. // * From any class-type S to any interface-type T, provided S is not sealed and // provided S does not implement T. // * From any interface-type S to any class-type T, provided T is not sealed or provided // T implements S. // * From any interface-type S to any interface-type T, provided S is not derived from T. Debug.Assert(_typeSrc != null); Debug.Assert(aggTypeDest != null); if (!_typeSrc.IsAggregateType()) { return AggCastResult.Failure; } AggregateSymbol aggSrc = _typeSrc.AsAggregateType().getAggregate(); AggregateSymbol aggDest = aggTypeDest.getAggregate(); if (GetSymbolLoader().HasBaseConversion(aggTypeDest, _typeSrc.AsAggregateType())) { if (_needsExprDest) { if (aggDest.IsValueType() && aggSrc.getThisType().fundType() == FUNDTYPE.FT_REF) { _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_UNBOX); } else { _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_REFCHECK | (_exprSrc != null ? (_exprSrc.flags & EXPRFLAG.EXF_CANTBENULL) : 0)); } } return AggCastResult.Success; } if ((aggSrc.IsClass() && !aggSrc.IsSealed() && aggDest.IsInterface()) || (aggSrc.IsInterface() && aggDest.IsClass() && !aggDest.IsSealed()) || (aggSrc.IsInterface() && aggDest.IsInterface()) || CConversions.HasGenericDelegateExplicitReferenceConversion(GetSymbolLoader(), _typeSrc, aggTypeDest)) { if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_REFCHECK | (_exprSrc != null ? (_exprSrc.flags & EXPRFLAG.EXF_CANTBENULL) : 0)); return AggCastResult.Success; } return AggCastResult.Failure; } private AggCastResult bindExplicitConversionFromPointerToInt(AggregateType aggTypeDest) { // 27.4 Pointer conversions // in an unsafe context, the set of available explicit conversions (13.2) is extended to include // the following explicit pointer conversions: // // * From any pointer-type to sbyte, byte, short, ushort, int, uint, long, or ulong. if (!_typeSrc.IsPointerType() || aggTypeDest.fundType() > FUNDTYPE.FT_LASTINTEGRAL || !aggTypeDest.isNumericType()) { return AggCastResult.Failure; } if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest); return AggCastResult.Success; } private AggCastResult bindExplicitConversionFromTypeVarToAggregate(AggregateType aggTypeDest) { // 13.2.3 Explicit reference conversions // // For a type-parameter T that is known to be a reference type (25.7), the following // explicit reference conversions exist: // // * From T to any interface-type I provided there isn't already an implicit reference // conversion from T to I. if (!_typeSrc.IsTypeParameterType()) { return AggCastResult.Failure; } #if ! CSEE if (aggTypeDest.getAggregate().IsInterface()) #else if ((exprSrc != null && !exprSrc.eeValue.substType.IsNullableType()) || aggTypeDest.getAggregate().IsInterface()) #endif { // Explicit conversion of type variables to interfaces. if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_FORCE_BOX | EXPRFLAG.EXF_REFCHECK); return AggCastResult.Success; } return AggCastResult.Failure; } private AggCastResult bindExplicitConversionToAggregate(AggregateType aggTypeDest) { Debug.Assert(_typeSrc != null); Debug.Assert(aggTypeDest != null); // TypeReference and ArgIterator can't be boxed (or converted to anything else) if (_typeSrc.isSpecialByRefType()) { return AggCastResult.Abort; } AggCastResult result; result = bindExplicitConversionFromEnumToAggregate(aggTypeDest); if (result != AggCastResult.Failure) { return result; } result = bindExplicitConversionToEnum(aggTypeDest); if (result != AggCastResult.Failure) { return result; } result = bindExplicitConversionBetweenSimpleTypes(aggTypeDest); if (result != AggCastResult.Failure) { return result; } result = bindExplicitConversionBetweenAggregates(aggTypeDest); if (result != AggCastResult.Failure) { return result; } result = bindExplicitConversionFromPointerToInt(aggTypeDest); if (result != AggCastResult.Failure) { return result; } if (_typeSrc.IsVoidType()) { // No conversion is allowed to or from a void type (user defined or otherwise) // This is most likely the result of a failed anonymous method or member group conversion return AggCastResult.Abort; } result = bindExplicitConversionFromTypeVarToAggregate(aggTypeDest); if (result != AggCastResult.Failure) { return result; } return AggCastResult.Failure; } private SymbolLoader GetSymbolLoader() { return _binder.GetSymbolLoader(); } private ExprFactory GetExprFactory() { return _binder.GetExprFactory(); } } } }
using System; using System.Linq; using NUnit.Framework; namespace HouraiTeahouse { [Parallelizable] public class TaskTest { [Test] public void can_resolve_simple_task() { var taskdValue = 5; ITask<int> task = Task.FromResult(taskdValue); var completed = 0; task.Then(v => { Assert.AreEqual(taskdValue, v); ++completed; }); Assert.AreEqual(1, completed); } [Test] public void can_reject_simple_task() { var ex = new Exception(); ITask task = Task.FromError(ex); var errors = 0; task.Catch(e => { Assert.AreEqual(ex, e); ++errors; }); Assert.AreEqual(1, errors); } [Test] public void exception_is_thrown_for_reject_after_reject() { var task = new Task<int>(); task.Reject(new Exception()); Assert.Throws<InvalidOperationException>(() => task.Reject(new Exception())); } [Test] public void exception_is_thrown_for_reject_after_resolve() { var task = new Task<int>(); task.Resolve(5); Assert.Throws<InvalidOperationException>(() => task.Reject(new Exception())); } [Test] public void exception_is_thrown_for_resolve_after_reject() { var task = new Task<int>(); task.Reject(new Exception()); Assert.Throws<InvalidOperationException>(() => task.Resolve(5)); } [Test] public void can_resolve_task_and_trigger_then_handler() { var task = new Task<int>(); var completed = 0; var taskdValue = 15; task.Then(v => { Assert.AreEqual(taskdValue, v); ++completed; }); task.Resolve(taskdValue); Assert.AreEqual(1, completed); } [Test] public void exception_is_thrown_for_resolve_after_resolve() { var task = new Task<int>(); task.Resolve(5); Assert.Throws<InvalidOperationException>(() => task.Resolve(5)); } [Test] public void can_resolve_task_and_trigger_multiple_then_handlers_in_order() { var task = new Task<int>(); var completed = 0; task.Then(v => Assert.AreEqual(1, completed++)); task.Then(v => Assert.AreEqual(2, completed++)); task.Resolve(1); Assert.AreEqual(2, completed); } [Test] public void can_resolve_task_and_trigger_then_handler_with_callback_registration_after_resolve() { var task = new Task<int>(); var completed = 0; int taskdValue = -10; task.Resolve(taskdValue); task.Then(v => { Assert.AreEqual(taskdValue, v); ++completed; }); Assert.AreEqual(1, completed); } [Test] public void can_reject_task_and_trigger_error_handler() { var task = new Task<int>(); var ex = new ApplicationException(); var completed = 0; task.Catch(e => { Assert.AreEqual(ex, e); ++completed; }); task.Reject(ex); Assert.AreEqual(1, completed); } [Test] public void can_reject_task_and_trigger_multiple_error_handlers_in_order() { var task = new Task<int>(); var ex = new ApplicationException(); var completed = 0; task.Catch(e => { Assert.AreEqual(ex, e); Assert.AreEqual(1, ++completed); }); task.Catch(e => { Assert.AreEqual(ex, e); Assert.AreEqual(2, ++completed); }); task.Reject(ex); Assert.AreEqual(2, completed); } [Test] public void can_reject_task_and_trigger_error_handler_with_registration_after_reject() { var task = new Task<int>(); var ex = new ApplicationException(); task.Reject(ex); var completed = 0; task.Catch(e => { Assert.AreEqual(ex, e); ++completed; }); Assert.AreEqual(1, completed); } [Test] public void error_handler_is_not_invoked_for_resolved_taskd() { var task = new Task<int>(); task.Catch(e => { throw new ApplicationException("This shouldn't happen"); }); task.Resolve(5); } [Test] public void then_handler_is_not_invoked_for_rejected_task() { var task = new Task<int>(); task.Then(v => { throw new ApplicationException("This shouldn't happen"); }); task.Reject(new ApplicationException("Rejection!")); } [Test] public void chain_multiple_tasks_using_all() { var task = new Task<string>(); var chainedTask1 = new Task<int>(); var chainedTask2 = new Task<int>(); var chainedResult1 = 10; var chainedResult2 = 15; var completed = 0; task.ThenAll(chainedTask1, chainedTask2).Then(result => { Assert.AreEqual(2, result.Length); Assert.AreEqual(chainedResult1, result[0]); Assert.AreEqual(chainedResult2, result[1]); completed++; }); Assert.AreEqual(0, completed); task.Resolve("hello"); Assert.AreEqual(0, completed); chainedTask1.Resolve(chainedResult1); Assert.AreEqual(0, completed); chainedTask2.Resolve(chainedResult2); Assert.AreEqual(1, completed); } [Test] public void chain_multiple_tasks_using_all_that_are_resolved_out_of_order() { var task = new Task<string>(); var chainedTask1 = new Task<int>(); var chainedTask2 = new Task<int>(); var chainedResult1 = 10; var chainedResult2 = 15; var completed = 0; task.ThenAll(chainedTask1, chainedTask2).Then(result => { Assert.AreEqual(2, result.Length); Assert.AreEqual(chainedResult1, result[0]); Assert.AreEqual(chainedResult2, result[1]); completed++; }); Assert.AreEqual(0, completed); task.Resolve("hello"); Assert.AreEqual(0, completed); chainedTask2.Resolve(chainedResult2); Assert.AreEqual(0, completed); chainedTask1.Resolve(chainedResult1); Assert.AreEqual(1, completed); } [Test] public void chain_multiple_tasks_using_all_and_convert_to_non_value_task() { var task = new Task<string>(); var chainedTask1 = new Task(); var chainedTask2 = new Task(); var completed = 0; task.ThenAll(chainedTask1, chainedTask2).Then(() => { ++completed; }); Assert.AreEqual(0, completed); task.Resolve("hello"); Assert.AreEqual(0, completed); chainedTask1.Resolve(); Assert.AreEqual(0, completed); chainedTask2.Resolve(); Assert.AreEqual(1, completed); } [Test] public void combined_task_is_resolved_when_children_are_resolved() { var task1 = new Task<int>(); var task2 = new Task<int>(); ITask<int[]> all = Task.All(task1, task2); var completed = 0; all.Then(v => { completed++; Assert.AreEqual(2, v.Length); Assert.AreEqual(1, v[0]); Assert.AreEqual(2, v[1]); }); task1.Resolve(1); task2.Resolve(2); Assert.AreEqual(1, completed); } [Test] public void combined_task_is_rejected_when_first_task_is_rejected() { var task1 = new Task<int>(); var task2 = new Task<int>(); ITask<int[]> all = Task.All(task1, task2); all.Then(v => { throw new ApplicationException("Shouldn't happen"); }); var errors = 0; all.Catch(e => { errors++; }); task1.Reject(new ApplicationException("Error!")); task2.Resolve(2); Assert.AreEqual(1, errors); } [Test] public void combined_task_is_rejected_when_second_task_is_rejected() { var task1 = new Task<int>(); var task2 = new Task<int>(); ITask<int[]> all = Task.All(task1, task2); all.Then(v => { throw new ApplicationException("Shouldn't happen"); }); var errors = 0; all.Catch(e => { ++errors; }); task1.Resolve(2); task2.Reject(new ApplicationException("Error!")); Assert.AreEqual(1, errors); } [Test] public void combined_task_is_rejected_when_both_tasks_are_rejected() { var task1 = new Task<int>(); var task2 = new Task<int>(); ITask<int[]> all = Task.All(task1, task2); all.Then(v => { throw new ApplicationException("Shouldn't happen"); }); var errors = 0; all.Catch(e => { ++errors; }); task1.Reject(new ApplicationException("Error!")); task2.Reject(new ApplicationException("Error!")); Assert.AreEqual(1, errors); } [Test] public void combined_task_is_resolved_if_there_are_no_tasks() { ITask<int[]> all = Task.All(Enumerable.Empty<ITask<int>>()); var completed = 0; all.Then(v => { completed++; Assert.IsEmpty(v); }); Assert.AreEqual(1, completed); } [Test] public void combined_task_is_resolved_when_all_tasks_are_already_resolved() { ITask<int> task1 = Task.FromResult(1); ITask<int> task2 = Task.FromResult(1); ITask<ITask<int>[]> all = Task.All(Task.FromResults(task1, task2)); var completed = 0; all.Then(v => { completed++; Assert.IsEmpty(v); }); Assert.AreEqual(1, completed); } [Test] public void can_transform_task_value() { var task = new Task<int>(); var taskdValue = 15; var completed = 0; task.Then(v => v.ToString()).Then(v => { Assert.AreEqual(taskdValue.ToString(), v); completed++; }); task.Resolve(taskdValue); Assert.AreEqual(1, completed); } [Test] public void rejection_of_source_task_rejects_transformed_task() { var task = new Task<int>(); var ex = new Exception(); var errors = 0; task.Then(v => v.ToString()).Catch(e => { Assert.AreEqual(ex, e); errors++; }); task.Reject(ex); Assert.AreEqual(1, errors); } [Test] public void exception_thrown_during_transform_rejects_transformed_task() { var task = new Task<int>(); var taskdValue = 15; var errors = 0; var ex = new Exception(); task.Then(v => { throw ex; }).Catch(e => { Assert.AreEqual(ex, e); errors++; }); task.Resolve(taskdValue); Assert.AreEqual(1, errors); } [Test] public void can_chain_task_and_convert_type_of_value() { var task = new Task<int>(); var chainedTask = new Task<string>(); var taskdValue = 15; var chainedTaskValue = "blah"; var completed = 0; task.Then<string>(v => chainedTask).Then(v => { Assert.AreEqual(chainedTaskValue, v); completed++; }); task.Resolve(taskdValue); chainedTask.Resolve(chainedTaskValue); Assert.AreEqual(1, completed); } [Test] public void can_chain_task_and_convert_to_non_value_task() { var task = new Task<int>(); var chainedTask = new Task(); var taskdValue = 15; var completed = 0; task.Then(v => (ITask) chainedTask).Then(() => { ++completed; }); task.Resolve(taskdValue); chainedTask.Resolve(); Assert.AreEqual(1, completed); } [Test] public void exception_thrown_in_chain_rejects_resulting_task() { var task = new Task<int>(); var ex = new Exception(); var errors = 0; task.Then(v => { throw ex; }).Catch(e => { Assert.AreEqual(ex, e); errors++; }); task.Resolve(15); Assert.AreEqual(1, errors); } [Test] public void rejection_of_source_task_rejects_chained_task() { var task = new Task<int>(); var chainedTask = new Task<string>(); var ex = new Exception(); var errors = 0; task.Then<string>(v => chainedTask).Catch(e => { Assert.AreEqual(ex, e); errors++; }); task.Reject(ex); Assert.AreEqual(1, errors); } [Test] public void race_is_resolved_when_first_task_is_resolved_first() { var task1 = new Task<int>(); var task2 = new Task<int>(); var resolved = 0; Task.Any(task1, task2).Then(i => resolved = i); task1.Resolve(5); Assert.AreEqual(5, resolved); } [Test] public void race_is_resolved_when_second_task_is_resolved_first() { var task1 = new Task<int>(); var task2 = new Task<int>(); var resolved = 0; Task.Any(task1, task2).Then(i => resolved = i); task2.Resolve(12); Assert.AreEqual(12, resolved); } [Test] public void race_is_rejected_when_first_task_is_rejected_first() { var task1 = new Task<int>(); var task2 = new Task<int>(); Exception ex = null; Task.Any(task1, task2).Catch(e => ex = e); var expected = new Exception(); task1.Reject(expected); Assert.AreEqual(expected, ex); } [Test] public void race_is_rejected_when_second_task_is_rejected_first() { var task1 = new Task<int>(); var task2 = new Task<int>(); Exception ex = null; Task.Any(task1, task2).Catch(e => ex = e); var expected = new Exception(); task2.Reject(expected); Assert.AreEqual(expected, ex); } [Test] public void can_resolve_task_via_resolver_function() { var task = new Task<int>((resolve, reject) => { resolve(5); }); var completed = 0; task.Then(v => { Assert.AreEqual(5, v); ++completed; }); Assert.AreEqual(1, completed); } [Test] public void can_reject_task_via_reject_function() { var ex = new Exception(); var task = new Task<int>((resolve, reject) => { reject(ex); }); var completed = 0; task.Catch(e => { Assert.AreEqual(ex, e); ++completed; }); Assert.AreEqual(1, completed); } [Test] public void exception_thrown_during_resolver_rejects_task() { var ex = new Exception(); var task = new Task<int>((resolve, reject) => { throw ex; }); var completed = 0; task.Catch(e => { Assert.AreEqual(ex, e); ++completed; }); Assert.AreEqual(1, completed); } [Test] public void unhandled_exception_is_propagated_via_event() { var task = new Task<int>(); var ex = new Exception(); var eventRaised = 0; EventHandler<UnhandledExceptionEventArgs> handler = (s, e) => { Assert.AreEqual(ex, e.ExceptionObject); eventRaised++; }; Task.UnhandledException += handler; try { task.Then(a => { throw ex; }).Done(); task.Resolve(5); Assert.AreEqual(1, eventRaised); } finally { Task.UnhandledException -= handler; } } [Test] public void exception_in_done_callback_is_propagated_via_event() { var task = new Task<int>(); var ex = new Exception(); var eventRaised = 0; EventHandler<UnhandledExceptionEventArgs> handler = (s, e) => { Assert.AreEqual(ex, e.ExceptionObject); eventRaised++; }; Task.UnhandledException += handler; try { task.Then(x => { throw ex; }).Done(); task.Resolve(5); Assert.AreEqual(1, eventRaised); } finally { Task.UnhandledException -= handler; } } [Test] public void handled_exception_is_not_propagated_via_event() { var task = new Task<int>(); var ex = new Exception(); var eventRaised = 0; EventHandler<UnhandledExceptionEventArgs> handler = (s, e) => ++eventRaised; Task.UnhandledException += handler; try { task.Then(a => { throw ex; }).Catch(_ => { // Catch the error. }).Done(); task.Resolve(5); Assert.AreEqual(1, eventRaised); } finally { Task.UnhandledException -= handler; } } [Test] public void can_handle_Done_onResolved() { var task = new Task<int>(); var callback = 0; var expectedValue = 5; task.Then(value => { Assert.AreEqual(expectedValue, value); callback++; }).Done(); task.Resolve(expectedValue); Assert.AreEqual(1, callback); } [Test] public void can_handle_Done_onResolved_with_onReject() { var task = new Task<int>(); var callback = 0; var errorCallback = 0; var expectedValue = 5; task.Then(value => { Assert.AreEqual(expectedValue, value); callback++; }).Catch(ex => { ++errorCallback; }).Done(); task.Resolve(expectedValue); Assert.AreEqual(1, callback); Assert.AreEqual(0, errorCallback); } /*todo: * Also want a test that exception thrown during Then triggers the error handler. * How do Javascript tasks work in this regard? [Test] public void exception_during_Done_onResolved_triggers_error_hander() { var task = new Task<int>(); var callback = 0; var errorCallback = 0; var expectedValue = 5; var expectedException = new Exception(); task.Done( value => { Assert.AreEqual(expectedValue, value); ++callback; throw expectedException; }, ex => { Assert.AreEqual(expectedException, ex); ++errorCallback; } ); task.Resolve(expectedValue); Assert.AreEqual(1, callback); Assert.AreEqual(1, errorCallback); } * */ [Test] public void exception_during_Then_onResolved_triggers_error_hander() { var task = new Task<int>(); var callback = 0; var errorCallback = 0; var expectedException = new Exception(); task.Then(value => { throw expectedException; }).Then(() => ++callback).Catch(ex => { Assert.AreEqual(expectedException, ex); errorCallback++; }).Done(); task.Resolve(6); Assert.AreEqual(0, callback); Assert.AreEqual(1, errorCallback); } } }
// *********************************************************************** // Copyright (c) 2007 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; #if CLR_2_0 || CLR_4_0 using System.Collections.Generic; #else using System.Collections; #endif using System.Reflection; using NUnit.Framework.Api; using NUnit.Framework.Internal.Commands; using NUnit.Framework.Internal.WorkItems; namespace NUnit.Framework.Internal { /// <summary> /// TestSuite represents a composite test, which contains other tests. /// </summary> public class TestSuite : Test { #region Fields /// <summary> /// Our collection of child tests /// </summary> #if CLR_2_0 || CLR_4_0 private List<ITest> tests = new List<ITest>(); #else private ArrayList tests = new ArrayList(); #endif /// <summary> /// Set to true to suppress sorting this suite's contents /// </summary> protected bool maintainTestOrder; /// <summary> /// Argument list for use in creating the fixture. /// </summary> internal object[] arguments; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="TestSuite"/> class. /// </summary> /// <param name="name">The name of the suite.</param> public TestSuite( string name ) : base( name ) { } /// <summary> /// Initializes a new instance of the <see cref="TestSuite"/> class. /// </summary> /// <param name="parentSuiteName">Name of the parent suite.</param> /// <param name="name">The name of the suite.</param> public TestSuite( string parentSuiteName, string name ) : base( parentSuiteName, name ) { } /// <summary> /// Initializes a new instance of the <see cref="TestSuite"/> class. /// </summary> /// <param name="fixtureType">Type of the fixture.</param> public TestSuite(Type fixtureType) : this(fixtureType, null) { } /// <summary> /// Initializes a new instance of the <see cref="TestSuite"/> class. /// </summary> /// <param name="fixtureType">Type of the fixture.</param> /// <param name="arguments">The arguments.</param> public TestSuite(Type fixtureType, object[] arguments) : base(fixtureType) { string name = TypeHelper.GetDisplayName(fixtureType, arguments); this.Name = name; this.FullName = name; string nspace = fixtureType.Namespace; if (nspace != null && nspace != "") this.FullName = nspace + "." + name; this.arguments = arguments; } #endregion #region Public Methods /// <summary> /// Sorts tests under this suite. /// </summary> public void Sort() { if (!maintainTestOrder) { this.tests.Sort(); foreach (Test test in Tests) { TestSuite suite = test as TestSuite; if (suite != null) suite.Sort(); } } } #if false /// <summary> /// Sorts tests under this suite using the specified comparer. /// </summary> /// <param name="comparer">The comparer.</param> public void Sort(IComparer comparer) { this.tests.Sort(comparer); foreach( Test test in Tests ) { TestSuite suite = test as TestSuite; if ( suite != null ) suite.Sort(comparer); } } #endif /// <summary> /// Adds a test to the suite. /// </summary> /// <param name="test">The test.</param> public void Add( Test test ) { // if( test.RunState == RunState.Runnable ) // { // test.RunState = this.RunState; // test.IgnoreReason = this.IgnoreReason; // } test.Parent = this; tests.Add(test); } #if !NUNITLITE /// <summary> /// Adds a pre-constructed test fixture to the suite. /// </summary> /// <param name="fixture">The fixture.</param> public void Add( object fixture ) { Test test = TestFixtureBuilder.BuildFrom( fixture ); if ( test != null ) Add( test ); } #endif /// <summary> /// Gets the command to be executed before any of /// the child tests are run. /// </summary> /// <returns>A TestCommand</returns> public virtual TestCommand GetOneTimeSetUpCommand() { if (RunState != RunState.Runnable && RunState != RunState.Explicit) return new SkipCommand(this); TestCommand command = new OneTimeSetUpCommand(this); if (this.FixtureType != null) { IApplyToContext[] changes = (IApplyToContext[])this.FixtureType.GetCustomAttributes(typeof(IApplyToContext), true); if (changes.Length > 0) command = new ApplyChangesToContextCommand(command, changes); } return command; } /// <summary> /// Gets the command to be executed after all of the /// child tests are run. /// </summary> /// <returns>A TestCommand</returns> public virtual TestCommand GetOneTimeTearDownCommand() { TestCommand command = new OneTimeTearDownCommand(this); return command; } #endregion #region Properties /// <summary> /// Gets this test's child tests /// </summary> /// <value>The list of child tests</value> #if CLR_2_0 || CLR_4_0 public override IList<ITest> Tests #else public override IList Tests #endif { get { return tests; } } /// <summary> /// Gets a count of test cases represented by /// or contained under this test. /// </summary> /// <value></value> public override int TestCaseCount { get { int count = 0; foreach(Test test in Tests) { count += test.TestCaseCount; } return count; } } #endregion #region Test Overrides /// <summary> /// Overridden to return a TestSuiteResult. /// </summary> /// <returns>A TestResult for this test.</returns> public override TestResult MakeTestResult() { return new TestSuiteResult(this); } /// <summary> /// Creates a WorkItem for executing this test. /// </summary> /// <param name="childFilter">A filter to be used in selecting child tests</param> /// <returns>A new WorkItem</returns> public override WorkItem CreateWorkItem(ITestFilter childFilter) { //return RunState == Api.RunState.Runnable || RunState == Api.RunState.Explicit // ? (WorkItem)new CompositeWorkItem(this, childFilter) // : (WorkItem)new SimpleWorkItem(this); return new CompositeWorkItem(this, childFilter); } /// <summary> /// Gets a bool indicating whether the current test /// has any descendant tests. /// </summary> public override bool HasChildren { get { return tests.Count > 0; } } /// <summary> /// Gets the name used for the top-level element in the /// XML representation of this test /// </summary> public override string XmlElementName { get { return "test-suite"; } } /// <summary> /// Returns an XmlNode representing the current result after /// adding it as a child of the supplied parent node. /// </summary> /// <param name="parentNode">The parent node.</param> /// <param name="recursive">If true, descendant results are included</param> /// <returns></returns> public override XmlNode AddToXml(XmlNode parentNode, bool recursive) { XmlNode thisNode = parentNode.AddElement("test-suite"); thisNode.AddAttribute("type", this.TestType); PopulateTestNode(thisNode, recursive); thisNode.AddAttribute("testcasecount", this.TestCaseCount.ToString()); if (recursive) foreach (Test test in this.Tests) test.AddToXml(thisNode, recursive); return thisNode; } #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.IO; using System.Globalization; using System.Runtime.ExceptionServices; using System.Threading.Tasks; namespace System.Net { internal class StreamFramer { private Stream _transport; private bool _eof; private FrameHeader _writeHeader = new FrameHeader(); private FrameHeader _curReadHeader = new FrameHeader(); private FrameHeader _readVerifier = new FrameHeader( FrameHeader.IgnoreValue, FrameHeader.IgnoreValue, FrameHeader.IgnoreValue); private byte[] _readHeaderBuffer; private byte[] _writeHeaderBuffer; private readonly AsyncCallback _readFrameCallback; private readonly AsyncCallback _beginWriteCallback; public StreamFramer(Stream Transport) { if (Transport == null || Transport == Stream.Null) { throw new ArgumentNullException(nameof(Transport)); } _transport = Transport; _readHeaderBuffer = new byte[_curReadHeader.Size]; _writeHeaderBuffer = new byte[_writeHeader.Size]; _readFrameCallback = new AsyncCallback(ReadFrameCallback); _beginWriteCallback = new AsyncCallback(BeginWriteCallback); } public FrameHeader ReadHeader { get { return _curReadHeader; } } public FrameHeader WriteHeader { get { return _writeHeader; } } public Stream Transport { get { return _transport; } } public byte[] ReadMessage() { if (_eof) { return null; } int offset = 0; byte[] buffer = _readHeaderBuffer; int bytesRead; while (offset < buffer.Length) { bytesRead = Transport.Read(buffer, offset, buffer.Length - offset); if (bytesRead == 0) { if (offset == 0) { // m_Eof, return null _eof = true; return null; } else { throw new IOException(SR.Format(SR.net_io_readfailure, SR.net_io_connectionclosed)); } } offset += bytesRead; } _curReadHeader.CopyFrom(buffer, 0, _readVerifier); if (_curReadHeader.PayloadSize > _curReadHeader.MaxMessageSize) { throw new InvalidOperationException(SR.Format(SR.net_frame_size, _curReadHeader.MaxMessageSize.ToString(NumberFormatInfo.InvariantInfo), _curReadHeader.PayloadSize.ToString(NumberFormatInfo.InvariantInfo))); } buffer = new byte[_curReadHeader.PayloadSize]; offset = 0; while (offset < buffer.Length) { bytesRead = Transport.Read(buffer, offset, buffer.Length - offset); if (bytesRead == 0) { throw new IOException(SR.Format(SR.net_io_readfailure, SR.net_io_connectionclosed)); } offset += bytesRead; } return buffer; } public IAsyncResult BeginReadMessage(AsyncCallback asyncCallback, object stateObject) { WorkerAsyncResult workerResult; if (_eof) { workerResult = new WorkerAsyncResult(this, stateObject, asyncCallback, null, 0, 0); workerResult.InvokeCallback(-1); return workerResult; } workerResult = new WorkerAsyncResult(this, stateObject, asyncCallback, _readHeaderBuffer, 0, _readHeaderBuffer.Length); IAsyncResult result = TaskToApm.Begin(_transport.ReadAsync(_readHeaderBuffer, 0, _readHeaderBuffer.Length), _readFrameCallback, workerResult); if (result.CompletedSynchronously) { ReadFrameComplete(result); } return workerResult; } private void ReadFrameCallback(IAsyncResult transportResult) { if (!(transportResult.AsyncState is WorkerAsyncResult)) { NetEventSource.Fail(this, $"The state expected to be WorkerAsyncResult, received {transportResult}."); } if (transportResult.CompletedSynchronously) { return; } WorkerAsyncResult workerResult = (WorkerAsyncResult)transportResult.AsyncState; try { ReadFrameComplete(transportResult); } catch (Exception e) { if (e is OutOfMemoryException) { throw; } if (!(e is IOException)) { e = new System.IO.IOException(SR.Format(SR.net_io_readfailure, e.Message), e); } workerResult.InvokeCallback(e); } } // IO COMPLETION CALLBACK // // This callback is responsible for getting the complete protocol frame. // 1. it reads the header. // 2. it determines the frame size. // 3. loops while not all frame received or an error. // private void ReadFrameComplete(IAsyncResult transportResult) { do { if (!(transportResult.AsyncState is WorkerAsyncResult)) { NetEventSource.Fail(this, $"The state expected to be WorkerAsyncResult, received {transportResult}."); } WorkerAsyncResult workerResult = (WorkerAsyncResult)transportResult.AsyncState; int bytesRead = TaskToApm.End<int>(transportResult); workerResult.Offset += bytesRead; if (!(workerResult.Offset <= workerResult.End)) { NetEventSource.Fail(this, $"WRONG: offset - end = {workerResult.Offset - workerResult.End}"); } if (bytesRead <= 0) { // (by design) This indicates the stream has receives EOF // If we are in the middle of a Frame - fail, otherwise - produce EOF object result = null; if (!workerResult.HeaderDone && workerResult.Offset == 0) { result = (object)-1; } else { result = new System.IO.IOException(SR.net_frame_read_io); } workerResult.InvokeCallback(result); return; } if (workerResult.Offset >= workerResult.End) { if (!workerResult.HeaderDone) { workerResult.HeaderDone = true; // This indicates the header has been read successfully _curReadHeader.CopyFrom(workerResult.Buffer, 0, _readVerifier); int payloadSize = _curReadHeader.PayloadSize; if (payloadSize < 0) { // Let's call user callback and he call us back and we will throw workerResult.InvokeCallback(new System.IO.IOException(SR.net_frame_read_size)); } if (payloadSize == 0) { // report empty frame (NOT eof!) to the caller, he might be interested in workerResult.InvokeCallback(0); return; } if (payloadSize > _curReadHeader.MaxMessageSize) { throw new InvalidOperationException(SR.Format(SR.net_frame_size, _curReadHeader.MaxMessageSize.ToString(NumberFormatInfo.InvariantInfo), payloadSize.ToString(NumberFormatInfo.InvariantInfo))); } // Start reading the remaining frame data (note header does not count). byte[] frame = new byte[payloadSize]; // Save the ref of the data block workerResult.Buffer = frame; workerResult.End = frame.Length; workerResult.Offset = 0; // Transport.ReadAsync below will pickup those changes. } else { workerResult.HeaderDone = false; // Reset for optional object reuse. workerResult.InvokeCallback(workerResult.End); return; } } // This means we need more data to complete the data block. transportResult = TaskToApm.Begin(_transport.ReadAsync(workerResult.Buffer, workerResult.Offset, workerResult.End - workerResult.Offset), _readFrameCallback, workerResult); } while (transportResult.CompletedSynchronously); } // // User code will call this when workerResult gets signaled. // // On BeginRead, the user always gets back our WorkerAsyncResult. // The Result property represents either a number of bytes read or an // exception put by our async state machine. // public byte[] EndReadMessage(IAsyncResult asyncResult) { if (asyncResult == null) { throw new ArgumentNullException(nameof(asyncResult)); } WorkerAsyncResult workerResult = asyncResult as WorkerAsyncResult; if (workerResult == null) { throw new ArgumentException(SR.Format(SR.net_io_async_result, typeof(WorkerAsyncResult).FullName), nameof(asyncResult)); } if (!workerResult.InternalPeekCompleted) { workerResult.InternalWaitForCompletion(); } if (workerResult.Result is Exception e) { ExceptionDispatchInfo.Throw(e); } int size = (int)workerResult.Result; if (size == -1) { _eof = true; return null; } else if (size == 0) { // Empty frame. return Array.Empty<byte>(); } return workerResult.Buffer; } public void WriteMessage(byte[] message) { if (message == null) { throw new ArgumentNullException(nameof(message)); } _writeHeader.PayloadSize = message.Length; _writeHeader.CopyTo(_writeHeaderBuffer, 0); Transport.Write(_writeHeaderBuffer, 0, _writeHeaderBuffer.Length); if (message.Length == 0) { return; } Transport.Write(message, 0, message.Length); } public IAsyncResult BeginWriteMessage(byte[] message, AsyncCallback asyncCallback, object stateObject) { if (message == null) { throw new ArgumentNullException(nameof(message)); } _writeHeader.PayloadSize = message.Length; _writeHeader.CopyTo(_writeHeaderBuffer, 0); if (message.Length == 0) { return TaskToApm.Begin(_transport.WriteAsync(_writeHeaderBuffer, 0, _writeHeaderBuffer.Length), asyncCallback, stateObject); } // Will need two async writes. Prepare the second: WorkerAsyncResult workerResult = new WorkerAsyncResult(this, stateObject, asyncCallback, message, 0, message.Length); // Charge the first: IAsyncResult result = TaskToApm.Begin(_transport.WriteAsync(_writeHeaderBuffer, 0, _writeHeaderBuffer.Length), _beginWriteCallback, workerResult); if (result.CompletedSynchronously) { BeginWriteComplete(result); } return workerResult; } private void BeginWriteCallback(IAsyncResult transportResult) { if (!(transportResult.AsyncState is WorkerAsyncResult)) { NetEventSource.Fail(this, $"The state expected to be WorkerAsyncResult, received {transportResult}."); } if (transportResult.CompletedSynchronously) { return; } var workerResult = (WorkerAsyncResult)transportResult.AsyncState; try { BeginWriteComplete(transportResult); } catch (Exception e) { if (e is OutOfMemoryException) { throw; } workerResult.InvokeCallback(e); } } // IO COMPLETION CALLBACK // // Called when user IO request was wrapped to do several underlined IO. // private void BeginWriteComplete(IAsyncResult transportResult) { do { WorkerAsyncResult workerResult = (WorkerAsyncResult)transportResult.AsyncState; // First, complete the previous portion write. TaskToApm.End(transportResult); // Check on exit criterion. if (workerResult.Offset == workerResult.End) { workerResult.InvokeCallback(); return; } // Setup exit criterion. workerResult.Offset = workerResult.End; // Write next portion (frame body) using Async IO. transportResult = TaskToApm.Begin(_transport.WriteAsync(workerResult.Buffer, 0, workerResult.End), _beginWriteCallback, workerResult); } while (transportResult.CompletedSynchronously); } public void EndWriteMessage(IAsyncResult asyncResult) { if (asyncResult == null) { throw new ArgumentNullException(nameof(asyncResult)); } WorkerAsyncResult workerResult = asyncResult as WorkerAsyncResult; if (workerResult != null) { if (!workerResult.InternalPeekCompleted) { workerResult.InternalWaitForCompletion(); } if (workerResult.Result is Exception e) { ExceptionDispatchInfo.Throw(e); } } else { TaskToApm.End(asyncResult); } } } // // This class wraps an Async IO request. It is based on our internal LazyAsyncResult helper. // - If ParentResult is not null then the base class (LazyAsyncResult) methods must not be used. // - If ParentResult == null, then real user IO request is wrapped. // internal class WorkerAsyncResult : LazyAsyncResult { public byte[] Buffer; public int Offset; public int End; public bool HeaderDone; // This might be reworked so we read both header and frame in one chunk. public WorkerAsyncResult(object asyncObject, object asyncState, AsyncCallback savedAsyncCallback, byte[] buffer, int offset, int end) : base(asyncObject, asyncState, savedAsyncCallback) { Buffer = buffer; Offset = offset; End = end; } } // Describes the header used in framing of the stream data. internal class FrameHeader { public const int IgnoreValue = -1; public const int HandshakeDoneId = 20; public const int HandshakeErrId = 21; public const int HandshakeId = 22; public const int DefaultMajorV = 1; public const int DefaultMinorV = 0; private int _MessageId; private int _MajorV; private int _MinorV; private int _PayloadSize; public FrameHeader() { _MessageId = HandshakeId; _MajorV = DefaultMajorV; _MinorV = DefaultMinorV; _PayloadSize = -1; } public FrameHeader(int messageId, int majorV, int minorV) { _MessageId = messageId; _MajorV = majorV; _MinorV = minorV; _PayloadSize = -1; } public int Size { get { return 5; } } public int MaxMessageSize { get { return 0xFFFF; } } public int MessageId { get { return _MessageId; } set { _MessageId = value; } } public int MajorV { get { return _MajorV; } } public int MinorV { get { return _MinorV; } } public int PayloadSize { get { return _PayloadSize; } set { if (value > MaxMessageSize) { throw new ArgumentException(SR.Format(SR.net_frame_max_size, MaxMessageSize.ToString(NumberFormatInfo.InvariantInfo), value.ToString(NumberFormatInfo.InvariantInfo)), "PayloadSize"); } _PayloadSize = value; } } public void CopyTo(byte[] dest, int start) { dest[start++] = (byte)_MessageId; dest[start++] = (byte)_MajorV; dest[start++] = (byte)_MinorV; dest[start++] = (byte)((_PayloadSize >> 8) & 0xFF); dest[start] = (byte)(_PayloadSize & 0xFF); } public void CopyFrom(byte[] bytes, int start, FrameHeader verifier) { _MessageId = bytes[start++]; _MajorV = bytes[start++]; _MinorV = bytes[start++]; _PayloadSize = (int)((bytes[start++] << 8) | bytes[start]); if (verifier.MessageId != FrameHeader.IgnoreValue && MessageId != verifier.MessageId) { throw new InvalidOperationException(SR.Format(SR.net_io_header_id, "MessageId", MessageId, verifier.MessageId)); } if (verifier.MajorV != FrameHeader.IgnoreValue && MajorV != verifier.MajorV) { throw new InvalidOperationException(SR.Format(SR.net_io_header_id, "MajorV", MajorV, verifier.MajorV)); } if (verifier.MinorV != FrameHeader.IgnoreValue && MinorV != verifier.MinorV) { throw new InvalidOperationException(SR.Format(SR.net_io_header_id, "MinorV", MinorV, verifier.MinorV)); } } } }
using System; using System.Collections.Generic; using UnityEditor; using System.IO; using UnityEngine.AssetBundles.GraphTool; namespace UnityEngine.AssetBundles.GraphTool.DataModel.Version2 { public class Settings { /* if true, ignore .meta files inside AssetBundleGraph. */ public const bool IGNORE_META = true; public const string GUI_TEXT_MENU_OPEN = "Window/AssetBundleGraph/Open Graph Editor"; public const string GUI_TEXT_MENU_BATCHWINDOW_OPEN = "Window/AssetBundleGraph/Open Batch Build Window"; public const string GUI_TEXT_MENU_PROJECTWINDOW_OPEN = "Window/AssetBundleGraph/Open Project Window"; public const string GUI_TEXT_MENU_BUILD = "Window/AssetBundleGraph/Build Bundles for Current Platform"; public const string GUI_TEXT_MENU_BATCHBUILD = "Window/AssetBundleGraph/Build Current Graph Selections"; public const string GUI_TEXT_MENU_GENERATE = "Window/AssetBundleGraph/Create Node Script"; public const string GUI_TEXT_MENU_GENERATE_MODIFIER = GUI_TEXT_MENU_GENERATE + "/Modifier Script"; public const string GUI_TEXT_MENU_GENERATE_PREFABBUILDER = GUI_TEXT_MENU_GENERATE + "/PrefabBuilder Script"; public const string GUI_TEXT_MENU_GENERATE_ASSETGENERATOR = GUI_TEXT_MENU_GENERATE + "/AssetGenerator Script"; public const string GUI_TEXT_MENU_GENERATE_CUITOOL = "Window/AssetBundleGraph/Create CUI Tool"; public const string GUI_TEXT_MENU_GENERATE_POSTPROCESS = GUI_TEXT_MENU_GENERATE + "/Postprocess Script"; public const string GUI_TEXT_MENU_GENERATE_FILTER = GUI_TEXT_MENU_GENERATE + "/Filter Script"; public const string GUI_TEXT_MENU_GENERATE_NODE = GUI_TEXT_MENU_GENERATE + "/Custom Node Script"; public const string GUI_TEXT_MENU_DELETE_CACHE = "Window/AssetBundleGraph/Clear Build Cache"; public const string GUI_TEXT_MENU_DELETE_IMPORTSETTING_SETTINGS = "Window/AssetBundleGraph/Clear Saved ImportSettings"; public const string GRAPH_SEARCH_CONDITION = "t:UnityEngine.AssetBundles.GraphTool.DataModel.Version2.ConfigGraph"; public const string GUI_TEXT_SETTINGTEMPLATE_MODEL = "Model"; public const string GUI_TEXT_SETTINGTEMPLATE_AUDIO = "Audio"; public const string GUI_TEXT_SETTINGTEMPLATE_TEXTURE= "Texture"; public const string GUI_TEXT_SETTINGTEMPLATE_VIDEO = "Video"; public const string UNITY_METAFILE_EXTENSION = ".meta"; public const string DOTSTART_HIDDEN_FILE_HEADSTRING = "."; public const string MANIFEST_FOOTER = ".manifest"; public const char UNITY_FOLDER_SEPARATOR = '/';// Mac/Windows/Linux can use '/' in Unity. public const string BASE64_IDENTIFIER = "B64|"; public const char KEYWORD_WILDCARD = '*'; public class UserSettings { private static readonly string PREFKEY_AB_BUILD_CACHE_DIR = "AssetBundles.GraphTool.Cache.AssetBundle"; private static readonly string PREFKEY_BATCHBUILD_LASTSELECTEDCOLLECTION = "AssetBundles.GraphTool.LastSelectedCollection"; private static readonly string PREFKEY_BATCHBUILD__USECOLLECTIONSTATE = "AssetBundles.GraphTool.UseCollection"; public static string AssetBundleBuildCacheDir { get { var cacheDir = EditorUserSettings.GetConfigValue (PREFKEY_AB_BUILD_CACHE_DIR); if (string.IsNullOrEmpty (cacheDir)) { return Path.CachePath + "AssetBundles/"; } return cacheDir; } set { if (!value.EndsWith ("/")) { value = value + "/"; } EditorUserSettings.SetConfigValue (PREFKEY_AB_BUILD_CACHE_DIR, value); } } public static string BatchBuildLastSelectedCollection { get { return EditorUserSettings.GetConfigValue (PREFKEY_BATCHBUILD_LASTSELECTEDCOLLECTION); } set { EditorUserSettings.SetConfigValue (PREFKEY_BATCHBUILD_LASTSELECTEDCOLLECTION, value); } } public static bool BatchBuildUseCollectionState { get { return EditorUserSettings.GetConfigValue (PREFKEY_BATCHBUILD__USECOLLECTIONSTATE) == "True"; } set { EditorUserSettings.SetConfigValue (PREFKEY_BATCHBUILD__USECOLLECTIONSTATE, value.ToString()); } } } public class Path { private static string s_basePath; public static string BasePath { get { //if (string.IsNullOrEmpty (s_basePath)) { var obj = ScriptableObject.CreateInstance<ConfigGraph> (); MonoScript s = MonoScript.FromScriptableObject (obj); var configGuiPath = AssetDatabase.GetAssetPath( s ); UnityEngine.Object.DestroyImmediate (obj); var fileInfo = new FileInfo(configGuiPath); var baseDir = fileInfo.Directory.Parent.Parent.Parent.Parent; Assertions.Assert.AreEqual ("UnityEngine.AssetBundleGraph", baseDir.Name); string baseDirPath = baseDir.ToString ().Replace( '\\', '/'); int index = baseDirPath.LastIndexOf (ASSETS_PATH); Assertions.Assert.IsTrue ( index >= 0 ); s_basePath = baseDirPath.Substring (index); //} return s_basePath; } } public const string ASSETS_PATH = "Assets/"; public static string ScriptTemplatePath { get { return BasePath + "/Editor/ScriptTemplate/"; } } public static string UserSpacePath { get { return BasePath + "/Generated/Editor/"; } } public static string CUISpacePath { get { return BasePath + "/Generated/CUI/"; } } public static string ImporterSettingsPath { get { return BasePath + "/SavedSettings/ImportSettings/"; } } public static string CachePath { get { return BasePath + "/Cache/"; } } public static string PrefabBuilderCachePath { get { return CachePath + "Prefabs/"; } } public static string AssetGeneratorCachePath { get { return CachePath + "GeneratedAssets/"; } } public static string BundleBuilderCachePath { get { return UserSettings.AssetBundleBuildCacheDir; } } public static string SettingFilePath { get { return BasePath + "/SettingFiles/"; } } public static string DatabasePath { get { return SettingFilePath + "AssetReferenceDB.asset"; } } public static string BuildMapPath { get { return SettingFilePath + "AssetBundleBuildMap.asset"; } } public static string BatchBuildConfigPath { get { return SettingFilePath + "BatchBuildConfig.asset"; } } public static string SettingTemplatePath { get { return BasePath + "/Editor/SettingTemplate/"; } } public static string SettingTemplateModel { get { return SettingTemplatePath + "setting.fbx"; } } public static string SettingTemplateAudio { get { return SettingTemplatePath + "setting.wav"; } } public static string SettingTemplateTexture { get { return SettingTemplatePath + "setting.png"; } } public static string SettingTemplateVideo { get { return SettingTemplatePath + "setting.m4v"; } } public static string GUIResourceBasePath { get { return BasePath + "/Editor/GUI/GraphicResources/"; } } } public struct BuildAssetBundleOption { public readonly BuildAssetBundleOptions option; public readonly string description; public BuildAssetBundleOption(string desc, BuildAssetBundleOptions opt) { option = opt; description = desc; } } public struct BuildPlayerOption { public readonly BuildOptions option; public readonly string description; public BuildPlayerOption(string desc, BuildOptions opt) { option = opt; description = desc; } } public static List<BuildAssetBundleOption> BundleOptionSettings = new List<BuildAssetBundleOption> { new BuildAssetBundleOption("Uncompressed AssetBundle", BuildAssetBundleOptions.UncompressedAssetBundle), new BuildAssetBundleOption("Disable Write TypeTree", BuildAssetBundleOptions.DisableWriteTypeTree), new BuildAssetBundleOption("Deterministic AssetBundle", BuildAssetBundleOptions.DeterministicAssetBundle), new BuildAssetBundleOption("Force Rebuild AssetBundle", BuildAssetBundleOptions.ForceRebuildAssetBundle), new BuildAssetBundleOption("Ignore TypeTree Changes", BuildAssetBundleOptions.IgnoreTypeTreeChanges), new BuildAssetBundleOption("Append Hash To AssetBundle Name", BuildAssetBundleOptions.AppendHashToAssetBundleName), new BuildAssetBundleOption("ChunkBased Compression", BuildAssetBundleOptions.ChunkBasedCompression), new BuildAssetBundleOption("Strict Mode", BuildAssetBundleOptions.StrictMode) #if !UNITY_5_5_OR_NEWER , // UnityEditor.BuildAssetBundleOptions does no longer have OmitClassVersions available new BuildAssetBundleOption("Omit Class Versions", BuildAssetBundleOptions.OmitClassVersions) #endif }; public static List<BuildPlayerOption> BuildPlayerOptionsSettings = new List<BuildPlayerOption> { new BuildPlayerOption("Accept External Modification To Player", BuildOptions.AcceptExternalModificationsToPlayer), new BuildPlayerOption("Allow Debugging", BuildOptions.AllowDebugging), new BuildPlayerOption("Auto Run Player", BuildOptions.AutoRunPlayer), new BuildPlayerOption("Build Additional Streamed Scenes", BuildOptions.BuildAdditionalStreamedScenes), new BuildPlayerOption("Build Scripts Only", BuildOptions.BuildScriptsOnly), #if UNITY_5_6_OR_NEWER new BuildPlayerOption("Compress With LZ4", BuildOptions.CompressWithLz4), #endif new BuildPlayerOption("Compute CRC", BuildOptions.ComputeCRC), new BuildPlayerOption("Connect To Host", BuildOptions.ConnectToHost), new BuildPlayerOption("Connect With Profiler", BuildOptions.ConnectWithProfiler), new BuildPlayerOption("Development Build", BuildOptions.Development), new BuildPlayerOption("Enable Headless Mode", BuildOptions.EnableHeadlessMode), new BuildPlayerOption("Force Enable Assertions", BuildOptions.ForceEnableAssertions), #if !UNITY_2017_1_OR_NEWER new BuildPlayerOption("Force Optimize Script Compilation", BuildOptions.ForceOptimizeScriptCompilation), #endif new BuildPlayerOption("Use IL2CPP", BuildOptions.Il2CPP), new BuildPlayerOption("Install In Build Folder", BuildOptions.InstallInBuildFolder), new BuildPlayerOption("Show Built Player", BuildOptions.ShowBuiltPlayer), new BuildPlayerOption("Strict Mode", BuildOptions.StrictMode), new BuildPlayerOption("Symlink Libraries", BuildOptions.SymlinkLibraries), new BuildPlayerOption("Uncompressed AssetBundle", BuildOptions.UncompressedAssetBundle) }; public const float WINDOW_SPAN = 20f; public const string GROUPING_KEYWORD_DEFAULT = "/Group_*/"; public const string BUNDLECONFIG_BUNDLENAME_TEMPLATE_DEFAULT = "bundle_*"; // by default, AssetBundleGraph's node has only 1 InputPoint. and // this is only one definition of it's label. public const string DEFAULT_INPUTPOINT_LABEL = "-"; public const string DEFAULT_OUTPUTPOINT_LABEL = "+"; public const string BUNDLECONFIG_BUNDLE_OUTPUTPOINT_LABEL = "bundles"; public const string BUNDLECONFIG_VARIANTNAME_DEFAULT = ""; public const string DEFAULT_FILTER_KEYWORD = ""; public const string DEFAULT_FILTER_KEYTYPE = "Any"; public const string FILTER_KEYWORD_WILDCARD = "*"; public const string NODE_INPUTPOINT_FIXED_LABEL = "FIXED_INPUTPOINT_ID"; public class GUI { public const float NODE_BASE_WIDTH = 120f; public const float NODE_BASE_HEIGHT = 40f; public const float NODE_WIDTH_MARGIN = 48f; public const float NODE_TITLE_HEIGHT_MARGIN = 8f; public const float CONNECTION_ARROW_WIDTH = 12f; public const float CONNECTION_ARROW_HEIGHT = 15f; public const float INPUT_POINT_WIDTH = 21f; public const float INPUT_POINT_HEIGHT = 29f; public const float OUTPUT_POINT_WIDTH = 10f; public const float OUTPUT_POINT_HEIGHT = 23f; public const float FILTER_OUTPUT_SPAN = 32f; public const float CONNECTION_POINT_MARK_SIZE = 16f; public const float CONNECTION_CURVE_LENGTH = 20f; public const float TOOLBAR_HEIGHT = 20f; public const float TOOLBAR_GRAPHNAMEMENU_WIDTH = 150f; public const int TOOLBAR_GRAPHNAMEMENU_CHAR_LENGTH = 20; public static readonly Color COLOR_ENABLED = new Color(0.43f, 0.65f, 1.0f, 1.0f); public static readonly Color COLOR_CONNECTED = new Color(0.9f, 0.9f, 0.9f, 1.0f); public static readonly Color COLOR_NOT_CONNECTED = Color.grey; public static readonly Color COLOR_CAN_CONNECT = Color.white;//new Color(0.60f, 0.60f, 1.0f, 1.0f); public static readonly Color COLOR_CAN_NOT_CONNECT = new Color(0.33f, 0.33f, 0.33f, 1.0f); public static string Skin { get { return Path.GUIResourceBasePath + "NodeStyle.guiskin"; } } public static string ConnectionPoint { get { return Path.GUIResourceBasePath + "ConnectionPoint.png"; } } public static string InputBG { get { return Path.GUIResourceBasePath + "InputBG.png"; } } public static string OutputBG { get { return Path.GUIResourceBasePath + "OutputBG.png"; } } } } }
// // Copyright (c) 2012-2021 Antmicro // // This file is licensed under the MIT License. // Full license text is available in the LICENSE file. using System; using System.IO; using System.Runtime.Serialization; using System.Linq; using System.Collections.Generic; using System.Collections; using Antmicro.Migrant.Hooks; using Antmicro.Migrant.Utilities; using Antmicro.Migrant.Generators; using Antmicro.Migrant.VersionTolerance; using Antmicro.Migrant.Customization; namespace Antmicro.Migrant { internal class ObjectReader { public ObjectReader(Stream stream, Serializer.ReadMethods readMethods, SwapList objectsForSurrogates = null, Action<object> postDeserializationCallback = null, bool treatCollectionAsUserObject = false, VersionToleranceLevel versionToleranceLevel = 0, bool useBuffering = true, bool disableStamping = false, ReferencePreservation referencePreservation = ReferencePreservation.Preserve, bool forceStampVerification = false) { this.readMethods = readMethods; this.postDeserializationCallback = postDeserializationCallback; this.treatCollectionAsUserObject = treatCollectionAsUserObject; this.referencePreservation = referencePreservation; this.objectsForSurrogates = objectsForSurrogates ?? new SwapList(); VersionToleranceLevel = versionToleranceLevel; types = new List<TypeDescriptor>(); Methods = new IdentifiedElementsList<MethodDescriptor>(this); Assemblies = new IdentifiedElementsList<AssemblyDescriptor>(this); Modules = new IdentifiedElementsList<ModuleDescriptor>(this); latePostDeserializationHooks = new List<Action>(); reader = new PrimitiveReader(stream, useBuffering); surrogatesWhileReading = new OneToOneMap<int, object>(); readTypeMethod = disableStamping ? (Func<TypeDescriptor>)ReadSimpleTypeDescriptor : ReadFullTypeDescriptor; ForceStampVerification = forceStampVerification; } public void ReuseWithNewStream(Stream stream) { deserializedObjects.Clear(); types.Clear(); Methods.Clear(); Assemblies.Clear(); Modules.Clear(); reader = new PrimitiveReader(stream, reader.IsBuffered); } public T ReadObject<T>() { if(soFarDeserialized != null) { deserializedObjects = new AutoResizingList<object>(soFarDeserialized.Length); for(var i = 0; i < soFarDeserialized.Length; i++) { deserializedObjects[i] = soFarDeserialized[i].Target; } } if(deserializedObjects == null) { deserializedObjects = new AutoResizingList<object>(InitialCapacity); } objectsWrittenInlineCount = 0; var before = deserializedObjects.Count; var theRefId = ReadAndTouchReference(); if(theRefId == before) { var after = deserializedObjects.Count; if(before < after - objectsWrittenInlineCount) { int prevRefId; int refId = -1; do { prevRefId = refId; refId = reader.ReadInt32(); var type = GetObjectByReferenceId(refId).GetType(); readMethods.readMethodsProvider.GetOrCreate(type)(this, type, refId); // this is to compensate objects written inline that has been already counted objectsWrittenInlineCount -= (refId - prevRefId - 1); } while(deserializedObjects.Count - before - refId - objectsWrittenInlineCount > 1); } } var obj = deserializedObjects[theRefId]; try { for(var i = deserializedObjects.Count - 1; i >= 0; i--) { Completed(i); } if(!(obj is T)) { throw new InvalidDataException( string.Format("Type {0} requested to be deserialized, however type {1} encountered in the stream.", typeof(T), obj.GetType())); } PrepareForNextRead(); foreach(var hook in latePostDeserializationHooks) { hook(); } } finally { latePostDeserializationHooks.Clear(); } return (T)obj; } public void Flush() { reader.Dispose(); } private void PrepareForNextRead() { if(referencePreservation == ReferencePreservation.UseWeakReference) { soFarDeserialized = new WeakReference[deserializedObjects.Count]; for(var i = 0; i < soFarDeserialized.Length; i++) { soFarDeserialized[i] = new WeakReference(deserializedObjects[i]); } } if(referencePreservation != ReferencePreservation.Preserve) { deserializedObjects = null; } } internal static bool HasSpecialReadMethod(Type type) { return type == typeof(string) || typeof(ISpeciallySerializable).IsAssignableFrom(type) || Helpers.IsTransient(type); } /// <summary> /// Reads the object using reflection. /// /// REMARK: this method is not thread-safe /// </summary> /// <param name="objectReader">Object reader</param> /// <param name="actualType">Type of object to deserialize</param> /// <param name="objectId">Identifier of object to deserialize</param> internal static void ReadObjectInnerUsingReflection(ObjectReader objectReader, Type actualType, int objectId) { objectReader.TryTouchObject(actualType, objectId); switch(GetCreationWay(actualType, objectReader.treatCollectionAsUserObject)) { case CreationWay.Null: objectReader.ReadNotPrecreated(actualType, objectId); break; case CreationWay.DefaultCtor: objectReader.UpdateElements(actualType, objectId); break; case CreationWay.Uninitialized: objectReader.UpdateFields(actualType, objectReader.GetObjectByReferenceId(objectId)); break; } } private void UpdateFields(Type actualType, object target) { var fieldOrTypeInfos = ((TypeFullDescriptor)actualType).FieldsToDeserialize; foreach(var fieldOrTypeInfo in fieldOrTypeInfos) { if(fieldOrTypeInfo.Field == null) { ReadField(fieldOrTypeInfo.TypeToOmit); continue; } var field = fieldOrTypeInfo.Field; if(field.IsDefined(typeof(TransientAttribute), false)) { if(field.IsDefined(typeof(ConstructorAttribute), false)) { var ctorAttribute = (ConstructorAttribute)field.GetCustomAttributes(false).First(x => x is ConstructorAttribute); field.SetValue(target, Activator.CreateInstance(field.FieldType, ctorAttribute.Parameters)); } continue; } var value = ReadField(field.FieldType); field.SetValue(target, value); } } internal void Completed(int refId) { var currentObject = GetObjectByReferenceId(refId); if(currentObject == null) { // this may happen with empty delegates return; } var type = currentObject.GetType(); readMethods.completeMethodsProvider.GetOrCreate(type)(this, refId); } internal void CompletedInnerUsingReflection(int refId) { var obj = GetObjectByReferenceId(refId); var factoryId = objectsForSurrogates.FindMatchingIndex(obj.GetType()); // (1) call post-deserialization hooks on it Helpers.InvokeAttribute(typeof(PostDeserializationAttribute), obj); var postHook = Helpers.GetDelegateWithAttribute(typeof(LatePostDeserializationAttribute), obj); if(postHook != null) { if(factoryId != -1) { throw new InvalidOperationException(string.Format(LateHookAndSurrogateError, obj.GetType())); } latePostDeserializationHooks.Add(postHook); } if(postDeserializationCallback != null) { postDeserializationCallback(obj); } // (2) de-surrogate it if needed & clone the content if(factoryId != -1) { var desurrogated = objectsForSurrogates.GetByIndex(factoryId).DynamicInvoke(new[] { obj }); // clone value of de-surrogated objects to final objects CloneContentUsingReflection(desurrogated, deserializedObjects[refId]); obj = deserializedObjects[refId]; surrogatesWhileReading.Remove(refId); } } internal static void CloneContentUsingReflection(object source, object destination) { var sourceType = source.GetType(); var destinationType = destination.GetType(); if(sourceType != destinationType) { throw new ArgumentException("Source and destination types mismatched."); } foreach(var field in source.GetType().GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)) { var srcValue = field.GetValue(source); field.SetValue(destination, srcValue == source ? destination : srcValue); } } private void ReadNotPrecreated(Type type, int objectId) { if(type.IsValueType) { // a boxed value type SetObjectByReferenceId(objectId, ReadField(type)); } else if(typeof(MulticastDelegate).IsAssignableFrom(type)) { ReadDelegate(type, objectId); } else if(type.IsArray) { ReadArray(type.GetElementType(), objectId); } else { throw new InvalidOperationException(InternalErrorMessage); } } private void UpdateElements(Type type, int objectId) { var obj = GetObjectByReferenceId(objectId); var speciallyDeserializable = obj as ISpeciallySerializable; if(speciallyDeserializable != null) { LoadAndVerifySpeciallySerializableAndVerify(speciallyDeserializable, reader); return; } CollectionMetaToken token; if(!CollectionMetaToken.TryGetCollectionMetaToken(type, out token)) { throw new InvalidOperationException(InternalErrorMessage); } // so we can assume it is ICollection<T> or ICollection FillCollection(token.FormalElementType, objectId); } internal object GetObjectByReferenceId(int refId, bool forceDeserializedObject = false) { object obj; if(!forceDeserializedObject && surrogatesWhileReading.TryGetValue(refId, out obj)) { return obj; } return deserializedObjects[refId]; } internal void SetObjectByReferenceId(int refId, object obj) { if(surrogatesWhileReading.ContainsKey(refId)) { surrogatesWhileReading[refId] = obj; } else { deserializedObjects[refId] = obj; } } internal int ReadAndTouchReference() { var refId = reader.ReadInt32(); if(refId == Consts.NullObjectId) { // there was an explicit 'null' stored in stream return Consts.NullObjectId; } if(refId >= deserializedObjects.Count) { var type = ReadType(); var isSurrogated = reader.ReadBoolean(); if(isSurrogated) { var objectTypeAfterDesurrogation = ReadType(); // using formatter service here is enough, as the whole content of an object will be cloned later deserializedObjects[refId] = FormatterServices.GetUninitializedObject(objectTypeAfterDesurrogation.UnderlyingType); var surrogate = readMethods.createObjectMethodsProvider.GetOrCreate(type.UnderlyingType)(); surrogatesWhileReading.Add(refId, surrogate); } readMethods.touchInlinedObjectMethodsProvider.GetOrCreate(type.UnderlyingType)(this, refId); } return refId; } internal void TryTouchInlinedObjectUsingReflection(Type type, int refId) { if(!TryTouchObject(type, refId)) { if(!TryRecreateObjectUsingAdditionalMetadata(type, refId)) { ReadNotPrecreated(type, refId); objectsWrittenInlineCount++; } } } private object ReadField(Type formalType) { if(Helpers.IsTransient(formalType)) { return Helpers.GetDefaultValue(formalType); } if(!formalType.IsValueType) { var refId = ReadAndTouchReference(); if(refId == Consts.NullObjectId) { // there was an explicit 'null' stored in stream return null; } return GetObjectByReferenceId(refId, true); } if(formalType.IsEnum) { var value = ReadField(Enum.GetUnderlyingType(formalType)); return Enum.ToObject(formalType, value); } var nullableActualType = Nullable.GetUnderlyingType(formalType); if(nullableActualType != null) { var isNotNull = reader.ReadBoolean(); return isNotNull ? ReadField(nullableActualType) : null; } if(Helpers.IsWriteableByPrimitiveWriter(formalType)) { var methodName = string.Concat("Read", formalType.Name); var readMethod = typeof(PrimitiveReader).GetMethod(methodName); return readMethod.Invoke(reader, Type.EmptyTypes); } var returnedObject = Activator.CreateInstance(formalType); // here we have a boxed struct which we put to struct reference list UpdateFields(formalType, returnedObject); // if this is subtype return returnedObject; } private bool TryRecreateObjectUsingAdditionalMetadata(Type type, int objectId) { if(type.IsArray) { ReadMetadataAndTouchArray(type.GetElementType(), objectId); return true; } if(type == typeof(string)) { var result = reader.ReadString(); SetObjectByReferenceId(objectId, result); objectsWrittenInlineCount++; return true; } return false; } private void FillCollection(Type elementFormalType, int objectId) { var obj = GetObjectByReferenceId(objectId); var collectionType = obj.GetType(); var count = reader.ReadInt32(); if(collectionType == typeof(Stack) || (collectionType.IsGenericType && collectionType.GetGenericTypeDefinition() == typeof(Stack<>))) { var stack = (dynamic)obj; var temp = new dynamic[count]; for(int i = 0; i < count; i++) { temp[i] = ReadField(elementFormalType); } for(int i = count - 1; i >= 0; --i) { stack.Push(temp[i]); } } else { var addMethod = collectionType.GetMethod("Add", new[] { elementFormalType }) ?? collectionType.GetMethod("Enqueue", new[] { elementFormalType }) ?? collectionType.GetMethod("Push", new[] { elementFormalType }); if(addMethod == null) { throw new InvalidOperationException(string.Format(CouldNotFindAddErrorMessage, collectionType)); } Type delegateType; if(addMethod.ReturnType == typeof(void)) { delegateType = typeof(Action<>).MakeGenericType(new[] { elementFormalType }); } else { delegateType = typeof(Func<,>).MakeGenericType(new[] { elementFormalType, addMethod.ReturnType }); } var addDelegate = Delegate.CreateDelegate(delegateType, obj, addMethod); for(var i = 0; i < count; i++) { var value = ReadField(elementFormalType); addDelegate.DynamicInvoke(value); } } } private void ReadMetadataAndTouchArray(Type elementFormalType, int objectId) { var rank = reader.ReadInt32(); var lengths = new int[rank]; for(var i = 0; i < rank; i++) { lengths[i] = reader.ReadInt32(); } var array = Array.CreateInstance(elementFormalType, lengths); // we should update the array object as soon as we can // why? because it can have the reference to itself (what a corner case!) SetObjectByReferenceId(objectId, array); } private void ReadArray(Type elementFormalType, int objectId) { var array = (Array)GetObjectByReferenceId(objectId); var position = new int[array.Rank]; FillArrayRowRecursive(array, 0, position, elementFormalType); } private void ReadDelegate(Type type, int objectId) { var invocationListLength = reader.ReadInt32(); if(invocationListLength == 0) { return; } Delegate result = null; for(var i = 0; i < invocationListLength; i++) { var target = ReadField(typeof(object)); var method = Methods.Read(); var del = Delegate.CreateDelegate(type, target, method.UnderlyingMethod); result = Delegate.Combine(result, del); } SetObjectByReferenceId(objectId, result); } private void FillArrayRowRecursive(Array array, int currentDimension, int[] position, Type elementFormalType) { var length = array.GetLength(currentDimension); for(var i = 0; i < length; i++) { if(currentDimension == array.Rank - 1) { var value = ReadField(elementFormalType); array.SetValue(value, position); } else { FillArrayRowRecursive(array, currentDimension + 1, position, elementFormalType); } position[currentDimension]++; for(var j = currentDimension + 1; j < array.Rank; j++) { position[j] = 0; } } } internal static void LoadAndVerifySpeciallySerializableAndVerify(ISpeciallySerializable obj, PrimitiveReader reader) { var beforePosition = reader.Position; obj.Load(reader); var afterPosition = reader.Position; var serializedLength = reader.ReadInt64(); if(serializedLength + beforePosition != afterPosition) { throw new InvalidOperationException(string.Format( "Stream corruption by '{0}', incorrent magic {1} when {2} expected.", obj.GetType(), serializedLength, afterPosition - beforePosition)); } } internal TypeDescriptor ReadType() { return readTypeMethod(); } private TypeSimpleDescriptor ReadSimpleTypeDescriptor() { TypeSimpleDescriptor type; var typeId = reader.ReadInt32(); if(typeId == Consts.NullObjectId) { return null; } if(types.Count > typeId) { type = (TypeSimpleDescriptor)types[typeId]; } else { type = new TypeSimpleDescriptor(); types.Add(type); type.Read(this); } return type; } private TypeFullDescriptor ReadFullTypeDescriptor() { TypeFullDescriptor type; var typeIdOrPosition = reader.ReadInt32(); if(typeIdOrPosition == Consts.NullObjectId) { return null; } var isGenericParameter = reader.ReadBoolean(); if(isGenericParameter) { var genericType = ReadFullTypeDescriptor().UnderlyingType; type = (TypeFullDescriptor)genericType.GetGenericArguments()[typeIdOrPosition]; } else { if(types.Count > typeIdOrPosition) { type = (TypeFullDescriptor)types[typeIdOrPosition]; } else { type = new TypeFullDescriptor(); types.Add(type); type.Read(this); } } if(type.UnderlyingType.IsGenericType) { var containsAnyFixedGenericArguments = reader.ReadBoolean(); if(containsAnyFixedGenericArguments) { var args = new Type[type.UnderlyingType.GetGenericArguments().Count()]; for(int i = 0; i < args.Length; i++) { args[i] = ReadFullTypeDescriptor().UnderlyingType; } type = (TypeFullDescriptor)type.UnderlyingType.MakeGenericType(args); } } if(Helpers.ContainsGenericArguments(type.UnderlyingType)) { var ranks = reader.ReadArray(); if(ranks.Length > 0) { var arrayDescriptor = new ArrayDescriptor(type.UnderlyingType, ranks); type = (TypeFullDescriptor)arrayDescriptor.BuildArrayType(); } } return type; } private bool TryTouchObject(Type actualType, int refId) { if(refId < deserializedObjects.Count) { return true; } var created = CreateObjectUsingReflection(actualType, treatCollectionAsUserObject); if(created != null) { SetObjectByReferenceId(refId, created); } return created != null; } internal static object CreateObjectUsingReflection(Type type, bool treatCollectionAsUserObject) { object result = null; switch(GetCreationWay(type, treatCollectionAsUserObject)) { case CreationWay.Null: break; case CreationWay.DefaultCtor: result = Activator.CreateInstance(type, true); break; case CreationWay.Uninitialized: result = FormatterServices.GetUninitializedObject(type); break; } return result; } internal static CreationWay GetCreationWay(Type actualType, bool treatCollectionAsUserObject) { if(Helpers.CanBeCreatedWithDataOnly(actualType)) { return CreationWay.Null; } if(!treatCollectionAsUserObject && CollectionMetaToken.IsCollection(actualType)) { return CreationWay.DefaultCtor; } if(typeof(ISpeciallySerializable).IsAssignableFrom(actualType)) { return CreationWay.DefaultCtor; } return CreationWay.Uninitialized; } internal bool TreatCollectionAsUserObject { get { return treatCollectionAsUserObject; } } internal PrimitiveReader PrimitiveReader { get { return reader; } } internal IdentifiedElementsList<ModuleDescriptor> Modules { get; private set; } internal IdentifiedElementsList<AssemblyDescriptor> Assemblies { get; private set; } internal IdentifiedElementsList<MethodDescriptor> Methods { get; private set; } internal VersionToleranceLevel VersionToleranceLevel { get; private set; } internal bool ForceStampVerification { get; private set; } internal const string LateHookAndSurrogateError = "Type {0}: late post deserialization callback cannot be used in conjunction with surrogates."; internal readonly Action<object> postDeserializationCallback; internal readonly List<Action> latePostDeserializationHooks; internal readonly SwapList objectsForSurrogates; internal AutoResizingList<object> deserializedObjects; internal readonly OneToOneMap<int, object> surrogatesWhileReading; internal readonly Serializer.ReadMethods readMethods; internal int objectsWrittenInlineCount; private readonly Func<TypeDescriptor> readTypeMethod; private List<TypeDescriptor> types; private WeakReference[] soFarDeserialized; private readonly bool treatCollectionAsUserObject; private ReferencePreservation referencePreservation; private PrimitiveReader reader; private const int InitialCapacity = 128; private const string InternalErrorMessage = "Internal error: should not reach here."; private const string CouldNotFindAddErrorMessage = "Could not find suitable Add method for the type {0}."; internal enum CreationWay { Uninitialized, DefaultCtor, Null } } internal delegate void ReadMethodDelegate(ObjectReader reader, Type type, int objectId); internal delegate void CompleteMethodDelegate(ObjectReader reader, int objectId); internal delegate void TouchInlinedObjectMethodDelegate(ObjectReader reader, int objectId); internal delegate object CreateObjectMethodDelegate(); internal delegate void CloneMethodDelegate(object src, object dst); }
/* * The MIT License (MIT) * * Copyright (c) 2014 Itay Sagui * * 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.IO; using System.Net.Http; using DropboxRestAPI.Utils; namespace DropboxRestAPI.RequestsGenerators.Core { public class MetadataRequestGenerator : IMetadataRequestGenerator { public IRequest Files(string root, string path, string rev = null, string asTeamMember = null) { var request = new Request { BaseAddress = Consts.ApiContentBaseUrl, Resource = Consts.Version + "/files/" + root + path.EncodePathParts(), Method = HttpMethod.Head }; request.AddHeader(Consts.AsTeamMemberHeader, asTeamMember); if (!string.IsNullOrEmpty(rev)) request.AddParameter("rev", rev); return request; } public IRequest FilesRange(string root, string path, long @from, long to, string etag, string rev = null, string asTeamMember = null) { var request = new Request { BaseAddress = Consts.ApiContentBaseUrl, Resource = Consts.Version + "/files/" + root + path.EncodePathParts(), Method = HttpMethod.Get }; request.AddHeader(Consts.AsTeamMemberHeader, asTeamMember); if (to < 0) to = 0; request.AddHeader("Range", string.Format("bytes={0}-{1}", from, to)); request.AddHeader("ETag", etag); if (!string.IsNullOrEmpty(rev)) request.AddParameter("rev", rev); return request; } public IRequest FilesPut(string root, Stream content, string path, string locale = null, bool overwrite = true, string parent_rev = null, bool autorename = true, string asTeamMember = null) { var request = new Request { BaseAddress = Consts.ApiContentBaseUrl, Resource = Consts.Version + "/files_put/" + root + path.EncodePathParts(), Method = HttpMethod.Put }; request.AddHeader(Consts.AsTeamMemberHeader, asTeamMember); request.AddHeader("locale", locale); request.AddParameter("parent_rev", parent_rev); if (!overwrite) request.AddParameter("overwrite", false.ToString()); if (!autorename) request.AddParameter("autorename", false.ToString()); var httpContent = new StreamContent(content); request.Content = httpContent; return request; } public IRequest Metadata(string root, string path, int file_limit = 10000, string hash = null, bool list = true, bool include_deleted = false, string rev = null, string locale = null, bool include_media_info = false, bool include_membership = false, string asTeamMember = null) { var request = new Request { Method = HttpMethod.Get, BaseAddress = Consts.ApiBaseUrl, Resource = Consts.Version + "/metadata/" + root + path.EncodePathParts() }; request.AddHeader(Consts.AsTeamMemberHeader, asTeamMember); request.AddParameter("hash", hash); request.AddParameter("rev", rev); request.AddParameter("locale", locale); if (file_limit != 10000) request.AddParameter("file_limit", file_limit.ToString()); if (list != true) request.AddParameter("list", false.ToString()); if (include_deleted) request.AddParameter("include_deleted", true.ToString()); if (include_media_info) request.AddParameter("include_media_info", true.ToString()); if (include_membership) request.AddParameter("include_membership", true.ToString()); return request; } public IRequest Delta(string cursor = null, string locale = null, string path_prefix = null, bool include_media_info = false, string asTeamMember = null) { var request = new Request { BaseAddress = Consts.ApiBaseUrl, Resource = Consts.Version + "/delta", Method = HttpMethod.Post }; request.AddHeader(Consts.AsTeamMemberHeader, asTeamMember); request.AddParameter("cursor", cursor); request.AddHeader("locale", locale); request.AddParameter("path_prefix", path_prefix); if (include_media_info) request.AddParameter("include_media_info", true.ToString()); return request; } public IRequest DeltaLatestCursor(string path_prefix = null, bool include_media_info = false, string asTeamMember = null) { var request = new Request { BaseAddress = Consts.ApiBaseUrl, Resource = Consts.Version + "/delta/latest_cursor", Method = HttpMethod.Post }; request.AddHeader(Consts.AsTeamMemberHeader, asTeamMember); request.AddParameter("path_prefix", path_prefix); if (include_media_info) request.AddParameter("include_media_info", true.ToString()); return request; } public IRequest LongPollDelta(string cursor = null, int timeout = 30, string asTeamMember = null) { var request = new Request { BaseAddress = Consts.ApiNotifyBaseUrl, Resource = Consts.Version + "/longpoll_delta", Method = HttpMethod.Get }; request.AddHeader(Consts.AsTeamMemberHeader, asTeamMember); request.AddParameter("cursor", cursor); if (timeout != 30) request.AddParameter("timeout", timeout.ToString()); return request; } public IRequest Revisions(string root, string path, int rev_limit = 10, string locale = null, string asTeamMember = null) { var request = new Request { BaseAddress = Consts.ApiBaseUrl, Resource = Consts.Version + "/revisions/" + root + path.EncodePathParts(), Method = HttpMethod.Get }; request.AddHeader(Consts.AsTeamMemberHeader, asTeamMember); request.AddParameter("locale", locale); if (rev_limit != 10) request.AddParameter("rev_limit", rev_limit.ToString()); return request; } public IRequest Restore(string root, string path, string rev = null, string locale = null, string asTeamMember = null) { var request = new Request { BaseAddress = Consts.ApiBaseUrl, Resource = Consts.Version + "/restore/" + root + path.EncodePathParts(), Method = HttpMethod.Post }; request.AddHeader(Consts.AsTeamMemberHeader, asTeamMember); request.AddParameter("rev", rev); request.AddParameter("locale", locale); return request; } public IRequest Search(string root, string path, string query, int file_limit = 1000, bool include_deleted = false, string locale = null, bool include_membership = false, string asTeamMember = null) { var request = new Request { BaseAddress = Consts.ApiBaseUrl, Resource = Consts.Version + "/search/" + root + path.EncodePathParts(), Method = HttpMethod.Get }; request.AddHeader(Consts.AsTeamMemberHeader, asTeamMember); request.AddParameter("query", query); request.AddParameter("locale", locale); if (include_deleted) request.AddParameter("include_deleted", true.ToString()); if (include_membership) request.AddParameter("include_membership", true.ToString()); if (file_limit != 1000) request.AddParameter("file_limit", file_limit.ToString()); return request; } public IRequest Shares(string root, string path, string locale = null, bool short_url = true, string asTeamMember = null) { var request = new Request { BaseAddress = Consts.ApiBaseUrl, Resource = Consts.Version + "/shares/" + root + path.EncodePathParts(), Method = HttpMethod.Post }; request.AddHeader(Consts.AsTeamMemberHeader, asTeamMember); request.AddParameter("locale", locale); if (!short_url) request.AddParameter("short_url", false.ToString()); return request; } public IRequest Media(string root, string path, string locale = null, string asTeamMember = null) { var request = new Request { BaseAddress = Consts.ApiBaseUrl, Resource = Consts.Version + "/media/" + root + path.EncodePathParts(), Method = HttpMethod.Post }; request.AddHeader(Consts.AsTeamMemberHeader, asTeamMember); request.AddParameter("locale", locale); return request; } public IRequest CopyRef(string root, string path, string asTeamMember = null) { var request = new Request { BaseAddress = Consts.ApiBaseUrl, Resource = Consts.Version + "/copy_ref/" + root + path.EncodePathParts(), Method = HttpMethod.Get }; request.AddHeader(Consts.AsTeamMemberHeader, asTeamMember); return request; } public IRequest Thumbnails(string root, string path, string format = "jpeg", string size = "s", string asTeamMember = null) { var request = new Request { BaseAddress = Consts.ApiContentBaseUrl, Resource = Consts.Version + "/thumbnails/" + root + path.EncodePathParts(), Method = HttpMethod.Get }; request.AddHeader(Consts.AsTeamMemberHeader, asTeamMember); request.AddParameter("format", format); request.AddParameter("size", size); return request; } public IRequest Previews(string root, string path, string rev = null, string asTeamMember = null) { var request = new Request { BaseAddress = Consts.ApiContentBaseUrl, Resource = Consts.Version + "/previews/" + root + path.EncodePathParts(), Method = HttpMethod.Get }; request.AddHeader(Consts.AsTeamMemberHeader, asTeamMember); request.AddParameter("rev", rev); return request; } public IRequest ChunkedUpload(byte[] content, int count, string uploadId = null, long? offset = null, string asTeamMember = null) { var request = new Request { BaseAddress = Consts.ApiContentBaseUrl, Resource = Consts.Version + "/chunked_upload/", Method = HttpMethod.Put }; request.AddHeader(Consts.AsTeamMemberHeader, asTeamMember); request.AddParameter("upload_id", uploadId); if (offset != null) request.AddParameter("offset", offset.ToString()); HttpContent httpContent = new ByteArrayContent(content, 0, count); request.Content = httpContent; return request; } public IRequest CommitChunkedUpload(string root, string path, string uploadId, string locale = null, bool overwrite = true, string parent_rev = null, bool autorename = true, string asTeamMember = null) { var request = new Request { BaseAddress = Consts.ApiContentBaseUrl, Resource = Consts.Version + "/commit_chunked_upload/" + root + path.EncodePathParts(), Method = HttpMethod.Post }; request.AddHeader(Consts.AsTeamMemberHeader, asTeamMember); request.AddParameter("upload_id", uploadId); request.AddParameter("locale", locale); request.AddParameter("overwrite", overwrite.ToString()); request.AddParameter("parent_rev", parent_rev); if (!autorename) request.AddParameter("autorename", false.ToString()); return request; } public IRequest SharedFolders(string id = null, string asTeamMember = null) { var request = new Request { BaseAddress = Consts.ApiBaseUrl, Resource = Consts.Version + "/shared_folders/" + id, Method = HttpMethod.Get }; request.AddHeader(Consts.AsTeamMemberHeader, asTeamMember); return request; } public IRequest SaveUrl(string root, string path, string url) { var request = new Request { BaseAddress = Consts.ApiBaseUrl, Resource = Consts.Version + "/save_url/" + root + path.EncodePathParts(), Method = HttpMethod.Post }; request.AddParameter("url", url); return request; } public IRequest SaveUrlJob(string jobId) { var request = new Request { BaseAddress = Consts.ApiBaseUrl, Resource = Consts.Version + "/save_url_job/" + jobId, Method = HttpMethod.Get }; return request; } } }
// Copyright (c) 2013 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.Drawing; using System.IO; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using NUnit.Framework; using SharpYaml.Events; using SharpYaml.Serialization; using SharpYaml.Serialization.Serializers; namespace SharpYaml.Tests.Serialization { public class SerializationTests : YamlTest { [Test] public void Roundtrip() { var settings = new SerializerSettings(); settings.RegisterAssembly(typeof(SerializationTests).Assembly); var serializer = new Serializer(settings); var buffer = new StringWriter(); var original = new X(); serializer.Serialize(buffer, original); Dump.WriteLine(buffer); var bufferText = buffer.ToString(); var copy = serializer.Deserialize<X>(bufferText); foreach (var property in typeof(X).GetProperties(BindingFlags.Public | BindingFlags.Instance)) { if (property.CanRead && property.CanWrite) { Assert.AreEqual( property.GetValue(original, null), property.GetValue(copy, null)); } } } [Test] public void RoundtripWithDefaults() { var settings = new SerializerSettings() {EmitDefaultValues = true}; settings.RegisterAssembly(typeof(SerializationTests).Assembly); var serializer = new Serializer(settings); var buffer = new StringWriter(); var original = new X(); serializer.Serialize(buffer, original); Dump.WriteLine(buffer); var bufferText = buffer.ToString(); var copy = serializer.Deserialize<X>(bufferText); foreach (var property in typeof(X).GetProperties(BindingFlags.Public | BindingFlags.Instance)) { if (property.CanRead && property.CanWrite) { Assert.AreEqual( property.GetValue(original, null), property.GetValue(copy, null)); } } } [Test] public void CircularReference() { var serializer = new Serializer(); var buffer = new StringWriter(); var original = new Y(); original.Child = new Y { Child = original, Child2 = original }; serializer.Serialize(buffer, original, typeof(Y)); Dump.WriteLine(buffer); } private class Y { public Y Child { get; set; } public Y Child2 { get; set; } } [Test] public void DeserializeScalar() { var sut = new Serializer(); var result = sut.Deserialize(YamlFile("test2.yaml"), typeof(object)); Assert.AreEqual("a scalar", result); } [Test] public void DeserializeExplicitType() { var settings = new SerializerSettings(); settings.RegisterAssembly(typeof(SerializationTests).Assembly); var serializer = new Serializer(); object result = serializer.Deserialize(YamlFile("explicitType.yaml"), typeof(object)); Assert.True(typeof(Z).IsAssignableFrom(result.GetType())); Assert.AreEqual("bbb", ((Z)result).aaa); } [Test] public void DeserializeDictionary() { var serializer = new Serializer(); var result = serializer.Deserialize(YamlFile("dictionary.yaml")); Assert.True(typeof(IDictionary<object, object>).IsAssignableFrom(result.GetType()), "The deserialized object has the wrong type."); var dictionary = (IDictionary<object, object>)result; Assert.AreEqual("value1", dictionary["key1"]); Assert.AreEqual("value2", dictionary["key2"]); } [Test] public void DeserializeExplicitDictionary() { var serializer = new Serializer(); object result = serializer.Deserialize(YamlFile("dictionaryExplicit.yaml")); Assert.True(typeof(IDictionary<string, int>).IsAssignableFrom(result.GetType()), "The deserialized object has the wrong type."); var dictionary = (IDictionary<string, int>)result; Assert.AreEqual(1, dictionary["key1"]); Assert.AreEqual(2, dictionary["key2"]); } [Test] public void DeserializeListOfDictionaries() { var serializer = new Serializer(); var result = serializer.Deserialize(YamlFile("listOfDictionaries.yaml"), typeof(List<Dictionary<string, string>>)); Assert.IsInstanceOf<List<Dictionary<string, string>>>(result); var list = (List<Dictionary<string, string>>)result; Assert.AreEqual("conn1", list[0]["connection"]); Assert.AreEqual("path1", list[0]["path"]); Assert.AreEqual("conn2", list[1]["connection"]); Assert.AreEqual("path2", list[1]["path"]); } [Test] public void DeserializeList() { var serializer = new Serializer(); var result = serializer.Deserialize(YamlFile("list.yaml")); Assert.True(typeof(IList).IsAssignableFrom(result.GetType())); var list = (IList)result; Assert.AreEqual("one", list[0]); Assert.AreEqual("two", list[1]); Assert.AreEqual("three", list[2]); } [Test] public void DeserializeExplicitList() { var serializer = new Serializer(); var result = serializer.Deserialize(YamlFile("listExplicit.yaml")); Assert.True(typeof(IList<int>).IsAssignableFrom(result.GetType())); var list = (IList<int>)result; Assert.AreEqual(3, list[0]); Assert.AreEqual(4, list[1]); Assert.AreEqual(5, list[2]); } [Test] public void DeserializeEnumerable() { var settings = new SerializerSettings(); settings.RegisterAssembly(typeof(SerializationTests).Assembly); var serializer = new Serializer(settings); var buffer = new StringWriter(); var z = new[] { new Z { aaa = "Yo" }}; serializer.Serialize(buffer, z); var bufferAsText = buffer.ToString(); var result = (IEnumerable<Z>)serializer.Deserialize(bufferAsText, typeof(IEnumerable<Z>)); Assert.AreEqual(1, result.Count()); Assert.AreEqual("Yo", result.First().aaa); } [Test] public void RoundtripList() { var serializer = new Serializer(); var buffer = new StringWriter(); var original = new List<int> { 2, 4, 6 }; serializer.Serialize(buffer, original, typeof(List<int>)); Dump.WriteLine(buffer); var copy = (List<int>) serializer.Deserialize(new StringReader(buffer.ToString()), typeof(List<int>)); Assert.AreEqual(original.Count, copy.Count); for (int i = 0; i < original.Count; ++i) { Assert.AreEqual(original[i], copy[i]); } } [Test] public void DeserializeArray() { var serializer = new Serializer(); var result = serializer.Deserialize(YamlFile("list.yaml"), typeof(String[])); Assert.True(result is String[]); var array = (String[])result; Assert.AreEqual("one", array[0]); Assert.AreEqual("two", array[1]); Assert.AreEqual("three", array[2]); } [Test] public void Enums() { var settings = new SerializerSettings(); settings.RegisterAssembly(typeof(StringFormatFlags).Assembly); var serializer = new Serializer(settings); var flags = StringFormatFlags.NoClip | StringFormatFlags.NoFontFallback; var buffer = new StringWriter(); serializer.Serialize(buffer, flags); var bufferAsText = buffer.ToString(); var deserialized = (StringFormatFlags)serializer.Deserialize(bufferAsText, typeof(StringFormatFlags)); Assert.AreEqual(flags, deserialized); } [Test] public void CustomTags() { var settings = new SerializerSettings(); settings.RegisterTagMapping("tag:yaml.org,2002:point", typeof(Point)); var serializer = new Serializer(settings); var result = serializer.Deserialize(YamlFile("tags.yaml")); Assert.AreEqual(typeof(Point), result.GetType()); var value = (Point)result; Assert.AreEqual(10, value.X); Assert.AreEqual(20, value.Y); } // Convertible are not supported //[Test] //public void DeserializeConvertible() //{ // var settings = new SerializerSettings(); // settings.RegisterAssembly(typeof(SerializationTests).Assembly); // settings.RegisterSerializerFactory(new TypeConverterSerializerFactory()); // var serializer = new Serializer(settings); // var result = serializer.Deserialize(YamlFile("convertible.yaml"), typeof(Z)); // Assert.True(typeof(Z).IsAssignableFrom(result.GetType())); // Assert.AreEqual("[hello, world]", ((Z)result).aaa); //} [Test] public void RoundtripWithTypeConverter() { var buffer = new StringWriter(); var x = new SomeCustomType("Yo"); var settings = new SerializerSettings(); settings.RegisterSerializerFactory(new CustomTypeConverter()); var serializer = new Serializer(settings); serializer.Serialize(buffer, x); Dump.WriteLine(buffer); var bufferText = buffer.ToString(); var copy = serializer.Deserialize<SomeCustomType>(bufferText); Assert.AreEqual("Yo", copy.Value); } class SomeCustomType { // Test specifically with no parameterless, supposed to fail unless a type converter is specified public SomeCustomType(string value) { Value = value; } public string Value; } public class CustomTypeConverter : ScalarSerializerBase, IYamlSerializableFactory { public IYamlSerializable TryCreate(SerializerContext context, ITypeDescriptor typeDescriptor) { return typeDescriptor.Type == typeof (SomeCustomType) ? this : null; } public override object ConvertFrom(ref ObjectContext context, Scalar fromScalar) { return new SomeCustomType(fromScalar.Value); } public override string ConvertTo(ref ObjectContext objectContext) { return ((SomeCustomType) objectContext.Instance).Value; } } [Test] public void RoundtripDictionary() { var entries = new Dictionary<string, string> { { "key1", "value1" }, { "key2", "value2" }, { "key3", "value3" }, }; var buffer = new StringWriter(); var serializer = new Serializer(); serializer.Serialize(buffer, entries); Dump.WriteLine(buffer); var deserialized = serializer.Deserialize<Dictionary<string, string>>(new StringReader(buffer.ToString())); foreach (var pair in deserialized) { Assert.AreEqual(entries[pair.Key], pair.Value); } } [Test] public void SerializeAnonymousType() { var data = new { Key = 3 }; var serializer = new Serializer(); var buffer = new StringWriter(); serializer.Serialize(buffer, data); Dump.WriteLine(buffer); var bufferText = buffer.ToString(); var parsed = serializer.Deserialize<Dictionary<string, string>>(bufferText); Assert.NotNull(parsed); Assert.AreEqual(1, parsed.Count); Assert.True(parsed.ContainsKey("Key")); Assert.AreEqual(parsed["Key"], "3"); } [Test] public void SerializationIncludesDefaultValueWhenAsked() { var settings = new SerializerSettings() {EmitDefaultValues = true}; settings.RegisterAssembly(typeof(X).Assembly); var serializer = new Serializer(settings); var buffer = new StringWriter(); var original = new X(); serializer.Serialize(buffer, original, typeof(X)); Dump.WriteLine(buffer); var bufferText = buffer.ToString(); Assert.True(bufferText.Contains("MyString")); } [Test] public void SerializationDoesNotIncludeDefaultValueWhenNotAsked() { var settings = new SerializerSettings() { EmitDefaultValues = false }; settings.RegisterAssembly(typeof(X).Assembly); var serializer = new Serializer(settings); var buffer = new StringWriter(); var original = new X(); serializer.Serialize(buffer, original, typeof(X)); Dump.WriteLine(buffer); var bufferText = buffer.ToString(); Assert.False(bufferText.Contains("MyString")); } [Test] public void SerializationOfNullWorksInJson() { var settings = new SerializerSettings() { EmitDefaultValues = true, EmitJsonComptible = true }; settings.RegisterAssembly(typeof(X).Assembly); var serializer = new Serializer(settings); var buffer = new StringWriter(); var original = new X { MyString = null }; serializer.Serialize(buffer, original, typeof(X)); Dump.WriteLine(buffer); var bufferText = buffer.ToString(); Assert.True(bufferText.Contains("MyString")); } [Test] public void DeserializationOfNullWorksInJson() { var settings = new SerializerSettings() { EmitDefaultValues = true, EmitJsonComptible = true }; settings.RegisterAssembly(typeof(X).Assembly); var serializer = new Serializer(settings); var buffer = new StringWriter(); var original = new X { MyString = null }; serializer.Serialize(buffer, original, typeof(X)); Dump.WriteLine(buffer); var bufferText = buffer.ToString(); var copy = (X) serializer.Deserialize(bufferText, typeof(X)); Assert.Null(copy.MyString); } [Test] public void SerializationRespectsYamlIgnoreAttribute() { var settings = new SerializerSettings(); settings.RegisterAssembly(typeof(ContainsIgnore).Assembly); var serializer = new Serializer(settings); var buffer = new StringWriter(); var orig = new ContainsIgnore { IgnoreMe = "Some Text" }; serializer.Serialize(buffer, orig); Dump.WriteLine(buffer); var copy = (ContainsIgnore) serializer.Deserialize(new StringReader(buffer.ToString()), typeof(ContainsIgnore)); Assert.Null(copy.IgnoreMe); } class ContainsIgnore { [YamlIgnore] public String IgnoreMe { get; set; } } [Test] public void SerializeArrayOfIdenticalObjects() { var obj1 = new Z { aaa = "abc" }; var objects = new[] { obj1, obj1, obj1 }; var result = SerializeThenDeserialize(objects); Assert.NotNull(result); Assert.AreEqual(3, result.Length); Assert.AreEqual(obj1.aaa, result[0].aaa); Assert.AreEqual(obj1.aaa, result[1].aaa); Assert.AreEqual(obj1.aaa, result[2].aaa); Assert.AreSame(result[0], result[1]); Assert.AreSame(result[1], result[2]); } private T SerializeThenDeserialize<T>(T input) { var serializer = new Serializer(); var writer = new StringWriter(); serializer.Serialize(writer, input, typeof(T)); var serialized = writer.ToString(); Dump.WriteLine("serialized =\n-----\n{0}", serialized); return serializer.Deserialize<T>(new StringReader(serialized)); } public class Z { public string aaa { get; set; } } [Test] public void RoundtripAlias() { var input = new ConventionTest { AliasTest = "Fourth" }; var serializer = new Serializer(); var writer = new StringWriter(); serializer.Serialize(writer, input, input.GetType()); var serialized = writer.ToString(); // Ensure serialisation is correct Assert.True(serialized.Contains("fourthTest: Fourth")); var output = serializer.Deserialize<ConventionTest>(serialized); // Ensure round-trip retains value Assert.AreEqual(input.AliasTest, output.AliasTest); } private class ConventionTest { [DefaultValue(null)] public string FirstTest { get; set; } [DefaultValue(null)] public string SecondTest { get; set; } [DefaultValue(null)] public string ThirdTest { get; set; } [YamlMember("fourthTest")] public string AliasTest { get; set; } [YamlIgnore] public string fourthTest { get; set; } } [Test] public void DefaultValueAttributeIsUsedWhenPresentWithoutEmitDefaults() { var input = new HasDefaults { Value = HasDefaults.DefaultValue }; var serializer = new Serializer(); var writer = new StringWriter(); serializer.Serialize(writer, input); var serialized = writer.ToString(); Dump.WriteLine(serialized); Assert.False(serialized.Contains("Value")); } [Test] public void DefaultValueAttributeIsIgnoredWhenPresentWithEmitDefaults() { var input = new HasDefaults { Value = HasDefaults.DefaultValue }; var serializer = new Serializer(new SerializerSettings() { EmitDefaultValues = true}); var writer = new StringWriter(); serializer.Serialize(writer, input); var serialized = writer.ToString(); Dump.WriteLine(serialized); Assert.True(serialized.Contains("Value")); } [Test] public void DefaultValueAttributeIsIgnoredWhenValueIsDifferent() { var input = new HasDefaults { Value = "non-default" }; var serializer = new Serializer(); var writer = new StringWriter(); serializer.Serialize(writer, input); var serialized = writer.ToString(); Dump.WriteLine(serialized); Assert.True(serialized.Contains("Value")); } public class HasDefaults { public const string DefaultValue = "myDefault"; [DefaultValue(DefaultValue)] public string Value { get; set; } } [Test] public void NullValuesInListsAreAlwaysEmittedWithoutEmitDefaults() { var input = new[] { "foo", null, "bar" }; var serializer = new Serializer(new SerializerSettings() { LimitPrimitiveFlowSequence = 0 }); var writer = new StringWriter(); serializer.Serialize(writer, input); var serialized = writer.ToString(); Dump.WriteLine(serialized); Assert.AreEqual(3, Regex.Matches(serialized, "-").Count); } [Test] public void NullValuesInListsAreAlwaysEmittedWithEmitDefaults() { var input = new[] { "foo", null, "bar" }; var serializer = new Serializer(new SerializerSettings() { EmitDefaultValues = true, LimitPrimitiveFlowSequence = 0}); var writer = new StringWriter(); serializer.Serialize(writer, input); var serialized = writer.ToString(); Dump.WriteLine(serialized); Assert.AreEqual(3, Regex.Matches(serialized, "-").Count); } [Test] public void DeserializeTwoDocuments() { var yaml = @"--- Name: Andy --- Name: Brad ..."; var serializer = new Serializer(); var reader = new EventReader(new Parser(new StringReader(yaml))); reader.Expect<StreamStart>(); var andy = serializer.Deserialize<Person>(reader); Assert.NotNull(andy); Assert.AreEqual("Andy", andy.Name); var brad = serializer.Deserialize<Person>(reader); Assert.NotNull(brad); Assert.AreEqual("Brad", brad.Name); } [Test] public void DeserializeManyDocuments() { var yaml = @"--- Name: Andy --- Name: Brad --- Name: Charles ..."; var serializer = new Serializer(); var reader = new EventReader(new Parser(new StringReader(yaml))); reader.Allow<StreamStart>(); var people = new List<Person>(); while (!reader.Accept<StreamEnd>()) { var person = serializer.Deserialize<Person>(reader); people.Add(person); } Assert.AreEqual(3, people.Count); Assert.AreEqual("Andy", people[0].Name); Assert.AreEqual("Brad", people[1].Name); Assert.AreEqual("Charles", people[2].Name); } public class Person { public string Name { get; set; } } [Test] public void DeserializeEmptyDocument() { var serializer = new Serializer(); var array = (int[])serializer.Deserialize(new StringReader(""), typeof(int[])); Assert.Null(array); } [Test] public void SerializeGenericDictionaryShouldNotThrowTargetException() { var serializer = new Serializer(); var buffer = new StringWriter(); serializer.Serialize(buffer, new OnlyGenericDictionary { { "hello", "world" }, }); } private class OnlyGenericDictionary : IDictionary<string, string> { private readonly Dictionary<string, string> _dictionary = new Dictionary<string, string>(); #region IDictionary<string,string> Members public void Add(string key, string value) { _dictionary.Add(key, value); } public bool ContainsKey(string key) { throw new NotImplementedException(); } public ICollection<string> Keys { get { throw new NotImplementedException(); } } public bool Remove(string key) { throw new NotImplementedException(); } public bool TryGetValue(string key, out string value) { throw new NotImplementedException(); } public ICollection<string> Values { get { throw new NotImplementedException(); } } public string this[string key] { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } #endregion #region ICollection<KeyValuePair<string,string>> Members public void Add(KeyValuePair<string, string> item) { throw new NotImplementedException(); } public void Clear() { throw new NotImplementedException(); } public bool Contains(KeyValuePair<string, string> item) { throw new NotImplementedException(); } public void CopyTo(KeyValuePair<string, string>[] array, int arrayIndex) { throw new NotImplementedException(); } public int Count { get { throw new NotImplementedException(); } } public bool IsReadOnly { get { throw new NotImplementedException(); } } public bool Remove(KeyValuePair<string, string> item) { throw new NotImplementedException(); } #endregion #region IEnumerable<KeyValuePair<string,string>> Members public IEnumerator<KeyValuePair<string, string>> GetEnumerator() { return _dictionary.GetEnumerator(); } #endregion #region IEnumerable Members IEnumerator IEnumerable.GetEnumerator() { return _dictionary.GetEnumerator(); } #endregion } [Test] public void ForwardReferencesWorkInGenericLists() { var serializer = new Serializer(); var result = serializer.Deserialize<string[]>(YamlText(@" - *forward - &forward ForwardReference ")); Assert.AreEqual(2, result.Length); Assert.AreEqual("ForwardReference", result[0]); Assert.AreEqual("ForwardReference", result[1]); } [Test] public void ForwardReferencesWorkInNonGenericLists() { var serializer = new Serializer(); var result = serializer.Deserialize<ArrayList>(YamlText(@" - *forward - &forward ForwardReference ")); Assert.AreEqual(2, result.Count); Assert.AreEqual("ForwardReference", result[0]); Assert.AreEqual("ForwardReference", result[1]); } [Test] public void ForwardReferencesWorkInGenericDictionaries() { var serializer = new Serializer(); var result = serializer.Deserialize<Dictionary<string, string>>(YamlText(@" key1: *forward *forwardKey: ForwardKeyValue *forward: *forward key2: &forward ForwardReference key3: &forwardKey key4 ")); Assert.AreEqual(5, result.Count); Assert.AreEqual("ForwardReference", result["ForwardReference"]); Assert.AreEqual("ForwardReference", result["key1"]); Assert.AreEqual("ForwardReference", result["key2"]); Assert.AreEqual("ForwardKeyValue", result["key4"]); Assert.AreEqual("key4", result["key3"]); } [Test] public void ForwardReferencesWorkInNonGenericDictionaries() { var serializer = new Serializer(); var result = serializer.Deserialize<Hashtable>(YamlText(@" key1: *forward *forwardKey: ForwardKeyValue *forward: *forward key2: &forward ForwardReference key3: &forwardKey key4 ")); Assert.AreEqual(5, result.Count); Assert.AreEqual("ForwardReference", result["ForwardReference"]); Assert.AreEqual("ForwardReference", result["key1"]); Assert.AreEqual("ForwardReference", result["key2"]); Assert.AreEqual("ForwardKeyValue", result["key4"]); Assert.AreEqual("key4", result["key3"]); } [Test] public void ForwardReferencesWorkInObjects() { var serializer = new Serializer(); var result = serializer.Deserialize<X>(YamlText(@" Nothing: *forward MyString: &forward ForwardReference ")); Assert.AreEqual("ForwardReference", result.Nothing); Assert.AreEqual("ForwardReference", result.MyString); } [Test] public void UndefinedForwardReferencesFail() { var serializer = new Serializer(); Assert.Throws<AnchorNotFoundException>(() => serializer.Deserialize<X>(YamlText(@" Nothing: *forward MyString: ForwardReference ")) ); } private class X { [DefaultValue(false)] public bool MyFlag { get; set; } [DefaultValue(null)] public string Nothing { get; set; } [DefaultValue(1234)] public int MyInt { get; set; } [DefaultValue(6789.1011)] public double MyDouble { get; set; } [DefaultValue("Hello world")] public string MyString { get; set; } public DateTime MyDate { get; set; } public TimeSpan MyTimeSpan { get; set; } public Point MyPoint { get; set; } [DefaultValue(8)] public int? MyNullableWithValue { get; set; } [DefaultValue(null)] public int? MyNullableWithoutValue { get; set; } public X() { MyInt = 1234; MyDouble = 6789.1011; MyString = "Hello world"; MyDate = DateTime.Now; MyTimeSpan = TimeSpan.FromHours(1); MyPoint = new Point(100, 200); MyNullableWithValue = 8; } } } }
// 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.Threading.Tasks; namespace Microsoft.Xml { using System; internal partial class ReadContentAsBinaryHelper { // Internal methods internal async Task<int> ReadContentAsBase64Async(byte[] buffer, int index, int count) { // check arguments if (buffer == null) { throw new ArgumentNullException("buffer"); } if (count < 0) { throw new ArgumentOutOfRangeException("count"); } if (index < 0) { throw new ArgumentOutOfRangeException("index"); } if (buffer.Length - index < count) { throw new ArgumentOutOfRangeException("count"); } switch (_state) { case State.None: if (!_reader.CanReadContentAs()) { throw _reader.CreateReadContentAsException("ReadContentAsBase64"); } if (!await InitAsync().ConfigureAwait(false)) { return 0; } break; case State.InReadContent: // if we have a correct decoder, go read if (_decoder == _base64Decoder) { // read more binary data return await ReadContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false); } break; case State.InReadElementContent: throw new InvalidOperationException(ResXml.Xml_MixingBinaryContentMethods); default: Debug.Assert(false); return 0; } Debug.Assert(_state == State.InReadContent); // setup base64 decoder InitBase64Decoder(); // read more binary data return await ReadContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false); } internal async Task<int> ReadContentAsBinHexAsync(byte[] buffer, int index, int count) { // check arguments if (buffer == null) { throw new ArgumentNullException("buffer"); } if (count < 0) { throw new ArgumentOutOfRangeException("count"); } if (index < 0) { throw new ArgumentOutOfRangeException("index"); } if (buffer.Length - index < count) { throw new ArgumentOutOfRangeException("count"); } switch (_state) { case State.None: if (!_reader.CanReadContentAs()) { throw _reader.CreateReadContentAsException("ReadContentAsBinHex"); } if (!await InitAsync().ConfigureAwait(false)) { return 0; } break; case State.InReadContent: // if we have a correct decoder, go read if (_decoder == _binHexDecoder) { // read more binary data return await ReadContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false); } break; case State.InReadElementContent: throw new InvalidOperationException(ResXml.Xml_MixingBinaryContentMethods); default: Debug.Assert(false); return 0; } Debug.Assert(_state == State.InReadContent); // setup binhex decoder InitBinHexDecoder(); // read more binary data return await ReadContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false); } internal async Task<int> ReadElementContentAsBase64Async(byte[] buffer, int index, int count) { // check arguments if (buffer == null) { throw new ArgumentNullException("buffer"); } if (count < 0) { throw new ArgumentOutOfRangeException("count"); } if (index < 0) { throw new ArgumentOutOfRangeException("index"); } if (buffer.Length - index < count) { throw new ArgumentOutOfRangeException("count"); } switch (_state) { case State.None: if (_reader.NodeType != XmlNodeType.Element) { throw _reader.CreateReadElementContentAsException("ReadElementContentAsBase64"); } if (!await InitOnElementAsync().ConfigureAwait(false)) { return 0; } break; case State.InReadContent: throw new InvalidOperationException(ResXml.Xml_MixingBinaryContentMethods); case State.InReadElementContent: // if we have a correct decoder, go read if (_decoder == _base64Decoder) { // read more binary data return await ReadElementContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false); } break; default: Debug.Assert(false); return 0; } Debug.Assert(_state == State.InReadElementContent); // setup base64 decoder InitBase64Decoder(); // read more binary data return await ReadElementContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false); } internal async Task<int> ReadElementContentAsBinHexAsync(byte[] buffer, int index, int count) { // check arguments if (buffer == null) { throw new ArgumentNullException("buffer"); } if (count < 0) { throw new ArgumentOutOfRangeException("count"); } if (index < 0) { throw new ArgumentOutOfRangeException("index"); } if (buffer.Length - index < count) { throw new ArgumentOutOfRangeException("count"); } switch (_state) { case State.None: if (_reader.NodeType != XmlNodeType.Element) { throw _reader.CreateReadElementContentAsException("ReadElementContentAsBinHex"); } if (!await InitOnElementAsync().ConfigureAwait(false)) { return 0; } break; case State.InReadContent: throw new InvalidOperationException(ResXml.Xml_MixingBinaryContentMethods); case State.InReadElementContent: // if we have a correct decoder, go read if (_decoder == _binHexDecoder) { // read more binary data return await ReadElementContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false); } break; default: Debug.Assert(false); return 0; } Debug.Assert(_state == State.InReadElementContent); // setup binhex decoder InitBinHexDecoder(); // read more binary data return await ReadElementContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false); } internal async Task FinishAsync() { if (_state != State.None) { while (await MoveToNextContentNodeAsync(true).ConfigureAwait(false)) ; if (_state == State.InReadElementContent) { if (_reader.NodeType != XmlNodeType.EndElement) { throw new XmlException(ResXml.Xml_InvalidNodeType, _reader.NodeType.ToString(), _reader as IXmlLineInfo); } // move off the EndElement await _reader.ReadAsync().ConfigureAwait(false); } } Reset(); } // Private methods private async Task<bool> InitAsync() { // make sure we are on a content node if (!await MoveToNextContentNodeAsync(false).ConfigureAwait(false)) { return false; } _state = State.InReadContent; _isEnd = false; return true; } private async Task<bool> InitOnElementAsync() { Debug.Assert(_reader.NodeType == XmlNodeType.Element); bool isEmpty = _reader.IsEmptyElement; // move to content or off the empty element await _reader.ReadAsync().ConfigureAwait(false); if (isEmpty) { return false; } // make sure we are on a content node if (!await MoveToNextContentNodeAsync(false).ConfigureAwait(false)) { if (_reader.NodeType != XmlNodeType.EndElement) { throw new XmlException(ResXml.Xml_InvalidNodeType, _reader.NodeType.ToString(), _reader as IXmlLineInfo); } // move off end element await _reader.ReadAsync().ConfigureAwait(false); return false; } _state = State.InReadElementContent; _isEnd = false; return true; } private async Task<int> ReadContentAsBinaryAsync(byte[] buffer, int index, int count) { Debug.Assert(_decoder != null); if (_isEnd) { Reset(); return 0; } _decoder.SetNextOutputBuffer(buffer, index, count); for (; ; ) { // use streaming ReadValueChunk if the reader supports it if (_canReadValueChunk) { for (; ; ) { if (_valueOffset < _valueChunkLength) { int decodedCharsCount = _decoder.Decode(_valueChunk, _valueOffset, _valueChunkLength - _valueOffset); _valueOffset += decodedCharsCount; } if (_decoder.IsFull) { return _decoder.DecodedCount; } Debug.Assert(_valueOffset == _valueChunkLength); if ((_valueChunkLength = await _reader.ReadValueChunkAsync(_valueChunk, 0, ChunkSize).ConfigureAwait(false)) == 0) { break; } _valueOffset = 0; } } else { // read what is reader.Value string value = await _reader.GetValueAsync().ConfigureAwait(false); int decodedCharsCount = _decoder.Decode(value, _valueOffset, value.Length - _valueOffset); _valueOffset += decodedCharsCount; if (_decoder.IsFull) { return _decoder.DecodedCount; } } _valueOffset = 0; // move to next textual node in the element content; throw on sub elements if (!await MoveToNextContentNodeAsync(true).ConfigureAwait(false)) { _isEnd = true; return _decoder.DecodedCount; } } } private async Task<int> ReadElementContentAsBinaryAsync(byte[] buffer, int index, int count) { if (count == 0) { return 0; } // read binary int decoded = await ReadContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false); if (decoded > 0) { return decoded; } // if 0 bytes returned check if we are on a closing EndElement, throw exception if not if (_reader.NodeType != XmlNodeType.EndElement) { throw new XmlException(ResXml.Xml_InvalidNodeType, _reader.NodeType.ToString(), _reader as IXmlLineInfo); } // move off the EndElement await _reader.ReadAsync().ConfigureAwait(false); _state = State.None; return 0; } private async Task<bool> MoveToNextContentNodeAsync(bool moveIfOnContentNode) { do { switch (_reader.NodeType) { case XmlNodeType.Attribute: return !moveIfOnContentNode; case XmlNodeType.Text: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: case XmlNodeType.CDATA: if (!moveIfOnContentNode) { return true; } break; case XmlNodeType.ProcessingInstruction: case XmlNodeType.Comment: case XmlNodeType.EndEntity: // skip comments, pis and end entity nodes break; case XmlNodeType.EntityReference: if (_reader.CanResolveEntity) { _reader.ResolveEntity(); break; } goto default; default: return false; } moveIfOnContentNode = false; } while (await _reader.ReadAsync().ConfigureAwait(false)); return false; } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Text; using TribalWars.Villages.Buildings; using TribalWars.Villages.Resources; using TribalWars.Villages.Units; using TribalWars.Worlds; namespace TribalWars.Browsers.Reporting { /// <summary> /// Generates a BBCode report /// </summary> public class ReportBbCodeOutput { #region Fields private readonly Report _report; #endregion #region Constructors public ReportBbCodeOutput(Report report) { _report = report; } /// <summary> /// Generates the standard BBCode output for the /// given report /// </summary> public static string Generate(Report report) { var output = new ReportBbCodeOutput(report); switch (report.ReportType) { case ReportTypes.Scout: return output.BbCodeScout(); default: return output.BbCodeStandard(); } } #endregion #region Output Types public string BbCodeStandard() { // players var str = new StringBuilder(200); PrintPlayers(str); if (_report.ReportDate.HasValue) { str.Append(Environment.NewLine); TimeSpan span = World.Default.Settings.ServerTime - _report.ReportDate.Value; if (span.TotalHours < 1) str.Append(string.Format("Date: {0}", _report.ReportDate.Value)); else str.Append(string.Format("Date: {0} ({1} hours ago)", _report.ReportDate.Value, Math.Round(span.TotalHours))); } // resources if (_report.ReportOptions.ResourceDetails || true) str.Append(PrintResources()); // Troops if (_report.ReportOptions.AttackingTroops) str.Append(PrintTroops("Attacker:", _report.Attack, true)); if (_report.ReportOptions.DefendingTroops) str.Append(PrintTroops("Defender:", _report.Defense, false)); // print free space if (_report.ReportOptions.People) { string space = Environment.NewLine + Resource.FaceBBCodeString; space += "[b]" + Report.GetTotalPeople(_report.Defense, TotalPeople.End).ToString("#,0") + "[/b]"; if (_report.Buildings != null && _report.Buildings.Count > 2) { int farmBuildings = _report.GetTotalPeopleInBuildings(); if (farmBuildings > 0) space += string.Format(" + {0:#,0}", farmBuildings); if (_report.Buildings.ContainsKey(BuildingTypes.Farm)) { ReportBuilding farm = _report.Buildings[BuildingTypes.Farm]; int totalFarm = farm.GetTotalProduction(); //space += string.Format(" + {0:#,0}", farmBuildings); space = string.Format("{1} ({0:#,0} free)", totalFarm - farmBuildings - Report.GetTotalPeople(_report.Defense, TotalPeople.End), space); } } if (space.Length > 0) { if (Report.GetTotalPeople(_report.Defense, TotalPeople.Start) == 0) str.Append(Environment.NewLine + Environment.NewLine + "[b]Defender:[/b]"); str.Append(space); } } // Buildings if (_report.ReportOptions.Buildings) str.Append(PrintBuildings("Buildings:", _report.Buildings)); return str.ToString(); } public string BbCodeScout() { // players var str = new StringBuilder(200); PrintPlayers(str); if (_report.ReportDate.HasValue) { str.Append(Environment.NewLine); TimeSpan span = World.Default.Settings.ServerTime - _report.ReportDate.Value; if (span.TotalHours < 1) str.Append(string.Format("Date: {0}", _report.ReportDate.Value)); else str.Append(string.Format("Date: {0} ({1} hours ago)", _report.ReportDate.Value, Math.Round(span.TotalHours))); } // Troops str.Append(PrintTroops("Defender:", _report.Defense, false)); // Buildings str.Append(PrintBuildings("Buildings:", _report.Buildings)); return str.ToString(); } #endregion #region Buildings private string PrintBuildings(string title, Dictionary<BuildingTypes, ReportBuilding> buildings) { string str = ""; foreach (ReportBuilding build in buildings.Values) { str += ", " + string.Format(build.BbCode()); } if (str.Length > 2) { str = string.Format("{1}{1}[b]{0}[/b]{1}{2}", title, Environment.NewLine, str.Substring(2)); if (buildings.Count > 3) str += Environment.NewLine + string.Format("Calculated points: {0:#,0}", _report.CalculatedPoints); } return str; } #endregion #region Troops private string PrintTroops(string title, Dictionary<UnitTypes, ReportUnit> troops, bool isAttacker) { int troopsTotalLost = 0; string str = string.Empty; foreach (ReportUnit unit in troops.Values) { if (unit.AmountStart > 0 && !(isAttacker && unit.Unit.HideAttacker)) { // add attack numbers - losses if (unit.AmountEnd > 0) { //str += Environment.NewLine; str += string.Format(" {0}{1}", unit.Unit.BbCodeImage, unit.AmountStart.ToString("#,0")); if (unit.AmountLost > 0) { str += string.Format(" ([b]{0}[/b])", unit.AmountEnd.ToString("#,0")); } } troopsTotalLost += unit.AmountLost; } } if (troopsTotalLost > 0) { // print cost lost troops int clay = 0, iron = 0, wood = 0; int totalLostType = 0; string str2 = ""; foreach (ReportUnit unit in troops.Values) { if (unit.AmountStart > 0 && unit.AmountEnd == 0) { str2 += unit.Unit.BbCodeImage; totalLostType += unit.AmountLost; } if (isAttacker && unit.AmountLost > 0) { clay += unit.Unit.Cost.Clay * unit.AmountLost; wood += unit.Unit.Cost.Wood * unit.AmountLost; iron += unit.Unit.Cost.Iron * unit.AmountLost; } } if (str2.Length > 0) str += Environment.NewLine + string.Format("{1} {0:#,0} vanquished", totalLostType, str2); //if (total == totalLost) str += string.Format("[b]!!All Dead!![/b]"); /*if (isAttacker && clay > 0) { // add resource cost losses str += Environment.NewLine + "Losses cost: "; str += Resource.ClayString + clay.ToString("#,0") + " "; str += Resource.WoodString + wood.ToString("#,0") + " "; str += Resource.IronString + iron.ToString("#,0") + " "; str += Resource.AllString + (iron + clay + wood).ToString("#,0"); }*/ } if (str.Length > 0) { str = string.Format("{1}{1}[b]{0}[/b]{1}{2}", title, Environment.NewLine, str.Trim()); // .Trim() } string unitOut = string.Empty; foreach (ReportUnit unit in troops.Values) { if (unit.AmountOut > 0) { unitOut += string.Format("{1}{0} ", unit.AmountOut.ToString("#,0"), unit.Unit.BbCodeImage); } } if (unitOut.Length > 0) str += Environment.NewLine + "Outside: " + unitOut; return str; } #endregion #region Resources private string PrintResources() { string str = Environment.NewLine; int totalLeft = _report.ResourcesLeft.Total(); int totalHaul = _report.ResourcesHaul.Total(); int room = _report.GetTotalResourceRoom(); if (room > 0) { str += Environment.NewLine + string.Format("{0} [b]{2:#,0}[/b] / {1:#,0}", _report.Buildings[BuildingTypes.Warehouse].Building.BbCodeImage, room, totalLeft); const string pattern = "{1} {0:#,0} ({2})"; str += Environment.NewLine + string.Format(pattern, _report.ResourcesLeft.Wood, Resource.WoodBBCodeString, _report.Buildings[BuildingTypes.TimberCamp].BbCodeForResource(room, _report.ResourcesLeft.Wood)); str += Environment.NewLine + string.Format(pattern, _report.ResourcesLeft.Clay, Resource.ClayBBCodeString, _report.Buildings[BuildingTypes.ClayPit].BbCodeForResource(room, _report.ResourcesLeft.Clay)); str += Environment.NewLine + string.Format(pattern, _report.ResourcesLeft.Iron, Resource.IronBBCodeString, _report.Buildings[BuildingTypes.IronMine].BbCodeForResource(room, _report.ResourcesLeft.Iron)); } else if (_report.ResourcesLeft.Total() > 0) { // normal 1 line resource print: str += Environment.NewLine + "Resources left: "; str += PrintResourcesCore(_report.ResourcesLeft, 0, " ", true); } //str += PrintResourceHaulFarmers(); if (_report.ResourcesHaul.Total() > 0) { str += Environment.NewLine + "Resources taken: "; str += PrintResourcesCore(_report.ResourcesHaul, _report.ResourceHaulMax, " ", true); } if (str.Length > 0 && str != Environment.NewLine) return Environment.NewLine + Environment.NewLine + "[b]Resource Details[/b]" + Environment.NewLine + str.Trim(); return ""; } protected string PrintResourceHaulFarmers() { // showMinTroops: print how many 'farmer' (spear&lc) units are needed to get all resources int tot = _report.ResourcesLeft.Total(); if (tot > 0) { string str = Environment.NewLine; string farmer = string.Empty; foreach (Unit unit in WorldUnits.Default) { if (unit.Farmer && unit.Carry > 0) farmer += string.Format(", {0}{1}", unit.BbCodeImage, Math.Ceiling((double)tot / unit.Carry).ToString("#,0")); } if (farmer.Length > 0) str += string.Format("{0}", farmer.Substring(2)); return str; } return string.Empty; } protected string PrintResourcesCore(Resource resources, int haulMax, string seperator, bool printTotal) { // print the three resources // if there are only two numbers (because he has 0 of some type) // then the icon for iron will have 0 resources even if the type // was wood/clay. since we can't really see the image:) string str = ""; if (resources.Wood > 0) str += string.Format("{1} {0:#,0}{2}", resources.Wood, Resource.WoodBBCodeString, seperator); if (resources.Clay > 0) str += string.Format("{1} {0:#,0}{2}", resources.Clay, Resource.ClayBBCodeString, seperator); if (resources.Iron > 0) str += string.Format("{1} {0:#,0}{2}", resources.Iron, Resource.IronBBCodeString, seperator); if (printTotal) { int total = resources.Total(); if (total > 0) { str += string.Format("{0}{1:#,0}", Resource.GetImage(ResourceTypes.All), total); if (resources.Total() != haulMax && haulMax > 0) str += " (All)"; } } return str; } #endregion #region Players /// <summary> /// Gets BBCode of the report winner /// Also adds loyalty changes /// </summary> private string GetWinner() { if (_report.LoyaltyBegin > 0) { Unit snob = WorldUnits.Default[UnitTypes.Snob]; return string.Format("{0} [b]{1}[/b] to [b]{2}[/b]", snob.BbCodeImage, _report.LoyaltyBegin.ToString(CultureInfo.InvariantCulture), _report.LoyaltyEnd.ToString(CultureInfo.InvariantCulture)); } if (_report.Winner == "attacker") return "[b]won[/b] against"; if (_report.Winner == "defender") return "[b]lost[/b] against"; return "[b]fought[/b] against"; } /// <summary> /// Adds village and player info to the output /// </summary> public void PrintPlayers(StringBuilder str) { if (_report.ReportType != ReportTypes.Scout) { if (_report.ReportOptions.AttackingPlayer) str.Append(_report.Attacker.BBCode()); if (_report.ReportOptions.DefendingPlayer || _report.ReportType == ReportTypes.Noble) { str.Append(Environment.NewLine + GetWinner()); str.Append(Environment.NewLine); } } if (_report.ReportOptions.DefendingPlayer) str.Append(_report.Defender.BBCode()); } #endregion } }
//! \file ArcPAC.cs //! \date 2018 Jan 11 //! \brief DAI system resource archive. // // Copyright (C) 2018 by morkt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Diagnostics; using System.IO; using System.Linq; using GameRes.Utility; namespace GameRes.Formats.DaiSystem { [Export(typeof(ArchiveFormat))] public class PacOpener : ArchiveFormat { public override string Tag { get { return "PAC/DAI"; } } public override string Description { get { return "DAI system resource archive"; } } public override uint Signature { get { return 0x5F494144; } } // 'DAI_SYSTEM_01000' public override bool IsHierarchic { get { return false; } } public override bool CanWrite { get { return false; } } public override ArcFile TryOpen (ArcView file) { if (!file.View.AsciiEqual (4, "SYSTEM_01000")) return null; int count = Binary.BigEndian (file.View.ReadUInt16 (0x10)); if (!IsSaneCount (count)) return null; uint index_size = Binary.BigEndian (file.View.ReadUInt32 (0x12)); var index = file.View.ReadBytes (0x16, index_size); for (int i = 0; i < index.Length; ++i) index[i] -= (byte)(i + 0x28); int index_offset = 0; var dir = new List<Entry> (count); for (int i = 0; i < count; ++i) { int name_end = Array.IndexOf<byte> (index, (byte)',', index_offset); if (-1 == name_end) return null; var name = Encodings.cp932.GetString (index, index_offset, name_end - index_offset); index_offset = name_end + 1; var entry = FormatCatalog.Instance.Create<Entry> (name); entry.Offset = BigEndian.ToUInt32 (index, index_offset); index_offset += 5; dir.Add (entry); } for (int i = 1; i < dir.Count; ++i) { var entry = dir[i-1]; entry.Size = (uint)(dir[i].Offset - entry.Offset); if (!entry.CheckPlacement (file.MaxOffset)) return null; } dir[dir.Count-1].Size = (uint)(file.MaxOffset - dir[dir.Count-1].Offset); DetectFileTypes (file, dir); return new ArcFile (file, this, dir); } void DetectFileTypes (ArcView file, List<Entry> dir) { foreach (var entry in dir.Where (e => string.IsNullOrEmpty (e.Type))) { uint signature = file.View.ReadUInt32 (entry.Offset); if (0x05304148 == signature) { entry.Type = "image"; continue; } else if (0x304148 == (signature & 0xFFFFFF)) { uint encryption = file.View.ReadUInt32 (entry.Offset+8); long offset = entry.Offset + 0x10 + (signature >> 24); if (0 != encryption) { if (4 == encryption) { uint bits = Binary.BigEndian (file.View.ReadUInt32 (offset + 8)); if (bits > entry.Size) continue; if (file.View.AsciiEqual (offset+12+bits, "BM")) { entry.ChangeType (ImageFormat.Bmp); } else if (file.View.AsciiEqual (entry.Offset+entry.Size-0x12, "TRUEVISION")) { entry.ChangeType (ImageFormat.Tga); } } continue; } signature = file.View.ReadUInt32 (offset); } entry.ChangeType (AutoEntry.DetectFileType (signature)); } } public override Stream OpenEntry (ArcFile arc, Entry entry) { if (!arc.File.View.AsciiEqual (entry.Offset, "HA0")) return base.OpenEntry (arc, entry); byte header_length = arc.File.View.ReadByte (entry.Offset+3); uint ha0_header_length = 0x10u + header_length; if (ha0_header_length >= entry.Size) return base.OpenEntry (arc, entry); uint unpacked_size = Binary.BigEndian (arc.File.View.ReadUInt32 (entry.Offset+4)); uint pattern = arc.File.View.ReadUInt32 (entry.Offset+8); var header = arc.File.View.ReadBytes (entry.Offset+0x10, header_length); var input = arc.File.View.ReadBytes (entry.Offset + ha0_header_length, entry.Size - ha0_header_length); while (pattern != 0) { uint code = pattern >> 24; switch (code) { case 0: break; case 2: input = Decrypt2 (input); break; case 3: input = Decrypt3 (input); break; case 4: input = Unpack4 (input); break; default: Trace.WriteLine (string.Format ("Unknown encryption method ({0})", code), "[DAI_SYSTEM]"); return base.OpenEntry (arc, entry); } pattern <<= 8; } return new BinMemoryStream (input, entry.Name); } byte[] Decrypt2 (byte[] input) { var output = new byte[input.Length]; int src = 0; for (int i = 0; i < 3; ++i) { for (int dst = i; dst < output.Length; dst += 3) output[dst] = input[src++]; } return output; } byte[] Decrypt3 (byte[] input) { for (int i = 1; i < input.Length; ++i) { input[i] += input[i-1]; } return input; } byte[] Unpack4 (byte[] input) { int unpacked_size = BigEndian.ToInt32 (input, 0); var output = new byte[unpacked_size]; int ctl_bits = BigEndian.ToInt32 (input, 4); int ctl_bytes = BigEndian.ToInt32 (input, 8); int ctl = 12; int src = 12 + ctl_bytes; int dst = 0; int bits = 2; while (dst < output.Length) { bits >>= 1; if (1 == bits) { bits = input[ctl++] | 0x100; } if (0 == (bits & 1)) { output[dst++] = input[src++]; } else { int offset = input[src++]; int count = input[src++]; Binary.CopyOverlapped (output, dst-offset, dst, count); dst += count; } } return output; } } }
//Copyright 2010 Microsoft Corporation // //Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. //You may obtain a copy of the License at // //http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an //"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and limitations under the License. namespace System.Data.Services.Client { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; #if !ASTORIA_LIGHT using System.Net; #else using System.Data.Services.Http; #endif using System.Xml; public abstract class DataServiceRequest { internal DataServiceRequest() { } public abstract Type ElementType { get; } public abstract Uri RequestUri { get; } internal abstract ProjectionPlan Plan { get; } internal abstract QueryComponents QueryComponents { get; } public override string ToString() { return this.QueryComponents.Uri.ToString(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Returning MaterializeAtom, caller will dispose")] internal static MaterializeAtom Materialize(DataServiceContext context, QueryComponents queryComponents, ProjectionPlan plan, string contentType, Stream response) { Debug.Assert(null != queryComponents, "querycomponents"); string mime = null; Encoding encoding = null; if (!String.IsNullOrEmpty(contentType)) { HttpProcessUtility.ReadContentType(contentType, out mime, out encoding); } if (String.Equals(mime, XmlConstants.MimeApplicationAtom, StringComparison.OrdinalIgnoreCase) || String.Equals(mime, XmlConstants.MimeApplicationXml, StringComparison.OrdinalIgnoreCase)) { if (null != response) { XmlReader reader = XmlUtil.CreateXmlReader(response, encoding); return new MaterializeAtom(context, reader, queryComponents, plan, context.MergeOption); } } return MaterializeAtom.EmptyResults; } internal static DataServiceRequest GetInstance(Type elementType, Uri requestUri) { Type genericType = typeof(DataServiceRequest<>).MakeGenericType(elementType); return (DataServiceRequest)Activator.CreateInstance(genericType, new object[] { requestUri }); } internal static IEnumerable<TElement> EndExecute<TElement>(object source, DataServiceContext context, IAsyncResult asyncResult) { QueryResult result = null; try { result = QueryResult.EndExecute<TElement>(source, asyncResult); return result.ProcessResult<TElement>(context, result.ServiceRequest.Plan); } catch (DataServiceQueryException ex) { Exception inEx = ex; while (inEx.InnerException != null) { inEx = inEx.InnerException; } DataServiceClientException serviceEx = inEx as DataServiceClientException; if (context.IgnoreResourceNotFoundException && serviceEx != null && serviceEx.StatusCode == (int)HttpStatusCode.NotFound) { QueryOperationResponse qor = new QueryOperationResponse<TElement>(new Dictionary<string, string>(ex.Response.Headers), ex.Response.Query, MaterializeAtom.EmptyResults); qor.StatusCode = (int)HttpStatusCode.NotFound; return (IEnumerable<TElement>)qor; } throw; } } #if !ASTORIA_LIGHT internal QueryOperationResponse<TElement> Execute<TElement>(DataServiceContext context, QueryComponents queryComponents) { QueryResult result = null; try { DataServiceRequest<TElement> serviceRequest = new DataServiceRequest<TElement>(queryComponents, this.Plan); result = serviceRequest.CreateResult(this, context, null, null); result.Execute(); return result.ProcessResult<TElement>(context, this.Plan); } catch (InvalidOperationException ex) { QueryOperationResponse operationResponse = result.GetResponse<TElement>(MaterializeAtom.EmptyResults); if (null != operationResponse) { if (context.IgnoreResourceNotFoundException) { DataServiceClientException cex = ex as DataServiceClientException; if (cex != null && cex.StatusCode == (int)HttpStatusCode.NotFound) { return (QueryOperationResponse<TElement>)operationResponse; } } operationResponse.Error = ex; throw new DataServiceQueryException(Strings.DataServiceException_GeneralError, ex, operationResponse); } throw; } } internal long GetQuerySetCount(DataServiceContext context) { Debug.Assert(null != context, "context is null"); this.QueryComponents.Version = Util.DataServiceVersion2; QueryResult response = null; DataServiceRequest<long> serviceRequest = new DataServiceRequest<long>(this.QueryComponents, null); HttpWebRequest request = context.CreateRequest(this.QueryComponents.Uri, XmlConstants.HttpMethodGet, false, null, this.QueryComponents.Version, false); request.Accept = "text/plain"; response = new QueryResult(this, "Execute", serviceRequest, request, null, null); try { response.Execute(); if (HttpStatusCode.NoContent != response.StatusCode) { StreamReader sr = new StreamReader(response.GetResponseStream()); long r = -1; try { r = XmlConvert.ToInt64(sr.ReadToEnd()); } finally { sr.Close(); } return r; } else { throw new DataServiceQueryException(Strings.DataServiceRequest_FailGetCount, response.Failure); } } catch (InvalidOperationException ex) { QueryOperationResponse operationResponse = null; operationResponse = response.GetResponse<long>(MaterializeAtom.EmptyResults); if (null != operationResponse) { operationResponse.Error = ex; throw new DataServiceQueryException(Strings.DataServiceException_GeneralError, ex, operationResponse); } throw; } } #endif internal IAsyncResult BeginExecute(object source, DataServiceContext context, AsyncCallback callback, object state) { QueryResult result = this.CreateResult(source, context, callback, state); result.BeginExecute(); return result; } private QueryResult CreateResult(object source, DataServiceContext context, AsyncCallback callback, object state) { Debug.Assert(null != context, "context is null"); HttpWebRequest request = context.CreateRequest(this.QueryComponents.Uri, XmlConstants.HttpMethodGet, false, null, this.QueryComponents.Version, false); return new QueryResult(source, "Execute", this, request, callback, state); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.hide003.hide003 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.hide003.hide003; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class C { } public class Base { public static int Status; public void Method(C x) { Base.Status = 1; } } public class Derived : Base { public new void Method(C x) { Base.Status = 2; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); C x = new C(); d.Method(x); if (Base.Status == 2) return 0; else return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.overload001.overload001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.overload001.overload001; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public static int Status; public void Method(short x) { Base.Status = 1; } } public class Derived : Base { public void Method(int x) { Base.Status = 2; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); short x = 3; d.Method(x); if (Base.Status == 2) return 0; else return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.overload002.overload002 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.overload002.overload002; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public static int Status; public void Method(short x) { Base.Status = 1; } } public class Derived : Base { public void Method(int x) { Base.Status = 2; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); int x = 3; d.Method(x); if (Base.Status == 2) return 0; else return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.overload003.overload003 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.overload003.overload003; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // Call methods with different accessibility level and selecting the right one.:) // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public static int Status; protected void Method(short x) { Base.Status = 1; } } public class Derived : Base { public void Method(int x) { Base.Status = 2; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); int x = 3; d.Method(x); if (Base.Status == 2) return 0; else return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.overload004.overload004 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.overload004.overload004; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // Call methods with different accessibility level and selecting the right one.:) // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public static int Status; public void Method(int x) { Base.Status = 1; } } public class Derived : Base { protected void Method(short x) { Base.Status = 2; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); short x = 3; d.Method(x); if (Base.Status == 1) return 0; else return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.overload005.overload005 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.overload005.overload005; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // Call methods with different accessibility level and selecting the right one.:) // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public static int Status; public void Method(int x) { Base.Status = 1; } } public class Derived : Base { private void Method(short x) { Base.Status = 2; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); short x = 3; d.Method(x); if (Base.Status == 1) return 0; else return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.overload006.overload006 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.overload006.overload006; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // Call methods with different accessibility level and selecting the right one.:) // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public static int Status; internal void Method(short x) { Base.Status = 1; } } public class Derived : Base { public void Method(int x) { Base.Status = 2; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); int x = 3; d.Method(x); if (Base.Status == 2) return 0; else return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.overload007.overload007 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.overload007.overload007; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // Call methods with different accessibility level and selecting the right one.:) // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public static int Status; protected internal void Method(short x) { Base.Status = 1; } } public class Derived : Base { public void Method(int x) { Base.Status = 2; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); int x = 3; d.Method(x); if (Base.Status == 2) return 0; else return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.overload008.overload008 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.overload008.overload008; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // Select the best method to call. // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public static int Status; public int Method(dynamic x) { Base.Status = 1; return 1; } public void Method(short x) { Base.Status = 2; } } public class Derived : Base { public void Method(int x) { Base.Status = 3; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); dynamic x = 3; d.Method(x); if (Base.Status == 3) return 0; else return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.overload009.overload009 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.overload009.overload009; // <Title> Tests overload resolution</Title> // <Description></Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public class B { static public int status = -1; public void Foo(out int x) { status = 1; x = 1; } } public class A : B { public void Foo(ref int x) { status = 2; } public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic a = new A(); int x; // used to call 'ref', should call 'out' a.Foo(out x); return (1 == status) ? 0 : 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.overload010.overload010 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.overload010.overload010; // <Title> Tests overload resolution</Title> // <Description>regression test </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public class B { static public int status = -1; public void Foo(out int x) { status = 1; x = 1; } } public class A : B { public void Foo(ref int x) { status = 2; } public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic a = new A(); int x; // used to call 'ref', should call 'out' a.Foo(out x); return (1 == status) ? 0 : 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.overload011.overload011 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.overload011.overload011; //<Area></Area> //<Title></Title> //<Description>regression test</Description> //<Related Bugs></Related Bugs> //<Expects Status=success></Expects Status> //<Code> public class NO { public void Foo<T, U>(U u = default(U), T t2 = default(T)) { System.Console.WriteLine(1); } public void Foo<T>(params T[] t) { Program.result = 0; } } public class Program { public static int result; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic x = new NO(); x.Foo(3); return result; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.overload012.overload012 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.overload012.overload012; //<Area></Area> //<Title></Title> //<Description>regression test</Description> //<Related Bugs></Related Bugs> //<Expects Status=success></Expects Status> //<Code> public class NO { public void Foo<T>(T t = default(T)) { } } public class Program { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new NO(); try { d.Foo(); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException) { return 0; } catch (System.Exception) { return 1; } return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.overload013.overload013 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.overload013.overload013; // <Area>dynamic</Area> // <Title>ref parameter overloading</Title> // <Description> // binder generates bad expression tree in presence of ref overload // </Description> // <Related Bugs></Related Bugs> //<Expects Status=success></Expects> // <Code> using System; public class A { public static int x = 0; public void Foo(ref string y) { x = 1; } } public class C : A { public void Foo(string y) { } public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic x = new C(); string y = ""; x.Foo(ref y); return (A.x == 1) ? 0 : 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.ovr001.ovr001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.ovr001.ovr001; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public static int Status; public virtual void Method(int x) { Base.Status = 1; } } public class Derived : Base { public override void Method(int x) { Base.Status = 2; } public void Method(long l) { Base.Status = 3; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); int x = 3; d.Method(x); if (Base.Status == 3) return 0; else return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.ovr002.ovr002 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.ovr002.ovr002; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public static int Status; public virtual void Method(int x) { Base.Status = 1; } } public class Derived : Base { public override void Method(int x) { Base.Status = 2; } public void Method(long l) { Base.Status = 3; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); short x = 3; d.Method(x); if (Base.Status == 3) return 0; else return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.ovr003.ovr003 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.ovr003.ovr003; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public static int Status; public virtual void Method(string x) { Base.Status = 1; } } public class Derived : Base { public override void Method(string x) { Base.Status = 2; } public void Method(object o) { Base.Status = 3; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); string x = "3"; d.Method(x); if (Base.Status == 3) return 0; else return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.ovr004.ovr004 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.ovr004.ovr004; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class C { } public class D : C { } public class Base { public static int Status; public virtual void Method(D x) { Base.Status = 1; } } public class Derived : Base { public override void Method(D x) { Base.Status = 2; } public void Method(C o) { Base.Status = 3; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); C x = new C(); d.Method(x); if (Base.Status == 3) return 0; else return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.ovr005.ovr005 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.ovr005.ovr005; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class C { } public class D : C { } public class Base { public static int Status; public virtual void Method(D x) { Base.Status = 1; } } public class Derived : Base { public override void Method(D x) { Base.Status = 2; } public void Method(C o) { Base.Status = 3; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); D x = new D(); d.Method(x); if (Base.Status == 3) return 0; else return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.ovr006.ovr006 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.ovr006.ovr006; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class C { } public class D : C { } public class Base { public static int Status; public virtual void Method(D x) { Base.Status = 1; } } public class Derived : Base { public override void Method(D x) { Base.Status = 2; } public void Method(C o) { Base.Status = 3; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); C x = new D(); d.Method(x); if (Base.Status == 3) return 0; else return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.ovr007.ovr007 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.ovr007.ovr007; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class C { } public class D : C { } public class Base { public static int Status; public virtual void Method(int x) { Base.Status = 1; } } public class Derived : Base { public override void Method(int x) { Base.Status = 2; } public void Method(string o) { Base.Status = 3; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); int x = 3; d.Method(x); if (Base.Status == 2) return 0; else return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.ovr008.ovr008 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.ovr008.ovr008; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class C { } public class Base { public static int Status; public virtual void Method(int x) { Base.Status = 1; } } public class Derived : Base { public override void Method(int x) { Base.Status = 2; } public void Method(C o) { Base.Status = 3; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); short x = 3; d.Method(x); if (Base.Status == 2) return 0; else return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.ovr009.ovr009 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.ovr009.ovr009; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public enum E { first, second } public class Base { public static int Status; public virtual void Method(string x) { Base.Status = 1; } } public class Derived : Base { public override void Method(string x) { Base.Status = 2; } public void Method(E o) { Base.Status = 3; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); string x = "adfs"; d.Method(x); if (Base.Status == 2) return 0; else return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.ovr010.ovr010 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.ovr010.ovr010; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class C { public static implicit operator int (C c) { return 0; } } public class Base { public static int Status; public virtual void Method(C x) { Base.Status = 1; } } public class Derived : Base { public override void Method(C x) { Base.Status = 2; } public void Method(int o) { Base.Status = 3; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); C x = new C(); d.Method(x); if (Base.Status == 3) return 0; else return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.ovr011.ovr011 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.ovr011.ovr011; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class C { public static implicit operator int (C c) { return 0; } } public class Base { public static int Status; public virtual void Method(C x) { Base.Status = 1; } } public class Derived : Base { public override void Method(C x) { Base.Status = 2; } public void Method(long o) { Base.Status = 3; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); C x = new C(); //This should go to Base.Status = 3 d.Method(x); if (Base.Status == 3) return 0; else return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.ovr012.ovr012 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.ovr012.ovr012; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public static int Status; public virtual void Method(int x) { Base.Status = 1; } public virtual void Method(long y) { Base.Status = 2; } } public class Derived : Base { public override void Method(long x) { Base.Status = 3; } } public class FurtherDerived : Derived { public override void Method(int y) { Base.Status = 4; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new FurtherDerived(); int x = 3; d.Method(x); if (Base.Status == 4) //We should pick the second method return 0; else return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.ovrdynamic001.ovrdynamic001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.ovrdynamic001.ovrdynamic001; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class C { } public class Base { public static int Status; public virtual void Method(object x) { Base.Status = 1; } } public class Derived : Base { public override void Method(dynamic x) { Base.Status = 2; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); C x = new C(); //This should go to Base.Status = 3 d.Method(x); if (Base.Status == 2) return 0; else return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.ovrdynamic002.ovrdynamic002 { using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.ovrdynamic002.ovrdynamic002; // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class C { } public class Base { public static int Status; public virtual void Method(dynamic x) { Base.Status = 1; } } public class Derived : Base { public override void Method(object x) { Base.Status = 2; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); C x = new C(); //This should go to Base.Status = 3 d.Method(x); if (Base.Status == 2) return 0; else return 1; } } // </Code> }
using System; using System.Collections.Generic; using System.Net; using System.Runtime.Serialization; using System.Threading; using Funq; using NServiceKit.Common.Extensions; using NServiceKit.Common.Web; using NServiceKit.Configuration; using NServiceKit.DataAnnotations; using NServiceKit.Logging; using NServiceKit.Logging.Support.Logging; using NServiceKit.OrmLite; using NServiceKit.OrmLite.Sqlite; using NServiceKit.Plugins.ProtoBuf; using NServiceKit.ServiceHost; using NServiceKit.ServiceInterface; using NServiceKit.ServiceInterface.ServiceModel; using NServiceKit.Text; using NServiceKit.WebHost.Endpoints.Tests.IntegrationTests; using NServiceKit.WebHost.Endpoints.Tests.Support.Operations; namespace NServiceKit.WebHost.Endpoints.Tests.Support.Host { /// <summary>A get factorial.</summary> [Route("/factorial/{ForNumber}")] [DataContract] public class GetFactorial { /// <summary>Gets or sets for number.</summary> /// /// <value>for number.</value> [DataMember] public long ForNumber { get; set; } } /// <summary>A get factorial response.</summary> [DataContract] public class GetFactorialResponse { /// <summary>Gets or sets the result.</summary> /// /// <value>The result.</value> [DataMember] public long Result { get; set; } } /// <summary>A get factorial service.</summary> public class GetFactorialService : IService { /// <summary>Anies the given request.</summary> /// /// <param name="request">The request.</param> /// /// <returns>An object.</returns> public object Any(GetFactorial request) { return new GetFactorialResponse { Result = GetFactorial(request.ForNumber) }; } /// <summary>Gets a factorial.</summary> /// /// <param name="n">The long to process.</param> /// /// <returns>The factorial.</returns> public static long GetFactorial(long n) { return n > 1 ? n * GetFactorial(n - 1) : 1; } } /// <summary>The always throws.</summary> [DataContract] public class AlwaysThrows { } /// <summary>The always throws response.</summary> [DataContract] public class AlwaysThrowsResponse : IHasResponseStatus { /// <summary>Gets or sets the response status.</summary> /// /// <value>The response status.</value> [DataMember] public ResponseStatus ResponseStatus { get; set; } } /// <summary>The always throws service.</summary> public class AlwaysThrowsService : ServiceInterface.Service { /// <summary>Anies the given request.</summary> /// /// <exception cref="ArgumentException">Thrown when one or more arguments have unsupported or illegal values.</exception> /// /// <param name="request">The request.</param> /// /// <returns>An object.</returns> public object Any(AlwaysThrows request) { throw new ArgumentException("This service always throws an error"); } } /// <summary>A movie.</summary> [Route("/movies", "POST,PUT")] [Route("/movies/{Id}")] [DataContract] public class Movie { /// <summary>Initializes a new instance of the NServiceKit.WebHost.Endpoints.Tests.Support.Host.Movie class.</summary> public Movie() { this.Genres = new List<string>(); } /// <summary>Gets or sets the identifier.</summary> /// /// <value>The identifier.</value> [DataMember(Order = 1)] [AutoIncrement] public int Id { get; set; } /// <summary>Gets or sets the identifier of the imdb.</summary> /// /// <value>The identifier of the imdb.</value> [DataMember(Order = 2)] public string ImdbId { get; set; } /// <summary>Gets or sets the title.</summary> /// /// <value>The title.</value> [DataMember(Order = 3)] public string Title { get; set; } /// <summary>Gets or sets the rating.</summary> /// /// <value>The rating.</value> [DataMember(Order = 4)] public decimal Rating { get; set; } /// <summary>Gets or sets the director.</summary> /// /// <value>The director.</value> [DataMember(Order = 5)] public string Director { get; set; } /// <summary>Gets or sets the release date.</summary> /// /// <value>The release date.</value> [DataMember(Order = 6)] public DateTime ReleaseDate { get; set; } /// <summary>Gets or sets the tag line.</summary> /// /// <value>The tag line.</value> [DataMember(Order = 7)] public string TagLine { get; set; } /// <summary>Gets or sets the genres.</summary> /// /// <value>The genres.</value> [DataMember(Order = 8)] public List<string> Genres { get; set; } #region AutoGen ReSharper code, only required by tests /// <summary>Determines whether the specified <see cref="T:System.Object" /> is equal to the current <see cref="T:System.Object" />.</summary> /// /// <param name="other">The movie to compare to this object.</param> /// /// <returns>true if the specified <see cref="T:System.Object" /> is equal to the current <see cref="T:System.Object" />; otherwise, false.</returns> public bool Equals(Movie other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Equals(other.ImdbId, ImdbId) && Equals(other.Title, Title) && other.Rating == Rating && Equals(other.Director, Director) && other.ReleaseDate.Equals(ReleaseDate) && Equals(other.TagLine, TagLine) && Genres.EquivalentTo(other.Genres); } /// <summary>Determines whether the specified <see cref="T:System.Object" /> is equal to the current <see cref="T:System.Object" />.</summary> /// /// <param name="obj">The object to compare with the current object.</param> /// /// <returns>true if the specified <see cref="T:System.Object" /> is equal to the current <see cref="T:System.Object" />; otherwise, false.</returns> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != typeof(Movie)) return false; return Equals((Movie)obj); } /// <summary>Serves as a hash function for a particular type.</summary> /// /// <returns>A hash code for the current <see cref="T:System.Object" />.</returns> public override int GetHashCode() { return ImdbId != null ? ImdbId.GetHashCode() : 0; } #endregion } /// <summary>A movie response.</summary> [DataContract] public class MovieResponse { /// <summary>Gets or sets the movie.</summary> /// /// <value>The movie.</value> [DataMember] public Movie Movie { get; set; } } /// <summary>A movie service.</summary> public class MovieService : ServiceInterface.Service { /// <summary>Gets or sets the database factory.</summary> /// /// <value>The database factory.</value> public IDbConnectionFactory DbFactory { get; set; } /// <summary> /// GET /movies/{Id} /// </summary> public object Get(Movie movie) { return new MovieResponse { Movie = DbFactory.Run(db => db.GetById<Movie>(movie.Id)) }; } /// <summary> /// POST /movies /// </summary> public object Post(Movie movie) { var newMovieId = DbFactory.Run(db => { db.Insert(movie); return db.GetLastInsertId(); }); var newMovie = new MovieResponse { Movie = DbFactory.Run(db => db.GetById<Movie>(newMovieId)) }; return new HttpResult(newMovie) { StatusCode = HttpStatusCode.Created, Headers = { { HttpHeaders.Location, this.RequestContext.AbsoluteUri.WithTrailingSlash() + newMovieId } } }; } /// <summary> /// PUT /movies /// </summary> public object Put(Movie movie) { DbFactory.Run(db => db.Save(movie)); return new MovieResponse(); } /// <summary> /// DELETE /movies/{Id} /// </summary> public object Delete(Movie request) { DbFactory.Run(db => db.DeleteById<Movie>(request.Id)); return new MovieResponse(); } } /// <summary>A movies.</summary> [DataContract] [Route("/movies", "GET")] [Route("/movies/genres/{Genre}")] public class Movies { /// <summary>Gets or sets the genre.</summary> /// /// <value>The genre.</value> [DataMember] public string Genre { get; set; } /// <summary>Gets or sets the movie.</summary> /// /// <value>The movie.</value> [DataMember] public Movie Movie { get; set; } } /// <summary>The movies response.</summary> [DataContract] public class MoviesResponse { /// <summary>Initializes a new instance of the NServiceKit.WebHost.Endpoints.Tests.Support.Host.MoviesResponse class.</summary> public MoviesResponse() { Movies = new List<Movie>(); } /// <summary>Gets or sets the movies.</summary> /// /// <value>The movies.</value> [DataMember(Order = 1)] public List<Movie> Movies { get; set; } } /// <summary>The movies service.</summary> public class MoviesService : ServiceInterface.Service { /// <summary> /// GET /movies /// GET /movies/genres/{Genre} /// </summary> public object Get(Movies request) { var response = new MoviesResponse { Movies = request.Genre.IsNullOrEmpty() ? Db.Select<Movie>() : Db.Select<Movie>("Genres LIKE {0}", "%" + request.Genre + "%") }; return response; } } /// <summary>The movies zip.</summary> public class MoviesZip { /// <summary>Gets or sets the genre.</summary> /// /// <value>The genre.</value> public string Genre { get; set; } /// <summary>Gets or sets the movie.</summary> /// /// <value>The movie.</value> public Movie Movie { get; set; } } /// <summary>The movies zip response.</summary> public class MoviesZipResponse { /// <summary>Initializes a new instance of the NServiceKit.WebHost.Endpoints.Tests.Support.Host.MoviesZipResponse class.</summary> public MoviesZipResponse() { Movies = new List<Movie>(); } /// <summary>Gets or sets the movies.</summary> /// /// <value>The movies.</value> public List<Movie> Movies { get; set; } } /// <summary>The movies zip service.</summary> public class MoviesZipService : ServiceInterface.Service { /// <summary>Gets or sets the database factory.</summary> /// /// <value>The database factory.</value> public IDbConnectionFactory DbFactory { get; set; } /// <summary>Gets the given request.</summary> /// /// <param name="request">The request.</param> /// /// <returns>An object.</returns> public object Get(MoviesZip request) { return Post(request); } /// <summary>Post this message.</summary> /// /// <param name="request">The request.</param> /// /// <returns>An object.</returns> public object Post(MoviesZip request) { var response = new MoviesZipResponse { Movies = request.Genre.IsNullOrEmpty() ? DbFactory.Run(db => db.Select<Movie>()) : DbFactory.Run(db => db.Select<Movie>("Genres LIKE {0}", "%" + request.Genre + "%")) }; return RequestContext.ToOptimizedResult(response); } } /// <summary>A reset movies.</summary> [DataContract] [Route("/reset-movies")] public class ResetMovies { } /// <summary>A reset movies response.</summary> [DataContract] public class ResetMoviesResponse : IHasResponseStatus { /// <summary>Initializes a new instance of the NServiceKit.WebHost.Endpoints.Tests.Support.Host.ResetMoviesResponse class.</summary> public ResetMoviesResponse() { this.ResponseStatus = new ResponseStatus(); } /// <summary>Gets or sets the response status.</summary> /// /// <value>The response status.</value> [DataMember] public ResponseStatus ResponseStatus { get; set; } } /// <summary>A reset movies service.</summary> public class ResetMoviesService : ServiceInterface.Service { /// <summary>The top 5 movies.</summary> public static List<Movie> Top5Movies = new List<Movie> { new Movie { ImdbId = "tt0111161", Title = "The Shawshank Redemption", Rating = 9.2m, Director = "Frank Darabont", ReleaseDate = new DateTime(1995,2,17), TagLine = "Fear can hold you prisoner. Hope can set you free.", Genres = new List<string>{"Crime","Drama"}, }, new Movie { ImdbId = "tt0068646", Title = "The Godfather", Rating = 9.2m, Director = "Francis Ford Coppola", ReleaseDate = new DateTime(1972,3,24), TagLine = "An offer you can't refuse.", Genres = new List<string> {"Crime","Drama", "Thriller"}, }, new Movie { ImdbId = "tt1375666", Title = "Inception", Rating = 9.2m, Director = "Christopher Nolan", ReleaseDate = new DateTime(2010,7,16), TagLine = "Your mind is the scene of the crime", Genres = new List<string>{"Action", "Mystery", "Sci-Fi", "Thriller"}, }, new Movie { ImdbId = "tt0071562", Title = "The Godfather: Part II", Rating = 9.0m, Director = "Francis Ford Coppola", ReleaseDate = new DateTime(1974,12,20), Genres = new List<string> {"Crime","Drama", "Thriller"}, }, new Movie { ImdbId = "tt0060196", Title = "The Good, the Bad and the Ugly", Rating = 9.0m, Director = "Sergio Leone", ReleaseDate = new DateTime(1967,12,29), TagLine = "They formed an alliance of hate to steal a fortune in dead man's gold", Genres = new List<string>{"Adventure","Western"}, }, }; /// <summary>Post this message.</summary> /// /// <param name="request">The request.</param> /// /// <returns>An object.</returns> public object Post(ResetMovies request) { const bool overwriteTable = true; Db.CreateTable<Movie>(overwriteTable); Db.SaveAll(Top5Movies); return new ResetMoviesResponse(); } } /// <summary>Encapsulates the result of a get http.</summary> [DataContract] public class GetHttpResult { } /// <summary>A get HTTP result response.</summary> [DataContract] public class GetHttpResultResponse { /// <summary>Gets or sets the result.</summary> /// /// <value>The result.</value> [DataMember] public string Result { get; set; } } /// <summary>A HTTP result service.</summary> public class HttpResultService : IService { /// <summary>Anies the given request.</summary> /// /// <param name="request">The request.</param> /// /// <returns>An object.</returns> public object Any(GetHttpResult request) { var getHttpResultResponse = new GetHttpResultResponse { Result = "result" }; return new HttpResult(getHttpResultResponse); } } /// <summary>An inbox post response request.</summary> [Route("/inbox/{Id}/responses", "GET, PUT, OPTIONS")] public class InboxPostResponseRequest { /// <summary>Gets or sets the identifier.</summary> /// /// <value>The identifier.</value> public int Id { get; set; } /// <summary>Gets or sets the responses.</summary> /// /// <value>The responses.</value> public List<PageElementResponseDTO> Responses { get; set; } } /// <summary>An inbox post response request response.</summary> public class InboxPostResponseRequestResponse { /// <summary>Gets or sets the identifier.</summary> /// /// <value>The identifier.</value> public int Id { get; set; } /// <summary>Gets or sets the responses.</summary> /// /// <value>The responses.</value> public List<PageElementResponseDTO> Responses { get; set; } } /// <summary>A page element response dto.</summary> public class PageElementResponseDTO { /// <summary>Gets or sets the identifier of the page element.</summary> /// /// <value>The identifier of the page element.</value> public int PageElementId { get; set; } /// <summary>Gets or sets the type of the page element.</summary> /// /// <value>The type of the page element.</value> public string PageElementType { get; set; } /// <summary>Gets or sets the page element response.</summary> /// /// <value>The page element response.</value> public string PageElementResponse { get; set; } } /// <summary>An inbox post response request service.</summary> public class InboxPostResponseRequestService : ServiceInterface.Service { /// <summary>Anies the given request.</summary> /// /// <exception cref="ArgumentNullException">Thrown when one or more required arguments are null.</exception> /// /// <param name="request">The request.</param> /// /// <returns>An object.</returns> public object Any(InboxPostResponseRequest request) { if (request.Responses == null || request.Responses.Count == 0) { throw new ArgumentNullException("Responses"); } return new InboxPostResponseRequestResponse { Id = request.Id, Responses = request.Responses }; } } /// <summary>An inbox post.</summary> [Route("/inbox/{Id}/responses", "GET, PUT, OPTIONS")] public class InboxPost { /// <summary>Gets or sets a value indicating whether the throw.</summary> /// /// <value>true if throw, false if not.</value> public bool Throw { get; set; } /// <summary>Gets or sets the identifier.</summary> /// /// <value>The identifier.</value> public int Id { get; set; } } /// <summary>An inbox post service.</summary> public class InboxPostService : ServiceInterface.Service { /// <summary>Anies the given request.</summary> /// /// <exception cref="ArgumentNullException">Thrown when one or more required arguments are null.</exception> /// /// <param name="request">The request.</param> /// /// <returns>An object.</returns> public object Any(InboxPost request) { if (request.Throw) throw new ArgumentNullException("Throw"); return null; } } /// <summary>A long running.</summary> [DataContract] [Route("/long_running")] public class LongRunning { } /// <summary>A long running service.</summary> public class LongRunningService : ServiceInterface.Service { /// <summary>Anies the given request.</summary> /// /// <param name="request">The request.</param> /// /// <returns>An object.</returns> public object Any(LongRunning request) { Thread.Sleep(5000); return "LongRunning done."; } } /// <summary>An example application host HTTP listener.</summary> public class ExampleAppHostHttpListener : AppHostHttpListenerBase { //private static ILog log; /// <summary>Initializes a new instance of the NServiceKit.WebHost.Endpoints.Tests.Support.Host.ExampleAppHostHttpListener class.</summary> public ExampleAppHostHttpListener() : base("NServiceKit Examples", typeof(GetFactorialService).Assembly) { LogManager.LogFactory = new DebugLogFactory(); //log = LogManager.GetLogger(typeof(ExampleAppHostHttpListener)); } /// <summary>Gets or sets the configure filter.</summary> /// /// <value>The configure filter.</value> public Action<Container> ConfigureFilter { get; set; } /// <summary>Configures the given container.</summary> /// /// <param name="container">The container.</param> public override void Configure(Container container) { EndpointHostConfig.Instance.GlobalResponseHeaders.Clear(); //Signal advanced web browsers what HTTP Methods you accept base.SetConfig(new EndpointHostConfig { GlobalResponseHeaders = { { "Access-Control-Allow-Origin", "*" }, { "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS" }, }, WsdlServiceNamespace = "http://www.NServiceKit.net/types", LogFactory = new ConsoleLogFactory(), DebugMode = true, }); this.RegisterRequestBinder<CustomRequestBinder>( httpReq => new CustomRequestBinder { IsFromBinder = true }); Routes .Add<Movies>("/custom-movies", "GET") .Add<Movies>("/custom-movies/genres/{Genre}") .Add<Movie>("/custom-movies", "POST,PUT") .Add<Movie>("/custom-movies/{Id}") .Add<GetFactorial>("/fact/{ForNumber}") .Add<MoviesZip>("/movies.zip") .Add<GetHttpResult>("/gethttpresult") ; container.Register<IResourceManager>(new ConfigurationResourceManager()); //var appSettings = container.Resolve<IResourceManager>(); container.Register(c => new ExampleConfig(c.Resolve<IResourceManager>())); //var appConfig = container.Resolve<ExampleConfig>(); container.Register<IDbConnectionFactory>(c => new OrmLiteConnectionFactory( ":memory:", false, SqliteOrmLiteDialectProvider.Instance)); var resetMovies = container.Resolve<ResetMoviesService>(); resetMovies.Post(null); //var movies = container.Resolve<IDbConnectionFactory>().Exec(x => x.Select<Movie>()); //Console.WriteLine(movies.Dump()); if (ConfigureFilter != null) { ConfigureFilter(container); } Plugins.Add(new ProtoBufFormat()); Plugins.Add(new RequestInfoFeature()); } } /// <summary>An example application host HTTP listener long running.</summary> public class ExampleAppHostHttpListenerLongRunning : AppHostHttpListenerLongRunningBase { //private static ILog log; /// <summary>Initializes a new instance of the NServiceKit.WebHost.Endpoints.Tests.Support.Host.ExampleAppHostHttpListenerLongRunning class.</summary> public ExampleAppHostHttpListenerLongRunning() : base("NServiceKit Examples", 500, typeof(GetFactorialService).Assembly) { LogManager.LogFactory = new DebugLogFactory(); //log = LogManager.GetLogger(typeof(ExampleAppHostHttpListener)); } /// <summary>Gets or sets the configure filter.</summary> /// /// <value>The configure filter.</value> public Action<Container> ConfigureFilter { get; set; } /// <summary>Configures the given container.</summary> /// /// <param name="container">The container.</param> public override void Configure(Container container) { EndpointHostConfig.Instance.GlobalResponseHeaders.Clear(); //Signal advanced web browsers what HTTP Methods you accept base.SetConfig(new EndpointHostConfig { GlobalResponseHeaders = { { "Access-Control-Allow-Origin", "*" }, { "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS" }, }, WsdlServiceNamespace = "http://www.NServiceKit.net/types", LogFactory = new ConsoleLogFactory(), DebugMode = true, }); this.RegisterRequestBinder<CustomRequestBinder>( httpReq => new CustomRequestBinder { IsFromBinder = true }); Routes .Add<Movies>("/custom-movies", "GET") .Add<Movies>("/custom-movies/genres/{Genre}") .Add<Movie>("/custom-movies", "POST,PUT") .Add<Movie>("/custom-movies/{Id}") .Add<GetFactorial>("/fact/{ForNumber}") .Add<MoviesZip>("/movies.zip") .Add<GetHttpResult>("/gethttpresult") ; container.Register<IResourceManager>(new ConfigurationResourceManager()); //var appSettings = container.Resolve<IResourceManager>(); container.Register(c => new ExampleConfig(c.Resolve<IResourceManager>())); //var appConfig = container.Resolve<ExampleConfig>(); container.Register<IDbConnectionFactory>(c => new OrmLiteConnectionFactory( ":memory:", false, SqliteOrmLiteDialectProvider.Instance)); var resetMovies = container.Resolve<ResetMoviesService>(); resetMovies.Post(null); //var movies = container.Resolve<IDbConnectionFactory>().Exec(x => x.Select<Movie>()); //Console.WriteLine(movies.Dump()); if (ConfigureFilter != null) { ConfigureFilter(container); } Plugins.Add(new RequestInfoFeature()); } } }
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; //using System.Runtime.InteropServices; public class FacetrackingManager : MonoBehaviour { // Public bool to determine whether to track face model data or not public bool getFaceModelData = true; // Public Bool to determine whether to display face rectangle on the GUI public bool displayFaceRect = true; // Tolerance (in seconds) allowed to miss the tracked face before losing it public float faceTrackingTolerance = 0.25f; // The game object that will be used to display the face model mesh public GameObject faceModelMesh = null; // Public Bool to determine whether the model mesh should be mirrored or not public bool mirroredModelMesh = true; // GUI Text to show messages. public GameObject debugText; // Is currently tracking user's face private bool isTrackingFace = false; private float lastFaceTrackedTime = 0f; // Skeleton ID of the tracked face //private long faceTrackingID = 0; // Animation units private Dictionary<KinectInterop.FaceShapeAnimations, float> dictAU = new Dictionary<KinectInterop.FaceShapeAnimations, float>(); private bool bGotAU = false; // Shape units private Dictionary<KinectInterop.FaceShapeDeformations, float> dictSU = new Dictionary<KinectInterop.FaceShapeDeformations, float>(); private bool bGotSU = false; // whether the face model mesh was initialized private bool bFaceModelMeshInited = false; // Vertices of the face model private Vector3[] avModelVertices = null; private bool bGotModelVertices = false; // Head position and rotation private Vector3 headPos = Vector3.zero; private bool bGotHeadPos = false; private Quaternion headRot = Quaternion.identity; private bool bGotHeadRot = false; // Tracked face rectangle // private Rect faceRect; // private bool bGotFaceRect; // primary user ID, as reported by KinectManager private long primaryUserID = 0; // primary sensor data structure private KinectInterop.SensorData sensorData = null; // Bool to keep track of whether Kinect and FT-library have been initialized private bool isFacetrackingInitialized = false; // The single instance of FacetrackingManager private static FacetrackingManager instance; // returns the single FacetrackingManager instance public static FacetrackingManager Instance { get { return instance; } } // returns true if SAPI is successfully initialized, false otherwise public bool IsFacetrackingInitialized() { return isFacetrackingInitialized; } // returns true if the facetracking system is tracking a face public bool IsTrackingFace() { return isTrackingFace; } // returns the skeleton ID of the tracked user, or 0 if no user was associated with the face public long GetFaceTrackingID() { return isTrackingFace ? primaryUserID : 0; } // returns true if the the face of the specified user is being tracked, false otherwise public bool IsTrackingFace(long userId) { if(sensorData != null && sensorData.sensorInterface != null) { return sensorData.sensorInterface.IsFaceTracked(userId); } return false; } // returns the tracked head position public Vector3 GetHeadPosition(bool bMirroredMovement) { Vector3 vHeadPos = bGotHeadPos ? headPos : Vector3.zero; if(!bMirroredMovement) { vHeadPos.z = -vHeadPos.z; } return vHeadPos; } // returns the tracked head position for the specified user public Vector3 GetHeadPosition(long userId, bool bMirroredMovement) { Vector3 vHeadPos = Vector3.zero; bool bGotPosition = sensorData.sensorInterface.GetHeadPosition(userId, ref vHeadPos); if(bGotPosition) { if(!bMirroredMovement) { vHeadPos.z = -vHeadPos.z; } return vHeadPos; } return Vector3.zero; } // returns the tracked head rotation public Quaternion GetHeadRotation(bool bMirroredMovement) { Vector3 rotAngles = bGotHeadRot ? headRot.eulerAngles : Vector3.zero; if(bMirroredMovement) { rotAngles.x = -rotAngles.x; rotAngles.z = -rotAngles.z; } else { rotAngles.x = -rotAngles.x; rotAngles.y = -rotAngles.y; } return Quaternion.Euler(rotAngles); } // returns the tracked head rotation for the specified user public Quaternion GetHeadRotation(long userId, bool bMirroredMovement) { Quaternion vHeadRot = Quaternion.identity; bool bGotRotation = sensorData.sensorInterface.GetHeadRotation(userId, ref vHeadRot); if(bGotRotation) { Vector3 rotAngles = vHeadRot.eulerAngles; if(bMirroredMovement) { rotAngles.x = -rotAngles.x; rotAngles.z = -rotAngles.z; } else { rotAngles.x = -rotAngles.x; rotAngles.y = -rotAngles.y; } return Quaternion.Euler(rotAngles); } return Quaternion.identity; } // returns true if there are valid anim units public bool IsGotAU() { return bGotAU; } // returns the animation unit at given index, or 0 if the index is invalid public float GetAnimUnit(KinectInterop.FaceShapeAnimations faceAnimKey) { if(dictAU.ContainsKey(faceAnimKey)) { return dictAU[faceAnimKey]; } return 0.0f; } // gets all animation units for the specified user. returns true if the user's face is tracked, false otherwise public bool GetUserAnimUnits(long userId, ref Dictionary<KinectInterop.FaceShapeAnimations, float> dictAnimUnits) { if(sensorData != null && sensorData.sensorInterface != null) { bool bGotIt = sensorData.sensorInterface.GetAnimUnits(userId, ref dictAnimUnits); return bGotIt; } return false; } // returns true if there are valid shape units public bool IsGotSU() { return bGotSU; } // returns the shape unit at given index, or 0 if the index is invalid public float GetShapeUnit(KinectInterop.FaceShapeDeformations faceShapeKey) { if(dictSU.ContainsKey(faceShapeKey)) { return dictSU[faceShapeKey]; } return 0.0f; } // gets all animation units for the specified user. returns true if the user's face is tracked, false otherwise public bool GetUserShapeUnits(long userId, ref Dictionary<KinectInterop.FaceShapeDeformations, float> dictShapeUnits) { if(sensorData != null && sensorData.sensorInterface != null) { bool bGotIt = sensorData.sensorInterface.GetShapeUnits(userId, ref dictShapeUnits); return bGotIt; } return false; } // returns the count of face model vertices public int GetFaceModelVertexCount() { if (bGotModelVertices) { return avModelVertices.Length; } return 0; } // returns the face model vertices, if face model is available and index is in range; Vector3.zero otherwise public Vector3 GetFaceModelVertex(int index) { if (bGotModelVertices) { if(index >= 0 && index < avModelVertices.Length) { return avModelVertices[index]; } } return Vector3.zero; } // returns the face model vertices, if face model is available; null otherwise public Vector3[] GetFaceModelVertices() { if (bGotModelVertices) { return avModelVertices; } return null; } // gets all face model vertices for the specified user. returns true if the user's face is tracked, false otherwise public bool GetUserFaceVertices(long userId, ref Vector3[] avVertices) { if(sensorData != null && sensorData.sensorInterface != null) { bool bGotIt = sensorData.sensorInterface.GetFaceModelVertices(userId, ref avVertices); return bGotIt; } return false; } // returns the face model triangle indices, if face model is available; null otherwise public int[] GetFaceModelTriangleIndices(bool bMirroredModel) { if(sensorData != null && sensorData.sensorInterface != null) { int iNumTriangles = sensorData.sensorInterface.GetFaceModelTrianglesCount(); if(iNumTriangles > 0) { int[] avModelTriangles = new int[iNumTriangles]; bool bGotModelTriangles = sensorData.sensorInterface.GetFaceModelTriangles(bMirroredModel, ref avModelTriangles); if(bGotModelTriangles) { return avModelTriangles; } } } return null; } //----------------------------------- end of public functions --------------------------------------// void Start() { try { // get sensor data KinectManager kinectManager = KinectManager.Instance; if(kinectManager && kinectManager.IsInitialized()) { sensorData = kinectManager.GetSensorData(); } if(sensorData == null || sensorData.sensorInterface == null) { throw new Exception("Face tracking cannot be started, because KinectManager is missing or not initialized."); } if(debugText != null) { debugText.guiText.text = "Please, wait..."; } // ensure the needed dlls are in place bool bNeedRestart = false; if(sensorData.sensorInterface.IsFaceTrackingAvailable(ref bNeedRestart)) { if(bNeedRestart) { // reload the same level GameObject.Destroy(gameObject); Application.LoadLevel(Application.loadedLevel); return; } } else { string sInterfaceName = sensorData.sensorInterface.GetType().Name; throw new Exception(sInterfaceName + ": Face tracking is not supported!"); } // Initialize the face tracker if (!sensorData.sensorInterface.InitFaceTracking(getFaceModelData, displayFaceRect)) { throw new Exception("Face tracking could not be initialized."); } instance = this; isFacetrackingInitialized = true; //DontDestroyOnLoad(gameObject); if(debugText != null) { debugText.guiText.text = "Ready."; } } catch(DllNotFoundException ex) { Debug.LogError(ex.ToString()); if(debugText != null) debugText.guiText.text = "Please check the Kinect and FT-Library installations."; } catch (Exception ex) { Debug.LogError(ex.ToString()); if(debugText != null) debugText.guiText.text = ex.Message; } } void OnDestroy() { if(isFacetrackingInitialized && sensorData != null && sensorData.sensorInterface != null) { // finish face tracking if(sensorData != null && sensorData.sensorInterface != null) { sensorData.sensorInterface.FinishFaceTracking(); } isFacetrackingInitialized = false; instance = null; } } void Update() { if(isFacetrackingInitialized) { KinectManager kinectManager = KinectManager.Instance; if(kinectManager && kinectManager.IsInitialized()) { primaryUserID = kinectManager.GetPrimaryUserID(); } // update the face tracker if(sensorData.sensorInterface.UpdateFaceTracking()) { // estimate the tracking state isTrackingFace = sensorData.sensorInterface.IsFaceTracked(primaryUserID); // get the facetracking parameters if(isTrackingFace) { lastFaceTrackedTime = Time.realtimeSinceStartup; // get face rectangle //bGotFaceRect = sensorData.sensorInterface.GetFaceRect(primaryUserID, ref faceRect); // get head position bGotHeadPos = sensorData.sensorInterface.GetHeadPosition(primaryUserID, ref headPos); // get head rotation bGotHeadRot = sensorData.sensorInterface.GetHeadRotation(primaryUserID, ref headRot); // get the animation units bGotAU = sensorData.sensorInterface.GetAnimUnits(primaryUserID, ref dictAU); // get the shape units bGotSU = sensorData.sensorInterface.GetShapeUnits(primaryUserID, ref dictSU); if(faceModelMesh != null && faceModelMesh.activeInHierarchy) { // apply model vertices to the mesh if(!bFaceModelMeshInited) { CreateFaceModelMesh(); } } if(getFaceModelData) { UpdateFaceModelMesh(); } } else if((Time.realtimeSinceStartup - lastFaceTrackedTime) <= faceTrackingTolerance) { // allow tolerance in tracking isTrackingFace = true; } } } } void OnGUI() { if(isFacetrackingInitialized) { if(debugText != null) { if(isTrackingFace) { debugText.guiText.text = "Tracking - skeletonID: " + primaryUserID; } else { debugText.guiText.text = "Not tracking..."; } } } } private void CreateFaceModelMesh() { if(faceModelMesh == null) return; int iNumTriangles = sensorData.sensorInterface.GetFaceModelTrianglesCount(); if(iNumTriangles <= 0) return; int[] avModelTriangles = new int[iNumTriangles]; bool bGotModelTriangles = sensorData.sensorInterface.GetFaceModelTriangles(mirroredModelMesh, ref avModelTriangles); if(!bGotModelTriangles) return; int iNumVertices = sensorData.sensorInterface.GetFaceModelVerticesCount(0); if(iNumVertices < 0) return; avModelVertices = new Vector3[iNumVertices]; bGotModelVertices = sensorData.sensorInterface.GetFaceModelVertices(0, ref avModelVertices); if(!bGotModelVertices) return; Vector2[] avModelUV = new Vector2[iNumVertices]; //Quaternion faceModelRot = faceModelMesh.transform.rotation; //faceModelMesh.transform.rotation = Quaternion.identity; Mesh mesh = new Mesh(); mesh.name = "FaceMesh"; faceModelMesh.GetComponent<MeshFilter>().mesh = mesh; mesh.vertices = avModelVertices; mesh.uv = avModelUV; mesh.triangles = avModelTriangles; mesh.RecalculateNormals(); //faceModelMesh.transform.rotation = faceModelRot; bFaceModelMeshInited = true; } private void UpdateFaceModelMesh() { // init the vertices array if needed if(avModelVertices == null) { int iNumVertices = sensorData.sensorInterface.GetFaceModelVerticesCount(primaryUserID); avModelVertices = new Vector3[iNumVertices]; } // get face model vertices bGotModelVertices = sensorData.sensorInterface.GetFaceModelVertices(primaryUserID, ref avModelVertices); if(bGotModelVertices && faceModelMesh != null && bFaceModelMeshInited) { //Quaternion faceModelRot = faceModelMesh.transform.rotation; //faceModelMesh.transform.rotation = Quaternion.identity; Mesh mesh = faceModelMesh.GetComponent<MeshFilter>().mesh; mesh.vertices = avModelVertices; mesh.RecalculateNormals(); //faceModelMesh.transform.rotation = faceModelRot; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace Kappa.RestServices.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.Collections.Generic; using Void = lox.Util.Void; using static lox.TokenType; namespace lox { class Interpreter : Expr.IVisitor<object>, Stmt.IVisitor<Void> { readonly Environment globals = new Environment(); readonly Dictionary<Expr, int> locals = new Dictionary<Expr, int>(); Environment environment; public Environment Globals => globals; bool IsTruthy(object value) { if (value is null) return false; if (value is bool boolValue) return boolValue; return true; } bool IsEqual(object a, object b) { if (a == null && b == null) return true; if (a == null) return false; return a.Equals(b); } void CheckNumberOperand(Token op, object operand) { if (operand is double) return; throw new RuntimeException(op, "Operand must be a number."); } void CheckNumberOperands(Token op, object left, object right) { if (left is double && right is double) return; throw new RuntimeException(op, "Operands must be numbers."); } object LookupVariable(Token name, Expr expr) { if (locals.TryGetValue(expr, out var distance)) return environment.LookupAt(distance, name.Lexeme); else return globals.Lookup(name); } public string Stringify(object value) { if (value == null) return "nil"; return value.ToString(); } public void Resolve(Expr expr, int depth) => locals[expr] = depth; public object Evaluate(Expr expr) => expr.Accept(this); public void Execute(Stmt statement) => statement.Accept(this); public void ExecuteBlock(IEnumerable<Stmt> statements, Environment environment) { var previous = this.environment; try { this.environment = environment; foreach (var stmt in statements) Execute(stmt); } finally { this.environment = previous; } } public void Interpret(IEnumerable<Stmt> statements) { try { foreach (var stmt in statements) Execute(stmt); } catch (RuntimeException exc) { Program.RuntimeError(exc); } } public object Interpret(Expr expression) { try { return Evaluate(expression); } catch (RuntimeException exc) { Program.RuntimeError(exc); return null; } } public void Interpret(Stmt statement) { try { Execute(statement); } catch (RuntimeException exc) { Program.RuntimeError(exc); } } object Expr.IVisitor<object>.VisitLiteralExpr(Expr.Literal expr) => expr.Value; object Expr.IVisitor<object>.VisitLogicalExpr(Expr.Logical expr) { var left = Evaluate(expr.Left); if (expr.Op.Type == Or) { if (IsTruthy(left)) return left; } else { if (!IsTruthy(left)) return left; } return Evaluate(expr.Right); } object Expr.IVisitor<object>.VisitGroupingExpr(Expr.Grouping expr) => Evaluate(expr.Expression); object Expr.IVisitor<object>.VisitUnaryExpr(Expr.Unary expr) { var right = Evaluate(expr.Right); switch (expr.Op.Type) { case Minus: CheckNumberOperand(expr.Op, right); return -(double)right; case Bang: return !IsTruthy(right); } // Unreachable return null; } object Expr.IVisitor<object>.VisitVariableExpr(Expr.Variable expr) { return LookupVariable(expr.Name, expr); } object Expr.IVisitor<object>.VisitBinaryExpr(Expr.Binary expr) { var right = Evaluate(expr.Right); var left = Evaluate(expr.Left); switch (expr.Op.Type) { case Minus: CheckNumberOperands(expr.Op, left, right); return (double)left - (double)right; case Slash: CheckNumberOperands(expr.Op, left, right); if ((double)right == 0) throw new RuntimeException(expr.Op, "Division by zero."); return (double)left / (double)right; case Star: CheckNumberOperands(expr.Op, left, right); return (double)left * (double)right; case Plus: if (left is double && right is double) return (double)left + (double)right; if (left is string && right is string) return (string)left + (string)right; throw new RuntimeException(expr.Op, "Operands must be two numbers or two strings."); case Greater: CheckNumberOperands(expr.Op, left, right); return (double)left > (double)right; case GreaterEqual: CheckNumberOperands(expr.Op, left, right); return (double)left >= (double)right; case Less: CheckNumberOperands(expr.Op, left, right); return (double)left < (double)right; case LessEqual: CheckNumberOperands(expr.Op, left, right); return (double)left <= (double)right; case BangEqual: return !IsEqual(left, right); case EqualEqual: return IsEqual(left, right); } // Unreachable return null; } object Expr.IVisitor<object>.VisitCallExpr(Expr.Call expr) { var callee = Evaluate(expr.Callee); var arguments = new List<object>(); foreach (var argument in expr.Arguments) arguments.Add(Evaluate(argument)); if (callee is ICallable function) { if (arguments.Count != function.Arity) throw new RuntimeException(expr.Paren, $"Expected {function.Arity} arguments but got {arguments.Count}."); return function.Call(this, arguments); } else throw new RuntimeException(expr.Paren, "Can only call functions and classes."); } object Expr.IVisitor<object>.VisitTernaryExpr(Expr.Ternary expr) { var condValue = Evaluate(expr.Cond); if (IsTruthy(condValue)) return Evaluate(expr.Left); else return Evaluate(expr.Right); } object Expr.IVisitor<object>.VisitAssignExpr(Expr.Assign expr) { var value = Evaluate(expr.Value); if (locals.TryGetValue(expr, out var distance)) environment.AssignAt(distance, expr.Name, value); else globals.Assign(expr.Name, value); return value; } Void Stmt.IVisitor<Void>.VisitBreakStmt(Stmt.Break stmt) { throw new BreakStatement(); } Void Stmt.IVisitor<Void>.VisitExpressionStmt(Stmt.Expression stmt) { Evaluate(stmt.Expr); return null; } Void Stmt.IVisitor<Void>.VisitFunctionStmt(Stmt.Function stmt) { var function = new Function(stmt, environment); environment.Define(stmt.Name.Lexeme, function); return null; } Void Stmt.IVisitor<Void>.VisitIfStmt(Stmt.If stmt) { if (IsTruthy(Evaluate(stmt.Cond))) Execute(stmt.ThenBranch); else if (stmt.ElseBranch != null) Execute(stmt.ElseBranch); return null; } Void Stmt.IVisitor<Void>.VisitPrintStmt(Stmt.Print stmt) { var value = Evaluate(stmt.Expr); Console.WriteLine(Stringify(value)); return null; } Void Stmt.IVisitor<Void>.VisitReturnStmt(Stmt.Return stmt) { object value = null; if (stmt.Value != null) value = Evaluate(stmt.Value); throw new ReturnStatement(value); } Void Stmt.IVisitor<Void>.VisitVarStmt(Stmt.Var stmt) { object value = null; if (stmt.Initializer != null) value = Evaluate(stmt.Initializer); environment.Define(stmt.Name.Lexeme, value); return null; } Void Stmt.IVisitor<Void>.VisitWhileStmt(Stmt.While stmt) { try { while (IsTruthy(Evaluate(stmt.Cond))) Execute(stmt.Body); } catch (BreakStatement) { } return null; } Void Stmt.IVisitor<Void>.VisitBlockStmt(Stmt.Block stmt) { ExecuteBlock(stmt.Statements, new Environment(environment)); return null; } public Interpreter() { environment = globals; globals.Define("clock", new NativeFunctions.ClockFunction()); } } }