context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.IO; using Xunit; using NMagickWand.Enums; namespace NMagickWand.Tests { public class ContrastTests { const bool KEEP_FILES = false; static readonly string[] _files = Directory.GetFiles("contrast_tests"); [Fact()] [Trait("area", "contrast")] public void SigmoidalTest() { double[] alpha = { 1, 2, 3, 4 }; double[] beta = { 0 , 5000, 20000, 30000, 40000, 65000 }; MagickWandEnvironment.Genesis(); foreach(var file in _files) { using(var wand = new MagickWand(file)) { foreach(var a in alpha) { foreach(var b in beta) { using(var tmp = wand.Clone()) { tmp.SigmoidalContrastImage(true, a, b); WriteImage("sigmoidal", file, new string[] { a.ToString(), b.ToString() }, tmp); } } } } } MagickWandEnvironment.Terminus(); } [Fact()] [Trait("area", "contrast")] public void ContrastTest() { double[] alpha = { 0, .5, 1, 1.1 }; double[] beta = { 0 , 5000, 20000, 30000, 40000, 65000 }; MagickWandEnvironment.Genesis(); foreach(var file in _files) { using(var wand = new MagickWand(file)) { using(var tmp = wand.Clone()) { tmp.ContrastImage(true); WriteImage("contrast", file, new string[] { "1" }, tmp); tmp.ContrastImage(true); WriteImage("contrast", file, new string[] { "2" }, tmp); tmp.ContrastImage(true); WriteImage("contrast", file, new string[] { "3" }, tmp); } } } MagickWandEnvironment.Terminus(); } [Fact()] [Trait("area", "contrast")] public void ContrastStretchTest() { double[] black = { 0, 100, 1000, 2000 }; double[] white = { 0, 50000, 60000, 65000 }; MagickWandEnvironment.Genesis(); foreach(var file in _files) { using(var wand = new MagickWand(file)) { foreach(var b in black) { foreach(var w in white) { using(var tmp = wand.Clone()) { tmp.ContrastStretchImage(b, w); WriteImage("contrast_stretch", file, new string[] { b.ToString(), w.ToString() }, tmp); } } } } } MagickWandEnvironment.Terminus(); } [Fact()] [Trait("area", "contrast")] public void LevelTest() { double[] black = { 0, 100, 1000, 2000 }; double[] white = { 0, 50000, 60000, 65000 }; MagickWandEnvironment.Genesis(); foreach(var file in _files) { using(var wand = new MagickWand(file)) { foreach(var b in black) { foreach(var w in white) { using(var tmp = wand.Clone()) { tmp.LevelImage(b, 1, w); // 1 = no gamma WriteImage("level", file, new string[] { b.ToString(), w.ToString() }, tmp); } } } } } MagickWandEnvironment.Terminus(); } [Fact()] [Trait("area", "contrast")] public void LinearStretchTest() { double[] black = { 0, 100, 1000, 2000 }; double[] white = { 0, 50000, 60000, 65000 }; MagickWandEnvironment.Genesis(); foreach(var file in _files) { using(var wand = new MagickWand(file)) { foreach(var b in black) { foreach(var w in white) { using(var tmp = wand.Clone()) { tmp.LinearStretchImage(b, w); WriteImage("linear_stretch", file, new string[] { b.ToString(), w.ToString() }, tmp); } } } } } MagickWandEnvironment.Terminus(); } [Fact()] [Trait("area", "contrast")] public void ModulateTest() { double[] brightness = { 50, 100, 150 }; double[] saturation = { 0, 100, 120, 150 }; MagickWandEnvironment.Genesis(); foreach(var file in _files) { using(var wand = new MagickWand(file)) { foreach(var b in brightness) { foreach(var s in saturation) { using(var tmp = wand.Clone()) { tmp.ModulateImage(b, s, 300); // 300 = no rotation WriteImage("modulate", file, new string[] { b.ToString(), s.ToString() }, tmp); } } } } } MagickWandEnvironment.Terminus(); } [Fact()] [Trait("area", "contrast")] public void NormalizeTest() { MagickWandEnvironment.Genesis(); foreach(var file in _files) { using(var wand = new MagickWand(file)) { wand.NormalizeImage(); WriteImage("normalize", file, new string[] { }, wand); } } MagickWandEnvironment.Terminus(); } [Fact()] [Trait("area", "contrast")] public void BrightnessContrastTest() { double[] brightness = { 0, 10, 25 }; double[] contrast = { 0, 10, 25 }; MagickWandEnvironment.Genesis(); foreach(var file in _files) { using(var wand = new MagickWand(file)) { foreach(var b in brightness) { foreach(var c in contrast) { using(var tmp = wand.Clone()) { tmp.BrightnessContrastImage(b, c); WriteImage("brightness_contrast", file, new string[] { b.ToString(), c.ToString() }, tmp); } } } } } MagickWandEnvironment.Terminus(); } [Fact()] [Trait("area", "contrast")] public void AutoLevelTest() { MagickWandEnvironment.Genesis(); foreach(var file in _files) { using(var wand = new MagickWand(file)) { wand.AutoLevelImage(); WriteImage("auto_level", file, new string[] { }, wand); } } MagickWandEnvironment.Terminus(); } [Fact()] [Trait("area", "composed")] public void ComposedTest() { var contrastRatioThreshold = 0.5; var tooContrastyThreshold = 1.9; MagickWandEnvironment.Genesis(); PrintStatsHeader(); foreach(var file in _files) { using(var wand = new MagickWand(file)) { double mean, stddev; wand.GetImageChannelMean(ChannelType.AllChannels, out mean, out stddev); PrintStats(file, wand); wand.AutoLevelImage(); var contrastRatio = stddev / mean; var contrastyRatio = stddev / 10000; if(contrastRatio < contrastRatioThreshold) { var saturationAmount = Convert.ToInt32((contrastRatioThreshold - contrastRatio) * 100) * 4; // limit the saturation adjustment to 20% if(saturationAmount > 20) { saturationAmount = 20; } saturationAmount += 100; Console.WriteLine("modulating by: " + saturationAmount); // 100 = don't adjust brightness // 300 = don't rotate hue wand.ModulateImage(100, saturationAmount, 300); } else if(contrastyRatio > tooContrastyThreshold) { Console.WriteLine("attempting to reduce contrast"); wand.SigmoidalContrastImage(true, 2, 0); // smooth brightness/contrast } wand.UnsharpMaskImage(0, 0.7, 0.7, 0.008); // sharpen WriteImage("composed", file, new string[] { }, wand); } } MagickWandEnvironment.Terminus(); } void PrintStatsHeader() { Console.WriteLine("File\tMean\tStdDev\tKurtosis\tSkewness"); } void PrintStats(string file, MagickWand wand) { double mean, stddev, kurtosis, skewness; wand.GetImageChannelMean(ChannelType.AllChannels, out mean, out stddev); wand.GetImageChannelKurtosis(ChannelType.AllChannels, out kurtosis, out skewness); Console.WriteLine($"{Path.GetFileName(file)}\t{mean}\t{stddev}\t{kurtosis}\t{skewness}"); } void WriteImage(string test, string filename, string[] args, MagickWand wand) { var dir = Path.Combine("contrast_tests", test); var file = $"{Path.GetFileNameWithoutExtension(filename)}_{string.Join("_", args)}{Path.GetExtension(filename)}"; var fullPath = Path.Combine(dir, file); Directory.CreateDirectory(dir); wand.WriteImage(fullPath, true); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Text; using System.Diagnostics; using System.Globalization; using System.Collections.Generic; using System.Runtime.InteropServices; using Internal.NativeCrypto; using Internal.Cryptography; using Internal.Cryptography.Pal.Native; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; namespace Internal.Cryptography.Pal { /// <summary> /// A singleton class that encapsulates the native implementation of various X509 services. (Implementing this as a singleton makes it /// easier to split the class into abstract and implementation classes if desired.) /// </summary> internal sealed partial class X509Pal : IX509Pal { public byte[] EncodeX509KeyUsageExtension(X509KeyUsageFlags keyUsages) { unsafe { ushort keyUsagesAsShort = (ushort)keyUsages; CRYPT_BIT_BLOB blob = new CRYPT_BIT_BLOB() { cbData = 2, pbData = (byte*)&keyUsagesAsShort, cUnusedBits = 0, }; return Interop.crypt32.EncodeObject(CryptDecodeObjectStructType.X509_KEY_USAGE, &blob); } } public void DecodeX509KeyUsageExtension(byte[] encoded, out X509KeyUsageFlags keyUsages) { unsafe { uint keyUsagesAsUint = 0; encoded.DecodeObject( CryptDecodeObjectStructType.X509_KEY_USAGE, delegate (void* pvDecoded) { CRYPT_BIT_BLOB* pBlob = (CRYPT_BIT_BLOB*)pvDecoded; keyUsagesAsUint = 0; if (pBlob->pbData != null) { keyUsagesAsUint = *(uint*)(pBlob->pbData); } } ); keyUsages = (X509KeyUsageFlags)keyUsagesAsUint; } } public bool SupportsLegacyBasicConstraintsExtension { get { return true; } } public byte[] EncodeX509BasicConstraints2Extension(bool certificateAuthority, bool hasPathLengthConstraint, int pathLengthConstraint) { unsafe { CERT_BASIC_CONSTRAINTS2_INFO constraintsInfo = new CERT_BASIC_CONSTRAINTS2_INFO() { fCA = certificateAuthority ? 1 : 0, fPathLenConstraint = hasPathLengthConstraint ? 1 : 0, dwPathLenConstraint = pathLengthConstraint, }; return Interop.crypt32.EncodeObject(Oids.BasicConstraints2, &constraintsInfo); } } public void DecodeX509BasicConstraintsExtension(byte[] encoded, out bool certificateAuthority, out bool hasPathLengthConstraint, out int pathLengthConstraint) { unsafe { bool localCertificateAuthority = false; bool localHasPathLengthConstraint = false; int localPathLengthConstraint = 0; encoded.DecodeObject( CryptDecodeObjectStructType.X509_BASIC_CONSTRAINTS, delegate (void* pvDecoded) { CERT_BASIC_CONSTRAINTS_INFO* pBasicConstraints = (CERT_BASIC_CONSTRAINTS_INFO*)pvDecoded; localCertificateAuthority = (pBasicConstraints->SubjectType.pbData[0] & CERT_BASIC_CONSTRAINTS_INFO.CERT_CA_SUBJECT_FLAG) != 0; localHasPathLengthConstraint = pBasicConstraints->fPathLenConstraint != 0; localPathLengthConstraint = pBasicConstraints->dwPathLenConstraint; } ); certificateAuthority = localCertificateAuthority; hasPathLengthConstraint = localHasPathLengthConstraint; pathLengthConstraint = localPathLengthConstraint; } } public void DecodeX509BasicConstraints2Extension(byte[] encoded, out bool certificateAuthority, out bool hasPathLengthConstraint, out int pathLengthConstraint) { unsafe { bool localCertificateAuthority = false; bool localHasPathLengthConstraint = false; int localPathLengthConstraint = 0; encoded.DecodeObject( CryptDecodeObjectStructType.X509_BASIC_CONSTRAINTS2, delegate (void* pvDecoded) { CERT_BASIC_CONSTRAINTS2_INFO* pBasicConstraints2 = (CERT_BASIC_CONSTRAINTS2_INFO*)pvDecoded; localCertificateAuthority = pBasicConstraints2->fCA != 0; localHasPathLengthConstraint = pBasicConstraints2->fPathLenConstraint != 0; localPathLengthConstraint = pBasicConstraints2->dwPathLenConstraint; } ); certificateAuthority = localCertificateAuthority; hasPathLengthConstraint = localHasPathLengthConstraint; pathLengthConstraint = localPathLengthConstraint; } } public byte[] EncodeX509EnhancedKeyUsageExtension(OidCollection usages) { int numUsages; using (SafeHandle usagesSafeHandle = usages.ToLpstrArray(out numUsages)) { unsafe { CERT_ENHKEY_USAGE enhKeyUsage = new CERT_ENHKEY_USAGE() { cUsageIdentifier = numUsages, rgpszUsageIdentifier = (IntPtr*)(usagesSafeHandle.DangerousGetHandle()), }; return Interop.crypt32.EncodeObject(Oids.EnhancedKeyUsage, &enhKeyUsage); } } } public void DecodeX509EnhancedKeyUsageExtension(byte[] encoded, out OidCollection usages) { OidCollection localUsages = new OidCollection(); unsafe { encoded.DecodeObject( CryptDecodeObjectStructType.X509_ENHANCED_KEY_USAGE, delegate (void* pvDecoded) { CERT_ENHKEY_USAGE* pEnhKeyUsage = (CERT_ENHKEY_USAGE*)pvDecoded; int count = pEnhKeyUsage->cUsageIdentifier; for (int i = 0; i < count; i++) { IntPtr oidValuePointer = pEnhKeyUsage->rgpszUsageIdentifier[i]; string oidValue = Marshal.PtrToStringAnsi(oidValuePointer); Oid oid = new Oid(oidValue); localUsages.Add(oid); } } ); } usages = localUsages; } public byte[] EncodeX509SubjectKeyIdentifierExtension(byte[] subjectKeyIdentifier) { unsafe { fixed (byte* pSubkectKeyIdentifier = subjectKeyIdentifier) { CRYPTOAPI_BLOB blob = new CRYPTOAPI_BLOB(subjectKeyIdentifier.Length, pSubkectKeyIdentifier); return Interop.crypt32.EncodeObject(Oids.SubjectKeyIdentifier, &blob); } } } public void DecodeX509SubjectKeyIdentifierExtension(byte[] encoded, out byte[] subjectKeyIdentifier) { unsafe { byte[] localSubjectKeyIdentifier = null; encoded.DecodeObject( Oids.SubjectKeyIdentifier, delegate (void* pvDecoded) { CRYPTOAPI_BLOB* pBlob = (CRYPTOAPI_BLOB*)pvDecoded; localSubjectKeyIdentifier = pBlob->ToByteArray(); } ); subjectKeyIdentifier = localSubjectKeyIdentifier; } } public byte[] ComputeCapiSha1OfPublicKey(PublicKey key) { unsafe { fixed (byte* pszOidValue = key.Oid.ValueAsAscii()) { byte[] encodedParameters = key.EncodedParameters.RawData; fixed (byte* pEncodedParameters = encodedParameters) { byte[] encodedKeyValue = key.EncodedKeyValue.RawData; fixed (byte* pEncodedKeyValue = encodedKeyValue) { CERT_PUBLIC_KEY_INFO publicKeyInfo = new CERT_PUBLIC_KEY_INFO() { Algorithm = new CRYPT_ALGORITHM_IDENTIFIER() { pszObjId = new IntPtr(pszOidValue), Parameters = new CRYPTOAPI_BLOB(encodedParameters.Length, pEncodedParameters), }, PublicKey = new CRYPT_BIT_BLOB() { cbData = encodedKeyValue.Length, pbData = pEncodedKeyValue, cUnusedBits = 0, }, }; int cb = 20; byte[] buffer = new byte[cb]; if (!Interop.crypt32.CryptHashPublicKeyInfo(IntPtr.Zero, AlgId.CALG_SHA1, 0, CertEncodingType.All, ref publicKeyInfo, buffer, ref cb)) throw Marshal.GetHRForLastWin32Error().ToCryptographicException();; if (cb < buffer.Length) { byte[] newBuffer = new byte[cb]; Array.Copy(buffer, 0, newBuffer, 0, cb); buffer = newBuffer; } return buffer; } } } } } } }
// 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 gaxgrpc = Google.Api.Gax.Grpc; using lro = Google.LongRunning; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Compute.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedDisksClientTest { [xunit::FactAttribute] public void GetRequestObject() { moq::Mock<Disks.DisksClient> mockGrpcClient = new moq::Mock<Disks.DisksClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetDiskRequest request = new GetDiskRequest { Disk = "disk028b6875", Zone = "zone255f4ea8", Project = "projectaa6ff846", }; Disk expectedResponse = new Disk { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Type = "typee2cc9d59", Zone = "zone255f4ea8", ResourcePolicies = { "resource_policiesdff15734", }, CreationTimestamp = "creation_timestamp235e59a1", LastAttachTimestamp = "last_attach_timestamp4fe3fe94", LicenseCodes = { -3549522739643304114L, }, ReplicaZones = { "replica_zonesc1977354", }, SourceImage = "source_image5e9c0c38", SourceImageId = "source_image_id954b5e55", LastDetachTimestamp = "last_detach_timestampffef196b", GuestOsFeatures = { new GuestOsFeature(), }, SourceSnapshotId = "source_snapshot_id008ab5dd", Users = { "users2a5cc69b", }, SourceSnapshot = "source_snapshot1fcf3da1", Region = "regionedb20d96", LabelFingerprint = "label_fingerprint06ccff3a", Status = "status5444cb9a", ProvisionedIops = -3779563869670119518L, SourceStorageObject = "source_storage_object4e059972", DiskEncryptionKey = new CustomerEncryptionKey(), SourceSnapshotEncryptionKey = new CustomerEncryptionKey(), Licenses = { "licensesd1cc2f9d", }, LocationHint = "location_hint666f366c", Options = "optionsa965da93", SourceImageEncryptionKey = new CustomerEncryptionKey(), PhysicalBlockSizeBytes = -7292518380745299537L, Description = "description2cf9da67", SourceDisk = "source_disk0eec086f", SourceDiskId = "source_disk_id020f9fb8", SelfLink = "self_link7e87f12d", SatisfiesPzs = false, SizeGb = -3653169847519542788L, Labels = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DisksClient client = new DisksClientImpl(mockGrpcClient.Object, null); Disk response = client.Get(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetRequestObjectAsync() { moq::Mock<Disks.DisksClient> mockGrpcClient = new moq::Mock<Disks.DisksClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetDiskRequest request = new GetDiskRequest { Disk = "disk028b6875", Zone = "zone255f4ea8", Project = "projectaa6ff846", }; Disk expectedResponse = new Disk { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Type = "typee2cc9d59", Zone = "zone255f4ea8", ResourcePolicies = { "resource_policiesdff15734", }, CreationTimestamp = "creation_timestamp235e59a1", LastAttachTimestamp = "last_attach_timestamp4fe3fe94", LicenseCodes = { -3549522739643304114L, }, ReplicaZones = { "replica_zonesc1977354", }, SourceImage = "source_image5e9c0c38", SourceImageId = "source_image_id954b5e55", LastDetachTimestamp = "last_detach_timestampffef196b", GuestOsFeatures = { new GuestOsFeature(), }, SourceSnapshotId = "source_snapshot_id008ab5dd", Users = { "users2a5cc69b", }, SourceSnapshot = "source_snapshot1fcf3da1", Region = "regionedb20d96", LabelFingerprint = "label_fingerprint06ccff3a", Status = "status5444cb9a", ProvisionedIops = -3779563869670119518L, SourceStorageObject = "source_storage_object4e059972", DiskEncryptionKey = new CustomerEncryptionKey(), SourceSnapshotEncryptionKey = new CustomerEncryptionKey(), Licenses = { "licensesd1cc2f9d", }, LocationHint = "location_hint666f366c", Options = "optionsa965da93", SourceImageEncryptionKey = new CustomerEncryptionKey(), PhysicalBlockSizeBytes = -7292518380745299537L, Description = "description2cf9da67", SourceDisk = "source_disk0eec086f", SourceDiskId = "source_disk_id020f9fb8", SelfLink = "self_link7e87f12d", SatisfiesPzs = false, SizeGb = -3653169847519542788L, Labels = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Disk>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DisksClient client = new DisksClientImpl(mockGrpcClient.Object, null); Disk responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Disk responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void Get() { moq::Mock<Disks.DisksClient> mockGrpcClient = new moq::Mock<Disks.DisksClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetDiskRequest request = new GetDiskRequest { Disk = "disk028b6875", Zone = "zone255f4ea8", Project = "projectaa6ff846", }; Disk expectedResponse = new Disk { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Type = "typee2cc9d59", Zone = "zone255f4ea8", ResourcePolicies = { "resource_policiesdff15734", }, CreationTimestamp = "creation_timestamp235e59a1", LastAttachTimestamp = "last_attach_timestamp4fe3fe94", LicenseCodes = { -3549522739643304114L, }, ReplicaZones = { "replica_zonesc1977354", }, SourceImage = "source_image5e9c0c38", SourceImageId = "source_image_id954b5e55", LastDetachTimestamp = "last_detach_timestampffef196b", GuestOsFeatures = { new GuestOsFeature(), }, SourceSnapshotId = "source_snapshot_id008ab5dd", Users = { "users2a5cc69b", }, SourceSnapshot = "source_snapshot1fcf3da1", Region = "regionedb20d96", LabelFingerprint = "label_fingerprint06ccff3a", Status = "status5444cb9a", ProvisionedIops = -3779563869670119518L, SourceStorageObject = "source_storage_object4e059972", DiskEncryptionKey = new CustomerEncryptionKey(), SourceSnapshotEncryptionKey = new CustomerEncryptionKey(), Licenses = { "licensesd1cc2f9d", }, LocationHint = "location_hint666f366c", Options = "optionsa965da93", SourceImageEncryptionKey = new CustomerEncryptionKey(), PhysicalBlockSizeBytes = -7292518380745299537L, Description = "description2cf9da67", SourceDisk = "source_disk0eec086f", SourceDiskId = "source_disk_id020f9fb8", SelfLink = "self_link7e87f12d", SatisfiesPzs = false, SizeGb = -3653169847519542788L, Labels = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DisksClient client = new DisksClientImpl(mockGrpcClient.Object, null); Disk response = client.Get(request.Project, request.Zone, request.Disk); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAsync() { moq::Mock<Disks.DisksClient> mockGrpcClient = new moq::Mock<Disks.DisksClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetDiskRequest request = new GetDiskRequest { Disk = "disk028b6875", Zone = "zone255f4ea8", Project = "projectaa6ff846", }; Disk expectedResponse = new Disk { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Type = "typee2cc9d59", Zone = "zone255f4ea8", ResourcePolicies = { "resource_policiesdff15734", }, CreationTimestamp = "creation_timestamp235e59a1", LastAttachTimestamp = "last_attach_timestamp4fe3fe94", LicenseCodes = { -3549522739643304114L, }, ReplicaZones = { "replica_zonesc1977354", }, SourceImage = "source_image5e9c0c38", SourceImageId = "source_image_id954b5e55", LastDetachTimestamp = "last_detach_timestampffef196b", GuestOsFeatures = { new GuestOsFeature(), }, SourceSnapshotId = "source_snapshot_id008ab5dd", Users = { "users2a5cc69b", }, SourceSnapshot = "source_snapshot1fcf3da1", Region = "regionedb20d96", LabelFingerprint = "label_fingerprint06ccff3a", Status = "status5444cb9a", ProvisionedIops = -3779563869670119518L, SourceStorageObject = "source_storage_object4e059972", DiskEncryptionKey = new CustomerEncryptionKey(), SourceSnapshotEncryptionKey = new CustomerEncryptionKey(), Licenses = { "licensesd1cc2f9d", }, LocationHint = "location_hint666f366c", Options = "optionsa965da93", SourceImageEncryptionKey = new CustomerEncryptionKey(), PhysicalBlockSizeBytes = -7292518380745299537L, Description = "description2cf9da67", SourceDisk = "source_disk0eec086f", SourceDiskId = "source_disk_id020f9fb8", SelfLink = "self_link7e87f12d", SatisfiesPzs = false, SizeGb = -3653169847519542788L, Labels = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Disk>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DisksClient client = new DisksClientImpl(mockGrpcClient.Object, null); Disk responseCallSettings = await client.GetAsync(request.Project, request.Zone, request.Disk, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Disk responseCancellationToken = await client.GetAsync(request.Project, request.Zone, request.Disk, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetIamPolicyRequestObject() { moq::Mock<Disks.DisksClient> mockGrpcClient = new moq::Mock<Disks.DisksClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetIamPolicyDiskRequest request = new GetIamPolicyDiskRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", OptionsRequestedPolicyVersion = -1471234741, }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DisksClient client = new DisksClientImpl(mockGrpcClient.Object, null); Policy response = client.GetIamPolicy(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetIamPolicyRequestObjectAsync() { moq::Mock<Disks.DisksClient> mockGrpcClient = new moq::Mock<Disks.DisksClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetIamPolicyDiskRequest request = new GetIamPolicyDiskRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", OptionsRequestedPolicyVersion = -1471234741, }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DisksClient client = new DisksClientImpl(mockGrpcClient.Object, null); Policy responseCallSettings = await client.GetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Policy responseCancellationToken = await client.GetIamPolicyAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetIamPolicy() { moq::Mock<Disks.DisksClient> mockGrpcClient = new moq::Mock<Disks.DisksClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetIamPolicyDiskRequest request = new GetIamPolicyDiskRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DisksClient client = new DisksClientImpl(mockGrpcClient.Object, null); Policy response = client.GetIamPolicy(request.Project, request.Zone, request.Resource); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetIamPolicyAsync() { moq::Mock<Disks.DisksClient> mockGrpcClient = new moq::Mock<Disks.DisksClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetIamPolicyDiskRequest request = new GetIamPolicyDiskRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DisksClient client = new DisksClientImpl(mockGrpcClient.Object, null); Policy responseCallSettings = await client.GetIamPolicyAsync(request.Project, request.Zone, request.Resource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Policy responseCancellationToken = await client.GetIamPolicyAsync(request.Project, request.Zone, request.Resource, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SetIamPolicyRequestObject() { moq::Mock<Disks.DisksClient> mockGrpcClient = new moq::Mock<Disks.DisksClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SetIamPolicyDiskRequest request = new SetIamPolicyDiskRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", ZoneSetPolicyRequestResource = new ZoneSetPolicyRequest(), }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DisksClient client = new DisksClientImpl(mockGrpcClient.Object, null); Policy response = client.SetIamPolicy(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SetIamPolicyRequestObjectAsync() { moq::Mock<Disks.DisksClient> mockGrpcClient = new moq::Mock<Disks.DisksClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SetIamPolicyDiskRequest request = new SetIamPolicyDiskRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", ZoneSetPolicyRequestResource = new ZoneSetPolicyRequest(), }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DisksClient client = new DisksClientImpl(mockGrpcClient.Object, null); Policy responseCallSettings = await client.SetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Policy responseCancellationToken = await client.SetIamPolicyAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SetIamPolicy() { moq::Mock<Disks.DisksClient> mockGrpcClient = new moq::Mock<Disks.DisksClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SetIamPolicyDiskRequest request = new SetIamPolicyDiskRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", ZoneSetPolicyRequestResource = new ZoneSetPolicyRequest(), }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DisksClient client = new DisksClientImpl(mockGrpcClient.Object, null); Policy response = client.SetIamPolicy(request.Project, request.Zone, request.Resource, request.ZoneSetPolicyRequestResource); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SetIamPolicyAsync() { moq::Mock<Disks.DisksClient> mockGrpcClient = new moq::Mock<Disks.DisksClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SetIamPolicyDiskRequest request = new SetIamPolicyDiskRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", ZoneSetPolicyRequestResource = new ZoneSetPolicyRequest(), }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DisksClient client = new DisksClientImpl(mockGrpcClient.Object, null); Policy responseCallSettings = await client.SetIamPolicyAsync(request.Project, request.Zone, request.Resource, request.ZoneSetPolicyRequestResource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Policy responseCancellationToken = await client.SetIamPolicyAsync(request.Project, request.Zone, request.Resource, request.ZoneSetPolicyRequestResource, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void TestIamPermissionsRequestObject() { moq::Mock<Disks.DisksClient> mockGrpcClient = new moq::Mock<Disks.DisksClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TestIamPermissionsDiskRequest request = new TestIamPermissionsDiskRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DisksClient client = new DisksClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse response = client.TestIamPermissions(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task TestIamPermissionsRequestObjectAsync() { moq::Mock<Disks.DisksClient> mockGrpcClient = new moq::Mock<Disks.DisksClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TestIamPermissionsDiskRequest request = new TestIamPermissionsDiskRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DisksClient client = new DisksClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TestPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void TestIamPermissions() { moq::Mock<Disks.DisksClient> mockGrpcClient = new moq::Mock<Disks.DisksClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TestIamPermissionsDiskRequest request = new TestIamPermissionsDiskRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DisksClient client = new DisksClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse response = client.TestIamPermissions(request.Project, request.Zone, request.Resource, request.TestPermissionsRequestResource); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task TestIamPermissionsAsync() { moq::Mock<Disks.DisksClient> mockGrpcClient = new moq::Mock<Disks.DisksClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TestIamPermissionsDiskRequest request = new TestIamPermissionsDiskRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DisksClient client = new DisksClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request.Project, request.Zone, request.Resource, request.TestPermissionsRequestResource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TestPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request.Project, request.Zone, request.Resource, request.TestPermissionsRequestResource, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
// 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.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { internal delegate BoundStatement GenerateMethodBody(EEMethodSymbol method, DiagnosticBag diagnostics, out ImmutableArray<LocalSymbol> declaredLocals); /// <summary> /// Synthesized expression evaluation method. /// </summary> internal sealed class EEMethodSymbol : MethodSymbol { // We only create a single EE method (per EE type) that represents an arbitrary expression, // whose lowering may produce synthesized members (lambdas, dynamic sites, etc). // We may thus assume that the method ordinal is always 0. // // Consider making the implementation more flexible in order to avoid this assumption. // In future we might need to compile multiple expression and then we'll need to assign // a unique method ordinal to each of them to avoid duplicate synthesized member names. private const int _methodOrdinal = 0; internal readonly TypeMap TypeMap; internal readonly MethodSymbol SubstitutedSourceMethod; internal readonly ImmutableArray<LocalSymbol> Locals; internal readonly ImmutableArray<LocalSymbol> LocalsForBinding; private readonly EENamedTypeSymbol _container; private readonly string _name; private readonly ImmutableArray<Location> _locations; private readonly ImmutableArray<TypeParameterSymbol> _typeParameters; private readonly ImmutableArray<ParameterSymbol> _parameters; private readonly ParameterSymbol _thisParameter; private readonly ImmutableDictionary<string, DisplayClassVariable> _displayClassVariables; /// <summary> /// Invoked at most once to generate the method body. /// (If the compilation has no errors, it will be invoked /// exactly once, otherwise it may be skipped.) /// </summary> private readonly GenerateMethodBody _generateMethodBody; private TypeSymbol _lazyReturnType; // NOTE: This is only used for asserts, so it could be conditional on DEBUG. private readonly ImmutableArray<TypeParameterSymbol> _allTypeParameters; internal EEMethodSymbol( EENamedTypeSymbol container, string name, Location location, MethodSymbol sourceMethod, ImmutableArray<LocalSymbol> sourceLocals, ImmutableArray<LocalSymbol> sourceLocalsForBinding, ImmutableDictionary<string, DisplayClassVariable> sourceDisplayClassVariables, GenerateMethodBody generateMethodBody) { Debug.Assert(sourceMethod.IsDefinition); Debug.Assert(sourceMethod.ContainingSymbol == container.SubstitutedSourceType.OriginalDefinition); Debug.Assert(sourceLocals.All(l => l.ContainingSymbol == sourceMethod)); _container = container; _name = name; _locations = ImmutableArray.Create(location); // What we want is to map all original type parameters to the corresponding new type parameters // (since the old ones have the wrong owners). Unfortunately, we have a circular dependency: // 1) Each new type parameter requires the entire map in order to be able to construct its constraint list. // 2) The map cannot be constructed until all new type parameters exist. // Our solution is to pass each new type parameter a lazy reference to the type map. We then // initialize the map as soon as the new type parameters are available - and before they are // handed out - so that there is never a period where they can require the type map and find // it uninitialized. var sourceMethodTypeParameters = sourceMethod.TypeParameters; var allSourceTypeParameters = container.SourceTypeParameters.Concat(sourceMethodTypeParameters); var getTypeMap = new Func<TypeMap>(() => this.TypeMap); _typeParameters = sourceMethodTypeParameters.SelectAsArray( (tp, i, arg) => (TypeParameterSymbol)new EETypeParameterSymbol(this, tp, i, getTypeMap), (object)null); _allTypeParameters = container.TypeParameters.Concat(_typeParameters); this.TypeMap = new TypeMap(allSourceTypeParameters, _allTypeParameters); EENamedTypeSymbol.VerifyTypeParameters(this, _typeParameters); var substitutedSourceType = container.SubstitutedSourceType; this.SubstitutedSourceMethod = sourceMethod.AsMember(substitutedSourceType); if (sourceMethod.Arity > 0) { this.SubstitutedSourceMethod = this.SubstitutedSourceMethod.Construct(_typeParameters.As<TypeSymbol>()); } TypeParameterChecker.Check(this.SubstitutedSourceMethod, _allTypeParameters); // Create a map from original parameter to target parameter. var parameterBuilder = ArrayBuilder<ParameterSymbol>.GetInstance(); var substitutedSourceThisParameter = this.SubstitutedSourceMethod.ThisParameter; var substitutedSourceHasThisParameter = (object)substitutedSourceThisParameter != null; if (substitutedSourceHasThisParameter) { _thisParameter = MakeParameterSymbol(0, GeneratedNames.ThisProxyFieldName(), substitutedSourceThisParameter); Debug.Assert(_thisParameter.Type == this.SubstitutedSourceMethod.ContainingType); parameterBuilder.Add(_thisParameter); } var ordinalOffset = (substitutedSourceHasThisParameter ? 1 : 0); foreach (var substitutedSourceParameter in this.SubstitutedSourceMethod.Parameters) { var ordinal = substitutedSourceParameter.Ordinal + ordinalOffset; Debug.Assert(ordinal == parameterBuilder.Count); var parameter = MakeParameterSymbol(ordinal, substitutedSourceParameter.Name, substitutedSourceParameter); parameterBuilder.Add(parameter); } _parameters = parameterBuilder.ToImmutableAndFree(); var localsBuilder = ArrayBuilder<LocalSymbol>.GetInstance(); var localsMap = PooledDictionary<LocalSymbol, LocalSymbol>.GetInstance(); foreach (var sourceLocal in sourceLocals) { var local = sourceLocal.ToOtherMethod(this, this.TypeMap); localsMap.Add(sourceLocal, local); localsBuilder.Add(local); } this.Locals = localsBuilder.ToImmutableAndFree(); localsBuilder = ArrayBuilder<LocalSymbol>.GetInstance(); foreach (var sourceLocal in sourceLocalsForBinding) { LocalSymbol local; if (!localsMap.TryGetValue(sourceLocal, out local)) { local = sourceLocal.ToOtherMethod(this, this.TypeMap); localsMap.Add(sourceLocal, local); } localsBuilder.Add(local); } this.LocalsForBinding = localsBuilder.ToImmutableAndFree(); // Create a map from variable name to display class field. var displayClassVariables = PooledDictionary<string, DisplayClassVariable>.GetInstance(); foreach (var pair in sourceDisplayClassVariables) { var variable = pair.Value; var oldDisplayClassInstance = variable.DisplayClassInstance; // Note: we don't call ToOtherMethod in the local case because doing so would produce // a new LocalSymbol that would not be ReferenceEquals to the one in this.LocalsForBinding. var oldDisplayClassInstanceFromLocal = oldDisplayClassInstance as DisplayClassInstanceFromLocal; var newDisplayClassInstance = (oldDisplayClassInstanceFromLocal == null) ? oldDisplayClassInstance.ToOtherMethod(this, this.TypeMap) : new DisplayClassInstanceFromLocal((EELocalSymbol)localsMap[oldDisplayClassInstanceFromLocal.Local]); variable = variable.SubstituteFields(newDisplayClassInstance, this.TypeMap); displayClassVariables.Add(pair.Key, variable); } _displayClassVariables = displayClassVariables.ToImmutableDictionary(); displayClassVariables.Free(); localsMap.Free(); _generateMethodBody = generateMethodBody; } private ParameterSymbol MakeParameterSymbol(int ordinal, string name, ParameterSymbol sourceParameter) { return SynthesizedParameterSymbol.Create(this, sourceParameter.Type, ordinal, sourceParameter.RefKind, name, sourceParameter.CustomModifiers, sourceParameter.RefCustomModifiers); } internal override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) { return false; } internal override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) { return false; } internal override bool IsMetadataFinal { get { return false; } } public override MethodKind MethodKind { get { return MethodKind.Ordinary; } } public override string Name { get { return _name; } } public override int Arity { get { return _typeParameters.Length; } } public override bool IsExtensionMethod { get { return false; } } internal override bool HasSpecialName { get { return true; } } internal override System.Reflection.MethodImplAttributes ImplementationAttributes { get { return default(System.Reflection.MethodImplAttributes); } } internal override bool HasDeclarativeSecurity { get { return false; } } public override DllImportData GetDllImportData() { return null; } internal override IEnumerable<Cci.SecurityAttribute> GetSecurityInformation() { throw ExceptionUtilities.Unreachable; } internal override MarshalPseudoCustomAttributeData ReturnValueMarshallingInformation { get { return null; } } internal override bool RequiresSecurityObject { get { return false; } } internal override bool TryGetThisParameter(out ParameterSymbol thisParameter) { thisParameter = null; return true; } public override bool HidesBaseMethodsByName { get { return false; } } public override bool IsVararg { get { return this.SubstitutedSourceMethod.IsVararg; } } internal override RefKind RefKind { get { return this.SubstitutedSourceMethod.RefKind; } } public override bool ReturnsVoid { get { return this.ReturnType.SpecialType == SpecialType.System_Void; } } public override bool IsAsync { get { return false; } } public override TypeSymbol ReturnType { get { if (_lazyReturnType == null) { throw new InvalidOperationException(); } return _lazyReturnType; } } public override ImmutableArray<TypeSymbol> TypeArguments { get { return _typeParameters.Cast<TypeParameterSymbol, TypeSymbol>(); } } public override ImmutableArray<TypeParameterSymbol> TypeParameters { get { return _typeParameters; } } public override ImmutableArray<ParameterSymbol> Parameters { get { return _parameters; } } public override ImmutableArray<MethodSymbol> ExplicitInterfaceImplementations { get { return ImmutableArray<MethodSymbol>.Empty; } } public override ImmutableArray<CustomModifier> ReturnTypeCustomModifiers { get { return ImmutableArray<CustomModifier>.Empty; } } public override ImmutableArray<CustomModifier> RefCustomModifiers { get { return ImmutableArray<CustomModifier>.Empty; } } public override Symbol AssociatedSymbol { get { return null; } } internal override ImmutableArray<string> GetAppliedConditionalSymbols() { throw ExceptionUtilities.Unreachable; } internal override Cci.CallingConvention CallingConvention { get { Debug.Assert(this.IsStatic); var cc = Cci.CallingConvention.Default; if (this.IsVararg) { cc |= Cci.CallingConvention.ExtraArguments; } if (this.IsGenericMethod) { cc |= Cci.CallingConvention.Generic; } return cc; } } internal override bool GenerateDebugInfo { get { return false; } } public override Symbol ContainingSymbol { get { return _container; } } public override ImmutableArray<Location> Locations { get { return _locations; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { throw ExceptionUtilities.Unreachable; } } public override Accessibility DeclaredAccessibility { get { return Accessibility.Internal; } } public override bool IsStatic { get { return true; } } public override bool IsVirtual { get { return false; } } public override bool IsOverride { get { return false; } } public override bool IsAbstract { get { return false; } } public override bool IsSealed { get { return false; } } public override bool IsExtern { get { return false; } } internal override ObsoleteAttributeData ObsoleteAttributeData { get { throw ExceptionUtilities.Unreachable; } } internal override void GenerateMethodBody(TypeCompilationState compilationState, DiagnosticBag diagnostics) { ImmutableArray<LocalSymbol> declaredLocalsArray; var body = _generateMethodBody(this, diagnostics, out declaredLocalsArray); var compilation = compilationState.Compilation; _lazyReturnType = CalculateReturnType(compilation, body); // Can't do this until the return type has been computed. TypeParameterChecker.Check(this, _allTypeParameters); if (diagnostics.HasAnyErrors()) { return; } DiagnosticsPass.IssueDiagnostics(compilation, body, diagnostics, this); if (diagnostics.HasAnyErrors()) { return; } // Check for use-site diagnostics (e.g. missing types in the signature). DiagnosticInfo useSiteDiagnosticInfo = null; this.CalculateUseSiteDiagnostic(ref useSiteDiagnosticInfo); if (useSiteDiagnosticInfo != null && useSiteDiagnosticInfo.Severity == DiagnosticSeverity.Error) { diagnostics.Add(useSiteDiagnosticInfo, this.Locations[0]); return; } try { var declaredLocals = PooledHashSet<LocalSymbol>.GetInstance(); try { // Rewrite local declaration statement. body = (BoundStatement)LocalDeclarationRewriter.Rewrite(compilation, _container, declaredLocals, body, declaredLocalsArray); // Verify local declaration names. foreach (var local in declaredLocals) { Debug.Assert(local.Locations.Length > 0); var name = local.Name; if (name.StartsWith("$", StringComparison.Ordinal)) { diagnostics.Add(ErrorCode.ERR_UnexpectedCharacter, local.Locations[0], name[0]); return; } } // Rewrite references to placeholder "locals". body = (BoundStatement)PlaceholderLocalRewriter.Rewrite(compilation, _container, declaredLocals, body, diagnostics); if (diagnostics.HasAnyErrors()) { return; } } finally { declaredLocals.Free(); } var syntax = body.Syntax; var statementsBuilder = ArrayBuilder<BoundStatement>.GetInstance(); statementsBuilder.Add(body); // Insert an implicit return statement if necessary. if (body.Kind != BoundKind.ReturnStatement) { statementsBuilder.Add(new BoundReturnStatement(syntax, RefKind.None, expressionOpt: null)); } var localsBuilder = ArrayBuilder<LocalSymbol>.GetInstance(); var localsSet = PooledHashSet<LocalSymbol>.GetInstance(); foreach (var local in this.LocalsForBinding) { Debug.Assert(!localsSet.Contains(local)); localsBuilder.Add(local); localsSet.Add(local); } foreach (var local in this.Locals) { if (!localsSet.Contains(local)) { Debug.Assert(!localsSet.Contains(local)); localsBuilder.Add(local); localsSet.Add(local); } } localsSet.Free(); body = new BoundBlock(syntax, localsBuilder.ToImmutableAndFree(), statementsBuilder.ToImmutableAndFree()) { WasCompilerGenerated = true }; Debug.Assert(!diagnostics.HasAnyErrors()); Debug.Assert(!body.HasErrors); bool sawLambdas; bool sawLocalFunctions; bool sawAwaitInExceptionHandler; ImmutableArray<SourceSpan> dynamicAnalysisSpans = ImmutableArray<SourceSpan>.Empty; body = LocalRewriter.Rewrite( compilation: this.DeclaringCompilation, method: this, methodOrdinal: _methodOrdinal, containingType: _container, statement: body, compilationState: compilationState, previousSubmissionFields: null, allowOmissionOfConditionalCalls: false, instrumentForDynamicAnalysis: false, debugDocumentProvider: null, dynamicAnalysisSpans: ref dynamicAnalysisSpans, diagnostics: diagnostics, sawLambdas: out sawLambdas, sawLocalFunctions: out sawLocalFunctions, sawAwaitInExceptionHandler: out sawAwaitInExceptionHandler); Debug.Assert(!sawAwaitInExceptionHandler); Debug.Assert(dynamicAnalysisSpans.Length == 0); if (body.HasErrors) { return; } // Variables may have been captured by lambdas in the original method // or in the expression, and we need to preserve the existing values of // those variables in the expression. This requires rewriting the variables // in the expression based on the closure classes from both the original // method and the expression, and generating a preamble that copies // values into the expression closure classes. // // Consider the original method: // static void M() // { // int x, y, z; // ... // F(() => x + y); // } // and the expression in the EE: "F(() => x + z)". // // The expression is first rewritten using the closure class and local <1> // from the original method: F(() => <1>.x + z) // Then lambda rewriting introduces a new closure class that includes // the locals <1> and z, and a corresponding local <2>: F(() => <2>.<1>.x + <2>.z) // And a preamble is added to initialize the fields of <2>: // <2> = new <>c__DisplayClass0(); // <2>.<1> = <1>; // <2>.z = z; // Rewrite "this" and "base" references to parameter in this method. // Rewrite variables within body to reference existing display classes. body = (BoundStatement)CapturedVariableRewriter.Rewrite( this.SubstitutedSourceMethod.IsStatic ? null : _parameters[0], compilation.Conversions, _displayClassVariables, body, diagnostics); if (body.HasErrors) { Debug.Assert(false, "Please add a test case capturing whatever caused this assert."); return; } if (diagnostics.HasAnyErrors()) { return; } if (sawLambdas || sawLocalFunctions) { var closureDebugInfoBuilder = ArrayBuilder<ClosureDebugInfo>.GetInstance(); var lambdaDebugInfoBuilder = ArrayBuilder<LambdaDebugInfo>.GetInstance(); body = LambdaRewriter.Rewrite( loweredBody: body, thisType: this.SubstitutedSourceMethod.ContainingType, thisParameter: _thisParameter, method: this, methodOrdinal: _methodOrdinal, substitutedSourceMethod: this.SubstitutedSourceMethod.OriginalDefinition, closureDebugInfoBuilder: closureDebugInfoBuilder, lambdaDebugInfoBuilder: lambdaDebugInfoBuilder, slotAllocatorOpt: null, compilationState: compilationState, diagnostics: diagnostics, assignLocals: true); // we don't need this information: closureDebugInfoBuilder.Free(); lambdaDebugInfoBuilder.Free(); } // Insert locals from the original method, // followed by any new locals. var block = (BoundBlock)body; var localBuilder = ArrayBuilder<LocalSymbol>.GetInstance(); foreach (var local in this.Locals) { Debug.Assert(!(local is EELocalSymbol) || (((EELocalSymbol)local).Ordinal == localBuilder.Count)); localBuilder.Add(local); } foreach (var local in block.Locals) { var oldLocal = local as EELocalSymbol; if (oldLocal != null) { Debug.Assert(localBuilder[oldLocal.Ordinal] == oldLocal); continue; } localBuilder.Add(local); } body = block.Update(localBuilder.ToImmutableAndFree(), block.LocalFunctions, block.Statements); TypeParameterChecker.Check(body, _allTypeParameters); compilationState.AddSynthesizedMethod(this, body); } catch (BoundTreeVisitor.CancelledByStackGuardException ex) { ex.AddAnError(diagnostics); } } private static TypeSymbol CalculateReturnType(CSharpCompilation compilation, BoundStatement bodyOpt) { if (bodyOpt == null) { // If the method doesn't do anything, then it doesn't return anything. return compilation.GetSpecialType(SpecialType.System_Void); } switch (bodyOpt.Kind) { case BoundKind.ReturnStatement: return ((BoundReturnStatement)bodyOpt).ExpressionOpt.Type; case BoundKind.ExpressionStatement: case BoundKind.LocalDeclaration: case BoundKind.MultipleLocalDeclarations: return compilation.GetSpecialType(SpecialType.System_Void); default: throw ExceptionUtilities.UnexpectedValue(bodyOpt.Kind); } } internal override void AddSynthesizedReturnTypeAttributes(ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedReturnTypeAttributes(ref attributes); var compilation = this.DeclaringCompilation; var returnType = this.ReturnType; if (returnType.ContainsDynamic() && compilation.HasDynamicEmitAttributes()) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeDynamicAttribute(returnType, ReturnTypeCustomModifiers.Length + RefCustomModifiers.Length, RefKind)); } if (returnType.ContainsTupleNames() && compilation.HasTupleNamesAttributes) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeTupleNamesAttribute(returnType)); } } internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) { return localPosition; } } }
namespace Medo.Windows.Forms.Examples { partial class MainForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel(); this.btnMessageBoxInformation = new System.Windows.Forms.Button(); this.btnMessageBoxWarning = new System.Windows.Forms.Button(); this.btnMessageBoxError = new System.Windows.Forms.Button(); this.btnMessageBoxQuestion = new System.Windows.Forms.Button(); this.btnUnhandledCatch = new System.Windows.Forms.Button(); this.btnUnhandledCatchTask = new System.Windows.Forms.Button(); this.btnUnhandledCatchWorker = new System.Windows.Forms.Button(); this.btnAboutBox = new System.Windows.Forms.Button(); this.btnTps = new System.Windows.Forms.Button(); this.btnTimerResolution = new System.Windows.Forms.Button(); this.btnWaitCursor = new System.Windows.Forms.Button(); this.btnErrorReport = new System.Windows.Forms.Button(); this.btnFeedback = new System.Windows.Forms.Button(); this.btnUpgrade = new System.Windows.Forms.Button(); this.bwUnhandledCatchBackground = new System.ComponentModel.BackgroundWorker(); this.btnCyberCard = new System.Windows.Forms.Button(); this.flowLayoutPanel1.SuspendLayout(); this.SuspendLayout(); // // flowLayoutPanel1 // this.flowLayoutPanel1.Controls.Add(this.btnMessageBoxInformation); this.flowLayoutPanel1.Controls.Add(this.btnMessageBoxWarning); this.flowLayoutPanel1.Controls.Add(this.btnMessageBoxError); this.flowLayoutPanel1.Controls.Add(this.btnMessageBoxQuestion); this.flowLayoutPanel1.Controls.Add(this.btnUnhandledCatch); this.flowLayoutPanel1.Controls.Add(this.btnUnhandledCatchTask); this.flowLayoutPanel1.Controls.Add(this.btnUnhandledCatchWorker); this.flowLayoutPanel1.Controls.Add(this.btnAboutBox); this.flowLayoutPanel1.Controls.Add(this.btnTps); this.flowLayoutPanel1.Controls.Add(this.btnTimerResolution); this.flowLayoutPanel1.Controls.Add(this.btnWaitCursor); this.flowLayoutPanel1.Controls.Add(this.btnErrorReport); this.flowLayoutPanel1.Controls.Add(this.btnFeedback); this.flowLayoutPanel1.Controls.Add(this.btnUpgrade); this.flowLayoutPanel1.Controls.Add(this.btnCyberCard); this.flowLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill; this.flowLayoutPanel1.Location = new System.Drawing.Point(0, 0); this.flowLayoutPanel1.Name = "flowLayoutPanel1"; this.flowLayoutPanel1.Size = new System.Drawing.Size(800, 450); this.flowLayoutPanel1.TabIndex = 0; // // btnMessageBoxInformation // this.btnMessageBoxInformation.Location = new System.Drawing.Point(3, 3); this.btnMessageBoxInformation.Name = "btnMessageBoxInformation"; this.btnMessageBoxInformation.Size = new System.Drawing.Size(200, 29); this.btnMessageBoxInformation.TabIndex = 0; this.btnMessageBoxInformation.Text = "MessageBox: Information"; this.btnMessageBoxInformation.UseVisualStyleBackColor = true; this.btnMessageBoxInformation.Click += new System.EventHandler(this.btnMessageBoxInformation_Click); // // btnMessageBoxWarning // this.btnMessageBoxWarning.Location = new System.Drawing.Point(209, 3); this.btnMessageBoxWarning.Name = "btnMessageBoxWarning"; this.btnMessageBoxWarning.Size = new System.Drawing.Size(200, 29); this.btnMessageBoxWarning.TabIndex = 1; this.btnMessageBoxWarning.Text = "MessageBox: Warning"; this.btnMessageBoxWarning.UseVisualStyleBackColor = true; this.btnMessageBoxWarning.Click += new System.EventHandler(this.btnMessageBoxWarning_Click); // // btnMessageBoxError // this.btnMessageBoxError.Location = new System.Drawing.Point(415, 3); this.btnMessageBoxError.Name = "btnMessageBoxError"; this.btnMessageBoxError.Size = new System.Drawing.Size(200, 29); this.btnMessageBoxError.TabIndex = 2; this.btnMessageBoxError.Text = "MessageBox: Error"; this.btnMessageBoxError.UseVisualStyleBackColor = true; this.btnMessageBoxError.Click += new System.EventHandler(this.btnMessageBoxError_Click); // // btnMessageBoxQuestion // this.btnMessageBoxQuestion.Location = new System.Drawing.Point(3, 38); this.btnMessageBoxQuestion.Name = "btnMessageBoxQuestion"; this.btnMessageBoxQuestion.Size = new System.Drawing.Size(200, 29); this.btnMessageBoxQuestion.TabIndex = 3; this.btnMessageBoxQuestion.Text = "MessageBox: Question"; this.btnMessageBoxQuestion.UseVisualStyleBackColor = true; this.btnMessageBoxQuestion.Click += new System.EventHandler(this.btnMessageBoxQuestion_Click); // // btnUnhandledCatch // this.btnUnhandledCatch.Location = new System.Drawing.Point(209, 38); this.btnUnhandledCatch.Name = "btnUnhandledCatch"; this.btnUnhandledCatch.Size = new System.Drawing.Size(200, 29); this.btnUnhandledCatch.TabIndex = 4; this.btnUnhandledCatch.Text = "Unhandled catch"; this.btnUnhandledCatch.UseVisualStyleBackColor = true; this.btnUnhandledCatch.Click += new System.EventHandler(this.btnUnhandledCatch_Click); // // btnUnhandledCatchTask // this.btnUnhandledCatchTask.Location = new System.Drawing.Point(415, 38); this.btnUnhandledCatchTask.Name = "btnUnhandledCatchTask"; this.btnUnhandledCatchTask.Size = new System.Drawing.Size(200, 29); this.btnUnhandledCatchTask.TabIndex = 9; this.btnUnhandledCatchTask.Text = "Unhandled catch (task)"; this.btnUnhandledCatchTask.UseVisualStyleBackColor = true; this.btnUnhandledCatchTask.Click += new System.EventHandler(this.btnUnhandledCatchTask_Click); // // btnUnhandledCatchWorker // this.btnUnhandledCatchWorker.Location = new System.Drawing.Point(3, 73); this.btnUnhandledCatchWorker.Name = "btnUnhandledCatchWorker"; this.btnUnhandledCatchWorker.Size = new System.Drawing.Size(200, 29); this.btnUnhandledCatchWorker.TabIndex = 8; this.btnUnhandledCatchWorker.Text = "Unhandled catch (thread)"; this.btnUnhandledCatchWorker.UseVisualStyleBackColor = true; this.btnUnhandledCatchWorker.Click += new System.EventHandler(this.btnUnhandledCatchBackground_Click); // // btnAboutBox // this.btnAboutBox.Location = new System.Drawing.Point(209, 73); this.btnAboutBox.Name = "btnAboutBox"; this.btnAboutBox.Size = new System.Drawing.Size(200, 29); this.btnAboutBox.TabIndex = 5; this.btnAboutBox.Text = "About box"; this.btnAboutBox.UseVisualStyleBackColor = true; this.btnAboutBox.Click += new System.EventHandler(this.btnAboutBox_Click); // // btnTps // this.btnTps.Location = new System.Drawing.Point(415, 73); this.btnTps.Name = "btnTps"; this.btnTps.Size = new System.Drawing.Size(200, 29); this.btnTps.TabIndex = 6; this.btnTps.Text = "TPS"; this.btnTps.UseVisualStyleBackColor = true; this.btnTps.Click += new System.EventHandler(this.btnTps_Click); // // btnTimerResolution // this.btnTimerResolution.Location = new System.Drawing.Point(3, 108); this.btnTimerResolution.Name = "btnTimerResolution"; this.btnTimerResolution.Size = new System.Drawing.Size(200, 29); this.btnTimerResolution.TabIndex = 7; this.btnTimerResolution.Text = "Timer resolution"; this.btnTimerResolution.UseVisualStyleBackColor = true; this.btnTimerResolution.Click += new System.EventHandler(this.btnTimerResolution_Click); // // btnWaitCursor // this.btnWaitCursor.Location = new System.Drawing.Point(209, 108); this.btnWaitCursor.Name = "btnWaitCursor"; this.btnWaitCursor.Size = new System.Drawing.Size(200, 29); this.btnWaitCursor.TabIndex = 10; this.btnWaitCursor.Text = "Wait Cursor"; this.btnWaitCursor.UseVisualStyleBackColor = true; this.btnWaitCursor.Click += new System.EventHandler(this.btnWaitCursor_Click); // // btnErrorReport // this.btnErrorReport.Location = new System.Drawing.Point(415, 108); this.btnErrorReport.Name = "btnErrorReport"; this.btnErrorReport.Size = new System.Drawing.Size(200, 29); this.btnErrorReport.TabIndex = 11; this.btnErrorReport.Text = "Error report"; this.btnErrorReport.UseVisualStyleBackColor = true; this.btnErrorReport.Click += new System.EventHandler(this.btnErrorReport_Click); // // btnFeedback // this.btnFeedback.Location = new System.Drawing.Point(3, 143); this.btnFeedback.Name = "btnFeedback"; this.btnFeedback.Size = new System.Drawing.Size(200, 29); this.btnFeedback.TabIndex = 12; this.btnFeedback.Text = "Feedback"; this.btnFeedback.UseVisualStyleBackColor = true; this.btnFeedback.Click += new System.EventHandler(this.btnFeedback_Click); // // btnUpgrade // this.btnUpgrade.Location = new System.Drawing.Point(209, 143); this.btnUpgrade.Name = "btnUpgrade"; this.btnUpgrade.Size = new System.Drawing.Size(200, 29); this.btnUpgrade.TabIndex = 13; this.btnUpgrade.Text = "Upgrade"; this.btnUpgrade.UseVisualStyleBackColor = true; this.btnUpgrade.Click += new System.EventHandler(this.btnUpgrade_Click); // // bwUnhandledCatchBackground // this.bwUnhandledCatchBackground.DoWork += new System.ComponentModel.DoWorkEventHandler(this.bwUnhandledCatchWorker_DoWork); this.bwUnhandledCatchBackground.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.bwUnhandledCatchBackground_RunWorkerCompleted); // // btnCyberCard // this.btnCyberCard.Location = new System.Drawing.Point(415, 143); this.btnCyberCard.Name = "btnCyberCard"; this.btnCyberCard.Size = new System.Drawing.Size(200, 29); this.btnCyberCard.TabIndex = 14; this.btnCyberCard.Text = "CyberCard"; this.btnCyberCard.UseVisualStyleBackColor = true; this.btnCyberCard.Click += new System.EventHandler(this.btnCyberCard_Click); // // MainForm // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(800, 450); this.Controls.Add(this.flowLayoutPanel1); this.Name = "MainForm"; this.Text = "Form1"; this.flowLayoutPanel1.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1; private System.Windows.Forms.Button btnMessageBoxInformation; private System.Windows.Forms.Button btnMessageBoxWarning; private System.Windows.Forms.Button btnMessageBoxError; private System.Windows.Forms.Button btnMessageBoxQuestion; private System.Windows.Forms.Button btnUnhandledCatch; private System.Windows.Forms.Button btnAboutBox; private System.Windows.Forms.Button btnTps; private System.Windows.Forms.Button btnTimerResolution; private System.Windows.Forms.Button btnUnhandledCatchWorker; private System.ComponentModel.BackgroundWorker bwUnhandledCatchBackground; private System.Windows.Forms.Button btnUnhandledCatchTask; private System.Windows.Forms.Button btnWaitCursor; private System.Windows.Forms.Button btnErrorReport; private System.Windows.Forms.Button btnFeedback; private System.Windows.Forms.Button btnUpgrade; private System.Windows.Forms.Button btnCyberCard; } }
/* * Swaggy Jenkins * * Jenkins API clients generated from Swagger / Open API specification * * The version of the OpenAPI document: 1.1.2-pre.0 * Contact: [email protected] * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; namespace Org.OpenAPITools.Model { /// <summary> /// HudsonMasterComputermonitorData /// </summary> [DataContract] public partial class HudsonMasterComputermonitorData : IEquatable<HudsonMasterComputermonitorData>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="HudsonMasterComputermonitorData" /> class. /// </summary> /// <param name="hudsonNodeMonitorsSwapSpaceMonitor">hudsonNodeMonitorsSwapSpaceMonitor.</param> /// <param name="hudsonNodeMonitorsTemporarySpaceMonitor">hudsonNodeMonitorsTemporarySpaceMonitor.</param> /// <param name="hudsonNodeMonitorsDiskSpaceMonitor">hudsonNodeMonitorsDiskSpaceMonitor.</param> /// <param name="hudsonNodeMonitorsArchitectureMonitor">hudsonNodeMonitorsArchitectureMonitor.</param> /// <param name="hudsonNodeMonitorsResponseTimeMonitor">hudsonNodeMonitorsResponseTimeMonitor.</param> /// <param name="hudsonNodeMonitorsClockMonitor">hudsonNodeMonitorsClockMonitor.</param> /// <param name="_class">_class.</param> public HudsonMasterComputermonitorData(SwapSpaceMonitorMemoryUsage2 hudsonNodeMonitorsSwapSpaceMonitor = default(SwapSpaceMonitorMemoryUsage2), DiskSpaceMonitorDescriptorDiskSpace hudsonNodeMonitorsTemporarySpaceMonitor = default(DiskSpaceMonitorDescriptorDiskSpace), DiskSpaceMonitorDescriptorDiskSpace hudsonNodeMonitorsDiskSpaceMonitor = default(DiskSpaceMonitorDescriptorDiskSpace), string hudsonNodeMonitorsArchitectureMonitor = default(string), ResponseTimeMonitorData hudsonNodeMonitorsResponseTimeMonitor = default(ResponseTimeMonitorData), ClockDifference hudsonNodeMonitorsClockMonitor = default(ClockDifference), string _class = default(string)) { this.HudsonNodeMonitorsSwapSpaceMonitor = hudsonNodeMonitorsSwapSpaceMonitor; this.HudsonNodeMonitorsTemporarySpaceMonitor = hudsonNodeMonitorsTemporarySpaceMonitor; this.HudsonNodeMonitorsDiskSpaceMonitor = hudsonNodeMonitorsDiskSpaceMonitor; this.HudsonNodeMonitorsArchitectureMonitor = hudsonNodeMonitorsArchitectureMonitor; this.HudsonNodeMonitorsResponseTimeMonitor = hudsonNodeMonitorsResponseTimeMonitor; this.HudsonNodeMonitorsClockMonitor = hudsonNodeMonitorsClockMonitor; this.Class = _class; } /// <summary> /// Gets or Sets HudsonNodeMonitorsSwapSpaceMonitor /// </summary> [DataMember(Name="hudson.node_monitors.SwapSpaceMonitor", EmitDefaultValue=false)] public SwapSpaceMonitorMemoryUsage2 HudsonNodeMonitorsSwapSpaceMonitor { get; set; } /// <summary> /// Gets or Sets HudsonNodeMonitorsTemporarySpaceMonitor /// </summary> [DataMember(Name="hudson.node_monitors.TemporarySpaceMonitor", EmitDefaultValue=false)] public DiskSpaceMonitorDescriptorDiskSpace HudsonNodeMonitorsTemporarySpaceMonitor { get; set; } /// <summary> /// Gets or Sets HudsonNodeMonitorsDiskSpaceMonitor /// </summary> [DataMember(Name="hudson.node_monitors.DiskSpaceMonitor", EmitDefaultValue=false)] public DiskSpaceMonitorDescriptorDiskSpace HudsonNodeMonitorsDiskSpaceMonitor { get; set; } /// <summary> /// Gets or Sets HudsonNodeMonitorsArchitectureMonitor /// </summary> [DataMember(Name="hudson.node_monitors.ArchitectureMonitor", EmitDefaultValue=false)] public string HudsonNodeMonitorsArchitectureMonitor { get; set; } /// <summary> /// Gets or Sets HudsonNodeMonitorsResponseTimeMonitor /// </summary> [DataMember(Name="hudson.node_monitors.ResponseTimeMonitor", EmitDefaultValue=false)] public ResponseTimeMonitorData HudsonNodeMonitorsResponseTimeMonitor { get; set; } /// <summary> /// Gets or Sets HudsonNodeMonitorsClockMonitor /// </summary> [DataMember(Name="hudson.node_monitors.ClockMonitor", EmitDefaultValue=false)] public ClockDifference HudsonNodeMonitorsClockMonitor { get; set; } /// <summary> /// Gets or Sets Class /// </summary> [DataMember(Name="_class", EmitDefaultValue=false)] public string Class { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class HudsonMasterComputermonitorData {\n"); sb.Append(" HudsonNodeMonitorsSwapSpaceMonitor: ").Append(HudsonNodeMonitorsSwapSpaceMonitor).Append("\n"); sb.Append(" HudsonNodeMonitorsTemporarySpaceMonitor: ").Append(HudsonNodeMonitorsTemporarySpaceMonitor).Append("\n"); sb.Append(" HudsonNodeMonitorsDiskSpaceMonitor: ").Append(HudsonNodeMonitorsDiskSpaceMonitor).Append("\n"); sb.Append(" HudsonNodeMonitorsArchitectureMonitor: ").Append(HudsonNodeMonitorsArchitectureMonitor).Append("\n"); sb.Append(" HudsonNodeMonitorsResponseTimeMonitor: ").Append(HudsonNodeMonitorsResponseTimeMonitor).Append("\n"); sb.Append(" HudsonNodeMonitorsClockMonitor: ").Append(HudsonNodeMonitorsClockMonitor).Append("\n"); sb.Append(" Class: ").Append(Class).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as HudsonMasterComputermonitorData); } /// <summary> /// Returns true if HudsonMasterComputermonitorData instances are equal /// </summary> /// <param name="input">Instance of HudsonMasterComputermonitorData to be compared</param> /// <returns>Boolean</returns> public bool Equals(HudsonMasterComputermonitorData input) { if (input == null) return false; return ( this.HudsonNodeMonitorsSwapSpaceMonitor == input.HudsonNodeMonitorsSwapSpaceMonitor || (this.HudsonNodeMonitorsSwapSpaceMonitor != null && this.HudsonNodeMonitorsSwapSpaceMonitor.Equals(input.HudsonNodeMonitorsSwapSpaceMonitor)) ) && ( this.HudsonNodeMonitorsTemporarySpaceMonitor == input.HudsonNodeMonitorsTemporarySpaceMonitor || (this.HudsonNodeMonitorsTemporarySpaceMonitor != null && this.HudsonNodeMonitorsTemporarySpaceMonitor.Equals(input.HudsonNodeMonitorsTemporarySpaceMonitor)) ) && ( this.HudsonNodeMonitorsDiskSpaceMonitor == input.HudsonNodeMonitorsDiskSpaceMonitor || (this.HudsonNodeMonitorsDiskSpaceMonitor != null && this.HudsonNodeMonitorsDiskSpaceMonitor.Equals(input.HudsonNodeMonitorsDiskSpaceMonitor)) ) && ( this.HudsonNodeMonitorsArchitectureMonitor == input.HudsonNodeMonitorsArchitectureMonitor || (this.HudsonNodeMonitorsArchitectureMonitor != null && this.HudsonNodeMonitorsArchitectureMonitor.Equals(input.HudsonNodeMonitorsArchitectureMonitor)) ) && ( this.HudsonNodeMonitorsResponseTimeMonitor == input.HudsonNodeMonitorsResponseTimeMonitor || (this.HudsonNodeMonitorsResponseTimeMonitor != null && this.HudsonNodeMonitorsResponseTimeMonitor.Equals(input.HudsonNodeMonitorsResponseTimeMonitor)) ) && ( this.HudsonNodeMonitorsClockMonitor == input.HudsonNodeMonitorsClockMonitor || (this.HudsonNodeMonitorsClockMonitor != null && this.HudsonNodeMonitorsClockMonitor.Equals(input.HudsonNodeMonitorsClockMonitor)) ) && ( this.Class == input.Class || (this.Class != null && this.Class.Equals(input.Class)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.HudsonNodeMonitorsSwapSpaceMonitor != null) hashCode = hashCode * 59 + this.HudsonNodeMonitorsSwapSpaceMonitor.GetHashCode(); if (this.HudsonNodeMonitorsTemporarySpaceMonitor != null) hashCode = hashCode * 59 + this.HudsonNodeMonitorsTemporarySpaceMonitor.GetHashCode(); if (this.HudsonNodeMonitorsDiskSpaceMonitor != null) hashCode = hashCode * 59 + this.HudsonNodeMonitorsDiskSpaceMonitor.GetHashCode(); if (this.HudsonNodeMonitorsArchitectureMonitor != null) hashCode = hashCode * 59 + this.HudsonNodeMonitorsArchitectureMonitor.GetHashCode(); if (this.HudsonNodeMonitorsResponseTimeMonitor != null) hashCode = hashCode * 59 + this.HudsonNodeMonitorsResponseTimeMonitor.GetHashCode(); if (this.HudsonNodeMonitorsClockMonitor != null) hashCode = hashCode * 59 + this.HudsonNodeMonitorsClockMonitor.GetHashCode(); if (this.Class != null) hashCode = hashCode * 59 + this.Class.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
using System.Data.Common; using System.Net.Sockets; using System.Reactive.Concurrency; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; using System.Text; using AutoMapper; using Microsoft.Extensions.Hosting; using Miningcore.Configuration; using Miningcore.Extensions; using Miningcore.Messaging; using Miningcore.Notifications.Messages; using Miningcore.Persistence; using Miningcore.Persistence.Model; using Miningcore.Persistence.Repositories; using Newtonsoft.Json; using NLog; using Polly; using Polly.CircuitBreaker; using Contract = Miningcore.Contracts.Contract; using Share = Miningcore.Blockchain.Share; using static Miningcore.Util.ActionUtils; namespace Miningcore.Mining; /// <summary> /// Asynchronously persist shares produced by all pools for processing by coin-specific payment processor(s) /// </summary> public class ShareRecorder : BackgroundService { public ShareRecorder(IConnectionFactory cf, IMapper mapper, JsonSerializerSettings jsonSerializerSettings, IShareRepository shareRepo, IBlockRepository blockRepo, ClusterConfig clusterConfig, IMessageBus messageBus) { Contract.RequiresNonNull(cf, nameof(cf)); Contract.RequiresNonNull(mapper, nameof(mapper)); Contract.RequiresNonNull(shareRepo, nameof(shareRepo)); Contract.RequiresNonNull(blockRepo, nameof(blockRepo)); Contract.RequiresNonNull(jsonSerializerSettings, nameof(jsonSerializerSettings)); Contract.RequiresNonNull(messageBus, nameof(messageBus)); this.cf = cf; this.mapper = mapper; this.jsonSerializerSettings = jsonSerializerSettings; this.messageBus = messageBus; this.clusterConfig = clusterConfig; this.shareRepo = shareRepo; this.blockRepo = blockRepo; pools = clusterConfig.Pools.ToDictionary(x => x.Id, x => x); BuildFaultHandlingPolicy(); ConfigureRecovery(); } private static readonly ILogger logger = LogManager.GetCurrentClassLogger(); private readonly IShareRepository shareRepo; private readonly IBlockRepository blockRepo; private readonly IConnectionFactory cf; private readonly JsonSerializerSettings jsonSerializerSettings; private readonly IMessageBus messageBus; private readonly ClusterConfig clusterConfig; private readonly Dictionary<string, PoolConfig> pools; private readonly IMapper mapper; private IAsyncPolicy faultPolicy; private bool hasLoggedPolicyFallbackFailure; private string recoveryFilename; private const int RetryCount = 3; private const string PolicyContextKeyShares = "share"; private bool notifiedAdminOnPolicyFallback = false; private async Task PersistSharesAsync(IList<Share> shares) { var context = new Dictionary<string, object> { { PolicyContextKeyShares, shares } }; await faultPolicy.ExecuteAsync(ctx => PersistSharesCoreAsync((IList<Share>) ctx[PolicyContextKeyShares]), context); } private async Task PersistSharesCoreAsync(IList<Share> shares) { await cf.RunTx(async (con, tx) => { // Insert shares var mapped = shares.Select(mapper.Map<Persistence.Model.Share>).ToArray(); await shareRepo.BatchInsertAsync(con, tx, mapped); // Insert blocks foreach(var share in shares) { if(!share.IsBlockCandidate) continue; var blockEntity = mapper.Map<Block>(share); blockEntity.Status = BlockStatus.Pending; await blockRepo.InsertAsync(con, tx, blockEntity); if(pools.TryGetValue(share.PoolId, out var poolConfig)) messageBus.NotifyBlockFound(share.PoolId, blockEntity, poolConfig.Template); else logger.Warn(()=> $"Block found for unknown pool {share.PoolId}"); } }); } private static void OnPolicyRetry(Exception ex, TimeSpan timeSpan, int retry, object context) { logger.Warn(() => $"Retry {retry} in {timeSpan} due to {ex.Source}: {ex.GetType().Name} ({ex.Message})"); } private Task OnPolicyFallbackAsync(Exception ex, Context context) { logger.Warn(() => $"Fallback due to {ex.Source}: {ex.GetType().Name} ({ex.Message})"); return Task.FromResult(true); } private async Task OnExecutePolicyFallbackAsync(Context context, CancellationToken ct) { var shares = (IList<Share>) context[PolicyContextKeyShares]; try { await using(var stream = new FileStream(recoveryFilename, FileMode.Append, FileAccess.Write)) { await using(var writer = new StreamWriter(stream, new UTF8Encoding(false))) { if(stream.Length == 0) WriteRecoveryFileheader(writer); foreach(var share in shares) { var json = JsonConvert.SerializeObject(share, jsonSerializerSettings); await writer.WriteLineAsync(json); } } } NotifyAdminOnPolicyFallback(); } catch(Exception ex) { if(!hasLoggedPolicyFallbackFailure) { logger.Fatal(ex, "Fatal error during policy fallback execution. Share(s) will be lost!"); hasLoggedPolicyFallbackFailure = true; } } } private static void WriteRecoveryFileheader(TextWriter writer) { writer.WriteLine("# The existence of this file means shares could not be committed to the database."); writer.WriteLine("# You should stop the pool cluster and run the following command:"); writer.WriteLine("# miningcore -c <path-to-config> -rs <path-to-this-file>\n"); } public async Task RecoverSharesAsync(ClusterConfig clusterConfig, string recoveryFilename) { logger.Info(() => $"Recovering shares using {recoveryFilename} ..."); try { var successCount = 0; var failCount = 0; const int bufferSize = 100; await using(var stream = new FileStream(recoveryFilename, FileMode.Open, FileAccess.Read)) { using(var reader = new StreamReader(stream, new UTF8Encoding(false))) { var shares = new List<Share>(); var lastProgressUpdate = DateTime.UtcNow; while(!reader.EndOfStream) { var line = reader.ReadLine().Trim(); // skip blank lines if(line.Length == 0) continue; // skip comments if(line.StartsWith("#")) continue; // parse try { var share = JsonConvert.DeserializeObject<Share>(line, jsonSerializerSettings); shares.Add(share); } catch(JsonException ex) { logger.Error(ex, () => $"Unable to parse share record: {line}"); failCount++; } // import try { if(shares.Count == bufferSize) { await PersistSharesCoreAsync(shares); successCount += shares.Count; shares.Clear(); } } catch(Exception ex) { logger.Error(ex, () => "Unable to import shares"); failCount++; } // progress var now = DateTime.UtcNow; if(now - lastProgressUpdate > TimeSpan.FromSeconds(10)) { logger.Info($"{successCount} shares imported"); lastProgressUpdate = now; } } // import remaining shares try { if(shares.Count > 0) { await PersistSharesCoreAsync(shares); successCount += shares.Count; } } catch(Exception ex) { logger.Error(ex, () => "Unable to import shares"); failCount++; } } } if(failCount == 0) logger.Info(() => $"Successfully imported {successCount} shares"); else logger.Warn(() => $"Successfully imported {successCount} shares with {failCount} failures"); } catch(FileNotFoundException) { logger.Error(() => $"Recovery file {recoveryFilename} was not found"); } } private void NotifyAdminOnPolicyFallback() { if(clusterConfig.Notifications?.Admin?.Enabled == true && clusterConfig.Notifications?.Admin?.NotifyPaymentSuccess == true && !notifiedAdminOnPolicyFallback) { notifiedAdminOnPolicyFallback = true; messageBus.SendMessage(new AdminNotification("Share Recorder Policy Fallback", $"The Share Recorder's Policy Fallback has been engaged. Check share recovery file {recoveryFilename}.")); } } private void ConfigureRecovery() { recoveryFilename = !string.IsNullOrEmpty(clusterConfig.ShareRecoveryFile) ? clusterConfig.ShareRecoveryFile : "recovered-shares.txt"; } private void BuildFaultHandlingPolicy() { // retry with increasing delay (1s, 2s, 4s etc) var retry = Policy .Handle<DbException>() .Or<SocketException>() .Or<TimeoutException>() .WaitAndRetryAsync(RetryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), OnPolicyRetry); // after retries failed several times, break the circuit and fall through to // fallback action for one minute, not attempting further retries during that period var breaker = Policy .Handle<DbException>() .Or<SocketException>() .Or<TimeoutException>() .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); var fallback = Policy .Handle<DbException>() .Or<SocketException>() .Or<TimeoutException>() .FallbackAsync(OnExecutePolicyFallbackAsync, OnPolicyFallbackAsync); var fallbackOnBrokenCircuit = Policy .Handle<BrokenCircuitException>() .FallbackAsync(OnExecutePolicyFallbackAsync, (ex, context) => Task.FromResult(true)); faultPolicy = Policy.WrapAsync( fallbackOnBrokenCircuit, Policy.WrapAsync(fallback, breaker, retry)); } protected override Task ExecuteAsync(CancellationToken ct) { logger.Info(() => "Online"); return messageBus.Listen<StratumShare>() .ObserveOn(TaskPoolScheduler.Default) .Where(x => x.Share != null) .Select(x => x.Share) .Buffer(TimeSpan.FromSeconds(5), 250) .Where(shares => shares.Any()) .Select(shares => Observable.FromAsync(() => Guard(() => PersistSharesAsync(shares), ex => logger.Error(ex)))) .Concat() .ToTask(ct) .ContinueWith(task => { if(task.IsFaulted) logger.Fatal(() => $"Terminated due to error {task.Exception?.InnerException ?? task.Exception}"); else logger.Info(() => "Offline"); }, ct); } }
#region License /* * WebSocketServiceManager.cs * * The MIT License * * Copyright (c) 2012-2015 sta.blockhead * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading; using WebSocketSharp.Net; namespace WebSocketSharp.Server { /// <summary> /// Provides the management function for the WebSocket services. /// </summary> /// <remarks> /// This class manages the WebSocket services provided by /// the <see cref="WebSocketServer"/> or <see cref="HttpServer"/>. /// </remarks> public class WebSocketServiceManager { #region Private Fields private volatile bool _clean; private Dictionary<string, WebSocketServiceHost> _hosts; private Logger _log; private volatile ServerState _state; private object _sync; private TimeSpan _waitTime; #endregion #region Internal Constructors internal WebSocketServiceManager (Logger log) { _log = log; _clean = true; _hosts = new Dictionary<string, WebSocketServiceHost> (); _state = ServerState.Ready; _sync = ((ICollection) _hosts).SyncRoot; _waitTime = TimeSpan.FromSeconds (1); } #endregion #region Public Properties /// <summary> /// Gets the number of the WebSocket services. /// </summary> /// <value> /// An <see cref="int"/> that represents the number of the services. /// </value> public int Count { get { lock (_sync) return _hosts.Count; } } /// <summary> /// Gets the host instances for the WebSocket services. /// </summary> /// <value> /// <para> /// An <c>IEnumerable&lt;WebSocketServiceHost&gt;</c> instance. /// </para> /// <para> /// It provides an enumerator which supports the iteration over /// the collection of the host instances. /// </para> /// </value> public IEnumerable<WebSocketServiceHost> Hosts { get { lock (_sync) return _hosts.Values.ToList (); } } /// <summary> /// Gets the host instance for a WebSocket service with the specified path. /// </summary> /// <value> /// <para> /// A <see cref="WebSocketServiceHost"/> instance or /// <see langword="null"/> if not found. /// </para> /// <para> /// The host instance provides the function to access /// the information in the service. /// </para> /// </value> /// <param name="path"> /// <para> /// A <see cref="string"/> that represents an absolute path to /// the service to find. /// </para> /// <para> /// / is trimmed from the end of the string if present. /// </para> /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="path"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="path"/> is empty. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="path"/> is not an absolute path. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="path"/> includes either or both /// query and fragment components. /// </para> /// </exception> public WebSocketServiceHost this[string path] { get { if (path == null) throw new ArgumentNullException ("path"); if (path.Length == 0) throw new ArgumentException ("An empty string.", "path"); if (path[0] != '/') throw new ArgumentException ("Not an absolute path.", "path"); if (path.IndexOfAny (new[] { '?', '#' }) > -1) { var msg = "It includes either or both query and fragment components."; throw new ArgumentException (msg, "path"); } WebSocketServiceHost host; InternalTryGetServiceHost (path, out host); return host; } } /// <summary> /// Gets or sets a value indicating whether the inactive sessions in /// the WebSocket services are cleaned up periodically. /// </summary> /// <remarks> /// The set operation does nothing if the server has already started or /// it is shutting down. /// </remarks> /// <value> /// <c>true</c> if the inactive sessions are cleaned up every 60 seconds; /// otherwise, <c>false</c>. /// </value> public bool KeepClean { get { return _clean; } set { string msg; if (!canSet (out msg)) { _log.Warn (msg); return; } lock (_sync) { if (!canSet (out msg)) { _log.Warn (msg); return; } foreach (var host in _hosts.Values) host.KeepClean = value; _clean = value; } } } /// <summary> /// Gets the paths for the WebSocket services. /// </summary> /// <value> /// <para> /// An <c>IEnumerable&lt;string&gt;</c> instance. /// </para> /// <para> /// It provides an enumerator which supports the iteration over /// the collection of the paths. /// </para> /// </value> public IEnumerable<string> Paths { get { lock (_sync) return _hosts.Keys.ToList (); } } /// <summary> /// Gets the total number of the sessions in the WebSocket services. /// </summary> /// <value> /// An <see cref="int"/> that represents the total number of /// the sessions in the services. /// </value> [Obsolete ("This property will be removed.")] public int SessionCount { get { var cnt = 0; foreach (var host in Hosts) { if (_state != ServerState.Start) break; cnt += host.Sessions.Count; } return cnt; } } /// <summary> /// Gets or sets the time to wait for the response to the WebSocket Ping or /// Close. /// </summary> /// <remarks> /// The set operation does nothing if the server has already started or /// it is shutting down. /// </remarks> /// <value> /// A <see cref="TimeSpan"/> to wait for the response. /// </value> /// <exception cref="ArgumentOutOfRangeException"> /// The value specified for a set operation is zero or less. /// </exception> public TimeSpan WaitTime { get { return _waitTime; } set { if (value <= TimeSpan.Zero) throw new ArgumentOutOfRangeException ("value", "Zero or less."); string msg; if (!canSet (out msg)) { _log.Warn (msg); return; } lock (_sync) { if (!canSet (out msg)) { _log.Warn (msg); return; } foreach (var host in _hosts.Values) host.WaitTime = value; _waitTime = value; } } } #endregion #region Private Methods private void broadcast (Opcode opcode, byte[] data, Action completed) { var cache = new Dictionary<CompressionMethod, byte[]> (); try { foreach (var host in Hosts) { if (_state != ServerState.Start) { _log.Error ("The server is shutting down."); break; } host.Sessions.Broadcast (opcode, data, cache); } if (completed != null) completed (); } catch (Exception ex) { _log.Error (ex.Message); _log.Debug (ex.ToString ()); } finally { cache.Clear (); } } private void broadcast (Opcode opcode, Stream stream, Action completed) { var cache = new Dictionary<CompressionMethod, Stream> (); try { foreach (var host in Hosts) { if (_state != ServerState.Start) { _log.Error ("The server is shutting down."); break; } host.Sessions.Broadcast (opcode, stream, cache); } if (completed != null) completed (); } catch (Exception ex) { _log.Error (ex.Message); _log.Debug (ex.ToString ()); } finally { foreach (var cached in cache.Values) cached.Dispose (); cache.Clear (); } } private void broadcastAsync (Opcode opcode, byte[] data, Action completed) { ThreadPool.QueueUserWorkItem ( state => broadcast (opcode, data, completed) ); } private void broadcastAsync (Opcode opcode, Stream stream, Action completed) { ThreadPool.QueueUserWorkItem ( state => broadcast (opcode, stream, completed) ); } private Dictionary<string, Dictionary<string, bool>> broadping ( byte[] frameAsBytes, TimeSpan timeout ) { var ret = new Dictionary<string, Dictionary<string, bool>> (); foreach (var host in Hosts) { if (_state != ServerState.Start) { _log.Error ("The server is shutting down."); break; } var res = host.Sessions.Broadping (frameAsBytes, timeout); ret.Add (host.Path, res); } return ret; } private bool canSet (out string message) { message = null; if (_state == ServerState.Start) { message = "The server has already started."; return false; } if (_state == ServerState.ShuttingDown) { message = "The server is shutting down."; return false; } return true; } #endregion #region Internal Methods internal void Add<TBehavior> (string path, Func<TBehavior> creator) where TBehavior : WebSocketBehavior { path = path.TrimSlashFromEnd (); lock (_sync) { WebSocketServiceHost host; if (_hosts.TryGetValue (path, out host)) throw new ArgumentException ("Already in use.", "path"); host = new WebSocketServiceHost<TBehavior> ( path, creator, null, _log ); if (!_clean) host.KeepClean = false; if (_waitTime != host.WaitTime) host.WaitTime = _waitTime; if (_state == ServerState.Start) host.Start (); _hosts.Add (path, host); } } internal bool InternalTryGetServiceHost ( string path, out WebSocketServiceHost host ) { path = path.TrimSlashFromEnd (); lock (_sync) return _hosts.TryGetValue (path, out host); } internal void Start () { lock (_sync) { foreach (var host in _hosts.Values) host.Start (); _state = ServerState.Start; } } internal void Stop (ushort code, string reason) { lock (_sync) { _state = ServerState.ShuttingDown; foreach (var host in _hosts.Values) host.Stop (code, reason); _state = ServerState.Stop; } } #endregion #region Public Methods /// <summary> /// Adds a WebSocket service with the specified behavior, path, /// and delegate. /// </summary> /// <param name="path"> /// <para> /// A <see cref="string"/> that represents an absolute path to /// the service to add. /// </para> /// <para> /// / is trimmed from the end of the string if present. /// </para> /// </param> /// <param name="initializer"> /// <para> /// An <c>Action&lt;TBehavior&gt;</c> delegate or /// <see langword="null"/> if not needed. /// </para> /// <para> /// The delegate invokes the method called when initializing /// a new session instance for the service. /// </para> /// </param> /// <typeparam name="TBehavior"> /// <para> /// The type of the behavior for the service. /// </para> /// <para> /// It must inherit the <see cref="WebSocketBehavior"/> class. /// </para> /// <para> /// And also, it must have a public parameterless constructor. /// </para> /// </typeparam> /// <exception cref="ArgumentNullException"> /// <paramref name="path"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="path"/> is empty. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="path"/> is not an absolute path. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="path"/> includes either or both /// query and fragment components. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="path"/> is already in use. /// </para> /// </exception> public void AddService<TBehavior> ( string path, Action<TBehavior> initializer ) where TBehavior : WebSocketBehavior, new () { if (path == null) throw new ArgumentNullException ("path"); if (path.Length == 0) throw new ArgumentException ("An empty string.", "path"); if (path[0] != '/') throw new ArgumentException ("Not an absolute path.", "path"); if (path.IndexOfAny (new[] { '?', '#' }) > -1) { var msg = "It includes either or both query and fragment components."; throw new ArgumentException (msg, "path"); } path = path.TrimSlashFromEnd (); lock (_sync) { WebSocketServiceHost host; if (_hosts.TryGetValue (path, out host)) throw new ArgumentException ("Already in use.", "path"); host = new WebSocketServiceHost<TBehavior> ( path, () => new TBehavior (), initializer, _log ); if (!_clean) host.KeepClean = false; if (_waitTime != host.WaitTime) host.WaitTime = _waitTime; if (_state == ServerState.Start) host.Start (); _hosts.Add (path, host); } } /// <summary> /// Sends <paramref name="data"/> to every client in the WebSocket services. /// </summary> /// <param name="data"> /// An array of <see cref="byte"/> that represents the binary data to send. /// </param> /// <exception cref="InvalidOperationException"> /// The current state of the manager is not Start. /// </exception> /// <exception cref="ArgumentNullException"> /// <paramref name="data"/> is <see langword="null"/>. /// </exception> [Obsolete ("This method will be removed.")] public void Broadcast (byte[] data) { if (_state != ServerState.Start) { var msg = "The current state of the manager is not Start."; throw new InvalidOperationException (msg); } if (data == null) throw new ArgumentNullException ("data"); if (data.LongLength <= WebSocket.FragmentLength) broadcast (Opcode.Binary, data, null); else broadcast (Opcode.Binary, new MemoryStream (data), null); } /// <summary> /// Sends <paramref name="data"/> to every client in the WebSocket services. /// </summary> /// <param name="data"> /// A <see cref="string"/> that represents the text data to send. /// </param> /// <exception cref="InvalidOperationException"> /// The current state of the manager is not Start. /// </exception> /// <exception cref="ArgumentNullException"> /// <paramref name="data"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="data"/> could not be UTF-8-encoded. /// </exception> [Obsolete ("This method will be removed.")] public void Broadcast (string data) { if (_state != ServerState.Start) { var msg = "The current state of the manager is not Start."; throw new InvalidOperationException (msg); } if (data == null) throw new ArgumentNullException ("data"); byte[] bytes; if (!data.TryGetUTF8EncodedBytes (out bytes)) { var msg = "It could not be UTF-8-encoded."; throw new ArgumentException (msg, "data"); } if (bytes.LongLength <= WebSocket.FragmentLength) broadcast (Opcode.Text, bytes, null); else broadcast (Opcode.Text, new MemoryStream (bytes), null); } /// <summary> /// Sends <paramref name="data"/> asynchronously to every client in /// the WebSocket services. /// </summary> /// <remarks> /// This method does not wait for the send to be complete. /// </remarks> /// <param name="data"> /// An array of <see cref="byte"/> that represents the binary data to send. /// </param> /// <param name="completed"> /// <para> /// An <see cref="Action"/> delegate or <see langword="null"/> /// if not needed. /// </para> /// <para> /// The delegate invokes the method called when the send is complete. /// </para> /// </param> /// <exception cref="InvalidOperationException"> /// The current state of the manager is not Start. /// </exception> /// <exception cref="ArgumentNullException"> /// <paramref name="data"/> is <see langword="null"/>. /// </exception> [Obsolete ("This method will be removed.")] public void BroadcastAsync (byte[] data, Action completed) { if (_state != ServerState.Start) { var msg = "The current state of the manager is not Start."; throw new InvalidOperationException (msg); } if (data == null) throw new ArgumentNullException ("data"); if (data.LongLength <= WebSocket.FragmentLength) broadcastAsync (Opcode.Binary, data, completed); else broadcastAsync (Opcode.Binary, new MemoryStream (data), completed); } /// <summary> /// Sends <paramref name="data"/> asynchronously to every client in /// the WebSocket services. /// </summary> /// <remarks> /// This method does not wait for the send to be complete. /// </remarks> /// <param name="data"> /// A <see cref="string"/> that represents the text data to send. /// </param> /// <param name="completed"> /// <para> /// An <see cref="Action"/> delegate or <see langword="null"/> /// if not needed. /// </para> /// <para> /// The delegate invokes the method called when the send is complete. /// </para> /// </param> /// <exception cref="InvalidOperationException"> /// The current state of the manager is not Start. /// </exception> /// <exception cref="ArgumentNullException"> /// <paramref name="data"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="data"/> could not be UTF-8-encoded. /// </exception> [Obsolete ("This method will be removed.")] public void BroadcastAsync (string data, Action completed) { if (_state != ServerState.Start) { var msg = "The current state of the manager is not Start."; throw new InvalidOperationException (msg); } if (data == null) throw new ArgumentNullException ("data"); byte[] bytes; if (!data.TryGetUTF8EncodedBytes (out bytes)) { var msg = "It could not be UTF-8-encoded."; throw new ArgumentException (msg, "data"); } if (bytes.LongLength <= WebSocket.FragmentLength) broadcastAsync (Opcode.Text, bytes, completed); else broadcastAsync (Opcode.Text, new MemoryStream (bytes), completed); } /// <summary> /// Sends the data from <paramref name="stream"/> asynchronously to /// every client in the WebSocket services. /// </summary> /// <remarks> /// <para> /// The data is sent as the binary data. /// </para> /// <para> /// This method does not wait for the send to be complete. /// </para> /// </remarks> /// <param name="stream"> /// A <see cref="Stream"/> instance from which to read the data to send. /// </param> /// <param name="length"> /// An <see cref="int"/> that specifies the number of bytes to send. /// </param> /// <param name="completed"> /// <para> /// An <see cref="Action"/> delegate or <see langword="null"/> /// if not needed. /// </para> /// <para> /// The delegate invokes the method called when the send is complete. /// </para> /// </param> /// <exception cref="InvalidOperationException"> /// The current state of the manager is not Start. /// </exception> /// <exception cref="ArgumentNullException"> /// <paramref name="stream"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="stream"/> cannot be read. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="length"/> is less than 1. /// </para> /// <para> /// -or- /// </para> /// <para> /// No data could be read from <paramref name="stream"/>. /// </para> /// </exception> [Obsolete ("This method will be removed.")] public void BroadcastAsync (Stream stream, int length, Action completed) { if (_state != ServerState.Start) { var msg = "The current state of the manager is not Start."; throw new InvalidOperationException (msg); } if (stream == null) throw new ArgumentNullException ("stream"); if (!stream.CanRead) { var msg = "It cannot be read."; throw new ArgumentException (msg, "stream"); } if (length < 1) { var msg = "Less than 1."; throw new ArgumentException (msg, "length"); } var bytes = stream.ReadBytes (length); var len = bytes.Length; if (len == 0) { var msg = "No data could be read from it."; throw new ArgumentException (msg, "stream"); } if (len < length) { _log.Warn ( String.Format ( "Only {0} byte(s) of data could be read from the stream.", len ) ); } if (len <= WebSocket.FragmentLength) broadcastAsync (Opcode.Binary, bytes, completed); else broadcastAsync (Opcode.Binary, new MemoryStream (bytes), completed); } /// <summary> /// Sends a ping to every client in the WebSocket services. /// </summary> /// <returns> /// <para> /// A <c>Dictionary&lt;string, Dictionary&lt;string, bool&gt;&gt;</c>. /// </para> /// <para> /// It represents a collection of pairs of a service path and another /// collection of pairs of a session ID and a value indicating whether /// a pong has been received from the client within a time. /// </para> /// </returns> /// <exception cref="InvalidOperationException"> /// The current state of the manager is not Start. /// </exception> [Obsolete ("This method will be removed.")] public Dictionary<string, Dictionary<string, bool>> Broadping () { if (_state != ServerState.Start) { var msg = "The current state of the manager is not Start."; throw new InvalidOperationException (msg); } return broadping (WebSocketFrame.EmptyPingBytes, _waitTime); } /// <summary> /// Sends a ping with <paramref name="message"/> to every client in /// the WebSocket services. /// </summary> /// <returns> /// <para> /// A <c>Dictionary&lt;string, Dictionary&lt;string, bool&gt;&gt;</c>. /// </para> /// <para> /// It represents a collection of pairs of a service path and another /// collection of pairs of a session ID and a value indicating whether /// a pong has been received from the client within a time. /// </para> /// </returns> /// <param name="message"> /// <para> /// A <see cref="string"/> that represents the message to send. /// </para> /// <para> /// The size must be 125 bytes or less in UTF-8. /// </para> /// </param> /// <exception cref="InvalidOperationException"> /// The current state of the manager is not Start. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="message"/> could not be UTF-8-encoded. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// The size of <paramref name="message"/> is greater than 125 bytes. /// </exception> [Obsolete ("This method will be removed.")] public Dictionary<string, Dictionary<string, bool>> Broadping (string message) { if (_state != ServerState.Start) { var msg = "The current state of the manager is not Start."; throw new InvalidOperationException (msg); } if (message.IsNullOrEmpty ()) return broadping (WebSocketFrame.EmptyPingBytes, _waitTime); byte[] bytes; if (!message.TryGetUTF8EncodedBytes (out bytes)) { var msg = "It could not be UTF-8-encoded."; throw new ArgumentException (msg, "message"); } if (bytes.Length > 125) { var msg = "Its size is greater than 125 bytes."; throw new ArgumentOutOfRangeException ("message", msg); } var frame = WebSocketFrame.CreatePingFrame (bytes, false); return broadping (frame.ToArray (), _waitTime); } /// <summary> /// Removes all WebSocket services managed by the manager. /// </summary> /// <remarks> /// A service is stopped with close status 1001 (going away) /// if it has already started. /// </remarks> public void Clear () { List<WebSocketServiceHost> hosts = null; lock (_sync) { hosts = _hosts.Values.ToList (); _hosts.Clear (); } foreach (var host in hosts) { if (host.State == ServerState.Start) host.Stop (1001, String.Empty); } } /// <summary> /// Removes a WebSocket service with the specified path. /// </summary> /// <remarks> /// The service is stopped with close status 1001 (going away) /// if it has already started. /// </remarks> /// <returns> /// <c>true</c> if the service is successfully found and removed; /// otherwise, <c>false</c>. /// </returns> /// <param name="path"> /// <para> /// A <see cref="string"/> that represents an absolute path to /// the service to remove. /// </para> /// <para> /// / is trimmed from the end of the string if present. /// </para> /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="path"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="path"/> is empty. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="path"/> is not an absolute path. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="path"/> includes either or both /// query and fragment components. /// </para> /// </exception> public bool RemoveService (string path) { if (path == null) throw new ArgumentNullException ("path"); if (path.Length == 0) throw new ArgumentException ("An empty string.", "path"); if (path[0] != '/') throw new ArgumentException ("Not an absolute path.", "path"); if (path.IndexOfAny (new[] { '?', '#' }) > -1) { var msg = "It includes either or both query and fragment components."; throw new ArgumentException (msg, "path"); } path = path.TrimSlashFromEnd (); WebSocketServiceHost host; lock (_sync) { if (!_hosts.TryGetValue (path, out host)) return false; _hosts.Remove (path); } if (host.State == ServerState.Start) host.Stop (1001, String.Empty); return true; } /// <summary> /// Tries to get the host instance for a WebSocket service with /// the specified path. /// </summary> /// <returns> /// <c>true</c> if the service is successfully found; otherwise, /// <c>false</c>. /// </returns> /// <param name="path"> /// <para> /// A <see cref="string"/> that represents an absolute path to /// the service to find. /// </para> /// <para> /// / is trimmed from the end of the string if present. /// </para> /// </param> /// <param name="host"> /// <para> /// When this method returns, a <see cref="WebSocketServiceHost"/> /// instance or <see langword="null"/> if not found. /// </para> /// <para> /// The host instance provides the function to access /// the information in the service. /// </para> /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="path"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="path"/> is empty. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="path"/> is not an absolute path. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="path"/> includes either or both /// query and fragment components. /// </para> /// </exception> public bool TryGetServiceHost (string path, out WebSocketServiceHost host) { if (path == null) throw new ArgumentNullException ("path"); if (path.Length == 0) throw new ArgumentException ("An empty string.", "path"); if (path[0] != '/') throw new ArgumentException ("Not an absolute path.", "path"); if (path.IndexOfAny (new[] { '?', '#' }) > -1) { var msg = "It includes either or both query and fragment components."; throw new ArgumentException (msg, "path"); } return InternalTryGetServiceHost (path, out host); } #endregion } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) Under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You Under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed Under the License is distributed on an "AS Is" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations Under the License. ==================================================================== */ namespace NPOI.SS.Formula.PTG { using System; using NPOI.Util; using NPOI.SS.Util; using NPOI.HSSF.Record; /** * Specifies a rectangular area of cells A1:A4 for instance. * @author andy * @author Jason Height (jheight at chariot dot net dot au) */ [Serializable] public abstract class AreaPtgBase : OperandPtg, AreaI { /** * TODO - (May-2008) fix subclasses of AreaPtg 'AreaN~' which are used in shared formulas. * see similar comment in ReferencePtg */ protected Exception NotImplemented() { return new NotImplementedException("Coding Error: This method should never be called. This ptg should be Converted"); } protected AreaPtgBase() { // do nothing } /** zero based, Unsigned 16 bit */ private int field_1_first_row; /** zero based, Unsigned 16 bit */ private int field_2_last_row; /** zero based, Unsigned 8 bit */ private int field_3_first_column; /** zero based, Unsigned 8 bit */ private int field_4_last_column; private static BitField rowRelative = BitFieldFactory.GetInstance(0x8000); private static BitField colRelative = BitFieldFactory.GetInstance(0x4000); private static BitField columnMask = BitFieldFactory.GetInstance(0x3FFF); protected AreaPtgBase(String arearef) : this(new AreaReference(arearef)) { //AreaReference ar = new AreaReference(arearef); //CellReference firstCell = ar.FirstCell; //CellReference lastCell = ar.LastCell; //FirstRow = firstCell.Row; //FirstColumn = firstCell.Col; //LastRow = lastCell.Row; //LastColumn = lastCell.Col; //IsFirstColRelative = !firstCell.IsColAbsolute; //IsLastColRelative = !lastCell.IsColAbsolute; //IsFirstRowRelative = !firstCell.IsRowAbsolute; //IsLastRowRelative = !lastCell.IsRowAbsolute; } protected AreaPtgBase(AreaReference ar) { CellReference firstCell = ar.FirstCell; CellReference lastCell = ar.LastCell; FirstRow = (firstCell.Row); FirstColumn = (firstCell.Col == -1 ? 0 : (int)firstCell.Col); LastRow = (lastCell.Row); LastColumn = (lastCell.Col == -1 ? 0xFF : (int)lastCell.Col); IsFirstColRelative = (!firstCell.IsColAbsolute); IsLastColRelative = (!lastCell.IsColAbsolute); IsFirstRowRelative = (!firstCell.IsRowAbsolute); IsLastRowRelative = (!lastCell.IsRowAbsolute); } protected AreaPtgBase(int firstRow, int lastRow, int firstColumn, int lastColumn, bool firstRowRelative, bool lastRowRelative, bool firstColRelative, bool lastColRelative) { if (lastRow > firstRow) { FirstRow=(firstRow); LastRow=(lastRow); IsFirstRowRelative=(firstRowRelative); IsLastRowRelative = (lastRowRelative); } else { FirstRow=(lastRow); LastRow=(firstRow); IsFirstRowRelative = (lastRowRelative); IsLastRowRelative = (firstRowRelative); } if (lastColumn > firstColumn) { FirstColumn=(firstColumn); LastColumn=(lastColumn); IsFirstColRelative = (firstColRelative); IsLastColRelative = (lastColRelative); } else { FirstColumn=(lastColumn); LastColumn=(firstColumn); IsFirstColRelative = (lastColRelative); IsLastColRelative = (firstColRelative); } } protected void ReadCoordinates(ILittleEndianInput in1) { field_1_first_row = in1.ReadUShort(); field_2_last_row = in1.ReadUShort(); field_3_first_column = in1.ReadUShort(); field_4_last_column = in1.ReadUShort(); } protected void WriteCoordinates(ILittleEndianOutput out1) { out1.WriteShort(field_1_first_row); out1.WriteShort(field_2_last_row); out1.WriteShort(field_3_first_column); out1.WriteShort(field_4_last_column); } protected void WriteCoordinates(byte[] array, int offset) { LittleEndian.PutUShort(array, offset + 0, field_1_first_row); LittleEndian.PutUShort(array, offset + 2, field_2_last_row); LittleEndian.PutUShort(array, offset + 4, field_3_first_column); LittleEndian.PutUShort(array, offset + 6, field_4_last_column); } protected AreaPtgBase(RecordInputStream in1) { field_1_first_row = in1.ReadUShort(); field_2_last_row = in1.ReadUShort(); field_3_first_column = in1.ReadUShort(); field_4_last_column = in1.ReadUShort(); } /** * @return the first row in the area */ public virtual int FirstRow { get { return field_1_first_row; } set { field_1_first_row = value; } } /** * @return last row in the range (x2 in x1,y1-x2,y2) */ public virtual int LastRow { get { return field_2_last_row; } set { field_2_last_row = value; } } /** * @return the first column number in the area. */ public virtual int FirstColumn { get { return columnMask.GetValue(field_3_first_column); } set { field_3_first_column = columnMask.SetValue(field_3_first_column, value); } } /** * @return whether or not the first row is a relative reference or not. */ public virtual bool IsFirstRowRelative { get { return rowRelative.IsSet(field_3_first_column); } set { field_3_first_column = rowRelative.SetBoolean(field_3_first_column, value); } } /** * @return Isrelative first column to relative or not */ public virtual bool IsFirstColRelative { get { return colRelative.IsSet(field_3_first_column); } set { field_3_first_column = colRelative.SetBoolean(field_3_first_column, value); } } /** * @return lastcolumn in the area */ public virtual int LastColumn { get { return columnMask.GetValue(field_4_last_column); } set { field_4_last_column = columnMask.SetValue(field_4_last_column, value); } } /** * @return last column and bitmask (the raw field) */ public virtual short LastColumnRaw { get { return (short)field_4_last_column; } } /** * @return last row relative or not */ public virtual bool IsLastRowRelative { get { return rowRelative.IsSet(field_4_last_column); } set { field_4_last_column = rowRelative.SetBoolean(field_4_last_column, value); } } /** * @return lastcol relative or not */ public virtual bool IsLastColRelative { get { return colRelative.IsSet(field_4_last_column); } set { field_4_last_column = colRelative.SetBoolean(field_4_last_column, value); } } /** * Set the last column irrespective of the bitmasks */ public void SetLastColumnRaw(short column) { field_4_last_column = column; } public override String ToFormulaString() { return FormatReferenceAsString(); } public override byte DefaultOperandClass { get { return Ptg.CLASS_REF; } } protected String FormatReferenceAsString() { CellReference topLeft = new CellReference(FirstRow, FirstColumn, !IsFirstRowRelative, !IsFirstColRelative); CellReference botRight = new CellReference(LastRow, LastColumn, !IsLastRowRelative, !IsLastColRelative); if (AreaReference.IsWholeColumnReference(topLeft, botRight)) { return (new AreaReference(topLeft, botRight)).FormatAsString(); } return topLeft.FormatAsString() + ":" + botRight.FormatAsString(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Text; using System.Threading; using System.Security; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Globalization; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Diagnostics.Contracts; namespace System.Diagnostics { // READ ME: // Modifying the order or fields of this object may require other changes // to the unmanaged definition of the StackFrameHelper class, in // VM\DebugDebugger.h. The binder will catch some of these layout problems. [Serializable] internal class StackFrameHelper : IDisposable { [NonSerialized] private Thread targetThread; private int[] rgiOffset; private int[] rgiILOffset; // this field is here only for backwards compatibility of serialization format private MethodBase[] rgMethodBase; #pragma warning disable 414 // dynamicMethods is an array of System.Resolver objects, used to keep // DynamicMethodDescs alive for the lifetime of StackFrameHelper. private Object dynamicMethods; // Field is not used from managed. [NonSerialized] private IntPtr[] rgMethodHandle; private String[] rgAssemblyPath; private IntPtr[] rgLoadedPeAddress; private int[] rgiLoadedPeSize; private IntPtr[] rgInMemoryPdbAddress; private int[] rgiInMemoryPdbSize; // if rgiMethodToken[i] == 0, then don't attempt to get the portable PDB source/info private int[] rgiMethodToken; private String[] rgFilename; private int[] rgiLineNumber; private int[] rgiColumnNumber; [OptionalField] private bool[] rgiLastFrameFromForeignExceptionStackTrace; private GetSourceLineInfoDelegate getSourceLineInfo; private int iFrameCount; #pragma warning restore 414 private delegate void GetSourceLineInfoDelegate(string assemblyPath, IntPtr loadedPeAddress, int loadedPeSize, IntPtr inMemoryPdbAddress, int inMemoryPdbSize, int methodToken, int ilOffset, out string sourceFile, out int sourceLine, out int sourceColumn); private static Type s_symbolsType = null; private static MethodInfo s_symbolsMethodInfo = null; [ThreadStatic] private static int t_reentrancy = 0; public StackFrameHelper(Thread target) { targetThread = target; rgMethodBase = null; rgMethodHandle = null; rgiMethodToken = null; rgiOffset = null; rgiILOffset = null; rgAssemblyPath = null; rgLoadedPeAddress = null; rgiLoadedPeSize = null; rgInMemoryPdbAddress = null; rgiInMemoryPdbSize = null; dynamicMethods = null; rgFilename = null; rgiLineNumber = null; rgiColumnNumber = null; getSourceLineInfo = null; rgiLastFrameFromForeignExceptionStackTrace = null; // 0 means capture all frames. For StackTraces from an Exception, the EE always // captures all frames. For other uses of StackTraces, we can abort stack walking after // some limit if we want to by setting this to a non-zero value. In Whidbey this was // hard-coded to 512, but some customers complained. There shouldn't be any need to limit // this as memory/CPU is no longer allocated up front. If there is some reason to provide a // limit in the future, then we should expose it in the managed API so applications can // override it. iFrameCount = 0; } // // Initializes the stack trace helper. If fNeedFileInfo is true, initializes rgFilename, // rgiLineNumber and rgiColumnNumber fields using the portable PDB reader if not already // done by GetStackFramesInternal (on Windows for old PDB format). // internal void InitializeSourceInfo(int iSkip, bool fNeedFileInfo, Exception exception) { StackTrace.GetStackFramesInternal(this, iSkip, fNeedFileInfo, exception); if (!fNeedFileInfo) return; // Check if this function is being reentered because of an exception in the code below if (t_reentrancy > 0) return; t_reentrancy++; try { if (s_symbolsMethodInfo == null) { s_symbolsType = Type.GetType( "System.Diagnostics.StackTraceSymbols, System.Diagnostics.StackTrace, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", throwOnError: false); if (s_symbolsType == null) return; s_symbolsMethodInfo = s_symbolsType.GetMethod("GetSourceLineInfo", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); if (s_symbolsMethodInfo == null) return; } if (getSourceLineInfo == null) { // Create an instance of System.Diagnostics.Stacktrace.Symbols object target = Activator.CreateInstance(s_symbolsType); // Create an instance delegate for the GetSourceLineInfo method getSourceLineInfo = (GetSourceLineInfoDelegate)s_symbolsMethodInfo.CreateDelegate(typeof(GetSourceLineInfoDelegate), target); } for (int index = 0; index < iFrameCount; index++) { // If there was some reason not to try get the symbols from the portable PDB reader like the module was // ENC or the source/line info was already retrieved, the method token is 0. if (rgiMethodToken[index] != 0) { getSourceLineInfo(rgAssemblyPath[index], rgLoadedPeAddress[index], rgiLoadedPeSize[index], rgInMemoryPdbAddress[index], rgiInMemoryPdbSize[index], rgiMethodToken[index], rgiILOffset[index], out rgFilename[index], out rgiLineNumber[index], out rgiColumnNumber[index]); } } } catch { } finally { t_reentrancy--; } } void IDisposable.Dispose() { if (getSourceLineInfo != null) { IDisposable disposable = getSourceLineInfo.Target as IDisposable; if (disposable != null) { disposable.Dispose(); } } } public virtual MethodBase GetMethodBase(int i) { // There may be a better way to do this. // we got RuntimeMethodHandles here and we need to go to MethodBase // but we don't know whether the reflection info has been initialized // or not. So we call GetMethods and GetConstructors on the type // and then we fetch the proper MethodBase!! IntPtr mh = rgMethodHandle[i]; if (mh.IsNull()) return null; IRuntimeMethodInfo mhReal = RuntimeMethodHandle.GetTypicalMethodDefinition(new RuntimeMethodInfoStub(mh, this)); return RuntimeType.GetMethodBase(mhReal); } public virtual int GetOffset(int i) { return rgiOffset[i]; } public virtual int GetILOffset(int i) { return rgiILOffset[i]; } public virtual String GetFilename(int i) { return rgFilename == null ? null : rgFilename[i]; } public virtual int GetLineNumber(int i) { return rgiLineNumber == null ? 0 : rgiLineNumber[i]; } public virtual int GetColumnNumber(int i) { return rgiColumnNumber == null ? 0 : rgiColumnNumber[i]; } public virtual bool IsLastFrameFromForeignExceptionStackTrace(int i) { return (rgiLastFrameFromForeignExceptionStackTrace == null) ? false : rgiLastFrameFromForeignExceptionStackTrace[i]; } public virtual int GetNumberOfFrames() { return iFrameCount; } // // serialization implementation // [OnSerializing] private void OnSerializing(StreamingContext context) { // this is called in the process of serializing this object. // For compatibility with Everett we need to assign the rgMethodBase field as that is the field // that will be serialized rgMethodBase = (rgMethodHandle == null) ? null : new MethodBase[rgMethodHandle.Length]; if (rgMethodHandle != null) { for (int i = 0; i < rgMethodHandle.Length; i++) { if (!rgMethodHandle[i].IsNull()) rgMethodBase[i] = RuntimeType.GetMethodBase(new RuntimeMethodInfoStub(rgMethodHandle[i], this)); } } } [OnSerialized] private void OnSerialized(StreamingContext context) { // after we are done serializing null the rgMethodBase field rgMethodBase = null; } [OnDeserialized] private void OnDeserialized(StreamingContext context) { // after we are done deserializing we need to transform the rgMethodBase in rgMethodHandle rgMethodHandle = (rgMethodBase == null) ? null : new IntPtr[rgMethodBase.Length]; if (rgMethodBase != null) { for (int i = 0; i < rgMethodBase.Length; i++) { if (rgMethodBase[i] != null) rgMethodHandle[i] = rgMethodBase[i].MethodHandle.Value; } } rgMethodBase = null; } } // Class which represents a description of a stack trace // There is no good reason for the methods of this class to be virtual. // In order to ensure trusted code can trust the data it gets from a // StackTrace, we use an InheritanceDemand to prevent partially-trusted // subclasses. [Serializable] public class StackTrace { private StackFrame[] frames; private int m_iNumOfFrames; public const int METHODS_TO_SKIP = 0; private int m_iMethodsToSkip; // Constructs a stack trace from the current location. public StackTrace() { m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace(METHODS_TO_SKIP, false, null, null); } // Constructs a stack trace from the current location. // public StackTrace(bool fNeedFileInfo) { m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace(METHODS_TO_SKIP, fNeedFileInfo, null, null); } // Constructs a stack trace from the current location, in a caller's // frame // public StackTrace(int skipFrames) { if (skipFrames < 0) throw new ArgumentOutOfRangeException(nameof(skipFrames), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace(skipFrames + METHODS_TO_SKIP, false, null, null); } // Constructs a stack trace from the current location, in a caller's // frame // public StackTrace(int skipFrames, bool fNeedFileInfo) { if (skipFrames < 0) throw new ArgumentOutOfRangeException(nameof(skipFrames), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace(skipFrames + METHODS_TO_SKIP, fNeedFileInfo, null, null); } // Constructs a stack trace from the current location. public StackTrace(Exception e) { if (e == null) throw new ArgumentNullException(nameof(e)); Contract.EndContractBlock(); m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace(METHODS_TO_SKIP, false, null, e); } // Constructs a stack trace from the current location. // public StackTrace(Exception e, bool fNeedFileInfo) { if (e == null) throw new ArgumentNullException(nameof(e)); Contract.EndContractBlock(); m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace(METHODS_TO_SKIP, fNeedFileInfo, null, e); } // Constructs a stack trace from the current location, in a caller's // frame // public StackTrace(Exception e, int skipFrames) { if (e == null) throw new ArgumentNullException(nameof(e)); if (skipFrames < 0) throw new ArgumentOutOfRangeException(nameof(skipFrames), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace(skipFrames + METHODS_TO_SKIP, false, null, e); } // Constructs a stack trace from the current location, in a caller's // frame // public StackTrace(Exception e, int skipFrames, bool fNeedFileInfo) { if (e == null) throw new ArgumentNullException(nameof(e)); if (skipFrames < 0) throw new ArgumentOutOfRangeException(nameof(skipFrames), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace(skipFrames + METHODS_TO_SKIP, fNeedFileInfo, null, e); } // Constructs a "fake" stack trace, just containing a single frame. // Does not have the overhead of a full stack trace. // public StackTrace(StackFrame frame) { frames = new StackFrame[1]; frames[0] = frame; m_iMethodsToSkip = 0; m_iNumOfFrames = 1; } // Constructs a stack trace for the given thread // [Obsolete("This constructor has been deprecated. Please use a constructor that does not require a Thread parameter. http://go.microsoft.com/fwlink/?linkid=14202")] public StackTrace(Thread targetThread, bool needFileInfo) { m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace(METHODS_TO_SKIP, needFileInfo, targetThread, null); } [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void GetStackFramesInternal(StackFrameHelper sfh, int iSkip, bool fNeedFileInfo, Exception e); internal static int CalculateFramesToSkip(StackFrameHelper StackF, int iNumFrames) { int iRetVal = 0; String PackageName = "System.Diagnostics"; // Check if this method is part of the System.Diagnostics // package. If so, increment counter keeping track of // System.Diagnostics functions for (int i = 0; i < iNumFrames; i++) { MethodBase mb = StackF.GetMethodBase(i); if (mb != null) { Type t = mb.DeclaringType; if (t == null) break; String ns = t.Namespace; if (ns == null) break; if (String.Compare(ns, PackageName, StringComparison.Ordinal) != 0) break; } iRetVal++; } return iRetVal; } // Retrieves an object with stack trace information encoded. // It leaves out the first "iSkip" lines of the stacktrace. // private void CaptureStackTrace(int iSkip, bool fNeedFileInfo, Thread targetThread, Exception e) { m_iMethodsToSkip += iSkip; using (StackFrameHelper StackF = new StackFrameHelper(targetThread)) { StackF.InitializeSourceInfo(0, fNeedFileInfo, e); m_iNumOfFrames = StackF.GetNumberOfFrames(); if (m_iMethodsToSkip > m_iNumOfFrames) m_iMethodsToSkip = m_iNumOfFrames; if (m_iNumOfFrames != 0) { frames = new StackFrame[m_iNumOfFrames]; for (int i = 0; i < m_iNumOfFrames; i++) { bool fDummy1 = true; bool fDummy2 = true; StackFrame sfTemp = new StackFrame(fDummy1, fDummy2); sfTemp.SetMethodBase(StackF.GetMethodBase(i)); sfTemp.SetOffset(StackF.GetOffset(i)); sfTemp.SetILOffset(StackF.GetILOffset(i)); sfTemp.SetIsLastFrameFromForeignExceptionStackTrace(StackF.IsLastFrameFromForeignExceptionStackTrace(i)); if (fNeedFileInfo) { sfTemp.SetFileName(StackF.GetFilename(i)); sfTemp.SetLineNumber(StackF.GetLineNumber(i)); sfTemp.SetColumnNumber(StackF.GetColumnNumber(i)); } frames[i] = sfTemp; } // CalculateFramesToSkip skips all frames in the System.Diagnostics namespace, // but this is not desired if building a stack trace from an exception. if (e == null) m_iMethodsToSkip += CalculateFramesToSkip(StackF, m_iNumOfFrames); m_iNumOfFrames -= m_iMethodsToSkip; if (m_iNumOfFrames < 0) { m_iNumOfFrames = 0; } } // In case this is the same object being re-used, set frames to null else frames = null; } } // Property to get the number of frames in the stack trace // public virtual int FrameCount { get { return m_iNumOfFrames; } } // Returns a given stack frame. Stack frames are numbered starting at // zero, which is the last stack frame pushed. // public virtual StackFrame GetFrame(int index) { if ((frames != null) && (index < m_iNumOfFrames) && (index >= 0)) return frames[index + m_iMethodsToSkip]; return null; } // Returns an array of all stack frames for this stacktrace. // The array is ordered and sized such that GetFrames()[i] == GetFrame(i) // The nth element of this array is the same as GetFrame(n). // The length of the array is the same as FrameCount. // public virtual StackFrame[] GetFrames() { if (frames == null || m_iNumOfFrames <= 0) return null; // We have to return a subset of the array. Unfortunately this // means we have to allocate a new array and copy over. StackFrame[] array = new StackFrame[m_iNumOfFrames]; Array.Copy(frames, m_iMethodsToSkip, array, 0, m_iNumOfFrames); return array; } // Builds a readable representation of the stack trace // public override String ToString() { // Include a trailing newline for backwards compatibility return ToString(TraceFormat.TrailingNewLine); } // TraceFormat is Used to specify options for how the // string-representation of a StackTrace should be generated. internal enum TraceFormat { Normal, TrailingNewLine, // include a trailing new line character NoResourceLookup // to prevent infinite resource recusion } // Builds a readable representation of the stack trace, specifying // the format for backwards compatibility. internal String ToString(TraceFormat traceFormat) { bool displayFilenames = true; // we'll try, but demand may fail String word_At = "at"; String inFileLineNum = "in {0}:line {1}"; if (traceFormat != TraceFormat.NoResourceLookup) { word_At = Environment.GetResourceString("Word_At"); inFileLineNum = Environment.GetResourceString("StackTrace_InFileLineNumber"); } bool fFirstFrame = true; StringBuilder sb = new StringBuilder(255); for (int iFrameIndex = 0; iFrameIndex < m_iNumOfFrames; iFrameIndex++) { StackFrame sf = GetFrame(iFrameIndex); MethodBase mb = sf.GetMethod(); if (mb != null) { // We want a newline at the end of every line except for the last if (fFirstFrame) fFirstFrame = false; else sb.Append(Environment.NewLine); sb.AppendFormat(CultureInfo.InvariantCulture, " {0} ", word_At); Type t = mb.DeclaringType; // if there is a type (non global method) print it if (t != null) { // Append t.FullName, replacing '+' with '.' string fullName = t.FullName; for (int i = 0; i < fullName.Length; i++) { char ch = fullName[i]; sb.Append(ch == '+' ? '.' : ch); } sb.Append('.'); } sb.Append(mb.Name); // deal with the generic portion of the method if (mb is MethodInfo && ((MethodInfo)mb).IsGenericMethod) { Type[] typars = ((MethodInfo)mb).GetGenericArguments(); sb.Append('['); int k = 0; bool fFirstTyParam = true; while (k < typars.Length) { if (fFirstTyParam == false) sb.Append(','); else fFirstTyParam = false; sb.Append(typars[k].Name); k++; } sb.Append(']'); } ParameterInfo[] pi = null; try { pi = mb.GetParameters(); } catch { // The parameter info cannot be loaded, so we don't // append the parameter list. } if (pi != null) { // arguments printing sb.Append('('); bool fFirstParam = true; for (int j = 0; j < pi.Length; j++) { if (fFirstParam == false) sb.Append(", "); else fFirstParam = false; String typeName = "<UnknownType>"; if (pi[j].ParameterType != null) typeName = pi[j].ParameterType.Name; sb.Append(typeName); sb.Append(' '); sb.Append(pi[j].Name); } sb.Append(')'); } // source location printing if (displayFilenames && (sf.GetILOffset() != -1)) { // If we don't have a PDB or PDB-reading is disabled for the module, // then the file name will be null. String fileName = null; // Getting the filename from a StackFrame is a privileged operation - we won't want // to disclose full path names to arbitrarily untrusted code. Rather than just omit // this we could probably trim to just the filename so it's still mostly usefull. try { fileName = sf.GetFileName(); } catch (SecurityException) { // If the demand for displaying filenames fails, then it won't // succeed later in the loop. Avoid repeated exceptions by not trying again. displayFilenames = false; } if (fileName != null) { // tack on " in c:\tmp\MyFile.cs:line 5" sb.Append(' '); sb.AppendFormat(CultureInfo.InvariantCulture, inFileLineNum, fileName, sf.GetFileLineNumber()); } } if (sf.GetIsLastFrameFromForeignExceptionStackTrace()) { sb.Append(Environment.NewLine); sb.Append(Environment.GetResourceString("Exception_EndStackTraceFromPreviousThrow")); } } } if (traceFormat == TraceFormat.TrailingNewLine) sb.Append(Environment.NewLine); return sb.ToString(); } // This helper is called from within the EE to construct a string representation // of the current stack trace. private static String GetManagedStackTraceStringHelper(bool fNeedFileInfo) { // Note all the frames in System.Diagnostics will be skipped when capturing // a normal stack trace (not from an exception) so we don't need to explicitly // skip the GetManagedStackTraceStringHelper frame. StackTrace st = new StackTrace(0, fNeedFileInfo); return st.ToString(); } } }
using System; using System.Linq.Expressions; using System.Threading.Tasks; using NSpectator.Domain; // ReSharper disable InconsistentNaming namespace NSpectator { /// <summary> /// Inherit from this class to create your own specifications. /// SpecRunner will look through your project for /// classes that derive from this class (inheritance chain is taken into consideration). /// </summary> public class Spec { public static string todo_reason => string.Empty; /// <summary> /// ctor /// </summary> public Spec() { Context = new ActionRegister(AddContext); xContext = new ActionRegister(AddIgnoredContext); Describe = new ActionRegister(AddContext); xDescribe = new ActionRegister(AddIgnoredContext); It = new ActionRegister((name, tags, action) => AddExample(new Example(name, tags, action, pending: action == Todo))); xIt = new ActionRegister((name, tags, action) => AddExample(new Example(name, tags, action, pending: true))); ItAsync = new AsyncActionRegister((name, tags, asyncAction) => AddExample(new AsyncExample(name, tags, asyncAction, pending: asyncAction == TodoAsync))); xItAsync = new AsyncActionRegister((name, tags, asyncAction) => AddExample(new AsyncExample(name, tags, asyncAction, pending: true))); } /// <summary> /// Create a specification/example using a single line lambda with an assertion/expectation /// The name of the specification will be parsed from the Expression /// <para>For Example:</para> /// <para>specify = () => _controller.should_be(false);</para> /// </summary> public virtual Expression<Action> Specify { set { AddExample(new Example(value)); } } /* No need for the following, as async lambda expressions cannot be converted to expression trees: public virtual Expression<Func<Task>> specifyAsync { ... } */ /// <summary> /// Mark a spec as pending /// <para>For Example:</para> /// <para>xspecify = () => _controller.Expected().False();</para> /// <para>(the example will be marked as pending any lambda provided will not be executed)</para> /// </summary> public virtual Expression<Action> xSpecify { set { AddExample(new Example(value, pending: true)); } } /* No need for the following, as async lambda expressions cannot be converted to expression trees: public virtual Expression<Func<Task>> xspecifyAsync { ... } */ /// <summary> /// This Action gets executed before each example is run. /// <para>For Example:</para> /// <para>before = () => someList = new List&lt;int&gt;();</para> /// <para>The before can be a multi-line lambda. Setting the member multiple times through out sub-contexts will not override the action, but instead will append to your setup (this is a good thing). /// For more information visit https://github.com/nspectator/NSpectator/wiki </para> /// </summary> public virtual Action Before { get { return InnerContext.Before; } set { InnerContext.Before = value; } } /// <summary> /// This Function gets executed asynchronously before each example is run. /// <para>For Example:</para> /// <para>beforeAsync = async () => someList = await GetListAsync();</para> /// <para>The beforeAsync can be a multi-line lambda. Setting the member multiple times through out sub-contexts will not override the action, but instead will append to your setup (this is a good thing).</para> /// <para>For more information visit https://github.com/nspectator/NSpectator/wiki </para> /// </summary> public virtual Func<Task> BeforeAsync { get { return InnerContext.BeforeAsync; } set { InnerContext.BeforeAsync = value; } } /// <summary> /// This Action is an alias of before. This Action gets executed before each example is run. /// <para>For Example:</para> /// <para>beforeEach = () => someList = new List&lt;int&gt;();</para> /// <para>The beforeEach can be a multi-line lambda. Setting the member multiple times through out sub-contexts will not override the action, but instead will append to your setup (this is a good thing).</para> /// <para>For more information visit https://github.com/nspectator/NSpectator/wiki </para> /// </summary> public virtual Action BeforeEach { get { return InnerContext.Before; } set { InnerContext.Before = value; } } /// <summary> /// This Function is an alias of beforeAsync. It gets executed asynchronously before each example is run. /// <para>For Example:</para> /// <para>beforeEachAsync = async () => someList = await GetListAsync();</para> /// <para>The beforeEachAsync can be a multi-line lambda. Setting the member multiple times through out sub-contexts will not override the action, but instead will append to your setup (this is a good thing). </para> /// <para> For more information visit https://github.com/nspectator/NSpectator/wiki </para> /// </summary> public virtual Func<Task> BeforeEachAsync { get { return InnerContext.BeforeAsync; } set { InnerContext.BeforeAsync = value; } } /// <summary> /// This Action gets executed before all examples in a context. /// <para>For Example:</para> /// <para>beforeAll = () => someList = new List&lt;int&gt;();</para> /// <para>The beforeAll can be a multi-line lambda. Setting the member multiple times through out sub-contexts will not override the action, but instead will append to your setup (this is a good thing). </para> /// <para>For more information visit https://github.com/nspectator/NSpectator/wiki </para> /// </summary> public virtual Action BeforeAll { get { return InnerContext.BeforeAll; } set { InnerContext.BeforeAll = value; } } /// <summary> /// This Function gets executed asynchronously before all examples in a context. /// <para>For Example:</para> /// <para>beforeAllAsync = async () => someList = await GetListAsync();</para> /// <para>The beforeAllAsync can be a multi-line lambda. Setting the member multiple times through out sub-contexts will not override the action, but instead will append to your setup (this is a good thing).</para> /// <para>For more information visit https://github.com/nspectator/NSpectator/wiki </para> /// </summary> public virtual Func<Task> BeforeAllAsync { get { return InnerContext.BeforeAllAsync; } set { InnerContext.BeforeAllAsync = value; } } /// <summary> /// This Action gets executed after each example is run. /// <para>For Example:</para> /// <para>after = () => someList = new List&lt;int&gt;();</para> /// <para>The after can be a multi-line lambda. Setting the member multiple times through out sub-contexts will not override the action, but instead will append to your setup (this is a good thing). </para> /// <para>For more information visit https://github.com/nspectator/NSpectator/wiki </para> /// </summary> public virtual Action After { get { return InnerContext.After; } set { InnerContext.After = value; } } /// <summary> /// This Function gets executed asynchronously after each example is run. /// <para>For Example:</para> /// <para>afterAsync = async () => someList = await GetListAsync();</para> /// <para>The after can be a multi-line lambda. Setting the member multiple times through out sub-contexts will not override the action, but instead will append to your setup (this is a good thing). </para> /// <para>For more information visit https://github.com/nspectator/NSpectator/wiki </para> /// </summary> public virtual Func<Task> AfterAsync { get { return InnerContext.AfterAsync; } set { InnerContext.AfterAsync = value; } } /// <summary> /// This Action is an alias of after. This Action gets executed after each example is run. /// <para>For Example:</para> /// <para>afterEach = () => someList = new List&lt;int&gt;();</para> /// <para>The afterEach can be a multi-line lambda. Setting the member multiple times through out sub-contexts will not override the action, but instead will append to your setup (this is a good thing). </para> /// <para>For more information visit https://github.com/nspectator/NSpectator/wiki </para> /// </summary> public virtual Action AfterEach { get { return InnerContext.After; } set { InnerContext.After = value; } } /// <summary> /// This Action is an alias of afterAsync. This Function gets executed asynchronously after each example is run. /// <para>For Example:</para> /// <para>afterEachAsync = async () => someList = await GetListAsync();</para> /// <para>The after can be a multi-line lambda. Setting the member multiple times through out sub-contexts will not override the action, but instead will append to your setup (this is a good thing). </para> /// <para>For more information visit https://github.com/nspectator/NSpectator/wiki </para> /// </summary> public virtual Func<Task> AfterEachAsync { get { return InnerContext.AfterAsync; } set { InnerContext.AfterAsync = value; } } /// <summary> /// This Action gets executed after all examples in a context. /// <para>For Example:</para> /// <para>afterAll = () => someList = new List&lt;int&gt;();</para> /// <para>The afterAll can be a multi-line lambda. Setting the member multiple times through out sub-contexts will not override the action, but instead will append to your setup (this is a good thing). </para> /// <para>For more information visit https://github.com/nspectator/NSpectator/wiki </para> /// </summary> public virtual Action AfterAll { get { return InnerContext.AfterAll; } set { InnerContext.AfterAll = value; } } /// <summary> /// This Function gets executed asynchronously after all examples in a context. /// <para>For Example:</para> /// <para>afterAllAsync = async () => someList = await GetListAsync();</para> /// <para>The afterAllAsync can be a multi-line lambda. Setting the member multiple times through out sub-contexts will not override the action, but instead will append to your setup (this is a good thing).</para> /// <para>For more information visit https://github.com/nspectator/NSpectator/wiki </para> /// </summary> public virtual Func<Task> AfterAllAsync { get { return InnerContext.AfterAllAsync; } set { InnerContext.AfterAllAsync = value; } } /// <summary> /// Assign this member within your context. The Action assigned will gets executed /// with every example in scope. Befores will run first, then acts, then your examples. /// <para>It's a way for you to define once a common Act in Arrange-Act-Assert for all subcontexts. </para> /// <para>For more information visit https://github.com/nspectator/NSpectator/wiki </para> /// </summary> public virtual Action Act { get { return InnerContext.Act; } set { InnerContext.Act = value; } } /// <summary> /// Assign this member within your context. The Function assigned will gets executed asynchronously /// with every example in scope. Befores will run first, then acts, then your examples. /// It's a way for you to define once a common Act in Arrange-Act-Assert for all subcontexts. /// For more information visit https://github.com/nspectator/NSpectator/wiki /// </summary> public virtual Func<Task> ActAsync { get { return InnerContext.ActAsync; } set { InnerContext.ActAsync = value; } } /// <summary> /// Create a subcontext. /// <para>For Examples see https://github.com/nspectator/NSpectator/wiki </para> /// </summary> public ActionRegister Context { get; } /// <summary> /// Mark a subcontext as pending (add all child contexts as pending) /// </summary> public ActionRegister xContext { get; } /// <summary> /// This is an alias for creating a subcontext. Use this to create sub contexts within your methods. /// <para>For Examples see https://github.com/nspectator/NSpectator/wiki </para> /// </summary> public ActionRegister Describe { get; } /// <summary> /// This is an alias for creating a xcontext. /// <para>For Examples see https://github.com/nspectator/NSpectator/wiki </para> /// </summary> public ActionRegister xDescribe { get; } /// <summary> /// Create a specification/example using a name and a lambda with an assertion(should). /// <para>For Example:</para> /// <para>it["should return false"] = () => _controller.Should().BeFalse();</para> /// </summary> public ActionRegister It { get; } /// <summary> /// Create an asynchronous specification/example using a name and an async lambda with an assertion(should). /// <para>For Example:</para> /// <para>itAsync["should return false"] = async () => (await GetResultAsync()).Should().BeFalse();</para> /// </summary> public AsyncActionRegister ItAsync { get; } /// <summary> /// Mark a spec as pending /// <para>For Example:</para> /// <para>xit["should return false"] = () => _controller.should_be(false);</para> /// <para>(the example will be marked as pending, any lambda provided will not be executed)</para> /// </summary> public ActionRegister xIt { get; } /// <summary> /// Mark an asynchronous spec as pending /// <para>For Example:</para> /// <para>xitAsync["should return false"] = async () => (await GetResultAsync()).should_be(false);</para> /// <para>(the example will be marked as pending, any lambda provided will not be executed)</para> /// </summary> public AsyncActionRegister xItAsync { get; } /// <summary> /// Set up a pending spec. /// <para>For Example:</para> /// <para>it["a test i haven't flushed out yet, but need to"] = todo;</para> /// </summary> public readonly Action Todo = () => { }; /// <summary> /// Set up a pending asynchronous spec. /// <para>For Example:</para> /// <para>itAsync["a test i haven't flushed out yet, but need to"] = todoAsync;</para> /// </summary> public readonly Func<Task> TodoAsync = () => Task.Run(() => { }); /// <summary> /// Set up an expectation for a particular exception type to be thrown before expectation. /// <para>For Example:</para> /// <para>it["should throw exception"] = expect&lt;InvalidOperationException&gt;();</para> /// </summary> public virtual Action Expect<T>() where T : Exception { return Expect<T>(expectedMessage: null); } /// <summary> /// Set up an expectation for a particular exception type to be thrown before expectation, with an expected message. /// <para>For Example:</para> /// <para>it["should throw exception"] = expect&lt;InvalidOperationException&gt;();</para> /// </summary> public virtual Action Expect<T>(string expectedMessage) where T : Exception { var specContext = InnerContext; return () => { if (specContext.Exception == null) throw new ExceptionNotThrown(IncorrectType<T>()); AssertExpectedException<T>(specContext.Exception, expectedMessage); // do not clear exception right now, during first phase, but leave a note for second phase specContext.ClearExpectedException = true; }; } /// <summary> /// Set up an expectation for a particular exception type to be thrown inside passed action. /// <para>For Example:</para> /// <para>it["should throw exception"] = expect&lt;InvalidOperationException&gt;(() => SomeMethodThatThrowsException());</para> /// </summary> public virtual Action Expect<T>(Action action) where T : Exception { return Expect<T>(null, action); } /// <summary> /// Set up an expectation for a particular exception type to be thrown inside passed action, with an expected message. /// <para>For Example:</para> /// <para>it["should throw exception with message Error"] = expect&lt;InvalidOperationException&gt;("Error", () => SomeMethodThatThrowsException());</para> /// </summary> public virtual Action Expect<T>(string expectedMessage, Action action) where T : Exception { return () => { var closureType = typeof(T); try { action(); throw new ExceptionNotThrown(IncorrectType<T>()); } catch (ExceptionNotThrown) { throw; } catch (Exception ex) { AssertExpectedException<T>(ex, expectedMessage); } }; } /// <summary> /// Set up an asynchronous expectation for a particular exception type to be thrown inside passed asynchronous action. /// <para>For Example:</para> /// <para>itAsync["should throw exception"] = expectAsync&lt;InvalidOperationException&gt;(async () => await SomeAsyncMethodThatThrowsException());</para> /// </summary> public virtual Func<Task> ExpectAsync<T>(Func<Task> asyncAction) where T : Exception { return ExpectAsync<T>(null, asyncAction); } /// <summary> /// Set up an asynchronous expectation for a particular exception type to be thrown inside passed asynchronous action, with an expected message. /// <para>For Example:</para> /// <para>itAsync["should throw exception with message Error"] = expectAsync&lt;InvalidOperationException&gt;("Error", async () => await SomeAsyncMethodThatThrowsException());</para> /// </summary> public virtual Func<Task> ExpectAsync<T>(string expectedMessage, Func<Task> asyncAction) where T : Exception { return async () => { var closureType = typeof(T); try { await asyncAction(); throw new ExceptionNotThrown(IncorrectType<T>()); } catch (ExceptionNotThrown) { throw; } catch (Exception ex) { AssertExpectedException<T>(ex, expectedMessage); } }; } /// <summary> /// Override this method to alter the stack trace that NSpectator prints. /// This is useful to override if you want to provide additional information /// (eg. information from a log that is generated out of proc). /// </summary> /// <param name="flattenedStackTrace">A clean stack trace that excludes NSpectator specific namespaces</param> /// <returns></returns> public virtual string StackTraceToPrint(string flattenedStackTrace) { return flattenedStackTrace; } /// <summary> /// Override this method to return another exception in the event of a failure of a test. This is useful to override /// when catching for specific exceptions and returning a more meaningful exception to the developer. /// </summary> /// <param name="originalException">Original exception that was thrown.</param> /// <returns></returns> public virtual Exception ExceptionToReturn(Exception originalException) { return originalException; } private static string IncorrectType<T>() where T : Exception { return $"Exception of type {typeof(T).Name} was not thrown."; } private static string IncorrectMessage(string expected, string actual) { return $@"Expected message: ""{expected}"" But was: ""{actual}"""; } private void AddExample(ExampleBase example) { InnerContext.AddExample(example); } private void AddContext(string name, string tags, Action action) { var childContext = new Context(name, tags); RunContext(childContext, action); } private void AddIgnoredContext(string name, string tags, Action action) { var ignored = new Context(name, tags, isPending: true); RunContext(ignored, action); } private void RunContext(Context ctx, Action action) { InnerContext.AddContext(ctx); var beforeContext = InnerContext; InnerContext = ctx; action(); InnerContext = beforeContext; } private static void AssertExpectedException<T>(Exception actualException, string expectedMessage) where T : Exception { var expectedType = typeof(T); Exception matchingException = null; if (actualException.GetType() == expectedType) { matchingException = actualException; } else { var aggregateException = actualException as AggregateException; if (aggregateException != null) { foreach (var innerException in aggregateException.InnerExceptions) { if (innerException.GetType() != expectedType) continue; matchingException = innerException; break; } } } if (matchingException == null) { throw new ExceptionNotThrown(IncorrectType<T>()); } if (expectedMessage != null && expectedMessage != matchingException.Message) { throw new ExceptionNotThrown(IncorrectMessage(expectedMessage, matchingException.Message)); } } /// <summary> /// Error handler /// </summary> /// <param name="flattenedStackTrace"></param> /// <returns></returns> protected virtual string OnError(string flattenedStackTrace) { return flattenedStackTrace; } internal Context InnerContext { get; set; } /// <summary>Tags required to be present or not present in context or example</summary> /// <remarks> /// Currently, multiple tags indicates any of the tags must be present to be included/excluded. In other words, they are OR'd, not AND'd. /// NOTE: Cucumber's tags wiki offers ideas for handling tags: https://github.com/cucumber/cucumber/wiki/tags /// </remarks> internal Tags TagsFilter = new Tags(); } }
/* * Copyright (c) 2015, InWorldz Halcyon Developers * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of halcyon nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Text; using OpenSim.Framework; using log4net; using System.Reflection; using OpenSim.Framework.AssetLoader.Filesystem; namespace InWorldz.Whip.Client { /// <summary> /// Implements the IAssetServer interface for the InWorldz WHIP asset server /// </summary> public class AssetClient : IAssetServer { private static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private RemoteServer _readWhipServer; private RemoteServer _writeWhipServer; private IAssetReceiver _receiver; protected IAssetLoader assetLoader = new AssetLoaderFileSystem(); ConfigSettings _settings; private bool _loadingDefaultAssets = false; #region IAssetServer Members public AssetClient() { } public AssetClient(string url) { _log.Info("[WHIP.AssetClient] Direct constructor"); this.SetupConnections(url); } public void Initialise(ConfigSettings settings) { _settings = settings; Nini.Config.IConfig netConfig = settings.SettingsFile["Network"]; if (netConfig != null && netConfig.Contains("asset_server_url")) { string url = netConfig.GetString("asset_server_url"); this.SetupConnections(url); } else { throw new Exception("Network/asset_server_url is a required setting"); } } private void SetupConnections(string url) { if (url.Contains(",")) { List<string[]> rwServers = this.ParseReadWriteWhipURL(url); _readWhipServer = new RemoteServer(rwServers[0][1], Convert.ToUInt16(rwServers[0][2]), rwServers[0][0]); //if the port or hosts are different the write server is separate if (rwServers[0][1] != rwServers[1][1] || rwServers[0][2] != rwServers[1][2]) { _writeWhipServer = new RemoteServer(rwServers[1][1], Convert.ToUInt16(rwServers[1][2]), rwServers[1][0]); } else { //else the servers are the same _writeWhipServer = _readWhipServer; } } else { string[] urlParts = this.ParseSingularWhipURL(url); _readWhipServer = new RemoteServer(urlParts[1], Convert.ToUInt16(urlParts[2]), urlParts[0]); _writeWhipServer = _readWhipServer; } } public virtual void LoadDefaultAssets(string pAssetSetsXml) { _log.Info("[ASSET SERVER]: Setting up asset database"); _loadingDefaultAssets = true; assetLoader.ForEachDefaultXmlAsset(pAssetSetsXml, StoreAsset); _loadingDefaultAssets = false; } private List<string[]> ParseReadWriteWhipURL(string url) { // R:whip://[email protected]:32700,W:whip://[email protected]:32700 //split by , this will give us the two WHIP URLs prefixed by their //usage string[] readAndWriteServers = url.Split(new char[1] { ',' }); string[] readURL = null; string[] writeURL = null; string firstServerType = readAndWriteServers[0].Substring(0, 2); if (firstServerType == "R:") { readURL = this.ParseSingularWhipURL(readAndWriteServers[0].Substring(2)); } else if (firstServerType == "W:") { writeURL = this.ParseSingularWhipURL(readAndWriteServers[0].Substring(2)); } else { throw new Exception("Invalid whip URL. For first server R: or W: type not specified"); } string secondServerType = readAndWriteServers[1].Substring(0, 2); if (secondServerType == "R:") { if (readURL != null) { throw new Exception("Invalid whip URL. Read URL specified twice"); } readURL = this.ParseSingularWhipURL(readAndWriteServers[1].Substring(2)); } else if (secondServerType == "W:") { if (writeURL != null) { throw new Exception("Invalid whip URL. Write URL specified twice"); } writeURL = this.ParseSingularWhipURL(readAndWriteServers[1].Substring(2)); } else { throw new Exception("Invalid whip URL. For second server R: or W: type not specified"); } return new List<string[]>(new[] { readURL, writeURL}); } /// <summary> /// Returns an array with [user, password, host, port] /// </summary> /// <param name="url"></param> private string[] ParseSingularWhipURL(string url) { // whip://[email protected]:32700 //url must start with whip if (url.Substring(0, 7) != "whip://") throw new Exception("Invaid whip URL. Must start with whip://"); //strip the Resource ID portion url = url.Substring(7); //split by @ this will give us username:password ip:port string[] userAndHost = url.Split(new char[1]{'@'}); if (userAndHost.Length != 2) throw new Exception("Invalid whip URL, missing @"); //get the user and pass string pass = userAndHost[0]; //get the host and port string[] hostAndPort = userAndHost[1].Split(new char[1]{':'}); if (hostAndPort.Length != 2) throw new Exception("Invalid whip URL, missing : between host and port"); string[] ret = new string[4]; ret[0] = pass; ret[1] = hostAndPort[0]; ret[2] = hostAndPort[1]; return ret; } private bool HasRWSplit() { return _readWhipServer != _writeWhipServer; } public void Start() { _readWhipServer.Start(); if (this.HasRWSplit()) { _writeWhipServer.Start(); } if (_settings != null) this.LoadDefaultAssets(_settings.AssetSetsXMLFile); } public void Stop() { _readWhipServer.Stop(); if (this.HasRWSplit()) { _writeWhipServer.Stop(); } } public void SetReceiver(IAssetReceiver receiver) { _receiver = receiver; } /// <summary> /// Converts a whip asset to an opensim asset /// </summary> /// <param name="whipAsset"></param> /// <returns></returns> private AssetBase WhipAssetToOpensim(Asset whipAsset) { AssetBase osAsset = new AssetBase(); osAsset.Data = whipAsset.Data; osAsset.Name = whipAsset.Name; osAsset.Description = whipAsset.Description; osAsset.Type = (sbyte)whipAsset.Type; osAsset.Local = whipAsset.Local; osAsset.Temporary = whipAsset.Temporary; osAsset.FullID = new OpenMetaverse.UUID(whipAsset.Uuid); return osAsset; } public void RequestAsset(OpenMetaverse.UUID assetID, AssetRequestInfo args) { try { _readWhipServer.GetAssetAsync(assetID.ToString(), delegate(Asset asset, AssetServerError e) { if (e == null) { //no error, pass asset to caller _receiver.AssetReceived(WhipAssetToOpensim(asset), args); } else { string errorString = e.ToString(); if (!errorString.Contains("not found")) { //there is an error, log it, and then tell the caller we have no asset to give _log.ErrorFormat( "[WHIP.AssetClient]: Failure fetching asset {0}" + Environment.NewLine + errorString + Environment.NewLine, assetID); } _receiver.AssetNotFound(assetID, args); } } ); } catch (AssetServerError e) { //there is an error, log it, and then tell the caller we have no asset to give string errorString = e.ToString(); if (!errorString.Contains("not found")) { _log.ErrorFormat( "[WHIP.AssetClient]: Failure fetching asset {0}" + Environment.NewLine + errorString + Environment.NewLine, assetID); } _receiver.AssetNotFound(assetID, args); } } public AssetBase RequestAssetSync(OpenMetaverse.UUID assetID) { try { AssetBase asset = this.WhipAssetToOpensim(_readWhipServer.GetAsset(assetID.ToString())); return asset; } catch (AssetServerError e) { string errorString = e.ToString(); if (!errorString.Contains("not found")) { //there is an error, log it, and then tell the caller we have no asset to give _log.ErrorFormat( "[WHIP.AssetClient]: Failure fetching asset {0}" + Environment.NewLine + errorString + Environment.NewLine, assetID); } return null; } } private Asset OpensimAssetToWhip(AssetBase osAsset) { Asset whipAsset = new Asset(osAsset.FullID.ToString(), (byte)osAsset.Type, osAsset.Local, osAsset.Temporary, OpenSim.Framework.Util.UnixTimeSinceEpoch(), osAsset.Name, osAsset.Description, osAsset.Data); return whipAsset; } public void StoreAsset(AssetBase asset) { try { _writeWhipServer.PutAsset(OpensimAssetToWhip(asset)); } catch (AssetServerError e) { //there is an error, log it, and then tell the caller we have no asset to give if (!_loadingDefaultAssets) { _log.ErrorFormat( "[WHIP.AssetClient]: Failure storing asset {0}" + Environment.NewLine + e.ToString() + Environment.NewLine, asset.FullID); if (e.Message.Contains("already exists")) { //this is hacky, but I dont want to edit the whip client this //late in the game when we're going to be phasing it out throw new AssetAlreadyExistsException(e.Message, e); } else { throw new AssetServerException(e.Message, e); } } } } /// <summary> /// Okay... assets are immutable so im not even sure what place this has here.. /// </summary> /// <param name="asset"></param> public void UpdateAsset(AssetBase asset) { _log.WarnFormat("[WHIP.AssetClient]: UpdateAsset called for {0} Assets are immutable.", asset.FullID); this.StoreAsset(asset); } #endregion #region IPlugin Members public string Version { get { return "1.0"; } } public string Name { get { return "InWorldz WHIP Asset Client"; } } public void Initialise() { } #endregion #region IDisposable Members public void Dispose() { this.Stop(); } #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.Text; using System; using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Text { // A Decoder is used to decode a sequence of blocks of bytes into a // sequence of blocks of characters. Following instantiation of a decoder, // sequential blocks of bytes are converted into blocks of characters through // calls to the GetChars method. The decoder maintains state between the // conversions, allowing it to correctly decode byte sequences that span // adjacent blocks. // // Instances of specific implementations of the Decoder abstract base // class are typically obtained through calls to the GetDecoder method // of Encoding objects. // public abstract class Decoder { internal DecoderFallback _fallback = null; internal DecoderFallbackBuffer _fallbackBuffer = null; protected Decoder() { // We don't call default reset because default reset probably isn't good if we aren't initialized. } public DecoderFallback Fallback { get { return _fallback; } set { if (value == null) throw new ArgumentNullException(nameof(value)); Contract.EndContractBlock(); // Can't change fallback if buffer is wrong if (_fallbackBuffer != null && _fallbackBuffer.Remaining > 0) throw new ArgumentException( SR.Argument_FallbackBufferNotEmpty, nameof(value)); _fallback = value; _fallbackBuffer = null; } } // Note: we don't test for threading here because async access to Encoders and Decoders // doesn't work anyway. public DecoderFallbackBuffer FallbackBuffer { get { if (_fallbackBuffer == null) { if (_fallback != null) _fallbackBuffer = _fallback.CreateFallbackBuffer(); else _fallbackBuffer = DecoderFallback.ReplacementFallback.CreateFallbackBuffer(); } return _fallbackBuffer; } } internal bool InternalHasFallbackBuffer { get { return _fallbackBuffer != null; } } // Reset the Decoder // // Normally if we call GetChars() and an error is thrown we don't change the state of the Decoder. This // would allow the caller to correct the error condition and try again (such as if they need a bigger buffer.) // // If the caller doesn't want to try again after GetChars() throws an error, then they need to call Reset(). // // Virtual implementation has to call GetChars with flush and a big enough buffer to clear a 0 byte string // We avoid GetMaxCharCount() because a) we can't call the base encoder and b) it might be really big. public virtual void Reset() { byte[] byteTemp = Array.Empty<byte>(); char[] charTemp = new char[GetCharCount(byteTemp, 0, 0, true)]; GetChars(byteTemp, 0, 0, charTemp, 0, true); _fallbackBuffer?.Reset(); } // Returns the number of characters the next call to GetChars will // produce if presented with the given range of bytes. The returned value // takes into account the state in which the decoder was left following the // last call to GetChars. The state of the decoder is not affected // by a call to this method. // public abstract int GetCharCount(byte[] bytes, int index, int count); public virtual int GetCharCount(byte[] bytes, int index, int count, bool flush) { return GetCharCount(bytes, index, count); } // We expect this to be the workhorse for NLS Encodings, but for existing // ones we need a working (if slow) default implementation) [CLSCompliant(false)] public virtual unsafe int GetCharCount(byte* bytes, int count, bool flush) { // Validate input parameters if (bytes == null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); byte[] arrbyte = new byte[count]; int index; for (index = 0; index < count; index++) arrbyte[index] = bytes[index]; return GetCharCount(arrbyte, 0, count); } public virtual unsafe int GetCharCount(ReadOnlySpan<byte> bytes, bool flush) { fixed (byte* bytesPtr = &bytes.DangerousGetPinnableReference()) { return GetCharCount(bytesPtr, bytes.Length, flush); } } // Decodes a range of bytes in a byte array into a range of characters // in a character array. The method decodes byteCount bytes from // bytes starting at index byteIndex, storing the resulting // characters in chars starting at index charIndex. The // decoding takes into account the state in which the decoder was left // following the last call to this method. // // An exception occurs if the character array is not large enough to // hold the complete decoding of the bytes. The GetCharCount method // can be used to determine the exact number of characters that will be // produced for a given range of bytes. Alternatively, the // GetMaxCharCount method of the Encoding that produced this // decoder can be used to determine the maximum number of characters that // will be produced for a given number of bytes, regardless of the actual // byte values. // public abstract int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex); public virtual int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, bool flush) { return GetChars(bytes, byteIndex, byteCount, chars, charIndex); } // We expect this to be the workhorse for NLS Encodings, but for existing // ones we need a working (if slow) default implementation) // // WARNING WARNING WARNING // // WARNING: If this breaks it could be a security threat. Obviously we // call this internally, so you need to make sure that your pointers, counts // and indexes are correct when you call this method. // // In addition, we have internal code, which will be marked as "safe" calling // this code. However this code is dependent upon the implementation of an // external GetChars() method, which could be overridden by a third party and // the results of which cannot be guaranteed. We use that result to copy // the char[] to our char* output buffer. If the result count was wrong, we // could easily overflow our output buffer. Therefore we do an extra test // when we copy the buffer so that we don't overflow charCount either. [CLSCompliant(false)] public virtual unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, bool flush) { // Validate input parameters if (chars == null || bytes == null) throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), SR.ArgumentNull_Array); if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); // Get the byte array to convert byte[] arrByte = new byte[byteCount]; int index; for (index = 0; index < byteCount; index++) arrByte[index] = bytes[index]; // Get the char array to fill char[] arrChar = new char[charCount]; // Do the work int result = GetChars(arrByte, 0, byteCount, arrChar, 0, flush); Debug.Assert(result <= charCount, "Returned more chars than we have space for"); // Copy the char array // WARNING: We MUST make sure that we don't copy too many chars. We can't // rely on result because it could be a 3rd party implementation. We need // to make sure we never copy more than charCount chars no matter the value // of result if (result < charCount) charCount = result; // We check both result and charCount so that we don't accidentally overrun // our pointer buffer just because of an issue in GetChars for (index = 0; index < charCount; index++) chars[index] = arrChar[index]; return charCount; } public virtual unsafe int GetChars(ReadOnlySpan<byte> bytes, Span<char> chars, bool flush) { fixed (byte* bytesPtr = &bytes.DangerousGetPinnableReference()) fixed (char* charsPtr = &chars.DangerousGetPinnableReference()) { return GetChars(bytesPtr, bytes.Length, charsPtr, chars.Length, flush); } } // This method is used when the output buffer might not be large enough. // It will decode until it runs out of bytes, and then it will return // true if it the entire input was converted. In either case it // will also return the number of converted bytes and output characters used. // It will only throw a buffer overflow exception if the entire lenght of chars[] is // too small to store the next char. (like 0 or maybe 1 or 4 for some encodings) // We're done processing this buffer only if completed returns true. // // Might consider checking Max...Count to avoid the extra counting step. // // Note that if all of the input bytes are not consumed, then we'll do a /2, which means // that its likely that we didn't consume as many bytes as we could have. For some // applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream) public virtual void Convert(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { // Validate parameters if (bytes == null || chars == null) throw new ArgumentNullException((bytes == null ? nameof(bytes) : nameof(chars)), SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); Contract.EndContractBlock(); bytesUsed = byteCount; // Its easy to do if it won't overrun our buffer. while (bytesUsed > 0) { if (GetCharCount(bytes, byteIndex, bytesUsed, flush) <= charCount) { charsUsed = GetChars(bytes, byteIndex, bytesUsed, chars, charIndex, flush); completed = (bytesUsed == byteCount && (_fallbackBuffer == null || _fallbackBuffer.Remaining == 0)); return; } // Try again with 1/2 the count, won't flush then 'cause won't read it all flush = false; bytesUsed /= 2; } // Oops, we didn't have anything, we'll have to throw an overflow throw new ArgumentException(SR.Argument_ConversionOverflow); } // This is the version that uses *. // We're done processing this buffer only if completed returns true. // // Might consider checking Max...Count to avoid the extra counting step. // // Note that if all of the input bytes are not consumed, then we'll do a /2, which means // that its likely that we didn't consume as many bytes as we could have. For some // applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream) [CLSCompliant(false)] public virtual unsafe void Convert(byte* bytes, int byteCount, char* chars, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { // Validate input parameters if (chars == null || bytes == null) throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), SR.ArgumentNull_Array); if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); // Get ready to do it bytesUsed = byteCount; // Its easy to do if it won't overrun our buffer. while (bytesUsed > 0) { if (GetCharCount(bytes, bytesUsed, flush) <= charCount) { charsUsed = GetChars(bytes, bytesUsed, chars, charCount, flush); completed = (bytesUsed == byteCount && (_fallbackBuffer == null || _fallbackBuffer.Remaining == 0)); return; } // Try again with 1/2 the count, won't flush then 'cause won't read it all flush = false; bytesUsed /= 2; } // Oops, we didn't have anything, we'll have to throw an overflow throw new ArgumentException(SR.Argument_ConversionOverflow); } public virtual unsafe void Convert(ReadOnlySpan<byte> bytes, Span<char> chars, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { fixed (byte* bytesPtr = &bytes.DangerousGetPinnableReference()) fixed (char* charsPtr = &chars.DangerousGetPinnableReference()) { Convert(bytesPtr, bytes.Length, charsPtr, chars.Length, flush, out bytesUsed, out charsUsed, out completed); } } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable enable using System.Collections.Generic; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.SignalR.Client; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Game.Online.API; using osu.Game.Online.Rooms; namespace osu.Game.Online.Multiplayer { /// <summary> /// A <see cref="MultiplayerClient"/> with online connectivity. /// </summary> public class OnlineMultiplayerClient : MultiplayerClient { private readonly string endpoint; private IHubClientConnector? connector; public override IBindable<bool> IsConnected { get; } = new BindableBool(); private HubConnection? connection => connector?.CurrentConnection; public OnlineMultiplayerClient(EndpointConfiguration endpoints) { endpoint = endpoints.MultiplayerEndpointUrl; } [BackgroundDependencyLoader] private void load(IAPIProvider api) { // Importantly, we are intentionally not using MessagePack here to correctly support derived class serialization. // More information on the limitations / reasoning can be found in osu-server-spectator's initialisation code. connector = api.GetHubConnector(nameof(OnlineMultiplayerClient), endpoint); if (connector != null) { connector.ConfigureConnection = connection => { // this is kind of SILLY // https://github.com/dotnet/aspnetcore/issues/15198 connection.On<MultiplayerRoomState>(nameof(IMultiplayerClient.RoomStateChanged), ((IMultiplayerClient)this).RoomStateChanged); connection.On<MultiplayerRoomUser>(nameof(IMultiplayerClient.UserJoined), ((IMultiplayerClient)this).UserJoined); connection.On<MultiplayerRoomUser>(nameof(IMultiplayerClient.UserLeft), ((IMultiplayerClient)this).UserLeft); connection.On<MultiplayerRoomUser>(nameof(IMultiplayerClient.UserKicked), ((IMultiplayerClient)this).UserKicked); connection.On<int>(nameof(IMultiplayerClient.HostChanged), ((IMultiplayerClient)this).HostChanged); connection.On<MultiplayerRoomSettings>(nameof(IMultiplayerClient.SettingsChanged), ((IMultiplayerClient)this).SettingsChanged); connection.On<int, MultiplayerUserState>(nameof(IMultiplayerClient.UserStateChanged), ((IMultiplayerClient)this).UserStateChanged); connection.On(nameof(IMultiplayerClient.LoadRequested), ((IMultiplayerClient)this).LoadRequested); connection.On(nameof(IMultiplayerClient.MatchStarted), ((IMultiplayerClient)this).MatchStarted); connection.On(nameof(IMultiplayerClient.ResultsReady), ((IMultiplayerClient)this).ResultsReady); connection.On<int, IEnumerable<APIMod>>(nameof(IMultiplayerClient.UserModsChanged), ((IMultiplayerClient)this).UserModsChanged); connection.On<int, BeatmapAvailability>(nameof(IMultiplayerClient.UserBeatmapAvailabilityChanged), ((IMultiplayerClient)this).UserBeatmapAvailabilityChanged); connection.On<MatchRoomState>(nameof(IMultiplayerClient.MatchRoomStateChanged), ((IMultiplayerClient)this).MatchRoomStateChanged); connection.On<int, MatchUserState>(nameof(IMultiplayerClient.MatchUserStateChanged), ((IMultiplayerClient)this).MatchUserStateChanged); connection.On<MatchServerEvent>(nameof(IMultiplayerClient.MatchEvent), ((IMultiplayerClient)this).MatchEvent); connection.On<MultiplayerPlaylistItem>(nameof(IMultiplayerClient.PlaylistItemAdded), ((IMultiplayerClient)this).PlaylistItemAdded); connection.On<long>(nameof(IMultiplayerClient.PlaylistItemRemoved), ((IMultiplayerClient)this).PlaylistItemRemoved); connection.On<MultiplayerPlaylistItem>(nameof(IMultiplayerClient.PlaylistItemChanged), ((IMultiplayerClient)this).PlaylistItemChanged); }; IsConnected.BindTo(connector.IsConnected); } } protected override Task<MultiplayerRoom> JoinRoom(long roomId, string? password = null) { if (!IsConnected.Value) return Task.FromCanceled<MultiplayerRoom>(new CancellationToken(true)); Debug.Assert(connection != null); return connection.InvokeAsync<MultiplayerRoom>(nameof(IMultiplayerServer.JoinRoomWithPassword), roomId, password ?? string.Empty); } protected override Task LeaveRoomInternal() { if (!IsConnected.Value) return Task.FromCanceled(new CancellationToken(true)); Debug.Assert(connection != null); return connection.InvokeAsync(nameof(IMultiplayerServer.LeaveRoom)); } public override Task TransferHost(int userId) { if (!IsConnected.Value) return Task.CompletedTask; Debug.Assert(connection != null); return connection.InvokeAsync(nameof(IMultiplayerServer.TransferHost), userId); } public override Task KickUser(int userId) { if (!IsConnected.Value) return Task.CompletedTask; Debug.Assert(connection != null); return connection.InvokeAsync(nameof(IMultiplayerServer.KickUser), userId); } public override Task ChangeSettings(MultiplayerRoomSettings settings) { if (!IsConnected.Value) return Task.CompletedTask; Debug.Assert(connection != null); return connection.InvokeAsync(nameof(IMultiplayerServer.ChangeSettings), settings); } public override Task ChangeState(MultiplayerUserState newState) { if (!IsConnected.Value) return Task.CompletedTask; Debug.Assert(connection != null); return connection.InvokeAsync(nameof(IMultiplayerServer.ChangeState), newState); } public override Task ChangeBeatmapAvailability(BeatmapAvailability newBeatmapAvailability) { if (!IsConnected.Value) return Task.CompletedTask; Debug.Assert(connection != null); return connection.InvokeAsync(nameof(IMultiplayerServer.ChangeBeatmapAvailability), newBeatmapAvailability); } public override Task ChangeUserMods(IEnumerable<APIMod> newMods) { if (!IsConnected.Value) return Task.CompletedTask; Debug.Assert(connection != null); return connection.InvokeAsync(nameof(IMultiplayerServer.ChangeUserMods), newMods); } public override Task SendMatchRequest(MatchUserRequest request) { if (!IsConnected.Value) return Task.CompletedTask; Debug.Assert(connection != null); return connection.InvokeAsync(nameof(IMultiplayerServer.SendMatchRequest), request); } public override Task StartMatch() { if (!IsConnected.Value) return Task.CompletedTask; Debug.Assert(connection != null); return connection.InvokeAsync(nameof(IMultiplayerServer.StartMatch)); } public override Task AbortGameplay() { if (!IsConnected.Value) return Task.CompletedTask; Debug.Assert(connection != null); return connection.InvokeAsync(nameof(IMultiplayerServer.AbortGameplay)); } public override Task AddPlaylistItem(MultiplayerPlaylistItem item) { if (!IsConnected.Value) return Task.CompletedTask; Debug.Assert(connection != null); return connection.InvokeAsync(nameof(IMultiplayerServer.AddPlaylistItem), item); } public override Task EditPlaylistItem(MultiplayerPlaylistItem item) { if (!IsConnected.Value) return Task.CompletedTask; Debug.Assert(connection != null); return connection.InvokeAsync(nameof(IMultiplayerServer.EditPlaylistItem), item); } public override Task RemovePlaylistItem(long playlistItemId) { if (!IsConnected.Value) return Task.CompletedTask; Debug.Assert(connection != null); return connection.InvokeAsync(nameof(IMultiplayerServer.RemovePlaylistItem), playlistItemId); } protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); connector?.Dispose(); } } }
// // Copyright (C) DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Cassandra.IntegrationTests.TestBase; using Cassandra.SessionManagement; using Cassandra.Tests; using NUnit.Framework; namespace Cassandra.IntegrationTests.Core { [Category(TestCategory.Short), Category(TestCategory.RealCluster)] public class SessionTests : SharedClusterTest { public SessionTests() : base(3, false) { } [Test] public void Session_Cancels_Pending_When_Disposed() { Trace.TraceInformation("SessionCancelsPendingWhenDisposed"); using (var localCluster = ClusterBuilder().AddContactPoint(TestCluster.InitialContactPoint).Build()) { var localSession = localCluster.Connect(); localSession.CreateKeyspaceIfNotExists(KeyspaceName, null, false); localSession.ChangeKeyspace(KeyspaceName); localSession.Execute("CREATE TABLE tbl_cancel_pending (id uuid primary key)"); var taskList = new Task[500]; for (var i = 0; i < taskList.Length; i++) { taskList[i] = localSession.ExecuteAsync(new SimpleStatement( "INSERT INTO tbl_cancel_pending (id) VALUES (uuid())")); } localSession.Dispose(); try { Task.WaitAll(taskList); } catch { // Its OK to have a failed task } Assert.False(taskList.Any(t => t.Status == TaskStatus.WaitingForActivation), "No more task should be pending"); Assert.True(taskList.All(t => t.Status == TaskStatus.RanToCompletion || t.Status == TaskStatus.Faulted), "All task should be completed or faulted"); } } [Test] public void Session_Keyspace_Does_Not_Exist_On_Connect_Throws() { var localCluster = GetNewTemporaryCluster(); var ex = Assert.Throws<InvalidQueryException>(() => localCluster.Connect("THIS_KEYSPACE_DOES_NOT_EXIST")); Assert.True(ex.Message.ToLower().Contains("keyspace")); } [Test] public void Session_Keyspace_Empty_On_Connect() { var localCluster = GetNewTemporaryCluster(); Assert.DoesNotThrow(() => { var localSession = localCluster.Connect(""); localSession.Execute("SELECT * FROM system.local"); }); } [Test] public void Session_Keyspace_Does_Not_Exist_On_Change_Throws() { var localCluster = GetNewTemporaryCluster(); var localSession = localCluster.Connect(); var ex = Assert.Throws<InvalidQueryException>(() => localSession.ChangeKeyspace("THIS_KEYSPACE_DOES_NOT_EXIST_EITHER")); Assert.True(ex.Message.ToLower().Contains("keyspace")); } [Test] public void ChangeKeyspace_SetsKeyspace() { var localCluster = GetNewTemporaryCluster(); var localSession = localCluster.Connect(); localSession.CreateKeyspace(KeyspaceName, null, false); localSession = localCluster.Connect(); Assert.IsNull(localSession.Keyspace); localSession.ChangeKeyspace(KeyspaceName); Assert.IsNotNull(localSession.Keyspace); Assert.AreEqual(KeyspaceName, localSession.Keyspace); } [Test] public void Session_Keyspace_Connect_Case_Sensitive() { var localCluster = GetNewTemporaryCluster(); Assert.Throws<InvalidQueryException>(() => localCluster.Connect("SYSTEM")); } [Test] public void Session_Use_Statement_Changes_Keyspace() { var localCluster = GetNewTemporaryCluster(); var localSession = localCluster.Connect(); localSession.Execute("USE system"); //The session should be using the system keyspace now Assert.DoesNotThrow(() => { for (var i = 0; i < 5; i++) { localSession.Execute("select * from local"); } }); Assert.That(localSession.Keyspace, Is.EqualTo("system")); } [Test] public void Session_Use_Statement_Changes_Keyspace_Case_Insensitive() { var localCluster = GetNewTemporaryCluster(); var localSession = localCluster.Connect(); //The statement is case insensitive by default, as no quotes were specified localSession.Execute("USE SyStEm"); //The session should be using the system keyspace now Assert.DoesNotThrow(() => { for (var i = 0; i < 5; i++) { localSession.Execute("select * from local"); } }); } [Test] public void Session_Keyspace_Create_Case_Sensitive() { var localCluster = GetNewTemporaryCluster(); var localSession = localCluster.Connect(); const string ks1 = "UPPER_ks"; localSession.CreateKeyspace(ks1); localSession.ChangeKeyspace(ks1); localSession.Execute("CREATE TABLE test1 (k uuid PRIMARY KEY, v text)"); TestUtils.WaitForSchemaAgreement(localCluster); //Execute multiple times a query on the newly created keyspace Assert.DoesNotThrow(() => { for (var i = 0; i < 5; i++) { localSession.Execute("SELECT * FROM test1"); } }); } [Test] public void Should_Create_The_Right_Amount_Of_Connections() { var localCluster1 = GetNewTemporaryCluster( builder => builder .WithPoolingOptions( new PoolingOptions() .SetCoreConnectionsPerHost(HostDistance.Local, 3))); var localSession1 = (IInternalSession)localCluster1.Connect(); var hosts1 = localCluster1.AllHosts().ToList(); Assert.AreEqual(3, hosts1.Count); //Execute multiple times a query on the newly created keyspace for (var i = 0; i < 12; i++) { localSession1.Execute("SELECT * FROM system.local"); } Thread.Sleep(2000); var pool11 = localSession1.GetOrCreateConnectionPool(hosts1[0], HostDistance.Local); var pool12 = localSession1.GetOrCreateConnectionPool(hosts1[1], HostDistance.Local); Assert.That(pool11.OpenConnections, Is.EqualTo(3)); Assert.That(pool12.OpenConnections, Is.EqualTo(3)); using (var localCluster2 = ClusterBuilder() .AddContactPoint(TestCluster.InitialContactPoint) .WithPoolingOptions(new PoolingOptions().SetCoreConnectionsPerHost(HostDistance.Local, 1)) .Build()) { var localSession2 = (IInternalSession)localCluster2.Connect(); var hosts2 = localCluster2.AllHosts().ToList(); Assert.AreEqual(3, hosts2.Count); //Execute multiple times a query on the newly created keyspace for (var i = 0; i < 6; i++) { localSession2.Execute("SELECT * FROM system.local"); } Thread.Sleep(2000); var pool21 = localSession2.GetOrCreateConnectionPool(hosts2[0], HostDistance.Local); var pool22 = localSession2.GetOrCreateConnectionPool(hosts2[1], HostDistance.Local); Assert.That(pool21.OpenConnections, Is.EqualTo(1)); Assert.That(pool22.OpenConnections, Is.EqualTo(1)); } } /// <summary> /// It uses a load balancing policy that initially uses 2 hosts as local. /// Then changes one of the hosts as ignored: the pool should be closed. /// Then changes the host back to local: the pool should be recreated. /// </summary> [Test, TestTimeout(5 * 60 * 1000), Repeat(10)] public async Task Session_With_Host_Changing_Distance() { if (TestHelper.IsMono) { Assert.Ignore("The test should not run under the Mono runtime"); } var lbp = new DistanceChangingLbp(); var builder = ClusterBuilder() .AddContactPoint(TestCluster.InitialContactPoint) .WithLoadBalancingPolicy(lbp) .WithPoolingOptions(new PoolingOptions().SetCoreConnectionsPerHost(HostDistance.Local, 3)) .WithReconnectionPolicy(new ConstantReconnectionPolicy(1000)); var counter = 0; using (var localCluster = builder.Build()) { var localSession = (IInternalSession)localCluster.Connect(); var remoteHost = localCluster.AllHosts().First(h => TestHelper.GetLastAddressByte(h) == 2); var stopWatch = new Stopwatch(); var distanceReset = 0; TestHelper.Invoke(() => localSession.Execute("SELECT key FROM system.local"), 10); var hosts = localCluster.AllHosts().ToArray(); var pool1 = localSession.GetOrCreateConnectionPool(hosts[0], HostDistance.Local); var pool2 = localSession.GetOrCreateConnectionPool(hosts[1], HostDistance.Local); var tcs = new TaskCompletionSource<RowSet>(); tcs.SetResult(null); var completedTask = tcs.Task; Func<Task<RowSet>> execute = () => { var wasReset = Volatile.Read(ref distanceReset); var count = Interlocked.Increment(ref counter); if (count == 80) { Trace.TraceInformation("Setting to remote: {0}", DateTimeOffset.Now); lbp.SetRemoteHost(remoteHost); stopWatch.Start(); } if (wasReset == 0 && count >= 240 && stopWatch.ElapsedMilliseconds > 2000) { if (Interlocked.CompareExchange(ref distanceReset, 1, 0) == 0) { Trace.TraceInformation("Setting back to local: {0}", DateTimeOffset.Now); lbp.SetRemoteHost(null); stopWatch.Restart(); } } var poolHasBeenReset = wasReset == 1 && pool1.OpenConnections == 3 && pool2.OpenConnections == 3 && stopWatch.ElapsedMilliseconds > 2000; if (poolHasBeenReset) { // We have been setting the host as ignored and then take it back into account // The pool is looking good, there is no point in continue executing queries return completedTask; } return localSession.ExecuteAsync(new SimpleStatement("SELECT key FROM system.local")); }; await TestHelper.TimesLimit(execute, 200000, 32).ConfigureAwait(false); TestHelper.RetryAssert( () => { Assert.That(pool1.OpenConnections, Is.EqualTo(3), "pool1 != 3"); Assert.That(pool2.OpenConnections, Is.EqualTo(3), "pool2 != 3"); }, 500, 20); } } private class DistanceChangingLbp : ILoadBalancingPolicy { private readonly RoundRobinPolicy _childPolicy; private volatile Host _ignoredHost; public DistanceChangingLbp() { _childPolicy = new RoundRobinPolicy(); } public void SetRemoteHost(Host h) { _ignoredHost = h; } public void Initialize(ICluster cluster) { _childPolicy.Initialize(cluster); } public HostDistance Distance(Host host) { if (host == _ignoredHost) { return HostDistance.Ignored; } return HostDistance.Local; } public IEnumerable<Host> NewQueryPlan(string keyspace, IStatement query) { return _childPolicy.NewQueryPlan(keyspace, query); } } /// <summary> /// Checks that having a disposed Session created by the cluster does not affects other sessions /// </summary> [Test] public async Task Session_Disposed_On_Cluster() { var cluster = GetNewTemporaryCluster(); var session1 = cluster.Connect(); var session2 = cluster.Connect(); var isDown = 0; foreach (var host in cluster.AllHosts()) { host.Down += _ => Interlocked.Increment(ref isDown); } const string query = "SELECT * from system.local"; await TestHelper.TimesLimit(() => session1.ExecuteAsync(new SimpleStatement(query)), 100, 32).ConfigureAwait(false); await TestHelper.TimesLimit(() => session2.ExecuteAsync(new SimpleStatement(query)), 100, 32).ConfigureAwait(false); // Dispose the first session session1.Dispose(); // All nodes should be up Assert.AreEqual(cluster.AllHosts().Count, cluster.AllHosts().Count(h => h.IsUp)); // And session2 should be queryable await TestHelper.TimesLimit(() => session2.ExecuteAsync(new SimpleStatement(query)), 100, 32).ConfigureAwait(false); Assert.AreEqual(cluster.AllHosts().Count, cluster.AllHosts().Count(h => h.IsUp)); cluster.Dispose(); Assert.AreEqual(0, Volatile.Read(ref isDown)); } #if NETFRAMEWORK [Test, Apartment(ApartmentState.STA)] public void Session_Connect_And_ShutDown_SupportsSTA() { Assert.DoesNotThrow(() => { using (var localCluster = ClusterBuilder().AddContactPoint(TestCluster.InitialContactPoint).Build()) { var localSession = localCluster.Connect(); var ps = localSession.Prepare("SELECT * FROM system.local"); TestHelper.Invoke(() => localSession.Execute(ps.Bind()), 10); } }); } #endif [Test] public void Session_Execute_Logging_With_Verbose_Level_Test() { var originalLevel = Diagnostics.CassandraTraceSwitch.Level; Diagnostics.CassandraTraceSwitch.Level = TraceLevel.Verbose; try { Assert.DoesNotThrow(() => { using (var localCluster = ClusterBuilder().AddContactPoint(TestCluster.InitialContactPoint).Build()) { var localSession = localCluster.Connect("system"); var ps = localSession.Prepare("SELECT * FROM local"); TestHelper.ParallelInvoke(() => localSession.Execute(ps.Bind()), 100); } }); } finally { Diagnostics.CassandraTraceSwitch.Level = originalLevel; } } [Test] public void Session_Execute_Throws_TimeoutException_When_QueryAbortTimeout_Elapsed() { using (var dummyCluster = ClusterBuilder().AddContactPoint("0.0.0.0").Build()) { Assert.AreNotEqual(dummyCluster.Configuration.ClientOptions.QueryAbortTimeout, Timeout.Infinite); } using (var localCluster = ClusterBuilder() .AddContactPoint(TestCluster.InitialContactPoint) //Disable socket read timeout .WithSocketOptions(new SocketOptions().SetReadTimeoutMillis(0)) //Set abort timeout at a low value .WithQueryTimeout(1500) .Build()) { var t = Task.Factory.StartNew(() => { try { var localSession = localCluster.Connect("system"); localSession.Execute("SELECT * FROM local"); TestCluster.PauseNode(1); TestCluster.PauseNode(2); TestCluster.PauseNode(3); Assert.Throws<TimeoutException>(() => localSession.Execute("SELECT * FROM local")); } finally { TestCluster.ResumeNode(1); TestCluster.ResumeNode(2); TestCluster.ResumeNode(3); } }, TaskCreationOptions.LongRunning | TaskCreationOptions.DenyChildAttach); t.Wait(5 * 60 * 1000); } } /// Tests that void results return empty RowSets /// /// Empty_RowSet_Test tests that empty RowSets are returned for void results. It creates a simple table and performs /// an INSERT query on the table, returning an empty RowSet. It then verifies the RowSet metadata is populated /// properly. /// /// @since 3.0.0 /// @jira_ticket CSHARP-377 /// @expected_result RowSet metadata is properly returned /// /// @test_category queries:basic [Test] public void Empty_RowSet_Test() { var localCluster = GetNewTemporaryCluster(); var localSession = localCluster.Connect(); localSession.CreateKeyspaceIfNotExists(KeyspaceName, null, false); localSession.ChangeKeyspace(KeyspaceName); localSession.Execute("CREATE TABLE test (k int PRIMARY KEY, v int)"); var rowSet = localSession.Execute("INSERT INTO test (k, v) VALUES (0, 0)"); Assert.True(rowSet.IsExhausted()); Assert.True(rowSet.IsFullyFetched); Assert.AreEqual(0, rowSet.Count()); Assert.AreEqual(0, rowSet.GetAvailableWithoutFetching()); } [Test] public async Task Cluster_ConnectAsync_Should_Create_A_Session_With_Keyspace_Set() { const string query = "SELECT * FROM local"; // Using a default keyspace using (var cluster = ClusterBuilder().AddContactPoint(TestCluster.InitialContactPoint) .WithDefaultKeyspace("system").Build()) { ISession session = await cluster.ConnectAsync().ConfigureAwait(false); Assert.DoesNotThrowAsync(async () => await session.ExecuteAsync(new SimpleStatement(query)).ConfigureAwait(false)); Assert.DoesNotThrowAsync(async () => await session.ExecuteAsync(new SimpleStatement(query)).ConfigureAwait(false)); await cluster.ShutdownAsync().ConfigureAwait(false); } // Setting the keyspace on ConnectAsync using (var cluster = ClusterBuilder().AddContactPoint(TestCluster.InitialContactPoint).Build()) { ISession session = await cluster.ConnectAsync("system").ConfigureAwait(false); Assert.DoesNotThrowAsync(async () => await session.ExecuteAsync(new SimpleStatement(query)).ConfigureAwait(false)); Assert.DoesNotThrowAsync(async () => await session.ExecuteAsync(new SimpleStatement(query)).ConfigureAwait(false)); await cluster.ShutdownAsync().ConfigureAwait(false); } // Without setting the keyspace using (var cluster = ClusterBuilder().AddContactPoint(TestCluster.InitialContactPoint).Build()) { ISession session = await cluster.ConnectAsync().ConfigureAwait(false); Assert.DoesNotThrowAsync(async () => await session.ExecuteAsync(new SimpleStatement("SELECT * FROM system.local")) .ConfigureAwait(false)); await cluster.ShutdownAsync().ConfigureAwait(false); } } } }
// 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; using System.Collections.Generic; using Xunit; namespace System.Linq.Tests { public class ZipTests : EnumerableTests { [Fact] public void ImplicitTypeParameters() { IEnumerable<int> first = new int[] { 1, 2, 3 }; IEnumerable<int> second = new int[] { 2, 5, 9 }; IEnumerable<int> expected = new int[] { 3, 7, 12 }; Assert.Equal(expected, first.Zip(second, (x, y) => x + y)); } [Fact] public void ExplicitTypeParameters() { IEnumerable<int> first = new int[] { 1, 2, 3 }; IEnumerable<int> second = new int[] { 2, 5, 9 }; IEnumerable<int> expected = new int[] { 3, 7, 12 }; Assert.Equal(expected, first.Zip<int, int, int>(second, (x, y) => x + y)); } [Fact] public void FirstIsNull() { IEnumerable<int> first = null; IEnumerable<int> second = new int[] { 2, 5, 9 }; Assert.Throws<ArgumentNullException>("first", () => first.Zip<int, int, int>(second, (x, y) => x + y)); } [Fact] public void SecondIsNull() { IEnumerable<int> first = new int[] { 1, 2, 3 }; IEnumerable<int> second = null; Assert.Throws<ArgumentNullException>("second", () => first.Zip<int, int, int>(second, (x, y) => x + y)); } [Fact] public void FuncIsNull() { IEnumerable<int> first = new int[] { 1, 2, 3 }; IEnumerable<int> second = new int[] { 2, 4, 6 }; Func<int, int, int> func = null; Assert.Throws<ArgumentNullException>("resultSelector", () => first.Zip(second, func)); } [Fact] public void ExceptionThrownFromFirstsEnumerator() { ThrowsOnMatchEnumerable<int> first = new ThrowsOnMatchEnumerable<int>(new int[] { 1, 3, 3 }, 2); IEnumerable<int> second = new int[] { 2, 4, 6 }; Func<int, int, int> func = (x, y) => x + y; IEnumerable<int> expected = new int[] { 3, 7, 9 }; Assert.Equal(expected, first.Zip(second, func)); first = new ThrowsOnMatchEnumerable<int>(new int[] { 1, 2, 3 }, 2); var zip = first.Zip(second, func); Assert.Throws<Exception>(() => zip.ToList()); } [Fact] public void ExceptionThrownFromSecondsEnumerator() { ThrowsOnMatchEnumerable<int> second = new ThrowsOnMatchEnumerable<int>(new int[] { 1, 3, 3 }, 2); IEnumerable<int> first = new int[] { 2, 4, 6 }; Func<int, int, int> func = (x, y) => x + y; IEnumerable<int> expected = new int[] { 3, 7, 9 }; Assert.Equal(expected, first.Zip(second, func)); second = new ThrowsOnMatchEnumerable<int>(new int[] { 1, 2, 3 }, 2); var zip = first.Zip(second, func); Assert.Throws<Exception>(() => zip.ToList()); } [Fact] public void FirstAndSecondEmpty() { IEnumerable<int> first = new int[] { }; IEnumerable<int> second = new int[] { }; Func<int, int, int> func = (x, y) => x + y; IEnumerable<int> expected = new int[] { }; Assert.Equal(expected, first.Zip(second, func)); } [Fact] public void FirstEmptySecondSingle() { IEnumerable<int> first = new int[] { }; IEnumerable<int> second = new int[] { 2 }; Func<int, int, int> func = (x, y) => x + y; IEnumerable<int> expected = new int[] { }; Assert.Equal(expected, first.Zip(second, func)); } [Fact] public void FirstEmptySecondMany() { IEnumerable<int> first = new int[] { }; IEnumerable<int> second = new int[] { 2, 4, 8 }; Func<int, int, int> func = (x, y) => x + y; IEnumerable<int> expected = new int[] { }; Assert.Equal(expected, first.Zip(second, func)); } [Fact] public void SecondEmptyFirstSingle() { IEnumerable<int> first = new int[] { 1 }; IEnumerable<int> second = new int[] { }; Func<int, int, int> func = (x, y) => x + y; IEnumerable<int> expected = new int[] { }; Assert.Equal(expected, first.Zip(second, func)); } [Fact] public void SecondEmptyFirstMany() { IEnumerable<int> first = new int[] { 1, 2, 3 }; IEnumerable<int> second = new int[] { }; Func<int, int, int> func = (x, y) => x + y; IEnumerable<int> expected = new int[] { }; Assert.Equal(expected, first.Zip(second, func)); } [Fact] public void FirstAndSecondSingle() { IEnumerable<int> first = new int[] { 1 }; IEnumerable<int> second = new int[] { 2 }; Func<int, int, int> func = (x, y) => x + y; IEnumerable<int> expected = new int[] { 3 }; Assert.Equal(expected, first.Zip(second, func)); } [Fact] public void FirstAndSecondEqualSize() { IEnumerable<int> first = new int[] { 1, 2, 3 }; IEnumerable<int> second = new int[] { 2, 3, 4 }; Func<int, int, int> func = (x, y) => x + y; IEnumerable<int> expected = new int[] { 3, 5, 7 }; Assert.Equal(expected, first.Zip(second, func)); } [Fact] public void SecondOneMoreThanFirst() { IEnumerable<int> first = new int[] { 1, 2 }; IEnumerable<int> second = new int[] { 2, 4, 8 }; Func<int, int, int> func = (x, y) => x + y; IEnumerable<int> expected = new int[] { 3, 6 }; Assert.Equal(expected, first.Zip(second, func)); } [Fact] public void SecondManyMoreThanFirst() { IEnumerable<int> first = new int[] { 1, 2 }; IEnumerable<int> second = new int[] { 2, 4, 8, 16 }; Func<int, int, int> func = (x, y) => x + y; IEnumerable<int> expected = new int[] { 3, 6 }; Assert.Equal(expected, first.Zip(second, func)); } [Fact] public void FirstOneMoreThanSecond() { IEnumerable<int> first = new int[] { 1, 2, 3 }; IEnumerable<int> second = new int[] { 2, 4 }; Func<int, int, int> func = (x, y) => x + y; IEnumerable<int> expected = new int[] { 3, 6 }; Assert.Equal(expected, first.Zip(second, func)); } [Fact] public void FirstManyMoreThanSecond() { IEnumerable<int> first = new int[] { 1, 2, 3, 4 }; IEnumerable<int> second = new int[] { 2, 4 }; Func<int, int, int> func = (x, y) => x + y; IEnumerable<int> expected = new int[] { 3, 6 }; Assert.Equal(expected, first.Zip(second, func)); } [Fact] public void DelegateFuncChanged() { IEnumerable<int> first = new int[] { 1, 2, 3, 4 }; IEnumerable<int> second = new int[] { 2, 4, 8 }; Func<int, int, int> func = (x, y) => x + y; IEnumerable<int> expected = new int[] { 3, 6, 11 }; Assert.Equal(expected, first.Zip(second, func)); func = (x, y) => x - y; expected = new int[] { -1, -2, -5 }; Assert.Equal(expected, first.Zip(second, func)); } [Fact] public void LambdaFuncChanged() { IEnumerable<int> first = new int[] { 1, 2, 3, 4 }; IEnumerable<int> second = new int[] { 2, 4, 8 }; IEnumerable<int> expected = new int[] { 3, 6, 11 }; Assert.Equal(expected, first.Zip(second, (x, y) => x + y)); expected = new int[] { -1, -2, -5 }; Assert.Equal(expected, first.Zip(second, (x, y) => x - y)); } [Fact] public void FirstHasFirstElementNull() { IEnumerable<int?> first = new[] { (int?)null, 2, 3, 4 }; IEnumerable<int> second = new int[] { 2, 4, 8 }; Func<int?, int, int?> func = (x, y) => x + y; IEnumerable<int?> expected = new int?[] { null, 6, 11 }; Assert.Equal(expected, first.Zip(second, func)); } [Fact] public void FirstHasLastElementNull() { IEnumerable<int?> first = new[] { 1, 2, (int?)null }; IEnumerable<int> second = new int[] { 2, 4, 6, 8 }; Func<int?, int, int?> func = (x, y) => x + y; IEnumerable<int?> expected = new int?[] { 3, 6, null }; Assert.Equal(expected, first.Zip(second, func)); } [Fact] public void FirstHasMiddleNullValue() { IEnumerable<int?> first = new[] { 1, (int?)null, 3 }; IEnumerable<int> second = new int[] { 2, 4, 6, 8 }; Func<int?, int, int?> func = (x, y) => x + y; IEnumerable<int?> expected = new int?[] { 3, null, 9 }; Assert.Equal(expected, first.Zip(second, func)); } [Fact] public void FirstAllElementsNull() { IEnumerable<int?> first = new int?[] { null, null, null }; IEnumerable<int> second = new int[] { 2, 4, 6, 8 }; Func<int?, int, int?> func = (x, y) => x + y; IEnumerable<int?> expected = new int?[] { null, null, null }; Assert.Equal(expected, first.Zip(second, func)); } [Fact] public void SecondHasFirstElementNull() { IEnumerable<int> first = new int[] { 1, 2, 3, 4 }; IEnumerable<int?> second = new int?[] { null, 4, 6 }; Func<int, int?, int?> func = (x, y) => x + y; IEnumerable<int?> expected = new int?[] { null, 6, 9 }; Assert.Equal(expected, first.Zip(second, func)); } [Fact] public void SecondHasLastElementNull() { IEnumerable<int> first = new int[] { 1, 2, 3, 4 }; IEnumerable<int?> second = new int?[] { 2, 4, null }; Func<int, int?, int?> func = (x, y) => x + y; IEnumerable<int?> expected = new int?[] { 3, 6, null }; Assert.Equal(expected, first.Zip(second, func)); } [Fact] public void SecondHasMiddleElementNull() { IEnumerable<int> first = new int[] { 1, 2, 3, 4 }; IEnumerable<int?> second = new int?[] { 2, null, 6 }; Func<int, int?, int?> func = (x, y) => x + y; IEnumerable<int?> expected = new int?[] { 3, null, 9 }; Assert.Equal(expected, first.Zip(second, func)); } [Fact] public void SecondHasAllElementsNull() { IEnumerable<int> first = new int[] { 1, 2, 3, 4 }; IEnumerable<int?> second = new int?[] { null, null, null }; Func<int, int?, int?> func = (x, y) => x + y; IEnumerable<int?> expected = new int?[] { null, null, null }; Assert.Equal(expected, first.Zip(second, func)); } [Fact] public void SecondLargerFirstAllNull() { IEnumerable<int?> first = new int?[] { null, null, null, null }; IEnumerable<int?> second = new int?[] { null, null, null }; Func<int?, int?, int?> func = (x, y) => x + y; IEnumerable<int?> expected = new int?[] { null, null, null }; Assert.Equal(expected, first.Zip(second, func)); } [Fact] public void FirstSameSizeSecondAllNull() { IEnumerable<int?> first = new int?[] { null, null, null }; IEnumerable<int?> second = new int?[] { null, null, null }; Func<int?, int?, int?> func = (x, y) => x + y; IEnumerable<int?> expected = new int?[] { null, null, null }; Assert.Equal(expected, first.Zip(second, func)); } [Fact] public void FirstSmallerSecondAllNull() { IEnumerable<int?> first = new int?[] { null, null, null }; IEnumerable<int?> second = new int?[] { null, null, null, null }; Func<int?, int?, int?> func = (x, y) => x + y; IEnumerable<int?> expected = new int?[] { null, null, null }; Assert.Equal(expected, first.Zip(second, func)); } [Fact] public void ForcedToEnumeratorDoesntEnumerate() { var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).Zip(Enumerable.Range(0, 3), (x, y) => x + y); // Don't insist on this behaviour, but check its correct if it happens var en = iterator as IEnumerator<int>; Assert.False(en != null && en.MoveNext()); } } }
// Copyright (c) .NET Foundation. 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.Buffers; using System.Diagnostics; using System.IO; using System.Threading; using System.Threading.Tasks; namespace HtcSharp.HttpModule.Http.WebUtilities { // SourceTools-Start // Remote-File C:\ASP\src\Http\WebUtilities\src\MultipartReaderStream.cs // Start-At-Remote-Line 12 // SourceTools-End internal sealed class MultipartReaderStream : Stream { private readonly MultipartBoundary _boundary; private readonly BufferedReadStream _innerStream; private readonly ArrayPool<byte> _bytePool; private readonly long _innerOffset; private long _position; private long _observedLength; private bool _finished; /// <summary> /// Creates a stream that reads until it reaches the given boundary pattern. /// </summary> /// <param name="stream">The <see cref="BufferedReadStream"/>.</param> /// <param name="boundary">The boundary pattern to use.</param> public MultipartReaderStream(BufferedReadStream stream, MultipartBoundary boundary) : this(stream, boundary, ArrayPool<byte>.Shared) { } /// <summary> /// Creates a stream that reads until it reaches the given boundary pattern. /// </summary> /// <param name="stream">The <see cref="BufferedReadStream"/>.</param> /// <param name="boundary">The boundary pattern to use.</param> /// <param name="bytePool">The ArrayPool pool to use for temporary byte arrays.</param> public MultipartReaderStream(BufferedReadStream stream, MultipartBoundary boundary, ArrayPool<byte> bytePool) { if (stream == null) { throw new ArgumentNullException(nameof(stream)); } if (boundary == null) { throw new ArgumentNullException(nameof(boundary)); } _bytePool = bytePool; _innerStream = stream; _innerOffset = _innerStream.CanSeek ? _innerStream.Position : 0; _boundary = boundary; } public bool FinalBoundaryFound { get; private set; } public long? LengthLimit { get; set; } public override bool CanRead { get { return true; } } public override bool CanSeek { get { return _innerStream.CanSeek; } } public override bool CanWrite { get { return false; } } public override long Length { get { return _observedLength; } } public override long Position { get { return _position; } set { if (value < 0) { throw new ArgumentOutOfRangeException(nameof(value), value, "The Position must be positive."); } if (value > _observedLength) { throw new ArgumentOutOfRangeException(nameof(value), value, "The Position must be less than length."); } _position = value; if (_position < _observedLength) { _finished = false; } } } public override long Seek(long offset, SeekOrigin origin) { if (origin == SeekOrigin.Begin) { Position = offset; } else if (origin == SeekOrigin.Current) { Position = Position + offset; } else // if (origin == SeekOrigin.End) { Position = Length + offset; } return Position; } public override void SetLength(long value) { throw new NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { throw new NotSupportedException(); } public override void Flush() { throw new NotSupportedException(); } private void PositionInnerStream() { if (_innerStream.CanSeek && _innerStream.Position != (_innerOffset + _position)) { _innerStream.Position = _innerOffset + _position; } } private int UpdatePosition(int read) { _position += read; if (_observedLength < _position) { _observedLength = _position; if (LengthLimit.HasValue && _observedLength > LengthLimit.GetValueOrDefault()) { throw new InvalidDataException($"Multipart body length limit {LengthLimit.GetValueOrDefault()} exceeded."); } } return read; } public override int Read(byte[] buffer, int offset, int count) { if (_finished) { return 0; } PositionInnerStream(); if (!_innerStream.EnsureBuffered(_boundary.FinalBoundaryLength)) { throw new IOException("Unexpected end of Stream, the content may have already been read by another component. "); } var bufferedData = _innerStream.BufferedData; // scan for a boundary match, full or partial. int read; if (SubMatch(bufferedData, _boundary.BoundaryBytes, out var matchOffset, out var matchCount)) { // We found a possible match, return any data before it. if (matchOffset > bufferedData.Offset) { read = _innerStream.Read(buffer, offset, Math.Min(count, matchOffset - bufferedData.Offset)); return UpdatePosition(read); } var length = _boundary.BoundaryBytes.Length; Debug.Assert(matchCount == length); // "The boundary may be followed by zero or more characters of // linear whitespace. It is then terminated by either another CRLF" // or -- for the final boundary. var boundary = _bytePool.Rent(length); read = _innerStream.Read(boundary, 0, length); _bytePool.Return(boundary); Debug.Assert(read == length); // It should have all been buffered var remainder = _innerStream.ReadLine(lengthLimit: 100); // Whitespace may exceed the buffer. remainder = remainder.Trim(); if (string.Equals("--", remainder, StringComparison.Ordinal)) { FinalBoundaryFound = true; } Debug.Assert(FinalBoundaryFound || string.Equals(string.Empty, remainder, StringComparison.Ordinal), "Un-expected data found on the boundary line: " + remainder); _finished = true; return 0; } // No possible boundary match within the buffered data, return the data from the buffer. read = _innerStream.Read(buffer, offset, Math.Min(count, bufferedData.Count)); return UpdatePosition(read); } public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (_finished) { return 0; } PositionInnerStream(); if (!await _innerStream.EnsureBufferedAsync(_boundary.FinalBoundaryLength, cancellationToken)) { throw new IOException("Unexpected end of Stream, the content may have already been read by another component. "); } var bufferedData = _innerStream.BufferedData; // scan for a boundary match, full or partial. int matchOffset; int matchCount; int read; if (SubMatch(bufferedData, _boundary.BoundaryBytes, out matchOffset, out matchCount)) { // We found a possible match, return any data before it. if (matchOffset > bufferedData.Offset) { // Sync, it's already buffered read = _innerStream.Read(buffer, offset, Math.Min(count, matchOffset - bufferedData.Offset)); return UpdatePosition(read); } var length = _boundary.BoundaryBytes.Length; Debug.Assert(matchCount == length); // "The boundary may be followed by zero or more characters of // linear whitespace. It is then terminated by either another CRLF" // or -- for the final boundary. var boundary = _bytePool.Rent(length); read = _innerStream.Read(boundary, 0, length); _bytePool.Return(boundary); Debug.Assert(read == length); // It should have all been buffered var remainder = await _innerStream.ReadLineAsync(lengthLimit: 100, cancellationToken: cancellationToken); // Whitespace may exceed the buffer. remainder = remainder.Trim(); if (string.Equals("--", remainder, StringComparison.Ordinal)) { FinalBoundaryFound = true; } Debug.Assert(FinalBoundaryFound || string.Equals(string.Empty, remainder, StringComparison.Ordinal), "Un-expected data found on the boundary line: " + remainder); _finished = true; return 0; } // No possible boundary match within the buffered data, return the data from the buffer. read = _innerStream.Read(buffer, offset, Math.Min(count, bufferedData.Count)); return UpdatePosition(read); } // Does segment1 contain all of matchBytes, or does it end with the start of matchBytes? // 1: AAAAABBBBBCCCCC // 2: BBBBB // Or: // 1: AAAAABBB // 2: BBBBB private bool SubMatch(ArraySegment<byte> segment1, byte[] matchBytes, out int matchOffset, out int matchCount) { // clear matchCount to zero matchCount = 0; // case 1: does segment1 fully contain matchBytes? { var matchBytesLengthMinusOne = matchBytes.Length - 1; var matchBytesLastByte = matchBytes[matchBytesLengthMinusOne]; var segmentEndMinusMatchBytesLength = segment1.Offset + segment1.Count - matchBytes.Length; matchOffset = segment1.Offset; while (matchOffset < segmentEndMinusMatchBytesLength) { var lookaheadTailChar = segment1.Array[matchOffset + matchBytesLengthMinusOne]; if (lookaheadTailChar == matchBytesLastByte && CompareBuffers(segment1.Array, matchOffset, matchBytes, 0, matchBytesLengthMinusOne) == 0) { matchCount = matchBytes.Length; return true; } matchOffset += _boundary.GetSkipValue(lookaheadTailChar); } } // case 2: does segment1 end with the start of matchBytes? var segmentEnd = segment1.Offset + segment1.Count; matchCount = 0; for (; matchOffset < segmentEnd; matchOffset++) { var countLimit = segmentEnd - matchOffset; for (matchCount = 0; matchCount < matchBytes.Length && matchCount < countLimit; matchCount++) { if (matchBytes[matchCount] != segment1.Array[matchOffset + matchCount]) { matchCount = 0; break; } } if (matchCount > 0) { break; } } return matchCount > 0; } private static int CompareBuffers(byte[] buffer1, int offset1, byte[] buffer2, int offset2, int count) { for (; count-- > 0; offset1++, offset2++) { if (buffer1[offset1] != buffer2[offset2]) { return buffer1[offset1] - buffer2[offset2]; } } return 0; } } }
using System; using LumiSoft.Net; using LumiSoft.Net.Mime; namespace LumiSoft.Net.IMAP.Server { /// <summary> /// IMAP search key (RFC 3501 6.4.4 SEARCH Command). /// </summary> internal class SearchKey { private string m_SearchKeyName = ""; private object m_SearchKeyValue = null; /// <summary> /// Default constructor. /// </summary> public SearchKey(string searchKeyName,object value) { m_SearchKeyName = searchKeyName; m_SearchKeyValue = value; } #region method Parse /// <summary> /// Parses one search key from current position. Returns null if there isn't any search key left. /// </summary> /// <param name="reader"></param> public static SearchKey Parse(StringReader reader) { string searchKeyName = ""; object searchKeyValue = null; //Remove spaces from string start reader.ReadToFirstChar(); // Search keyname is always 1 word string word = reader.ReadWord(); if(word == null){ return null; } word = word.ToUpper().Trim(); //Remove spaces from string start reader.ReadToFirstChar(); #region ALL // ALL // All messages in the mailbox; the default initial key for ANDing. if(word == "ALL"){ searchKeyName = "ALL"; } #endregion #region ANSWERED // ANSWERED // Messages with the \Answered flag set. else if(word == "ANSWERED"){ // We internally use KEYWORD ANSWERED searchKeyName = "KEYWORD"; searchKeyValue = "ANSWERED"; } #endregion #region BCC // BCC <string> // Messages that contain the specified string in the envelope structure's BCC field. else if(word == "BCC"){ // We internally use HEADER "BCC:" "value" searchKeyName = "HEADER"; // Read <string> string val = ReadString(reader); if(val != null){ searchKeyValue = new string[]{"BCC:",TextUtils.UnQuoteString(val)}; } else{ throw new Exception("BCC <string> value is missing !"); } } #endregion #region BEFORE // BEFORE <date> // Messages whose internal date (disregarding time and timezone) is earlier than the specified date. else if(word == "BEFORE"){ searchKeyName = "BEFORE"; // Read <date> string val = reader.QuotedReadToDelimiter(' '); if(val != null){ // Parse date try{ searchKeyValue = IMAP_Utils.ParseDate(TextUtils.UnQuoteString(val)); } // Invalid date catch{ throw new Exception("Invalid BEFORE <date> value '" + val + "', valid date syntax: {dd-MMM-yyyy} !"); } } else{ throw new Exception("BEFORE <date> value is missing !"); } } #endregion #region BODY // BODY <string> // Messages that contain the specified string in the body of the message. else if(word == "BODY"){ searchKeyName = "BODY"; string val = ReadString(reader); if(val != null){ searchKeyValue = val; } else{ throw new Exception("BODY <string> value is missing !"); } } #endregion #region CC // CC <string> // Messages that contain the specified string in the envelope structure's CC field. else if(word == "CC"){ // We internally use HEADER "CC:" "value" searchKeyName = "HEADER"; // Read <string> string val = ReadString(reader); if(val != null){ searchKeyValue = new string[]{"CC:",TextUtils.UnQuoteString(val)}; } else{ throw new Exception("CC <string> value is missing !"); } } #endregion #region DELETED // DELETED // Messages with the \Deleted flag set. else if(word == "DELETED"){ // We internally use KEYWORD DELETED searchKeyName = "KEYWORD"; searchKeyValue = "DELETED"; } #endregion #region DRAFT // DRAFT // Messages with the \Draft flag set. else if(word == "DRAFT"){ // We internally use KEYWORD DRAFT searchKeyName = "KEYWORD"; searchKeyValue = "DRAFT"; } #endregion #region FLAGGED // FLAGGED // Messages with the \Flagged flag set. else if(word == "FLAGGED"){ // We internally use KEYWORD FLAGGED searchKeyName = "KEYWORD"; searchKeyValue = "FLAGGED"; } #endregion #region FROM // FROM <string> // Messages that contain the specified string in the envelope structure's FROM field. else if(word == "FROM"){ // We internally use HEADER "FROM:" "value" searchKeyName = "HEADER"; // Read <string> string val = ReadString(reader); if(val != null){ searchKeyValue = new string[]{"FROM:",TextUtils.UnQuoteString(val)}; } else{ throw new Exception("FROM <string> value is missing !"); } } #endregion #region HEADER // HEADER <field-name> <string> // Messages that have a header with the specified field-name (as // defined in [RFC-2822]) and that contains the specified string // in the text of the header (what comes after the colon). If the // string to search is zero-length, this matches all messages that // have a header line with the specified field-name regardless of // the contents. else if(word == "HEADER"){ searchKeyName = "HEADER"; // Read <field-name> string fieldName = ReadString(reader); if(fieldName != null){ fieldName = TextUtils.UnQuoteString(fieldName); } else{ throw new Exception("HEADER <field-name> value is missing !"); } // Read <string> string val = ReadString(reader); if(val != null){ searchKeyValue = new string[]{fieldName,TextUtils.UnQuoteString(val)}; } else{ throw new Exception("(HEADER <field-name>) <string> value is missing !"); } } #endregion #region KEYWORD // KEYWORD <flag> // Messages with the specified keyword flag set. else if(word == "KEYWORD"){ searchKeyName = "KEYWORD"; // Read <flag> string val = reader.QuotedReadToDelimiter(' '); if(val != null){ searchKeyValue = TextUtils.UnQuoteString(val); } else{ throw new Exception("KEYWORD <flag> value is missing !"); } } #endregion #region LARGER // LARGER <n> // Messages with an [RFC-2822] size larger than the specified number of octets. else if(word == "LARGER"){ searchKeyName = "LARGER"; // Read <n> string val = reader.QuotedReadToDelimiter(' '); if(val != null){ // Parse <n> - must be integer value try{ searchKeyValue = Convert.ToInt64(TextUtils.UnQuoteString(val)); } // Invalid <n> catch{ throw new Exception("Invalid LARGER <n> value '" + val + "', it must be numeric value !"); } } else{ throw new Exception("LARGER <n> value is missing !"); } } #endregion #region NEW // NEW // Messages that have the \Recent flag set but not the \Seen flag. // This is functionally equivalent to "(RECENT UNSEEN)". else if(word == "NEW"){ // We internally use KEYWORD RECENT searchKeyName = "KEYWORD"; searchKeyValue = "RECENT"; } #endregion #region NOT // NOT <search-key> or (<search-key> <search-key> ...)(SearchGroup) // Messages that do not match the specified search key. else if(word == "NOT"){ searchKeyName = "NOT"; object searchItem = SearchGroup.ParseSearchKey(reader); if(searchItem != null){ searchKeyValue = searchItem; } else{ throw new Exception("Required NOT <search-key> isn't specified !"); } } #endregion #region OLD // OLD // Messages that do not have the \Recent flag set. This is // functionally equivalent to "NOT RECENT" (as opposed to "NOT NEW"). else if(word == "OLD"){ // We internally use UNKEYWORD RECENT searchKeyName = "UNKEYWORD"; searchKeyValue = "RECENT"; } #endregion #region ON // ON <date> // Messages whose internal date (disregarding time and timezone) is within the specified date. else if(word == "ON"){ searchKeyName = "ON"; // Read <date> string val = reader.QuotedReadToDelimiter(' '); if(val != null){ // Parse date try{ searchKeyValue = IMAP_Utils.ParseDate(TextUtils.UnQuoteString(val)); } // Invalid date catch{ throw new Exception("Invalid ON <date> value '" + val + "', valid date syntax: {dd-MMM-yyyy} !"); } } else{ throw new Exception("ON <date> value is missing !"); } } #endregion #region OR // OR <search-key1> <search-key2> - SearckKey can be parenthesis list of keys ! // Messages that match either search key. else if(word == "OR"){ searchKeyName = "OR"; //--- <search-key1> ----------------------------------------------------// object searchKey1 = SearchGroup.ParseSearchKey(reader); if(searchKey1 == null){ throw new Exception("Required OR <search-key1> isn't specified !"); } //----------------------------------------------------------------------// //--- <search-key2> ----------------------------------------------------// object searchKey2 = SearchGroup.ParseSearchKey(reader); if(searchKey2 == null){ throw new Exception("Required (OR <search-key1>) <search-key2> isn't specified !"); } //-----------------------------------------------------------------------// searchKeyValue = new object[]{searchKey1,searchKey2}; } #endregion #region RECENT // RECENT // Messages that have the \Recent flag set. else if(word == "RECENT"){ // We internally use KEYWORD RECENT searchKeyName = "KEYWORD"; searchKeyValue = "RECENT"; } #endregion #region SEEN // SEEN // Messages that have the \Seen flag set. else if(word == "SEEN"){ // We internally use KEYWORD SEEN searchKeyName = "KEYWORD"; searchKeyValue = "SEEN"; } #endregion #region SENTBEFORE // SENTBEFORE <date> // Messages whose [RFC-2822] Date: header (disregarding time and // timezone) is earlier than the specified date. else if(word == "SENTBEFORE"){ searchKeyName = "SENTBEFORE"; // Read <date> string val = reader.QuotedReadToDelimiter(' '); if(val != null){ // Parse date try{ searchKeyValue = IMAP_Utils.ParseDate(TextUtils.UnQuoteString(val)); } // Invalid date catch{ throw new Exception("Invalid SENTBEFORE <date> value '" + val + "', valid date syntax: {dd-MMM-yyyy} !"); } } else{ throw new Exception("SENTBEFORE <date> value is missing !"); } } #endregion #region SENTON // SENTON <date> // Messages whose [RFC-2822] Date: header (disregarding time and // timezone) is within the specified date. else if(word == "SENTON"){ searchKeyName = "SENTON"; // Read <date> string val = reader.QuotedReadToDelimiter(' '); if(val != null){ // Parse date try{ searchKeyValue = IMAP_Utils.ParseDate(TextUtils.UnQuoteString(val)); } // Invalid date catch{ throw new Exception("Invalid SENTON <date> value '" + val + "', valid date syntax: {dd-MMM-yyyy} !"); } } else{ throw new Exception("SENTON <date> value is missing !"); } } #endregion #region SENTSINCE // SENTSINCE <date> // Messages whose [RFC-2822] Date: header (disregarding time and // timezone) is within or later than the specified date. else if(word == "SENTSINCE"){ searchKeyName = "SENTSINCE"; // Read <date> string val = reader.QuotedReadToDelimiter(' '); if(val != null){ // Parse date try{ searchKeyValue = IMAP_Utils.ParseDate(TextUtils.UnQuoteString(val)); } // Invalid date catch{ throw new Exception("Invalid SENTSINCE <date> value '" + val + "', valid date syntax: {dd-MMM-yyyy} !"); } } else{ throw new Exception("SENTSINCE <date> value is missing !"); } } #endregion #region SINCE // SINCE <date> // Messages whose internal date (disregarding time and timezone) // is within or later than the specified date. else if(word == "SINCE"){ searchKeyName = "SINCE"; // Read <date> string val = reader.ReadWord(); if(val != null){ // Parse date try{ searchKeyValue = IMAP_Utils.ParseDate(TextUtils.UnQuoteString(val)); } // Invalid date catch{ throw new Exception("Invalid SINCE <date> value '" + val + "', valid date syntax: {dd-MMM-yyyy} !"); } } else{ throw new Exception("SINCE <date> value is missing !"); } } #endregion #region SMALLER // SMALLER <n> // Messages with an [RFC-2822] size smaller than the specified number of octets. else if(word == "SMALLER"){ searchKeyName = "SMALLER"; // Read <n> string val = reader.QuotedReadToDelimiter(' '); if(val != null){ val = TextUtils.UnQuoteString(val); // Parse <n> - must be integer value try{ searchKeyValue = Convert.ToInt64(val); } // Invalid <n> catch{ throw new Exception("Invalid SMALLER <n> value '" + val + "', it must be numeric value !"); } } else{ throw new Exception("SMALLER <n> value is missing !"); } } #endregion #region SUBJECT // SUBJECT <string> // Messages that contain the specified string in the envelope structure's SUBJECT field. else if(word == "SUBJECT"){ // We internally use HEADER "SUBJECT:" "value" searchKeyName = "HEADER"; // Read <string> string val = ReadString(reader); if(val != null){ searchKeyValue = new string[]{"SUBJECT:",TextUtils.UnQuoteString(val)}; } else{ throw new Exception("SUBJECT <string> value is missing !"); } } #endregion #region TEXT // TEXT <string> // Messages that contain the specified string in the header or body of the message. else if(word == "TEXT"){ searchKeyName = "TEXT"; string val = ReadString(reader); if(val != null){ searchKeyValue = val; } else{ throw new Exception("TEXT <string> value is missing !"); } } #endregion #region TO // TO <string> // Messages that contain the specified string in the envelope structure's TO field. else if(word == "TO"){ // We internally use HEADER "TO:" "value" searchKeyName = "HEADER"; // Read <string> string val = ReadString(reader); if(val != null){ searchKeyValue = new string[]{"TO:",TextUtils.UnQuoteString(val)}; } else{ throw new Exception("TO <string> value is missing !"); } } #endregion #region UID // UID <sequence set> // Messages with unique identifiers corresponding to the specified // unique identifier set. Sequence set ranges are permitted. else if(word == "UID"){ searchKeyName = "UID"; // Read <sequence set> string val = reader.QuotedReadToDelimiter(' '); if(val != null){ try{ IMAP_SequenceSet sequenceSet = new IMAP_SequenceSet(); sequenceSet.Parse(TextUtils.UnQuoteString(val),long.MaxValue); searchKeyValue = sequenceSet; } catch{ throw new Exception("Invalid UID <sequence-set> value '" + val + "' !"); } } else{ throw new Exception("UID <sequence-set> value is missing !"); } } #endregion #region UNANSWERED // UNANSWERED // Messages that do not have the \Answered flag set. else if(word == "UNANSWERED"){ // We internally use UNKEYWORD SEEN searchKeyName = "UNKEYWORD"; searchKeyValue = "ANSWERED"; } #endregion #region UNDELETED // UNDELETED // Messages that do not have the \Deleted flag set. else if(word == "UNDELETED"){ // We internally use UNKEYWORD UNDELETED searchKeyName = "UNKEYWORD"; searchKeyValue = "DELETED"; } #endregion #region UNDRAFT // UNDRAFT // Messages that do not have the \Draft flag set. else if(word == "UNDRAFT"){ // We internally use UNKEYWORD UNDRAFT searchKeyName = "UNKEYWORD"; searchKeyValue = "DRAFT"; } #endregion #region UNFLAGGED // UNFLAGGED // Messages that do not have the \Flagged flag set. else if(word == "UNFLAGGED"){ // We internally use UNKEYWORD UNFLAGGED searchKeyName = "UNKEYWORD"; searchKeyValue = "FLAGGED"; } #endregion #region UNKEYWORD // UNKEYWORD <flag> // Messages that do not have the specified keyword flag set. else if(word == "UNKEYWORD"){ searchKeyName = "UNKEYWORD"; // Read <flag> string val = reader.QuotedReadToDelimiter(' '); if(val != null){ searchKeyValue = TextUtils.UnQuoteString(val); } else{ throw new Exception("UNKEYWORD <flag> value is missing !"); } } #endregion #region UNSEEN // UNSEEN // Messages that do not have the \Seen flag set. else if(word == "UNSEEN"){ // We internally use UNKEYWORD UNSEEN searchKeyName = "UNKEYWORD"; searchKeyValue = "SEEN"; } #endregion #region Unknown or SEQUENCESET // Unkown keyword or <sequence set> else{ // DUMMY palce(bad design) in IMAP. // Active keyword can be <sequence set> or bad keyword, there is now way to distinguish what is meant. // Why they don't key work SEQUENCESET <sequence set> ? // <sequence set> // Messages with message sequence numbers corresponding to the // specified message sequence number set. // Just try if it can be parsed as sequence-set try{ IMAP_SequenceSet sequenceSet = new IMAP_SequenceSet(); sequenceSet.Parse(word,long.MaxValue); searchKeyName = "SEQUENCESET"; searchKeyValue = sequenceSet; } // This isn't vaild sequnce-set value catch{ throw new Exception("Invalid search key or <sequnce-set> value '" + word + "' !"); } } #endregion // REMOVE ME: // Console.WriteLine(searchKeyName + " : " + Convert.ToString(searchKeyValue)); return new SearchKey(searchKeyName,searchKeyValue); } #endregion // TODO: We have envelope, see if Header is needed or can use envelope for it #region method IsHeaderNeeded /// <summary> /// Gets if message Header is needed for matching. /// </summary> /// <returns></returns> public bool IsHeaderNeeded() { if(m_SearchKeyName == "HEADER"){ return true; } else if(m_SearchKeyName == "NOT"){ return SearchGroup.IsHeaderNeededForKey(m_SearchKeyValue); } else if(m_SearchKeyName == "OR"){ object serachKey1 = ((object[])m_SearchKeyValue)[0]; object serachKey2 = ((object[])m_SearchKeyValue)[1]; if(SearchGroup.IsHeaderNeededForKey(serachKey1) || SearchGroup.IsHeaderNeededForKey(serachKey2)){ return true; } } else if(m_SearchKeyName == "SENTBEFORE"){ return true; } else if(m_SearchKeyName == "SENTON"){ return true; } else if(m_SearchKeyName == "SENTSINCE"){ return true; } else if(m_SearchKeyName == "TEXT"){ return true; } return false; } #endregion #region method IsBodyTextNeeded /// <summary> /// Gets if message body text is needed for matching. /// </summary> /// <returns></returns> public bool IsBodyTextNeeded() { if(m_SearchKeyName == "BODY"){ return true; } else if(m_SearchKeyName == "NOT"){ return SearchGroup.IsBodyTextNeededForKey(m_SearchKeyValue); } else if(m_SearchKeyName == "OR"){ object serachKey1 = ((object[])m_SearchKeyValue)[0]; object serachKey2 = ((object[])m_SearchKeyValue)[1]; if(SearchGroup.IsBodyTextNeededForKey(serachKey1) || SearchGroup.IsBodyTextNeededForKey(serachKey2)){ return true; } } else if(m_SearchKeyName == "TEXT"){ return true; } return false; } #endregion #region method Match /// <summary> /// Gets if specified message matches with this class search-key. /// </summary> /// <param name="no">IMAP message sequence number.</param> /// <param name="uid">IMAP message UID.</param> /// <param name="size">IMAP message size in bytes.</param> /// <param name="internalDate">IMAP message INTERNALDATE (dateTime when server stored message).</param> /// <param name="flags">IMAP message flags.</param> /// <param name="mime">Mime message main header only.</param> /// <param name="bodyText">Message body text.</param> /// <returns></returns> public bool Match(long no,long uid,long size,DateTime internalDate,IMAP_MessageFlags flags,LumiSoft.Net.Mime.Mime mime,string bodyText) { #region ALL // ALL // All messages in the mailbox; the default initial key for ANDing. if(m_SearchKeyName == "ALL"){ return true; } #endregion #region BEFORE // BEFORE <date> // Messages whose internal date (disregarding time and timezone) // is earlier than the specified date. else if(m_SearchKeyName == "BEFORE"){ if(internalDate.Date < (DateTime)m_SearchKeyValue){ return true; } } #endregion #region BODY // BODY <string> // Messages that contain the specified string in the body of the message. // // NOTE: Compare must be done on decoded header and decoded body of message. // In all search keys that use strings, a message matches the key if // the string is a substring of the field. The matching is case-insensitive. else if(m_SearchKeyName == "BODY"){ string val = bodyText; if(val != null && val.ToLower().IndexOf(((string)m_SearchKeyValue).ToLower()) > -1){ return true; } } #endregion #region HEADER // HEADER <field-name> <string> // Messages that have a header with the specified field-name (as // defined in [RFC-2822]) and that contains the specified string // in the text of the header (what comes after the colon). If the // string to search is zero-length, this matches all messages that // have a header line with the specified field-name regardless of // the contents. // // NOTE: Compare must be done on decoded header field value. // In all search keys that use strings, a message matches the key if // the string is a substring of the field. The matching is case-insensitive. else if(m_SearchKeyName == "HEADER"){ string[] headerField_value = (string[])m_SearchKeyValue; // If header field name won't end with :, add it if(!headerField_value[0].EndsWith(":")){ headerField_value[0] = headerField_value[0] + ":"; } if(mime.MainEntity.Header.Contains(headerField_value[0])){ if(headerField_value[1].Length == 0){ return true; } else if(mime.MainEntity.Header.GetFirst(headerField_value[0]).Value.ToLower().IndexOf(headerField_value[1].ToLower()) > -1){ return true; } } } #endregion #region KEYWORD // KEYWORD <flag> // Messages with the specified keyword flag set. else if(m_SearchKeyName == "KEYWORD"){ if((flags & IMAP_Utils.ParseMessageFlags((string)m_SearchKeyValue)) != 0){ return true; } } #endregion #region LARGER // LARGER <n> // Messages with an [RFC-2822] size larger than the specified number of octets. else if(m_SearchKeyName == "LARGER"){ if(size > (long)m_SearchKeyValue){ return true; } } #endregion #region NOT // NOT <search-key> or (<search-key> <search-key> ...)(SearchGroup) // Messages that do not match the specified search key. else if(m_SearchKeyName == "NOT"){ return !SearchGroup.Match_Key_Value(m_SearchKeyValue,no,uid,size,internalDate,flags,mime,bodyText); } #endregion #region ON // ON <date> // Messages whose internal date (disregarding time and timezone) // is within the specified date. else if(m_SearchKeyName == "ON"){ if(internalDate.Date == (DateTime)m_SearchKeyValue){ return true; } } #endregion #region OR // OR <search-key1> <search-key2> - SearckKey can be parenthesis list of keys ! // Messages that match either search key. else if(m_SearchKeyName == "OR"){ object serachKey1 = ((object[])m_SearchKeyValue)[0]; object serachKey2 = ((object[])m_SearchKeyValue)[1]; if(SearchGroup.Match_Key_Value(serachKey1,no,uid,size,internalDate,flags,mime,bodyText) || SearchGroup.Match_Key_Value(serachKey2,no,uid,size,internalDate,flags,mime,bodyText)){ return true; } } #endregion #region SENTBEFORE // SENTBEFORE <date> // Messages whose [RFC-2822] Date: header (disregarding time and // timezone) is earlier than the specified date. else if(m_SearchKeyName == "SENTBEFORE"){ if(mime.MainEntity.Date.Date < (DateTime)m_SearchKeyValue){ return true; } } #endregion #region SENTON // SENTON <date> // Messages whose [RFC-2822] Date: header (disregarding time and // timezone) is within the specified date. else if(m_SearchKeyName == "SENTON"){ if(mime.MainEntity.Date.Date == (DateTime)m_SearchKeyValue){ return true; } } #endregion #region SENTSINCE // SENTSINCE <date> // Messages whose [RFC-2822] Date: header (disregarding time and // timezone) is within or later than the specified date. else if(m_SearchKeyName == "SENTSINCE"){ if(mime.MainEntity.Date.Date >= (DateTime)m_SearchKeyValue){ return true; } } #endregion #region SINCE // SINCE <date> // Messages whose internal date (disregarding time and timezone) // is within or later than the specified date. else if(m_SearchKeyName == "SINCE"){ if(internalDate.Date >= (DateTime)m_SearchKeyValue){ return true; } } #endregion #region SMALLER // SMALLER <n> // Messages with an [RFC-2822] size smaller than the specified number of octets. else if(m_SearchKeyName == "SMALLER"){ if(size < (long)m_SearchKeyValue){ return true; } } #endregion #region TEXT // TEXT <string> // Messages that contain the specified string in the header or body of the message. // // NOTE: Compare must be done on decoded header and decoded body of message. // In all search keys that use strings, a message matches the key if // the string is a substring of the field. The matching is case-insensitive. else if(m_SearchKeyName == "TEXT"){ // See body first string val = bodyText; if(val != null && val.ToLower().IndexOf(((string)m_SearchKeyValue).ToLower()) > -1){ return true; } // If we reach so far, that means body won't contain specified text and we need to check header. foreach(HeaderField headerField in mime.MainEntity.Header){ if(headerField.Value.ToLower().IndexOf(((string)m_SearchKeyValue).ToLower()) > -1){ return true; } } } #endregion #region UID // UID <sequence set> // Messages with unique identifiers corresponding to the specified // unique identifier set. Sequence set ranges are permitted. else if(m_SearchKeyName == "UID"){ return ((IMAP_SequenceSet)m_SearchKeyValue).Contains(uid); } #endregion #region UNKEYWORD // UNKEYWORD <flag> // Messages that do not have the specified keyword flag set. else if(m_SearchKeyName == "UNKEYWORD"){ if((flags & IMAP_Utils.ParseMessageFlags((string)m_SearchKeyValue)) == 0){ return true; } } #endregion #region SEQUENCESET // <sequence set> // Messages with message sequence numbers corresponding to the // specified message sequence number set. else if(m_SearchKeyName == "SEQUENCESET"){ return ((IMAP_SequenceSet)m_SearchKeyValue).Contains(no); } #endregion return false; } #endregion #region method ReadString /// <summary> /// Reads search-key &lt;string&gt; value. /// </summary> /// <param name="reader"></param> /// <returns></returns> private static string ReadString(StringReader reader) { //Remove spaces from string start reader.ReadToFirstChar(); // We must support: // word // "text" // {string_length}data(string_length) // {string_length}data(string_length) if(reader.StartsWith("{")){ // Remove { reader.ReadSpecifiedLength("{".Length); int dataLength = Convert.ToInt32(reader.QuotedReadToDelimiter('}')); return reader.ReadSpecifiedLength(dataLength); } return TextUtils.UnQuoteString(reader.QuotedReadToDelimiter(' ')); } #endregion } }
// 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>ExtensionFeedItem</c> resource.</summary> public sealed partial class ExtensionFeedItemName : gax::IResourceName, sys::IEquatable<ExtensionFeedItemName> { /// <summary>The possible contents of <see cref="ExtensionFeedItemName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>customers/{customer_id}/extensionFeedItems/{feed_item_id}</c>. /// </summary> CustomerFeedItem = 1, } private static gax::PathTemplate s_customerFeedItem = new gax::PathTemplate("customers/{customer_id}/extensionFeedItems/{feed_item_id}"); /// <summary>Creates a <see cref="ExtensionFeedItemName"/> 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="ExtensionFeedItemName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static ExtensionFeedItemName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new ExtensionFeedItemName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="ExtensionFeedItemName"/> with the pattern /// <c>customers/{customer_id}/extensionFeedItems/{feed_item_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedItemId">The <c>FeedItem</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="ExtensionFeedItemName"/> constructed from the provided ids.</returns> public static ExtensionFeedItemName FromCustomerFeedItem(string customerId, string feedItemId) => new ExtensionFeedItemName(ResourceNameType.CustomerFeedItem, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), feedItemId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedItemId, nameof(feedItemId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="ExtensionFeedItemName"/> with pattern /// <c>customers/{customer_id}/extensionFeedItems/{feed_item_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedItemId">The <c>FeedItem</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ExtensionFeedItemName"/> with pattern /// <c>customers/{customer_id}/extensionFeedItems/{feed_item_id}</c>. /// </returns> public static string Format(string customerId, string feedItemId) => FormatCustomerFeedItem(customerId, feedItemId); /// <summary> /// Formats the IDs into the string representation of this <see cref="ExtensionFeedItemName"/> with pattern /// <c>customers/{customer_id}/extensionFeedItems/{feed_item_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedItemId">The <c>FeedItem</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ExtensionFeedItemName"/> with pattern /// <c>customers/{customer_id}/extensionFeedItems/{feed_item_id}</c>. /// </returns> public static string FormatCustomerFeedItem(string customerId, string feedItemId) => s_customerFeedItem.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(feedItemId, nameof(feedItemId))); /// <summary> /// Parses the given resource name string into a new <see cref="ExtensionFeedItemName"/> 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}/extensionFeedItems/{feed_item_id}</c></description></item> /// </list> /// </remarks> /// <param name="extensionFeedItemName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="ExtensionFeedItemName"/> if successful.</returns> public static ExtensionFeedItemName Parse(string extensionFeedItemName) => Parse(extensionFeedItemName, false); /// <summary> /// Parses the given resource name string into a new <see cref="ExtensionFeedItemName"/> 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}/extensionFeedItems/{feed_item_id}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="extensionFeedItemName">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="ExtensionFeedItemName"/> if successful.</returns> public static ExtensionFeedItemName Parse(string extensionFeedItemName, bool allowUnparsed) => TryParse(extensionFeedItemName, allowUnparsed, out ExtensionFeedItemName 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="ExtensionFeedItemName"/> 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}/extensionFeedItems/{feed_item_id}</c></description></item> /// </list> /// </remarks> /// <param name="extensionFeedItemName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="ExtensionFeedItemName"/>, 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 extensionFeedItemName, out ExtensionFeedItemName result) => TryParse(extensionFeedItemName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="ExtensionFeedItemName"/> 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}/extensionFeedItems/{feed_item_id}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="extensionFeedItemName">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="ExtensionFeedItemName"/>, 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 extensionFeedItemName, bool allowUnparsed, out ExtensionFeedItemName result) { gax::GaxPreconditions.CheckNotNull(extensionFeedItemName, nameof(extensionFeedItemName)); gax::TemplatedResourceName resourceName; if (s_customerFeedItem.TryParseName(extensionFeedItemName, out resourceName)) { result = FromCustomerFeedItem(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(extensionFeedItemName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private ExtensionFeedItemName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string feedItemId = null) { Type = type; UnparsedResource = unparsedResourceName; CustomerId = customerId; FeedItemId = feedItemId; } /// <summary> /// Constructs a new instance of a <see cref="ExtensionFeedItemName"/> class from the component parts of pattern /// <c>customers/{customer_id}/extensionFeedItems/{feed_item_id}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedItemId">The <c>FeedItem</c> ID. Must not be <c>null</c> or empty.</param> public ExtensionFeedItemName(string customerId, string feedItemId) : this(ResourceNameType.CustomerFeedItem, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), feedItemId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedItemId, nameof(feedItemId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary> /// The <c>FeedItem</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string FeedItemId { 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.CustomerFeedItem: return s_customerFeedItem.Expand(CustomerId, FeedItemId); 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 ExtensionFeedItemName); /// <inheritdoc/> public bool Equals(ExtensionFeedItemName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(ExtensionFeedItemName a, ExtensionFeedItemName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(ExtensionFeedItemName a, ExtensionFeedItemName b) => !(a == b); } public partial class ExtensionFeedItem { /// <summary> /// <see cref="ExtensionFeedItemName"/>-typed view over the <see cref="ResourceName"/> resource name property. /// </summary> internal ExtensionFeedItemName ResourceNameAsExtensionFeedItemName { get => string.IsNullOrEmpty(ResourceName) ? null : ExtensionFeedItemName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } /// <summary> /// <see cref="CampaignName"/>-typed view over the <see cref="TargetedCampaign"/> resource name property. /// </summary> internal CampaignName TargetedCampaignAsCampaignName { get => string.IsNullOrEmpty(TargetedCampaign) ? null : CampaignName.Parse(TargetedCampaign, allowUnparsed: true); set => TargetedCampaign = value?.ToString() ?? ""; } /// <summary> /// <see cref="AdGroupName"/>-typed view over the <see cref="TargetedAdGroup"/> resource name property. /// </summary> internal AdGroupName TargetedAdGroupAsAdGroupName { get => string.IsNullOrEmpty(TargetedAdGroup) ? null : AdGroupName.Parse(TargetedAdGroup, allowUnparsed: true); set => TargetedAdGroup = value?.ToString() ?? ""; } /// <summary> /// <see cref="GeoTargetConstantName"/>-typed view over the <see cref="TargetedGeoTargetConstant"/> resource /// name property. /// </summary> internal GeoTargetConstantName TargetedGeoTargetConstantAsGeoTargetConstantName { get => string.IsNullOrEmpty(TargetedGeoTargetConstant) ? null : GeoTargetConstantName.Parse(TargetedGeoTargetConstant, allowUnparsed: true); set => TargetedGeoTargetConstant = value?.ToString() ?? ""; } } }
using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.Extensions.Logging; using NBitcoin; namespace Stratis.Bitcoin.Features.MemoryPool.Fee { /// <summary> /// Transation confirmation statistics. /// </summary> public class TxConfirmStats { /// <summary>Instance logger for logging messages.</summary> private readonly ILogger logger; /// <summary> /// Moving average of total fee rate of all transactions in each bucket. /// </summary> /// <remarks> /// Track the historical moving average of this total over blocks. /// </remarks> private List<double> avg; /// <summary>Map of bucket upper-bound to index into all vectors by bucket.</summary> private Dictionary<double, int> bucketMap; //Define the buckets we will group transactions into. /// <summary>The upper-bound of the range for the bucket (inclusive).</summary> private List<double> buckets; // Count the total # of txs confirmed within Y blocks in each bucket. // Track the historical moving average of theses totals over blocks. /// <summary>Confirmation average. confAvg[Y][X].</summary> private List<List<double>> confAvg; /// <summary>Current block confirmations. curBlockConf[Y][X].</summary> private List<List<int>> curBlockConf; /// <summary>Current block transaction count.</summary> private List<int> curBlockTxCt; /// <summary>Current block fee rate.</summary> private List<double> curBlockVal; // Combine the conf counts with tx counts to calculate the confirmation % for each Y,X // Combine the total value with the tx counts to calculate the avg feerate per bucket /// <summary>Decay value to use.</summary> private double decay; /// <summary>Transactions still unconfirmed after MAX_CONFIRMS for each bucket</summary> private List<int> oldUnconfTxs; /// <summary> /// Historical moving average of transaction counts. /// </summary> /// <remarks> /// For each bucket X: /// Count the total # of txs in each bucket. /// Track the historical moving average of this total over blocks /// </remarks> private List<double> txCtAvg; /// <summary> /// Mempool counts of outstanding transactions. /// </summary> /// <remarks> /// For each bucket X, track the number of transactions in the mempool /// that are unconfirmed for each possible confirmation value Y /// unconfTxs[Y][X] /// </remarks> private List<List<int>> unconfTxs; /// <summary> /// Constructs an instance of the transaction confirmation stats object. /// </summary> /// <param name="logger">Instance logger to use for message logging.</param> public TxConfirmStats(ILogger logger) { this.logger = logger; } /// <summary> /// Initialize the data structures. This is called by BlockPolicyEstimator's /// constructor with default values. /// </summary> /// <param name="defaultBuckets">Contains the upper limits for the bucket boundaries.</param> /// <param name="maxConfirms">Max number of confirms to track.</param> /// <param name="decay">How much to decay the historical moving average per block.</param> public void Initialize(List<double> defaultBuckets, int maxConfirms, double decay) { this.buckets = new List<double>(); this.bucketMap = new Dictionary<double, int>(); this.decay = decay; for (int i = 0; i < defaultBuckets.Count; i++) { this.buckets.Add(defaultBuckets[i]); this.bucketMap[defaultBuckets[i]] = i; } this.confAvg = new List<List<double>>(); this.curBlockConf = new List<List<int>>(); this.unconfTxs = new List<List<int>>(); for (int i = 0; i < maxConfirms; i++) { this.confAvg.Insert(i, Enumerable.Repeat(default(double), this.buckets.Count).ToList()); this.curBlockConf.Insert(i, Enumerable.Repeat(default(int), this.buckets.Count).ToList()); this.unconfTxs.Insert(i, Enumerable.Repeat(default(int), this.buckets.Count).ToList()); } this.oldUnconfTxs = new List<int>(Enumerable.Repeat(default(int), this.buckets.Count)); this.curBlockTxCt = new List<int>(Enumerable.Repeat(default(int), this.buckets.Count)); this.txCtAvg = new List<double>(Enumerable.Repeat(default(double), this.buckets.Count)); this.curBlockVal = new List<double>(Enumerable.Repeat(default(double), this.buckets.Count)); this.avg = new List<double>(Enumerable.Repeat(default(double), this.buckets.Count)); } /// <summary> /// Clear the state of the curBlock variables to start counting for the new block. /// </summary> /// <param name="nBlockHeight">Block height.</param> public void ClearCurrent(int nBlockHeight) { for (int j = 0; j < this.buckets.Count; j++) { this.oldUnconfTxs[j] += this.unconfTxs[nBlockHeight % this.unconfTxs.Count][j]; this.unconfTxs[nBlockHeight % this.unconfTxs.Count][j] = 0; for (int i = 0; i < this.curBlockConf.Count; i++) this.curBlockConf[i][j] = 0; this.curBlockTxCt[j] = 0; this.curBlockVal[j] = 0; } } /// <summary> /// Record a new transaction data point in the current block stats. /// </summary> /// <param name="blocksToConfirm">The number of blocks it took this transaction to confirm. blocksToConfirm is 1-based and has to be >= 1.</param> /// <param name="val">The feerate of the transaction.</param> public void Record(int blocksToConfirm, double val) { // blocksToConfirm is 1-based if (blocksToConfirm < 1) return; int bucketindex = this.bucketMap.FirstOrDefault(k => k.Key > val).Value; for (int i = blocksToConfirm; i <= this.curBlockConf.Count; i++) this.curBlockConf[i - 1][bucketindex]++; this.curBlockTxCt[bucketindex]++; this.curBlockVal[bucketindex] += val; } /// <summary> /// Record a new transaction entering the mempool. /// </summary> /// <param name="nBlockHeight">The block height.</param> /// <param name="val"></param> /// <returns>The feerate of the transaction.</returns> public int NewTx(int nBlockHeight, double val) { int bucketindex = this.bucketMap.FirstOrDefault(k => k.Key > val).Value; int blockIndex = nBlockHeight % this.unconfTxs.Count; this.unconfTxs[blockIndex][bucketindex]++; return bucketindex; } /// <summary> /// Remove a transaction from mempool tracking stats. /// </summary> /// <param name="entryHeight">The height of the mempool entry.</param> /// <param name="nBestSeenHeight">The best sceen height.</param> /// <param name="bucketIndex">The bucket index.</param> public void RemoveTx(int entryHeight, int nBestSeenHeight, int bucketIndex) { //nBestSeenHeight is not updated yet for the new block int blocksAgo = nBestSeenHeight - entryHeight; if (nBestSeenHeight == 0) // the BlockPolicyEstimator hasn't seen any blocks yet blocksAgo = 0; if (blocksAgo < 0) { this.logger.LogInformation($"Blockpolicy error, blocks ago is negative for mempool tx"); return; //This can't happen because we call this with our best seen height, no entries can have higher } if (blocksAgo >= this.unconfTxs.Count) { if (this.oldUnconfTxs[bucketIndex] > 0) this.oldUnconfTxs[bucketIndex]--; else { this.logger.LogInformation( $"Blockpolicy error, mempool tx removed from >25 blocks,bucketIndex={bucketIndex} already"); } } else { int blockIndex = entryHeight % this.unconfTxs.Count; if (this.unconfTxs[blockIndex][bucketIndex] > 0) this.unconfTxs[blockIndex][bucketIndex]--; else { this.logger.LogInformation( $"Blockpolicy error, mempool tx removed from blockIndex={blockIndex},bucketIndex={bucketIndex} already"); } } } /// <summary> /// Update our estimates by decaying our historical moving average and updating /// with the data gathered from the current block. /// </summary> public void UpdateMovingAverages() { for (int j = 0; j < this.buckets.Count; j++) { for (int i = 0; i < this.confAvg.Count; i++) this.confAvg[i][j] = this.confAvg[i][j] * this.decay + this.curBlockConf[i][j]; this.avg[j] = this.avg[j] * this.decay + this.curBlockVal[j]; this.txCtAvg[j] = this.txCtAvg[j] * this.decay + this.curBlockTxCt[j]; } } /// <summary> /// Calculate a feerate estimate. Find the lowest value bucket (or range of buckets /// to make sure we have enough data points) whose transactions still have sufficient likelihood /// of being confirmed within the target number of confirmations. /// </summary> /// <param name="confTarget">Target number of confirmations.</param> /// <param name="sufficientTxVal">Required average number of transactions per block in a bucket range.</param> /// <param name="successBreakPoint">The success probability we require.</param> /// <param name="requireGreater">Return the lowest feerate such that all higher values pass minSuccess OR return the highest feerate such that all lower values fail minSuccess.</param> /// <param name="nBlockHeight">The current block height.</param> /// <returns></returns> public double EstimateMedianVal(int confTarget, double sufficientTxVal, double successBreakPoint, bool requireGreater, int nBlockHeight) { // Counters for a bucket (or range of buckets) double nConf = 0; // Number of tx's confirmed within the confTarget double totalNum = 0; // Total number of tx's that were ever confirmed int extraNum = 0; // Number of tx's still in mempool for confTarget or longer int maxbucketindex = this.buckets.Count - 1; // requireGreater means we are looking for the lowest feerate such that all higher // values pass, so we start at maxbucketindex (highest feerate) and look at successively // smaller buckets until we reach failure. Otherwise, we are looking for the highest // feerate such that all lower values fail, and we go in the opposite direction. int startbucket = requireGreater ? maxbucketindex : 0; int step = requireGreater ? -1 : 1; // We'll combine buckets until we have enough samples. // The near and far variables will define the range we've combined // The best variables are the last range we saw which still had a high // enough confirmation rate to count as success. // The cur variables are the current range we're counting. int curNearBucket = startbucket; int bestNearBucket = startbucket; int curFarBucket = startbucket; int bestFarBucket = startbucket; bool foundAnswer = false; int bins = this.unconfTxs.Count; // Start counting from highest(default) or lowest feerate transactions for (int bucket = startbucket; bucket >= 0 && bucket <= maxbucketindex; bucket += step) { curFarBucket = bucket; nConf += this.confAvg[confTarget - 1][bucket]; totalNum += this.txCtAvg[bucket]; for (int confct = confTarget; confct < this.GetMaxConfirms(); confct++) extraNum += this.unconfTxs[(nBlockHeight - confct) % bins][bucket]; extraNum += this.oldUnconfTxs[bucket]; // If we have enough transaction data points in this range of buckets, // we can test for success // (Only count the confirmed data points, so that each confirmation count // will be looking at the same amount of data and same bucket breaks) if (totalNum >= sufficientTxVal / (1 - this.decay)) { double curPct = nConf / (totalNum + extraNum); // Check to see if we are no longer getting confirmed at the success rate if (requireGreater && curPct < successBreakPoint) break; if (!requireGreater && curPct > successBreakPoint) break; // Otherwise update the cumulative stats, and the bucket variables // and reset the counters foundAnswer = true; nConf = 0; totalNum = 0; extraNum = 0; bestNearBucket = curNearBucket; bestFarBucket = curFarBucket; curNearBucket = bucket + step; } } double median = -1; double txSum = 0; // Calculate the "average" feerate of the best bucket range that met success conditions // Find the bucket with the median transaction and then report the average feerate from that bucket // This is a compromise between finding the median which we can't since we don't save all tx's // and reporting the average which is less accurate int minBucket = bestNearBucket < bestFarBucket ? bestNearBucket : bestFarBucket; int maxBucket = bestNearBucket > bestFarBucket ? bestNearBucket : bestFarBucket; for (int j = minBucket; j <= maxBucket; j++) txSum += this.txCtAvg[j]; if (foundAnswer && txSum != 0) { txSum = txSum / 2; for (int j = minBucket; j <= maxBucket; j++) { if (this.txCtAvg[j] < txSum) { txSum -= this.txCtAvg[j]; } else { // we're in the right bucket median = this.avg[j] / this.txCtAvg[j]; break; } } } this.logger.LogInformation( $"{confTarget}: For conf success {(requireGreater ? $">" : $"<")} {successBreakPoint} need feerate {(requireGreater ? $">" : $"<")}: {median} from buckets {this.buckets[minBucket]} -{this.buckets[maxBucket]} Cur Bucket stats {100 * nConf / (totalNum + extraNum)} {nConf}/({totalNum}+{extraNum} mempool)"); return median; } /// <summary> /// Return the max number of confirms we're tracking. /// </summary> /// <returns>The max number of confirms.</returns> public int GetMaxConfirms() { return this.confAvg.Count; } /// <summary> /// Write state of estimation data to a file. /// </summary> /// <param name="stream">Stream to write to.</param> public void Write(BitcoinStream stream) { } /// <summary> /// Read saved state of estimation data from a file and replace all internal data structures and /// variables with this state. /// </summary> /// <param name="filein">Stream to read from.</param> public void Read(Stream filein) { } } }
// <copyright company="APX Labs, Inc."> // Copyright (c) APX Labs, Inc. All rights reserved. // </copyright> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using Java.Interop; namespace ApxLabs.FastAndroidCamera { /// <summary> /// A wrapper around a Java array that reads elements directly from the pointer instead of through expensive JNI calls. /// </summary> public sealed class FastJavaByteArray : IList<byte>, IDisposable { private JniObjectReference _javaRef; #region Constructors /// <summary> /// Creates a new FastJavaByteArray with the given number of bytes reserved. /// </summary> /// <param name="length">Number of bytes to reserve</param> public FastJavaByteArray(int length) { if (length <= 0) throw new ArgumentOutOfRangeException(); JniObjectReference localRef = JniEnvironment.Arrays.NewByteArray(length); if (!localRef.IsValid) throw new OutOfMemoryException(); // Retain a global reference to the byte array. _javaRef = localRef.NewGlobalRef(); Count = length; bool isCopy = false; unsafe { // Get the pointer to the byte array using the global Handle Raw = (byte*)JniEnvironment.Arrays.GetByteArrayElements(_javaRef, &isCopy); } } /// <summary> /// Creates a FastJavaByteArray wrapper around an existing Java/JNI byte array /// </summary> /// <param name="handle">Native Java array handle</param> /// <param name="readOnly">Whether to consider this byte array read-only</param> public FastJavaByteArray(IntPtr handle, bool readOnly = true) { if (handle == IntPtr.Zero) throw new ArgumentNullException("handle"); IsReadOnly = readOnly; // Retain a global reference to the byte array. _javaRef = new JniObjectReference(handle).NewGlobalRef(); Count = JniEnvironment.Arrays.GetArrayLength(_javaRef); bool isCopy = false; unsafe { // Get a pinned pointer to the byte array using the global Handle Raw = (byte*)JniEnvironment.Arrays.GetByteArrayElements(_javaRef, &isCopy); } } #endregion #region Dispose Pattern /// <summary> /// Releases unmanaged resources and performs other cleanup operations before the /// <see cref="T:ApxLabs.FastAndroidCamera.FastJavaByteArray"/> is reclaimed by garbage collection. /// </summary> ~FastJavaByteArray() { Dispose(false); } /// <summary> /// Releases all resource used by the <see cref="T:ApxLabs.FastAndroidCamera.FastJavaByteArray"/> object. /// </summary> /// <remarks>Call <see cref="Dispose"/> when you are finished using the /// <see cref="T:ApxLabs.FastAndroidCamera.FastJavaByteArray"/>. The <see cref="Dispose"/> method leaves the /// <see cref="T:ApxLabs.FastAndroidCamera.FastJavaByteArray"/> in an unusable state. After calling /// <see cref="Dispose"/>, you must release all references to the /// <see cref="T:ApxLabs.FastAndroidCamera.FastJavaByteArray"/> so the garbage collector can reclaim the memory that /// the <see cref="T:ApxLabs.FastAndroidCamera.FastJavaByteArray"/> was occupying.</remarks> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { if (!_javaRef.IsValid) return; unsafe { // tell Java that we're done with this array JniEnvironment.Arrays.ReleaseByteArrayElements(_javaRef, (sbyte*)Raw, JniReleaseArrayElementsMode.Default); } if (disposing) { JniObjectReference.Dispose(ref _javaRef); } } #endregion #region IList<byte> Properties /// <summary> /// Count of bytes /// </summary> public int Count { get; private set; } /// <summary> /// Gets a value indicating whether this byte array is read only. /// </summary> /// <value><c>true</c> if read only; otherwise, <c>false</c>.</value> public bool IsReadOnly { get; private set; } /// <summary> /// Indexer /// </summary> /// <param name="index">Index of byte</param> /// <returns>Byte at the given index</returns> public byte this[int index] { get { if (index < 0 || index >= Count) { throw new ArgumentOutOfRangeException(); } byte retval; unsafe { retval = Raw[index]; } return retval; } set { if (IsReadOnly) { throw new NotSupportedException("This FastJavaByteArray is read-only"); } if (index < 0 || index >= Count) { throw new ArgumentOutOfRangeException(); } unsafe { Raw[index] = value; } } } #endregion #region IList<byte> Methods /// <summary> /// Adds a single byte to the list. Not supported /// </summary> /// <param name="item">byte to add</param> public void Add(byte item) { throw new NotSupportedException("FastJavaByteArray is fixed length"); } /// <summary> /// Not supported /// </summary> public void Clear() { throw new NotSupportedException("FastJavaByteArray is fixed length"); } /// <summary> /// Returns true if the item is found int he array /// </summary> /// <param name="item">Item to find</param> /// <returns>True if the item is found</returns> public bool Contains(byte item) { return IndexOf(item) >= 0; } /// <summary> /// Copies the contents of the FastJavaByteArray into a byte array /// </summary> /// <param name="array">The array to copy to.</param> /// <param name="arrayIndex">The zero-based index into the destination array where CopyTo should start.</param> public void CopyTo(byte[] array, int arrayIndex) { unsafe { Marshal.Copy(new IntPtr(Raw), array, arrayIndex, Math.Min(Count, array.Length - arrayIndex)); } } /// <summary> /// Retreives enumerator /// </summary> /// <returns>Enumerator</returns> [DebuggerHidden] public IEnumerator<byte> GetEnumerator() { return new FastJavaByteArrayEnumerator(this); } /// <summary> /// Retreives enumerator /// </summary> /// <returns>Enumerator</returns> [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { return new FastJavaByteArrayEnumerator(this); } /// <summary> /// Gets the first index of the given value /// </summary> /// <param name="item">Item to search for</param> /// <returns>Index of found item</returns> public int IndexOf(byte item) { for (int i = 0; i < Count; ++i) { byte current; unsafe { current = Raw[i]; } if (current == item) return i; } return -1; } /// <summary> /// Not supported /// </summary> /// <param name="index"></param> /// <param name="item"></param> public void Insert(int index, byte item) { throw new NotSupportedException("FastJavaByteArray is fixed length"); } /// <summary> /// Not supported /// </summary> /// <param name="item"></param> /// <returns></returns> public bool Remove(byte item) { throw new NotSupportedException("FastJavaByteArray is fixed length"); } /// <summary> /// Not supported /// </summary> /// <param name="index"></param> public void RemoveAt(int index) { throw new NotSupportedException("FastJavaByteArray is fixed length"); } #endregion #region Public Properties /// <summary> /// Gets the raw pointer to the underlying data. /// </summary> public unsafe byte* Raw { get; private set; } /// <summary> /// Gets the handle of the Java reference to the array. /// </summary> /// <value>The handle.</value> public IntPtr Handle { get { return _javaRef.Handle; } } #endregion } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using SFML.Graphics; namespace NetGore.Graphics { /// <summary> /// Uses an interpolation to animate between multiple skeletons. /// </summary> public class SkeletonAnimation { readonly List<SkeletonBody> _bodyLayers = new List<SkeletonBody>(); /// <summary> /// Skeleton used for animating. Unlike _frames, the nodes of this skeleton /// are altered to interpolate between frames. /// </summary> readonly Skeleton _skel; /// <summary> /// Current keyframe. /// </summary> SkeletonFrame _currFrame; /// <summary> /// Current frame (unrounded). /// </summary> float _frame = 0.0f; /// <summary> /// Time the skeleton was last updated. /// </summary> TickCount _lastTime = 0; /// <summary> /// Skeleton animation modifier. /// </summary> SkeletonAnimation _mod = null; /// <summary> /// Next keyframe. /// </summary> SkeletonFrame _nextFrame; /// <summary> /// Contains the parent SkeletonAnimation if this SkeletonAnimation is a modifier. If null, this /// SkeletonAnimation is not a modifier. /// </summary> SkeletonAnimation _parent = null; /// <summary> /// Scaling modifier. /// </summary> float _scale = 1.0f; /// <summary> /// Skeleton body information. /// </summary> SkeletonBody _skelBody = null; /// <summary> /// Contains the frames used to animate the skeleton. /// </summary> SkeletonSet _skelSet; /// <summary> /// Speed modifier for animating. /// </summary> float _speed = 1.0f; /// <summary> /// Initializes a new instance of the <see cref="SkeletonAnimation"/> class. /// </summary> /// <param name="currentTime">The current time.</param> /// <param name="skeletonSet"><see cref="SkeletonSet"/> to use for the keyframes.</param> /// <exception cref="ArgumentNullException"><paramref name="skeletonSet" /> is <c>null</c>.</exception> /// <exception cref="ArgumentException">skeletonSet contains no KeyFrames.</exception> public SkeletonAnimation(TickCount currentTime, SkeletonSet skeletonSet) { if (skeletonSet == null) throw new ArgumentNullException("skeletonSet"); if (skeletonSet.KeyFrames.Length == 0) throw new ArgumentException("skeletonSet contains no KeyFrames.", "skeletonSet"); _lastTime = currentTime; _skelSet = skeletonSet; _currFrame = _skelSet.KeyFrames[0]; _nextFrame = _skelSet.KeyFrames.Length > 1 ? _skelSet.KeyFrames[1] : _skelSet.KeyFrames[0]; _skel = CurrentFrame.Skeleton.DeepCopy(); } /// <summary> /// Initializes a new instance of the <see cref="SkeletonAnimation"/> class. /// </summary> /// <param name="currentTime">Current time.</param> /// <param name="frame">Single frame to use for the keyframe.</param> public SkeletonAnimation(TickCount currentTime, SkeletonFrame frame) : this(currentTime, new SkeletonSet(new[] { frame })) { } /// <summary> /// Notifies listeners when the skeleton animation has rolled back over to the first frame. /// </summary> public event EventHandler Looped; /// <summary> /// Gets the collection of additional layers that can be stacked on top of the original. /// <see cref="SkeletonBody"/>. /// </summary> public ICollection<SkeletonBody> BodyLayers { get { return _bodyLayers; } } /// <summary> /// Gets the skeleton for the current frame. /// </summary> public SkeletonFrame CurrentFrame { get { return _currFrame; } } /// <summary> /// Gets the frame number of the animation. /// </summary> public float Frame { get { return _frame; } } /// <summary> /// Gets the SkeletonAnimation used to modify this SkeletonAnimation. /// </summary> public SkeletonAnimation Modifier { get { return _mod; } } /// <summary> /// Gets the skeleton for the next frame. /// </summary> public SkeletonFrame NextFrame { get { return _nextFrame; } } /// <summary> /// Gets or sets the scale of the resulting skeleton. /// </summary> public float Scale { get { return _scale; } set { _scale = value; } } /// <summary> /// Gets the skeleton used by the animation to interpolate between frames and draw. /// </summary> public Skeleton Skeleton { get { return _skel; } } /// <summary> /// Gets the skeleton body used by the animator. /// </summary> public SkeletonBody SkeletonBody { get { return _skelBody; } set { _skelBody = value; } } /// <summary> /// Gets the skeleton set currently in use by the animator. /// </summary> public SkeletonSet SkeletonSet { get { return _skelSet; } } /// <summary> /// Gets or sets the speed multiplier of the animation in percent (1.0 for normal speed). /// </summary> public float Speed { get { return _speed; } set { _speed = value; } } /// <summary> /// Adds a SkeletonAnimation modifier to this SkeletonAnimation. /// </summary> /// <param name="modifier">SkeletonAnimation to use as a modifier.</param> /// <param name="loop">If true, the modifier will loop forever until Detach() is called on the /// modifier or RemoveModifiers() is called on the parent.</param> public void AddModifier(SkeletonAnimation modifier, bool loop = false) { if (modifier == null) { Debug.Fail("modifier is null."); return; } // Remove any current modifier if (_mod != null) _mod.Detach(); // Attach the modifier to this SkeletonAnimation modifier._parent = this; _mod = modifier; // If not looping, detach once the animation finishes if (!loop) { modifier.Looped -= modifier_Looped; modifier.Looped += modifier_Looped; } } /// <summary> /// Changes the SkeletonSet used to animate. /// </summary> /// <param name="newSet">New SkeletonSet to use.</param> public void ChangeSet(SkeletonSet newSet) { if (newSet == null) { Debug.Fail("newSet is null."); return; } if (newSet.KeyFrames.Length == 0) { Debug.Fail("newSet contains no KeyFrames."); return; } // Set the new animation and clear the frame count _frame = 0; _nextFrame = newSet.KeyFrames[0]; _skelSet = newSet; // Create a temporary new current keyframe by duplicating the current state and making // that our new current keyframe, resulting in a smooth translation to the next animation float delay; if (CurrentFrame.Delay == 0) delay = _nextFrame.Delay; else delay = CurrentFrame.Delay; _currFrame = new SkeletonFrame("_worker_", _skel.DeepCopy(), delay); } /// <exception cref="ArgumentNullException"><paramref name="set" /> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException"><paramref name="skel" /> is <c>null</c>.</exception> /// <exception cref="ArgumentException"><paramref name="set"/> contians no KeyFrames.</exception> public static SkeletonSet CreateSmoothedSet(SkeletonSet set, Skeleton skel) { if (set == null) throw new ArgumentNullException("set"); if (skel == null) throw new ArgumentNullException("skel"); if (set.KeyFrames.Length == 0) throw new ArgumentException("Parameter `set` contians no KeyFrames.", "set"); // Create the new frames var frames = new SkeletonFrame[set.KeyFrames.Length + 2]; // Move the old frames into the new frames array for (var i = 0; i < set.KeyFrames.Length; i++) { frames[i + 1] = set.KeyFrames[i]; } // Set the first and last frame to the skeleton var lastFrame = frames.Length - 1; frames[0] = new SkeletonFrame(string.Empty, skel, frames[1].Delay); frames[lastFrame] = new SkeletonFrame(string.Empty, skel, frames[lastFrame - 1].Delay); // Copy over the IsModifier properties from the last frame from the old set // This is required to properly animate the new skeleton set // The last frame is used instead of the first since it is more important that // we transist out of the animation smoother than translating in, under the rare // and undesirable case that all IsModifier properties are not equal frames[0].Skeleton.CopyIsModifier(frames[lastFrame - 1].Skeleton); return new SkeletonSet(frames); } /// <summary> /// If the <see cref="SkeletonAnimation"/> is used as a modifier, this will detach it from its parent. /// </summary> public void Detach() { if (_parent != null) { _parent._mod = null; _parent = null; } } /// <summary> /// Draws the skeleton animation. /// </summary> /// <param name="sb"><see cref="ISpriteBatch"/> to draw to.</param> public void Draw(ISpriteBatch sb) { Draw(sb, Vector2.Zero); } /// <summary> /// Draws the skeleton animation. /// </summary> /// <param name="sb"><see cref="ISpriteBatch"/> to draw to.</param> /// <param name="position">Position offset to draw at.</param> /// <param name="color">The color.</param> /// <param name="effect">SpriteEffect to use when drawing.</param> public void Draw(ISpriteBatch sb, Vector2 position, Color color, SpriteEffects effect = SpriteEffects.None) { if (sb == null) { Debug.Fail("sb is null."); return; } if (sb.IsDisposed) { Debug.Fail("sb is disposed."); return; } if (_skelBody == null) return; // Draw the body and all layers // FUTURE: This is horribly inefficient. Can improve later by, whenever a body layer is added or removed // use a dictionary where the key is the _skelBody.BodyItems, and the value is an IEnumerable of all body layer // items to draw for that layer (giving us O(1) look-up). Then update that dictionary every time the collection // is changed. Will have to change the way the BodyLayers is exposed so we can keep track of adds/removes. foreach (var item in _skelBody.BodyItems) { item.Draw(sb, position, _scale, color, effect); foreach (var bodyLayer in BodyLayers) { foreach (var item2 in bodyLayer.BodyItems) { if (item2.Source == item.Source && item.Dest == item2.Dest) item2.Draw(sb, position, _scale, color, effect); } } } } /// <summary> /// Draws the skeleton animation. /// </summary> /// <param name="sb"><see cref="ISpriteBatch"/> to draw to.</param> /// <param name="position">Position offset to draw at.</param> /// <param name="effect">SpriteEffect to use when drawing.</param> public void Draw(ISpriteBatch sb, Vector2 position, SpriteEffects effect = SpriteEffects.None) { Draw(sb, position, Color.White, effect); } /// <summary> /// Recursively updates all the children of a node. /// </summary> /// <param name="srcA">Source skeleton node for the current frame.</param> /// <param name="srcB">Source skeleton node for the next frame.</param> /// <param name="srcP">Parent skeleton node (use null if theres no parent).</param> /// <param name="dest">Destination skeleton node to have the two sources applied to.</param> /// <param name="framePercent">A value between 0.0 and 1.0 stating how far along the animation is /// from the current frame.</param> void RecursiveUpdate(SkeletonNode srcA, SkeletonNode srcB, SkeletonNode srcP, SkeletonNode dest, float framePercent) { // Set the position Vector2 vA; Vector2 vB; if (_scale == 1.0f) { vA = srcA.Position; vB = srcB.Position; } else { vA = srcA.Position * _scale; vB = srcB.Position * _scale; } dest.Position = Vector2.Lerp(vA, vB, framePercent); // Check if the node is part of a modifier animation if (srcP == null) { // Set the length dest.SetLength(srcA.GetLength() * _scale); } else { // This is a modifier so check for inheriting node values dest.SetLength(srcP.GetLength()); if (!srcP.IsModifier && srcP.Parent != null) dest.SetAngle(srcP.GetAngle()); } // Update the child nodes (if there is any) for (var i = 0; i < srcA.internalNodes.Count; i++) { var nextSrcP = (srcP == null ? null : srcP.internalNodes[i]); RecursiveUpdate(srcA.internalNodes[i], srcB.internalNodes[i], nextSrcP, dest.internalNodes[i], framePercent); } } /// <summary> /// Updates the parent <see cref="SkeletonAnimation"/> that this modifier modifies. /// </summary> /// <param name="src">Source root <see cref="SkeletonNode"/>.</param> /// <param name="dest">Destination root <see cref="SkeletonNode"/>.</param> static void RecursiveUpdateParent(SkeletonNode src, SkeletonNode dest) { // Update modified values if (src.IsModifier && dest.Parent != null) dest.SetAngle(src.GetAngle()); // Update the child nodes (if there is any) for (var i = 0; i < src.internalNodes.Count; i++) { RecursiveUpdateParent(src.internalNodes[i], dest.internalNodes[i]); } } /// <summary> /// Sets the speed of the animation so that it finishes within a specified time limit. /// </summary> /// <param name="currentTime">The current time in milliseconds.</param> void SetTargetTime(TickCount currentTime) { var totalTime = 0.0f; //Find the total time taken to run through all of the frames foreach (var frame in _skelSet.KeyFrames) { totalTime += frame.Delay; } //Set the speed of the animation _speed = totalTime / currentTime; } /// <summary> /// Updates the skeleton animation. /// </summary> /// <param name="currentTime">Current time.</param> public void Update(TickCount currentTime) { // If theres no frames and no modifier, don't update if (_mod == null && (_skelSet.KeyFrames.Length == 1) && (CurrentFrame.Skeleton == _skelSet.KeyFrames[0].Skeleton)) _lastTime = currentTime; else { // Find the time that has elapsed since the last update float elapsedTime = currentTime - _lastTime; _lastTime = currentTime; // Calculate the new frame float delay; if (CurrentFrame.Delay == 0f) delay = NextFrame.Delay; else delay = CurrentFrame.Delay; var newFrame = _frame + ((elapsedTime * _speed) / delay); if (_skelSet.KeyFrames.Length != 1) newFrame %= _skelSet.KeyFrames.Length; // Set the new keyframe references if the frame changed if ((int)newFrame != (int)_frame) { if (_skelSet.KeyFrames.Length == 1) { _nextFrame = _skelSet.KeyFrames[0]; _currFrame = _nextFrame; } else { // If we have reached the first frame, raise the OnLoop event if ((int)newFrame == 0) { if (Looped != null) Looped.Raise(this, EventArgs.Empty); } // Store the new frame references _currFrame = _skelSet.KeyFrames[(int)newFrame]; _nextFrame = _skelSet.KeyFrames[((int)newFrame + 1) % _skelSet.KeyFrames.Length]; } } // Set the new frame _frame = newFrame; // Update the nodes of the working skeleton var framePercent = _frame - (int)_frame; SkeletonNode parentNode; if (_parent == null) parentNode = null; else parentNode = _parent.Skeleton.RootNode; RecursiveUpdate(CurrentFrame.Skeleton.RootNode, NextFrame.Skeleton.RootNode, parentNode, _skel.RootNode, framePercent); } // Update the body if (_skelBody != null) _skelBody.Update(currentTime); foreach (var bodyLayer in BodyLayers) { bodyLayer.Update(currentTime); } // If there is a parent, apply the changes to it if (_parent != null) RecursiveUpdateParent(_skel.RootNode, _parent.Skeleton.RootNode); // Apply the modifiers if (_mod != null) _mod.Update(currentTime); } /// <summary> /// Removes a SkeletonAnimation after a single loop by hooking to the OnLoop event. /// </summary> static void modifier_Looped(object sender, EventArgs e) { var src = sender as SkeletonAnimation; if (src == null) { Debug.Fail("src == null - unable to convert sender to SkeletonAnimation."); return; } // Remove all the events from the modifier SkeletonAnimation src.Looped = null; // If it has a parent (which it should), remove the references src.Detach(); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsAzureBodyDurationNoSync { using System; using System.Linq; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure; using Models; /// <summary> /// Test Infrastructure for AutoRest /// </summary> public partial class AutoRestDurationTestService : ServiceClient<AutoRestDurationTestService>, IAutoRestDurationTestService, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IDurationOperations. /// </summary> public virtual IDurationOperations Duration { get; private set; } /// <summary> /// Initializes a new instance of the AutoRestDurationTestService class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestDurationTestService(params DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestDurationTestService class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestDurationTestService(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestDurationTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected AutoRestDurationTestService(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestDurationTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected AutoRestDurationTestService(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestDurationTestService class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestDurationTestService(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestDurationTestService class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestDurationTestService(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestDurationTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestDurationTestService(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestDurationTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestDurationTestService(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.Duration = new DurationOperations(this); this.BaseUri = new Uri("https://localhost"); this.AcceptLanguage = "en-US"; this.LongRunningOperationRetryTimeout = 30; this.GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
/******************************************************************************* * Copyright (c) 2013, Daniel Murphy * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ /** * Created at 7:27:32 AM Jan 20, 2011 */ using System.Diagnostics; using SharpBox2D.Common; using SharpBox2D.Pooling; namespace SharpBox2D.Dynamics.Joints { /** * @author Daniel Murphy */ public class FrictionJoint : Joint { private Vec2 m_localAnchorA; private Vec2 m_localAnchorB; // Solver shared private Vec2 m_linearImpulse; private float m_angularImpulse; private float m_maxForce; private float m_maxTorque; // Solver temp private int m_indexA; private int m_indexB; private Vec2 m_rA = new Vec2(); private Vec2 m_rB = new Vec2(); private Vec2 m_localCenterA = new Vec2(); private Vec2 m_localCenterB = new Vec2(); private float m_invMassA; private float m_invMassB; private float m_invIA; private float m_invIB; private Mat22 m_linearMass = new Mat22(); private float m_angularMass; internal FrictionJoint(IWorldPool argWorldPool, FrictionJointDef def) : base(argWorldPool, def) { m_localAnchorA = new Vec2(def.localAnchorA); m_localAnchorB = new Vec2(def.localAnchorB); m_linearImpulse = new Vec2(); m_angularImpulse = 0.0f; m_maxForce = def.maxForce; m_maxTorque = def.maxTorque; } public Vec2 getLocalAnchorA() { return m_localAnchorA; } public Vec2 getLocalAnchorB() { return m_localAnchorB; } public override void getAnchorA(ref Vec2 argOut) { m_bodyA.getWorldPointToOut(m_localAnchorA, ref argOut); } public override void getAnchorB(ref Vec2 argOut) { m_bodyB.getWorldPointToOut(m_localAnchorB, ref argOut); } public override void getReactionForce(float inv_dt, ref Vec2 argOut) { argOut.set(m_linearImpulse); argOut.mulLocal(inv_dt); } public override float getReactionTorque(float inv_dt) { return inv_dt*m_angularImpulse; } public void setMaxForce(float force) { Debug.Assert(force >= 0.0f); m_maxForce = force; } public float getMaxForce() { return m_maxForce; } public void setMaxTorque(float torque) { Debug.Assert(torque >= 0.0f); m_maxTorque = torque; } public float getMaxTorque() { return m_maxTorque; } /** * @see org.jbox2d.dynamics.joints.Joint#initVelocityConstraints(org.jbox2d.dynamics.TimeStep) */ public override void initVelocityConstraints(SolverData data) { m_indexA = m_bodyA.m_islandIndex; m_indexB = m_bodyB.m_islandIndex; m_localCenterA.set(m_bodyA.m_sweep.localCenter); m_localCenterB.set(m_bodyB.m_sweep.localCenter); m_invMassA = m_bodyA.m_invMass; m_invMassB = m_bodyB.m_invMass; m_invIA = m_bodyA.m_invI; m_invIB = m_bodyB.m_invI; float aA = data.positions[m_indexA].a; Vec2 vA = data.velocities[m_indexA].v; float wA = data.velocities[m_indexA].w; float aB = data.positions[m_indexB].a; Vec2 vB = data.velocities[m_indexB].v; float wB = data.velocities[m_indexB].w; Vec2 temp = pool.popVec2(); Rot qA = pool.popRot(); Rot qB = pool.popRot(); qA.set(aA); qB.set(aB); // Compute the effective mass matrix. temp.set(m_localAnchorA); temp.subLocal(m_localCenterA); Rot.mulToOutUnsafe(qA, temp, ref m_rA); temp.set(m_localAnchorB); temp.subLocal(m_localCenterB); Rot.mulToOutUnsafe(qB, temp, ref m_rB); // J = [-I -r1_skew I r2_skew] // [ 0 -1 0 1] // r_skew = [-ry; rx] // Matlab // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] float mA = m_invMassA, mB = m_invMassB; float iA = m_invIA, iB = m_invIB; Mat22 K = pool.popMat22(); K.ex.x = mA + mB + iA*m_rA.y*m_rA.y + iB*m_rB.y*m_rB.y; K.ex.y = -iA*m_rA.x*m_rA.y - iB*m_rB.x*m_rB.y; K.ey.x = K.ex.y; K.ey.y = mA + mB + iA*m_rA.x*m_rA.x + iB*m_rB.x*m_rB.x; K.invertToOut(ref m_linearMass); m_angularMass = iA + iB; if (m_angularMass > 0.0f) { m_angularMass = 1.0f/m_angularMass; } if (data.step.warmStarting) { // Scale impulses to support a variable time step. m_linearImpulse.mulLocal(data.step.dtRatio); m_angularImpulse *= data.step.dtRatio; Vec2 P = pool.popVec2(); P.set(m_linearImpulse); temp.set(P); temp.mulLocal(mA); vA.subLocal(temp); wA -= iA*(Vec2.cross(m_rA, P) + m_angularImpulse); temp.set(P); temp.mulLocal(mB); vB.addLocal(temp); wB += iB*(Vec2.cross(m_rB, P) + m_angularImpulse); pool.pushVec2(1); } else { m_linearImpulse.setZero(); m_angularImpulse = 0.0f; } // data.velocities[m_indexA].v.set(vA); if (data.velocities[m_indexA].w != wA) { Debug.Assert(data.velocities[m_indexA].w != wA); } data.velocities[m_indexA].w = wA; // data.velocities[m_indexB].v.set(vB); data.velocities[m_indexB].w = wB; pool.pushRot(2); pool.pushVec2(1); pool.pushMat22(1); } public override void solveVelocityConstraints(SolverData data) { Vec2 vA = data.velocities[m_indexA].v; float wA = data.velocities[m_indexA].w; Vec2 vB = data.velocities[m_indexB].v; float wB = data.velocities[m_indexB].w; float mA = m_invMassA, mB = m_invMassB; float iA = m_invIA, iB = m_invIB; float h = data.step.dt; // Solve angular friction { float Cdot = wB - wA; float impulse = -m_angularMass*Cdot; float oldImpulse = m_angularImpulse; float maxImpulse = h*m_maxTorque; m_angularImpulse = MathUtils.clamp(m_angularImpulse + impulse, -maxImpulse, maxImpulse); impulse = m_angularImpulse - oldImpulse; wA -= iA*impulse; wB += iB*impulse; } // Solve linear friction { Vec2 Cdot = pool.popVec2(); Vec2 temp = pool.popVec2(); Vec2.crossToOutUnsafe(wA, m_rA, ref temp); Vec2.crossToOutUnsafe(wB, m_rB, ref Cdot); Cdot.addLocal(vB); Cdot.subLocal(vA); Cdot.subLocal(temp); Vec2 impulse = pool.popVec2(); Mat22.mulToOutUnsafe(m_linearMass, Cdot, ref impulse); impulse.negateLocal(); Vec2 oldImpulse = pool.popVec2(); oldImpulse.set(m_linearImpulse); m_linearImpulse.addLocal(impulse); float maxImpulse = h*m_maxForce; if (m_linearImpulse.lengthSquared() > maxImpulse*maxImpulse) { m_linearImpulse.normalize(); m_linearImpulse.mulLocal(maxImpulse); } impulse.set(m_linearImpulse); impulse.subLocal(oldImpulse); temp.set(impulse); temp.mulLocal(mA); vA.subLocal(temp); wA -= iA*Vec2.cross(m_rA, impulse); temp.set(impulse); temp.mulLocal(mB); vB.addLocal(temp); wB += iB*Vec2.cross(m_rB, impulse); } // data.velocities[m_indexA].v.set(vA); if (data.velocities[m_indexA].w != wA) { Debug.Assert(data.velocities[m_indexA].w != wA); } data.velocities[m_indexA].w = wA; // data.velocities[m_indexB].v.set(vB); data.velocities[m_indexB].w = wB; pool.pushVec2(4); } public override bool solvePositionConstraints(SolverData data) { return true; } } }
// Authors: Robert M. Scheller, James B. Domingo using Landis.Library.Succession; using Landis.Core; using System.Collections.Generic; using System.Collections; using System.Data; using Landis.Utilities; namespace Landis.Extension.Succession.Biomass { /// <summary> /// A parser that reads biomass succession parameters from text input. /// </summary> public class InputParametersParser : TextParser<IInputParameters> { public static class Names { public const string Timestep = "Timestep"; public const string SeedingAlgorithm = "SeedingAlgorithm"; public const string ClimateConfigFile = "ClimateConfigFile"; public const string DynamicInputFile = "SpeciesEcoregionDataFile"; public const string CalibrateMode = "CalibrateMode"; public const string FireReductionParameters = "FireReductionParameters"; public const string HarvestReductionParameters = "HarvestReductionParameters"; } //--------------------------------------------------------------------- public override string LandisDataValue { get { return PlugIn.ExtensionName; } } //--------------------------------------------------------------------- private Dictionary<string, int> speciesLineNums; private InputVar<string> speciesName; //--------------------------------------------------------------------- static InputParametersParser() { Percentage dummy = new Percentage(); SeedingAlgorithmsUtil.RegisterForInputValues(); } //--------------------------------------------------------------------- public InputParametersParser() { this.speciesLineNums = new Dictionary<string, int>(); this.speciesName = new InputVar<string>("Species"); } //--------------------------------------------------------------------- protected override IInputParameters Parse() { ReadLandisDataVar(); InputParameters parameters = new InputParameters(); InputVar<int> timestep = new InputVar<int>(Names.Timestep); ReadVar(timestep); parameters.Timestep = timestep.Value; InputVar<SeedingAlgorithms> seedAlg = new InputVar<SeedingAlgorithms>(Names.SeedingAlgorithm); ReadVar(seedAlg); parameters.SeedAlgorithm = seedAlg.Value; //--------------------------------------------------------------------------------- InputVar<string> initCommunities = new InputVar<string>("InitialCommunities"); ReadVar(initCommunities); parameters.InitialCommunities = initCommunities.Value; InputVar<string> communitiesMap = new InputVar<string>("InitialCommunitiesMap"); ReadVar(communitiesMap); parameters.InitialCommunitiesMap = communitiesMap.Value; InputVar<string> climateConfigFile = new InputVar<string>(Names.ClimateConfigFile); if (ReadOptionalVar(climateConfigFile)) parameters.ClimateConfigFile = climateConfigFile.Value; else parameters.ClimateConfigFile = null; //--------------------------------------------------------------------------------- InputVar<bool> calimode = new InputVar<bool>(Names.CalibrateMode); if(ReadOptionalVar(calimode)) parameters.CalibrateMode = calimode.Value; else parameters.CalibrateMode = false; InputVar<double> spinMort = new InputVar<double>("SpinupMortalityFraction"); if(ReadOptionalVar(spinMort)) parameters.SpinupMortalityFraction = spinMort.Value; else parameters.SpinupMortalityFraction = 0.0; //-------------------------- // MinRelativeBiomass table ReadName("MinRelativeBiomass"); const string SufficientLight = "SufficientLight"; List<IEcoregion> ecoregions = ReadEcoregions(); string lastEcoregion = ecoregions[ecoregions.Count - 1].Name; InputVar<byte> shadeClassVar = new InputVar<byte>("Shade Class"); for (byte shadeClass = 1; shadeClass <= 5; shadeClass++) { if (AtEndOfInput) throw NewParseException("Expected a line with shade class {0}", shadeClass); StringReader currentLine = new StringReader(CurrentLine); ReadValue(shadeClassVar, currentLine); if (shadeClassVar.Value.Actual != shadeClass) throw new InputValueException(shadeClassVar.Value.String, "Expected the shade class {0}", shadeClass); foreach (IEcoregion ecoregion in ecoregions) { InputVar<Percentage> MinRelativeBiomass = new InputVar<Percentage>("Ecoregion " + ecoregion.Name); ReadValue(MinRelativeBiomass, currentLine); parameters.SetMinRelativeBiomass(shadeClass, ecoregion, MinRelativeBiomass.Value); } CheckNoDataAfter("the Ecoregion " + lastEcoregion + " column", currentLine); GetNextLine(); } //---------------------------------------------------------- // Read table of sufficient light probabilities. // Shade classes are in increasing order. ReadName(SufficientLight); const string SpeciesParameters = "SpeciesDataFile"; InputVar<byte> sc = new InputVar<byte>("Shade Class"); InputVar<double> pl0 = new InputVar<double>("Probability of Germination - Light Level 0"); InputVar<double> pl1 = new InputVar<double>("Probability of Germination - Light Level 1"); InputVar<double> pl2 = new InputVar<double>("Probability of Germination - Light Level 2"); InputVar<double> pl3 = new InputVar<double>("Probability of Germination - Light Level 3"); InputVar<double> pl4 = new InputVar<double>("Probability of Germination - Light Level 4"); InputVar<double> pl5 = new InputVar<double>("Probability of Germination - Light Level 5"); int previousNumber = 0; while (! AtEndOfInput && CurrentName != SpeciesParameters && previousNumber != 6) { StringReader currentLine = new StringReader(CurrentLine); ISufficientLight suffLight = new SufficientLight(); parameters.LightClassProbabilities.Add(suffLight); ReadValue(sc, currentLine); suffLight.ShadeClass = sc.Value; // Check that the current shade class is 1 more than // the previous number (numbers are must be in increasing order). if (sc.Value.Actual != (byte) previousNumber + 1) throw new InputValueException(sc.Value.String, "Expected the severity number {0}", previousNumber + 1); previousNumber = (int) sc.Value.Actual; ReadValue(pl0, currentLine); suffLight.ProbabilityLight0 = pl0.Value; ReadValue(pl1, currentLine); suffLight.ProbabilityLight1 = pl1.Value; ReadValue(pl2, currentLine); suffLight.ProbabilityLight2 = pl2.Value; ReadValue(pl3, currentLine); suffLight.ProbabilityLight3 = pl3.Value; ReadValue(pl4, currentLine); suffLight.ProbabilityLight4 = pl4.Value; ReadValue(pl5, currentLine); suffLight.ProbabilityLight5 = pl5.Value; CheckNoDataAfter("the " + pl5.Name + " column", currentLine); GetNextLine(); } if (parameters.LightClassProbabilities.Count == 0) throw NewParseException("No sufficient light probabilities defined."); if (previousNumber != 5) throw NewParseException("Expected shade class {0}", previousNumber + 1); //------------------------- // SpeciesParameters table InputVar<string> sppInputFile = new InputVar<string>("SpeciesDataFile"); ReadVar(sppInputFile); CSVParser sppParser = new CSVParser(); DataTable speciesTable = sppParser.ParseToDataTable(sppInputFile.Value); foreach (DataRow row in speciesTable.Rows) { ISpecies species = ReadSpecies(System.Convert.ToString(row["SpeciesCode"])); parameters.SetLeafLongevity(species, System.Convert.ToDouble(row["LeafLongevity"])); parameters.SetWoodyDecayRate(species, System.Convert.ToDouble(row["WoodDecayRate"])); parameters.SetMortCurveShapeParm(species, System.Convert.ToDouble(row["MortalityCurve"])); parameters.SetGrowthCurveShapeParm(species, System.Convert.ToDouble(row["GrowthCurve"])); parameters.SetLeafLignin(species, System.Convert.ToDouble(row["LeafLignin"])); } // ReadName("SpeciesParameters"); //const string EcoregionParameters = "EcoregionParameters"; //speciesLineNums.Clear(); //InputVar<double> leafLongevity = new InputVar<double>("Leaf Longevity"); //InputVar<double> woodyDecayRate = new InputVar<double>("Woody Decay Rate"); //InputVar<double> mortCurveShapeParm = new InputVar<double>("Mortality Curve Shape Parameter"); //InputVar<double> growthCurveShapeParm = new InputVar<double>("Mortality Curve Shape Parameter"); //InputVar<double> leafLignin = new InputVar<double>("Leaf Percent Lignin"); //InputVar<double> maxlai = new InputVar<double>("Maximum LAI"); //InputVar<double> lec = new InputVar<double>("Light extinction coefficient"); //InputVar<double> pctBio = new InputVar<double>("Pct Biomass Max LAI"); ////string lastColumn = "the " + mortCurveShapeParm.Name + " column"; //while (! AtEndOfInput && CurrentName != EcoregionParameters) { // StringReader currentLine = new StringReader(CurrentLine); // ISpecies species = ReadSpecies(currentLine); // ReadValue(leafLongevity, currentLine); // parameters.SetLeafLongevity(species, leafLongevity.Value); // ReadValue(woodyDecayRate, currentLine); // parameters.SetWoodyDecayRate(species, woodyDecayRate.Value); // ReadValue(mortCurveShapeParm, currentLine); // parameters.SetMortCurveShapeParm(species, mortCurveShapeParm.Value); // ReadValue(growthCurveShapeParm, currentLine); // parameters.SetGrowthCurveShapeParm(species, growthCurveShapeParm.Value); // ReadValue(leafLignin, currentLine); // parameters.SetLeafLignin(species, leafLignin.Value); // CheckNoDataAfter(leafLignin.Name, currentLine); // GetNextLine(); //} ReadName("EcoregionParameters"); InputVar<string> ecoregionName = new InputVar<string>("Ecoregion Name"); InputVar<int> aet = new InputVar<int>("Actual Evapotranspiration"); Dictionary <string, int> lineNumbers = new Dictionary<string, int>(); string lastColumn = "the " + aet.Name + " column"; while (! AtEndOfInput && CurrentName != Names.DynamicInputFile) { StringReader currentLine = new StringReader(CurrentLine); ReadValue(ecoregionName, currentLine); IEcoregion ecoregion = GetEcoregion(ecoregionName.Value, lineNumbers); ReadValue(aet, currentLine); parameters.SetAET(ecoregion, aet.Value); CheckNoDataAfter(lastColumn, currentLine); GetNextLine(); } InputVar<string> dynInputFile = new InputVar<string>("SpeciesEcoregionDataFile"); ReadVar(dynInputFile); CSVParser sppEcoParser = new CSVParser(); DataTable sppEcoTable = sppEcoParser.ParseToDataTable(dynInputFile.Value); SpeciesData.SppEcoData = new Dictionary<int, IDynamicInputRecord[,]>(); foreach (DataRow row in sppEcoTable.Rows) { int year = System.Convert.ToInt32(row["Year"]); if (!SpeciesData.SppEcoData.ContainsKey(year)) { IDynamicInputRecord[,] inputTable = new IDynamicInputRecord[PlugIn.ModelCore.Species.Count, PlugIn.ModelCore.Ecoregions.Count]; SpeciesData.SppEcoData.Add(year, inputTable); //PlugIn.ModelCore.UI.WriteLine(" Dynamic Input Parser: Add new year = {0}.", year); } ISpecies species = ReadSpecies(System.Convert.ToString(row["SpeciesCode"])); IEcoregion ecoregion = GetEcoregion(System.Convert.ToString(row["EcoregionName"])); IDynamicInputRecord dynamicInputRecord = new DynamicInputRecord(); dynamicInputRecord.ProbEstablish = System.Convert.ToDouble(row["ProbEstablish"]); dynamicInputRecord.ProbMortality = System.Convert.ToDouble(row["ProbMortality"]); dynamicInputRecord.ANPP_MAX_Spp = System.Convert.ToInt32(row["ANPPmax"]); dynamicInputRecord.B_MAX_Spp = System.Convert.ToInt32(row["BiomassMax"]); SpeciesData.SppEcoData[year][species.Index, ecoregion.Index] = dynamicInputRecord; } //--------- Read In Fire Reductions Table --------------------------- PlugIn.ModelCore.UI.WriteLine(" Begin reading FIRE REDUCTION parameters."); ReadName(Names.FireReductionParameters); InputVar<int> frindex = new InputVar<int>("Fire Severity Index MUST = 1-5"); InputVar<double> wred = new InputVar<double>("Coarse Litter Reduction"); InputVar<double> lred = new InputVar<double>("Fine Litter Reduction"); //InputVar<double> som_red = new InputVar<double>("SOM Reduction"); while (!AtEndOfInput && CurrentName != Names.HarvestReductionParameters) { StringReader currentLine = new StringReader(CurrentLine); ReadValue(frindex, currentLine); int ln = (int)frindex.Value.Actual; if (ln < 1 || ln > 5) throw new InputValueException(frindex.Value.String, "The fire severity index: {0} must be 1-5,", frindex.Value.String); FireReductions inputFireReduction = new FireReductions(); // ignoring severity = zero parameters.FireReductionsTable[ln] = inputFireReduction; ReadValue(wred, currentLine); inputFireReduction.CoarseLitterReduction = wred.Value; ReadValue(lred, currentLine); inputFireReduction.FineLitterReduction = lred.Value; //ReadValue(som_red, currentLine); //inputFireReduction.SOMReduction = som_red.Value; CheckNoDataAfter("the " + lred.Name + " column", currentLine); GetNextLine(); } //--------- Read In Harvest Reductions Table --------------------------- InputVar<string> hreds = new InputVar<string>("HarvestReductions"); ReadName(Names.HarvestReductionParameters); PlugIn.ModelCore.UI.WriteLine(" Begin reading HARVEST REDUCTION parameters."); InputVar<string> prescriptionName = new InputVar<string>("Prescription"); InputVar<double> wred_pr = new InputVar<double>("Coarse Litter Reduction"); InputVar<double> lred_pr = new InputVar<double>("Fine Litter Reduction"); //InputVar<double> som_red_pr = new InputVar<double>("SOM Reduction"); InputVar<double> cohortw_red_pr = new InputVar<double>("Cohort Wood Removal"); InputVar<double> cohortl_red_pr = new InputVar<double>("Cohort Leaf Removal"); while (!AtEndOfInput) { StringReader currentLine = new StringReader(CurrentLine); HarvestReductions harvReduction = new HarvestReductions(); parameters.HarvestReductionsTable.Add(harvReduction); ReadValue(prescriptionName, currentLine); harvReduction.Name = prescriptionName.Value; ReadValue(wred_pr, currentLine); harvReduction.CoarseLitterReduction = wred_pr.Value; ReadValue(lred_pr, currentLine); harvReduction.FineLitterReduction = lred_pr.Value; ReadValue(cohortw_red_pr, currentLine); harvReduction.CohortWoodReduction = cohortw_red_pr.Value; ReadValue(cohortl_red_pr, currentLine); harvReduction.CohortLeafReduction = cohortl_red_pr.Value; GetNextLine(); } return parameters; } //--------------------------------------------------------------------- /// <summary> /// Reads a species name from the current line, and verifies the name. /// </summary> private ISpecies ReadSpecies(StringReader currentLine) { ReadValue(speciesName, currentLine); ISpecies species = PlugIn.ModelCore.Species[speciesName.Value.Actual]; if (species == null) throw new InputValueException(speciesName.Value.String, "{0} is not a species name.", speciesName.Value.String); int lineNumber; if (speciesLineNums.TryGetValue(species.Name, out lineNumber)) throw new InputValueException(speciesName.Value.String, "The species {0} was previously used on line {1}", speciesName.Value.String, lineNumber); else speciesLineNums[species.Name] = LineNumber; return species; } //--------------------------------------------------------------------- private IEcoregion GetEcoregion(InputValue<string> ecoregionName, Dictionary<string, int> lineNumbers) { IEcoregion ecoregion = PlugIn.ModelCore.Ecoregions[ecoregionName.Actual]; if (ecoregion == null) throw new InputValueException(ecoregionName.String, "{0} is not an ecoregion name.", ecoregionName.String); int lineNumber; if (lineNumbers.TryGetValue(ecoregion.Name, out lineNumber)) throw new InputValueException(ecoregionName.String, "The ecoregion {0} was previously used on line {1}", ecoregionName.String, lineNumber); else lineNumbers[ecoregion.Name] = LineNumber; return ecoregion; } //--------------------------------------------------------------------- /// <summary> /// Reads ecoregion names as column headings /// </summary> private List<IEcoregion> ReadEcoregions() { if (AtEndOfInput) throw NewParseException("Expected a line with the names of 1 or more active ecoregions."); InputVar<string> ecoregionName = new InputVar<string>("Ecoregion"); List<IEcoregion> ecoregions = new List<IEcoregion>(); StringReader currentLine = new StringReader(CurrentLine); TextReader.SkipWhitespace(currentLine); while (currentLine.Peek() != -1) { ReadValue(ecoregionName, currentLine); IEcoregion ecoregion = PlugIn.ModelCore.Ecoregions[ecoregionName.Value.Actual]; if (ecoregion == null) throw new InputValueException(ecoregionName.Value.String, "{0} is not an ecoregion name.", ecoregionName.Value.String); if (!ecoregion.Active) throw new InputValueException(ecoregionName.Value.String, "{0} is not an active ecoregion", ecoregionName.Value.String); if (ecoregions.Contains(ecoregion)) throw new InputValueException(ecoregionName.Value.String, "The ecoregion {0} appears more than once.", ecoregionName.Value.String); ecoregions.Add(ecoregion); TextReader.SkipWhitespace(currentLine); } GetNextLine(); if(ecoregions.Count == 0) throw new InputValueException("", "No ecoregions read in correctly.",""); return ecoregions; } private IEcoregion GetEcoregion(string ecoName) { IEcoregion ecoregion = PlugIn.ModelCore.Ecoregions[ecoName]; if (ecoregion == null) throw new InputValueException(ecoName, "{0} is not an ecoregion name.", ecoName); return ecoregion; } private ISpecies ReadSpecies(string speciesName) { ISpecies species = PlugIn.ModelCore.Species[speciesName.Trim()]; if (species == null) throw new InputValueException(speciesName, "{0} is not a species name.", speciesName); return species; } } }
using Microsoft.Diagnostics.Tracing.Analysis.GC; using Microsoft.Diagnostics.Tracing.Parsers.Clr; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Input; using System.Windows.Media; namespace PerfView { internal class GeometryBuilder { private StreamGeometry m_geometry; private StreamGeometryContext m_context; internal void AddRect(double x, double y, double w, double h) { if (m_geometry == null) { m_geometry = new StreamGeometry(); m_context = m_geometry.Open(); } m_context.BeginFigure(new Point(x, y), true, true); m_context.LineTo(new Point(x + w, y), false, true); m_context.LineTo(new Point(x + w, y + h), false, true); m_context.LineTo(new Point(x, y + h), false, true); } internal StreamGeometry Close() { if (m_context != null) { m_context.Close(); m_geometry.Freeze(); } return m_geometry; } } /// <summary> /// Class for combining multiple time intervals on the same horizontal bar /// </summary> internal class BarInterval { private double m_start; private double m_end; private Renderer m_render; private Brush m_brush; internal BarInterval(Renderer render, Brush brush) { m_start = -1; m_end = -1; m_render = render; m_brush = brush; } internal void Start(double start) { if (m_start < 0) // new interval { m_start = start; } else if (start > m_end) // disconnected with old one, draw old, start new { Draw(); m_start = start; m_end = -1; // may not close } // merge with old } internal void End(double end) { if (m_start > 0) // if opened { m_end = end; } } internal void Draw() { if (m_end > 0) // if closed { m_render.DrawBar(m_start, m_end, m_brush); } } } /// <summary> /// Renderer: WPF Visual generation /// </summary> internal class Renderer { private const double minWidth = 0.1; // min GC bar width private const double margin = 5; private int m_width; private int m_height; private int m_xAxis, m_yAxis; private DrawingVisual m_visual; private DrawingContext m_context; private double m_x0; private double m_x1; private double m_gcHeight; private Typeface m_arial; public void SetTimeScale(double start, double end, out double x0, out double x1, bool drawTick) { double duration = end - start; start -= duration / 50; // Add 2% before first event end += duration / 50; // Add 2% after last event m_x0 = -start; m_x1 = (m_width - m_xAxis - 5) / (end - start); // screen = (t + m_x0) * m_x1 + m_xAxis; x0 = m_x0 * m_x1 + m_xAxis; x1 = m_x1; end /= 100; // in 100 ms m_arial = new Typeface("arial"); if (!drawTick) { return; } double oneSecond = MapXDelta(1000); int size10 = 9; int size1 = 0; int size01 = 0; if (oneSecond >= 100) { size10 = 13; size1 = 11; size01 = 9; } else if (oneSecond >= 20) { size10 = 11; size1 = 9; } // second marks for (int t = (int)(start / 100); t < end; t++) { double x = MapX(t * 100); if (x >= m_xAxis) { if ((t % 100) == 0) // 10 seconds { m_context.DrawRectangle(Brushes.Black, null, new Rect(x - 1, m_yAxis, 2, 8)); DrawText(x - 5, m_yAxis + 10, (t / 10).ToString(), size10); } else if ((t % 10) == 0) // 1 second { m_context.DrawRectangle(Brushes.Black, null, new Rect(x - 0.5, m_yAxis, 1, 6)); if (size1 != 0) { DrawText(x - 5, m_yAxis + 8, (t / 10).ToString(), size1); } } else if (size01 != 0) // 100 ms { m_context.DrawRectangle(Brushes.Black, null, new Rect(x - 0.5, m_yAxis, 1, 4)); } } } } private Pen m_blackPen; private Brush m_black; private Brush m_red; private Brush m_yellow; private Brush m_blue25; private ColorScheme m_g0Palette; private ColorScheme m_g1Palette; private ColorScheme m_g2Palette; private ColorScheme m_gLPalette; private ColorScheme m_gTPalette; private ColorScheme[] m_Palettes; public void Open(int width, int height, bool allocTick) { m_black = Brushes.Black; m_red = Brushes.Red; m_yellow = Brushes.Yellow; m_blue25 = new SolidColorBrush(Color.FromArgb(63, 0, 0, 255)); m_g0Palette = new ColorScheme("Gen0", 60, 238, 111); // RGB(118,235,1) m_g1Palette = new ColorScheme("Gen1", 40, 238, 111); // RGB(235,235,1) m_g2Palette = new ColorScheme("Gen2", 20, 238, 111); // RGB(235,118,1) m_gLPalette = new ColorScheme("Loh", 0, 238, 111); // RGB(235, 1,1) m_gTPalette = new ColorScheme("Total", Colors.Black, Colors.Black, Colors.Black); m_Palettes = new ColorScheme[] { m_g0Palette, m_g1Palette, m_g2Palette, m_gLPalette, m_gTPalette }; m_width = width; m_height = height; m_visual = new DrawingVisual(); m_blackPen = new Pen(Brushes.Black, 1); m_xAxis = 48; m_yAxis = height - 20; if (allocTick) { m_yAxis -= 200; } m_gcHeight = m_yAxis - margin; m_context = m_visual.RenderOpen(); DrawRect(Brushes.WhiteSmoke, 0, 0, width, height); } private double MapX(double t) { return (t + m_x0) * m_x1 + m_xAxis; } private double MapXDelta(double t) { return t * m_x1; } private void DrawRect(Brush b, double x, double y, double width, double height) { if ((width > 0) && (height > 0)) { m_context.DrawRectangle(b, null, new Rect(x, y, width, height)); } } // G0/G3 budget // GC start/end eventd public void DrawGCEvent(double start, double end, int gen, double lastEnd, double g0Budget, double g3Budget, double gcCpu, bool induced, GeometryBuilder[] gcBarList) { start = MapX(start); end = MapX(end); if (lastEnd > 0) { double x = MapX(lastEnd); if (start >= (x + 1)) // Width at least 1 pixel in 96 dpi { double y; if (!Double.IsNaN(g0Budget) && (g0Budget > m_yPixel)) { y = MapY(g0Budget); DrawRect(m_g0Palette.budgetBrush, x, y, start - x, m_yAxis - y); } if (!Double.IsNaN(g3Budget) && (g3Budget > m_yPixel)) { y = MapY(g3Budget); DrawRect(m_gLPalette.budgetBrush, x, y, start - x, m_yAxis - y); } } } if (induced) { gen += 3; } if (gcBarList[gen] == null) { gcBarList[gen] = new GeometryBuilder(); } gcBarList[gen].AddRect(start, m_yAxis - m_gcHeight, Math.Max(minWidth, end - start), m_gcHeight); // DrawRect( // induced ? m_Palettes[gen].inducedGcBrush : m_Palettes[gen].gcBrush, // start, m_yAxis - m_gcHeight, Math.Max(minWidth, end - start), m_gcHeight); if (gcCpu > 0) { //DrawRect(Brushes.Black, start, m_yAxis - 100, MapXDelta(gcCpu), 20); } } internal void DrawGeometry(StreamGeometry geo, int gen) { m_context.DrawGeometry(gen >= 3 ? m_Palettes[gen - 3].inducedGcBrush : m_Palettes[gen].gcBrush, null, geo); } private double m_maxHeap; private Pen m_thinBlack; private double m_y0, m_y1, m_yPixel; public void SetMemoryScale(double maxHeap) { m_maxHeap = maxHeap; m_y0 = m_yAxis; m_y1 = -(m_yAxis - margin) / m_maxHeap; m_yPixel = Math.Abs(1 / m_y1); if (m_thinBlack == null) { m_thinBlack = new Pen(Brushes.Black, 0.1); } int unit = 1; if (m_maxHeap >= 2500) { unit = 500; } else if (m_maxHeap >= 500) { unit = 100; } else if (m_maxHeap >= 250) { unit = 50; } else if (m_maxHeap >= 50) { unit = 10; } else if (m_maxHeap >= 25) { unit = 5; } for (int y = unit; y < m_maxHeap; y += unit) { m_context.DrawRectangle(Brushes.Black, null, new Rect(m_xAxis - 8, MapY(y) - 0.5, 8, 1)); m_context.DrawLine( (y % (unit * 5)) == 0 ? m_blackPen : m_thinBlack, new Point(m_xAxis, MapY(y)), new Point(m_width - margin, MapY(y))); string lable = y.ToString(); DrawText(m_xAxis - 20 - lable.Length * 5, MapY(y) - 5, lable); } } private void DrawText(double x, double y, string text, double size = 9) { m_context.DrawText(new FormattedText(text, Thread.CurrentThread.CurrentCulture, FlowDirection.LeftToRight, m_arial, size, Brushes.Black), new Point(x, y)); } private double MapY(double y) { return m_y0 + y * m_y1; } private static double Diff(Point p0, Point p1) { return Math.Abs(p0.X - p1.X) + Math.Abs(p0.Y - p1.Y); } // x y0 y1 y2 ... public void DrawLines(List<double> line, int yCount, string[] curveLabels = null) { int stride = yCount + 1; List<Tuple<Point, string, Pen>> labels = new List<Tuple<Point, string, Pen>>(); // Draw the lines one by one for (int j = 0; j < yCount; j++) { StreamGeometry geometry = new StreamGeometry(); StreamGeometryContext ctx = geometry.Open(); Point p = new Point(); Point p0 = new Point(); double alloc = 0; for (int i = 0; i < line.Count; i += stride) { p = new Point(MapX(line[i]), MapY(alloc = line[i + 1 + j])); if (i == 0) { ctx.BeginFigure(p, false, false); p0 = p; } else { if (Diff(p, p0) >= 0.1) // 1 pixel in 960 dpi { ctx.LineTo(p, true, true); p0 = p; } } } ctx.Close(); ColorScheme pal = m_Palettes[j]; geometry.Freeze(); m_context.DrawGeometry(null, curveLabels == null ? pal.memoryPen2 : pal.memoryPen1, geometry); labels.Add(new Tuple<Point, string, Pen>( p, String.Format("{0} {1:N3} mb", curveLabels == null ? pal.label : curveLabels[j], alloc), pal.memoryPen2)); } double y = m_yAxis - 8; foreach (var v in labels.OrderByDescending(v => v.Item1.Y)) { if (v.Item1.Y < y) { y = v.Item1.Y; } m_context.DrawLine(v.Item3, new Point(v.Item1.X + 3, v.Item1.Y), new Point(v.Item1.X + 8, y)); DrawText(v.Item1.X + 10, y - 5, v.Item2, 10); y -= 10; } } public void DrawAlloc(int y, double alloc, double ratio, string key, string method) { int yy = m_yAxis + 20 + y * 9; DrawRect(m_Palettes[y % 4].budgetBrush, m_xAxis, yy, MapY(0) - MapY(alloc), 10); DrawText(m_xAxis + 5, yy, ratio.ToString("N1") + "% " + alloc.ToString("N3") + " mb"); DrawText(m_xAxis + 200, yy, key + " " + method); } public void DrawMarkers(int y, List<HeapEventData> events) { int count = events.Count; Brush brush1 = Brushes.Blue; Brush brush2 = Brushes.Brown; for (int i = 0; i < count; i++) { HeapEventData data = events[i]; double t = data.m_time; if (t < m_barT0) { continue; } if (t > m_barT1) { break; } if ((data.m_event >= HeapEvents.GCMarkerFirst) && (data.m_event <= HeapEvents.GCMarkerLast)) { DrawRect(brush1, MapX(t), y - 1, 1, 10); } else if ((data.m_event >= HeapEvents.BGCMarkerFirst) && (data.m_event <= HeapEvents.BGCMarkerLast)) { DrawRect(brush2, MapX(t), y - 1, 1, 10); } } } private double m_barY; private double m_barH; private double m_barT0; private double m_barT1; /// <summary> /// Set horizontal bar region /// </summary> /// <param name="h">height</param> /// <param name="t0">minimum time stamp</param> /// <param name="t1">maximum time stamp</param> public void SetBarRegion(double h, double t0, double t1) { m_barY = 0; m_barH = h; m_barT0 = t0; m_barT1 = t1; } public void DrawBar(double start, double end, Brush brush) { if ((start < m_barT1) && (end > m_barT0)) { DrawRect(brush, MapX(start), m_barY, MapXDelta(end - start), m_barH); } } public void DrawThread(int y, ThreadMemoryInfo thread, bool drawLegend, bool drawMarker) { List<HeapEventData> events = thread.m_events; int count = events.Count; m_barY = y; if (count > 1) { double start = events[0].m_time; double end = events[count - 1].m_time; if (drawLegend) { string name = thread.Name; if (!String.IsNullOrEmpty(name)) { if (name.StartsWith(".Net ", StringComparison.OrdinalIgnoreCase)) { name = name.Substring(5); } } DrawText(5, y + 8, String.Format("{0}, {1}, {2} ms", thread.ThreadID, name, thread.CpuSample), 9); return; } if ((start > m_barT1) || (end < m_barT0)) { return; } if (end > m_barT1) { end = m_barT1; } DrawText(MapX(end) + 5, y, String.Format("Thread {0}, {1}, {2} ms", thread.ThreadID, thread.Name, thread.CpuSample), 8); DrawRect(m_blue25, MapX(start), y, MapXDelta(end - start), m_barH); BarInterval cpuSample = new BarInterval(this, Brushes.Black); BarInterval contention = new BarInterval(this, Brushes.Red); BarInterval waitBgc = new BarInterval(this, Brushes.Yellow); double half = thread.SampleInterval / 2; for (int i = 0; i < count; i++) { HeapEventData evt = events[i]; double tick = evt.m_time; switch (evt.m_event) { case HeapEvents.CPUSample: cpuSample.Start(tick - half); cpuSample.End(tick + half); break; case HeapEvents.ContentionStart: contention.Start(tick); break; case HeapEvents.ContentionStop: contention.End(tick); break; case HeapEvents.BGCAllocWaitStart: waitBgc.Start(tick); break; case HeapEvents.BGCAllocWaitStop: waitBgc.End(tick); break; default: break; } } cpuSample.Draw(); contention.Draw(); waitBgc.Draw(); if (drawMarker) { DrawMarkers(y, events); } } } public Visual CloseDiagram(bool drawAxis) { if (m_context != null) { if (drawAxis) { m_context.DrawLine(m_blackPen, new Point(m_xAxis, m_yAxis), new Point(m_xAxis, margin)); m_context.DrawLine(m_blackPen, new Point(m_xAxis, m_yAxis), new Point(m_width - margin, m_yAxis)); } m_context.Close(); m_context = null; } return m_visual; } } /// <summary> /// Diagram generation /// </summary> internal class HeapDiagramGenerator { private static double CheckMax(ref double max, double value) { if (value > max) { max = value; } return value; } private DiagramData m_data; private double m_t0; private double m_t1; public void RenderDiagram(int width, int height, DiagramData data) { m_data = data; Renderer render = new Renderer(); render.Open(width, height, m_data.drawAllocTicks); m_t0 = m_data.startTime; m_t1 = m_data.endTime; render.SetTimeScale(m_t0, m_t1, out data.x0, out data.x1, data.drawGCEvents); if (data.drawGCEvents) { SetYScale(render); // GC events as vertical bars + heap size curves DrawGCEvents(render); } if (m_data.drawAllocTicks) { DrawAllocation(render); } if (m_data.drawThreadCount != 0) { DrawThreads(render); } data.visual = render.CloseDiagram(data.drawGCEvents); } private void SetYScale(Renderer render) { double maxHeap = m_data.vmMaxVM; foreach (TraceGC gc in m_data.events) { double g0 = gc.GenSizeBeforeMB[(int)Gens.Gen0]; double g1 = gc.GenSizeBeforeMB[(int)Gens.Gen1]; double g2 = gc.GenSizeBeforeMB[(int)Gens.Gen2]; double g3 = gc.GenSizeBeforeMB[(int)Gens.GenLargeObj]; CheckMax(ref maxHeap, g0 + g1 + g2 + g3); } render.SetMemoryScale(maxHeap); } // GC event marks + // Heap size curves private void DrawGCEvents(Renderer render) { List<double> sizeCurves = new List<double>((m_data.events.Count * 2 + 1) * 6); // Process start, no managed heap sizeCurves.Add(0); sizeCurves.Add(0); sizeCurves.Add(0); sizeCurves.Add(0); sizeCurves.Add(0); sizeCurves.Add(0); double lastEnd = 0; GeometryBuilder[] gcBarList = new GeometryBuilder[6]; foreach (TraceGC gc in m_data.events) { double start = gc.PauseStartRelativeMSec; double end = gc.PauseStartRelativeMSec + gc.PauseDurationMSec; if (end < m_t0) { continue; } if (start > m_t1) { break; } int gen = gc.Generation; double gcTime = gc.GetTotalGCTime(); render.DrawGCEvent( start, end, gen, lastEnd, gc.GenBudgetMB(Gens.Gen0), gc.GenBudgetMB(Gens.GenLargeObj), gcTime, gc.IsInduced(), gcBarList); // double smallAloc = gc.AllocedSinceLastGCBasedOnAllocTickMB[0]; // double largeAlloc = gc.AllocedSinceLastGCBasedOnAllocTickMB[1]; double g0 = gc.GenSizeBeforeMB[(int)Gens.Gen0]; double g1 = gc.GenSizeBeforeMB[(int)Gens.Gen1]; double g2 = gc.GenSizeBeforeMB[(int)Gens.Gen2]; double g3 = gc.GenSizeBeforeMB[(int)Gens.GenLargeObj]; sizeCurves.Add(start); sizeCurves.Add(g0); sizeCurves.Add(g1); sizeCurves.Add(g2); sizeCurves.Add(g3); sizeCurves.Add(g0 + g1 + g2 + g3); if (gc.HeapStats != null) // May not be complete, no HeapStats, assuming the same { g0 = gc.GenSizeAfterMB(Gens.Gen0); g1 = gc.GenSizeAfterMB(Gens.Gen1); g2 = gc.GenSizeAfterMB(Gens.Gen2); g3 = gc.GenSizeAfterMB(Gens.GenLargeObj); } sizeCurves.Add(end); sizeCurves.Add(g0); sizeCurves.Add(g1); sizeCurves.Add(g2); sizeCurves.Add(g3); sizeCurves.Add(g0 + g1 + g2 + g3); lastEnd = end; } for (int g = 0; g < 6; g++) { if (gcBarList[g] != null) { StreamGeometry geo = gcBarList[g].Close(); render.DrawGeometry(geo, g); } } render.DrawLines(sizeCurves, 5); if (m_data.vmCurve != null) { string[] labels = new string[] { "CLR VMC", "+ Graphics VMC", m_data.wwaHost? "+ Jscript VMC" : "+ Xaml VMC", "Total VMC" }; render.DrawLines(m_data.vmCurve, 4, labels); } } private void DrawThreads(Renderer render) { double totalSample = 0; foreach (ThreadMemoryInfo thread in m_data.threads.Values) { totalSample += thread.CpuSample; } double cutoff = totalSample / 1000; // 0.1 percent int y = 0; render.SetBarRegion(8, m_t0, m_t1); foreach (ThreadMemoryInfo thread in m_data.threads.Values.OrderBy(e => e, new ThreadMemoryInfoComparer())) { if (thread.CpuSample >= cutoff) { render.DrawThread(y * 10 + 5, thread, m_data.drawLegend, m_data.drawMarker); y++; if (y >= m_data.drawThreadCount) { break; } } } } public void DrawAllocation(Renderer render) { double total = 0; for (int i = 0; i < m_data.allocsites.Count; i++) { total += m_data.allocsites[i].Alloc; } double onePercent = total / 100; double other = 0; int y = 0; for (int i = 0; i < m_data.allocsites.Count; i++) { double alloc = m_data.allocsites[i].Alloc; if (alloc >= onePercent) { AllocTick key = m_data.allocsites[i]; string method = m_data.dataFile.GetMethodName(key.m_caller1); render.DrawAlloc(y, alloc, alloc * 100 / total, key.m_type, method); y++; } else { other += alloc; } } render.DrawAlloc(y, other, other * 100 / total, "Other", String.Empty); } } /// <summary> /// Metric for Metrics DataGrid /// </summary> public class Metric { private object m_value; private string m_format; public string Name { get; set; } public object Value { get { if ((m_value != null) && (m_value is double)) { return String.Format(m_format, m_value); } return m_value; } } public Metric(string name, object val, string format = null) { Name = name; m_value = val; m_format = format; } } /// <summary> /// HeapDiagram Panel /// </summary> public class HeapDiagram { private int TopPanelHeight = 31; private int LeftPanelWidth = 240; private int LegendWidth = 88; private PerfViewFile m_dataFile; private Window m_parent; private ProcessMemoryInfo m_heapInfo; private StatusBar m_statusBar; private List<Metric> m_metrics; public HeapDiagram(PerfViewFile dataFile, StatusBar status, Window parent) { m_dataFile = dataFile; m_statusBar = status; m_parent = parent; } private DockPanel m_topPanel; private DockPanel m_leftPanel; private CheckBox m_timeline; private CheckBox m_drawMarker; private ScrollViewer m_scrollViewer; private Label m_zoomLabel, m_posLabel; private VisualHolder m_diagramHolder; private Slider m_zoomSlider; // Button m_testButton; private Button m_cropButton; private Button m_undoButton; private int m_graphWidth = 80 * 11; private int m_graphHeight = 80 * 5; private double m_widthZoom = 1; private RubberBandAdorner m_rubberBand; private double m_diagramT0; private double m_diagramT1; private void RedrawDiagram() { int zoomWidth = (int)(m_graphWidth * m_widthZoom); Stopwatch watch = new Stopwatch(); watch.Start(); int threadCount = 0; if (m_timeline.IsChecked == true) { threadCount = 30; } DiagramData data = m_heapInfo.RenderDiagram(zoomWidth, m_graphHeight, m_diagramT0, m_diagramT1, true, threadCount, m_drawMarker.IsChecked == true, false); if (m_rubberBand != null) { m_rubberBand.Detach(); } m_diagramHolder = new VisualHolder(); m_rubberBand = new RubberBandAdorner(m_diagramHolder, m_diagramHolder.AddMessage, CreateContextMenu); m_diagramHolder.SetVisual(zoomWidth, m_graphHeight, data.visual, m_widthZoom, m_zoomSlider.Value, data.x0, data.x1); m_scrollViewer.Content = m_diagramHolder; m_scrollViewer.MouseMove += OnMouseMove; { DiagramData legend = m_heapInfo.RenderLegend(LegendWidth, m_graphHeight, threadCount); VisualHolder legendHolder = new VisualHolder(); legendHolder.SetVisual(LegendWidth, m_graphHeight, legend.visual, 1, 1, legend.x0, legend.x1); m_leftLegend.Children.Clear(); m_leftLegend.Children.Add(legendHolder); } watch.Stop(); m_statusBar.Log(String.Format("RadrawDiagram({0:N3} {1:N3}, {2}x{3} {4:N3} ms", m_diagramT0, m_diagramT1, zoomWidth, m_graphHeight, watch.Elapsed.TotalMilliseconds)); } private void SetZoom(double zoom) { m_zoomLabel.Content = String.Format("x {0:N3}", zoom); m_widthZoom = zoom; RedrawDiagram(); } private void ZoomValueChanged(object sender, RoutedPropertyChangedEventArgs<double> value) { SetZoom(value.NewValue); } private void ToggleTimeline(object sender, RoutedEventArgs e) { RedrawDiagram(); m_drawMarker.IsEnabled = m_timeline.IsChecked == true; } private void ToggleDrawMarker(object sender, RoutedEventArgs e) { RedrawDiagram(); } private int FindEvent(double tick, int start) { for (int i = start; i < m_heapInfo.GcEvents.Count; i++) { TraceGC gc = m_heapInfo.GcEvents[i]; if (tick >= gc.PauseStartRelativeMSec) { if (tick < gc.PauseStartRelativeMSec + gc.PauseDurationMSec) { return i; } } else { break; } } return -1; } private int m_lastEvent; private void OnMouseMove(object sender, MouseEventArgs e) { if (!m_scrollViewer.IsMouseCaptured) { Point p = e.GetPosition(m_diagramHolder); double t = m_diagramHolder.GetValueX(p.X); int g1 = FindEvent(t, 0); if (g1 >= 0) { int g2 = FindEvent(t, g1 + 1); // Over have overlapping GCs if ((g1 + g2) != m_lastEvent) { string message = m_heapInfo.GcEvents[g1].GetTip(); if (g2 >= 0) { message = message + "\r\n" + m_heapInfo.GcEvents[g2].GetTip(); } m_tip.Content = message; m_tip.PlacementTarget = m_scrollViewer; m_tip.Placement = PlacementMode.Relative; } p = e.GetPosition(m_scrollViewer); m_tip.IsOpen = true; m_tip.HorizontalOffset = p.X + 11; m_tip.VerticalOffset = p.Y + 18; m_lastEvent = g1 + g2; } else { m_tip.IsOpen = false; } string tip = String.Format("{0:N3} ms", t); m_posLabel.Content = tip; } } private bool m_allowResize; private void OnSizeChange(object sender, SizeChangedEventArgs e) { if (m_allowResize) { // m_testButton.Content = e.NewSize; // String.Format("{0} x {1} ", width, height); int width = (int)Math.Round(e.NewSize.Width) - 32; int height = (int)Math.Round(e.NewSize.Height) - 32; if ((width != m_graphWidth) || (height != m_graphHeight)) { if ((width > 0) && (height > 0)) { m_graphWidth = width; m_graphHeight = height; RedrawDiagram(); } } } } private ToolTip m_tip; private DataGrid m_metricGrid; private StackPanel m_leftLegend; private const double MaxZoom = 100; internal Panel CreateHeapDiagramPanel(TextBox helpBox) { // Top: controls m_topPanel = new DockPanel(); { m_topPanel.Height = TopPanelHeight; m_topPanel.Background = Brushes.LightGray; m_topPanel.DockLeft(m_timeline = Toolbox.CreateCheckBox(false, "Timeline", 10, 5, ToggleTimeline)); m_timeline.ToolTip = "Overlay thread time line."; m_topPanel.DockLeft(m_drawMarker = Toolbox.CreateCheckBox(false, "Marker", 10, 5, ToggleDrawMarker)); m_drawMarker.ToolTip = "Overlay GC marking events on thread time line."; m_drawMarker.IsEnabled = false; m_zoomSlider = new Slider(); m_zoomSlider.Margin = new Thickness(10, 2, 10, 2); m_zoomSlider.Minimum = 1; m_zoomSlider.Maximum = MaxZoom; m_zoomSlider.Value = 1; m_zoomSlider.Width = 200; m_zoomSlider.Ticks = new DoubleCollection(new double[] { 1, 2, 4, 8, 10, 16, 32, 50, 64, MaxZoom }); m_zoomSlider.TickPlacement = TickPlacement.BottomRight; m_zoomSlider.ValueChanged += ZoomValueChanged; m_zoomSlider.ToolTip = "Change time axis zoom ratio."; m_topPanel.DockLeft(m_zoomSlider); m_zoomLabel = new Label(); m_zoomLabel.Content = "x 1"; m_zoomLabel.Margin = new Thickness(10, 5, 10, 5); m_topPanel.DockLeft(m_zoomLabel); m_posLabel = new Label(); m_topPanel.DockLeft(m_posLabel); // m_testButton = Toolbox.CreateButton("Test", 50, OnTest, 5, 5); // m_topPanel.DockLeft(m_testButton); m_cropButton = Toolbox.CreateButton("Crop", 38, OnCropDiagram, 5, 5); m_cropButton.ToolTip = "Crop diagram to current displayed time range."; m_undoButton = Toolbox.CreateButton("Undo", 38, OnUndoCrop, 5, 5); m_undoButton.ToolTip = "Restore last time range."; m_undoButton.IsEnabled = false; m_topPanel.DockRight(m_undoButton); m_topPanel.DockRight(m_cropButton); } // Left: DataGrid with Metrics, helpBox m_leftPanel = new DockPanel(); { m_leftPanel.Width = LeftPanelWidth; m_leftPanel.Background = Brushes.LightGray; m_metricGrid = new DataGrid(); m_metricGrid.Background = Brushes.LightGray; m_metricGrid.AutoGenerateColumns = false; m_metricGrid.IsReadOnly = true; m_metricGrid.AddColumn("Metric", "Name", false); m_metricGrid.AddColumn("Value", "Value", true); m_leftLegend = new StackPanel(); m_leftLegend.Width = LegendWidth; m_leftPanel.DockRight(m_leftLegend); m_leftPanel.DockTop(m_metricGrid); m_leftPanel.DockTop(helpBox); } // Bottom-right: ScrollViewer with diagram m_scrollViewer = new ScrollViewer(); { m_scrollViewer.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto; m_scrollViewer.VerticalScrollBarVisibility = ScrollBarVisibility.Auto; m_scrollViewer.SizeChanged += OnSizeChange; m_tip = new ToolTip(); m_scrollViewer.ToolTip = m_tip; ToolTipService.SetInitialShowDelay(m_scrollViewer, 500); ToolTipService.SetShowDuration(m_scrollViewer, 1000); } DockPanel heapDiagram = Toolbox.DockTopLeft(m_topPanel, m_leftPanel, m_scrollViewer); return heapDiagram; } internal void SetData(ProcessMemoryInfo heapInfo) { m_heapInfo = heapInfo; m_diagramT0 = m_heapInfo.FirstEventTime; m_diagramT1 = m_heapInfo.LastEventTime; RedrawDiagram(); m_metrics = m_heapInfo.GetMetrics(); m_metricGrid.ItemsSource = m_metrics; m_allowResize = true; } private MenuItem m_zoomTo; private double m_rangeT0; private double m_rangeT1; /// <summary> /// Zoom to time range /// </summary> private void OnZoomTo(object sender, RoutedEventArgs e) { double range = Math.Abs(m_rangeT0 - m_rangeT1); if (range >= 0.1) // 0.1 ms { double t0 = m_diagramHolder.GetValueX(0); // Real start time displayed double t1 = m_diagramHolder.GetValueX(m_diagramHolder.Width); // Real end time displayed double whole = t1 - t0; // whole time range double zoom = whole / range; // Ratio if (zoom >= MaxZoom) // Limit at MaxZoom { zoom = MaxZoom; } range = whole / zoom; // Limited range double T0 = (m_rangeT0 + m_rangeT1) / 2 - range / 2; // Adjusted t0 to display m_zoomSlider.Value = zoom; // Update zoom double offset = (T0 - t0) / whole * zoom * m_graphWidth; // Scroll offset m_statusBar.Status = String.Format("ZoomTo({0:N3} .. {1:N3})", m_rangeT0, m_rangeT1); m_scrollViewer.ScrollToHorizontalOffset(offset); } } private StackWindowHook m_cpuStack; private StackWindowHook m_allocStack; private StackWindowHook m_vmallocStack; /// <summary> /// Create/update ContextMenu for RubbeerBand adorner /// </summary> private bool CreateContextMenu(ContextMenu cm, Point start, Point end) { m_rangeT0 = m_diagramHolder.GetValueX(start.X); m_rangeT1 = m_diagramHolder.GetValueX(end.X); if (cm.Items.Count == 0) { m_zoomTo = new MenuItem(); m_zoomTo.Click += OnZoomTo; cm.Items.Add(m_zoomTo); } m_zoomTo.Header = String.Format("Zoom to [{0:N3} ms .. {1:N3} ms]", m_rangeT0, m_rangeT1); if (m_cpuStack == null) { m_cpuStack = new StackWindowHook(m_dataFile, m_heapInfo.ProcessID, m_statusBar, "CPU", m_parent); m_allocStack = new StackWindowHook(m_dataFile, m_heapInfo.ProcessID, m_statusBar, "GC Heap Alloc Ignore Free (Coarse Sampling)", m_parent); if (m_heapInfo.HasVmAlloc) { m_vmallocStack = new StackWindowHook(m_dataFile, m_heapInfo.ProcessID, m_statusBar, "Net Virtual Alloc", m_parent); } } m_cpuStack.AttachMenu(cm, m_rangeT0, m_rangeT1); m_allocStack.AttachMenu(cm, m_rangeT0, m_rangeT1); if (m_heapInfo.HasVmAlloc) { m_vmallocStack.AttachMenu(cm, m_rangeT0, m_rangeT1); } return true; } private class DiagramPara { internal double scrollOffset; internal double t0; internal double t1; internal double zoom; } private Stack<DiagramPara> m_cropList = new Stack<DiagramPara>(); /// <summary> /// Crop diagram to displayed time range, for performance, bigger zoom range /// </summary> private void OnCropDiagram(object sender, RoutedEventArgs e) { DiagramPara para = new DiagramPara(); para.scrollOffset = m_scrollViewer.HorizontalOffset; para.zoom = m_zoomSlider.Value; para.t0 = m_diagramT0; para.t1 = m_diagramT1; m_cropList.Push(para); if (m_cropList.Count == 1) { m_undoButton.IsEnabled = true; } m_diagramT0 = m_diagramHolder.GetValueX(para.scrollOffset); // Real start time displayed m_diagramT1 = m_diagramHolder.GetValueX(para.scrollOffset + m_diagramHolder.Width / para.zoom); // Real end time displayed m_zoomSlider.Value = 1; // Update zoom to 1 m_scrollViewer.ScrollToHorizontalOffset(0); m_statusBar.Status = String.Format("CropTo({0:N3} .. {1:N3})", m_diagramT0, m_diagramT1); } /// <summary> /// Undo Crop /// </summary> private void OnUndoCrop(object sender, RoutedEventArgs e) { if (m_cropList.Count != 0) { DiagramPara para = m_cropList.Pop(); m_diagramT0 = para.t0; m_diagramT1 = para.t1; m_zoomSlider.Value = para.zoom; m_scrollViewer.ScrollToHorizontalOffset(para.scrollOffset); } if (m_cropList.Count == 0) { m_undoButton.IsEnabled = false; } } private void OnTest(object sender, RoutedEventArgs e) { } } }
// 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.Diagnostics; using System.Globalization; using System.IO; using System.Text.Encodings.Web; namespace Microsoft.AspNetCore.Html { /// <summary> /// Extension methods for <see cref="IHtmlContentBuilder"/>. /// </summary> public static class HtmlContentBuilderExtensions { /// <summary> /// Appends the specified <paramref name="format"/> to the existing content after replacing each format /// item with the HTML encoded <see cref="string"/> representation of the corresponding item in the /// <paramref name="args"/> array. /// </summary> /// <param name="builder">The <see cref="IHtmlContentBuilder"/>.</param> /// <param name="format"> /// The composite format <see cref="string"/> (see http://msdn.microsoft.com/en-us/library/txafckwd.aspx). /// The format string is assumed to be HTML encoded as-provided, and no further encoding will be performed. /// </param> /// <param name="args"> /// The object array to format. Each element in the array will be formatted and then HTML encoded. /// </param> /// <returns>A reference to this instance after the append operation has completed.</returns> public static IHtmlContentBuilder AppendFormat( this IHtmlContentBuilder builder, string format, params object?[] args) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } if (format == null) { throw new ArgumentNullException(nameof(format)); } if (args == null) { throw new ArgumentNullException(nameof(args)); } builder.AppendHtml(new HtmlFormattableString(format, args)); return builder; } /// <summary> /// Appends the specified <paramref name="format"/> to the existing content with information from the /// <paramref name="formatProvider"/> after replacing each format item with the HTML encoded /// <see cref="string"/> representation of the corresponding item in the <paramref name="args"/> array. /// </summary> /// <param name="builder">The <see cref="IHtmlContentBuilder"/>.</param> /// <param name="formatProvider">An object that supplies culture-specific formatting information.</param> /// <param name="format"> /// The composite format <see cref="string"/> (see http://msdn.microsoft.com/en-us/library/txafckwd.aspx). /// The format string is assumed to be HTML encoded as-provided, and no further encoding will be performed. /// </param> /// <param name="args"> /// The object array to format. Each element in the array will be formatted and then HTML encoded. /// </param> /// <returns>A reference to this instance after the append operation has completed.</returns> public static IHtmlContentBuilder AppendFormat( this IHtmlContentBuilder builder, IFormatProvider formatProvider, string format, params object?[] args) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } if (format == null) { throw new ArgumentNullException(nameof(format)); } if (args == null) { throw new ArgumentNullException(nameof(args)); } builder.AppendHtml(new HtmlFormattableString(formatProvider, format, args)); return builder; } /// <summary> /// Appends an <see cref="Environment.NewLine"/>. /// </summary> /// <param name="builder">The <see cref="IHtmlContentBuilder"/>.</param> /// <returns>The <see cref="IHtmlContentBuilder"/>.</returns> public static IHtmlContentBuilder AppendLine(this IHtmlContentBuilder builder) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } builder.AppendHtml(HtmlString.NewLine); return builder; } /// <summary> /// Appends an <see cref="Environment.NewLine"/> after appending the <see cref="string"/> value. /// The value is treated as unencoded as-provided, and will be HTML encoded before writing to output. /// </summary> /// <param name="builder">The <see cref="IHtmlContentBuilder"/>.</param> /// <param name="unencoded">The <see cref="string"/> to append.</param> /// <returns>The <see cref="IHtmlContentBuilder"/>.</returns> public static IHtmlContentBuilder AppendLine(this IHtmlContentBuilder builder, string unencoded) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } builder.Append(unencoded); builder.AppendHtml(HtmlString.NewLine); return builder; } /// <summary> /// Appends an <see cref="Environment.NewLine"/> after appending the <see cref="IHtmlContent"/> value. /// </summary> /// <param name="builder">The <see cref="IHtmlContentBuilder"/>.</param> /// <param name="content">The <see cref="IHtmlContent"/> to append.</param> /// <returns>The <see cref="IHtmlContentBuilder"/>.</returns> public static IHtmlContentBuilder AppendLine(this IHtmlContentBuilder builder, IHtmlContent content) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } builder.AppendHtml(content); builder.AppendHtml(HtmlString.NewLine); return builder; } /// <summary> /// Appends an <see cref="Environment.NewLine"/> after appending the <see cref="string"/> value. /// The value is treated as HTML encoded as-provided, and no further encoding will be performed. /// </summary> /// <param name="builder">The <see cref="IHtmlContentBuilder"/>.</param> /// <param name="encoded">The HTML encoded <see cref="string"/> to append.</param> /// <returns>The <see cref="IHtmlContentBuilder"/>.</returns> public static IHtmlContentBuilder AppendHtmlLine(this IHtmlContentBuilder builder, string encoded) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } builder.AppendHtml(encoded); builder.AppendHtml(HtmlString.NewLine); return builder; } /// <summary> /// Sets the content to the <see cref="string"/> value. The value is treated as unencoded as-provided, /// and will be HTML encoded before writing to output. /// </summary> /// <param name="builder">The <see cref="IHtmlContentBuilder"/>.</param> /// <param name="unencoded">The <see cref="string"/> value that replaces the content.</param> /// <returns>The <see cref="IHtmlContentBuilder"/>.</returns> public static IHtmlContentBuilder SetContent(this IHtmlContentBuilder builder, string unencoded) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } builder.Clear(); builder.Append(unencoded); return builder; } /// <summary> /// Sets the content to the <see cref="IHtmlContent"/> value. /// </summary> /// <param name="builder">The <see cref="IHtmlContentBuilder"/>.</param> /// <param name="content">The <see cref="IHtmlContent"/> value that replaces the content.</param> /// <returns>The <see cref="IHtmlContentBuilder"/>.</returns> public static IHtmlContentBuilder SetHtmlContent(this IHtmlContentBuilder builder, IHtmlContent content) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } builder.Clear(); builder.AppendHtml(content); return builder; } /// <summary> /// Sets the content to the <see cref="string"/> value. The value is treated as HTML encoded as-provided, and /// no further encoding will be performed. /// </summary> /// <param name="builder">The <see cref="IHtmlContentBuilder"/>.</param> /// <param name="encoded">The HTML encoded <see cref="string"/> that replaces the content.</param> /// <returns>The <see cref="IHtmlContentBuilder"/>.</returns> public static IHtmlContentBuilder SetHtmlContent(this IHtmlContentBuilder builder, string encoded) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } builder.Clear(); builder.AppendHtml(encoded); return builder; } } }
// 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>BiddingStrategySimulation</c> resource.</summary> public sealed partial class BiddingStrategySimulationName : gax::IResourceName, sys::IEquatable<BiddingStrategySimulationName> { /// <summary>The possible contents of <see cref="BiddingStrategySimulationName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c> /// customers/{customer_id}/biddingStrategySimulations/{bidding_strategy_id}~{type}~{modification_method}~{start_date}~{end_date}</c> /// . /// </summary> CustomerBiddingStrategyTypeModificationMethodStartDateEndDate = 1, } private static gax::PathTemplate s_customerBiddingStrategyTypeModificationMethodStartDateEndDate = new gax::PathTemplate("customers/{customer_id}/biddingStrategySimulations/{bidding_strategy_id_type_modification_method_start_date_end_date}"); /// <summary> /// Creates a <see cref="BiddingStrategySimulationName"/> 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="BiddingStrategySimulationName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static BiddingStrategySimulationName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new BiddingStrategySimulationName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="BiddingStrategySimulationName"/> with the pattern /// <c> /// customers/{customer_id}/biddingStrategySimulations/{bidding_strategy_id}~{type}~{modification_method}~{start_date}~{end_date}</c> /// . /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="biddingStrategyId">The <c>BiddingStrategy</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="typeId">The <c>Type</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="modificationMethodId"> /// The <c>ModificationMethod</c> ID. Must not be <c>null</c> or empty. /// </param> /// <param name="startDateId">The <c>StartDate</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="endDateId">The <c>EndDate</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// A new instance of <see cref="BiddingStrategySimulationName"/> constructed from the provided ids. /// </returns> public static BiddingStrategySimulationName FromCustomerBiddingStrategyTypeModificationMethodStartDateEndDate(string customerId, string biddingStrategyId, string typeId, string modificationMethodId, string startDateId, string endDateId) => new BiddingStrategySimulationName(ResourceNameType.CustomerBiddingStrategyTypeModificationMethodStartDateEndDate, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), biddingStrategyId: gax::GaxPreconditions.CheckNotNullOrEmpty(biddingStrategyId, nameof(biddingStrategyId)), typeId: gax::GaxPreconditions.CheckNotNullOrEmpty(typeId, nameof(typeId)), modificationMethodId: gax::GaxPreconditions.CheckNotNullOrEmpty(modificationMethodId, nameof(modificationMethodId)), startDateId: gax::GaxPreconditions.CheckNotNullOrEmpty(startDateId, nameof(startDateId)), endDateId: gax::GaxPreconditions.CheckNotNullOrEmpty(endDateId, nameof(endDateId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="BiddingStrategySimulationName"/> with /// pattern /// <c> /// customers/{customer_id}/biddingStrategySimulations/{bidding_strategy_id}~{type}~{modification_method}~{start_date}~{end_date}</c> /// . /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="biddingStrategyId">The <c>BiddingStrategy</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="typeId">The <c>Type</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="modificationMethodId"> /// The <c>ModificationMethod</c> ID. Must not be <c>null</c> or empty. /// </param> /// <param name="startDateId">The <c>StartDate</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="endDateId">The <c>EndDate</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="BiddingStrategySimulationName"/> with pattern /// <c> /// customers/{customer_id}/biddingStrategySimulations/{bidding_strategy_id}~{type}~{modification_method}~{start_date}~{end_date}</c> /// . /// </returns> public static string Format(string customerId, string biddingStrategyId, string typeId, string modificationMethodId, string startDateId, string endDateId) => FormatCustomerBiddingStrategyTypeModificationMethodStartDateEndDate(customerId, biddingStrategyId, typeId, modificationMethodId, startDateId, endDateId); /// <summary> /// Formats the IDs into the string representation of this <see cref="BiddingStrategySimulationName"/> with /// pattern /// <c> /// customers/{customer_id}/biddingStrategySimulations/{bidding_strategy_id}~{type}~{modification_method}~{start_date}~{end_date}</c> /// . /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="biddingStrategyId">The <c>BiddingStrategy</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="typeId">The <c>Type</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="modificationMethodId"> /// The <c>ModificationMethod</c> ID. Must not be <c>null</c> or empty. /// </param> /// <param name="startDateId">The <c>StartDate</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="endDateId">The <c>EndDate</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="BiddingStrategySimulationName"/> with pattern /// <c> /// customers/{customer_id}/biddingStrategySimulations/{bidding_strategy_id}~{type}~{modification_method}~{start_date}~{end_date}</c> /// . /// </returns> public static string FormatCustomerBiddingStrategyTypeModificationMethodStartDateEndDate(string customerId, string biddingStrategyId, string typeId, string modificationMethodId, string startDateId, string endDateId) => s_customerBiddingStrategyTypeModificationMethodStartDateEndDate.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(biddingStrategyId, nameof(biddingStrategyId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(typeId, nameof(typeId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(modificationMethodId, nameof(modificationMethodId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(startDateId, nameof(startDateId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(endDateId, nameof(endDateId)))}"); /// <summary> /// Parses the given resource name string into a new <see cref="BiddingStrategySimulationName"/> 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}/biddingStrategySimulations/{bidding_strategy_id}~{type}~{modification_method}~{start_date}~{end_date}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="biddingStrategySimulationName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <returns>The parsed <see cref="BiddingStrategySimulationName"/> if successful.</returns> public static BiddingStrategySimulationName Parse(string biddingStrategySimulationName) => Parse(biddingStrategySimulationName, false); /// <summary> /// Parses the given resource name string into a new <see cref="BiddingStrategySimulationName"/> 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}/biddingStrategySimulations/{bidding_strategy_id}~{type}~{modification_method}~{start_date}~{end_date}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="biddingStrategySimulationName"> /// 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="BiddingStrategySimulationName"/> if successful.</returns> public static BiddingStrategySimulationName Parse(string biddingStrategySimulationName, bool allowUnparsed) => TryParse(biddingStrategySimulationName, allowUnparsed, out BiddingStrategySimulationName 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="BiddingStrategySimulationName"/> /// 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}/biddingStrategySimulations/{bidding_strategy_id}~{type}~{modification_method}~{start_date}~{end_date}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="biddingStrategySimulationName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="BiddingStrategySimulationName"/>, 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 biddingStrategySimulationName, out BiddingStrategySimulationName result) => TryParse(biddingStrategySimulationName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="BiddingStrategySimulationName"/> /// 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}/biddingStrategySimulations/{bidding_strategy_id}~{type}~{modification_method}~{start_date}~{end_date}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="biddingStrategySimulationName"> /// 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="BiddingStrategySimulationName"/>, 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 biddingStrategySimulationName, bool allowUnparsed, out BiddingStrategySimulationName result) { gax::GaxPreconditions.CheckNotNull(biddingStrategySimulationName, nameof(biddingStrategySimulationName)); gax::TemplatedResourceName resourceName; if (s_customerBiddingStrategyTypeModificationMethodStartDateEndDate.TryParseName(biddingStrategySimulationName, out resourceName)) { string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', '~', '~', '~', }); if (split1 == null) { result = null; return false; } result = FromCustomerBiddingStrategyTypeModificationMethodStartDateEndDate(resourceName[0], split1[0], split1[1], split1[2], split1[3], split1[4]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(biddingStrategySimulationName, 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 BiddingStrategySimulationName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string biddingStrategyId = null, string customerId = null, string endDateId = null, string modificationMethodId = null, string startDateId = null, string typeId = null) { Type = type; UnparsedResource = unparsedResourceName; BiddingStrategyId = biddingStrategyId; CustomerId = customerId; EndDateId = endDateId; ModificationMethodId = modificationMethodId; StartDateId = startDateId; TypeId = typeId; } /// <summary> /// Constructs a new instance of a <see cref="BiddingStrategySimulationName"/> class from the component parts of /// pattern /// <c> /// customers/{customer_id}/biddingStrategySimulations/{bidding_strategy_id}~{type}~{modification_method}~{start_date}~{end_date}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="biddingStrategyId">The <c>BiddingStrategy</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="typeId">The <c>Type</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="modificationMethodId"> /// The <c>ModificationMethod</c> ID. Must not be <c>null</c> or empty. /// </param> /// <param name="startDateId">The <c>StartDate</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="endDateId">The <c>EndDate</c> ID. Must not be <c>null</c> or empty.</param> public BiddingStrategySimulationName(string customerId, string biddingStrategyId, string typeId, string modificationMethodId, string startDateId, string endDateId) : this(ResourceNameType.CustomerBiddingStrategyTypeModificationMethodStartDateEndDate, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), biddingStrategyId: gax::GaxPreconditions.CheckNotNullOrEmpty(biddingStrategyId, nameof(biddingStrategyId)), typeId: gax::GaxPreconditions.CheckNotNullOrEmpty(typeId, nameof(typeId)), modificationMethodId: gax::GaxPreconditions.CheckNotNullOrEmpty(modificationMethodId, nameof(modificationMethodId)), startDateId: gax::GaxPreconditions.CheckNotNullOrEmpty(startDateId, nameof(startDateId)), endDateId: gax::GaxPreconditions.CheckNotNullOrEmpty(endDateId, nameof(endDateId))) { } /// <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>BiddingStrategy</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource /// name. /// </summary> public string BiddingStrategyId { 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>EndDate</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string EndDateId { get; } /// <summary> /// The <c>ModificationMethod</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed /// resource name. /// </summary> public string ModificationMethodId { get; } /// <summary> /// The <c>StartDate</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string StartDateId { get; } /// <summary> /// The <c>Type</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string TypeId { 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.CustomerBiddingStrategyTypeModificationMethodStartDateEndDate: return s_customerBiddingStrategyTypeModificationMethodStartDateEndDate.Expand(CustomerId, $"{BiddingStrategyId}~{TypeId}~{ModificationMethodId}~{StartDateId}~{EndDateId}"); 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 BiddingStrategySimulationName); /// <inheritdoc/> public bool Equals(BiddingStrategySimulationName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(BiddingStrategySimulationName a, BiddingStrategySimulationName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(BiddingStrategySimulationName a, BiddingStrategySimulationName b) => !(a == b); } public partial class BiddingStrategySimulation { /// <summary> /// <see cref="BiddingStrategySimulationName"/>-typed view over the <see cref="ResourceName"/> resource name /// property. /// </summary> internal BiddingStrategySimulationName ResourceNameAsBiddingStrategySimulationName { get => string.IsNullOrEmpty(ResourceName) ? null : BiddingStrategySimulationName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using Newtonsoft.Json.Tests.TestObjects; using NUnit.Framework; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Converters; using System.IO; using System.Collections; using System.Collections.Specialized; #if !PocketPC && !SILVERLIGHT using System.Web.UI; #endif namespace Newtonsoft.Json.Tests.Linq { public class JObjectTests : TestFixtureBase { [Test] public void TryGetValue() { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); Assert.AreEqual(1, o.Children().Count()); JToken t; Assert.AreEqual(false, o.TryGetValue("sdf", out t)); Assert.AreEqual(null, t); Assert.AreEqual(false, o.TryGetValue(null, out t)); Assert.AreEqual(null, t); Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t)); Assert.AreEqual(true, JToken.DeepEquals(new JValue(1), t)); } [Test] public void DictionaryItemShouldSet() { JObject o = new JObject(); o["PropertyNameValue"] = new JValue(1); Assert.AreEqual(1, o.Children().Count()); JToken t; Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t)); Assert.AreEqual(true, JToken.DeepEquals(new JValue(1), t)); o["PropertyNameValue"] = new JValue(2); Assert.AreEqual(1, o.Children().Count()); Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t)); Assert.AreEqual(true, JToken.DeepEquals(new JValue(2), t)); o["PropertyNameValue"] = null; Assert.AreEqual(1, o.Children().Count()); Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t)); Assert.AreEqual(true, JToken.DeepEquals(new JValue((object)null), t)); } [Test] public void Remove() { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); Assert.AreEqual(1, o.Children().Count()); Assert.AreEqual(false, o.Remove("sdf")); Assert.AreEqual(false, o.Remove(null)); Assert.AreEqual(true, o.Remove("PropertyNameValue")); Assert.AreEqual(0, o.Children().Count()); } [Test] public void GenericCollectionRemove() { JValue v = new JValue(1); JObject o = new JObject(); o.Add("PropertyNameValue", v); Assert.AreEqual(1, o.Children().Count()); Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue1", new JValue(1)))); Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(2)))); Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(1)))); Assert.AreEqual(true, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", v))); Assert.AreEqual(0, o.Children().Count()); } [Test] [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not add property PropertyNameValue to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.")] public void DuplicatePropertyNameShouldThrow() { JObject o = new JObject(); o.Add("PropertyNameValue", null); o.Add("PropertyNameValue", null); } [Test] public void GenericDictionaryAdd() { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); Assert.AreEqual(1, (int)o["PropertyNameValue"]); o.Add("PropertyNameValue1", null); Assert.AreEqual(null, ((JValue)o["PropertyNameValue1"]).Value); Assert.AreEqual(2, o.Children().Count()); } [Test] public void GenericCollectionAdd() { JObject o = new JObject(); ((ICollection<KeyValuePair<string,JToken>>)o).Add(new KeyValuePair<string,JToken>("PropertyNameValue", new JValue(1))); Assert.AreEqual(1, (int)o["PropertyNameValue"]); Assert.AreEqual(1, o.Children().Count()); } [Test] public void GenericCollectionClear() { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); Assert.AreEqual(1, o.Children().Count()); JProperty p = (JProperty)o.Children().ElementAt(0); ((ICollection<KeyValuePair<string, JToken>>)o).Clear(); Assert.AreEqual(0, o.Children().Count()); Assert.AreEqual(null, p.Parent); } [Test] public void GenericCollectionContains() { JValue v = new JValue(1); JObject o = new JObject(); o.Add("PropertyNameValue", v); Assert.AreEqual(1, o.Children().Count()); bool contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(1))); Assert.AreEqual(false, contains); contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", v)); Assert.AreEqual(true, contains); contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(2))); Assert.AreEqual(false, contains); contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue1", new JValue(1))); Assert.AreEqual(false, contains); contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(default(KeyValuePair<string, JToken>)); Assert.AreEqual(false, contains); } [Test] public void GenericDictionaryContains() { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); Assert.AreEqual(1, o.Children().Count()); bool contains = ((IDictionary<string, JToken>)o).ContainsKey("PropertyNameValue"); Assert.AreEqual(true, contains); } [Test] public void GenericCollectionCopyTo() { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); o.Add("PropertyNameValue2", new JValue(2)); o.Add("PropertyNameValue3", new JValue(3)); Assert.AreEqual(3, o.Children().Count()); KeyValuePair<string, JToken>[] a = new KeyValuePair<string,JToken>[5]; ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(a, 1); Assert.AreEqual(default(KeyValuePair<string,JToken>), a[0]); Assert.AreEqual("PropertyNameValue", a[1].Key); Assert.AreEqual(1, (int)a[1].Value); Assert.AreEqual("PropertyNameValue2", a[2].Key); Assert.AreEqual(2, (int)a[2].Value); Assert.AreEqual("PropertyNameValue3", a[3].Key); Assert.AreEqual(3, (int)a[3].Value); Assert.AreEqual(default(KeyValuePair<string, JToken>), a[4]); } [Test] [ExpectedException(typeof(ArgumentNullException), ExpectedMessage = @"Value cannot be null. Parameter name: array")] public void GenericCollectionCopyToNullArrayShouldThrow() { JObject o = new JObject(); ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(null, 0); } [Test] [ExpectedException(typeof(ArgumentOutOfRangeException), ExpectedMessage = @"arrayIndex is less than 0. Parameter name: arrayIndex")] public void GenericCollectionCopyToNegativeArrayIndexShouldThrow() { JObject o = new JObject(); ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[1], -1); } [Test] [ExpectedException(typeof(ArgumentException), ExpectedMessage = @"arrayIndex is equal to or greater than the length of array.")] public void GenericCollectionCopyToArrayIndexEqualGreaterToArrayLengthShouldThrow() { JObject o = new JObject(); ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[1], 1); } [Test] [ExpectedException(typeof(ArgumentException), ExpectedMessage = @"The number of elements in the source JObject is greater than the available space from arrayIndex to the end of the destination array.")] public void GenericCollectionCopyToInsufficientArrayCapacity() { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); o.Add("PropertyNameValue2", new JValue(2)); o.Add("PropertyNameValue3", new JValue(3)); ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[3], 1); } [Test] public void FromObjectRaw() { PersonRaw raw = new PersonRaw { FirstName = "FirstNameValue", RawContent = new JRaw("[1,2,3,4,5]"), LastName = "LastNameValue" }; JObject o = JObject.FromObject(raw); Assert.AreEqual("FirstNameValue", (string)o["first_name"]); Assert.AreEqual(JTokenType.Raw, ((JValue)o["RawContent"]).Type); Assert.AreEqual("[1,2,3,4,5]", (string)o["RawContent"]); Assert.AreEqual("LastNameValue", (string)o["last_name"]); } [Test] public void JTokenReader() { PersonRaw raw = new PersonRaw { FirstName = "FirstNameValue", RawContent = new JRaw("[1,2,3,4,5]"), LastName = "LastNameValue" }; JObject o = JObject.FromObject(raw); JsonReader reader = new JTokenReader(o); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.StartObject, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.String, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.Raw, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.String, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.EndObject, reader.TokenType); Assert.IsFalse(reader.Read()); } [Test] public void DeserializeFromRaw() { PersonRaw raw = new PersonRaw { FirstName = "FirstNameValue", RawContent = new JRaw("[1,2,3,4,5]"), LastName = "LastNameValue" }; JObject o = JObject.FromObject(raw); JsonReader reader = new JTokenReader(o); JsonSerializer serializer = new JsonSerializer(); raw = (PersonRaw)serializer.Deserialize(reader, typeof(PersonRaw)); Assert.AreEqual("FirstNameValue", raw.FirstName); Assert.AreEqual("LastNameValue", raw.LastName); Assert.AreEqual("[1,2,3,4,5]", raw.RawContent.Value); } [Test] [ExpectedException(typeof(Exception), ExpectedMessage = "Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray")] public void Parse_ShouldThrowOnUnexpectedToken() { string json = @"[""prop""]"; JObject.Parse(json); } [Test] public void ParseJavaScriptDate() { string json = @"[new Date(1207285200000)]"; JArray a = (JArray)JsonConvert.DeserializeObject(json); JValue v = (JValue)a[0]; Assert.AreEqual(JsonConvert.ConvertJavaScriptTicksToDateTime(1207285200000), (DateTime)v); } [Test] public void GenericValueCast() { string json = @"{""foo"":true}"; JObject o = (JObject)JsonConvert.DeserializeObject(json); bool? value = o.Value<bool?>("foo"); Assert.AreEqual(true, value); json = @"{""foo"":null}"; o = (JObject)JsonConvert.DeserializeObject(json); value = o.Value<bool?>("foo"); Assert.AreEqual(null, value); } [Test] [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Invalid property identifier character: ]. Line 3, position 9.")] public void Blog() { JObject person = JObject.Parse(@"{ ""name"": ""James"", ]!#$THIS IS: BAD JSON![{}}}}] }"); // Invalid property identifier character: ]. Line 3, position 9. } [Test] public void RawChildValues() { JObject o = new JObject(); o["val1"] = new JRaw("1"); o["val2"] = new JRaw("1"); string json = o.ToString(); Assert.AreEqual(@"{ ""val1"": 1, ""val2"": 1 }", json); } [Test] public void Iterate() { JObject o = new JObject(); o.Add("PropertyNameValue1", new JValue(1)); o.Add("PropertyNameValue2", new JValue(2)); JToken t = o; int i = 1; foreach (JProperty property in t) { Assert.AreEqual("PropertyNameValue" + i, property.Name); Assert.AreEqual(i, (int)property.Value); i++; } } [Test] public void KeyValuePairIterate() { JObject o = new JObject(); o.Add("PropertyNameValue1", new JValue(1)); o.Add("PropertyNameValue2", new JValue(2)); int i = 1; foreach (KeyValuePair<string, JToken> pair in o) { Assert.AreEqual("PropertyNameValue" + i, pair.Key); Assert.AreEqual(i, (int)pair.Value); i++; } } [Test] public void WriteObjectNullStringValue() { string s = null; JValue v = new JValue(s); Assert.AreEqual(null, v.Value); Assert.AreEqual(JTokenType.String, v.Type); JObject o = new JObject(); o["title"] = v; string output = o.ToString(); Assert.AreEqual(@"{ ""title"": null }", output); } [Test] public void Example() { string json = @"{ ""Name"": ""Apple"", ""Expiry"": new Date(1230422400000), ""Price"": 3.99, ""Sizes"": [ ""Small"", ""Medium"", ""Large"" ] }"; JObject o = JObject.Parse(json); string name = (string)o["Name"]; // Apple JArray sizes = (JArray)o["Sizes"]; string smallest = (string)sizes[0]; // Small Console.WriteLine(name); Console.WriteLine(smallest); } [Test] public void DeserializeClassManually() { string jsonText = @"{ ""short"": { ""original"":""http://www.foo.com/"", ""short"":""krehqk"", ""error"": { ""code"":0, ""msg"":""No action taken"" } } }"; JObject json = JObject.Parse(jsonText); Shortie shortie = new Shortie { Original = (string)json["short"]["original"], Short = (string)json["short"]["short"], Error = new ShortieException { Code = (int)json["short"]["error"]["code"], ErrorMessage = (string)json["short"]["error"]["msg"] } }; Console.WriteLine(shortie.Original); // http://www.foo.com/ Console.WriteLine(shortie.Error.ErrorMessage); // No action taken Assert.AreEqual("http://www.foo.com/", shortie.Original); Assert.AreEqual("krehqk", shortie.Short); Assert.AreEqual(null, shortie.Shortened); Assert.AreEqual(0, shortie.Error.Code); Assert.AreEqual("No action taken", shortie.Error.ErrorMessage); } [Test] public void JObjectContainingHtml() { JObject o = new JObject(); o["rc"] = new JValue(200); o["m"] = new JValue(""); o["o"] = new JValue(@"<div class='s1'> <div class='avatar'> <a href='asdf'>asdf</a><br /> <strong>0</strong> </div> <div class='sl'> <p> 444444444 </p> </div> <div class='clear'> </div> </div>"); Assert.AreEqual(@"{ ""rc"": 200, ""m"": """", ""o"": ""<div class='s1'>\r\n <div class='avatar'> \r\n <a href='asdf'>asdf</a><br />\r\n <strong>0</strong>\r\n </div>\r\n <div class='sl'>\r\n <p>\r\n 444444444\r\n </p>\r\n </div>\r\n <div class='clear'>\r\n </div> \r\n</div>"" }", o.ToString()); } [Test] public void ImplicitValueConversions() { JObject moss = new JObject(); moss["FirstName"] = new JValue("Maurice"); moss["LastName"] = new JValue("Moss"); moss["BirthDate"] = new JValue(new DateTime(1977, 12, 30)); moss["Department"] = new JValue("IT"); moss["JobTitle"] = new JValue("Support"); Console.WriteLine(moss.ToString()); //{ // "FirstName": "Maurice", // "LastName": "Moss", // "BirthDate": "\/Date(252241200000+1300)\/", // "Department": "IT", // "JobTitle": "Support" //} JObject jen = new JObject(); jen["FirstName"] = "Jen"; jen["LastName"] = "Barber"; jen["BirthDate"] = new DateTime(1978, 3, 15); jen["Department"] = "IT"; jen["JobTitle"] = "Manager"; Console.WriteLine(jen.ToString()); //{ // "FirstName": "Jen", // "LastName": "Barber", // "BirthDate": "\/Date(258721200000+1300)\/", // "Department": "IT", // "JobTitle": "Manager" //} } [Test] public void ReplaceJPropertyWithJPropertyWithSameName() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); JObject o = new JObject(p1, p2); IList l = o; Assert.AreEqual(p1, l[0]); Assert.AreEqual(p2, l[1]); JProperty p3 = new JProperty("Test1", "III"); p1.Replace(p3); Assert.AreEqual(null, p1.Parent); Assert.AreEqual(l, p3.Parent); Assert.AreEqual(p3, l[0]); Assert.AreEqual(p2, l[1]); Assert.AreEqual(2, l.Count); Assert.AreEqual(2, o.Properties().Count()); JProperty p4 = new JProperty("Test4", "IV"); p2.Replace(p4); Assert.AreEqual(null, p2.Parent); Assert.AreEqual(l, p4.Parent); Assert.AreEqual(p3, l[0]); Assert.AreEqual(p4, l[1]); } #if !PocketPC && !SILVERLIGHT && !NET20 [Test] public void PropertyChanging() { object changing = null; object changed = null; int changingCount = 0; int changedCount = 0; JObject o = new JObject(); o.PropertyChanging += (sender, args) => { JObject s = (JObject) sender; changing = (s[args.PropertyName] != null) ? ((JValue)s[args.PropertyName]).Value : null; changingCount++; }; o.PropertyChanged += (sender, args) => { JObject s = (JObject)sender; changed = (s[args.PropertyName] != null) ? ((JValue)s[args.PropertyName]).Value : null; changedCount++; }; o["StringValue"] = "value1"; Assert.AreEqual(null, changing); Assert.AreEqual("value1", changed); Assert.AreEqual("value1", (string)o["StringValue"]); Assert.AreEqual(1, changingCount); Assert.AreEqual(1, changedCount); o["StringValue"] = "value1"; Assert.AreEqual(1, changingCount); Assert.AreEqual(1, changedCount); o["StringValue"] = "value2"; Assert.AreEqual("value1", changing); Assert.AreEqual("value2", changed); Assert.AreEqual("value2", (string)o["StringValue"]); Assert.AreEqual(2, changingCount); Assert.AreEqual(2, changedCount); o["StringValue"] = null; Assert.AreEqual("value2", changing); Assert.AreEqual(null, changed); Assert.AreEqual(null, (string)o["StringValue"]); Assert.AreEqual(3, changingCount); Assert.AreEqual(3, changedCount); o["NullValue"] = null; Assert.AreEqual(null, changing); Assert.AreEqual(null, changed); Assert.AreEqual(new JValue((object)null), o["NullValue"]); Assert.AreEqual(4, changingCount); Assert.AreEqual(4, changedCount); o["NullValue"] = null; Assert.AreEqual(4, changingCount); Assert.AreEqual(4, changedCount); } #endif [Test] public void PropertyChanged() { object changed = null; int changedCount = 0; JObject o = new JObject(); o.PropertyChanged += (sender, args) => { JObject s = (JObject)sender; changed = (s[args.PropertyName] != null) ? ((JValue)s[args.PropertyName]).Value : null; changedCount++; }; o["StringValue"] = "value1"; Assert.AreEqual("value1", changed); Assert.AreEqual("value1", (string)o["StringValue"]); Assert.AreEqual(1, changedCount); o["StringValue"] = "value1"; Assert.AreEqual(1, changedCount); o["StringValue"] = "value2"; Assert.AreEqual("value2", changed); Assert.AreEqual("value2", (string)o["StringValue"]); Assert.AreEqual(2, changedCount); o["StringValue"] = null; Assert.AreEqual(null, changed); Assert.AreEqual(null, (string)o["StringValue"]); Assert.AreEqual(3, changedCount); o["NullValue"] = null; Assert.AreEqual(null, changed); Assert.AreEqual(new JValue((object)null), o["NullValue"]); Assert.AreEqual(4, changedCount); o["NullValue"] = null; Assert.AreEqual(4, changedCount); } [Test] public void IListContains() { JProperty p = new JProperty("Test", 1); IList l = new JObject(p); Assert.IsTrue(l.Contains(p)); Assert.IsFalse(l.Contains(new JProperty("Test", 1))); } [Test] public void IListIndexOf() { JProperty p = new JProperty("Test", 1); IList l = new JObject(p); Assert.AreEqual(0, l.IndexOf(p)); Assert.AreEqual(-1, l.IndexOf(new JProperty("Test", 1))); } [Test] public void IListClear() { JProperty p = new JProperty("Test", 1); IList l = new JObject(p); Assert.AreEqual(1, l.Count); l.Clear(); Assert.AreEqual(0, l.Count); } [Test] public void IListCopyTo() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); object[] a = new object[l.Count]; l.CopyTo(a, 0); Assert.AreEqual(p1, a[0]); Assert.AreEqual(p2, a[1]); } [Test] public void IListAdd() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l.Add(p3); Assert.AreEqual(3, l.Count); Assert.AreEqual(p3, l[2]); } [Test] [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.")] public void IListAddBadToken() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); l.Add(new JValue("Bad!")); } [Test] [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Argument is not a JToken.")] public void IListAddBadValue() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); l.Add("Bad!"); } [Test] [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not add property Test2 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.")] public void IListAddPropertyWithExistingName() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test2", "II"); l.Add(p3); } [Test] public void IListRemove() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); // won't do anything l.Remove(p3); Assert.AreEqual(2, l.Count); l.Remove(p1); Assert.AreEqual(1, l.Count); Assert.IsFalse(l.Contains(p1)); Assert.IsTrue(l.Contains(p2)); l.Remove(p2); Assert.AreEqual(0, l.Count); Assert.IsFalse(l.Contains(p2)); Assert.AreEqual(null, p2.Parent); } [Test] public void IListRemoveAt() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); // won't do anything l.RemoveAt(0); l.Remove(p1); Assert.AreEqual(1, l.Count); l.Remove(p2); Assert.AreEqual(0, l.Count); } [Test] public void IListInsert() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l.Insert(1, p3); Assert.AreEqual(l, p3.Parent); Assert.AreEqual(p1, l[0]); Assert.AreEqual(p3, l[1]); Assert.AreEqual(p2, l[2]); } [Test] public void IListIsReadOnly() { IList l = new JObject(); Assert.IsFalse(l.IsReadOnly); } [Test] public void IListIsFixedSize() { IList l = new JObject(); Assert.IsFalse(l.IsFixedSize); } [Test] public void IListSetItem() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l[0] = p3; Assert.AreEqual(p3, l[0]); Assert.AreEqual(p2, l[1]); } [Test] [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not add property Test3 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.")] public void IListSetItemAlreadyExists() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l[0] = p3; l[1] = p3; } [Test] [ExpectedException(typeof(ArgumentException), ExpectedMessage = @"Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.")] public void IListSetItemInvalid() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); l[0] = new JValue(true); } [Test] public void IListSyncRoot() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); Assert.IsNotNull(l.SyncRoot); } [Test] public void IListIsSynchronized() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); Assert.IsFalse(l.IsSynchronized); } [Test] public void GenericListJTokenContains() { JProperty p = new JProperty("Test", 1); IList<JToken> l = new JObject(p); Assert.IsTrue(l.Contains(p)); Assert.IsFalse(l.Contains(new JProperty("Test", 1))); } [Test] public void GenericListJTokenIndexOf() { JProperty p = new JProperty("Test", 1); IList<JToken> l = new JObject(p); Assert.AreEqual(0, l.IndexOf(p)); Assert.AreEqual(-1, l.IndexOf(new JProperty("Test", 1))); } [Test] public void GenericListJTokenClear() { JProperty p = new JProperty("Test", 1); IList<JToken> l = new JObject(p); Assert.AreEqual(1, l.Count); l.Clear(); Assert.AreEqual(0, l.Count); } [Test] public void GenericListJTokenCopyTo() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JToken[] a = new JToken[l.Count]; l.CopyTo(a, 0); Assert.AreEqual(p1, a[0]); Assert.AreEqual(p2, a[1]); } [Test] public void GenericListJTokenAdd() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l.Add(p3); Assert.AreEqual(3, l.Count); Assert.AreEqual(p3, l[2]); } [Test] [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.")] public void GenericListJTokenAddBadToken() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); l.Add(new JValue("Bad!")); } [Test] [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.")] public void GenericListJTokenAddBadValue() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); // string is implicitly converted to JValue l.Add("Bad!"); } [Test] [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not add property Test2 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.")] public void GenericListJTokenAddPropertyWithExistingName() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test2", "II"); l.Add(p3); } [Test] public void GenericListJTokenRemove() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); // won't do anything Assert.IsFalse(l.Remove(p3)); Assert.AreEqual(2, l.Count); Assert.IsTrue(l.Remove(p1)); Assert.AreEqual(1, l.Count); Assert.IsFalse(l.Contains(p1)); Assert.IsTrue(l.Contains(p2)); Assert.IsTrue(l.Remove(p2)); Assert.AreEqual(0, l.Count); Assert.IsFalse(l.Contains(p2)); Assert.AreEqual(null, p2.Parent); } [Test] public void GenericListJTokenRemoveAt() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); // won't do anything l.RemoveAt(0); l.Remove(p1); Assert.AreEqual(1, l.Count); l.Remove(p2); Assert.AreEqual(0, l.Count); } [Test] public void GenericListJTokenInsert() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l.Insert(1, p3); Assert.AreEqual(l, p3.Parent); Assert.AreEqual(p1, l[0]); Assert.AreEqual(p3, l[1]); Assert.AreEqual(p2, l[2]); } [Test] public void GenericListJTokenIsReadOnly() { IList<JToken> l = new JObject(); Assert.IsFalse(l.IsReadOnly); } [Test] public void GenericListJTokenSetItem() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l[0] = p3; Assert.AreEqual(p3, l[0]); Assert.AreEqual(p2, l[1]); } [Test] [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not add property Test3 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.")] public void GenericListJTokenSetItemAlreadyExists() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l[0] = p3; l[1] = p3; } #if !SILVERLIGHT [Test] public void IBindingListSortDirection() { IBindingList l = new JObject(); Assert.AreEqual(ListSortDirection.Ascending, l.SortDirection); } [Test] public void IBindingListSortProperty() { IBindingList l = new JObject(); Assert.AreEqual(null, l.SortProperty); } [Test] public void IBindingListSupportsChangeNotification() { IBindingList l = new JObject(); Assert.AreEqual(true, l.SupportsChangeNotification); } [Test] public void IBindingListSupportsSearching() { IBindingList l = new JObject(); Assert.AreEqual(false, l.SupportsSearching); } [Test] public void IBindingListSupportsSorting() { IBindingList l = new JObject(); Assert.AreEqual(false, l.SupportsSorting); } [Test] public void IBindingListAllowEdit() { IBindingList l = new JObject(); Assert.AreEqual(true, l.AllowEdit); } [Test] public void IBindingListAllowNew() { IBindingList l = new JObject(); Assert.AreEqual(true, l.AllowNew); } [Test] public void IBindingListAllowRemove() { IBindingList l = new JObject(); Assert.AreEqual(true, l.AllowRemove); } [Test] public void IBindingListAddIndex() { IBindingList l = new JObject(); // do nothing l.AddIndex(null); } [Test] [ExpectedException(typeof(NotSupportedException))] public void IBindingListApplySort() { IBindingList l = new JObject(); l.ApplySort(null, ListSortDirection.Ascending); } [Test] [ExpectedException(typeof(NotSupportedException))] public void IBindingListRemoveSort() { IBindingList l = new JObject(); l.RemoveSort(); } [Test] public void IBindingListRemoveIndex() { IBindingList l = new JObject(); // do nothing l.RemoveIndex(null); } [Test] [ExpectedException(typeof(NotSupportedException))] public void IBindingListFind() { IBindingList l = new JObject(); l.Find(null, null); } [Test] public void IBindingListIsSorted() { IBindingList l = new JObject(); Assert.AreEqual(false, l.IsSorted); } [Test] [ExpectedException(typeof(Exception), ExpectedMessage = "Could not determine new value to add to 'Newtonsoft.Json.Linq.JObject'.")] public void IBindingListAddNew() { IBindingList l = new JObject(); l.AddNew(); } [Test] public void IBindingListAddNewWithEvent() { JObject o = new JObject(); o.AddingNew += (s, e) => e.NewObject = new JProperty("Property!"); IBindingList l = o; object newObject = l.AddNew(); Assert.IsNotNull(newObject); JProperty p = (JProperty) newObject; Assert.AreEqual("Property!", p.Name); Assert.AreEqual(o, p.Parent); } [Test] public void ITypedListGetListName() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); ITypedList l = new JObject(p1, p2); Assert.AreEqual(string.Empty, l.GetListName(null)); } [Test] public void ITypedListGetItemProperties() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); ITypedList l = new JObject(p1, p2); PropertyDescriptorCollection propertyDescriptors = l.GetItemProperties(null); Assert.IsNull(propertyDescriptors); } [Test] public void ListChanged() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); JObject o = new JObject(p1, p2); ListChangedType? changedType = null; int? index = null; o.ListChanged += (s, a) => { changedType = a.ListChangedType; index = a.NewIndex; }; JProperty p3 = new JProperty("Test3", "III"); o.Add(p3); Assert.AreEqual(changedType, ListChangedType.ItemAdded); Assert.AreEqual(index, 2); Assert.AreEqual(p3, ((IList<JToken>)o)[index.Value]); JProperty p4 = new JProperty("Test4", "IV"); ((IList<JToken>) o)[index.Value] = p4; Assert.AreEqual(changedType, ListChangedType.ItemChanged); Assert.AreEqual(index, 2); Assert.AreEqual(p4, ((IList<JToken>)o)[index.Value]); Assert.IsFalse(((IList<JToken>)o).Contains(p3)); Assert.IsTrue(((IList<JToken>)o).Contains(p4)); o["Test1"] = 2; Assert.AreEqual(changedType, ListChangedType.ItemChanged); Assert.AreEqual(index, 0); Assert.AreEqual(2, (int)o["Test1"]); } #endif #if SILVERLIGHT || !(NET20 || NET35) [Test] public void CollectionChanged() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); JObject o = new JObject(p1, p2); NotifyCollectionChangedAction? changedType = null; int? index = null; o.CollectionChanged += (s, a) => { changedType = a.Action; index = a.NewStartingIndex; }; JProperty p3 = new JProperty("Test3", "III"); o.Add(p3); Assert.AreEqual(changedType, NotifyCollectionChangedAction.Add); Assert.AreEqual(index, 2); Assert.AreEqual(p3, ((IList<JToken>)o)[index.Value]); JProperty p4 = new JProperty("Test4", "IV"); ((IList<JToken>)o)[index.Value] = p4; Assert.AreEqual(changedType, NotifyCollectionChangedAction.Replace); Assert.AreEqual(index, 2); Assert.AreEqual(p4, ((IList<JToken>)o)[index.Value]); Assert.IsFalse(((IList<JToken>)o).Contains(p3)); Assert.IsTrue(((IList<JToken>)o).Contains(p4)); o["Test1"] = 2; Assert.AreEqual(changedType, NotifyCollectionChangedAction.Replace); Assert.AreEqual(index, 0); Assert.AreEqual(2, (int)o["Test1"]); } #endif [Test] public void GetGeocodeAddress() { string json = @"{ ""name"": ""Address: 435 North Mulford Road Rockford, IL 61107"", ""Status"": { ""code"": 200, ""request"": ""geocode"" }, ""Placemark"": [ { ""id"": ""p1"", ""address"": ""435 N Mulford Rd, Rockford, IL 61107, USA"", ""AddressDetails"": { ""Accuracy"" : 8, ""Country"" : { ""AdministrativeArea"" : { ""AdministrativeAreaName"" : ""IL"", ""SubAdministrativeArea"" : { ""Locality"" : { ""LocalityName"" : ""Rockford"", ""PostalCode"" : { ""PostalCodeNumber"" : ""61107"" }, ""Thoroughfare"" : { ""ThoroughfareName"" : ""435 N Mulford Rd"" } }, ""SubAdministrativeAreaName"" : ""Winnebago"" } }, ""CountryName"" : ""USA"", ""CountryNameCode"" : ""US"" } }, ""ExtendedData"": { ""LatLonBox"": { ""north"": 42.2753076, ""south"": 42.2690124, ""east"": -88.9964645, ""west"": -89.0027597 } }, ""Point"": { ""coordinates"": [ -88.9995886, 42.2721596, 0 ] } } ] }"; JObject o = JObject.Parse(json); string searchAddress = (string)o["Placemark"][0]["AddressDetails"]["Country"]["AdministrativeArea"]["SubAdministrativeArea"]["Locality"]["Thoroughfare"]["ThoroughfareName"]; Assert.AreEqual("435 N Mulford Rd", searchAddress); } [Test] [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Set JObject values with invalid key value: 0. Object property name expected.")] public void SetValueWithInvalidPropertyName() { JObject o = new JObject(); o[0] = new JValue(3); } [Test] public void SetValue() { object key = "TestKey"; JObject o = new JObject(); o[key] = new JValue(3); Assert.AreEqual(3, (int)o[key]); } [Test] public void ParseMultipleProperties() { string json = @"{ ""Name"": ""Name1"", ""Name"": ""Name2"" }"; JObject o = JObject.Parse(json); string value = (string)o["Name"]; Assert.AreEqual("Name2", value); } [Test] public void WriteObjectNullDBNullValue() { DBNull dbNull = DBNull.Value; JValue v = new JValue(dbNull); Assert.AreEqual(DBNull.Value, v.Value); Assert.AreEqual(JTokenType.Null, v.Type); JObject o = new JObject(); o["title"] = v; string output = o.ToString(); Assert.AreEqual(@"{ ""title"": null }", output); } [Test] [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not convert Object to String.")] public void InvalidValueCastExceptionMessage() { string json = @"{ ""responseData"": {}, ""responseDetails"": null, ""responseStatus"": 200 }"; JObject o = JObject.Parse(json); string name = (string)o["responseData"]; } [Test] [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not convert Object to String.")] public void InvalidPropertyValueCastExceptionMessage() { string json = @"{ ""responseData"": {}, ""responseDetails"": null, ""responseStatus"": 200 }"; JObject o = JObject.Parse(json); string name = (string)o.Property("responseData"); } [Test] [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "JSON integer 307953220000517141511 is too large or small for an Int64.")] public void NumberTooBigForInt64() { string json = @"{""code"": 307953220000517141511}"; JObject.Parse(json); } [Test] [ExpectedException(typeof(Exception), ExpectedMessage = "Unexpected end of content while loading JObject.")] public void ParseIncomplete() { JObject.Parse("{ foo:"); } [Test] public void LoadFromNestedObject() { string jsonText = @"{ ""short"": { ""error"": { ""code"":0, ""msg"":""No action taken"" } } }"; JsonReader reader = new JsonTextReader(new StringReader(jsonText)); reader.Read(); reader.Read(); reader.Read(); reader.Read(); reader.Read(); JObject o = (JObject)JToken.ReadFrom(reader); Assert.IsNotNull(o); Assert.AreEqual(@"{ ""code"": 0, ""msg"": ""No action taken"" }", o.ToString(Formatting.Indented)); } [Test] [ExpectedException(typeof(Exception), ExpectedMessage = "Unexpected end of content while loading JObject.")] public void LoadFromNestedObjectIncomplete() { string jsonText = @"{ ""short"": { ""error"": { ""code"":0"; JsonReader reader = new JsonTextReader(new StringReader(jsonText)); reader.Read(); reader.Read(); reader.Read(); reader.Read(); reader.Read(); JToken.ReadFrom(reader); } #if !SILVERLIGHT [Test] public void GetProperties() { JObject o = JObject.Parse("{'prop1':12,'prop2':'hi!','prop3':null,'prop4':[1,2,3]}"); ICustomTypeDescriptor descriptor = o; PropertyDescriptorCollection properties = descriptor.GetProperties(); Assert.AreEqual(4, properties.Count); PropertyDescriptor prop1 = properties[0]; Assert.AreEqual("prop1", prop1.Name); Assert.AreEqual(typeof(long), prop1.PropertyType); Assert.AreEqual(typeof(JObject), prop1.ComponentType); Assert.AreEqual(false, prop1.CanResetValue(o)); Assert.AreEqual(false, prop1.ShouldSerializeValue(o)); PropertyDescriptor prop2 = properties[1]; Assert.AreEqual("prop2", prop2.Name); Assert.AreEqual(typeof(string), prop2.PropertyType); Assert.AreEqual(typeof(JObject), prop2.ComponentType); Assert.AreEqual(false, prop2.CanResetValue(o)); Assert.AreEqual(false, prop2.ShouldSerializeValue(o)); PropertyDescriptor prop3 = properties[2]; Assert.AreEqual("prop3", prop3.Name); Assert.AreEqual(typeof(object), prop3.PropertyType); Assert.AreEqual(typeof(JObject), prop3.ComponentType); Assert.AreEqual(false, prop3.CanResetValue(o)); Assert.AreEqual(false, prop3.ShouldSerializeValue(o)); PropertyDescriptor prop4 = properties[3]; Assert.AreEqual("prop4", prop4.Name); Assert.AreEqual(typeof(JArray), prop4.PropertyType); Assert.AreEqual(typeof(JObject), prop4.ComponentType); Assert.AreEqual(false, prop4.CanResetValue(o)); Assert.AreEqual(false, prop4.ShouldSerializeValue(o)); } #endif } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; namespace _4PosBackOffice.NET { [Microsoft.VisualBasic.CompilerServices.DesignerGenerated()] partial class frmPersonFPVerifyOT { #region "Windows Form Designer generated code " [System.Diagnostics.DebuggerNonUserCode()] public frmPersonFPVerifyOT() : base() { Load += frmPersonFPVerifyOT_Load; //This call is required by the Windows Form Designer. InitializeComponent(); } //Form overrides dispose to clean up the component list. [System.Diagnostics.DebuggerNonUserCode()] protected override void Dispose(bool Disposing) { if (Disposing) { if ((components != null)) { components.Dispose(); } } base.Dispose(Disposing); } //Required by the Windows Form Designer private System.ComponentModel.IContainer components; public System.Windows.Forms.ToolTip ToolTip1; public System.Windows.Forms.TextBox eName; private System.Windows.Forms.Button withEventsField_cmdExit; public System.Windows.Forms.Button cmdExit { get { return withEventsField_cmdExit; } set { if (withEventsField_cmdExit != null) { withEventsField_cmdExit.Click -= cmdExit_Click; } withEventsField_cmdExit = value; if (withEventsField_cmdExit != null) { withEventsField_cmdExit.Click += cmdExit_Click; } } } public System.Windows.Forms.Panel picButtons; public System.Windows.Forms.PictureBox HiddenPict; public System.Windows.Forms.PictureBox Picture1; private System.Windows.Forms.Button withEventsField_Close_Renamed; public System.Windows.Forms.Button Close_Renamed { get { return withEventsField_Close_Renamed; } set { if (withEventsField_Close_Renamed != null) { withEventsField_Close_Renamed.Click -= Close_Renamed_Click; } withEventsField_Close_Renamed = value; if (withEventsField_Close_Renamed != null) { withEventsField_Close_Renamed.Click += Close_Renamed_Click; } } } public System.Windows.Forms.ListBox Status; public System.Windows.Forms.Label FAR; public System.Windows.Forms.Label Label3; public System.Windows.Forms.Label Label1; public System.Windows.Forms.Label Prompt; public System.Windows.Forms.Label Label2; //NOTE: The following procedure is required by the Windows Form Designer //It can be modified using the Windows Form Designer. //Do not modify it using the code editor. [System.Diagnostics.DebuggerStepThrough()] private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmPersonFPVerifyOT)); this.components = new System.ComponentModel.Container(); this.ToolTip1 = new System.Windows.Forms.ToolTip(components); this.eName = new System.Windows.Forms.TextBox(); this.picButtons = new System.Windows.Forms.Panel(); this.cmdExit = new System.Windows.Forms.Button(); this.HiddenPict = new System.Windows.Forms.PictureBox(); this.Picture1 = new System.Windows.Forms.PictureBox(); this.Close_Renamed = new System.Windows.Forms.Button(); this.Status = new System.Windows.Forms.ListBox(); this.FAR = new System.Windows.Forms.Label(); this.Label3 = new System.Windows.Forms.Label(); this.Label1 = new System.Windows.Forms.Label(); this.Prompt = new System.Windows.Forms.Label(); this.Label2 = new System.Windows.Forms.Label(); this.picButtons.SuspendLayout(); this.SuspendLayout(); this.ToolTip1.Active = true; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Text = "Verify Form"; this.ClientSize = new System.Drawing.Size(522, 310); this.Location = new System.Drawing.Point(3, 29); this.ControlBox = false; this.KeyPreview = true; this.MaximizeBox = false; this.MinimizeBox = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.Control; this.Enabled = true; this.Cursor = System.Windows.Forms.Cursors.Default; this.RightToLeft = System.Windows.Forms.RightToLeft.No; this.ShowInTaskbar = true; this.HelpButton = false; this.WindowState = System.Windows.Forms.FormWindowState.Normal; this.Name = "frmPersonFPVerifyOT"; this.eName.AutoSize = false; this.eName.BackColor = System.Drawing.Color.Blue; this.eName.ForeColor = System.Drawing.Color.White; this.eName.Size = new System.Drawing.Size(505, 17); this.eName.Location = new System.Drawing.Point(8, 48); this.eName.ReadOnly = true; this.eName.TabIndex = 11; this.eName.Text = "name"; this.eName.AcceptsReturn = true; this.eName.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; this.eName.CausesValidation = true; this.eName.Enabled = true; this.eName.HideSelection = true; this.eName.MaxLength = 0; this.eName.Cursor = System.Windows.Forms.Cursors.IBeam; this.eName.Multiline = false; this.eName.RightToLeft = System.Windows.Forms.RightToLeft.No; this.eName.ScrollBars = System.Windows.Forms.ScrollBars.None; this.eName.TabStop = true; this.eName.Visible = true; this.eName.BorderStyle = System.Windows.Forms.BorderStyle.None; this.eName.Name = "eName"; this.picButtons.Dock = System.Windows.Forms.DockStyle.Top; this.picButtons.BackColor = System.Drawing.Color.Blue; this.picButtons.Size = new System.Drawing.Size(522, 39); this.picButtons.Location = new System.Drawing.Point(0, 0); this.picButtons.TabIndex = 9; this.picButtons.TabStop = false; this.picButtons.CausesValidation = true; this.picButtons.Enabled = true; this.picButtons.ForeColor = System.Drawing.SystemColors.ControlText; this.picButtons.Cursor = System.Windows.Forms.Cursors.Default; this.picButtons.RightToLeft = System.Windows.Forms.RightToLeft.No; this.picButtons.Visible = true; this.picButtons.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.picButtons.Name = "picButtons"; this.cmdExit.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdExit.Text = "E&xit"; this.cmdExit.Size = new System.Drawing.Size(73, 29); this.cmdExit.Location = new System.Drawing.Point(432, 3); this.cmdExit.TabIndex = 10; this.cmdExit.TabStop = false; this.cmdExit.BackColor = System.Drawing.SystemColors.Control; this.cmdExit.CausesValidation = true; this.cmdExit.Enabled = true; this.cmdExit.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdExit.Cursor = System.Windows.Forms.Cursors.Default; this.cmdExit.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdExit.Name = "cmdExit"; this.HiddenPict.Size = new System.Drawing.Size(41, 33); this.HiddenPict.Location = new System.Drawing.Point(152, 344); this.HiddenPict.TabIndex = 8; this.HiddenPict.Visible = false; this.HiddenPict.Dock = System.Windows.Forms.DockStyle.None; this.HiddenPict.BackColor = System.Drawing.SystemColors.Control; this.HiddenPict.CausesValidation = true; this.HiddenPict.Enabled = true; this.HiddenPict.ForeColor = System.Drawing.SystemColors.ControlText; this.HiddenPict.Cursor = System.Windows.Forms.Cursors.Default; this.HiddenPict.RightToLeft = System.Windows.Forms.RightToLeft.No; this.HiddenPict.TabStop = true; this.HiddenPict.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize; this.HiddenPict.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.HiddenPict.Name = "HiddenPict"; this.Picture1.Size = new System.Drawing.Size(185, 185); this.Picture1.Location = new System.Drawing.Point(8, 72); this.Picture1.TabIndex = 2; this.Picture1.Dock = System.Windows.Forms.DockStyle.None; this.Picture1.BackColor = System.Drawing.SystemColors.Control; this.Picture1.CausesValidation = true; this.Picture1.Enabled = true; this.Picture1.ForeColor = System.Drawing.SystemColors.ControlText; this.Picture1.Cursor = System.Windows.Forms.Cursors.Default; this.Picture1.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Picture1.TabStop = true; this.Picture1.Visible = true; this.Picture1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Normal; this.Picture1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.Picture1.Name = "Picture1"; this.Close_Renamed.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.Close_Renamed.Text = "Close"; this.Close_Renamed.Size = new System.Drawing.Size(81, 25); this.Close_Renamed.Location = new System.Drawing.Point(424, 344); this.Close_Renamed.TabIndex = 1; this.Close_Renamed.Visible = false; this.Close_Renamed.BackColor = System.Drawing.SystemColors.Control; this.Close_Renamed.CausesValidation = true; this.Close_Renamed.Enabled = true; this.Close_Renamed.ForeColor = System.Drawing.SystemColors.ControlText; this.Close_Renamed.Cursor = System.Windows.Forms.Cursors.Default; this.Close_Renamed.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Close_Renamed.TabStop = true; this.Close_Renamed.Name = "Close_Renamed"; this.Status.Size = new System.Drawing.Size(305, 124); this.Status.Location = new System.Drawing.Point(208, 128); this.Status.TabIndex = 0; this.Status.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.Status.BackColor = System.Drawing.SystemColors.Window; this.Status.CausesValidation = true; this.Status.Enabled = true; this.Status.ForeColor = System.Drawing.SystemColors.WindowText; this.Status.IntegralHeight = true; this.Status.Cursor = System.Windows.Forms.Cursors.Default; this.Status.SelectionMode = System.Windows.Forms.SelectionMode.One; this.Status.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Status.Sorted = false; this.Status.TabStop = true; this.Status.Visible = true; this.Status.MultiColumn = false; this.Status.Name = "Status"; this.FAR.Size = new System.Drawing.Size(177, 25); this.FAR.Location = new System.Drawing.Point(336, 272); this.FAR.TabIndex = 7; this.FAR.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.FAR.BackColor = System.Drawing.SystemColors.Control; this.FAR.Enabled = true; this.FAR.ForeColor = System.Drawing.SystemColors.ControlText; this.FAR.Cursor = System.Windows.Forms.Cursors.Default; this.FAR.RightToLeft = System.Windows.Forms.RightToLeft.No; this.FAR.UseMnemonic = true; this.FAR.Visible = true; this.FAR.AutoSize = false; this.FAR.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.FAR.Name = "FAR"; this.Label3.Text = "False Accept Rate:"; this.Label3.Size = new System.Drawing.Size(121, 17); this.Label3.Location = new System.Drawing.Point(208, 272); this.Label3.TabIndex = 6; this.Label3.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.Label3.BackColor = System.Drawing.SystemColors.Control; this.Label3.Enabled = true; this.Label3.ForeColor = System.Drawing.SystemColors.ControlText; this.Label3.Cursor = System.Windows.Forms.Cursors.Default; this.Label3.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Label3.UseMnemonic = true; this.Label3.Visible = true; this.Label3.AutoSize = false; this.Label3.BorderStyle = System.Windows.Forms.BorderStyle.None; this.Label3.Name = "Label3"; this.Label1.Text = "Prompt:"; this.Label1.Size = new System.Drawing.Size(177, 17); this.Label1.Location = new System.Drawing.Point(208, 72); this.Label1.TabIndex = 5; this.Label1.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.Label1.BackColor = System.Drawing.SystemColors.Control; this.Label1.Enabled = true; this.Label1.ForeColor = System.Drawing.SystemColors.ControlText; this.Label1.Cursor = System.Windows.Forms.Cursors.Default; this.Label1.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Label1.UseMnemonic = true; this.Label1.Visible = true; this.Label1.AutoSize = false; this.Label1.BorderStyle = System.Windows.Forms.BorderStyle.None; this.Label1.Name = "Label1"; this.Prompt.Text = "Touch the fingerprint reader."; this.Prompt.Size = new System.Drawing.Size(305, 25); this.Prompt.Location = new System.Drawing.Point(208, 88); this.Prompt.TabIndex = 4; this.Prompt.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.Prompt.BackColor = System.Drawing.SystemColors.Control; this.Prompt.Enabled = true; this.Prompt.ForeColor = System.Drawing.SystemColors.ControlText; this.Prompt.Cursor = System.Windows.Forms.Cursors.Default; this.Prompt.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Prompt.UseMnemonic = true; this.Prompt.Visible = true; this.Prompt.AutoSize = false; this.Prompt.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.Prompt.Name = "Prompt"; this.Label2.Text = "Status:"; this.Label2.Size = new System.Drawing.Size(177, 17); this.Label2.Location = new System.Drawing.Point(208, 112); this.Label2.TabIndex = 3; this.Label2.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.Label2.BackColor = System.Drawing.SystemColors.Control; this.Label2.Enabled = true; this.Label2.ForeColor = System.Drawing.SystemColors.ControlText; this.Label2.Cursor = System.Windows.Forms.Cursors.Default; this.Label2.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Label2.UseMnemonic = true; this.Label2.Visible = true; this.Label2.AutoSize = false; this.Label2.BorderStyle = System.Windows.Forms.BorderStyle.None; this.Label2.Name = "Label2"; this.Controls.Add(eName); this.Controls.Add(picButtons); this.Controls.Add(HiddenPict); this.Controls.Add(Picture1); this.Controls.Add(Close_Renamed); this.Controls.Add(Status); this.Controls.Add(FAR); this.Controls.Add(Label3); this.Controls.Add(Label1); this.Controls.Add(Prompt); this.Controls.Add(Label2); this.picButtons.Controls.Add(cmdExit); this.picButtons.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion } }
// // Copyright (c) 2017 The Material Components for iOS Xamarin Binding Authors. // All Rights Reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice 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 Foundation; using CoreAnimation; using CoreGraphics; using UIKit; using MaterialComponents; using ObjCRuntime; namespace MaterialComponents.MaterialFlexibleHeader { // @interface MDCFlexibleHeaderContainerViewController : UIViewController [BaseType(typeof(UIViewController))] interface MDCFlexibleHeaderContainerViewController { // -(instancetype _Nonnull)initWithContentViewController:(UIViewController * _Nullable)contentViewController __attribute__((objc_designated_initializer)); [Export("initWithContentViewController:")] [DesignatedInitializer] IntPtr Constructor([NullAllowed] UIViewController contentViewController); // @property (readonly, nonatomic, strong) MDCFlexibleHeaderViewController * _Nonnull headerViewController; [Export("headerViewController", ArgumentSemantic.Strong)] MDCFlexibleHeaderViewController HeaderViewController { get; } // @property (nonatomic, strong) UIViewController * _Nullable contentViewController; [NullAllowed, Export("contentViewController", ArgumentSemantic.Strong)] UIViewController ContentViewController { get; set; } } // typedef void (^MDCFlexibleHeaderChangeContentInsetsBlock)(); delegate void MDCFlexibleHeaderChangeContentInsetsBlock(); // typedef void (^MDCFlexibleHeaderShadowIntensityChangeBlock)(CALayer * _Nonnull, CGFloat); delegate void MDCFlexibleHeaderShadowIntensityChangeBlock(CALayer arg0, nfloat arg1); // @interface MDCFlexibleHeaderView : UIView [BaseType(typeof(UIView))] interface MDCFlexibleHeaderView { // @property (nonatomic, strong) CALayer * _Nullable shadowLayer; [NullAllowed, Export("shadowLayer", ArgumentSemantic.Strong)] CALayer ShadowLayer { get; set; } // -(void)setShadowLayer:(CALayer * _Nonnull)shadowLayer intensityDidChangeBlock:(MDCFlexibleHeaderShadowIntensityChangeBlock _Nonnull)block; [Export("setShadowLayer:intensityDidChangeBlock:")] void SetShadowLayer(CALayer shadowLayer, MDCFlexibleHeaderShadowIntensityChangeBlock block); // -(void)trackingScrollViewDidScroll; [Export("trackingScrollViewDidScroll")] void TrackingScrollViewDidScroll(); //void Scrolled(UIScrollView scrollView); // -(void)trackingScrollViewDidEndDraggingWillDecelerate:(BOOL)willDecelerate; [Export("trackingScrollViewDidEndDraggingWillDecelerate:")] void TrackingScrollViewDidEndDraggingWillDecelerate(bool willDecelerate); // -(void)trackingScrollViewDidEndDecelerating; [Export("trackingScrollViewDidEndDecelerating")] void TrackingScrollViewDidEndDecelerating(); // -(BOOL)trackingScrollViewWillEndDraggingWithVelocity:(CGPoint)velocity targetContentOffset:(CGPoint * _Nonnull)targetContentOffset; // HACK: was CGPoint* targetContentOffset [Export("trackingScrollViewWillEndDraggingWithVelocity:targetContentOffset:")] unsafe bool TrackingScrollViewWillEndDraggingWithVelocity(CGPoint velocity, CGPoint targetContentOffset); // -(void)trackingScrollWillChangeToScrollView:(UIScrollView * _Nullable)scrollView; [Export("trackingScrollWillChangeToScrollView:")] void TrackingScrollWillChangeToScrollView([NullAllowed] UIScrollView scrollView); // -(void)shiftHeaderOnScreenAnimated:(BOOL)animated; [Export("shiftHeaderOnScreenAnimated:")] void ShiftHeaderOnScreenAnimated(bool animated); // -(void)shiftHeaderOffScreenAnimated:(BOOL)animated; [Export("shiftHeaderOffScreenAnimated:")] void ShiftHeaderOffScreenAnimated(bool animated); // @property (readonly, nonatomic) BOOL prefersStatusBarHidden; [Export("prefersStatusBarHidden")] bool PrefersStatusBarHidden { get; } // -(void)interfaceOrientationWillChange; [Export("interfaceOrientationWillChange")] void InterfaceOrientationWillChange(); // -(void)interfaceOrientationIsChanging; [Export("interfaceOrientationIsChanging")] void InterfaceOrientationIsChanging(); // -(void)interfaceOrientationDidChange; [Export("interfaceOrientationDidChange")] void InterfaceOrientationDidChange(); // -(void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator> _Nonnull)coordinator; [Export("viewWillTransitionToSize:withTransitionCoordinator:")] void ViewWillTransitionToSize(CGSize size, IUIViewControllerTransitionCoordinator coordinator); // -(void)changeContentInsets:(MDCFlexibleHeaderChangeContentInsetsBlock _Nonnull)block; [Export("changeContentInsets:")] void ChangeContentInsets(MDCFlexibleHeaderChangeContentInsetsBlock block); // -(void)forwardTouchEventsForView:(UIView * _Nonnull)view; [Export("forwardTouchEventsForView:")] void ForwardTouchEventsForView(UIView view); // -(void)stopForwardingTouchEventsForView:(UIView * _Nonnull)view; [Export("stopForwardingTouchEventsForView:")] void StopForwardingTouchEventsForView(UIView view); // @property (readonly, nonatomic) MDCFlexibleHeaderScrollPhase scrollPhase; [Export("scrollPhase")] MDCFlexibleHeaderScrollPhase ScrollPhase { get; } // @property (readonly, nonatomic) CGFloat scrollPhaseValue; [Export("scrollPhaseValue")] nfloat ScrollPhaseValue { get; } // @property (readonly, nonatomic) CGFloat scrollPhasePercentage; [Export("scrollPhasePercentage")] nfloat ScrollPhasePercentage { get; } // @property (nonatomic) CGFloat minimumHeight; [Export("minimumHeight")] nfloat MinimumHeight { get; set; } // @property (nonatomic) CGFloat maximumHeight; [Export("maximumHeight")] nfloat MaximumHeight { get; set; } // @property (nonatomic) BOOL minMaxHeightIncludesSafeArea; [Export("minMaxHeightIncludesSafeArea")] bool MinMaxHeightIncludesSafeArea { get; set; } // @property (nonatomic) MDCFlexibleHeaderShiftBehavior shiftBehavior; [Export("shiftBehavior", ArgumentSemantic.Assign)] MDCFlexibleHeaderShiftBehavior ShiftBehavior { get; set; } // @property (nonatomic) MDCFlexibleHeaderContentImportance headerContentImportance; [Export("headerContentImportance", ArgumentSemantic.Assign)] MDCFlexibleHeaderContentImportance HeaderContentImportance { get; set; } // @property (nonatomic) BOOL canOverExtend; [Export("canOverExtend")] bool CanOverExtend { get; set; } // @property (nonatomic) BOOL statusBarHintCanOverlapHeader; [Export("statusBarHintCanOverlapHeader")] bool StatusBarHintCanOverlapHeader { get; set; } // @property (nonatomic) float visibleShadowOpacity; [Export("visibleShadowOpacity")] float VisibleShadowOpacity { get; set; } // @property (nonatomic, weak) UIScrollView * _Nullable trackingScrollView; [NullAllowed, Export("trackingScrollView", ArgumentSemantic.Weak)] UIScrollView TrackingScrollView { get; set; } // @property (nonatomic) BOOL trackingScrollViewIsBeingScrubbed; [Export("trackingScrollViewIsBeingScrubbed")] bool TrackingScrollViewIsBeingScrubbed { get; set; } // @property (getter = isInFrontOfInfiniteContent, nonatomic) BOOL inFrontOfInfiniteContent; [Export("inFrontOfInfiniteContent")] bool InFrontOfInfiniteContent { [Bind("isInFrontOfInfiniteContent")] get; set; } // @property (nonatomic) BOOL sharedWithManyScrollViews; [Export("sharedWithManyScrollViews")] bool SharedWithManyScrollViews { get; set; } // @property (nonatomic) BOOL contentIsTranslucent; [Export("contentIsTranslucent")] bool ContentIsTranslucent { get; set; } [Wrap("WeakDelegate")] [NullAllowed] MDCFlexibleHeaderViewDelegate Delegate { get; set; } // @property (nonatomic, weak) id<MDCFlexibleHeaderViewDelegate> _Nullable delegate; [NullAllowed, Export("delegate", ArgumentSemantic.Weak)] NSObject WeakDelegate { get; set; } // @property (nonatomic) MDCFlexibleHeaderShiftBehavior behavior __attribute__((deprecated("Use shiftBehavior instead."))); [Export("behavior", ArgumentSemantic.Assign)] MDCFlexibleHeaderShiftBehavior Behavior { get; set; } // @property (nonatomic, strong) UIView * _Nonnull contentView __attribute__((deprecated("Please register views directly to the flexible header."))); [Export("contentView", ArgumentSemantic.Strong)] UIView ContentView { get; set; } } // @protocol MDCFlexibleHeaderViewDelegate <NSObject> [Protocol, Model] [BaseType(typeof(NSObject))] interface MDCFlexibleHeaderViewDelegate { // @required -(void)flexibleHeaderViewNeedsStatusBarAppearanceUpdate:(MDCFlexibleHeaderView * _Nonnull)headerView; [Abstract] [Export("flexibleHeaderViewNeedsStatusBarAppearanceUpdate:")] void FlexibleHeaderViewNeedsStatusBarAppearanceUpdate(MDCFlexibleHeaderView headerView); // @required -(void)flexibleHeaderViewFrameDidChange:(MDCFlexibleHeaderView * _Nonnull)headerView; [Abstract] [Export("flexibleHeaderViewFrameDidChange:")] void FlexibleHeaderViewFrameDidChange(MDCFlexibleHeaderView headerView); } // @interface MDCFlexibleHeaderViewController : UIViewController <UIScrollViewDelegate, UITableViewDelegate> [BaseType(typeof(UIViewController))] interface MDCFlexibleHeaderViewController : IUIScrollViewDelegate, IUITableViewDelegate { // @property (readonly, nonatomic, strong) MDCFlexibleHeaderView * _Nonnull headerView; [Export("headerView", ArgumentSemantic.Strong)] MDCFlexibleHeaderView HeaderView { get; } [Wrap("WeakLayoutDelegate")] [NullAllowed] MDCFlexibleHeaderViewLayoutDelegate LayoutDelegate { get; set; } // @property (nonatomic, weak) id<MDCFlexibleHeaderViewLayoutDelegate> _Nullable layoutDelegate; [NullAllowed, Export("layoutDelegate", ArgumentSemantic.Weak)] NSObject WeakLayoutDelegate { get; set; } // -(BOOL)prefersStatusBarHidden; [Export("prefersStatusBarHidden")] //[Verify(MethodToProperty)] bool PrefersStatusBarHidden(); // -(UIStatusBarStyle)preferredStatusBarStyle; [Export("preferredStatusBarStyle")] //[Verify(MethodToProperty)] UIStatusBarStyle PreferredStatusBarStyle(); // -(void)updateTopLayoutGuide; [Export("updateTopLayoutGuide")] void UpdateTopLayoutGuide(); } // @protocol MDCFlexibleHeaderViewLayoutDelegate <NSObject> [Protocol, Model] [BaseType(typeof(NSObject))] interface MDCFlexibleHeaderViewLayoutDelegate { // @required -(void)flexibleHeaderViewController:(MDCFlexibleHeaderViewController * _Nonnull)flexibleHeaderViewController flexibleHeaderViewFrameDidChange:(MDCFlexibleHeaderView * _Nonnull)flexibleHeaderView; [Abstract] [Export("flexibleHeaderViewController:flexibleHeaderViewFrameDidChange:")] void FlexibleHeaderViewFrameDidChange(MDCFlexibleHeaderViewController flexibleHeaderViewController, MDCFlexibleHeaderView flexibleHeaderView); } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Drawing; using System.IO; using System.Linq; using System.Management.Automation; using System.Management.Automation.Provider; using System.Text; namespace Erwine.Leonard.T.GDIPlus.Commands { /// <summary> /// Open-Image /// </summary> [Cmdlet(VerbsCommon.Open, "Image", DefaultParameterSetName = ParameterSetName_Path, RemotingCapability = RemotingCapability.None)] [OutputType(typeof(Image))] public class Open_Image : PSCmdlet { #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member public const string ParameterSetName_Path = "Path"; public const string ParameterSetName_LiteralPath = "LiteralPath"; [Parameter(Mandatory = true, ParameterSetName = ParameterSetName_Path)] [ValidateNotNullOrEmpty()] [Alias("PSPath")] public string[] Path { get; set; } [Parameter(Mandatory = true, ParameterSetName = ParameterSetName_LiteralPath)] [ValidateNotNullOrEmpty()] public string LiteralPath { get; set; } private static void FromContentReader(Collection<IContentReader> readerCollection, Stream stream) { if (readerCollection == null || readerCollection.Count == 0) return; foreach (IContentReader reader in readerCollection) { IList item = reader.Read(1); if (item == null || item.Count == 0) continue; if (item[0] is byte) { stream.WriteByte((byte)(item[0])); FromBinaryContentReader(reader, stream); } else { UTF8Encoding binaryEncoding = new UTF8Encoding(false); WriteContent(item, stream, binaryEncoding); FromContentReader(reader, stream, binaryEncoding); } } } private static void WriteContent(IList item, Stream stream, UTF8Encoding binaryEncoding) { byte[] buffer; if (item is byte[]) buffer = (byte[])item; else if (item is IEnumerable<byte>) buffer = ((IEnumerable<byte>)item).ToArray(); else if (item is char[]) { char[] c = (char[])item; buffer = (c.Length == 0) ? new byte[0] : binaryEncoding.GetBytes(c, 0, c.Length); } else if (item is IEnumerable<char>) { char[] c = ((IEnumerable<char>)item).ToArray(); buffer = (c.Length == 0) ? new byte[0] : binaryEncoding.GetBytes(c, 0, c.Length); } else { foreach (object obj in item) { if (obj is byte) { stream.WriteByte((byte)obj); continue; } if (obj is byte[]) buffer = (byte[])item; else if (obj is IEnumerable<byte>) buffer = ((IEnumerable<byte>)obj).ToArray(); else if (obj is string) { string s = obj as string; buffer = (s.Length == 0) ? new byte[0] : binaryEncoding.GetBytes(s); } else if (obj is char) buffer = binaryEncoding.GetBytes(new char[] { (char)obj }, 0, 1); else if (obj is char[]) { char[] c = (char[])obj; buffer = (c.Length == 0) ? new byte[0] : binaryEncoding.GetBytes(c, 0, c.Length); } else if (obj is IEnumerable<char>) { char[] c = ((IEnumerable<char>)obj).ToArray(); buffer = (c.Length == 0) ? new byte[0] : binaryEncoding.GetBytes(c, 0, c.Length); } else { string s = LanguagePrimitives.ConvertTo(obj, typeof(string)) as string; buffer = (String.IsNullOrEmpty(s)) ? new byte[0] : binaryEncoding.GetBytes(s); } if (buffer.Length > 0) stream.Write(buffer, 0, buffer.Length); } return; } if (buffer.Length > 0) stream.Write(buffer, 0, buffer.Length); } private static void FromBinaryContentReader(IContentReader reader, Stream stream) { for (IList item = reader.Read(32768); item != null && item.Count > 0; item = reader.Read(32768)) { byte[] buffer; if (item is byte[]) buffer = (byte[])item; else if (item is IEnumerable<byte>) buffer = ((IEnumerable<byte>)item).ToArray(); else { for (int i = 0; i < item.Count; i++) { if (item[i] is byte) stream.WriteByte((byte)(item[i])); else { UTF8Encoding binaryEncoding = new UTF8Encoding(false); if (i == 0) WriteContent(item, stream, binaryEncoding); else WriteContent(item.Cast<object>().Skip(i).ToArray(), stream, binaryEncoding); FromContentReader(reader, stream, binaryEncoding); return; } } continue; } if (buffer.Length > 0) stream.Write(buffer, 0, buffer.Length); } } private static void FromContentReader(IContentReader reader, Stream stream, UTF8Encoding binaryEncoding) { for (IList item = reader.Read(32768); item != null && item.Count > 0; item = reader.Read(32768)) WriteContent(item, stream, binaryEncoding); } protected override void ProcessRecord() { Collection<PathInfo> pathCollection; if (ParameterSetName == ParameterSetName_Path) { if (Path == null) return; foreach (string psPath in Path) { if (String.IsNullOrEmpty(psPath)) continue; try { if ((pathCollection = SessionState.Path.GetResolvedPSPathFromPSPath(psPath)) == null || pathCollection.Count == 0) throw new ItemNotFoundException("\"" + psPath + "\" not found."); } catch (ItemNotFoundException e) { WriteError(new ErrorRecord(e, "Open_Image.NotFound", ErrorCategory.ObjectNotFound, psPath)); continue; } catch (System.Management.Automation.DriveNotFoundException e) { WriteError(new ErrorRecord(e, "Open_Image.NotFound", ErrorCategory.ObjectNotFound, psPath)); continue; } catch (System.IO.DriveNotFoundException e) { WriteError(new ErrorRecord(e, "Open_Image.NotFound", ErrorCategory.ObjectNotFound, psPath)); continue; } catch (Exception e) { WriteError(new ErrorRecord(e, "Open_Image.Path", ErrorCategory.InvalidArgument, psPath)); continue; } foreach (PathInfo path in pathCollection) { bool fileExists; try { fileExists = File.Exists(path.ProviderPath); } catch { fileExists = false; } if (fileExists) { try { WriteObject(Image.FromFile(path.ProviderPath)); } catch (Exception ex) { WriteError(new ErrorRecord(ex, "Open_Image.InvalidImage", ErrorCategory.InvalidData, psPath)); } } else ProcessPSPath(path.Path); } } } else { string path; try { path = SessionState.Path.GetUnresolvedProviderPathFromPSPath(LiteralPath); if (String.IsNullOrEmpty(path)) throw new ItemNotFoundException("\"" + LiteralPath + "\" not found."); } catch (ItemNotFoundException e) { WriteError(new ErrorRecord(e, "Open_Image.NotFound", ErrorCategory.ObjectNotFound, LiteralPath)); return; } catch (System.Management.Automation.DriveNotFoundException e) { WriteError(new ErrorRecord(e, "Open_Image.NotFound", ErrorCategory.ObjectNotFound, LiteralPath)); return; } catch (System.IO.DriveNotFoundException e) { WriteError(new ErrorRecord(e, "Open_Image.NotFound", ErrorCategory.ObjectNotFound, LiteralPath)); return; } catch (Exception e) { WriteError(new ErrorRecord(e, "Open_Image.Path", ErrorCategory.InvalidArgument, LiteralPath)); return; } bool fileExists; try { fileExists = File.Exists(path); } catch { fileExists = false; } if (fileExists) { try { WriteObject(Image.FromFile(path)); } catch (Exception ex) { WriteError(new ErrorRecord(ex, "Open_Image.InvalidImage", ErrorCategory.InvalidData, LiteralPath)); } } else ProcessPSPath(LiteralPath); } } private void ProcessPSPath(string path) { using (MemoryStream stream = new MemoryStream()) { Collection<IContentReader> readerCollection = null; try { readerCollection = InvokeProvider.Content.GetReader(path); } catch (PSNotSupportedException ex) { WriteError(new ErrorRecord(ex, "ContentAccessNotSupported", ErrorCategory.NotImplemented, path)); return; } catch (Exception ex) { WriteError(new ErrorRecord(ex, "Open_Image.OpenError", ErrorCategory.OpenError, path)); return; } try { FromContentReader(readerCollection, stream); } catch (Exception ex) { WriteError(new ErrorRecord(ex, "Open_Image.ReadError", ErrorCategory.ReadError, path)); return; } try { if (stream.Length == 0L) throw new FormatException("Item is empty."); stream.Seek(0L, SeekOrigin.Begin); WriteObject(Image.FromStream(stream)); } catch (Exception ex) { WriteError(new ErrorRecord(ex, "Open_Image.InvalidData", ErrorCategory.InvalidData, path)); } } } #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member } }
using System; using System.Collections.Generic; using System.Drawing; using MonoTouch.UIKit; using MonoTouch.CoreAnimation; using MonoTouch.CoreGraphics; namespace FrozenHeadersGrid { public class FrozenHeadersGridView : UIView { const float DefaultMinimumColumnWidth = 120; const float DefaultRowHeight = 55; const float DefaultHeaderColumnWidth = 60; const float DefaultHeaderRowHeight = 55; FrozenHeadersScrollView frozenHeadersScrollView; GridHeaderRowView gridHeaderRowView; GridHeaderColumnView gridHeaderColumnView; GridContentView gridContentView; int columnCount; int rowCount; IFrozenHeadersGridViewDelegate @delegate; public FrozenHeadersGridView(RectangleF frame) : base(frame) { MinimumColumnWidth = DefaultMinimumColumnWidth; RowHeight = DefaultRowHeight; Initialize(); } public float MinimumColumnWidth { get; set; } public float RowHeight { get; set; } public float HeaderColumnWidth { get { return frozenHeadersScrollView.HeaderColumnWidth; } set { frozenHeadersScrollView.HeaderColumnWidth = value; } } public float HeaderRowHeight { get { return frozenHeadersScrollView.HeaderRowHeight; } set { frozenHeadersScrollView.HeaderRowHeight = value; } } public IFrozenHeadersGridViewDelegate Delegate { get { return @delegate; } set { @delegate = value; UpdateContent(); } } public UIColor TintColor { set { gridHeaderRowView.TintColor = value; gridHeaderRowView.Gridlines.Color = value; gridHeaderColumnView.TintColor = value; gridHeaderColumnView.Gridlines.Color = value; } } public GridContentView ContentView { get { return gridContentView; } } public GridHeaderView HeaderRowView { get { return gridHeaderRowView; } } public GridHeaderView HeaderColumnView { get { return gridHeaderColumnView; } } public UIView HeaderCornerView { get { return frozenHeadersScrollView.HeaderCornerView; } } void Initialize() { BackgroundColor = UIColor.Clear; frozenHeadersScrollView = new FrozenHeadersScrollView(Bounds); HeaderRowHeight = DefaultHeaderRowHeight; HeaderColumnWidth = DefaultHeaderColumnWidth; gridHeaderRowView = new GridHeaderRowView(); gridHeaderRowView.Gridlines.Thickness = 1; frozenHeadersScrollView.HeaderRow.AddSubview(gridHeaderRowView); gridHeaderColumnView = new GridHeaderColumnView(); gridHeaderColumnView.Gridlines.Thickness = 1; frozenHeadersScrollView.HeaderColumn.AddSubview(gridHeaderColumnView); gridContentView = new GridContentView(); gridContentView.VerticalGridlines.Thickness = 1; gridContentView.HorizontalGridlines.Thickness = 1; frozenHeadersScrollView.ContentView.AddSubview(gridContentView); AddSubview(frozenHeadersScrollView); } public override void LayoutSubviews() { base.LayoutSubviews(); var columnWidth = CalcualteColumnWidth(); ContentView.CellSize = new SizeF(columnWidth, RowHeight); ContentView.GridSize = new Size(columnCount, rowCount); ContentView.LayoutIfNeeded(); frozenHeadersScrollView.Frame = Bounds; frozenHeadersScrollView.HeaderColumn.ContentSize = new SizeF(HeaderColumnWidth, RowHeight * rowCount); frozenHeadersScrollView.HeaderRow.ContentSize = new SizeF(columnWidth * columnCount, HeaderRowHeight); frozenHeadersScrollView.ContentView.ContentSize = ContentView.Frame.Size; frozenHeadersScrollView.LayoutIfNeeded(); gridHeaderRowView.CellSize = new SizeF(columnWidth, HeaderRowHeight); gridHeaderRowView.HeadersCount = columnCount; gridHeaderRowView.LayoutIfNeeded(); gridHeaderColumnView.CellSize = new SizeF(HeaderColumnWidth, RowHeight); gridHeaderColumnView.HeadersCount = rowCount; gridHeaderColumnView.LayoutIfNeeded(); } float CalcualteColumnWidth() { return columnCount > 0 ? (float)Math.Max(Math.Round((Bounds.Size.Width - HeaderColumnWidth) / columnCount), MinimumColumnWidth) : 0; } public virtual void UpdateContent() { Clear(); columnCount = @delegate.NumberOfColumns(this); rowCount = @delegate.NumberOfRows(this); UpdateHeaderRow(); UpdateHeaderColumn(); UpdateContentViews(); SetNeedsLayout(); } void Clear() { gridHeaderRowView.RemoveAll(); gridHeaderColumnView.RemoveAll(); gridContentView.RemoveAll(); } void UpdateHeaderRow() { gridHeaderRowView.HeadersCount = columnCount; for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) AddHeaderRowItemView(columnIndex); } void AddHeaderRowItemView(int columnIndex) { var item = CreateHeaderLabel(); item.Text = @delegate.TitleForColumn(this, columnIndex); item.TextAlignment = UITextAlignment.Center; gridHeaderRowView[columnIndex] = item; } void UpdateHeaderColumn() { gridHeaderColumnView.HeadersCount = rowCount; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) AddHeaderColumnItemView(rowIndex); } void AddHeaderColumnItemView(int rowIndex) { var item = CreateHeaderLabel(); item.Text = @delegate.TitleForRow(this, rowIndex); item.TextAlignment = UITextAlignment.Left; gridHeaderColumnView[rowIndex] = item; } UILabel CreateHeaderLabel() { return new UILabel { BackgroundColor = UIColor.Clear, TextColor = UIColor.White }; } void UpdateContentViews() { ContentView.GridSize = new Size(columnCount, rowCount); for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) UpdateContentViewRow(rowIndex); } void UpdateContentViewRow(int rowIndex) { for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) ContentView[new Point(columnIndex, rowIndex)] = @delegate.ViewForCell(this, new Point(columnIndex, rowIndex)); } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using Microsoft.WindowsAzure.Storage; using MS.Test.Common.MsTestLib; using StorageTestLib; using StorageBlob = Microsoft.WindowsAzure.Storage.Blob; using StorageType = Microsoft.WindowsAzure.Storage.Blob.BlobType; namespace Commands.Storage.ScenarioTest.Util { public class CloudBlobUtil { private CloudStorageAccount account; private StorageBlob.CloudBlobClient client; private Random random; private const int PageBlobUnitSize = 512; private static List<string> HttpsCopyHosts; public string ContainerName { get; private set; } public string BlobName { get; private set; } public StorageBlob.ICloudBlob Blob { get; private set; } public StorageBlob.CloudBlobContainer Container { get; private set; } private CloudBlobUtil() { } /// <summary> /// init cloud blob util /// </summary> /// <param name="account">storage account</param> public CloudBlobUtil(CloudStorageAccount account) { this.account = account; client = account.CreateCloudBlobClient(); random = new Random(); } /// <summary> /// Create a random container with a random blob /// </summary> public void SetupTestContainerAndBlob() { ContainerName = Utility.GenNameString("container"); BlobName = Utility.GenNameString("blob"); StorageBlob.CloudBlobContainer container = CreateContainer(ContainerName); Blob = CreateRandomBlob(container, BlobName); Container = container; } /// <summary> /// clean test container and blob /// </summary> public void CleanupTestContainerAndBlob() { if (String.IsNullOrEmpty(ContainerName)) { return; } RemoveContainer(ContainerName); ContainerName = string.Empty; BlobName = string.Empty; Blob = null; Container = null; } /// <summary> /// create a container with random properties and metadata /// </summary> /// <param name="containerName">container name</param> /// <returns>the created container object with properties and metadata</returns> public StorageBlob.CloudBlobContainer CreateContainer(string containerName = "") { if (String.IsNullOrEmpty(containerName)) { containerName = Utility.GenNameString("container"); } StorageBlob.CloudBlobContainer container = client.GetContainerReference(containerName); container.CreateIfNotExists(); //there is no properties to set container.FetchAttributes(); int minMetaCount = 1; int maxMetaCount = 5; int minMetaValueLength = 10; int maxMetaValueLength = 20; int count = random.Next(minMetaCount, maxMetaCount); for (int i = 0; i < count; i++) { string metaKey = Utility.GenNameString("metatest"); int valueLength = random.Next(minMetaValueLength, maxMetaValueLength); string metaValue = Utility.GenNameString("metavalue-", valueLength); container.Metadata.Add(metaKey, metaValue); } container.SetMetadata(); Test.Info(string.Format("create container '{0}'", containerName)); return container; } public StorageBlob.CloudBlobContainer CreateContainer(string containerName, StorageBlob.BlobContainerPublicAccessType permission) { StorageBlob.CloudBlobContainer container = CreateContainer(containerName); StorageBlob.BlobContainerPermissions containerPermission = new StorageBlob.BlobContainerPermissions(); containerPermission.PublicAccess = permission; container.SetPermissions(containerPermission); return container; } /// <summary> /// create mutiple containers /// </summary> /// <param name="containerNames">container names list</param> /// <returns>a list of container object</returns> public List<StorageBlob.CloudBlobContainer> CreateContainer(List<string> containerNames) { List<StorageBlob.CloudBlobContainer> containers = new List<StorageBlob.CloudBlobContainer>(); foreach (string name in containerNames) { containers.Add(CreateContainer(name)); } containers = containers.OrderBy(container => container.Name).ToList(); return containers; } /// <summary> /// remove specified container /// </summary> /// <param name="Container">Cloud blob container object</param> public void RemoveContainer(StorageBlob.CloudBlobContainer Container) { RemoveContainer(Container.Name); } /// <summary> /// remove specified container /// </summary> /// <param name="containerName">container name</param> public void RemoveContainer(string containerName) { StorageBlob.CloudBlobContainer container = client.GetContainerReference(containerName); container.DeleteIfExists(); Test.Info(string.Format("remove container '{0}'", containerName)); } /// <summary> /// remove a list containers /// </summary> /// <param name="containerNames">container names</param> public void RemoveContainer(List<string> containerNames) { foreach (string name in containerNames) { try { RemoveContainer(name); } catch (Exception e) { Test.Warn(string.Format("Can't remove container {0}. Exception: {1}", name, e.Message)); } } } /// <summary> /// create a new page blob with random properties and metadata /// </summary> /// <param name="container">CloudBlobContainer object</param> /// <param name="blobName">blob name</param> /// <returns>ICloudBlob object</returns> public StorageBlob.ICloudBlob CreatePageBlob(StorageBlob.CloudBlobContainer container, string blobName) { StorageBlob.CloudPageBlob pageBlob = container.GetPageBlobReference(blobName); int size = random.Next(1, 10) * PageBlobUnitSize; pageBlob.Create(size); byte[] buffer = new byte[size]; string md5sum = Convert.ToBase64String(Helper.GetMD5(buffer)); pageBlob.Properties.ContentMD5 = md5sum; GenerateBlobPropertiesAndMetaData(pageBlob); Test.Info(string.Format("create page blob '{0}' in container '{1}'", blobName, container.Name)); return pageBlob; } /// <summary> /// create a block blob with random properties and metadata /// </summary> /// <param name="container">CloudBlobContainer object</param> /// <param name="blobName">Block blob name</param> /// <returns>ICloudBlob object</returns> public StorageBlob.ICloudBlob CreateBlockBlob(StorageBlob.CloudBlobContainer container, string blobName) { StorageBlob.CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobName); int maxBlobSize = 1024 * 1024; string md5sum = string.Empty; int blobSize = random.Next(maxBlobSize); byte[] buffer = new byte[blobSize]; using (MemoryStream ms = new MemoryStream(buffer)) { random.NextBytes(buffer); //ms.Read(buffer, 0, buffer.Length); blockBlob.UploadFromStream(ms); md5sum = Convert.ToBase64String(Helper.GetMD5(buffer)); } blockBlob.Properties.ContentMD5 = md5sum; GenerateBlobPropertiesAndMetaData(blockBlob); Test.Info(string.Format("create block blob '{0}' in container '{1}'", blobName, container.Name)); return blockBlob; } /// <summary> /// generate random blob properties and metadata /// </summary> /// <param name="blob">ICloudBlob object</param> private void GenerateBlobPropertiesAndMetaData(StorageBlob.ICloudBlob blob) { blob.Properties.ContentEncoding = Utility.GenNameString("encoding"); blob.Properties.ContentLanguage = Utility.GenNameString("lang"); int minMetaCount = 1; int maxMetaCount = 5; int minMetaValueLength = 10; int maxMetaValueLength = 20; int count = random.Next(minMetaCount, maxMetaCount); for (int i = 0; i < count; i++) { string metaKey = Utility.GenNameString("metatest"); int valueLength = random.Next(minMetaValueLength, maxMetaValueLength); string metaValue = Utility.GenNameString("metavalue-", valueLength); blob.Metadata.Add(metaKey, metaValue); } blob.SetProperties(); blob.SetMetadata(); blob.FetchAttributes(); } /// <summary> /// Create a blob with specified blob type /// </summary> /// <param name="container">CloudBlobContainer object</param> /// <param name="blobName">Blob name</param> /// <param name="type">Blob type</param> /// <returns>ICloudBlob object</returns> public StorageBlob.ICloudBlob CreateBlob(StorageBlob.CloudBlobContainer container, string blobName, StorageBlob.BlobType type) { if (type == StorageBlob.BlobType.BlockBlob) { return CreateBlockBlob(container, blobName); } else { return CreatePageBlob(container, blobName); } } /// <summary> /// create a list of blobs with random properties/metadata/blob type /// </summary> /// <param name="container">CloudBlobContainer object</param> /// <param name="blobName">a list of blob names</param> /// <returns>a list of cloud page blobs</returns> public List<StorageBlob.ICloudBlob> CreateRandomBlob(StorageBlob.CloudBlobContainer container, List<string> blobNames) { List<StorageBlob.ICloudBlob> blobs = new List<StorageBlob.ICloudBlob>(); foreach (string blobName in blobNames) { blobs.Add(CreateRandomBlob(container, blobName)); } blobs = blobs.OrderBy(blob => blob.Name).ToList(); return blobs; } public List<StorageBlob.ICloudBlob> CreateRandomBlob(StorageBlob.CloudBlobContainer container) { int count = random.Next(1, 5); List<string> blobNames = new List<string>(); for (int i = 0; i < count; i++) { blobNames.Add(Utility.GenNameString("blob")); } return CreateRandomBlob(container, blobNames); } /// <summary> /// Create a list of blobs with random properties/metadata/blob type /// </summary> /// <param name="container">CloudBlobContainer object</param> /// <param name="blobName">Blob name</param> /// <returns>ICloudBlob object</returns> public StorageBlob.ICloudBlob CreateRandomBlob(StorageBlob.CloudBlobContainer container, string blobName) { int switchKey = 0; switchKey = random.Next(0, 2); if (switchKey == 0) { return CreatePageBlob(container, blobName); } else { return CreateBlockBlob(container, blobName); } } /// <summary> /// convert blob name into valid file name /// </summary> /// <param name="blobName">blob name</param> /// <returns>valid file name</returns> public string ConvertBlobNameToFileName(string blobName, string dir, DateTimeOffset? snapshotTime = null) { string fileName = blobName; //replace dirctionary Dictionary<string, string> replaceRules = new Dictionary<string, string>() { {"/", "\\"} }; foreach (KeyValuePair<string, string> rule in replaceRules) { fileName = fileName.Replace(rule.Key, rule.Value); } if (snapshotTime != null) { int index = fileName.LastIndexOf('.'); string prefix = string.Empty; string postfix = string.Empty; string timeStamp = string.Format("{0:u}", snapshotTime.Value); timeStamp = timeStamp.Replace(":", string.Empty).TrimEnd(new char[] { 'Z' }); if (index == -1) { prefix = fileName; postfix = string.Empty; } else { prefix = fileName.Substring(0, index); postfix = fileName.Substring(index); } fileName = string.Format("{0} ({1}){2}", prefix, timeStamp, postfix); } return Path.Combine(dir, fileName); } public string ConvertFileNameToBlobName(string fileName) { return fileName.Replace('\\', '/'); } /// <summary> /// list all the existing containers /// </summary> /// <returns>a list of cloudblobcontainer object</returns> public List<StorageBlob.CloudBlobContainer> GetExistingContainers() { StorageBlob.ContainerListingDetails details = StorageBlob.ContainerListingDetails.All; return client.ListContainers(string.Empty, details).ToList(); } /// <summary> /// get the number of existing container /// </summary> /// <returns></returns> public int GetExistingContainerCount() { return GetExistingContainers().Count; } /// <summary> /// Create a snapshot for the specified ICloudBlob object /// </summary> /// <param name="blob">ICloudBlob object</param> public StorageBlob.ICloudBlob SnapShot(StorageBlob.ICloudBlob blob) { StorageBlob.ICloudBlob snapshot = default(StorageBlob.ICloudBlob); switch (blob.BlobType) { case StorageBlob.BlobType.BlockBlob: snapshot = ((StorageBlob.CloudBlockBlob)blob).CreateSnapshot(); break; case StorageBlob.BlobType.PageBlob: snapshot = ((StorageBlob.CloudPageBlob)blob).CreateSnapshot(); break; default: throw new ArgumentException(string.Format("Unsupport blob type {0} when create snapshot", blob.BlobType)); } Test.Info(string.Format("Create snapshot for '{0}' at {1}", blob.Name, snapshot.SnapshotTime)); return snapshot; } public static void PackContainerCompareData(StorageBlob.CloudBlobContainer container, Dictionary<string, object> dic) { StorageBlob.BlobContainerPermissions permissions = container.GetPermissions(); dic["PublicAccess"] = permissions.PublicAccess; dic["Permission"] = permissions; dic["LastModified"] = container.Properties.LastModified; } public static void PackBlobCompareData(StorageBlob.ICloudBlob blob, Dictionary<string, object> dic) { dic["Length"] = blob.Properties.Length; dic["ContentType"] = blob.Properties.ContentType; dic["LastModified"] = blob.Properties.LastModified; dic["SnapshotTime"] = blob.SnapshotTime; } public static string ConvertCopySourceUri(string uri) { if (HttpsCopyHosts == null) { HttpsCopyHosts = new List<string>(); string httpsHosts = Test.Data.Get("HttpsCopyHosts"); string[] hosts = httpsHosts.Split(); foreach (string host in hosts) { if (!String.IsNullOrWhiteSpace(host)) { HttpsCopyHosts.Add(host); } } } //Azure always use https to copy from these hosts such windows.net bool useHttpsCopy = HttpsCopyHosts.Any(host => uri.IndexOf(host) != -1); if (useHttpsCopy) { return uri.Replace("http://", "https://"); } else { return uri; } } public static bool WaitForCopyOperationComplete(StorageBlob.ICloudBlob destBlob, int maxRetry = 100) { int retryCount = 0; int sleepInterval = 1000; //ms if (destBlob == null) { return false; } do { if (retryCount > 0) { Test.Info(String.Format("{0}th check current copy state and it's {1}. Wait for copy completion", retryCount, destBlob.CopyState.Status)); } Thread.Sleep(sleepInterval); destBlob.FetchAttributes(); retryCount++; } while (destBlob.CopyState.Status == StorageBlob.CopyStatus.Pending && retryCount < maxRetry); Test.Info(String.Format("Final Copy status is {0}", destBlob.CopyState.Status)); return destBlob.CopyState.Status != StorageBlob.CopyStatus.Pending; } public static StorageBlob.ICloudBlob GetBlob(StorageBlob.CloudBlobContainer container, string blobName, StorageType blobType) { StorageBlob.ICloudBlob blob = null; if (blobType == StorageType.BlockBlob) { blob = container.GetBlockBlobReference(blobName); } else { blob = container.GetPageBlobReference(blobName); } return blob; } } }
// 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.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements { public abstract class AbstractCodeType : AbstractCodeMember, EnvDTE.CodeType { internal AbstractCodeType( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) : base(state, fileCodeModel, nodeKey, nodeKind) { } internal AbstractCodeType( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) : base(state, fileCodeModel, nodeKind, name) { } private SyntaxNode GetNamespaceOrTypeNode() { return LookupNode().Ancestors() .Where(n => CodeModelService.IsNamespace(n) || CodeModelService.IsType(n)) .FirstOrDefault(); } internal INamedTypeSymbol LookupTypeSymbol() { return (INamedTypeSymbol)LookupSymbol(); } protected override object GetExtenderNames() { return CodeModelService.GetTypeExtenderNames(); } protected override object GetExtender(string name) { return CodeModelService.GetTypeExtender(name, this); } public override object Parent { get { var containingNamespaceOrType = GetNamespaceOrTypeNode(); return containingNamespaceOrType != null ? (object)FileCodeModel.CreateCodeElement<EnvDTE.CodeElement>(containingNamespaceOrType) : this.FileCodeModel; } } public override EnvDTE.CodeElements Children { get { return UnionCollection.Create(this.State, this, (ICodeElements)this.Attributes, (ICodeElements)InheritsImplementsCollection.Create(this.State, this, this.FileCodeModel, this.NodeKey), (ICodeElements)this.Members); } } public EnvDTE.CodeElements Bases { get { return BasesCollection.Create(this.State, this, this.FileCodeModel, this.NodeKey, interfaces: false); } } public EnvDTE80.vsCMDataTypeKind DataTypeKind { get { return CodeModelService.GetDataTypeKind(LookupNode(), (INamedTypeSymbol)LookupSymbol()); } set { UpdateNode(FileCodeModel.UpdateDataTypeKind, value); } } public EnvDTE.CodeElements DerivedTypes { get { throw new NotImplementedException(); } } public EnvDTE.CodeElements ImplementedInterfaces { get { return BasesCollection.Create(this.State, this, this.FileCodeModel, this.NodeKey, interfaces: true); } } public EnvDTE.CodeElements Members { get { return TypeCollection.Create(this.State, this, this.FileCodeModel, this.NodeKey); } } public EnvDTE.CodeNamespace Namespace { get { var namespaceNode = GetNamespaceOrTypeNode(); return namespaceNode != null ? FileCodeModel.CreateCodeElement<EnvDTE.CodeNamespace>(namespaceNode) : null; } } /// <returns>True if the current type inherits from or equals the type described by the /// given full name.</returns> /// <remarks>Equality is included in the check as per Dev10 Bug #725630</remarks> public bool get_IsDerivedFrom(string fullName) { var currentType = LookupTypeSymbol(); if (currentType == null) { return false; } var baseType = GetSemanticModel().Compilation.GetTypeByMetadataName(fullName); if (baseType == null) { return false; } return currentType.InheritsFromOrEquals(baseType); } public override bool IsCodeType { get { return true; } } public void RemoveMember(object element) { var codeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(element); if (codeElement == null) { codeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(this.Members.Item(element)); } if (codeElement == null) { throw new ArgumentException(ServicesVSResources.ElementIsNotValid, "element"); } codeElement.Delete(); } public EnvDTE.CodeElement AddBase(object @base, object position) { return FileCodeModel.EnsureEditor(() => { FileCodeModel.AddBase(LookupNode(), @base, position); var codeElements = this.Bases as ICodeElements; EnvDTE.CodeElement element; var hr = codeElements.Item(1, out element); if (ErrorHandler.Succeeded(hr)) { return element; } return null; }); } public EnvDTE.CodeInterface AddImplementedInterface(object @base, object position) { return FileCodeModel.EnsureEditor(() => { var name = FileCodeModel.AddImplementedInterface(LookupNode(), @base, position); var codeElements = this.ImplementedInterfaces as ICodeElements; EnvDTE.CodeElement element; var hr = codeElements.Item(name, out element); if (ErrorHandler.Succeeded(hr)) { return element as EnvDTE.CodeInterface; } return null; }); } public void RemoveBase(object element) { FileCodeModel.EnsureEditor(() => { FileCodeModel.RemoveBase(LookupNode(), element); }); } public void RemoveInterface(object element) { FileCodeModel.EnsureEditor(() => { FileCodeModel.RemoveImplementedInterface(LookupNode(), element); }); } } }
// // Mono.Xml.XPath.DTMXPathDocumentWriter2 // // Author: // Atsushi Enomoto <[email protected]> // // (C) 2004 Novell Inc. // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.IO; using System.Xml; using System.Xml.Schema; using System.Xml.XPath; namespace Mono.Xml.XPath { #if OUTSIDE_SYSTEM_XML public #else internal #endif class DTMXPathDocumentWriter2 : XmlWriter { public DTMXPathDocumentWriter2 (XmlNameTable nt, int defaultCapacity) { nameTable = nt == null ? new NameTable () : nt; nodeCapacity = defaultCapacity; attributeCapacity = nodeCapacity; nsCapacity = 10; idTable = new Hashtable (); nodes = new DTMXPathLinkedNode2 [nodeCapacity]; attributes = new DTMXPathAttributeNode2 [attributeCapacity]; namespaces = new DTMXPathNamespaceNode2 [nsCapacity]; atomicStringPool = new string [20]; nonAtomicStringPool = new string [20]; Init (); } XmlNameTable nameTable; int nodeCapacity; int attributeCapacity; int nsCapacity; // Linked Node DTMXPathLinkedNode2 [] nodes; // Attribute DTMXPathAttributeNode2 [] attributes; // NamespaceNode DTMXPathNamespaceNode2 [] namespaces; // String pool string [] atomicStringPool; int atomicIndex; string [] nonAtomicStringPool; int nonAtomicIndex; // idTable [string value] -> int nodeId Hashtable idTable; int nodeIndex; int attributeIndex; int nsIndex; int [] parentStack = new int [10]; int parentStackIndex = 0; // for attribute processing; should be reset per each element. bool hasAttributes; bool hasLocalNs; int attrIndexAtStart; int nsIndexAtStart; int lastNsInScope; // They are only used in Writer int prevSibling; WriteState state; bool openNamespace; bool isClosed; public DTMXPathDocument2 CreateDocument () { if (!isClosed) Close (); return new DTMXPathDocument2 (nameTable, nodes, attributes, namespaces, atomicStringPool, nonAtomicStringPool, idTable ); } public void Init () { // string pool index 0 to 3 are fixed. atomicStringPool [0] = nonAtomicStringPool [0] = ""; atomicStringPool [1] = nonAtomicStringPool [1] = null; atomicStringPool [2] = nonAtomicStringPool [2] = XmlNamespaces.XML; atomicStringPool [3] = nonAtomicStringPool [3] = XmlNamespaces.XMLNS; atomicIndex = nonAtomicIndex = 4; // index 0 is dummy. No node (including Root) is assigned to this index // So that we can easily compare index != 0 instead of index < 0. // (Difference between jnz or jbe in 80x86.) AddNode (0, 0, 0, XPathNodeType.All, "", false, "", "", "", "", "", 0, 0, 0); nodeIndex++; AddAttribute (0, "", "", "", "", 0, 0); AddNsNode (0, "", "", 0); nsIndex++; AddNsNode (1, "xml", XmlNamespaces.XML, 0); // add root. AddNode (0, 0, 0, XPathNodeType.Root, "", false, "", "", "", "", "", 1, 0, 0); this.nodeIndex = 1; this.lastNsInScope = 1; parentStack [0] = nodeIndex; state = WriteState.Content; } private int GetParentIndex () { return parentStack [parentStackIndex]; } private int GetPreviousSiblingIndex () { int parent = parentStack [parentStackIndex]; if (parent == nodeIndex) return 0; int prevSibling = nodeIndex; while (nodes [prevSibling].Parent != parent) prevSibling = nodes [prevSibling].Parent; return prevSibling; } private void UpdateTreeForAddition () { int parent = GetParentIndex (); prevSibling = GetPreviousSiblingIndex (); nodeIndex++; if (prevSibling != 0) nodes [prevSibling].NextSibling = nodeIndex; if (parent == nodeIndex - 1) nodes [parent].FirstChild = nodeIndex; } private void CloseStartElement () { if (attrIndexAtStart != attributeIndex) nodes [nodeIndex].FirstAttribute = attrIndexAtStart + 1; if (nsIndexAtStart != nsIndex) { nodes [nodeIndex].FirstNamespace = nsIndex; lastNsInScope = nsIndex; } parentStackIndex++; if (parentStack.Length == parentStackIndex) { int [] tmp = new int [parentStackIndex * 2]; Array.Copy (parentStack, tmp, parentStackIndex); parentStack = tmp; } parentStack [parentStackIndex] = nodeIndex; state = WriteState.Content; } #region Adding Nodes private int AtomicIndex (string s) { if (s == "") return 0; if (s == null) return 1; int i = 2; for (; i < atomicIndex; i++) if (Object.ReferenceEquals (s, atomicStringPool [i])) return i; if (atomicIndex == atomicStringPool.Length) { string [] newArr = new string [atomicIndex * 2]; Array.Copy (atomicStringPool, newArr, atomicIndex); atomicStringPool = newArr; } atomicStringPool [atomicIndex] = s; return atomicIndex++; } private int NonAtomicIndex (string s) { if (s == "") return 0; if (s == null) return 1; int i = 2; // Here we don't compare all the entries (sometimes it // goes extremely slow). int max = nonAtomicIndex < 100 ? nonAtomicIndex : 100; for (; i < max; i++) if (s == nonAtomicStringPool [i]) return i; if (nonAtomicIndex == nonAtomicStringPool.Length) { string [] newArr = new string [nonAtomicIndex * 2]; Array.Copy (nonAtomicStringPool, newArr, nonAtomicIndex); nonAtomicStringPool = newArr; } nonAtomicStringPool [nonAtomicIndex] = s; return nonAtomicIndex++; } private void SetNodeArrayLength (int size) { DTMXPathLinkedNode2 [] newArr = new DTMXPathLinkedNode2 [size]; Array.Copy (nodes, newArr, System.Math.Min (size, nodes.Length)); nodes = newArr; } private void SetAttributeArrayLength (int size) { DTMXPathAttributeNode2 [] newArr = new DTMXPathAttributeNode2 [size]; Array.Copy (attributes, newArr, System.Math.Min (size, attributes.Length)); attributes = newArr; } private void SetNsArrayLength (int size) { DTMXPathNamespaceNode2 [] newArr = new DTMXPathNamespaceNode2 [size]; Array.Copy (namespaces, newArr, System.Math.Min (size, namespaces.Length)); namespaces = newArr; } // Here followings are skipped: firstChild, nextSibling, public void AddNode (int parent, int firstAttribute, int previousSibling, XPathNodeType nodeType, string baseUri, bool isEmptyElement, string localName, string ns, string prefix, string value, string xmlLang, int namespaceNode, int lineNumber, int linePosition) { if (nodes.Length < nodeIndex + 1) { nodeCapacity *= 4; SetNodeArrayLength (nodeCapacity); } #if DTM_CLASS nodes [nodeIndex] = new DTMXPathLinkedNode2 (); #endif nodes [nodeIndex].FirstChild = 0; // dummy nodes [nodeIndex].Parent = parent; nodes [nodeIndex].FirstAttribute = firstAttribute; nodes [nodeIndex].PreviousSibling = previousSibling; nodes [nodeIndex].NextSibling = 0; // dummy nodes [nodeIndex].NodeType = nodeType; nodes [nodeIndex].BaseURI = AtomicIndex (baseUri); nodes [nodeIndex].IsEmptyElement = isEmptyElement; nodes [nodeIndex].LocalName = AtomicIndex (localName); nodes [nodeIndex].NamespaceURI = AtomicIndex (ns); nodes [nodeIndex].Prefix = AtomicIndex (prefix); nodes [nodeIndex].Value = NonAtomicIndex (value); nodes [nodeIndex].XmlLang = AtomicIndex (xmlLang); nodes [nodeIndex].FirstNamespace = namespaceNode; nodes [nodeIndex].LineNumber = lineNumber; nodes [nodeIndex].LinePosition = linePosition; } // Followings are skipped: nextAttribute, public void AddAttribute (int ownerElement, string localName, string ns, string prefix, string value, int lineNumber, int linePosition) { if (attributes.Length < attributeIndex + 1) { attributeCapacity *= 4; SetAttributeArrayLength (attributeCapacity); } #if DTM_CLASS attributes [attributeIndex] = new DTMXPathAttributeNode2 (); #endif attributes [attributeIndex].OwnerElement = ownerElement; attributes [attributeIndex].LocalName = AtomicIndex (localName); attributes [attributeIndex].NamespaceURI = AtomicIndex (ns); attributes [attributeIndex].Prefix = AtomicIndex (prefix); attributes [attributeIndex].Value = NonAtomicIndex (value); attributes [attributeIndex].LineNumber = lineNumber; attributes [attributeIndex].LinePosition = linePosition; } // Followings are skipped: nextNsNode (may be next attribute in the same element, or ancestors' nsNode) public void AddNsNode (int declaredElement, string name, string ns, int nextNs) { if (namespaces.Length < nsIndex + 1) { nsCapacity *= 4; SetNsArrayLength (nsCapacity); } #if DTM_CLASS namespaces [nsIndex] = new DTMXPathNamespaceNode2 (); #endif namespaces [nsIndex].DeclaredElement = declaredElement; namespaces [nsIndex].Name = AtomicIndex (name); namespaces [nsIndex].Namespace = AtomicIndex (ns); namespaces [nsIndex].NextNamespace = nextNs; } #endregion #region XmlWriter methods // They are not supported public override string XmlLang { get { return null; } } public override XmlSpace XmlSpace { get { return XmlSpace.None; } } public override WriteState WriteState { get { return state; } } public override void Close () { // Fixup arrays SetNodeArrayLength (nodeIndex + 1); SetAttributeArrayLength (attributeIndex + 1); SetNsArrayLength (nsIndex + 1); string [] newArr = new string [atomicIndex]; Array.Copy (atomicStringPool, newArr, atomicIndex); atomicStringPool = newArr; newArr = new string [nonAtomicIndex]; Array.Copy (nonAtomicStringPool, newArr, nonAtomicIndex); nonAtomicStringPool = newArr; isClosed = true; } public override void Flush () { // do nothing } public override string LookupPrefix (string ns) { int tmp = nsIndex; while (tmp != 0) { if (atomicStringPool [namespaces [tmp].Namespace] == ns) return atomicStringPool [namespaces [tmp].Name]; tmp = namespaces [tmp].NextNamespace; } return null; } public override void WriteCData (string data) { AddTextNode (data); } private void AddTextNode (string data) { switch (state) { case WriteState.Element: CloseStartElement (); break; case WriteState.Content: break; default: throw new InvalidOperationException ("Invalid document state for CDATA section: " + state); } // When text after text, just add the value, and return. if (nodes [nodeIndex].Parent == parentStack [parentStackIndex]) { switch (nodes [nodeIndex].NodeType) { case XPathNodeType.Text: case XPathNodeType.SignificantWhitespace: string value = nonAtomicStringPool [nodes [nodeIndex].Value] + data; nodes [nodeIndex].Value = NonAtomicIndex (value); if (IsWhitespace (value)) nodes [nodeIndex].NodeType = XPathNodeType.SignificantWhitespace; else nodes [nodeIndex].NodeType = XPathNodeType.Text; return; } } int parent = GetParentIndex (); UpdateTreeForAddition (); AddNode (parent, 0, // attribute prevSibling, XPathNodeType.Text, null, false, String.Empty, String.Empty, String.Empty, data, null, 0, // nsIndex 0, // line info 0); } private void CheckTopLevelNode () { switch (state) { case WriteState.Element: CloseStartElement (); break; case WriteState.Content: case WriteState.Prolog: case WriteState.Start: break; default: throw new InvalidOperationException ("Invalid document state for CDATA section: " + state); } } public override void WriteComment (string data) { CheckTopLevelNode (); int parent = GetParentIndex (); UpdateTreeForAddition (); AddNode (parent, 0, // attribute prevSibling, XPathNodeType.Comment, null, false, String.Empty, String.Empty, String.Empty, data, null, 0, // nsIndex 0, // line info 0); } public override void WriteProcessingInstruction (string name, string data) { CheckTopLevelNode (); int parent = GetParentIndex (); UpdateTreeForAddition (); AddNode (parent, 0, // attribute prevSibling, XPathNodeType.ProcessingInstruction, null, false, name, String.Empty, String.Empty, data, null, 0, // nsIndex 0, // line info 0); } public override void WriteWhitespace (string data) { CheckTopLevelNode (); int parent = GetParentIndex (); UpdateTreeForAddition (); AddNode (parent, 0, // attribute prevSibling, XPathNodeType.Whitespace, null, false, String.Empty, String.Empty, String.Empty, data, null, 0, // nsIndex 0, // line info 0); } public override void WriteStartDocument () { // do nothing } public override void WriteStartDocument (bool standalone) { // do nothing } public override void WriteEndDocument () { // do nothing } public override void WriteStartElement (string prefix, string localName, string ns) { if (ns == null) ns = String.Empty; else if (prefix == null && ns.Length > 0) prefix = LookupPrefix (ns); if (prefix == null) prefix = String.Empty; switch (state) { case WriteState.Element: CloseStartElement (); break; case WriteState.Start: case WriteState.Prolog: case WriteState.Content: break; default: throw new InvalidOperationException ("Invalid document state for writing element: " + state); } int parent = GetParentIndex (); UpdateTreeForAddition (); WriteStartElement (parent, prevSibling, prefix, localName, ns); state = WriteState.Element; } private void WriteStartElement (int parent, int previousSibling, string prefix, string localName, string ns) { PrepareStartElement (previousSibling); AddNode (parent, 0, // dummy:firstAttribute previousSibling, XPathNodeType.Element, null, false, localName, ns, prefix, "", // Element has no internal value. null, lastNsInScope, 0, 0); } private void PrepareStartElement (int previousSibling) { hasAttributes = false; hasLocalNs = false; attrIndexAtStart = attributeIndex; nsIndexAtStart = nsIndex; while (namespaces [lastNsInScope].DeclaredElement == previousSibling) { lastNsInScope = namespaces [lastNsInScope].NextNamespace; } } public override void WriteEndElement () { WriteEndElement (false); } public override void WriteFullEndElement () { WriteEndElement (true); } private void WriteEndElement (bool full) { switch (state) { case WriteState.Element: CloseStartElement (); break; case WriteState.Content: break; default: throw new InvalidOperationException ("Invalid state for writing EndElement: " + state); } parentStackIndex--; if (nodes [nodeIndex].NodeType == XPathNodeType.Element) { if (!full) nodes [nodeIndex].IsEmptyElement = true; } } public override void WriteStartAttribute (string prefix, string localName, string ns) { if (ns == null) ns = String.Empty; if (state != WriteState.Element) throw new InvalidOperationException ("Invalid document state for attribute: " + state); state = WriteState.Attribute; if (ns == XmlNamespaces.XMLNS) ProcessNamespace ((prefix == null || prefix == String.Empty) ? "" : localName, String.Empty); // dummy: Value should be completed else ProcessAttribute (prefix, localName, ns, String.Empty); // dummy: Value should be completed } private void ProcessNamespace (string prefix, string ns) { int nextTmp = hasLocalNs ? nsIndex : nodes [nodeIndex].FirstNamespace; nsIndex++; this.AddNsNode (nodeIndex, prefix, ns, nextTmp); hasLocalNs = true; openNamespace = true; } private void ProcessAttribute (string prefix, string localName, string ns, string value) { if (prefix == null && ns.Length > 0) prefix = LookupPrefix (ns); attributeIndex ++; this.AddAttribute (nodeIndex, localName, ns, prefix != null ? prefix : String.Empty, value, 0, 0); if (hasAttributes) attributes [attributeIndex - 1].NextAttribute = attributeIndex; else hasAttributes = true; } public override void WriteEndAttribute () { if (state != WriteState.Attribute) throw new InvalidOperationException (); openNamespace = false; state = WriteState.Element; } public override void WriteString (string text) { if (WriteState == WriteState.Attribute) { if (openNamespace) { string value = atomicStringPool [namespaces [nsIndex].Namespace] + text; namespaces [nsIndex].Namespace = AtomicIndex (value); } else { string value = nonAtomicStringPool [attributes [attributeIndex].Value] + text; attributes [attributeIndex].Value = NonAtomicIndex (value); } } else AddTextNode (text); } // Well, they cannot be supported, but actually used to // disable-output-escaping = "true" public override void WriteRaw (string data) { WriteString (data); } public override void WriteRaw (char [] data, int start, int len) { WriteString (new string (data, start, len)); } public override void WriteName (string name) { WriteString (name); } public override void WriteNmToken (string name) { WriteString (name); } public override void WriteBase64 (byte [] buffer, int index, int count) { WriteString (Convert.ToBase64String (buffer, index, count)); } public override void WriteBinHex (byte [] buffer, int index, int count) { throw new NotSupportedException (); } public override void WriteChars (char [] buffer, int index, int count) { WriteString (new string (buffer, index, count)); } public override void WriteCharEntity (char c) { WriteString (c.ToString ()); } public override void WriteDocType (string name, string pub, string sys, string intSubset) { throw new NotSupportedException (); } public override void WriteEntityRef (string name) { throw new NotSupportedException (); } public override void WriteQualifiedName (string localName, string ns) { string prefix = (ns == null || ns.Length == 0) ? null : LookupPrefix (ns); if (prefix != null && prefix.Length > 0) WriteString (prefix + ":" + localName); else WriteString (localName); } public override void WriteSurrogateCharEntity (char high, char low) { WriteString (high.ToString ()); WriteString (low.ToString ()); } private bool IsWhitespace (string data) { for (int i = 0; i < data.Length; i++) { switch (data [i]) { case ' ': case '\r': case '\n': case '\t': continue; default: return false; } } return true; } #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. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void ExtractInt321() { var test = new ExtractScalarTest__ExtractInt321(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ExtractScalarTest__ExtractInt321 { private struct TestStruct { public Vector128<Int32> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); return testStruct; } public void RunStructFldScenario(ExtractScalarTest__ExtractInt321 testClass) { var result = Sse41.Extract(_fld, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static Int32[] _data = new Int32[Op1ElementCount]; private static Vector128<Int32> _clsVar; private Vector128<Int32> _fld; private SimpleUnaryOpTest__DataTable<Int32, Int32> _dataTable; static ExtractScalarTest__ExtractInt321() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); } public ExtractScalarTest__ExtractInt321() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new SimpleUnaryOpTest__DataTable<Int32, Int32>(_data, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse41.Extract( Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse41.Extract( Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse41.Extract( Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse41).GetMethod(nameof(Sse41.Extract), new Type[] { typeof(Vector128<Int32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Int32)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse41).GetMethod(nameof(Sse41.Extract), new Type[] { typeof(Vector128<Int32>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Int32)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse41).GetMethod(nameof(Sse41.Extract), new Type[] { typeof(Vector128<Int32>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Int32)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse41.Extract( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr); var result = Sse41.Extract(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)); var result = Sse41.Extract(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var firstOp = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)); var result = Sse41.Extract(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ExtractScalarTest__ExtractInt321(); var result = Sse41.Extract(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse41.Extract(_fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse41.Extract(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Int32> firstOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray = new Int32[Op1ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray = new Int32[Op1ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(Int32[] firstOp, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((result[0] != firstOp[1])) { succeeded = false; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.Extract)}<Int32>(Vector128<Int32><9>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Globalization; using System.Linq; using PartsUnlimited.Models; namespace PartsUnlimited.Utils { public class PartsUnlimitedDbInitializer : CreateDatabaseIfNotExists<PartsUnlimitedContext> { protected override void Seed(PartsUnlimitedContext context) { // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. var categories = new List<Category>{ new Category { Name = "Brakes", Description = "Brakes description", ImageUrl = "product_brakes_disc.jpg" }, new Category { Name = "Lighting", Description = "Lighting description", ImageUrl = "product_lighting_headlight.jpg" }, new Category { Name = "Wheels & Tires", Description = "Wheels & Tires description", ImageUrl = "product_wheel_rim.jpg" }, new Category { Name = "Batteries", Description = "Batteries description", ImageUrl = "product_batteries_basic-battery.jpg" }, new Category { Name = "Oil", Description = "Oil description", ImageUrl = "product_oil_premium-oil.jpg" } }; context.Categories.AddOrUpdate(x => x.Name, categories.ToArray()); context.SaveChanges(); var categoriesMap = categories.ToDictionary(c => c.Name, c => c.CategoryId); var products = new List<Product>(); products.Add(new Product { SkuNumber = "LIG-0001", Created = DateTime.Now, Title = "Halogen Headlights (2 Pack)", CategoryId = categoriesMap["Lighting"], Price = 38.99M, SalePrice = 38.99M, ProductArtUrl = "product_lighting_headlight.jpg", ProductDetails = "{ \"Light Source\" : \"Halogen\", \"Assembly Required\": \"Yes\", \"Color\" : \"Clear\", \"Interior\" : \"Chrome\", \"Beam\": \"low and high\", \"Wiring harness included\" : \"Yes\", \"Bulbs Included\" : \"No\", \"Includes Parking Signal\" : \"Yes\"}", Description = "Our Halogen Headlights are made to fit majority of vehicles with our universal fitting mold. Product requires some assembly and includes light bulbs.", Inventory = 10, LeadTime = 0, RecommendationId = 1 }); products.Add(new Product { SkuNumber = "LIG-0002", Created = DateTime.Now, Title = "Bugeye Headlights (2 Pack)", CategoryId = categoriesMap["Lighting"], Price = 48.99M, SalePrice = 48.99M, ProductArtUrl = "product_lighting_bugeye-headlight.jpg", ProductDetails = "{ \"Light Source\" : \"Halogen\", \"Assembly Required\": \"Yes\", \"Color\" : \"Clear\", \"Interior\" : \"Chrome\", \"Beam\": \"low and high\", \"Wiring harness included\" : \"No\", \"Bulbs Included\" : \"Yes\", \"Includes Parking Signal\" : \"Yes\"}", Description = "Our Bugeye Headlights use Halogen light bulbs are made to fit into a standard Bugeye slot. Product requires some assembly and includes light bulbs.", Inventory = 7, LeadTime = 0, RecommendationId = 2 }); products.Add(new Product { SkuNumber = "LIG-0003", Created = DateTime.Now, Title = "Turn Signal Light Bulb", CategoryId = categoriesMap["Lighting"], Price = 6.49M, SalePrice = 6.49M, ProductArtUrl = "product_lighting_lightbulb.jpg", ProductDetails = "{ \"Color\" : \"Clear\", \"Fit\" : \"Universal\", \"Wattage\" : \"30 Watts\", \"Includes Socket\" : \"Yes\"}", Description = " Clear bulb that with a universal fitting for all headlights/taillights. Simple Installation, low wattage and a clear light for optimal visibility and efficiency.", Inventory = 18, LeadTime = 0, RecommendationId = 3 }); products.Add(new Product { SkuNumber = "WHE-0001", Created = DateTime.Now, Title = "Matte Finish Rim", CategoryId = categoriesMap["Wheels & Tires"], Price = 75.99M, SalePrice = 75.99M, ProductArtUrl = "product_wheel_rim.jpg", ProductDetails = "{ \"Material\" : \"Aluminum alloy\", \"Design\" : \"Spoke\", \"Spokes\" : \"9\", \"Number of Lugs\" : \"4\", \"Wheel Diameter\" : \"17 in.\", \"Color\" : \"Black\", \"Finish\" : \"Matte\" } ", Description = "A Parts Unlimited favorite, the Matte Finish Rim is affordable low profile style. Fits all low profile tires.", Inventory = 4, LeadTime = 0, RecommendationId = 4 }); products.Add(new Product { SkuNumber = "WHE-0002", Created = DateTime.Now, Title = "Blue Performance Alloy Rim", CategoryId = categoriesMap["Wheels & Tires"], Price = 88.99M, SalePrice = 88.99M, ProductArtUrl = "product_wheel_rim-blue.jpg", ProductDetails = "{ \"Material\" : \"Aluminum alloy\", \"Design\" : \"Spoke\", \"Spokes\" : \"5\", \"Number of Lugs\" : \"4\", \"Wheel Diameter\" : \"18 in.\", \"Color\" : \"Blue\", \"Finish\" : \"Glossy\" } ", Description = "Stand out from the crowd with a set of aftermarket blue rims to make you vehicle turn heads and at a price that will do the same.", Inventory = 8, LeadTime = 0, RecommendationId = 5 }); products.Add(new Product { SkuNumber = "WHE-0003", Created = DateTime.Now, Title = "High Performance Rim", CategoryId = categoriesMap["Wheels & Tires"], Price = 99.99M, SalePrice = 99.49M, ProductArtUrl = "product_wheel_rim-red.jpg", ProductDetails = "{ \"Material\" : \"Aluminum alloy\", \"Design\" : \"Spoke\", \"Spokes\" : \"12\", \"Number of Lugs\" : \"5\", \"Wheel Diameter\" : \"18 in.\", \"Color\" : \"Red\", \"Finish\" : \"Matte\" } ", Description = "Light Weight Rims with a twin cross spoke design for stability and reliable performance.", Inventory = 3, LeadTime = 0, RecommendationId = 6 }); products.Add(new Product { SkuNumber = "WHE-0004", Created = DateTime.Now, Title = "Wheel Tire Combo", CategoryId = categoriesMap["Wheels & Tires"], Price = 72.49M, SalePrice = 72.49M, ProductArtUrl = "product_wheel_tyre-wheel-combo.jpg", ProductDetails = "{ \"Material\" : \"Steel\", \"Design\" : \"Spoke\", \"Spokes\" : \"8\", \"Number of Lugs\" : \"4\", \"Wheel Diameter\" : \"19 in.\", \"Color\" : \"Gray\", \"Finish\" : \"Standard\", \"Pre-Assembled\" : \"Yes\" } ", Description = "For the endurance driver, take advantage of our best wearing tire yet. Composite rubber and a heavy duty steel rim.", Inventory = 0, LeadTime = 4, RecommendationId = 7 }); products.Add(new Product { SkuNumber = "WHE-0005", Created = DateTime.Now, Title = "Chrome Rim Tire Combo", CategoryId = categoriesMap["Wheels & Tires"], Price = 129.99M, SalePrice = 129.99M, ProductArtUrl = "product_wheel_tyre-rim-chrome-combo.jpg", ProductDetails = "{ \"Material\" : \"Aluminum alloy\", \"Design\" : \"Spoke\", \"Spokes\" : \"10\", \"Number of Lugs\" : \"5\", \"Wheel Diameter\" : \"17 in.\", \"Color\" : \"Silver\", \"Finish\" : \"Chrome\", \"Pre-Assembled\" : \"Yes\" } ", Description = "Save time and money with our ever popular wheel and tire combo. Pre-assembled and ready to go.", Inventory = 1, LeadTime = 0, RecommendationId = 8 }); products.Add(new Product { SkuNumber = "WHE-0006", Created = DateTime.Now, Title = "Wheel Tire Combo (4 Pack)", CategoryId = categoriesMap["Wheels & Tires"], Price = 219.99M, SalePrice = 219.99M, ProductArtUrl = "product_wheel_tyre-wheel-combo-pack.jpg", ProductDetails = "{ \"Material\" : \"Steel\", \"Design\" : \"Spoke\", \"Spokes\" : \"8\", \"Number of Lugs\" : \"5\", \"Wheel Diameter\" : \"19 in.\", \"Color\" : \"Gray\", \"Finish\" : \"Standard\", \"Pre-Assembled\" : \"Yes\" } ", Description = "Having trouble in the wet? Then try our special patent tire on a heavy duty steel rim. These wheels perform excellent in all conditions but were designed specifically for wet weather.", Inventory = 3, LeadTime = 0, RecommendationId = 9 }); products.Add(new Product { SkuNumber = "BRA-0001", Created = DateTime.Now, Title = "Disk and Pad Combo", CategoryId = categoriesMap["Brakes"], Price = 25.99M, SalePrice = 25.99M, ProductArtUrl = "product_brakes_disk-pad-combo.jpg", ProductDetails = "{ \"Disk Design\" : \"Cross Drill Slotted\", \" Pad Material\" : \"Ceramic\", \"Construction\" : \"Vented Rotor\", \"Diameter\" : \"10.3 in.\", \"Finish\" : \"Silver Zinc Plated\", \"Hat Finish\" : \"Silver Zinc Plated\", \"Material\" : \"Cast Iron\" }", Description = "Our brake disks and pads perform the best together. Better stopping distances without locking up, reduced rust and dusk.", Inventory = 0, LeadTime = 6, RecommendationId = 10 }); products.Add(new Product { SkuNumber = "BRA-0002", Created = DateTime.Now, Title = "Brake Rotor", CategoryId = categoriesMap["Brakes"], Price = 18.99M, SalePrice = 18.99M, ProductArtUrl = "product_brakes_disc.jpg", ProductDetails = "{ \"Disk Design\" : \"Cross Drill Slotted\", \"Construction\" : \"Vented Rotor\", \"Diameter\" : \"10.3 in.\", \"Finish\" : \"Silver Zinc Plated\", \"Hat Finish\" : \"Black E-coating\", \"Material\" : \"Cast Iron\" }", Description = "Our Brake Rotor Performs well in wet conditions with a smooth responsive feel. Machined to a high tolerance to ensure all of our Brake Rotors are safe and reliable.", Inventory = 4, LeadTime = 0, RecommendationId = 11 }); products.Add(new Product { SkuNumber = "BRA-0003", Created = DateTime.Now, Title = "Brake Disk and Calipers", CategoryId = categoriesMap["Brakes"], Price = 43.99M, SalePrice = 43.99M, ProductArtUrl = "product_brakes_disc-calipers-red.jpg", ProductDetails = "{\"Disk Design\" : \"Cross Drill Slotted\", \" Pad Material\" : \"Carbon Ceramic\", \"Construction\" : \"Vented Rotor\", \"Diameter\" : \"11.3 in.\", \"Bolt Pattern\": \"6 x 5.31 in.\", \"Finish\" : \"Silver Zinc Plated\", \"Material\" : \"Carbon Alloy\", \"Includes Brake Pads\" : \"Yes\" }", Description = "Upgrading your brakes can increase stopping power, reduce dust and noise. Our Disk Calipers exceed factory specification for the best performance.", Inventory = 2, LeadTime = 0, RecommendationId = 12 }); products.Add(new Product { SkuNumber = "BAT-0001", Created = DateTime.Now, Title = "12-Volt Calcium Battery", CategoryId = categoriesMap["Batteries"], Price = 129.99M, SalePrice = 129.99M, ProductArtUrl = "product_batteries_basic-battery.jpg", ProductDetails = "{ \"Type\": \"Calcium\", \"Volts\" : \"12\", \"Weight\" : \"22.9 lbs\", \"Size\" : \"7.7x5x8.6\", \"Cold Cranking Amps\" : \"510\" }", Description = "Calcium is the most common battery type. It is durable and has a long shelf and service life. They also provide high cold cranking amps.", Inventory = 9, LeadTime = 0, RecommendationId = 13 }); products.Add(new Product { SkuNumber = "BAT-0002", Created = DateTime.Now, Title = "Spiral Coil Battery", CategoryId = categoriesMap["Batteries"], Price = 154.99M, SalePrice = 154.99M, ProductArtUrl = "product_batteries_premium-battery.jpg", ProductDetails = "{ \"Type\": \"Spiral Coil\", \"Volts\" : \"12\", \"Weight\" : \"20.3 lbs\", \"Size\" : \"7.4x5.1x8.5\", \"Cold Cranking Amps\" : \"460\" }", Description = "Spiral Coil batteries are the preferred option for high performance Vehicles where extra toque is need for starting. They are more resistant to heat and higher charge rates than conventional batteries.", Inventory = 3, LeadTime = 0, RecommendationId = 14 }); products.Add(new Product { SkuNumber = "BAT-0003", Created = DateTime.Now, Title = "Jumper Leads", CategoryId = categoriesMap["Batteries"], Price = 16.99M, SalePrice = 16.99M, ProductArtUrl = "product_batteries_jumper-leads.jpg", ProductDetails = "{ \"length\" : \"6ft.\", \"Connection Type\" : \"Alligator Clips\", \"Fit\" : \"Universal\", \"Max Amp's\" : \"750\" }", Description = "Battery Jumper Leads have a built in surge protector and a includes a plastic carry case to keep them safe from corrosion.", Inventory = 6, LeadTime = 0, RecommendationId = 15 }); products.Add(new Product { SkuNumber = "OIL-0001", Created = DateTime.Now, Title = "Filter Set", CategoryId = categoriesMap["Oil"], Price = 28.99M, SalePrice = 28.99M, ProductArtUrl = "product_oil_filters.jpg", ProductDetails = "{ \"Filter Type\" : \"Canister and Cartridge\", \"Thread Size\" : \"0.75-16 in.\", \"Anti-Drainback Valve\" : \"Yes\"}", Description = "Ensure that your vehicle's engine has a longer life with our new filter set. Trapping more dirt to ensure old freely circulates through your engine.", Inventory = 3, LeadTime = 0, RecommendationId = 16 }); products.Add(new Product { SkuNumber = "OIL-0002", Created = DateTime.Now, Title = "Oil and Filter Combo", CategoryId = categoriesMap["Oil"], Price = 34.49M, SalePrice = 34.49M, ProductArtUrl = "product_oil_oil-filter-combo.jpg", ProductDetails = "{ \"Filter Type\" : \"Canister\", \"Thread Size\" : \"0.75-16 in.\", \"Anti-Drainback Valve\" : \"Yes\", \"Size\" : \"1.1 gal.\", \"Synthetic\" : \"No\" }", Description = "This Oil and Oil Filter combo is suitable for all types of passenger and light commercial vehicles. Providing affordable performance through excellent lubrication and breakdown resistance.", Inventory = 5, LeadTime = 0, RecommendationId = 17 }); products.Add(new Product { SkuNumber = "OIL-0003", Created = DateTime.Now, Title = "Synthetic Engine Oil", CategoryId = categoriesMap["Oil"], Price = 36.49M, SalePrice = 36.49M, ProductArtUrl = "product_oil_premium-oil.jpg", ProductDetails = "{ \"Size\" : \"1.1 Gal.\" , \"Synthetic \" : \"Yes\"}", Description = "This Oil is designed to reduce sludge deposits and metal friction throughout your cars engine. Provides performance no matter the condition or temperature.", Inventory = 11, LeadTime = 0, RecommendationId = 18 }); context.Products.AddOrUpdate(x => x.Title, products.ToArray()); context.SaveChanges(); var stores = Enumerable.Range(1, 20).Select(id => new Store { StoreId = id, Name = string.Format(CultureInfo.InvariantCulture, "Store{0}", id) }).ToList(); context.Stores.AddOrUpdate(x => x.Name, stores.ToArray()); context.SaveChanges(); var rainchecks = GetRainchecks(stores, products); context.RainChecks.AddOrUpdate(x => x.StoreId, rainchecks.ToArray()); context.SaveChanges(); } /// <summary> /// Generate an enumeration of rainchecks. The random number generator uses a seed to ensure /// that the sequence is consistent, but provides somewhat random looking data. /// </summary> public static IEnumerable<Raincheck> GetRainchecks(IList<Store> stores, IList<Product> products) { var random = new Random(1234); foreach (var store in stores) { for (var i = 0; i < random.Next(1, 5); i++) { yield return new Raincheck { StoreId = store.StoreId, Name = string.Format("John Smith{0}", random.Next()), Quantity = random.Next(1, 10), ProductId = products[random.Next(0, products.Count)].ProductId, SalePrice = Math.Round(100 * random.NextDouble(), 2) }; } } } } }
/* Copyright (c) 2006 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define USE_TRACING #define DEBUG using System; using System.IO; using System.Xml; using System.Collections; using System.Configuration; using System.Net; using NUnit.Framework; using Google.GData.Client; using Google.GData.Client.UnitTests; using Google.GData.Extensions; using Google.GData.Calendar; using Google.GData.AccessControl; using Google.Contacts; using Google.Documents; using System.Collections.Generic; namespace Google.GData.Client.LiveTests { [TestFixture] [Category("LiveTest")] public class OAuthTestSuite : BaseLiveTestClass { protected string oAuthConsumerKey; protected string oAuthConsumerSecret; protected string oAuthDomain; protected string oAuthUser; protected string oAuthToken; protected string oAuthTokenSecret; protected string oAuthScope; protected string oAuthSignatureMethod; /// <summary> /// default empty constructor /// </summary> public OAuthTestSuite() { } /// <summary> /// the setup method /// </summary> [SetUp] public override void InitTest() { Tracing.TraceCall(); base.InitTest(); } /// <summary> /// the end it all method /// </summary> [TearDown] public override void EndTest() { Tracing.ExitTracing(); } /// <summary> /// private void ReadConfigFile() /// </summary> /// <returns> </returns> protected override void ReadConfigFile() { base.ReadConfigFile(); if (unitTestConfiguration.Contains("OAUTHCONSUMERKEY")) { this.oAuthConsumerKey = (string)unitTestConfiguration["OAUTHCONSUMERKEY"]; } if (unitTestConfiguration.Contains("OAUTHCONSUMERSECRET")) { this.oAuthConsumerSecret = (string)unitTestConfiguration["OAUTHCONSUMERSECRET"]; } if (unitTestConfiguration.Contains("OAUTHDOMAIN")) { this.oAuthDomain = (string)unitTestConfiguration["OAUTHDOMAIN"]; } if (unitTestConfiguration.Contains("OAUTHUSER")) { this.oAuthUser = (string)unitTestConfiguration["OAUTHUSER"]; } if (unitTestConfiguration.Contains("OAUTHTOKEN")) { this.oAuthToken = (string)unitTestConfiguration["OAUTHTOKEN"]; } if (unitTestConfiguration.Contains("OAUTHTOKENSECRET")) { this.oAuthTokenSecret = (string)unitTestConfiguration["OAUTHTOKENSECRET"]; } if (unitTestConfiguration.Contains("OAUTHSCOPE")) { this.oAuthScope = (string)unitTestConfiguration["OAUTHSCOPE"]; } if (unitTestConfiguration.Contains("OAUTHSIGNATUREMETHOD")) { this.oAuthSignatureMethod = (string)unitTestConfiguration["OAUTHSIGNATUREMETHOD"]; } } /// <summary> /// Verifies the signature generation /// </summary> [Test] public void OAuthBaseSignatureTest() { Tracing.TraceMsg("Entering OAuthBaseSignatureTest"); Uri uri = new Uri("http://photos.example.net/photos?file=vacation.jpg&size=original"); string sig = OAuthBase.GenerateSignatureBase( uri, "dpf43f3p2l4k3l03", "nnch734d00sl2jdk", null, "GET", "1191242096", "kllo9940pd9333jh", "HMAC-SHA1"); Assert.AreEqual("GET&http%3A%2F%2Fphotos.example.net%2Fphotos&file%3Dvacation.jpg%26oauth_consumer_key%3Ddpf43f3p2l4k3l03%26oauth_nonce%3Dkllo9940pd9333jh%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1191242096%26oauth_token%3Dnnch734d00sl2jdk%26oauth_version%3D1.0%26size%3Doriginal", sig); // the file parameter is set twice, only the last value counts uri = new Uri("http://photos.example.net/photos?file=party.jpg&size=original&file=vacation.jpg"); sig = OAuthBase.GenerateSignatureBase( uri, "dpf43f3p2l4k3l03", "nnch734d00sl2jdk", null, "GET", "1191242096", "kllo9940pd9333jh", "HMAC-SHA1"); Assert.AreEqual("GET&http%3A%2F%2Fphotos.example.net%2Fphotos&file%3Dvacation.jpg%26oauth_consumer_key%3Ddpf43f3p2l4k3l03%26oauth_nonce%3Dkllo9940pd9333jh%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1191242096%26oauth_token%3Dnnch734d00sl2jdk%26oauth_version%3D1.0%26size%3Doriginal", sig); } /// <summary> /// Verifies the signature generation /// </summary> [Test] public void OAuthBaseGenerateOAuthSignatureTest() { Tracing.TraceMsg("Entering OAuthBaseGenerateOAuthSignatureTest"); string sig = OAuthBase.GenerateOAuthSignatureEncoded("djr9rjt0jd78jf88", ""); Assert.AreEqual("djr9rjt0jd78jf88%26", sig); sig = OAuthBase.GenerateOAuthSignatureEncoded("djr9rjt0jd78jf88", "jjd99$tj88uiths3"); Assert.AreEqual("djr9rjt0jd78jf88%26jjd99%2524tj88uiths3", sig); sig = OAuthBase.GenerateOAuthSignatureEncoded("djr9rjt0jd78jf88", "jjd999tj88uiths3"); Assert.AreEqual("djr9rjt0jd78jf88%26jjd999tj88uiths3", sig); } /// <summary> /// Verifies the signed signature generation /// </summary> [Test] public void OAuthBaseSigningTest() { Tracing.TraceMsg("Entering OAuthBaseSigningTest"); Uri uri = new Uri("http://photos.example.net/photos?file=vacation.jpg&size=original"); string sig = OAuthBase.GenerateSignature( uri, "dpf43f3p2l4k3l03", "kd94hf93k423kf44", "nnch734d00sl2jdk", "pfkkdhi9sl3r4s00", "GET", "1191242096", "kllo9940pd9333jh", OAuthBase.HMACSHA1SignatureType); Assert.AreEqual("tR3+Ty81lMeYAr/Fid0kMTYa/WM=", sig); } /// <summary> /// runs an authentication test with 2 legged oauth /// </summary> [Test] public void OAuth2LeggedAuthenticationTest() { Tracing.TraceMsg("Entering OAuth2LeggedAuthenticationTest"); CalendarService service = new CalendarService("OAuthTestcode"); GOAuthRequestFactory requestFactory = new GOAuthRequestFactory("cl", "OAuthTestcode"); requestFactory.ConsumerKey = this.oAuthConsumerKey; requestFactory.ConsumerSecret = this.oAuthConsumerSecret; requestFactory.UseSSL = true; service.RequestFactory = requestFactory; CalendarEntry calendar = new CalendarEntry(); calendar.Title.Text = "Test OAuth"; OAuthUri postUri = new OAuthUri("https://www.google.com/calendar/feeds/default/owncalendars/full", this.oAuthUser, this.oAuthDomain); CalendarEntry createdCalendar = (CalendarEntry)service.Insert(postUri, calendar); } [Test] public void OAuth2LeggedContactsTest() { Tracing.TraceMsg("Entering OAuth2LeggedContactsTest"); RequestSettings rs = new RequestSettings(this.ApplicationName, this.oAuthConsumerKey, this.oAuthConsumerSecret, this.oAuthUser, this.oAuthDomain); ContactsRequest cr = new ContactsRequest(rs); Feed<Contact> f = cr.GetContacts(); // modify one foreach (Contact c in f.Entries) { c.Title = "new title"; cr.Update(c); break; } Contact entry = new Contact(); entry.AtomEntry = ObjectModelHelper.CreateContactEntry(1); entry.PrimaryEmail.Address = "[email protected]"; Contact e = cr.Insert(f, entry); cr.Delete(e); } [Test] public void OAuth2LeggedDocumentsTest() { Tracing.TraceMsg("Entering OAuth2LeggedDocumentsTest"); RequestSettings rs = new RequestSettings(this.ApplicationName, this.oAuthConsumerKey, this.oAuthConsumerSecret, this.oAuthUser, this.oAuthDomain); DocumentsRequest dr = new DocumentsRequest(rs); Feed<Document> f = dr.GetDocuments(); // modify one foreach (Document d in f.Entries) { string s = d.AtomEntry.EditUri.ToString(); d.AtomEntry.EditUri = new AtomUri(s.Replace("@", "%40")); dr.Update(d); AclQuery q = new AclQuery(); q.Uri = d.AccessControlList; Feed<Google.AccessControl.Acl> facl = dr.Get<Google.AccessControl.Acl>(q); foreach (Google.AccessControl.Acl a in facl.Entries) { s = a.AclEntry.EditUri.ToString(); a.AclEntry.EditUri = new AtomUri(s.Replace("@", "%40")); dr.Update(a); } } } /// <summary> /// runs an authentication test using OAUTH, inserts lots of new contacts /// and deletes them again /// </summary> [Test] public void OAuth2LeggedModelContactsBatchInsertTest() { const int numberOfInserts = 10; Tracing.TraceMsg("Entering OAuth2LeggedModelContactsBatchInsertTest"); RequestSettings rs = new RequestSettings(this.ApplicationName, this.oAuthConsumerKey, this.oAuthConsumerSecret, this.oAuthUser, this.oAuthDomain); ContactsTestSuite.DeleteAllContacts(rs); rs.AutoPaging = true; ContactsRequest cr = new ContactsRequest(rs); Feed<Contact> f = cr.GetContacts(); int originalCount = f.TotalResults; PhoneNumber p = null; List<Contact> inserted = new List<Contact>(); if (f != null) { Assert.IsTrue(f.Entries != null, "the contacts needs entries"); for (int i = 0; i < numberOfInserts; i++) { Contact entry = new Contact(); entry.AtomEntry = ObjectModelHelper.CreateContactEntry(i); entry.PrimaryEmail.Address = "joe" + i.ToString() + "@doe.com"; p = entry.PrimaryPhonenumber; inserted.Add(cr.Insert(f, entry)); } } List<Contact> list = new List<Contact>(); f = cr.GetContacts(); foreach (Contact e in f.Entries) { list.Add(e); } Assert.AreEqual(numberOfInserts, inserted.Count); // now delete them again ContactsTestSuite.DeleteList(inserted, cr, new Uri(f.AtomFeed.Batch)); } /// <summary> /// runs an authentication test with 3-legged oauth /// </summary> [Test] public void OAuth3LeggedAuthenticationTest() { Tracing.TraceMsg("Entering OAuth3LeggedAuthenticationTest"); CalendarService service = new CalendarService("OAuthTestcode"); OAuthParameters parameters = new OAuthParameters() { ConsumerKey = this.oAuthConsumerKey, ConsumerSecret = this.oAuthConsumerSecret, Token = this.oAuthToken, TokenSecret = this.oAuthTokenSecret, Scope = this.oAuthScope, SignatureMethod = this.oAuthSignatureMethod }; GOAuthRequestFactory requestFactory = new GOAuthRequestFactory("cl", "OAuthTestcode", parameters); service.RequestFactory = requestFactory; CalendarEntry calendar = new CalendarEntry(); calendar.Title.Text = "Test OAuth"; Uri postUri = new Uri("https://www.google.com/calendar/feeds/default/owncalendars/full"); CalendarEntry createdCalendar = (CalendarEntry)service.Insert(postUri, calendar); // delete the new entry createdCalendar.Delete(); } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System { using System; using System.Reflection; using System.Runtime; using System.Threading; using System.Runtime.Serialization; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Diagnostics.Contracts; [Serializable] [ClassInterface(ClassInterfaceType.AutoDual)] [System.Runtime.InteropServices.ComVisible(true)] public abstract class Delegate : ICloneable, ISerializable { // _target is the object we will invoke on [System.Security.SecurityCritical] internal Object _target; // MethodBase, either cached after first request or assigned from a DynamicMethod // For open delegates to collectible types, this may be a LoaderAllocator object [System.Security.SecurityCritical] internal Object _methodBase; // _methodPtr is a pointer to the method we will invoke // It could be a small thunk if this is a static or UM call [System.Security.SecurityCritical] internal IntPtr _methodPtr; // In the case of a static method passed to a delegate, this field stores // whatever _methodPtr would have stored: and _methodPtr points to a // small thunk which removes the "this" pointer before going on // to _methodPtrAux. [System.Security.SecurityCritical] internal IntPtr _methodPtrAux; // This constructor is called from the class generated by the // compiler generated code [System.Security.SecuritySafeCritical] // auto-generated protected Delegate(Object target,String method) { if (target == null) throw new ArgumentNullException("target"); if (method == null) throw new ArgumentNullException("method"); Contract.EndContractBlock(); // This API existed in v1/v1.1 and only expected to create closed // instance delegates. Constrain the call to BindToMethodName to // such and don't allow relaxed signature matching (which could make // the choice of target method ambiguous) for backwards // compatibility. The name matching was case sensitive and we // preserve that as well. if (!BindToMethodName(target, (RuntimeType)target.GetType(), method, DelegateBindingFlags.InstanceMethodOnly | DelegateBindingFlags.ClosedDelegateOnly)) throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTargMeth")); } // This constructor is called from a class to generate a // delegate based upon a static method name and the Type object // for the class defining the method. [System.Security.SecuritySafeCritical] // auto-generated protected unsafe Delegate(Type target,String method) { if (target == null) throw new ArgumentNullException("target"); if (target.IsGenericType && target.ContainsGenericParameters) throw new ArgumentException(Environment.GetResourceString("Arg_UnboundGenParam"), "target"); if (method == null) throw new ArgumentNullException("method"); Contract.EndContractBlock(); RuntimeType rtTarget = target as RuntimeType; if (rtTarget == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "target"); // This API existed in v1/v1.1 and only expected to create open // static delegates. Constrain the call to BindToMethodName to such // and don't allow relaxed signature matching (which could make the // choice of target method ambiguous) for backwards compatibility. // The name matching was case insensitive (no idea why this is // different from the constructor above) and we preserve that as // well. BindToMethodName(null, rtTarget, method, DelegateBindingFlags.StaticMethodOnly | DelegateBindingFlags.OpenDelegateOnly | DelegateBindingFlags.CaselessMatching); } // Protect the default constructor so you can't build a delegate private Delegate() { } public Object DynamicInvoke(params Object[] args) { // Theoretically we should set up a LookForMyCaller stack mark here and pass that along. // But to maintain backward compatibility we can't switch to calling an // internal overload of DynamicInvokeImpl that takes a stack mark. // Fortunately the stack walker skips all the reflection invocation frames including this one. // So this method will never be returned by the stack walker as the caller. // See SystemDomain::CallersMethodCallbackWithStackMark in AppDomain.cpp. return DynamicInvokeImpl(args); } [System.Security.SecuritySafeCritical] // auto-generated protected virtual object DynamicInvokeImpl(object[] args) { RuntimeMethodHandleInternal method = new RuntimeMethodHandleInternal(GetInvokeMethod()); RuntimeMethodInfo invoke = (RuntimeMethodInfo)RuntimeType.GetMethodBase((RuntimeType)this.GetType(), method); return invoke.UnsafeInvoke(this, BindingFlags.Default, null, args, null); } [System.Security.SecuritySafeCritical] // auto-generated public override bool Equals(Object obj) { if (obj == null || !InternalEqualTypes(this, obj)) return false; Delegate d = (Delegate) obj; // do an optimistic check first. This is hopefully cheap enough to be worth if (_target == d._target && _methodPtr == d._methodPtr && _methodPtrAux == d._methodPtrAux) return true; // even though the fields were not all equals the delegates may still match // When target carries the delegate itself the 2 targets (delegates) may be different instances // but the delegates are logically the same // It may also happen that the method pointer was not jitted when creating one delegate and jitted in the other // if that's the case the delegates may still be equals but we need to make a more complicated check if (_methodPtrAux.IsNull()) { if (!d._methodPtrAux.IsNull()) return false; // different delegate kind // they are both closed over the first arg if (_target != d._target) return false; // fall through method handle check } else { if (d._methodPtrAux.IsNull()) return false; // different delegate kind // Ignore the target as it will be the delegate instance, though it may be a different one /* if (_methodPtr != d._methodPtr) return false; */ if (_methodPtrAux == d._methodPtrAux) return true; // fall through method handle check } // method ptrs don't match, go down long path // if (_methodBase == null || d._methodBase == null || !(_methodBase is MethodInfo) || !(d._methodBase is MethodInfo)) return Delegate.InternalEqualMethodHandles(this, d); else return _methodBase.Equals(d._methodBase); } public override int GetHashCode() { // // this is not right in the face of a method being jitted in one delegate and not in another // in that case the delegate is the same and Equals will return true but GetHashCode returns a // different hashcode which is not true. /* if (_methodPtrAux.IsNull()) return unchecked((int)((long)this._methodPtr)); else return unchecked((int)((long)this._methodPtrAux)); */ return GetType().GetHashCode(); } public static Delegate Combine(Delegate a, Delegate b) { if ((Object)a == null) // cast to object for a more efficient test return b; return a.CombineImpl(b); } [System.Runtime.InteropServices.ComVisible(true)] public static Delegate Combine(params Delegate[] delegates) { if (delegates == null || delegates.Length == 0) return null; Delegate d = delegates[0]; for (int i = 1; i < delegates.Length; i++) d = Combine(d,delegates[i]); return d; } public virtual Delegate[] GetInvocationList() { Delegate[] d = new Delegate[1]; d[0] = this; return d; } // This routine will return the method public MethodInfo Method { get { return GetMethodImpl(); } } [System.Security.SecuritySafeCritical] // auto-generated protected virtual MethodInfo GetMethodImpl() { if ((_methodBase == null) || !(_methodBase is MethodInfo)) { IRuntimeMethodInfo method = FindMethodHandle(); RuntimeType declaringType = RuntimeMethodHandle.GetDeclaringType(method); // need a proper declaring type instance method on a generic type if (RuntimeTypeHandle.IsGenericTypeDefinition(declaringType) || RuntimeTypeHandle.HasInstantiation(declaringType)) { bool isStatic = (RuntimeMethodHandle.GetAttributes(method) & MethodAttributes.Static) != (MethodAttributes)0; if (!isStatic) { if (_methodPtrAux == (IntPtr)0) { // The target may be of a derived type that doesn't have visibility onto the // target method. We don't want to call RuntimeType.GetMethodBase below with that // or reflection can end up generating a MethodInfo where the ReflectedType cannot // see the MethodInfo itself and that breaks an important invariant. But the // target type could include important generic type information we need in order // to work out what the exact instantiation of the method's declaring type is. So // we'll walk up the inheritance chain (which will yield exactly instantiated // types at each step) until we find the declaring type. Since the declaring type // we get from the method is probably shared and those in the hierarchy we're // walking won't be we compare using the generic type definition forms instead. Type currentType = _target.GetType(); Type targetType = declaringType.GetGenericTypeDefinition(); while (currentType != null) { if (currentType.IsGenericType && currentType.GetGenericTypeDefinition() == targetType) { declaringType = currentType as RuntimeType; break; } currentType = currentType.BaseType; } // RCWs don't need to be "strongly-typed" in which case we don't find a base type // that matches the declaring type of the method. This is fine because interop needs // to work with exact methods anyway so declaringType is never shared at this point. BCLDebug.Assert(currentType != null || _target.GetType().IsCOMObject, "The class hierarchy should declare the method"); } else { // it's an open one, need to fetch the first arg of the instantiation MethodInfo invoke = this.GetType().GetMethod("Invoke"); declaringType = (RuntimeType)invoke.GetParameters()[0].ParameterType; } } } _methodBase = (MethodInfo)RuntimeType.GetMethodBase(declaringType, method); } return (MethodInfo)_methodBase; } public Object Target { get { return GetTarget(); } } [System.Security.SecuritySafeCritical] // auto-generated public static Delegate Remove(Delegate source, Delegate value) { if (source == null) return null; if (value == null) return source; if (!InternalEqualTypes(source, value)) throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTypeMis")); return source.RemoveImpl(value); } public static Delegate RemoveAll(Delegate source, Delegate value) { Delegate newDelegate = null; do { newDelegate = source; source = Remove(source, value); } while (newDelegate != source); return newDelegate; } protected virtual Delegate CombineImpl(Delegate d) { throw new MulticastNotSupportedException(Environment.GetResourceString("Multicast_Combine")); } protected virtual Delegate RemoveImpl(Delegate d) { return (d.Equals(this)) ? null : this; } public virtual Object Clone() { return MemberwiseClone(); } // V1 API. public static Delegate CreateDelegate(Type type, Object target, String method) { return CreateDelegate(type, target, method, false, true); } // V1 API. public static Delegate CreateDelegate(Type type, Object target, String method, bool ignoreCase) { return CreateDelegate(type, target, method, ignoreCase, true); } #if FEATURE_LEGACYNETCF private static void CheckGetMethodInfo_Quirk(Type type, Type target, String method, BindingFlags bindingFlags) { ParameterInfo[] parameters = type.GetMethod("Invoke", BindingFlags.Public | BindingFlags.Instance).GetParameters(); Type[] types = new Type[parameters.Length]; for (Int32 i = 0; i < parameters.Length; i++) types[i] = parameters[i].ParameterType; MethodInfo mInfo = target.GetMethod(method, bindingFlags, null, types, null); if (mInfo == null) throw new MissingMethodException(target.FullName, method); } #endif // V1 API. [System.Security.SecuritySafeCritical] // auto-generated public static Delegate CreateDelegate(Type type, Object target, String method, bool ignoreCase, bool throwOnBindFailure) { if (type == null) throw new ArgumentNullException("type"); if (target == null) throw new ArgumentNullException("target"); if (method == null) throw new ArgumentNullException("method"); Contract.EndContractBlock(); RuntimeType rtType = type as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "type"); if (!rtType.IsDelegate()) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"),"type"); #if FEATURE_LEGACYNETCF if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) CheckGetMethodInfo_Quirk(type, target.GetType(), method, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | (ignoreCase?BindingFlags.IgnoreCase:0)); #endif Delegate d = InternalAlloc(rtType); // This API existed in v1/v1.1 and only expected to create closed // instance delegates. Constrain the call to BindToMethodName to such // and don't allow relaxed signature matching (which could make the // choice of target method ambiguous) for backwards compatibility. // We never generate a closed over null delegate and this is // actually enforced via the check on target above, but we pass // NeverCloseOverNull anyway just for clarity. if (!d.BindToMethodName(target, (RuntimeType)target.GetType(), method, DelegateBindingFlags.InstanceMethodOnly | DelegateBindingFlags.ClosedDelegateOnly | DelegateBindingFlags.NeverCloseOverNull | (ignoreCase ? DelegateBindingFlags.CaselessMatching : 0))) { if (throwOnBindFailure) throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTargMeth")); d = null; } return d; } // V1 API. public static Delegate CreateDelegate(Type type, Type target, String method) { return CreateDelegate(type, target, method, false, true); } // V1 API. public static Delegate CreateDelegate(Type type, Type target, String method, bool ignoreCase) { return CreateDelegate(type, target, method, ignoreCase, true); } // V1 API. [System.Security.SecuritySafeCritical] // auto-generated public static Delegate CreateDelegate(Type type, Type target, String method, bool ignoreCase, bool throwOnBindFailure) { if (type == null) throw new ArgumentNullException("type"); if (target == null) throw new ArgumentNullException("target"); if (target.IsGenericType && target.ContainsGenericParameters) throw new ArgumentException(Environment.GetResourceString("Arg_UnboundGenParam"), "target"); if (method == null) throw new ArgumentNullException("method"); Contract.EndContractBlock(); RuntimeType rtType = type as RuntimeType; RuntimeType rtTarget = target as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "type"); if (rtTarget == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "target"); if (!rtType.IsDelegate()) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"),"type"); #if FEATURE_LEGACYNETCF if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) CheckGetMethodInfo_Quirk(type, target, method, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | (ignoreCase?BindingFlags.IgnoreCase:0)); #endif Delegate d = InternalAlloc(rtType); // This API existed in v1/v1.1 and only expected to create open // static delegates. Constrain the call to BindToMethodName to such // and don't allow relaxed signature matching (which could make the // choice of target method ambiguous) for backwards compatibility. if (!d.BindToMethodName(null, rtTarget, method, DelegateBindingFlags.StaticMethodOnly | DelegateBindingFlags.OpenDelegateOnly | (ignoreCase ? DelegateBindingFlags.CaselessMatching : 0))) { if (throwOnBindFailure) throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTargMeth")); d = null; } return d; } // V1 API. [System.Security.SecuritySafeCritical] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public static Delegate CreateDelegate(Type type, MethodInfo method, bool throwOnBindFailure) { // Validate the parameters. if (type == null) throw new ArgumentNullException("type"); if (method == null) throw new ArgumentNullException("method"); Contract.EndContractBlock(); RuntimeType rtType = type as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "type"); RuntimeMethodInfo rmi = method as RuntimeMethodInfo; if (rmi == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), "method"); if (!rtType.IsDelegate()) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), "type"); // This API existed in v1/v1.1 and only expected to create closed // instance delegates. Constrain the call to BindToMethodInfo to // open delegates only for backwards compatibility. But we'll allow // relaxed signature checking and open static delegates because // there's no ambiguity there (the caller would have to explicitly // pass us a static method or a method with a non-exact signature // and the only change in behavior from v1.1 there is that we won't // fail the call). StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; Delegate d = CreateDelegateInternal( rtType, rmi, null, DelegateBindingFlags.OpenDelegateOnly | DelegateBindingFlags.RelaxedSignature, ref stackMark); if (d == null && throwOnBindFailure) throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTargMeth")); return d; } // V2 API. public static Delegate CreateDelegate(Type type, Object firstArgument, MethodInfo method) { return CreateDelegate(type, firstArgument, method, true); } // V2 API. [System.Security.SecuritySafeCritical] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public static Delegate CreateDelegate(Type type, Object firstArgument, MethodInfo method, bool throwOnBindFailure) { // Validate the parameters. if (type == null) throw new ArgumentNullException("type"); if (method == null) throw new ArgumentNullException("method"); Contract.EndContractBlock(); RuntimeType rtType = type as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "type"); RuntimeMethodInfo rmi = method as RuntimeMethodInfo; if (rmi == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), "method"); if (!rtType.IsDelegate()) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), "type"); // This API is new in Whidbey and allows the full range of delegate // flexability (open or closed delegates binding to static or // instance methods with relaxed signature checking. The delegate // can also be closed over null. There's no ambiguity with all these // options since the caller is providing us a specific MethodInfo. StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; Delegate d = CreateDelegateInternal( rtType, rmi, firstArgument, DelegateBindingFlags.RelaxedSignature, ref stackMark); if (d == null && throwOnBindFailure) throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTargMeth")); return d; } public static bool operator ==(Delegate d1, Delegate d2) { if ((Object)d1 == null) return (Object)d2 == null; return d1.Equals(d2); } public static bool operator != (Delegate d1, Delegate d2) { if ((Object)d1 == null) return (Object)d2 != null; return !d1.Equals(d2); } // // Implementation of ISerializable // [System.Security.SecurityCritical] public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { throw new NotSupportedException(); } // // internal implementation details (FCALLS and utilities) // // V2 internal API. // This is Critical because it skips the security check when creating the delegate. [System.Security.SecurityCritical] // auto-generated internal unsafe static Delegate CreateDelegateNoSecurityCheck(Type type, Object target, RuntimeMethodHandle method) { // Validate the parameters. if (type == null) throw new ArgumentNullException("type"); Contract.EndContractBlock(); if (method.IsNullHandle()) throw new ArgumentNullException("method"); RuntimeType rtType = type as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "type"); if (!rtType.IsDelegate()) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"),"type"); // Initialize the method... Delegate d = InternalAlloc(rtType); // This is a new internal API added in Whidbey. Currently it's only // used by the dynamic method code to generate a wrapper delegate. // Allow flexible binding options since the target method is // unambiguously provided to us. // < if (!d.BindToMethodInfo(target, method.GetMethodInfo(), RuntimeMethodHandle.GetDeclaringType(method.GetMethodInfo()), DelegateBindingFlags.RelaxedSignature | DelegateBindingFlags.SkipSecurityChecks)) throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTargMeth")); return d; } // Caution: this method is intended for deserialization only, no security checks are performed. [System.Security.SecurityCritical] // auto-generated internal static Delegate CreateDelegateNoSecurityCheck(RuntimeType type, Object firstArgument, MethodInfo method) { // Validate the parameters. if (type == null) throw new ArgumentNullException("type"); if (method == null) throw new ArgumentNullException("method"); Contract.EndContractBlock(); RuntimeMethodInfo rtMethod = method as RuntimeMethodInfo; if (rtMethod == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), "method"); if (!type.IsDelegate()) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"),"type"); // This API is used by the formatters when deserializing a delegate. // They pass us the specific target method (that was already the // target in a valid delegate) so we should bind with the most // relaxed rules available (the result will never be ambiguous, it // just increases the chance of success with minor (compatible) // signature changes). We explicitly skip security checks here -- // we're not really constructing a delegate, we're cloning an // existing instance which already passed its checks. Delegate d = UnsafeCreateDelegate(type, rtMethod, firstArgument, DelegateBindingFlags.SkipSecurityChecks | DelegateBindingFlags.RelaxedSignature); if (d == null) throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTargMeth")); return d; } // V1 API. public static Delegate CreateDelegate(Type type, MethodInfo method) { return CreateDelegate(type, method, true); } [System.Security.SecuritySafeCritical] internal static Delegate CreateDelegateInternal(RuntimeType rtType, RuntimeMethodInfo rtMethod, Object firstArgument, DelegateBindingFlags flags, ref StackCrawlMark stackMark) { Contract.Assert((flags & DelegateBindingFlags.SkipSecurityChecks) == 0); #if FEATURE_APPX bool nonW8PMethod = (rtMethod.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0; bool nonW8PType = (rtType.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0; if (nonW8PMethod || nonW8PType) { RuntimeAssembly caller = RuntimeAssembly.GetExecutingAssembly(ref stackMark); if (caller != null && !caller.IsSafeForReflection()) throw new InvalidOperationException( Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", nonW8PMethod ? rtMethod.FullName : rtType.FullName)); } #endif return UnsafeCreateDelegate(rtType, rtMethod, firstArgument, flags); } [System.Security.SecurityCritical] internal static Delegate UnsafeCreateDelegate(RuntimeType rtType, RuntimeMethodInfo rtMethod, Object firstArgument, DelegateBindingFlags flags) { #if FEATURE_LEGACYNETCF if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) if(rtMethod.IsGenericMethodDefinition) throw new MissingMethodException(rtMethod.DeclaringType.FullName, rtMethod.Name); #endif Delegate d = InternalAlloc(rtType); if (d.BindToMethodInfo(firstArgument, rtMethod, rtMethod.GetDeclaringTypeInternal(), flags)) return d; else return null; } // // internal implementation details (FCALLS and utilities) // [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern bool BindToMethodName(Object target, RuntimeType methodType, String method, DelegateBindingFlags flags); [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern bool BindToMethodInfo(Object target, IRuntimeMethodInfo method, RuntimeType methodType, DelegateBindingFlags flags); [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern static MulticastDelegate InternalAlloc(RuntimeType type); [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern static MulticastDelegate InternalAllocLike(Delegate d); [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern static bool InternalEqualTypes(object a, object b); // Used by the ctor. Do not call directly. // The name of this function will appear in managed stacktraces as delegate constructor. [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern void DelegateConstruct(Object target, IntPtr slot); [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern IntPtr GetMulticastInvoke(); [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern IntPtr GetInvokeMethod(); [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern IRuntimeMethodInfo FindMethodHandle(); [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern static bool InternalEqualMethodHandles(Delegate left, Delegate right); [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern IntPtr AdjustTarget(Object target, IntPtr methodPtr); [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern IntPtr GetCallStub(IntPtr methodPtr); [System.Security.SecuritySafeCritical] internal virtual Object GetTarget() { return (_methodPtrAux.IsNull()) ? _target : null; } [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern static bool CompareUnmanagedFunctionPtrs (Delegate d1, Delegate d2); } // These flags effect the way BindToMethodInfo and BindToMethodName are allowed to bind a delegate to a target method. Their // values must be kept in [....] with the definition in vm\comdelegate.h. internal enum DelegateBindingFlags { StaticMethodOnly = 0x00000001, // Can only bind to static target methods InstanceMethodOnly = 0x00000002, // Can only bind to instance (including virtual) methods OpenDelegateOnly = 0x00000004, // Only allow the creation of delegates open over the 1st argument ClosedDelegateOnly = 0x00000008, // Only allow the creation of delegates closed over the 1st argument NeverCloseOverNull = 0x00000010, // A null target will never been considered as a possible null 1st argument CaselessMatching = 0x00000020, // Use case insensitive lookup for methods matched by name SkipSecurityChecks = 0x00000040, // Skip security checks (visibility, link demand etc.) RelaxedSignature = 0x00000080, // Allow relaxed signature matching (co/contra variance) } }
// Copyright (c) 2015 Alachisoft // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections; namespace Alachisoft.NCache.Caching.Queries.Filters { public class LogicalAndPredicate : Predicate, IComparable { private ArrayList members; public LogicalAndPredicate() { members = new ArrayList(); } public ArrayList Children { get { return members; } } public override void Invert() { base.Invert(); for (int i = 0; i < members.Count; i++) ((Predicate)members[i]).Invert(); } public override bool ApplyPredicate(object o) { for (int i = 0; i < members.Count; i++) if (((Predicate)members[i]).Evaluate(o) == Inverse) return Inverse; return !Inverse; } internal override void ExecuteInternal(QueryContext queryContext, ref SortedList list) { bool sortAscending = true; ArrayList keys = new ArrayList(); if (Inverse) sortAscending = false; SortedList tmpList = new SortedList(new QueryResultComparer(sortAscending)); for (int i = 0; i < members.Count; i++) { Predicate predicate = (Predicate)members[i]; predicate.ExecuteInternal(queryContext, ref tmpList); } if (Inverse) keys = GetUnion(tmpList); else keys = GetIntersection(tmpList); if (keys != null) list.Add(keys.Count, keys); } internal override void Execute(QueryContext queryContext, Predicate nextPredicate) { bool sortAscending = true; bool normalizePredicates = true; if (Inverse) sortAscending = false; SortedList list = new SortedList(new QueryResultComparer(sortAscending)); for (int i = 0; i < members.Count; i++) { Predicate predicate = (Predicate)members[i]; bool isOfTypePredicate = predicate is IsOfTypePredicate; if (isOfTypePredicate) { predicate.Execute(queryContext, (Predicate)members[++i]); normalizePredicates = false; } else { predicate.ExecuteInternal(queryContext, ref list); } } if (normalizePredicates) { if (Inverse) queryContext.Tree.RightList = GetUnion(list); else queryContext.Tree.RightList = GetIntersection(list); } } /// <summary> /// handles case for 'OR' condition [Inverse == true] /// </summary> /// <param name="list"></param> /// <returns></returns> private ArrayList GetUnion(SortedList list) { Hashtable finalTable = new Hashtable(); if (list.Count > 0) { ArrayList finalKeys = list.GetByIndex(0) as ArrayList; for (int i = 0; i < finalKeys.Count; i++) { finalTable[finalKeys[i]] = null; } for (int i = 1; i < list.Count; i++) { ArrayList keys = list.GetByIndex(i) as ArrayList; if (keys != null && keys.Count > 0) { for (int j = 0; j < keys.Count; j++) { finalTable[keys[j]] = null; } } } } return new ArrayList(finalTable.Keys); } /// <summary> /// handles the case for 'AND' condition /// </summary> /// <param name="list"></param> /// <returns></returns> private ArrayList GetIntersection(SortedList list) { Hashtable finalTable = new Hashtable(); if (list.Count > 0) { ArrayList keys = list.GetByIndex(0) as ArrayList; for (int i = 0; i < keys.Count; i++) { finalTable[keys[i]] = null; } for (int i = 1; i < list.Count; i++) { Hashtable shiftTable = new Hashtable(); keys = list.GetByIndex(i) as ArrayList; if (keys != null) { for (int j = 0; j < keys.Count; j++) { object key = keys[j]; if (finalTable.ContainsKey(key)) shiftTable[key] = null; } } finalTable = shiftTable; } } return new ArrayList(finalTable.Keys); } public override string ToString() { string text = Inverse ? "(" : "("; for (int i = 0; i < members.Count; i++) { if (i > 0) text += Inverse ? " or " : " and "; text += members[i].ToString(); } text += ")"; return text; } #region IComparable Members public int CompareTo(object obj) { if (obj is LogicalAndPredicate) { LogicalAndPredicate other = (LogicalAndPredicate)obj; if (Inverse == other.Inverse) { if (members.Count == other.members.Count) { for (int i = 0; i < members.Count; i++) if (members[i] != other.members[i]) return -1; return 0; //members.CompareTo(other.members); } } } return -1; } #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.Immutable; using System.Diagnostics; using System.Reflection.Internal; using System.Reflection.Metadata.Ecma335; using System.Runtime.InteropServices; namespace System.Reflection.Metadata { sealed class MethodBodyBlock { private readonly MemoryBlock il; private readonly int size; private readonly ushort maxStack; private readonly bool localVariablesInitialized; private readonly StandaloneSignatureHandle localSignature; private readonly ImmutableArray<ExceptionRegion> exceptionRegions; private MethodBodyBlock( bool localVariablesInitialized, ushort maxStack, StandaloneSignatureHandle localSignatureHandle, MemoryBlock il, ImmutableArray<ExceptionRegion> exceptionRegions, int size) { DebugCorlib.Assert(!exceptionRegions.IsDefault); this.localVariablesInitialized = localVariablesInitialized; this.maxStack = maxStack; this.localSignature = localSignatureHandle; this.il = il; this.exceptionRegions = exceptionRegions; this.size = size; } /// <summary> /// Size of the method body - includes the header, IL and exception regions. /// </summary> public int Size { get { return size; } } public int MaxStack { get { return maxStack; } } public bool LocalVariablesInitialized { get { return localVariablesInitialized; } } public StandaloneSignatureHandle LocalSignature { get { return localSignature; } } public ImmutableArray<ExceptionRegion> ExceptionRegions { get { return exceptionRegions; } } public byte[] GetILBytes() { return il.ToArray(); } public ImmutableArray<byte> GetILContent() { byte[] bytes = GetILBytes(); return ImmutableArrayInterop.DangerousCreateFromUnderlyingArray(ref bytes); } public BlobReader GetILReader() { return new BlobReader(il); } private const byte ILTinyFormat = 0x02; private const byte ILFatFormat = 0x03; private const byte ILFormatMask = 0x03; private const int ILTinyFormatSizeShift = 2; private const byte ILMoreSects = 0x08; private const byte ILInitLocals = 0x10; private const byte ILFatFormatHeaderSize = 0x03; private const int ILFatFormatHeaderSizeShift = 4; private const byte SectEHTable = 0x01; private const byte SectOptILTable = 0x02; private const byte SectFatFormat = 0x40; private const byte SectMoreSects = 0x40; public static MethodBodyBlock Create(BlobReader reader) { int startOffset = reader.Offset; int ilSize; // Error need to check if the Memory Block is empty. This is calse for all the calls... byte headByte = reader.ReadByte(); if ((headByte & ILFormatMask) == ILTinyFormat) { // tiny IL can't have locals so technically this shouldn't matter, // but false is consistent with other metadata readers and helps // for use cases involving comparing our output with theirs. const bool initLocalsForTinyIL = false; ilSize = headByte >> ILTinyFormatSizeShift; return new MethodBodyBlock( initLocalsForTinyIL, 8, default(StandaloneSignatureHandle), reader.GetMemoryBlockAt(0, ilSize), ImmutableArray<ExceptionRegion>.Empty, 1 + ilSize // header + IL ); } if ((headByte & ILFormatMask) != ILFatFormat) { throw new BadImageFormatException(string.Format(MetadataResources.InvalidMethodHeader1, headByte)); } // FatILFormat byte headByte2 = reader.ReadByte(); if ((headByte2 >> ILFatFormatHeaderSizeShift) != ILFatFormatHeaderSize) { throw new BadImageFormatException(string.Format(MetadataResources.InvalidMethodHeader2, headByte, headByte2)); } bool localsInitialized = (headByte & ILInitLocals) == ILInitLocals; bool hasExceptionHandlers = (headByte & ILMoreSects) == ILMoreSects; ushort maxStack = reader.ReadUInt16(); ilSize = reader.ReadInt32(); int localSignatureToken = reader.ReadInt32(); StandaloneSignatureHandle localSignatureHandle; if (localSignatureToken == 0) { localSignatureHandle = default(StandaloneSignatureHandle); } else if ((localSignatureToken & TokenTypeIds.TokenTypeMask) == TokenTypeIds.Signature) { localSignatureHandle = StandaloneSignatureHandle.FromRowId((uint)localSignatureToken & TokenTypeIds.RIDMask); } else { throw new BadImageFormatException(string.Format(MetadataResources.InvalidLocalSignatureToken, unchecked((uint)localSignatureToken))); } var ilBlock = reader.GetMemoryBlockAt(0, ilSize); reader.SkipBytes(ilSize); ImmutableArray<ExceptionRegion> exceptionHandlers; if (hasExceptionHandlers) { reader.Align(4); byte sehHeader = reader.ReadByte(); if ((sehHeader & SectEHTable) != SectEHTable) { throw new BadImageFormatException(string.Format(MetadataResources.InvalidSehHeader, sehHeader)); } bool sehFatFormat = (sehHeader & SectFatFormat) == SectFatFormat; int dataSize = reader.ReadByte(); if (sehFatFormat) { dataSize += reader.ReadUInt16() << 8; exceptionHandlers = ReadFatExceptionHandlers(ref reader, dataSize / 24); } else { reader.SkipBytes(2); // skip over reserved field exceptionHandlers = ReadSmallExceptionHandlers(ref reader, dataSize / 12); } } else { exceptionHandlers = ImmutableArray<ExceptionRegion>.Empty; } return new MethodBodyBlock( localsInitialized, maxStack, localSignatureHandle, ilBlock, exceptionHandlers, reader.Offset - startOffset); } private static ImmutableArray<ExceptionRegion> ReadSmallExceptionHandlers(ref BlobReader memReader, int count) { var result = new ExceptionRegion[count]; for (int i = 0; i < result.Length; i++) { var kind = (ExceptionRegionKind)memReader.ReadUInt16(); var tryOffset = memReader.ReadUInt16(); var tryLength = memReader.ReadByte(); var handlerOffset = memReader.ReadUInt16(); var handlerLength = memReader.ReadByte(); var classTokenOrFilterOffset = memReader.ReadInt32(); result[i] = new ExceptionRegion(kind, tryOffset, tryLength, handlerOffset, handlerLength, classTokenOrFilterOffset); } return ImmutableArray.Create(result); } private static ImmutableArray<ExceptionRegion> ReadFatExceptionHandlers(ref BlobReader memReader, int count) { var result = new ExceptionRegion[count]; for (int i = 0; i < result.Length; i++) { var sehFlags = (ExceptionRegionKind)memReader.ReadUInt32(); int tryOffset = memReader.ReadInt32(); int tryLength = memReader.ReadInt32(); int handlerOffset = memReader.ReadInt32(); int handlerLength = memReader.ReadInt32(); int classTokenOrFilterOffset = memReader.ReadInt32(); result[i] = new ExceptionRegion(sehFlags, tryOffset, tryLength, handlerOffset, handlerLength, classTokenOrFilterOffset); } return ImmutableArray.Create(result); } } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets { using System; using System.Collections.Generic; using System.Text; using System.Threading; using NLog.Common; using NLog.Internal; using NLog.Internal.NetworkSenders; using NLog.Layouts; /// <summary> /// Sends log messages over the network. /// </summary> /// <seealso href="https://github.com/nlog/nlog/wiki/Network-target">Documentation on NLog Wiki</seealso> /// <example> /// <p> /// To set up the target in the <a href="config.html">configuration file</a>, /// use the following syntax: /// </p> /// <code lang="XML" source="examples/targets/Configuration File/Network/NLog.config" /> /// <p> /// This assumes just one target and a single rule. More configuration /// options are described <a href="config.html">here</a>. /// </p> /// <p> /// To set up the log target programmatically use code like this: /// </p> /// <code lang="C#" source="examples/targets/Configuration API/Network/Simple/Example.cs" /> /// <p> /// To print the results, use any application that's able to receive messages over /// TCP or UDP. <a href="http://m.nu/program/util/netcat/netcat.html">NetCat</a> is /// a simple but very powerful command-line tool that can be used for that. This image /// demonstrates the NetCat tool receiving log messages from Network target. /// </p> /// <img src="examples/targets/Screenshots/Network/Output.gif" /> /// <p> /// There are two specialized versions of the Network target: <a href="target.Chainsaw.html">Chainsaw</a> /// and <a href="target.NLogViewer.html">NLogViewer</a> which write to instances of Chainsaw log4j viewer /// or NLogViewer application respectively. /// </p> /// </example> [Target("Network")] public class NetworkTarget : TargetWithLayout { private readonly Dictionary<string, LinkedListNode<NetworkSender>> _currentSenderCache = new Dictionary<string, LinkedListNode<NetworkSender>>(StringComparer.Ordinal); private readonly LinkedList<NetworkSender> _openNetworkSenders = new LinkedList<NetworkSender>(); private readonly ReusableBufferCreator _reusableEncodingBuffer = new ReusableBufferCreator(16 * 1024); /// <summary> /// Initializes a new instance of the <see cref="NetworkTarget" /> class. /// </summary> /// <remarks> /// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}</code> /// </remarks> public NetworkTarget() { SenderFactory = NetworkSenderFactory.Default; } /// <summary> /// Initializes a new instance of the <see cref="NetworkTarget" /> class. /// </summary> /// <remarks> /// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}</code> /// </remarks> /// <param name="name">Name of the target.</param> public NetworkTarget(string name) : this() { Name = name; } /// <summary> /// Gets or sets the network address. /// </summary> /// <remarks> /// The network address can be: /// <ul> /// <li>tcp://host:port - TCP (auto select IPv4/IPv6)</li> /// <li>tcp4://host:port - force TCP/IPv4</li> /// <li>tcp6://host:port - force TCP/IPv6</li> /// <li>udp://host:port - UDP (auto select IPv4/IPv6)</li> /// <li>udp4://host:port - force UDP/IPv4</li> /// <li>udp6://host:port - force UDP/IPv6</li> /// <li>http://host:port/pageName - HTTP using POST verb</li> /// <li>https://host:port/pageName - HTTPS using POST verb</li> /// </ul> /// For SOAP-based webservice support over HTTP use WebService target. /// </remarks> /// <docgen category='Connection Options' order='10' /> public Layout Address { get; set; } /// <summary> /// Gets or sets a value indicating whether to keep connection open whenever possible. /// </summary> /// <docgen category='Connection Options' order='10' /> public bool KeepConnection { get; set; } = true; /// <summary> /// Gets or sets a value indicating whether to append newline at the end of log message. /// </summary> /// <docgen category='Layout Options' order='10' /> public bool NewLine { get; set; } /// <summary> /// Gets or sets the end of line value if a newline is appended at the end of log message <see cref="NewLine"/>. /// </summary> /// <docgen category='Layout Options' order='10' /> public LineEndingMode LineEnding { get => _lineEnding; set { _lineEnding = value; NewLine = value != null; } } private LineEndingMode _lineEnding = LineEndingMode.CRLF; /// <summary> /// Gets or sets the maximum message size in bytes. On limit breach then <see cref="OnOverflow"/> action is activated. /// </summary> /// <docgen category='Layout Options' order='10' /> public int MaxMessageSize { get; set; } = 65000; /// <summary> /// Gets or sets the maximum simultaneous connections. Requires <see cref="KeepConnection"/> = false /// </summary> /// <remarks> /// When having reached the maximum limit, then <see cref="OnConnectionOverflow"/> action will apply. /// </remarks> /// <docgen category="Connection Options" order="10"/> public int MaxConnections { get; set; } = 100; /// <summary> /// Gets or sets the action that should be taken, when more connections than <see cref="MaxConnections"/>. /// </summary> /// <docgen category='Connection Options' order='10' /> public NetworkTargetConnectionsOverflowAction OnConnectionOverflow { get; set; } = NetworkTargetConnectionsOverflowAction.Discard; /// <summary> /// Gets or sets the maximum queue size for a single connection. Requires <see cref="KeepConnection"/> = true /// </summary> /// <remarks> /// When having reached the maximum limit, then <see cref="OnQueueOverflow"/> action will apply. /// </remarks> /// <docgen category='Connection Options' order='10' /> public int MaxQueueSize { get; set; } = 10000; /// <summary> /// Gets or sets the action that should be taken, when more pending messages than <see cref="MaxQueueSize"/>. /// </summary> /// <docgen category='Connection Options' order='10' /> public NetworkTargetQueueOverflowAction OnQueueOverflow { get; set; } = NetworkTargetQueueOverflowAction.Discard; /// <summary> /// Gets or sets the size of the connection cache (number of connections which are kept alive). Requires <see cref="KeepConnection"/> = true /// </summary> /// <docgen category="Connection Options" order="10"/> public int ConnectionCacheSize { get; set; } = 5; /// <summary> /// Gets or sets the action that should be taken if the message is larger than <see cref="MaxMessageSize" /> /// </summary> /// <remarks> /// For TCP sockets then <see cref="NetworkTargetOverflowAction.Split"/> means no-limit, as TCP sockets /// performs splitting automatically. /// /// For UDP Network sender then <see cref="NetworkTargetOverflowAction.Split"/> means splitting the message /// into smaller chunks. This can be useful on networks using DontFragment, which drops network packages /// larger than MTU-size (1472 bytes). /// </remarks> /// <docgen category='Connection Options' order='10' /> public NetworkTargetOverflowAction OnOverflow { get; set; } = NetworkTargetOverflowAction.Split; /// <summary> /// Gets or sets the encoding to be used. /// </summary> /// <docgen category='Layout Options' order='10' /> public Encoding Encoding { get; set; } = Encoding.UTF8; /// <summary> /// Get or set the SSL/TLS protocols. Default no SSL/TLS is used. Currently only implemented for TCP. /// </summary> /// <docgen category='Connection Options' order='10' /> public System.Security.Authentication.SslProtocols SslProtocols { get; set; } = System.Security.Authentication.SslProtocols.None; /// <summary> /// The number of seconds a connection will remain idle before the first keep-alive probe is sent /// </summary> /// <docgen category='Connection Options' order='10' /> public int KeepAliveTimeSeconds { get; set; } internal INetworkSenderFactory SenderFactory { get; set; } /// <summary> /// Flush any pending log messages asynchronously (in case of asynchronous targets). /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> protected override void FlushAsync(AsyncContinuation asyncContinuation) { int remainingCount; void Continuation(Exception ex) { // ignore exception if (Interlocked.Decrement(ref remainingCount) == 0) { asyncContinuation(null); } } lock (_openNetworkSenders) { remainingCount = _openNetworkSenders.Count; if (remainingCount == 0) { // nothing to flush asyncContinuation(null); } else { // otherwise call FlushAsync() on all senders // and invoke continuation at the very end foreach (var openSender in _openNetworkSenders) { openSender.FlushAsync(Continuation); } } } } /// <inheritdoc/> protected override void CloseTarget() { base.CloseTarget(); lock (_currentSenderCache) { lock (_openNetworkSenders) { foreach (var openSender in _openNetworkSenders) { openSender.Close(ex => { }); } _openNetworkSenders.Clear(); } _currentSenderCache.Clear(); } } /// <summary> /// Sends the /// rendered logging event over the network optionally concatenating it with a newline character. /// </summary> /// <param name="logEvent">The logging event.</param> protected override void Write(AsyncLogEventInfo logEvent) { string address = RenderLogEvent(Address, logEvent.LogEvent); InternalLogger.Trace("{0}: Sending to address: '{1}'", this, address); byte[] bytes = GetBytesToWrite(logEvent.LogEvent); if (KeepConnection) { WriteBytesToCachedNetworkSender(address, bytes, logEvent); } else { WriteBytesToNewNetworkSender(address, bytes, logEvent); } } private void WriteBytesToCachedNetworkSender(string address, byte[] bytes, AsyncLogEventInfo logEvent) { LinkedListNode<NetworkSender> senderNode; try { senderNode = GetCachedNetworkSender(address); } catch (Exception ex) { InternalLogger.Error(ex, "{0}: Failed to create sender to address: '{1}'", this, address); throw; } WriteBytesToNetworkSender( senderNode.Value, bytes, ex => { if (ex != null) { InternalLogger.Error(ex, "{0}: Error when sending.", this); ReleaseCachedConnection(senderNode); } logEvent.Continuation(ex); }); } private void WriteBytesToNewNetworkSender(string address, byte[] bytes, AsyncLogEventInfo logEvent) { NetworkSender sender; LinkedListNode<NetworkSender> linkedListNode; lock (_openNetworkSenders) { //handle too many connections var tooManyConnections = _openNetworkSenders.Count >= MaxConnections; if (tooManyConnections && MaxConnections > 0) { switch (OnConnectionOverflow) { case NetworkTargetConnectionsOverflowAction.Discard: InternalLogger.Warn("{0}: Discarding message otherwise to many connections.", this); logEvent.Continuation(null); return; case NetworkTargetConnectionsOverflowAction.Grow: MaxConnections = MaxConnections * 2; InternalLogger.Debug("{0}: Too may connections, but this is allowed", this); break; case NetworkTargetConnectionsOverflowAction.Block: while (_openNetworkSenders.Count >= MaxConnections) { InternalLogger.Debug("{0}: Blocking networktarget otherwhise too many connections.", this); Monitor.Wait(_openNetworkSenders); InternalLogger.Trace("{0}: Entered critical section.", this); } InternalLogger.Trace("{0}: Limit ok.", this); break; } } try { sender = CreateNetworkSender(address); } catch (Exception ex) { InternalLogger.Error(ex, "{0}: Failed to create sender to address: '{1}'", this, address); throw; } linkedListNode = _openNetworkSenders.AddLast(sender); } WriteBytesToNetworkSender( sender, bytes, ex => { lock (_openNetworkSenders) { TryRemove(_openNetworkSenders, linkedListNode); if (OnConnectionOverflow == NetworkTargetConnectionsOverflowAction.Block) { Monitor.PulseAll(_openNetworkSenders); } } if (ex != null) { InternalLogger.Error(ex, "{0}: Error when sending.", this); } sender.Close(ex2 => { }); logEvent.Continuation(ex); }); } /// <summary> /// Try to remove. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="list"></param> /// <param name="node"></param> /// <returns>removed something?</returns> private static bool TryRemove<T>(LinkedList<T> list, LinkedListNode<T> node) { if (node is null || list != node.List) { return false; } list.Remove(node); return true; } /// <summary> /// Gets the bytes to be written. /// </summary> /// <param name="logEvent">Log event.</param> /// <returns>Byte array.</returns> protected virtual byte[] GetBytesToWrite(LogEventInfo logEvent) { using (var localBuffer = _reusableEncodingBuffer.Allocate()) { if (!NewLine && logEvent.TryGetCachedLayoutValue(Layout, out var text)) { return GetBytesFromString(localBuffer.Result, text?.ToString() ?? string.Empty); } else { using (var localBuilder = ReusableLayoutBuilder.Allocate()) { Layout.Render(logEvent, localBuilder.Result); if (NewLine) { localBuilder.Result.Append(LineEnding.NewLineCharacters); } return GetBytesFromStringBuilder(localBuffer.Result, localBuilder.Result); } } } } private byte[] GetBytesFromStringBuilder(char[] charBuffer, StringBuilder stringBuilder) { InternalLogger.Trace("{0}: Sending {1} chars", this, stringBuilder.Length); if (stringBuilder.Length <= charBuffer.Length) { stringBuilder.CopyTo(0, charBuffer, 0, stringBuilder.Length); return Encoding.GetBytes(charBuffer, 0, stringBuilder.Length); } return Encoding.GetBytes(stringBuilder.ToString()); } private byte[] GetBytesFromString(char[] charBuffer, string layoutMessage) { InternalLogger.Trace("{0}: Sending {1}", this, layoutMessage); if (layoutMessage.Length <= charBuffer.Length) { layoutMessage.CopyTo(0, charBuffer, 0, layoutMessage.Length); return Encoding.GetBytes(charBuffer, 0, layoutMessage.Length); } return Encoding.GetBytes(layoutMessage); } private LinkedListNode<NetworkSender> GetCachedNetworkSender(string address) { lock (_currentSenderCache) { // already have address if (_currentSenderCache.TryGetValue(address, out var senderNode)) { senderNode.Value.CheckSocket(); return senderNode; } if (_currentSenderCache.Count >= ConnectionCacheSize) { // make room in the cache by closing the least recently used connection int minAccessTime = int.MaxValue; LinkedListNode<NetworkSender> leastRecentlyUsed = null; foreach (var pair in _currentSenderCache) { var networkSender = pair.Value.Value; if (networkSender.LastSendTime < minAccessTime) { minAccessTime = networkSender.LastSendTime; leastRecentlyUsed = pair.Value; } } if (leastRecentlyUsed != null) { ReleaseCachedConnection(leastRecentlyUsed); } } NetworkSender sender = CreateNetworkSender(address); lock (_openNetworkSenders) { senderNode = _openNetworkSenders.AddLast(sender); } _currentSenderCache.Add(address, senderNode); return senderNode; } } private NetworkSender CreateNetworkSender(string address) { var sender = SenderFactory.Create(address, MaxQueueSize, OnQueueOverflow, MaxMessageSize, SslProtocols, TimeSpan.FromSeconds(KeepAliveTimeSeconds)); sender.Initialize(); return sender; } private void ReleaseCachedConnection(LinkedListNode<NetworkSender> senderNode) { lock (_currentSenderCache) { var networkSender = senderNode.Value; lock (_openNetworkSenders) { if (TryRemove(_openNetworkSenders, senderNode)) { // only remove it once networkSender.Close(ex => { }); } } // make sure the current sender for this address is the one we want to remove if (_currentSenderCache.TryGetValue(networkSender.Address, out var sender2) && ReferenceEquals(senderNode, sender2)) { _currentSenderCache.Remove(networkSender.Address); } } } private void WriteBytesToNetworkSender(NetworkSender sender, byte[] buffer, AsyncContinuation continuation) { int tosend = buffer.Length; if (tosend > MaxMessageSize) { if (OnOverflow == NetworkTargetOverflowAction.Discard) { InternalLogger.Trace("{0}: Discard because chunksize > this.MaxMessageSize", this); continuation(null); return; } if (OnOverflow == NetworkTargetOverflowAction.Error) { continuation(new OverflowException($"Attempted to send a message larger than MaxMessageSize ({MaxMessageSize}). Actual size was: {buffer.Length}. Adjust OnOverflow and MaxMessageSize parameters accordingly.")); return; } } InternalLogger.Trace("{0}: Sending chunk, position: {1}, length: {2}", this, 0, tosend); if (tosend <= 0) { continuation(null); return; } sender.Send(buffer, 0, tosend, continuation); } } }
// 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.Net.Test.Common; using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.WebSockets.Client.Tests { [ActiveIssue(20132, TargetFrameworkMonikers.Uap)] public class CloseTest : ClientWebSocketTestBase { public CloseTest(ITestOutputHelper output) : base(output) { } [OuterLoop] // TODO: Issue #11345 [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))] public async Task CloseAsync_ServerInitiatedClose_Success(Uri server) { const string closeWebSocketMetaCommand = ".close"; using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output)) { var cts = new CancellationTokenSource(TimeOutMilliseconds); _output.WriteLine("SendAsync starting."); await cws.SendAsync( WebSocketData.GetBufferFromText(closeWebSocketMetaCommand), WebSocketMessageType.Text, true, cts.Token); _output.WriteLine("SendAsync done."); var recvBuffer = new byte[256]; _output.WriteLine("ReceiveAsync starting."); WebSocketReceiveResult recvResult = await cws.ReceiveAsync(new ArraySegment<byte>(recvBuffer), cts.Token); _output.WriteLine("ReceiveAsync done."); // Verify received server-initiated close message. Assert.Equal(WebSocketCloseStatus.NormalClosure, recvResult.CloseStatus); Assert.Equal(closeWebSocketMetaCommand, recvResult.CloseStatusDescription); // Verify current websocket state as CloseReceived which indicates only partial close. Assert.Equal(WebSocketState.CloseReceived, cws.State); Assert.Equal(WebSocketCloseStatus.NormalClosure, cws.CloseStatus); Assert.Equal(closeWebSocketMetaCommand, cws.CloseStatusDescription); // Send back close message to acknowledge server-initiated close. _output.WriteLine("CloseAsync starting."); await cws.CloseAsync(WebSocketCloseStatus.InvalidMessageType, string.Empty, cts.Token); _output.WriteLine("CloseAsync done."); Assert.Equal(WebSocketState.Closed, cws.State); // Verify that there is no follow-up echo close message back from the server by // making sure the close code and message are the same as from the first server close message. Assert.Equal(WebSocketCloseStatus.NormalClosure, cws.CloseStatus); Assert.Equal(closeWebSocketMetaCommand, cws.CloseStatusDescription); } } [OuterLoop] // TODO: Issue #11345 [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))] public async Task CloseAsync_ClientInitiatedClose_Success(Uri server) { using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output)) { var cts = new CancellationTokenSource(TimeOutMilliseconds); Assert.Equal(WebSocketState.Open, cws.State); var closeStatus = WebSocketCloseStatus.InvalidMessageType; string closeDescription = "CloseAsync_InvalidMessageType"; await cws.CloseAsync(closeStatus, closeDescription, cts.Token); Assert.Equal(WebSocketState.Closed, cws.State); Assert.Equal(closeStatus, cws.CloseStatus); Assert.Equal(closeDescription, cws.CloseStatusDescription); } } [OuterLoop] // TODO: Issue #11345 [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))] public async Task CloseAsync_CloseDescriptionIsMaxLength_Success(Uri server) { string closeDescription = new string('C', CloseDescriptionMaxLength); using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output)) { var cts = new CancellationTokenSource(TimeOutMilliseconds); await cws.CloseAsync(WebSocketCloseStatus.NormalClosure, closeDescription, cts.Token); } } [OuterLoop] // TODO: Issue #11345 [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))] public async Task CloseAsync_CloseDescriptionIsMaxLengthPlusOne_ThrowsArgumentException(Uri server) { string closeDescription = new string('C', CloseDescriptionMaxLength + 1); using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output)) { var cts = new CancellationTokenSource(TimeOutMilliseconds); string expectedInnerMessage = ResourceHelper.GetExceptionMessage( "net_WebSockets_InvalidCloseStatusDescription", closeDescription, CloseDescriptionMaxLength); var expectedException = new ArgumentException(expectedInnerMessage, "statusDescription"); string expectedMessage = expectedException.Message; AssertExtensions.Throws<ArgumentException>("statusDescription", () => { Task t = cws.CloseAsync(WebSocketCloseStatus.NormalClosure, closeDescription, cts.Token); }); Assert.Equal(WebSocketState.Open, cws.State); } } [OuterLoop] // TODO: Issue #11345 [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))] public async Task CloseAsync_CloseDescriptionHasUnicode_Success(Uri server) { using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output)) { var cts = new CancellationTokenSource(TimeOutMilliseconds); var closeStatus = WebSocketCloseStatus.InvalidMessageType; string closeDescription = "CloseAsync_Containing\u016Cnicode."; await cws.CloseAsync(closeStatus, closeDescription, cts.Token); Assert.Equal(closeStatus, cws.CloseStatus); Assert.Equal(closeDescription, cws.CloseStatusDescription); } } [OuterLoop] // TODO: Issue #11345 [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))] public async Task CloseAsync_CloseDescriptionIsNull_Success(Uri server) { using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output)) { var cts = new CancellationTokenSource(TimeOutMilliseconds); var closeStatus = WebSocketCloseStatus.NormalClosure; string closeDescription = null; await cws.CloseAsync(closeStatus, closeDescription, cts.Token); Assert.Equal(closeStatus, cws.CloseStatus); Assert.Equal(true, String.IsNullOrEmpty(cws.CloseStatusDescription)); } } [OuterLoop] // TODO: Issue #11345 [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))] public async Task CloseOutputAsync_ClientInitiated_CanReceive_CanClose(Uri server) { string message = "Hello WebSockets!"; using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output)) { var cts = new CancellationTokenSource(TimeOutMilliseconds); var closeStatus = WebSocketCloseStatus.InvalidPayloadData; string closeDescription = "CloseOutputAsync_Client_InvalidPayloadData"; await cws.SendAsync(WebSocketData.GetBufferFromText(message), WebSocketMessageType.Text, true, cts.Token); // Need a short delay as per WebSocket rfc6455 section 5.5.1 there isn't a requirement to receive any // data fragments after a close has been sent. The delay allows the received data fragment to be // available before calling close. The WinRT MessageWebSocket implementation doesn't allow receiving // after a call to Close. await Task.Delay(100); await cws.CloseOutputAsync(closeStatus, closeDescription, cts.Token); // Should be able to receive the message echoed by the server. var recvBuffer = new byte[100]; var segmentRecv = new ArraySegment<byte>(recvBuffer); WebSocketReceiveResult recvResult = await cws.ReceiveAsync(segmentRecv, cts.Token); Assert.Equal(message.Length, recvResult.Count); segmentRecv = new ArraySegment<byte>(segmentRecv.Array, 0, recvResult.Count); Assert.Equal(message, WebSocketData.GetTextFromBuffer(segmentRecv)); Assert.Equal(null, recvResult.CloseStatus); Assert.Equal(null, recvResult.CloseStatusDescription); await cws.CloseAsync(closeStatus, closeDescription, cts.Token); Assert.Equal(closeStatus, cws.CloseStatus); Assert.Equal(closeDescription, cws.CloseStatusDescription); } } [OuterLoop] // TODO: Issue #11345 [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))] public async Task CloseOutputAsync_ServerInitiated_CanSend(Uri server) { string message = "Hello WebSockets!"; var expectedCloseStatus = WebSocketCloseStatus.NormalClosure; var expectedCloseDescription = ".shutdown"; using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output)) { var cts = new CancellationTokenSource(TimeOutMilliseconds); await cws.SendAsync( WebSocketData.GetBufferFromText(".shutdown"), WebSocketMessageType.Text, true, cts.Token); // Should be able to receive a shutdown message. var recvBuffer = new byte[100]; var segmentRecv = new ArraySegment<byte>(recvBuffer); WebSocketReceiveResult recvResult = await cws.ReceiveAsync(segmentRecv, cts.Token); Assert.Equal(0, recvResult.Count); Assert.Equal(expectedCloseStatus, recvResult.CloseStatus); Assert.Equal(expectedCloseDescription, recvResult.CloseStatusDescription); // Verify WebSocket state Assert.Equal(expectedCloseStatus, cws.CloseStatus); Assert.Equal(expectedCloseDescription, cws.CloseStatusDescription); Assert.Equal(WebSocketState.CloseReceived, cws.State); // Should be able to send. await cws.SendAsync(WebSocketData.GetBufferFromText(message), WebSocketMessageType.Text, true, cts.Token); // Cannot change the close status/description with the final close. var closeStatus = WebSocketCloseStatus.InvalidPayloadData; var closeDescription = "CloseOutputAsync_Client_Description"; await cws.CloseAsync(closeStatus, closeDescription, cts.Token); Assert.Equal(expectedCloseStatus, cws.CloseStatus); Assert.Equal(expectedCloseDescription, cws.CloseStatusDescription); Assert.Equal(WebSocketState.Closed, cws.State); } } [OuterLoop] // TODO: Issue #11345 [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))] public async Task CloseOutputAsync_CloseDescriptionIsNull_Success(Uri server) { using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output)) { var cts = new CancellationTokenSource(TimeOutMilliseconds); var closeStatus = WebSocketCloseStatus.NormalClosure; string closeDescription = null; await cws.CloseOutputAsync(closeStatus, closeDescription, cts.Token); } } [ActiveIssue(20362, TargetFrameworkMonikers.NetFramework)] [OuterLoop] // TODO: Issue #11345 [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))] public async Task CloseOutputAsync_DuringConcurrentReceiveAsync_ExpectedStates(Uri server) { var receiveBuffer = new byte[1024]; using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output)) { // Issue a receive but don't wait for it. var t = cws.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None); Assert.False(t.IsCompleted); Assert.Equal(WebSocketState.Open, cws.State); // Send a close frame. After this completes, the state could be CloseSent if we haven't // yet received the server response close frame, or it could be CloseReceived if we have. await cws.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None); Assert.True( cws.State == WebSocketState.CloseSent || cws.State == WebSocketState.CloseReceived, $"Expected CloseSent or CloseReceived, got {cws.State}"); // Then wait for the receive. After this completes, the state is most likely CloseReceived, // however there is a race condition between the our realizing that the send has completed // and a fast server sending back a close frame, such that we could end up noticing the // receive completion before we notice the send completion. WebSocketReceiveResult r = await t; Assert.Equal(WebSocketMessageType.Close, r.MessageType); Assert.True( cws.State == WebSocketState.CloseSent || cws.State == WebSocketState.CloseReceived, $"Expected CloseSent or CloseReceived, got {cws.State}"); // Then close await cws.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None); Assert.Equal(WebSocketState.Closed, cws.State); // Another close should fail await Assert.ThrowsAsync<WebSocketException>(() => cws.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None)); } } [OuterLoop] // TODO: Issue #11345 [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))] public async Task CloseAsync_DuringConcurrentReceiveAsync_ExpectedStates(Uri server) { var receiveBuffer = new byte[1024]; using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output)) { var t = cws.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None); Assert.False(t.IsCompleted); await cws.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None); // There is a race condition in the above. If the ReceiveAsync receives the sent close message from the server, // then it will complete successfully and the socket will close successfully. If the CloseAsync receive the sent // close message from the server, then the receive async will end up getting aborted along with the socket. try { await t; Assert.Equal(WebSocketState.Closed, cws.State); } catch (OperationCanceledException) { Assert.Equal(WebSocketState.Aborted, cws.State); } } } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: MemoryMappedFile ** ** Purpose: Managed MemoryMappedFiles. ** ** Date: February 7, 2007 ** ===========================================================*/ using System; using System.Diagnostics; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.AccessControl; using System.Security.Permissions; using Microsoft.Win32; using Microsoft.Win32.SafeHandles; namespace System.IO.MemoryMappedFiles { public class MemoryMappedFile : IDisposable { private SafeMemoryMappedFileHandle _handle; private bool _leaveOpen; private FileStream _fileStream; internal const int DefaultSize = 0; // Private constructors to be used by the factory methods. [System.Security.SecurityCritical] private MemoryMappedFile(SafeMemoryMappedFileHandle handle) { Debug.Assert(handle != null && !handle.IsClosed && !handle.IsInvalid, "handle is null, closed, or invalid"); _handle = handle; _leaveOpen = true; // No FileStream to dispose of in this case. } [System.Security.SecurityCritical] private MemoryMappedFile(SafeMemoryMappedFileHandle handle, FileStream fileStream, bool leaveOpen) { Debug.Assert(handle != null && !handle.IsClosed && !handle.IsInvalid, "handle is null, closed, or invalid"); Debug.Assert(fileStream != null, "fileStream is null"); _handle = handle; _fileStream = fileStream; _leaveOpen = leaveOpen; } // Factory Method Group #1: Opens an existing named memory mapped file. The native OpenFileMapping call // will check the desiredAccessRights against the ACL on the memory mapped file. Note that a memory // mapped file created without an ACL will use a default ACL taken from the primary or impersonation token // of the creator. On my machine, I always get ReadWrite access to it so I never have to use anything but // the first override of this method. Note: having ReadWrite access to the object does not mean that we // have ReadWrite access to the pages mapping the file. The OS will check against the access on the pages // when a view is created. public static MemoryMappedFile OpenExisting(string mapName) { return OpenExisting(mapName, MemoryMappedFileRights.ReadWrite, HandleInheritability.None); } public static MemoryMappedFile OpenExisting(string mapName, MemoryMappedFileRights desiredAccessRights) { return OpenExisting(mapName, desiredAccessRights, HandleInheritability.None); } [System.Security.SecurityCritical] [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)] public static MemoryMappedFile OpenExisting(string mapName, MemoryMappedFileRights desiredAccessRights, HandleInheritability inheritability) { if (mapName == null) { throw new ArgumentNullException("mapName", SR.GetString(SR.ArgumentNull_MapName)); } if (mapName.Length == 0) { throw new ArgumentException(SR.GetString(SR.Argument_MapNameEmptyString)); } if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable) { throw new ArgumentOutOfRangeException("inheritability"); } if (((int)desiredAccessRights & ~((int)(MemoryMappedFileRights.FullControl | MemoryMappedFileRights.AccessSystemSecurity))) != 0) { throw new ArgumentOutOfRangeException("desiredAccessRights"); } SafeMemoryMappedFileHandle handle = OpenCore(mapName, inheritability, (int)desiredAccessRights, false); return new MemoryMappedFile(handle); } // Factory Method Group #2: Creates a new memory mapped file where the content is taken from an existing // file on disk. This file must be opened by a FileStream before given to us. Specifying DefaultSize to // the capacity will make the capacity of the memory mapped file match the size of the file. Specifying // a value larger than the size of the file will enlarge the new file to this size. Note that in such a // case, the capacity (and there for the size of the file) will be rounded up to a multiple of the system // page size. One can use FileStream.SetLength to bring the length back to a desirable size. By default, // the MemoryMappedFile will close the FileStream object when it is disposed. This behavior can be // changed by the leaveOpen boolean argument. public static MemoryMappedFile CreateFromFile(String path) { return CreateFromFile(path, FileMode.Open, null, DefaultSize, MemoryMappedFileAccess.ReadWrite); } public static MemoryMappedFile CreateFromFile(String path, FileMode mode) { return CreateFromFile(path, mode, null, DefaultSize, MemoryMappedFileAccess.ReadWrite); } public static MemoryMappedFile CreateFromFile(String path, FileMode mode, String mapName) { return CreateFromFile(path, mode, mapName, DefaultSize, MemoryMappedFileAccess.ReadWrite); } public static MemoryMappedFile CreateFromFile(String path, FileMode mode, String mapName, Int64 capacity) { return CreateFromFile(path, mode, mapName, capacity, MemoryMappedFileAccess.ReadWrite); } [System.Security.SecurityCritical] [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)] public static MemoryMappedFile CreateFromFile(String path, FileMode mode, String mapName, Int64 capacity, MemoryMappedFileAccess access) { if (path == null) { throw new ArgumentNullException("path"); } if (mapName != null && mapName.Length == 0) { throw new ArgumentException(SR.GetString(SR.Argument_MapNameEmptyString)); } if (capacity < 0) { throw new ArgumentOutOfRangeException("capacity", SR.GetString(SR.ArgumentOutOfRange_PositiveOrDefaultCapacityRequired)); } if (access < MemoryMappedFileAccess.ReadWrite || access > MemoryMappedFileAccess.ReadWriteExecute) { throw new ArgumentOutOfRangeException("access"); } if (mode == FileMode.Append) { throw new ArgumentException(SR.GetString(SR.Argument_NewMMFAppendModeNotAllowed), "mode"); } if (access == MemoryMappedFileAccess.Write) { throw new ArgumentException(SR.GetString(SR.Argument_NewMMFWriteAccessNotAllowed), "access"); } bool existed = File.Exists(path); FileStream fileStream = new FileStream(path, mode, GetFileStreamFileSystemRights(access), FileShare.None, 0x1000, FileOptions.None); if (capacity == 0 && fileStream.Length == 0) { CleanupFile(fileStream, existed, path); throw new ArgumentException(SR.GetString(SR.Argument_EmptyFile)); } if (access == MemoryMappedFileAccess.Read && capacity > fileStream.Length) { CleanupFile(fileStream, existed, path); throw new ArgumentException(SR.GetString(SR.Argument_ReadAccessWithLargeCapacity)); } if (capacity == DefaultSize) { capacity = fileStream.Length; } // one can always create a small view if they do not want to map an entire file if (fileStream.Length > capacity) { CleanupFile(fileStream, existed, path); throw new ArgumentOutOfRangeException("capacity", SR.GetString(SR.ArgumentOutOfRange_CapacityGEFileSizeRequired)); } SafeMemoryMappedFileHandle handle = null; try { handle = CreateCore(fileStream.SafeFileHandle, mapName, HandleInheritability.None, null, access, MemoryMappedFileOptions.None, capacity); } catch { CleanupFile(fileStream, existed, path); throw; } Debug.Assert(handle != null && !handle.IsInvalid); return new MemoryMappedFile(handle, fileStream, false); } public static MemoryMappedFile CreateFromFile(FileStream fileStream, String mapName, Int64 capacity, MemoryMappedFileAccess access, HandleInheritability inheritability, bool leaveOpen) { return CreateFromFile(fileStream, mapName, capacity, access, null, inheritability, leaveOpen); } [System.Security.SecurityCritical] [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)] public static MemoryMappedFile CreateFromFile(FileStream fileStream, String mapName, Int64 capacity, MemoryMappedFileAccess access, MemoryMappedFileSecurity memoryMappedFileSecurity, HandleInheritability inheritability, bool leaveOpen) { if (fileStream == null) { throw new ArgumentNullException("fileStream", SR.GetString(SR.ArgumentNull_FileStream)); } if (mapName != null && mapName.Length == 0) { throw new ArgumentException(SR.GetString(SR.Argument_MapNameEmptyString)); } if (capacity < 0) { throw new ArgumentOutOfRangeException("capacity", SR.GetString(SR.ArgumentOutOfRange_PositiveOrDefaultCapacityRequired)); } if (capacity == 0 && fileStream.Length == 0) { throw new ArgumentException(SR.GetString(SR.Argument_EmptyFile)); } if (access < MemoryMappedFileAccess.ReadWrite || access > MemoryMappedFileAccess.ReadWriteExecute) { throw new ArgumentOutOfRangeException("access"); } if (access == MemoryMappedFileAccess.Write) { throw new ArgumentException(SR.GetString(SR.Argument_NewMMFWriteAccessNotAllowed), "access"); } if (access == MemoryMappedFileAccess.Read && capacity > fileStream.Length) { throw new ArgumentException(SR.GetString(SR.Argument_ReadAccessWithLargeCapacity)); } if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable) { throw new ArgumentOutOfRangeException("inheritability"); } // flush any bytes written to the FileStream buffer so that we can see them in our MemoryMappedFile fileStream.Flush(); if (capacity == DefaultSize) { capacity = fileStream.Length; } // one can always create a small view if they do not want to map an entire file if (fileStream.Length > capacity) { throw new ArgumentOutOfRangeException("capacity", SR.GetString(SR.ArgumentOutOfRange_CapacityGEFileSizeRequired)); } SafeMemoryMappedFileHandle handle = CreateCore(fileStream.SafeFileHandle, mapName, inheritability, memoryMappedFileSecurity, access, MemoryMappedFileOptions.None, capacity); return new MemoryMappedFile(handle, fileStream, leaveOpen); } // Factory Method Group #3: Creates a new empty memory mapped file. Such memory mapped files are ideal // for IPC, when mapName != null. public static MemoryMappedFile CreateNew(String mapName, Int64 capacity) { return CreateNew(mapName, capacity, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, null, HandleInheritability.None); } public static MemoryMappedFile CreateNew(String mapName, Int64 capacity, MemoryMappedFileAccess access) { return CreateNew(mapName, capacity, access, MemoryMappedFileOptions.None, null, HandleInheritability.None); } public static MemoryMappedFile CreateNew(String mapName, Int64 capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, HandleInheritability inheritability) { return CreateNew(mapName, capacity, access, options, null, inheritability); } [System.Security.SecurityCritical] [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)] public static MemoryMappedFile CreateNew(String mapName, Int64 capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, MemoryMappedFileSecurity memoryMappedFileSecurity, HandleInheritability inheritability) { if (mapName != null && mapName.Length == 0) { throw new ArgumentException(SR.GetString(SR.Argument_MapNameEmptyString)); } if (capacity <= 0) { throw new ArgumentOutOfRangeException("capacity", SR.GetString(SR.ArgumentOutOfRange_NeedPositiveNumber)); } if (IntPtr.Size == 4 && capacity > UInt32.MaxValue) { throw new ArgumentOutOfRangeException("capacity", SR.GetString(SR.ArgumentOutOfRange_CapacityLargerThanLogicalAddressSpaceNotAllowed)); } if (access < MemoryMappedFileAccess.ReadWrite || access > MemoryMappedFileAccess.ReadWriteExecute) { throw new ArgumentOutOfRangeException("access"); } if (access == MemoryMappedFileAccess.Write) { throw new ArgumentException(SR.GetString(SR.Argument_NewMMFWriteAccessNotAllowed), "access"); } if (((int)options & ~((int)(MemoryMappedFileOptions.DelayAllocatePages ))) != 0) { throw new ArgumentOutOfRangeException("options"); } if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable) { throw new ArgumentOutOfRangeException("inheritability"); } SafeMemoryMappedFileHandle handle = CreateCore(new SafeFileHandle(new IntPtr(-1), true), mapName, inheritability, memoryMappedFileSecurity, access, options, capacity); return new MemoryMappedFile(handle); } // Factory Method Group #4: Creates a new empty memory mapped file or opens an existing // memory mapped file if one exists with the same name. The capacity, options, and // memoryMappedFileSecurity arguments will be ignored in the case of the later. // This is ideal for P2P style IPC. public static MemoryMappedFile CreateOrOpen(String mapName, Int64 capacity) { return CreateOrOpen(mapName, capacity, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, null, HandleInheritability.None); } public static MemoryMappedFile CreateOrOpen(String mapName, Int64 capacity, MemoryMappedFileAccess access) { return CreateOrOpen(mapName, capacity, access, MemoryMappedFileOptions.None, null, HandleInheritability.None); } public static MemoryMappedFile CreateOrOpen(String mapName, Int64 capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, HandleInheritability inheritability) { return CreateOrOpen(mapName, capacity, access, options, null, inheritability); } [System.Security.SecurityCritical] [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)] public static MemoryMappedFile CreateOrOpen(String mapName, Int64 capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, MemoryMappedFileSecurity memoryMappedFileSecurity, HandleInheritability inheritability) { if (mapName == null) { throw new ArgumentNullException("mapName", SR.GetString(SR.ArgumentNull_MapName)); } if (mapName.Length == 0) { throw new ArgumentException(SR.GetString(SR.Argument_MapNameEmptyString)); } if (capacity <= 0) { throw new ArgumentOutOfRangeException("capacity", SR.GetString(SR.ArgumentOutOfRange_NeedPositiveNumber)); } if (IntPtr.Size == 4 && capacity > UInt32.MaxValue) { throw new ArgumentOutOfRangeException("capacity", SR.GetString(SR.ArgumentOutOfRange_CapacityLargerThanLogicalAddressSpaceNotAllowed)); } if (access < MemoryMappedFileAccess.ReadWrite || access > MemoryMappedFileAccess.ReadWriteExecute) { throw new ArgumentOutOfRangeException("access"); } if (((int)options & ~((int)(MemoryMappedFileOptions.DelayAllocatePages))) != 0) { throw new ArgumentOutOfRangeException("options"); } if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable) { throw new ArgumentOutOfRangeException("inheritability"); } SafeMemoryMappedFileHandle handle; // special case for write access; create will never succeed if (access == MemoryMappedFileAccess.Write) { handle = OpenCore(mapName, inheritability, GetFileMapAccess(access), true); } else { handle = CreateOrOpenCore(new SafeFileHandle(new IntPtr(-1), true), mapName, inheritability, memoryMappedFileSecurity, access, options, capacity); } return new MemoryMappedFile(handle); } // Used by the 2 Create factory method groups. A -1 fileHandle specifies that the // memory mapped file should not be associated with an exsiting file on disk (ie start // out empty). [System.Security.SecurityCritical] private static SafeMemoryMappedFileHandle CreateCore(SafeFileHandle fileHandle, String mapName, HandleInheritability inheritability, MemoryMappedFileSecurity memoryMappedFileSecurity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, Int64 capacity) { SafeMemoryMappedFileHandle handle = null; Object pinningHandle; UnsafeNativeMethods.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(inheritability, memoryMappedFileSecurity, out pinningHandle); // split the long into two ints Int32 capacityLow = (Int32)(capacity & 0x00000000FFFFFFFFL); Int32 capacityHigh = (Int32)(capacity >> 32); try { handle = UnsafeNativeMethods.CreateFileMapping(fileHandle, secAttrs, GetPageAccess(access) | (int)options, capacityHigh, capacityLow, mapName); Int32 errorCode = Marshal.GetLastWin32Error(); if (!handle.IsInvalid && errorCode == UnsafeNativeMethods.ERROR_ALREADY_EXISTS) { handle.Dispose(); __Error.WinIOError(errorCode, String.Empty); } else if (handle.IsInvalid) { __Error.WinIOError(errorCode, String.Empty); } } finally { if (pinningHandle != null) { GCHandle pinHandle = (GCHandle)pinningHandle; pinHandle.Free(); } } return handle; } // Used by the OpenExisting factory method group and by CreateOrOpen if access is write. // We'll throw an ArgumentException if the file mapping object didn't exist and the // caller used CreateOrOpen since Create isn't valid with Write access [System.Security.SecurityCritical] private static SafeMemoryMappedFileHandle OpenCore(String mapName, HandleInheritability inheritability, int desiredAccessRights, bool createOrOpen) { SafeMemoryMappedFileHandle handle = UnsafeNativeMethods.OpenFileMapping(desiredAccessRights, (inheritability & HandleInheritability.Inheritable) != 0, mapName); Int32 lastError = Marshal.GetLastWin32Error(); if (handle.IsInvalid) { if (createOrOpen && (lastError == UnsafeNativeMethods.ERROR_FILE_NOT_FOUND)) { throw new ArgumentException(SR.GetString(SR.Argument_NewMMFWriteAccessNotAllowed), "access"); } else { __Error.WinIOError(lastError, String.Empty); } } return handle; } // Used by the CreateOrOpen factory method groups. A -1 fileHandle specifies that the // memory mapped file should not be associated with an existing file on disk (ie start // out empty). // // Try to open the file if it exists -- this requires a bit more work. Loop until we can // either create or open a memory mapped file up to a timeout. CreateFileMapping may fail // if the file exists and we have non-null security attributes, in which case we need to // use OpenFileMapping. But, there exists a race condition because the memory mapped file // may have closed inbetween the two calls -- hence the loop. // // This uses similar retry/timeout logic as in performance counter. It increases the wait // time each pass through the loop and times out in approximately 1.4 minutes. If after // retrying, a MMF handle still hasn't been opened, throw an InvalidOperationException. // [System.Security.SecurityCritical] private static SafeMemoryMappedFileHandle CreateOrOpenCore(SafeFileHandle fileHandle, String mapName, HandleInheritability inheritability, MemoryMappedFileSecurity memoryMappedFileSecurity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, Int64 capacity) { Debug.Assert(access != MemoryMappedFileAccess.Write, "Callers requesting write access shouldn't try to create a mmf"); SafeMemoryMappedFileHandle handle = null; Object pinningHandle; UnsafeNativeMethods.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(inheritability, memoryMappedFileSecurity, out pinningHandle); // split the long into two ints Int32 capacityLow = (Int32)(capacity & 0x00000000FFFFFFFFL); Int32 capacityHigh = (Int32)(capacity >> 32); try { int waitRetries = 14; //((2^13)-1)*10ms == approximately 1.4mins int waitSleep = 0; // keep looping until we've exhausted retries or break as soon we we get valid handle while (waitRetries > 0) { // try to create handle = UnsafeNativeMethods.CreateFileMapping(fileHandle, secAttrs, GetPageAccess(access) | (int)options, capacityHigh, capacityLow, mapName); Int32 createErrorCode = Marshal.GetLastWin32Error(); if (!handle.IsInvalid) { break; } else { if (createErrorCode != UnsafeNativeMethods.ERROR_ACCESS_DENIED) { __Error.WinIOError(createErrorCode, String.Empty); } // the mapname exists but our ACL is preventing us from opening it with CreateFileMapping. // Let's try to open it with OpenFileMapping. handle.SetHandleAsInvalid(); } // try to open handle = UnsafeNativeMethods.OpenFileMapping(GetFileMapAccess(access), (inheritability & HandleInheritability.Inheritable) != 0, mapName); Int32 openErrorCode = Marshal.GetLastWin32Error(); // valid handle if (!handle.IsInvalid) { break; } // didn't get valid handle; have to retry else { if (openErrorCode != UnsafeNativeMethods.ERROR_FILE_NOT_FOUND) { __Error.WinIOError(openErrorCode, String.Empty); } // increase wait time --waitRetries; if (waitSleep == 0) { waitSleep = 10; } else { System.Threading.Thread.Sleep(waitSleep); waitSleep *= 2; } } } // finished retrying but couldn't create or open if (handle == null || handle.IsInvalid) { throw new InvalidOperationException(SR.GetString(SR.InvalidOperation_CantCreateFileMapping)); } } finally { if (pinningHandle != null) { GCHandle pinHandle = (GCHandle)pinningHandle; pinHandle.Free(); } } return handle; } // Creates a new view in the form of a stream. public MemoryMappedViewStream CreateViewStream() { return CreateViewStream(0, DefaultSize, MemoryMappedFileAccess.ReadWrite); } public MemoryMappedViewStream CreateViewStream(Int64 offset, Int64 size) { return CreateViewStream(offset, size, MemoryMappedFileAccess.ReadWrite); } [System.Security.SecurityCritical] [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)] public MemoryMappedViewStream CreateViewStream(Int64 offset, Int64 size, MemoryMappedFileAccess access) { if (offset < 0) { throw new ArgumentOutOfRangeException("offset", SR.GetString(SR.ArgumentOutOfRange_NeedNonNegNum)); } if (size < 0) { throw new ArgumentOutOfRangeException("size", SR.GetString(SR.ArgumentOutOfRange_PositiveOrDefaultSizeRequired)); } if (access < MemoryMappedFileAccess.ReadWrite || access > MemoryMappedFileAccess.ReadWriteExecute) { throw new ArgumentOutOfRangeException("access"); } if (IntPtr.Size == 4 && size > UInt32.MaxValue) { throw new ArgumentOutOfRangeException("size", SR.GetString(SR.ArgumentOutOfRange_CapacityLargerThanLogicalAddressSpaceNotAllowed)); } MemoryMappedView view = MemoryMappedView.CreateView(_handle, access, offset, size); return new MemoryMappedViewStream(view); } // Creates a new view in the form of an accessor. Accessors are for random access. public MemoryMappedViewAccessor CreateViewAccessor() { return CreateViewAccessor(0, DefaultSize, MemoryMappedFileAccess.ReadWrite); } public MemoryMappedViewAccessor CreateViewAccessor(Int64 offset, Int64 size) { return CreateViewAccessor(offset, size, MemoryMappedFileAccess.ReadWrite); } [System.Security.SecurityCritical] [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)] public MemoryMappedViewAccessor CreateViewAccessor(Int64 offset, Int64 size, MemoryMappedFileAccess access) { if (offset < 0) { throw new ArgumentOutOfRangeException("offset", SR.GetString(SR.ArgumentOutOfRange_NeedNonNegNum)); } if (size < 0) { throw new ArgumentOutOfRangeException("size", SR.GetString(SR.ArgumentOutOfRange_PositiveOrDefaultSizeRequired)); } if (access < MemoryMappedFileAccess.ReadWrite || access > MemoryMappedFileAccess.ReadWriteExecute) { throw new ArgumentOutOfRangeException("access"); } if (IntPtr.Size == 4 && size > UInt32.MaxValue) { throw new ArgumentOutOfRangeException("size", SR.GetString(SR.ArgumentOutOfRange_CapacityLargerThanLogicalAddressSpaceNotAllowed)); } MemoryMappedView view = MemoryMappedView.CreateView(_handle, access, offset, size); return new MemoryMappedViewAccessor(view); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } [SecuritySafeCritical] protected virtual void Dispose(bool disposing) { try { if (_handle != null && !_handle.IsClosed) { _handle.Dispose(); } } finally { if (_fileStream != null && _leaveOpen == false) { _fileStream.Dispose(); } } } public SafeMemoryMappedFileHandle SafeMemoryMappedFileHandle { [SecurityCritical] [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)] get { return _handle; } } [System.Security.SecurityCritical] public MemoryMappedFileSecurity GetAccessControl() { if (_handle.IsClosed) { __Error.FileNotOpen(); } return new MemoryMappedFileSecurity(_handle, AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group); } [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] [System.Security.SecurityCritical] public void SetAccessControl(MemoryMappedFileSecurity memoryMappedFileSecurity) { if (memoryMappedFileSecurity == null) { throw new ArgumentNullException("memoryMappedFileSecurity"); } if (_handle.IsClosed) { __Error.FileNotOpen(); } memoryMappedFileSecurity.PersistHandle(_handle); } // We don't need to expose this now that we have created views that can start at any address. [System.Security.SecurityCritical] internal static Int32 GetSystemPageAllocationGranularity() { UnsafeNativeMethods.SYSTEM_INFO info = new UnsafeNativeMethods.SYSTEM_INFO(); UnsafeNativeMethods.GetSystemInfo(ref info); return info.dwAllocationGranularity; } // This converts a MemoryMappedFileAccess to it's corresponding native PAGE_XXX value to be used by the // factory methods that construct a new memory mapped file object. MemoryMappedFileAccess.Write is not // valid here since there is no corresponding PAGE_XXX value. internal static Int32 GetPageAccess(MemoryMappedFileAccess access) { if (access == MemoryMappedFileAccess.Read) { return UnsafeNativeMethods.PAGE_READONLY; } else if (access == MemoryMappedFileAccess.ReadWrite) { return UnsafeNativeMethods.PAGE_READWRITE; } else if (access == MemoryMappedFileAccess.CopyOnWrite) { return UnsafeNativeMethods.PAGE_WRITECOPY; } else if (access == MemoryMappedFileAccess.ReadExecute) { return UnsafeNativeMethods.PAGE_EXECUTE_READ; } else if (access == MemoryMappedFileAccess.ReadWriteExecute) { return UnsafeNativeMethods.PAGE_EXECUTE_READWRITE; } // If we reached here, access was invalid. throw new ArgumentOutOfRangeException("access"); } // This converts a MemoryMappedFileAccess to its corresponding native FILE_MAP_XXX value to be used when // creating new views. internal static Int32 GetFileMapAccess(MemoryMappedFileAccess access) { if (access == MemoryMappedFileAccess.Read) { return UnsafeNativeMethods.FILE_MAP_READ; } else if (access == MemoryMappedFileAccess.Write) { return UnsafeNativeMethods.FILE_MAP_WRITE; } else if (access == MemoryMappedFileAccess.ReadWrite) { return UnsafeNativeMethods.FILE_MAP_READ | UnsafeNativeMethods.FILE_MAP_WRITE; } else if (access == MemoryMappedFileAccess.CopyOnWrite) { return UnsafeNativeMethods.FILE_MAP_COPY; } else if (access == MemoryMappedFileAccess.ReadExecute) { return UnsafeNativeMethods.FILE_MAP_EXECUTE | UnsafeNativeMethods.FILE_MAP_READ; } else if (access == MemoryMappedFileAccess.ReadWriteExecute) { return UnsafeNativeMethods.FILE_MAP_EXECUTE | UnsafeNativeMethods.FILE_MAP_READ | UnsafeNativeMethods.FILE_MAP_WRITE; } // If we reached here, access was invalid. throw new ArgumentOutOfRangeException("access"); } // This converts a MemoryMappedFileAccess to a FileSystemRights for use by FileStream private static FileSystemRights GetFileStreamFileSystemRights(MemoryMappedFileAccess access) { switch (access) { case MemoryMappedFileAccess.Read: case MemoryMappedFileAccess.CopyOnWrite: return FileSystemRights.ReadData; case MemoryMappedFileAccess.ReadWrite: return FileSystemRights.ReadData | FileSystemRights.WriteData; case MemoryMappedFileAccess.Write: return FileSystemRights.WriteData; case MemoryMappedFileAccess.ReadExecute: return FileSystemRights.ReadData | FileSystemRights.ExecuteFile; case MemoryMappedFileAccess.ReadWriteExecute: return FileSystemRights.ReadData | FileSystemRights.WriteData | FileSystemRights.ExecuteFile; default: // If we reached here, access was invalid. throw new ArgumentOutOfRangeException("access"); } } // This converts a MemoryMappedFileAccess to a FileAccess. MemoryMappedViewStream and // MemoryMappedViewAccessor subclass UnmanagedMemoryStream and UnmanagedMemoryAccessor, which both use // FileAccess to determine whether they are writable and/or readable. internal static FileAccess GetFileAccess(MemoryMappedFileAccess access) { if (access == MemoryMappedFileAccess.Read) { return FileAccess.Read; } if (access == MemoryMappedFileAccess.Write) { return FileAccess.Write; } else if (access == MemoryMappedFileAccess.ReadWrite) { return FileAccess.ReadWrite; } else if (access == MemoryMappedFileAccess.CopyOnWrite) { return FileAccess.ReadWrite; } else if (access == MemoryMappedFileAccess.ReadExecute) { return FileAccess.Read; } else if (access == MemoryMappedFileAccess.ReadWriteExecute) { return FileAccess.ReadWrite; } // If we reached here, access was invalid. throw new ArgumentOutOfRangeException("access"); } // Helper method used to extract the native binary security descriptor from the MemoryMappedFileSecurity // type. If pinningHandle is not null, caller must free it AFTER the call to CreateFile has returned. [System.Security.SecurityCritical] private unsafe static UnsafeNativeMethods.SECURITY_ATTRIBUTES GetSecAttrs(HandleInheritability inheritability, MemoryMappedFileSecurity memoryMappedFileSecurity, out Object pinningHandle) { pinningHandle = null; UnsafeNativeMethods.SECURITY_ATTRIBUTES secAttrs = null; if ((inheritability & HandleInheritability.Inheritable) != 0 || memoryMappedFileSecurity != null) { secAttrs = new UnsafeNativeMethods.SECURITY_ATTRIBUTES(); secAttrs.nLength = (Int32)Marshal.SizeOf(secAttrs); if ((inheritability & HandleInheritability.Inheritable) != 0) { secAttrs.bInheritHandle = 1; } // For ACLs, get the security descriptor from the MemoryMappedFileSecurity. if (memoryMappedFileSecurity != null) { byte[] sd = memoryMappedFileSecurity.GetSecurityDescriptorBinaryForm(); pinningHandle = GCHandle.Alloc(sd, GCHandleType.Pinned); fixed (byte* pSecDescriptor = sd) secAttrs.pSecurityDescriptor = pSecDescriptor; } } return secAttrs; } // clean up: close file handle and delete files we created private static void CleanupFile(FileStream fileStream, bool existed, String path) { fileStream.Close(); if (!existed) { File.Delete(path); } } } }
#if UNITY_EDITOR using UnityEditor; #endif using UnityEngine; using System; using System.IO; using System.Collections; using System.Collections.Generic; using System.Security.Cryptography; using System.Text; using System.Linq; namespace UnityCloudData { public struct CloudDataSheetWriteQueueEntry { public string sheetKey { get; private set; } public string putEntry { get; private set; } public string putUrl { get; private set; } public static CloudDataSheetWriteQueueEntry Get(string key, string entry, string url) { CloudDataSheetWriteQueueEntry writeQueueEntry = new CloudDataSheetWriteQueueEntry(); writeQueueEntry.sheetKey = key; writeQueueEntry.putEntry = entry; writeQueueEntry.putUrl = url; return writeQueueEntry; } } [ExecuteInEditMode] [AddComponentMenu("Unity Cloud Data/Cloud Data Sheet")] public class CloudDataSheet : JsonCloudDataSheet { public enum ApiEnvironments { dev, staging, production } const string k_ApiHostDev = "data-api-dev.cloud.unity3d.com"; const string k_ApiHostStaging = "data-api-staging.cloud.unity3d.com"; const string k_ApiHostProduction = "data-api.cloud.unity3d.com"; const string k_AccessTokenPostfixTemplate = "?access_token={0}"; const string k_SheetTokenPostfixTemplate = "?sheet_token={0}"; public bool debugUnusedKeys; [HideInInspector] public string sheetToken; [HideInInspector] public ApiEnvironments apiEnv = ApiEnvironments.production; protected Queue<CloudDataSheetWriteQueueEntry> m_WriteQueue = new Queue<CloudDataSheetWriteQueueEntry>(); protected WriteFinishDelegate m_WriteFinishCallback; protected CloudDataSheetWriteQueueEntry m_CurrentWriteEntry; public List<string> unusedSheetKeys { get; protected set; } protected virtual string apiHost { get { switch(apiEnv) { case ApiEnvironments.dev: return k_ApiHostDev; case ApiEnvironments.staging: return k_ApiHostStaging; default: return k_ApiHostProduction; } } } protected virtual string defaultUrlTemplate { get { return "https://" + apiHost + "/api/orgs/{0}/projects/{1}/sheet/{2}"; } } protected virtual string valueUrlTemplate { get { return "https://" + apiHost + "/api/orgs/{0}/projects/{1}/value/{2}/{3}"; } } protected virtual string sheetTokenUrlTemplate { get { return "https://" + apiHost + "/api/orgs/{0}/projects/{1}/tokens/{2}"; } } protected virtual string baseUrl { get { return string.Format(defaultUrlTemplate, myManager.organizationId, myManager.projectId, path); } } public override string sheetReadUrl { get { return baseUrl + GetAccessUrlPostfix(true); } } public override string sheetWriteUrl { get { return baseUrl + GetAccessUrlPostfix(false); } } public virtual string tokenReadUrl { get { return string.Format(sheetTokenUrlTemplate, myManager.organizationId, myManager.projectId, path) + GetAccessUrlPostfix(false); } } protected override string newSheetEntries { get { Debug.Log(string.Format("[Unity Cloud Data] There are {0} entries to save in the queue.", m_WriteQueue.Count)); string rawData = "["; bool first = true; while(m_WriteQueue.Count > 0) { CloudDataSheetWriteQueueEntry entry = m_WriteQueue.Dequeue(); if (first) { first = false; } else { rawData += ","; } rawData += entry.putEntry; } rawData += "]"; return rawData; } } protected virtual string getValueUrl(string key) { return string.Format(valueUrlTemplate, new object[] { myManager.organizationId, myManager.projectId, path, key }); } protected virtual string GetAccessUrlPostfix(bool readOnly) { #if UNITY_EDITOR if(readOnly) { return string.Format(k_SheetTokenPostfixTemplate, sheetToken); } else { return string.Format(k_AccessTokenPostfixTemplate, CloudDataManager.accessToken); } #else return string.Format(k_SheetTokenPostfixTemplate, sheetToken); #endif } protected override Dictionary<string,object> ParseSheetData(string tableData) { unusedSheetKeys = new List<string>(); return base.ParseSheetData(tableData); } protected override void OnParseSheet(Dictionary<string,object> dict) { foreach (var entry in dict) { unusedSheetKeys.Add(entry.Key); } base.OnParseSheet(dict); } public override object GetValue(string key) { unusedSheetKeys.Remove(key); return base.GetValue (key); } protected override void LoadFromURL() { #if UNITY_EDITOR if(String.IsNullOrEmpty(sheetToken)) { LoadSheetToken(); } else { base.LoadFromURL(); } #else base.LoadFromURL(); #endif } protected virtual void LoadSheetToken() { Debug.Log("[Unity Cloud Data] Requesting sheet token from Unity Cloud Data for sheet: '"+path+"'"); if (Application.internetReachability == NetworkReachability.NotReachable) { Debug.LogWarning("[Unity Cloud Data] Internet connection not detected; skipping sheet token request for '"+path+"'"); return; } isRefreshing = true; #if UNITY_EDITOR UnityEditor.EditorUtility.SetDirty(gameObject); #endif WWWUtility.StartRequest(tokenReadUrl, FinishedLoadingSheetToken); } protected virtual void FinishedLoadingSheetToken(WWWUtility utility) { isRefreshing = false; #if UNITY_EDITOR UnityEditor.EditorUtility.SetDirty(gameObject); #endif var www = utility.www; // handle loading error if(www.error != null) { if (www.error.Contains("404")) { hasBeenCreatedInCloud = false; Debug.LogWarning(string.Format("[Unity Cloud Data] sheet '{0}' not found in Unity Cloud Data. Need to create it?", path)); } else { Debug.LogError(string.Format("[Unity Cloud Data] Error getting token for sheet '{0}': {1}", path, www.error)); } return; } string text = www.text; var data = MiniJSON.Json.Deserialize(text) as List<object>; if(data != null && data.Count > 0) { var dict = data[0] as Dictionary<string,object>; sheetToken = (dict != null) ? dict["token"] as string : null; } // load data using new sheet token if(!String.IsNullOrEmpty(sheetToken)) { base.LoadFromURL(); } else { Debug.LogError(string.Format("[Unity Cloud Data] Error parsing sheet token for sheet'{0}': raw data: {1}", path, text)); } } void WriteQueueEntries() { if(m_WriteQueue.Count > 0) { m_CurrentWriteEntry = m_WriteQueue.Dequeue(); // Create request headers var headers = new Dictionary<string, string>(); headers.Add("Content-Type", "application/json"); Debug.Log(string.Format("[Unity Cloud Data] writing key '{0}' for sheet at path '{1}'", m_CurrentWriteEntry.sheetKey, path)); byte[] body = Encoding.UTF8.GetBytes(m_CurrentWriteEntry.putEntry); WWWUtility.StartRequest(m_CurrentWriteEntry.putUrl, body, headers, FinishedWritingEntry); } else { Debug.Log(string.Format("[Unity Cloud Data] Done saving sheet at path '{0}'!", path)); // wait until after the refresh completes to trigger the callback onRefreshCacheComplete += PostWriteRefreshFinished; RefreshCache(); } } void FinishedWritingEntry(WWWUtility utility) { var response = utility.www; if(response.error != null) { Debug.LogWarning(string.Format("[Unity Cloud Data] Error writing key '{0}' to sheet at path '{1}': {2}", m_CurrentWriteEntry.sheetKey, path,response.error)); } else { Debug.Log(string.Format("[Unity Cloud Data] Successfully wrote key '{0}' to sheet at path '{1}'", m_CurrentWriteEntry.sheetKey, path)); } WriteQueueEntries(); } protected void PostWriteRefreshFinished(BaseCloudDataSheet sheet) { onRefreshCacheComplete -= PostWriteRefreshFinished; if (m_WriteFinishCallback != null) { m_WriteFinishCallback(this, true); } } protected virtual CloudDataSheetWriteQueueEntry GetInsertQueueEntry(string cloudDataKey, object val) { // Create put entry string entry = " {" + " \"value\": " + val + " }"; // Format URL string putUrl = getValueUrl(cloudDataKey) + GetAccessUrlPostfix(false); return CloudDataSheetWriteQueueEntry.Get(cloudDataKey, entry, putUrl); } public override void InsertValue(string key, object val, System.Type fieldType) { // Make sure this key hasn't been queued up already and create a write queue entry string formattedValue = CloudDataTypeSerialization.SerializeValue(val, fieldType); int count = m_WriteQueue.Count(item => (item.sheetKey == key)); if(count == 0) { m_WriteQueue.Enqueue(GetInsertQueueEntry(key, formattedValue)); } } public override void Save(WriteFinishDelegate del) { if(m_WriteQueue.Count <= 0) { if (del != null) { del(this, true); } return; } Debug.Log(string.Format("[Unity Cloud Data] There are {0} entries to save in the queue.", m_WriteQueue.Count)); #if UNITY_EDITOR m_WriteFinishCallback = del; WriteQueueEntries(); #endif } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; namespace HouraiTeahouse { /// <summary> Set of extension methods for collections and enumerations of any type. </summary> public static class GenericCollectionExtensions { // Tries to get a value from a dictionary. Returns the default value if the dictionary or public static T GetOrDefault<TKey, T>(this IDictionary<TKey, T> dictionary, TKey key) { return dictionary != null && dictionary.ContainsKey(key) ? dictionary[key] : default(T); } // Tries to get a value from a dictionary, and adds one if it doesn't exist. // Throws an ArgumentNullException if $dictionary is null. public static T GetOrAdd<TKey, T>(this IDictionary<TKey, T> dictionary, TKey key) where T : new() { Argument.NotNull(dictionary); if (!dictionary.ContainsKey(key)) dictionary[key] = new T(); return dictionary[key]; } // Gets only the keys from a KVP set. public static IEnumerable<TKey> Keys<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> enumerable) { return enumerable.Select(k => k.Key); } // Gets only the values from a KVP set. public static IEnumerable<TValue> Values<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> enumerable) { return enumerable.Select(k => k.Value); } /// <summary> Checks if the enumeration is null or empty. </summary> /// <param name="enumeration"> the enumeration of values </param> /// <returns> true if <paramref name="enumeration" /> is null or empty. </returns> public static bool IsNullOrEmpty(this IEnumerable enumeration) { var s = enumeration as string; if (s != null) return string.IsNullOrEmpty(s); return enumeration == null || IsEmpty(enumeration); } /// <summary> Checks if a enumeration is empty or not. </summary> /// <param name="enumeration"> the enumeration of values </param> /// <exception cref="ArgumentNullException"> <paramref name="enumeration" /> is null </exception> /// <returns> true if <paramref name="enumeration" /> is empty, false otherwise </returns> public static bool IsEmpty(this IEnumerable enumeration) { var collection = Argument.NotNull(enumeration) as ICollection; if (collection != null) return collection.Count <= 0; return !enumeration.Cast<object>().Any(); } /// <summary> Samples one every N elements from an enumeration. </summary> /// <typeparam name="T"> the type of values being enumerated </typeparam> /// <param name="enumeration"> the enumeration of values </param> /// <param name="count"> the subsampling rate </param> /// <exception cref="ArgumentNullException"> <paramref name="enumeration" /> is null </exception> /// <returns> the subsampled enumeration </returns> public static IEnumerable<T> SampleEvery<T>(this IEnumerable<T> enumeration, int count) { if (enumeration == null) yield break; int i = count; foreach (T val in enumeration) { if (i >= count) { yield return val; i = 0; } i++; } } public static IEnumerable<KeyValuePair<TKey, TValue>> Zip<TKey, TValue>(this IEnumerable<TKey> keys, IEnumerable<TValue> value) { IEnumerator<TKey> keyEnumerator = keys.EmptyIfNull().GetEnumerator(); IEnumerator<TValue> valueEnumerator = value.EmptyIfNull().GetEnumerator(); keyEnumerator.MoveNext(); valueEnumerator.MoveNext(); while (keyEnumerator.MoveNext() && valueEnumerator.MoveNext()) yield return new KeyValuePair<TKey, TValue>(keyEnumerator.Current, valueEnumerator.Current); } /// <summary> Creates an empty enumeration if the provided one is null. Used to avoid NullReferenceExceptions. </summary> /// <typeparam name="T"> the type of values being enumerated </typeparam> /// <param name="enumeration"> the enumeration of values </param> /// <returns> the same enumeration if it is not null, an empty enumeration if it is. </returns> public static IEnumerable<T> EmptyIfNull<T>(this IEnumerable<T> enumeration) { return enumeration ?? Enumerable.Empty<T>(); } /// <summary> Removes all null values from an enumeration. </summary> /// <typeparam name="T"> the type of values being enumerated </typeparam> /// <param name="enumeration"> the enumeration of values </param> /// <returns> the enumeration without null values, empty if <paramref name="enumeration" /> is null. </returns> public static IEnumerable<T> IgnoreNulls<T>(this IEnumerable<T> enumeration) where T : class { return enumeration.EmptyIfNull().Where(obj => obj != null); } /// <summary> Finds the key with the maximum value over an enumeration of key-value pairs. Note this is not a streaming /// operator. An infinite enumeration will infinitely loop. </summary> /// <typeparam name="K"> the type of of the keys </typeparam> /// <typeparam name="V"> the type of the values </typeparam> /// <param name="values"> the enumeration </param> /// <exception cref="ArgumentNullException"> <paramref name="values" /> is null </exception> /// <returns> the key of the maximum value </returns> public static K ArgMax<K, V>(this IEnumerable<KeyValuePair<K, V>> values) where V : IComparable<V> { return FindArg(Argument.NotNull(values), (v1, v2) => v1.CompareTo(v2) > 0); } /// <summary> Finds the key with the minimum value over an enumeration of key-value pairs. Note this is not a streaming /// operator. An infinite enumeration will infinitely loop. </summary> /// <typeparam name="K"> the type of of the keys </typeparam> /// <typeparam name="V"> the type of the values </typeparam> /// <param name="values"> the enumeration </param> /// <exception cref="ArgumentNullException"> <paramref name="values" /> is null </exception> /// <returns> the key of the minimum value </returns> public static K ArgMin<K, V>(this IEnumerable<KeyValuePair<K, V>> values) where V : IComparable<V> { return FindArg(Argument.NotNull(values), (v1, v2) => v1.CompareTo(v2) < 0); } static K FindArg<K, V>(IEnumerable<KeyValuePair<K, V>> values, Func<V, V, bool> func) { IEnumerator<KeyValuePair<K, V>> iterator = values.GetEnumerator(); if (!iterator.MoveNext()) throw new InvalidOperationException(); K key = iterator.Current.Key; V val = iterator.Current.Value; while (iterator.MoveNext()) { if (!func(iterator.Current.Value, val)) continue; key = iterator.Current.Key; val = iterator.Current.Value; } return key; } /// <summary> Finds the index of the maximum value over an enumeration. Note this is not a streaming operator. An infinite /// enumeration will infinitely loop. </summary> /// <typeparam name="T"> the type of the values being enumerated </typeparam> /// <param name="values"> the enumeration </param> /// <exception cref="ArgumentNullException"> <paramref name="values" /> is null </exception> /// <returns> the index of the maximum value </returns> public static int ArgMax<T>(this IEnumerable<T> values) where T : IComparable<T> { return FindIndex(Argument.NotNull(values), (v1, v2) => v1.CompareTo(v2) > 0); } /// <summary> Finds the index of the minimum value over an enumeration. Note this is not a streaming operator. An infinite /// enumeration will infinitely loop. </summary> /// <typeparam name="T"> the type of the values being enumerated </typeparam> /// <param name="values"> the enumeration </param> /// <exception cref="ArgumentNullException"> <paramref name="values" /> is null </exception> /// <returns> the index of the minimum value </returns> public static int ArgMin<T>(this IEnumerable<T> values) where T : IComparable<T> { return FindIndex(Argument.NotNull(values), (v1, v2) => v1.CompareTo(v2) < 0); } static int FindIndex<T>(IEnumerable<T> enumeration, Func<T, T, bool> func) { IEnumerator<T> iterator = enumeration.GetEnumerator(); if (!iterator.MoveNext()) throw new InvalidOperationException(); var index = 0; T val = iterator.Current; var i = 0; while (iterator.MoveNext()) { i++; if (!func(iterator.Current, val)) continue; index = i; val = iterator.Current; } return index; } /// <summary> Selects a random element from a list. </summary> /// <typeparam name="T"> the type of the list </typeparam> /// <param name="list"> the list to randomly select from </param> /// <exception cref="ArgumentNullException"> <paramref name="list" /> is null </exception> /// <returns> a random element from the list </returns> public static T Random<T>(this IList<T> list) { Argument.NotNull(list); return list.Random(0, list.Count); } /// <summary> Selects a random element from a list, within a specified range. </summary> /// <typeparam name="T"> the type of the list </typeparam> /// <param name="list"> the list to randomly select from </param> /// <param name="start"> the start index of the range to select from. Will be clamped to [0, list.Count] </param> /// <param name="end"> the start index of the range to select from. Will be clamped to [0, list.Count] </param> /// <exception cref="ArgumentNullException"> <paramref name="list" /> is null </exception> /// <returns> a random element from the list selected from the range </returns> public static T Random<T>(this IList<T> list, int start, int end) { Argument.NotNull(list); start = Mathf.Clamp(start, 0, list.Count); end = Mathf.Clamp(end, 0, list.Count); return list[UnityEngine.Random.Range(start, end)]; } } }
#region License /* * Copyright 2002-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion #region Imports using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Web.UI; using Spring.Collections; using Spring.Validation; using IValidator = Spring.Validation.IValidator; using Spring.Context; using Spring.Context.Support; using Spring.Globalization; using System.ComponentModel; using System.Globalization; using System.Resources; using Spring.Web.Support; #endregion Imports namespace Spring.Web.UI { #region ASP.NET 2.0 Spring Master Page Implementation /// <summary> /// Spring.NET Master Page implementation for ASP.NET 2.0 /// </summary> /// <author>Aleksandar Seovic</author> public class MasterPage : System.Web.UI.MasterPage, IApplicationContextAware, ISupportsWebDependencyInjection, IWebNavigable { #region Instance Fields private ILocalizer localizer; private IValidationErrors validationErrors = new ValidationErrors(); private IMessageSource messageSource; private IApplicationContext applicationContext; private IApplicationContext defaultApplicationContext; private IWebNavigator webNavigator; private IDictionary args; #endregion #region Lifecycle methods /// <summary> /// Initialize a new MasterPage instance. /// </summary> public MasterPage() { InitializeNavigationSupport(); } /// <summary> /// Initializes user control. /// </summary> protected override void OnInit(EventArgs e) { InitializeMessageSource(); base.OnInit(e); // initialize controls OnInitializeControls(EventArgs.Empty); } /// <summary> /// Binds data from the data model into controls and raises /// PreRender event afterwards. /// </summary> /// <param name="e">Event arguments.</param> protected override void OnPreRender(EventArgs e) { if (localizer != null) { localizer.ApplyResources(this, messageSource, UserCulture); } else if (Page.Localizer != null) { Page.Localizer.ApplyResources(this, messageSource, UserCulture); } base.OnPreRender(e); } /// <summary> /// This event is raised before Load event and should be used to initialize /// controls as necessary. /// </summary> public event EventHandler InitializeControls; /// <summary> /// Raises InitializeControls event. /// </summary> /// <param name="e">Event arguments.</param> protected virtual void OnInitializeControls(EventArgs e) { if (InitializeControls != null) { InitializeControls(this, e); } } /// <summary> /// Obtains a <see cref="T:System.Web.UI.UserControl"/> object from a user control file /// and injects dependencies according to Spring config file. /// </summary> /// <param name="virtualPath">The virtual path to a user control file.</param> /// <returns> /// Returns the specified <see langword="UserControl"/> object, with dependencies injected. /// </returns> protected virtual new Control LoadControl(string virtualPath) { Control control = base.LoadControl(virtualPath); control = WebDependencyInjectionUtils.InjectDependenciesRecursive(defaultApplicationContext,control); return control; } /// <summary> /// Obtains a <see cref="T:System.Web.UI.UserControl"/> object by type /// and injects dependencies according to Spring config file. /// </summary> /// <param name="t">The type of a user control.</param> /// <param name="parameters">parameters to pass to the control</param> /// <returns> /// Returns the specified <see langword="UserControl"/> object, with dependencies injected. /// </returns> protected virtual new Control LoadControl( Type t, params object[] parameters) { Control control = base.LoadControl( t, parameters ); control = WebDependencyInjectionUtils.InjectDependenciesRecursive(defaultApplicationContext,control); return control; } #endregion Control lifecycle methods #region Data binding events /// <summary> /// This event is raised after all controls have been populated with values /// from the data model. /// </summary> public event EventHandler DataBound; /// <summary> /// Raises DataBound event. /// </summary> /// <param name="e">Event arguments.</param> protected virtual void OnDataBound(EventArgs e) { if (DataBound != null) { DataBound(this, e); } } /// <summary> /// This event is raised after data model has been populated with values from /// web controls. /// </summary> public event EventHandler DataUnbound; /// <summary> /// Raises DataBound event. /// </summary> /// <param name="e">Event arguments.</param> protected virtual void OnDataUnbound(EventArgs e) { if (DataUnbound != null) { DataUnbound(this, e); } } #endregion #region Application context support /// <summary> /// Gets or sets the <see cref="Spring.Context.IApplicationContext"/> that this /// object runs in. /// </summary> /// <value></value> /// <remarks> /// <p> /// Normally this call will be used to initialize the object. /// </p> /// <p> /// Invoked after population of normal object properties but before an /// init callback such as /// <see cref="Spring.Objects.Factory.IInitializingObject"/>'s /// <see cref="Spring.Objects.Factory.IInitializingObject.AfterPropertiesSet"/> /// or a custom init-method. Invoked after the setting of any /// <see cref="Spring.Context.IResourceLoaderAware"/>'s /// <see cref="Spring.Context.IResourceLoaderAware.ResourceLoader"/> /// property. /// </p> /// </remarks> /// <exception cref="Spring.Context.ApplicationContextException"> /// In the case of application context initialization errors. /// </exception> /// <exception cref="Spring.Objects.ObjectsException"> /// If thrown by any application context methods. /// </exception> /// <exception cref="Spring.Objects.Factory.ObjectInitializationException"/> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public virtual IApplicationContext ApplicationContext { get { return applicationContext; } set { applicationContext = value; } } #endregion #region Message source and localization support /// <summary> /// Gets or sets the localizer. /// </summary> /// <value>The localizer.</value> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public ILocalizer Localizer { get { return localizer; } set { localizer = value; if (localizer.ResourceCache is NullResourceCache) { localizer.ResourceCache = new AspNetResourceCache(); } } } /// <summary> /// Gets or sets the local message source. /// </summary> /// <value>The local message source.</value> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public IMessageSource MessageSource { get { return messageSource; } set { messageSource = value; if (messageSource != null && messageSource is AbstractMessageSource) { ((AbstractMessageSource) messageSource).ParentMessageSource = applicationContext; } } } /// <summary> /// Initializes local message source /// </summary> protected void InitializeMessageSource() { if (MessageSource == null) { string key = GetType().FullName + ".MessageSource"; MessageSource = (IMessageSource) Context.Cache.Get(key); if (MessageSource == null) { ResourceSetMessageSource defaultMessageSource = new ResourceSetMessageSource(); ResourceManager rm = GetLocalResourceManager(); if (rm != null) { defaultMessageSource.ResourceManagers.Add(rm); } Context.Cache.Insert(key, defaultMessageSource); MessageSource = defaultMessageSource; } } } /// <summary> /// Creates and returns local ResourceManager for this page. /// </summary> /// <remarks> /// <para> /// In ASP.NET 1.1, this method loads local resources from the web application assembly. /// </para> /// <para> /// However, in ASP.NET 2.0, local resources are compiled into the dynamic assembly, /// so we need to find that assembly instead and load the resources from it. /// </para> /// </remarks> /// <returns>Local ResourceManager instance.</returns> private ResourceManager GetLocalResourceManager() { return LocalResourceManager.GetLocalResourceManager(this); } /// <summary> /// Returns message for the specified resource name. /// </summary> /// <param name="name">Resource name.</param> /// <returns>Message text.</returns> public string GetMessage(string name) { return messageSource.GetMessage(name, UserCulture); } /// <summary> /// Returns message for the specified resource name. /// </summary> /// <param name="name">Resource name.</param> /// <param name="args">Message arguments that will be used to format return value.</param> /// <returns>Formatted message text.</returns> public string GetMessage(string name, params object[] args) { return messageSource.GetMessage(name, UserCulture, args); } /// <summary> /// Returns resource object for the specified resource name. /// </summary> /// <param name="name">Resource name.</param> /// <returns>Resource object.</returns> public object GetResourceObject(string name) { return messageSource.GetResourceObject(name, UserCulture); } /// <summary> /// Gets or sets user's culture /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public virtual CultureInfo UserCulture { get { return Page.UserCulture; } set { Page.UserCulture = value; } } #endregion #region Result support /// <summary> /// Ensure, that <see cref="WebNavigator"/> is set to a valid instance. /// </summary> /// <remarks> /// If <see cref="WebNavigator"/> is not already set, creates and sets a new <see cref="WebFormsResultWebNavigator"/> instance.<br/> /// Override this method if you don't want to inject a navigator, but need a different default. /// </remarks> protected virtual void InitializeNavigationSupport() { webNavigator = new WebFormsResultWebNavigator(this, null, null, true); } /// <summary> /// Gets/Sets the navigator to be used for handling <see cref="SetResult(string, object)"/> calls. /// </summary> public IWebNavigator WebNavigator { get { return webNavigator; } set { webNavigator = value; } } /// <summary> /// Gets or sets map of result names to target URLs /// </summary> /// <remarks> /// Using <see cref="Results"/> requires <see cref="WebNavigator"/> to implement <see cref="IResultWebNavigator"/>. /// </remarks> [Browsable( false )] [DesignerSerializationVisibility( DesignerSerializationVisibility.Hidden )] public virtual IDictionary Results { get { if (WebNavigator is IResultWebNavigator) { return ((IResultWebNavigator)WebNavigator).Results; } return null; } set { if (WebNavigator is IResultWebNavigator) { ((IResultWebNavigator)WebNavigator).Results = value; return; } throw new NotSupportedException("WebNavigator must be of type IResultWebNavigator to support Results"); } } /// <summary> /// A convenience, case-insensitive table that may be used to e.g. pass data into SpEL expressions"/>. /// </summary> /// <remarks> /// By default, e.g. <see cref="SetResult(string)"/> passes the control instance into an expression. Using /// <see cref="Args"/> is an easy way to pass additional parameters into the expression /// <example> /// // config: /// /// &lt;property Name=&quot;Results&quot;&gt; /// &lt;dictionary&gt; /// &lt;entry key=&quot;ok_clicked&quot; value=&quot;redirect:~/ShowResult.aspx?result=%{Args['result']}&quot; /&gt; /// &lt;/dictionary&gt; /// &lt;/property&gt; /// /// // code: /// /// void OnOkClicked(object sender, EventArgs e) /// { /// Args[&quot;result&quot;] = txtUserInput.Text; /// SetResult(&quot;ok_clicked&quot;); /// } /// </example> /// </remarks> public IDictionary Args { get { if (args == null) { args = new CaseInsensitiveHashtable(); } return args; } } /// <summary> /// Redirects user to a URL mapped to specified result name. /// </summary> /// <param name="resultName">Result name.</param> protected void SetResult( string resultName ) { WebNavigator.NavigateTo( resultName, this, null ); } /// <summary> /// Redirects user to a URL mapped to specified result name. /// </summary> /// <param name="resultName">Name of the result.</param> /// <param name="context">The context to use for evaluating the SpEL expression in the Result.</param> protected void SetResult( string resultName, object context ) { WebNavigator.NavigateTo( resultName, this, context ); } /// <summary> /// Returns a redirect url string that points to the /// <see cref="Spring.Web.Support.Result.TargetPage"/> defined by this /// result evaluated using this Page for expression /// </summary> /// <param name="resultName">Name of the result.</param> /// <returns>A redirect url string.</returns> protected string GetResultUrl( string resultName ) { return ResolveUrl( WebNavigator.GetResultUri( resultName, this, null ) ); } /// <summary> /// Returns a redirect url string that points to the /// <see cref="Spring.Web.Support.Result.TargetPage"/> defined by this /// result evaluated using this Page for expression /// </summary> /// <param name="resultName">Name of the result.</param> /// <param name="context">The context to use for evaluating the SpEL expression in the Result</param> /// <returns>A redirect url string.</returns> protected string GetResultUrl( string resultName, object context ) { return ResolveUrl( WebNavigator.GetResultUri( resultName, this, context ) ); } #endregion #region Validation support /// <summary> /// Evaluates specified validators and returns <c>True</c> if all of them are valid. /// </summary> /// <remarks> /// <p> /// Each validator can itself represent a collection of other validators if it is /// an instance of <see cref="ValidatorGroup"/> or one of its derived types. /// </p> /// <p> /// Please see the Validation Framework section in the documentation for more info. /// </p> /// </remarks> /// <param name="validationContext">Object to validate.</param> /// <param name="validators">Validators to evaluate.</param> /// <returns> /// <c>True</c> if all of the specified validators are valid, <c>False</c> otherwise. /// </returns> public virtual bool Validate(object validationContext, params IValidator[] validators) { IDictionary<string, object> contextParams = CreateValidatorParameters(); bool result = true; foreach (IValidator validator in validators) { if (validator == null) { throw new ArgumentException("Validator is not defined."); } result = validator.Validate(validationContext, contextParams, this.validationErrors) && result; } return result; } /// <summary> /// Gets the validation errors container. /// </summary> /// <value>The validation errors container.</value> public virtual IValidationErrors ValidationErrors { get { return validationErrors; } } /// <summary> /// Creates the validator parameters. /// </summary> /// <remarks> /// <para> /// This method can be overriden if you want to pass additional parameters /// to the validation framework, but you should make sure that you call /// this base implementation in order to add page, session, application, /// request, response and context to the variables collection. /// </para> /// </remarks> /// <returns> /// Dictionary containing parameters that should be passed to /// the data validation framework. /// </returns> protected virtual IDictionary<string, object> CreateValidatorParameters() { IDictionary<string, object> parameters = new Dictionary<string, object>(8); parameters["page"] = this.Page; parameters["usercontrol"] = this; parameters["session"] = this.Session; parameters["application"] = this.Application; parameters["request"] = this.Request; parameters["response"] = this.Response; parameters["context"] = this.Context; return parameters; } #endregion #region Spring Page support /// <summary> /// Overrides Page property to return <see cref="Spring.Web.UI.Page"/> /// instead of <see cref="System.Web.UI.Page"/>. /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public new Page Page { get { return (Page) base.Page; } } #endregion #region Dependency Injection Support /// <summary> /// Holds the default ApplicationContext to be used during DI. /// </summary> IApplicationContext ISupportsWebDependencyInjection.DefaultApplicationContext { get { return defaultApplicationContext; } set { defaultApplicationContext = value; } } /// <summary> /// Injects dependencies before adding the control. /// </summary> protected override void AddedControl(Control control,int index) { control = WebDependencyInjectionUtils.InjectDependenciesRecursive(defaultApplicationContext,control); base.AddedControl(control,index); } #endregion Dependency Injection Support } #endregion }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Text; using Microsoft.VisualStudio.Debugger.Interop; using System.Diagnostics; using System.Globalization; using MICore; using System.Threading.Tasks; using System.Linq; namespace Microsoft.MIDebugEngine { public static class EngineUtils { internal static string AsAddr(ulong addr, bool is64bit) { string addrFormat = is64bit ? "x16" : "x8"; return "0x" + addr.ToString(addrFormat, CultureInfo.InvariantCulture); } internal static string GetAddressDescription(DebuggedProcess proc, ulong ip) { string description = null; proc.WorkerThread.RunOperation(async () => { description = await EngineUtils.GetAddressDescriptionAsync(proc, ip); } ); return description; } internal static async Task<string> GetAddressDescriptionAsync(DebuggedProcess proc, ulong ip) { string location = null; IEnumerable<DisasmInstruction> instructions = await proc.Disassembly.FetchInstructions(ip, 1); if (instructions != null) { foreach (DisasmInstruction instruction in instructions) { if (location == null && !String.IsNullOrEmpty(instruction.Symbol)) { location = instruction.Symbol; break; } } } if (location == null) { string addrFormat = proc.Is64BitArch ? "x16" : "x8"; location = ip.ToString(addrFormat, CultureInfo.InvariantCulture); } return location; } public static void CheckOk(int hr) { if (hr != 0) { throw new MIException(hr); } } public static void RequireOk(int hr) { if (hr != 0) { throw new InvalidOperationException(); } } public static AD_PROCESS_ID GetProcessId(IDebugProcess2 process) { AD_PROCESS_ID[] pid = new AD_PROCESS_ID[1]; EngineUtils.RequireOk(process.GetPhysicalProcessId(pid)); return pid[0]; } public static int UnexpectedException(Exception e) { Debug.Fail("Unexpected exception during Attach"); return Constants.RPC_E_SERVERFAULT; } internal static bool IsFlagSet(uint value, int flagValue) { return (value & flagValue) != 0; } internal static bool ProcIdEquals(AD_PROCESS_ID pid1, AD_PROCESS_ID pid2) { if (pid1.ProcessIdType != pid2.ProcessIdType) { return false; } else if (pid1.ProcessIdType == (int)enum_AD_PROCESS_ID.AD_PROCESS_ID_SYSTEM) { return pid1.dwProcessId == pid2.dwProcessId; } else { return pid1.guidProcessId == pid2.guidProcessId; } } // // The RegisterNameMap maps register names to logical group names. The architecture of // the platform is described with all its varients. Any particular target may only contains a subset // of the available registers. public class RegisterNameMap { private Entry[] _map; private struct Entry { public readonly string Name; public readonly bool IsRegex; public readonly string Group; public Entry(string name, bool isRegex, string group) { Name = name; IsRegex = isRegex; Group = group; } }; private static readonly Entry[] s_arm32Registers = new Entry[] { new Entry( "sp", false, "CPU"), new Entry( "lr", false, "CPU"), new Entry( "pc", false, "CPU"), new Entry( "cpsr", false, "CPU"), new Entry( "r[0-9]+", true, "CPU"), new Entry( "fpscr", false, "FPU"), new Entry( "f[0-9]+", true, "FPU"), new Entry( "s[0-9]+", true, "IEEE Single"), new Entry( "d[0-9]+", true, "IEEE Double"), new Entry( "q[0-9]+", true, "Vector"), }; private static readonly Entry[] s_X86Registers = new Entry[] { new Entry( "eax", false, "CPU" ), new Entry( "ecx", false, "CPU" ), new Entry( "edx", false, "CPU" ), new Entry( "ebx", false, "CPU" ), new Entry( "esp", false, "CPU" ), new Entry( "ebp", false, "CPU" ), new Entry( "esi", false, "CPU" ), new Entry( "edi", false, "CPU" ), new Entry( "eip", false, "CPU" ), new Entry( "eflags", false, "CPU" ), new Entry( "cs", false, "CPU" ), new Entry( "ss", false, "CPU" ), new Entry( "ds", false, "CPU" ), new Entry( "es", false, "CPU" ), new Entry( "fs", false, "CPU" ), new Entry( "gs", false, "CPU" ), new Entry( "st", true, "CPU" ), new Entry( "fctrl", false, "CPU" ), new Entry( "fstat", false, "CPU" ), new Entry( "ftag", false, "CPU" ), new Entry( "fiseg", false, "CPU" ), new Entry( "fioff", false, "CPU" ), new Entry( "foseg", false, "CPU" ), new Entry( "fooff", false, "CPU" ), new Entry( "fop", false, "CPU" ), new Entry( "mxcsr", false, "CPU" ), new Entry( "orig_eax", false, "CPU" ), new Entry( "al", false, "CPU" ), new Entry( "cl", false, "CPU" ), new Entry( "dl", false, "CPU" ), new Entry( "bl", false, "CPU" ), new Entry( "ah", false, "CPU" ), new Entry( "ch", false, "CPU" ), new Entry( "dh", false, "CPU" ), new Entry( "bh", false, "CPU" ), new Entry( "ax", false, "CPU" ), new Entry( "cx", false, "CPU" ), new Entry( "dx", false, "CPU" ), new Entry( "bx", false, "CPU" ), new Entry( "bp", false, "CPU" ), new Entry( "si", false, "CPU" ), new Entry( "di", false, "CPU" ), new Entry( "mm[0-7]", true, "MMX" ), new Entry( "xmm[0-7]ih", true, "SSE2" ), new Entry( "xmm[0-7]il", true, "SSE2" ), new Entry( "xmm[0-7]dh", true, "SSE2" ), new Entry( "xmm[0-7]dl", true, "SSE2" ), new Entry( "xmm[0-7][0-7]", true, "SSE" ), new Entry( "ymm.+", true, "AVX" ), new Entry( "mm[0-7][0-7]", true, "AMD3DNow" ), }; private static readonly Entry[] s_allRegisters = new Entry[] { new Entry( ".+", true, "CPU"), }; public static RegisterNameMap Create(string[] registerNames) { // TODO: more robust mechanism for determining processor architecture RegisterNameMap map = new RegisterNameMap(); if (registerNames[0][0] == 'r') // registers are prefixed with 'r', assume ARM and initialize its register sets { map._map = s_arm32Registers; } else if (registerNames[0][0] == 'e') // x86 register set { map._map = s_X86Registers; } else { // report one global register set map._map = s_allRegisters; } return map; } public string GetGroupName(string regName) { foreach (var e in _map) { if (e.IsRegex) { if (System.Text.RegularExpressions.Regex.IsMatch(regName, e.Name)) { return e.Group; } } else if (e.Name == regName) { return e.Group; } } return "Other Registers"; } }; internal static string GetExceptionDescription(Exception exception) { if (!ExceptionHelper.IsCorruptingException(exception)) { return exception.Message; } else { return string.Format(CultureInfo.CurrentCulture, MICoreResources.Error_CorruptingException, exception.GetType().FullName, exception.StackTrace); } } internal class SignalMap : Dictionary<string, uint> { private static SignalMap s_instance; private SignalMap() { this["SIGHUP"] = 1; this["SIGINT"] = 2; this["SIGQUIT"] = 3; this["SIGILL"] = 4; this["SIGTRAP"] = 5; this["SIGABRT"] = 6; this["SIGIOT"] = 6; this["SIGBUS"] = 7; this["SIGFPE"] = 8; this["SIGKILL"] = 9; this["SIGUSR1"] = 10; this["SIGSEGV"] = 11; this["SIGUSR2"] = 12; this["SIGPIPE"] = 13; this["SIGALRM"] = 14; this["SIGTERM"] = 15; this["SIGSTKFLT"] = 16; this["SIGCHLD"] = 17; this["SIGCONT"] = 18; this["SIGSTOP"] = 19; this["SIGTSTP"] = 20; this["SIGTTIN"] = 21; this["SIGTTOU"] = 22; this["SIGURG"] = 23; this["SIGXCPU"] = 24; this["SIGXFSZ"] = 25; this["SIGVTALRM"] = 26; this["SIGPROF"] = 27; this["SIGWINCH"] = 28; this["SIGIO"] = 29; this["SIGPOLL"] = 29; this["SIGPWR"] = 30; this["SIGSYS"] = 31; this["SIGUNUSED"] = 31; } public static SignalMap Instance { get { if (s_instance == null) { s_instance = new SignalMap(); } return s_instance; } } } } }
// Copyright 2011 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml; using Microsoft.Data.Edm.Internal; using Microsoft.Data.Edm.Library; using Microsoft.Data.Edm.Values; namespace Microsoft.Data.Edm.Validation.Internal { internal static class ValidationHelper { internal static bool IsEdmSystemNamespace(string namespaceName) { return (namespaceName == EdmConstants.TransientNamespace || namespaceName == EdmConstants.EdmNamespace); } internal static bool AddMemberNameToHashSet(IEdmNamedElement item, HashSetInternal<string> memberNameList, ValidationContext context, EdmErrorCode errorCode, string errorString, bool suppressError) { IEdmSchemaElement schemaElement = item as IEdmSchemaElement; string name = (schemaElement != null) ? schemaElement.FullName() : item.Name; if (!memberNameList.Add(name)) { if (!suppressError) { context.AddError(item.Location(), errorCode, errorString); } return false; } return true; } internal static bool AllPropertiesAreNullable(IEnumerable<IEdmStructuralProperty> properties) { return properties.Where(p => !p.Type.IsNullable).Count() == 0; } internal static bool HasNullableProperty(IEnumerable<IEdmStructuralProperty> properties) { return properties.Where(p => p.Type.IsNullable).Count() > 0; } internal static bool PropertySetIsSubset(IEnumerable<IEdmStructuralProperty> set, IEnumerable<IEdmStructuralProperty> subset) { return subset.Except(set).Count() <= 0; } internal static bool PropertySetsAreEquivalent(IEnumerable<IEdmStructuralProperty> set1, IEnumerable<IEdmStructuralProperty> set2) { if (set1.Count() != set2.Count()) { return false; } IEnumerator<IEdmStructuralProperty> set2Enum = set2.GetEnumerator(); foreach (IEdmStructuralProperty prop1 in set1) { set2Enum.MoveNext(); if (prop1 != set2Enum.Current) { return false; } } return true; } internal static bool ValidateValueCanBeWrittenAsXmlElementAnnotation(IEdmValue value, string annotationNamespace, string annotationName, out EdmError error) { IEdmStringValue edmStringValue = value as IEdmStringValue; if (edmStringValue == null) { error = new EdmError(value.Location(), EdmErrorCode.InvalidElementAnnotation, Edm.Strings.EdmModel_Validator_Semantic_InvalidElementAnnotationNotIEdmStringValue); return false; } string rawString = edmStringValue.Value; XmlReader reader = XmlReader.Create(new StringReader(rawString)); try { // Skip to root element. if (reader.NodeType != XmlNodeType.Element) { while (reader.Read() && reader.NodeType != XmlNodeType.Element) { } } // The annotation must be an element. if (reader.EOF) { error = new EdmError(value.Location(), EdmErrorCode.InvalidElementAnnotation, Edm.Strings.EdmModel_Validator_Semantic_InvalidElementAnnotationValueInvalidXml); return false; } // The root element must corespond to the term of the annotation string elementNamespace = reader.NamespaceURI; string elementName = reader.LocalName; if (EdmUtil.IsNullOrWhiteSpaceInternal(elementNamespace) || EdmUtil.IsNullOrWhiteSpaceInternal(elementName)) { error = new EdmError(value.Location(), EdmErrorCode.InvalidElementAnnotation, Edm.Strings.EdmModel_Validator_Semantic_InvalidElementAnnotationNullNamespaceOrName); return false; } if (!((annotationNamespace == null || elementNamespace == annotationNamespace) && (annotationName == null || elementName == annotationName))) { error = new EdmError(value.Location(), EdmErrorCode.InvalidElementAnnotation, Edm.Strings.EdmModel_Validator_Semantic_InvalidElementAnnotationMismatchedTerm); return false; } // Parse the entire fragment to determine if the XML is valid while (reader.Read()) { } error = null; return true; } catch (Exception) { error = new EdmError(value.Location(), EdmErrorCode.InvalidElementAnnotation, Edm.Strings.EdmModel_Validator_Semantic_InvalidElementAnnotationValueInvalidXml); return false; } } internal static bool IsInterfaceCritical(EdmError error) { return error.ErrorCode >= EdmErrorCode.InterfaceCriticalPropertyValueMustNotBeNull && error.ErrorCode <= EdmErrorCode.InterfaceCriticalCycleInTypeHierarchy; } internal static bool ItemExistsInReferencedModel(this IEdmModel model, string fullName, bool checkEntityContainer) { foreach (IEdmModel referenced in model.ReferencedModels) { if (referenced.FindDeclaredType(fullName) != null || referenced.FindDeclaredValueTerm(fullName) != null || (checkEntityContainer && referenced.FindDeclaredEntityContainer(fullName) != null) || (referenced.FindDeclaredFunctions(fullName) ?? Enumerable.Empty<IEdmFunction>()).FirstOrDefault() != null) { return true; } } return false; } // Take function name to avoid recomputing it internal static bool FunctionOrNameExistsInReferencedModel(this IEdmModel model, IEdmFunction function, string functionFullName, bool checkEntityContainer) { foreach (IEdmModel referenced in model.ReferencedModels) { if (referenced.FindDeclaredType(functionFullName) != null || referenced.FindDeclaredValueTerm(functionFullName) != null || (checkEntityContainer && referenced.FindDeclaredEntityContainer(functionFullName) != null)) { return true; } else { IEnumerable<IEdmFunction> functionList = referenced.FindDeclaredFunctions(functionFullName) ?? Enumerable.Empty<IEdmFunction>(); if (functionList.Any(existingFunction => function.IsFunctionSignatureEquivalentTo(existingFunction))) { return true; } } } return false; } internal static bool TypeIndirectlyContainsTarget(IEdmEntityType source, IEdmEntityType target, HashSetInternal<IEdmEntityType> visited, IEdmModel context) { if (visited.Add(source)) { if (source.IsOrInheritsFrom(target)) { return true; } foreach (IEdmNavigationProperty navProp in source.NavigationProperties()) { if (navProp.ContainsTarget && TypeIndirectlyContainsTarget(navProp.ToEntityType(), target, visited, context)) { return true; } } foreach (IEdmStructuredType derived in context.FindAllDerivedTypes(source)) { IEdmEntityType derivedEntity = derived as IEdmEntityType; if (derivedEntity != null && TypeIndirectlyContainsTarget(derivedEntity, target, visited, context)) { return true; } } } return false; } } }
using System; using NUnit.Framework; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Digests; using Org.BouncyCastle.Crypto.Encodings; using Org.BouncyCastle.Crypto.Engines; using Org.BouncyCastle.Crypto.Generators; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Math; using Org.BouncyCastle.Security; using Org.BouncyCastle.Utilities.Encoders; using Org.BouncyCastle.Utilities.Test; namespace Org.BouncyCastle.Crypto.Tests { [TestFixture] public class RsaBlindedTest : SimpleTest { static BigInteger mod = new BigInteger("b259d2d6e627a768c94be36164c2d9fc79d97aab9253140e5bf17751197731d6f7540d2509e7b9ffee0a70a6e26d56e92d2edd7f85aba85600b69089f35f6bdbf3c298e05842535d9f064e6b0391cb7d306e0a2d20c4dfb4e7b49a9640bdea26c10ad69c3f05007ce2513cee44cfe01998e62b6c3637d3fc0391079b26ee36d5", 16); static BigInteger pubExp = new BigInteger("11", 16); static BigInteger privExp = new BigInteger("92e08f83cc9920746989ca5034dcb384a094fb9c5a6288fcc4304424ab8f56388f72652d8fafc65a4b9020896f2cde297080f2a540e7b7ce5af0b3446e1258d1dd7f245cf54124b4c6e17da21b90a0ebd22605e6f45c9f136d7a13eaac1c0f7487de8bd6d924972408ebb58af71e76fd7b012a8d0e165f3ae2e5077a8648e619", 16); static BigInteger p = new BigInteger("f75e80839b9b9379f1cf1128f321639757dba514642c206bbbd99f9a4846208b3e93fbbe5e0527cc59b1d4b929d9555853004c7c8b30ee6a213c3d1bb7415d03", 16); static BigInteger q = new BigInteger("b892d9ebdbfc37e397256dd8a5d3123534d1f03726284743ddc6be3a709edb696fc40c7d902ed804c6eee730eee3d5b20bf6bd8d87a296813c87d3b3cc9d7947", 16); static BigInteger pExp = new BigInteger("1d1a2d3ca8e52068b3094d501c9a842fec37f54db16e9a67070a8b3f53cc03d4257ad252a1a640eadd603724d7bf3737914b544ae332eedf4f34436cac25ceb5", 16); static BigInteger qExp = new BigInteger("6c929e4e81672fef49d9c825163fec97c4b7ba7acb26c0824638ac22605d7201c94625770984f78a56e6e25904fe7db407099cad9b14588841b94f5ab498dded", 16); static BigInteger crtCoef = new BigInteger("dae7651ee69ad1d081ec5e7188ae126f6004ff39556bde90e0b870962fa7b926d070686d8244fe5a9aa709a95686a104614834b0ada4b10f53197a5cb4c97339", 16); static string input = "4e6f77206973207468652074696d6520666f7220616c6c20676f6f64206d656e"; // // to check that we handling byte extension by big number correctly. // static string edgeInput = "ff6f77206973207468652074696d6520666f7220616c6c20676f6f64206d656e"; static byte[] oversizedSig = Hex.Decode("01ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff004e6f77206973207468652074696d6520666f7220616c6c20676f6f64206d656e"); static byte[] dudBlock = Hex.Decode("000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff004e6f77206973207468652074696d6520666f7220616c6c20676f6f64206d656e"); static byte[] truncatedDataBlock = Hex.Decode("0001ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff004e6f77206973207468652074696d6520666f7220616c6c20676f6f64206d656e"); static byte[] incorrectPadding = Hex.Decode("0001ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff4e6f77206973207468652074696d6520666f7220616c6c20676f6f64206d656e"); static byte[] missingDataBlock = Hex.Decode("0001ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); public override string Name { get { return "RSABlinded"; } } private void doTestStrictPkcs1Length(RsaKeyParameters pubParameters, RsaKeyParameters privParameters) { IAsymmetricBlockCipher eng = new RsaBlindedEngine(); eng.Init(true, privParameters); byte[] data = null; try { data = eng.ProcessBlock(oversizedSig, 0, oversizedSig.Length); } catch (Exception e) { Fail("RSA: failed - exception " + e.ToString(), e); } eng = new Pkcs1Encoding(eng); eng.Init(false, pubParameters); try { data = eng.ProcessBlock(data, 0, data.Length); Fail("oversized signature block not recognised"); } catch (InvalidCipherTextException e) { if (!e.Message.Equals("block incorrect size")) { Fail("RSA: failed - exception " + e.ToString(), e); } } // Create the encoding with StrictLengthEnabled=false (done thru environment in Java version) Pkcs1Encoding.StrictLengthEnabled = false; eng = new Pkcs1Encoding(new RsaBlindedEngine()); eng.Init(false, pubParameters); try { data = eng.ProcessBlock(data, 0, data.Length); } catch (InvalidCipherTextException e) { Fail("RSA: failed - exception " + e.ToString(), e); } Pkcs1Encoding.StrictLengthEnabled = true; } private void doTestTruncatedPkcs1Block(RsaKeyParameters pubParameters, RsaKeyParameters privParameters) { checkForPkcs1Exception(pubParameters, privParameters, truncatedDataBlock, "block truncated"); } private void doTestDudPkcs1Block(RsaKeyParameters pubParameters, RsaKeyParameters privParameters) { checkForPkcs1Exception(pubParameters, privParameters, dudBlock, "unknown block type"); } private void doTestWrongPaddingPkcs1Block(RsaKeyParameters pubParameters, RsaKeyParameters privParameters) { checkForPkcs1Exception(pubParameters, privParameters, incorrectPadding, "block padding incorrect"); } private void doTestMissingDataPkcs1Block(RsaKeyParameters pubParameters, RsaKeyParameters privParameters) { checkForPkcs1Exception(pubParameters, privParameters, missingDataBlock, "no data in block"); } private void checkForPkcs1Exception(RsaKeyParameters pubParameters, RsaKeyParameters privParameters, byte[] inputData, string expectedMessage) { IAsymmetricBlockCipher eng = new RsaBlindedEngine(); eng.Init(true, privParameters); byte[] data = null; try { data = eng.ProcessBlock(inputData, 0, inputData.Length); } catch (Exception e) { Fail("RSA: failed - exception " + e.ToString(), e); } eng = new Pkcs1Encoding(eng); eng.Init(false, pubParameters); try { data = eng.ProcessBlock(data, 0, data.Length); Fail("missing data block not recognised"); } catch (InvalidCipherTextException e) { if (!e.Message.Equals(expectedMessage)) { Fail("RSA: failed - exception " + e.ToString(), e); } } } private void doTestOaep(RsaKeyParameters pubParameters, RsaKeyParameters privParameters) { // // OAEP - public encrypt, private decrypt // IAsymmetricBlockCipher eng = new OaepEncoding(new RsaBlindedEngine()); byte[] data = Hex.Decode(input); eng.Init(true, pubParameters); try { data = eng.ProcessBlock(data, 0, data.Length); } catch (Exception e) { Fail("failed - exception " + e.ToString(), e); } eng.Init(false, privParameters); try { data = eng.ProcessBlock(data, 0, data.Length); } catch (Exception e) { Fail("failed - exception " + e.ToString(), e); } if (!input.Equals(Hex.ToHexString(data))) { Fail("failed OAEP Test"); } } public override void PerformTest() { RsaKeyParameters pubParameters = new RsaKeyParameters(false, mod, pubExp); RsaKeyParameters privParameters = new RsaPrivateCrtKeyParameters(mod, pubExp, privExp, p, q, pExp, qExp, crtCoef); byte[] data = Hex.Decode(edgeInput); // // RAW // IAsymmetricBlockCipher eng = new RsaBlindedEngine(); eng.Init(true, pubParameters); try { data = eng.ProcessBlock(data, 0, data.Length); } catch (Exception e) { Fail("RSA: failed - exception " + e.ToString(), e); } eng.Init(false, privParameters); try { data = eng.ProcessBlock(data, 0, data.Length); } catch (Exception e) { Fail("failed - exception " + e.ToString(), e); } if (!edgeInput.Equals(Hex.ToHexString(data))) { Fail("failed RAW edge Test"); } data = Hex.Decode(input); eng.Init(true, pubParameters); try { data = eng.ProcessBlock(data, 0, data.Length); } catch (Exception e) { Fail("failed - exception " + e.ToString(), e); } eng.Init(false, privParameters); try { data = eng.ProcessBlock(data, 0, data.Length); } catch (Exception e) { Fail("failed - exception " + e.ToString(), e); } if (!input.Equals(Hex.ToHexString(data))) { Fail("failed RAW Test"); } // // PKCS1 - public encrypt, private decrypt // eng = new Pkcs1Encoding(eng); eng.Init(true, pubParameters); if (eng.GetOutputBlockSize() != ((Pkcs1Encoding)eng).GetUnderlyingCipher().GetOutputBlockSize()) { Fail("PKCS1 output block size incorrect"); } try { data = eng.ProcessBlock(data, 0, data.Length); } catch (Exception e) { Fail("failed - exception " + e.ToString(), e); } eng.Init(false, privParameters); try { data = eng.ProcessBlock(data, 0, data.Length); } catch (Exception e) { Fail("failed - exception " + e.ToString(), e); } if (!input.Equals(Hex.ToHexString(data))) { Fail("failed PKCS1 public/private Test"); } // // PKCS1 - private encrypt, public decrypt // eng = new Pkcs1Encoding(((Pkcs1Encoding)eng).GetUnderlyingCipher()); eng.Init(true, privParameters); try { data = eng.ProcessBlock(data, 0, data.Length); } catch (Exception e) { Fail("failed - exception " + e.ToString(), e); } eng.Init(false, pubParameters); try { data = eng.ProcessBlock(data, 0, data.Length); } catch (Exception e) { Fail("failed - exception " + e.ToString(), e); } if (!input.Equals(Hex.ToHexString(data))) { Fail("failed PKCS1 private/public Test"); } // // key generation test // RsaKeyPairGenerator pGen = new RsaKeyPairGenerator(); RsaKeyGenerationParameters genParam = new RsaKeyGenerationParameters( BigInteger.ValueOf(0x11), new SecureRandom(), 768, 25); pGen.Init(genParam); AsymmetricCipherKeyPair pair = pGen.GenerateKeyPair(); eng = new RsaBlindedEngine(); if (((RsaKeyParameters)pair.Public).Modulus.BitLength < 768) { Fail("failed key generation (768) length test"); } eng.Init(true, pair.Public); try { data = eng.ProcessBlock(data, 0, data.Length); } catch (Exception e) { Fail("failed - exception " + e.ToString(), e); } eng.Init(false, pair.Private); try { data = eng.ProcessBlock(data, 0, data.Length); } catch (Exception e) { Fail("failed - exception " + e.ToString(), e); } if (!input.Equals(Hex.ToHexString(data))) { Fail("failed key generation (768) Test"); } genParam = new RsaKeyGenerationParameters(BigInteger.ValueOf(0x11), new SecureRandom(), 1024, 25); pGen.Init(genParam); pair = pGen.GenerateKeyPair(); eng.Init(true, pair.Public); if (((RsaKeyParameters)pair.Public).Modulus.BitLength < 1024) { Fail("failed key generation (1024) length test"); } try { data = eng.ProcessBlock(data, 0, data.Length); } catch (Exception e) { Fail("failed - exception " + e.ToString(), e); } eng.Init(false, pair.Private); try { data = eng.ProcessBlock(data, 0, data.Length); } catch (Exception e) { Fail("failed - exception " + e.ToString(), e); } if (!input.Equals(Hex.ToHexString(data))) { Fail("failed key generation (1024) test"); } doTestOaep(pubParameters, privParameters); doTestStrictPkcs1Length(pubParameters, privParameters); doTestDudPkcs1Block(pubParameters, privParameters); doTestMissingDataPkcs1Block(pubParameters, privParameters); doTestTruncatedPkcs1Block(pubParameters, privParameters); doTestWrongPaddingPkcs1Block(pubParameters, privParameters); try { new RsaBlindedEngine().ProcessBlock(new byte[]{ 1 }, 0, 1); Fail("failed initialisation check"); } catch (InvalidOperationException) { // expected } } public static void Main( string[] args) { ITest test = new RsaBlindedTest(); ITestResult result = test.Perform(); Console.WriteLine(result); } [Test] public void TestFunction() { string resultText = Perform().ToString(); Assert.AreEqual(Name + ": Okay", resultText); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using System.Text; using log4net; using Nini.Config; using NUnit.Framework; using OpenMetaverse; using OpenMetaverse.Assets; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Region.CoreModules.Avatar.Attachments; using OpenSim.Region.CoreModules.Avatar.AvatarFactory; using OpenSim.Region.OptionalModules.World.NPC; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.ScriptEngine.Shared; using OpenSim.Region.ScriptEngine.Shared.Api; using OpenSim.Region.ScriptEngine.Shared.Instance; using OpenSim.Region.ScriptEngine.Shared.ScriptBase; using OpenSim.Services.Interfaces; using OpenSim.Tests.Common; using OpenSim.Tests.Common.Mock; namespace OpenSim.Region.ScriptEngine.Shared.Tests { /// <summary> /// Tests for OSSL NPC API /// </summary> [TestFixture] public class OSSL_NpcApiAppearanceTest : OpenSimTestCase { protected Scene m_scene; protected XEngine.XEngine m_engine; [SetUp] public override void SetUp() { base.SetUp(); IConfigSource initConfigSource = new IniConfigSource(); IConfig config = initConfigSource.AddConfig("XEngine"); config.Set("Enabled", "true"); config.Set("AllowOSFunctions", "true"); config.Set("OSFunctionThreatLevel", "Severe"); config = initConfigSource.AddConfig("NPC"); config.Set("Enabled", "true"); m_scene = new SceneHelpers().SetupScene(); SceneHelpers.SetupSceneModules( m_scene, initConfigSource, new AvatarFactoryModule(), new AttachmentsModule(), new NPCModule()); m_engine = new XEngine.XEngine(); m_engine.Initialise(initConfigSource); m_engine.AddRegion(m_scene); } /// <summary> /// Test creation of an NPC where the appearance data comes from a notecard /// </summary> [Test] public void TestOsNpcCreateUsingAppearanceFromNotecard() { TestHelpers.InMethod(); // Store an avatar with a different height from default in a notecard. UUID userId = TestHelpers.ParseTail(0x1); float newHeight = 1.9f; ScenePresence sp = SceneHelpers.AddScenePresence(m_scene, userId); sp.Appearance.AvatarHeight = newHeight; SceneObjectGroup so = SceneHelpers.CreateSceneObject(1, userId, 0x10); SceneObjectPart part = so.RootPart; m_scene.AddSceneObject(so); OSSL_Api osslApi = new OSSL_Api(); osslApi.Initialize(m_engine, part, null, null); string notecardName = "appearanceNc"; osslApi.osOwnerSaveAppearance(notecardName); // Try creating a bot using the appearance in the notecard. string npcRaw = osslApi.osNpcCreate("Jane", "Doe", new LSL_Types.Vector3(128, 128, 128), notecardName); Assert.That(npcRaw, Is.Not.Null); UUID npcId = new UUID(npcRaw); ScenePresence npc = m_scene.GetScenePresence(npcId); Assert.That(npc, Is.Not.Null); Assert.That(npc.Appearance.AvatarHeight, Is.EqualTo(newHeight)); } [Test] public void TestOsNpcCreateNotExistingNotecard() { TestHelpers.InMethod(); UUID userId = TestHelpers.ParseTail(0x1); SceneObjectGroup so = SceneHelpers.CreateSceneObject(1, userId, 0x10); m_scene.AddSceneObject(so); OSSL_Api osslApi = new OSSL_Api(); osslApi.Initialize(m_engine, so.RootPart, null, null); bool gotExpectedException = false; try { osslApi.osNpcCreate("Jane", "Doe", new LSL_Types.Vector3(128, 128, 128), "not existing notecard name"); } catch (ScriptException) { gotExpectedException = true; } Assert.That(gotExpectedException, Is.True); } /// <summary> /// Test creation of an NPC where the appearance data comes from an avatar already in the region. /// </summary> [Test] public void TestOsNpcCreateUsingAppearanceFromAvatar() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); // Store an avatar with a different height from default in a notecard. UUID userId = TestHelpers.ParseTail(0x1); float newHeight = 1.9f; ScenePresence sp = SceneHelpers.AddScenePresence(m_scene, userId); sp.Appearance.AvatarHeight = newHeight; SceneObjectGroup so = SceneHelpers.CreateSceneObject(1, userId, 0x10); SceneObjectPart part = so.RootPart; m_scene.AddSceneObject(so); OSSL_Api osslApi = new OSSL_Api(); osslApi.Initialize(m_engine, part, null, null); string notecardName = "appearanceNc"; osslApi.osOwnerSaveAppearance(notecardName); // Try creating a bot using the existing avatar's appearance string npcRaw = osslApi.osNpcCreate("Jane", "Doe", new LSL_Types.Vector3(128, 128, 128), sp.UUID.ToString()); Assert.That(npcRaw, Is.Not.Null); UUID npcId = new UUID(npcRaw); ScenePresence npc = m_scene.GetScenePresence(npcId); Assert.That(npc, Is.Not.Null); Assert.That(npc.Appearance.AvatarHeight, Is.EqualTo(newHeight)); } [Test] public void TestOsNpcLoadAppearance() { TestHelpers.InMethod(); //TestHelpers.EnableLogging(); // Store an avatar with a different height from default in a notecard. UUID userId = TestHelpers.ParseTail(0x1); float firstHeight = 1.9f; float secondHeight = 2.1f; string firstAppearanceNcName = "appearanceNc1"; string secondAppearanceNcName = "appearanceNc2"; ScenePresence sp = SceneHelpers.AddScenePresence(m_scene, userId); sp.Appearance.AvatarHeight = firstHeight; SceneObjectGroup so = SceneHelpers.CreateSceneObject(1, userId, 0x10); SceneObjectPart part = so.RootPart; m_scene.AddSceneObject(so); OSSL_Api osslApi = new OSSL_Api(); osslApi.Initialize(m_engine, part, null, null); osslApi.osOwnerSaveAppearance(firstAppearanceNcName); string npcRaw = osslApi.osNpcCreate("Jane", "Doe", new LSL_Types.Vector3(128, 128, 128), firstAppearanceNcName); // Create a second appearance notecard with a different height sp.Appearance.AvatarHeight = secondHeight; osslApi.osOwnerSaveAppearance(secondAppearanceNcName); osslApi.osNpcLoadAppearance(npcRaw, secondAppearanceNcName); UUID npcId = new UUID(npcRaw); ScenePresence npc = m_scene.GetScenePresence(npcId); Assert.That(npc, Is.Not.Null); Assert.That(npc.Appearance.AvatarHeight, Is.EqualTo(secondHeight)); } [Test] public void TestOsNpcLoadAppearanceNotExistingNotecard() { TestHelpers.InMethod(); // Store an avatar with a different height from default in a notecard. UUID userId = TestHelpers.ParseTail(0x1); float firstHeight = 1.9f; // float secondHeight = 2.1f; string firstAppearanceNcName = "appearanceNc1"; string secondAppearanceNcName = "appearanceNc2"; ScenePresence sp = SceneHelpers.AddScenePresence(m_scene, userId); sp.Appearance.AvatarHeight = firstHeight; SceneObjectGroup so = SceneHelpers.CreateSceneObject(1, userId, 0x10); SceneObjectPart part = so.RootPart; m_scene.AddSceneObject(so); OSSL_Api osslApi = new OSSL_Api(); osslApi.Initialize(m_engine, part, null, null); osslApi.osOwnerSaveAppearance(firstAppearanceNcName); string npcRaw = osslApi.osNpcCreate("Jane", "Doe", new LSL_Types.Vector3(128, 128, 128), firstAppearanceNcName); bool gotExpectedException = false; try { osslApi.osNpcLoadAppearance(npcRaw, secondAppearanceNcName); } catch (ScriptException) { gotExpectedException = true; } Assert.That(gotExpectedException, Is.True); UUID npcId = new UUID(npcRaw); ScenePresence npc = m_scene.GetScenePresence(npcId); Assert.That(npc, Is.Not.Null); Assert.That(npc.Appearance.AvatarHeight, Is.EqualTo(firstHeight)); } /// <summary> /// Test removal of an owned NPC. /// </summary> [Test] public void TestOsNpcRemoveOwned() { TestHelpers.InMethod(); // Store an avatar with a different height from default in a notecard. UUID userId = TestHelpers.ParseTail(0x1); UUID otherUserId = TestHelpers.ParseTail(0x2); float newHeight = 1.9f; SceneHelpers.AddScenePresence(m_scene, otherUserId); ScenePresence sp = SceneHelpers.AddScenePresence(m_scene, userId); sp.Appearance.AvatarHeight = newHeight; SceneObjectGroup so = SceneHelpers.CreateSceneObject(1, userId, 0x10); SceneObjectPart part = so.RootPart; m_scene.AddSceneObject(so); SceneObjectGroup otherSo = SceneHelpers.CreateSceneObject(1, otherUserId, 0x20); SceneObjectPart otherPart = otherSo.RootPart; m_scene.AddSceneObject(otherSo); OSSL_Api osslApi = new OSSL_Api(); osslApi.Initialize(m_engine, part, null, null); OSSL_Api otherOsslApi = new OSSL_Api(); otherOsslApi.Initialize(m_engine, otherPart, null, null); string notecardName = "appearanceNc"; osslApi.osOwnerSaveAppearance(notecardName); string npcRaw = osslApi.osNpcCreate( "Jane", "Doe", new LSL_Types.Vector3(128, 128, 128), notecardName, ScriptBaseClass.OS_NPC_CREATOR_OWNED); otherOsslApi.osNpcRemove(npcRaw); // Should still be around UUID npcId = new UUID(npcRaw); ScenePresence npc = m_scene.GetScenePresence(npcId); Assert.That(npc, Is.Not.Null); osslApi.osNpcRemove(npcRaw); npc = m_scene.GetScenePresence(npcId); // Now the owner deleted it and it's gone Assert.That(npc, Is.Null); } /// <summary> /// Test removal of an unowned NPC. /// </summary> [Test] public void TestOsNpcRemoveUnowned() { TestHelpers.InMethod(); // log4net.Config.XmlConfigurator.Configure(); // Store an avatar with a different height from default in a notecard. UUID userId = TestHelpers.ParseTail(0x1); float newHeight = 1.9f; ScenePresence sp = SceneHelpers.AddScenePresence(m_scene, userId); sp.Appearance.AvatarHeight = newHeight; SceneObjectGroup so = SceneHelpers.CreateSceneObject(1, userId, 0x10); SceneObjectPart part = so.RootPart; m_scene.AddSceneObject(so); OSSL_Api osslApi = new OSSL_Api(); osslApi.Initialize(m_engine, part, null, null); string notecardName = "appearanceNc"; osslApi.osOwnerSaveAppearance(notecardName); string npcRaw = osslApi.osNpcCreate( "Jane", "Doe", new LSL_Types.Vector3(128, 128, 128), notecardName, ScriptBaseClass.OS_NPC_NOT_OWNED); osslApi.osNpcRemove(npcRaw); UUID npcId = new UUID(npcRaw); ScenePresence npc = m_scene.GetScenePresence(npcId); Assert.That(npc, Is.Null); } } }
using System; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; namespace FileHelpersSamples { /// <summary> /// Base class for the other forms. /// has the banner bar and footer bar on it /// </summary> /// <remarks> /// Has some logic for links and other things in here. /// </remarks> public class frmFather : Form { private PictureBox pictureBox1; private System.Windows.Forms.PictureBox pictureBox2; private Panel panel1; private LinkLabel linkLabel1; private LinkLabel linkLabel2; private PictureBox pictureBox3; private System.Windows.Forms.LinkLabel linkLabel3; /// <summary> /// Required designer variable. /// </summary> private Container components = null; public frmFather() { // // Required for Windows Form Designer support // InitializeComponent(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose(bool disposing) { if (disposing) { if (components != null) components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmFather)); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.pictureBox2 = new System.Windows.Forms.PictureBox(); this.panel1 = new System.Windows.Forms.Panel(); this.linkLabel3 = new System.Windows.Forms.LinkLabel(); this.linkLabel2 = new System.Windows.Forms.LinkLabel(); this.linkLabel1 = new System.Windows.Forms.LinkLabel(); this.pictureBox3 = new System.Windows.Forms.PictureBox(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit(); this.panel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox3)).BeginInit(); this.SuspendLayout(); // // pictureBox1 // this.pictureBox1.Cursor = System.Windows.Forms.Cursors.Hand; this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image"))); this.pictureBox1.Location = new System.Drawing.Point(0, 0); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(333, 51); this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize; this.pictureBox1.TabIndex = 0; this.pictureBox1.TabStop = false; this.pictureBox1.Click += new System.EventHandler(this.pictureBox1_Click); // // pictureBox2 // this.pictureBox2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.pictureBox2.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox2.Image"))); this.pictureBox2.Location = new System.Drawing.Point(288, 0); this.pictureBox2.Name = "pictureBox2"; this.pictureBox2.Size = new System.Drawing.Size(512, 51); this.pictureBox2.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; this.pictureBox2.TabIndex = 1; this.pictureBox2.TabStop = false; // // panel1 // this.panel1.Controls.Add(this.linkLabel3); this.panel1.Controls.Add(this.linkLabel2); this.panel1.Controls.Add(this.linkLabel1); this.panel1.Dock = System.Windows.Forms.DockStyle.Bottom; this.panel1.Location = new System.Drawing.Point(0, 358); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(592, 24); this.panel1.TabIndex = 2; this.panel1.Paint += new System.Windows.Forms.PaintEventHandler(this.panel1_Paint); // // linkLabel3 // this.linkLabel3.Anchor = System.Windows.Forms.AnchorStyles.Top; this.linkLabel3.BackColor = System.Drawing.Color.Transparent; this.linkLabel3.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.linkLabel3.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(150)))), ((int)(((byte)(50)))), ((int)(((byte)(0))))); this.linkLabel3.LinkBehavior = System.Windows.Forms.LinkBehavior.HoverUnderline; this.linkLabel3.LinkColor = System.Drawing.Color.FromArgb(((int)(((byte)(150)))), ((int)(((byte)(50)))), ((int)(((byte)(0))))); this.linkLabel3.Location = new System.Drawing.Point(268, 4); this.linkLabel3.Name = "linkLabel3"; this.linkLabel3.Size = new System.Drawing.Size(80, 16); this.linkLabel3.TabIndex = 102; this.linkLabel3.TabStop = true; this.linkLabel3.Text = "Devoo Soft"; this.linkLabel3.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel3_LinkClicked); // // linkLabel2 // this.linkLabel2.BackColor = System.Drawing.Color.Transparent; this.linkLabel2.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.linkLabel2.LinkBehavior = System.Windows.Forms.LinkBehavior.NeverUnderline; this.linkLabel2.LinkColor = System.Drawing.Color.Black; this.linkLabel2.Location = new System.Drawing.Point(2, 6); this.linkLabel2.Name = "linkLabel2"; this.linkLabel2.Size = new System.Drawing.Size(158, 16); this.linkLabel2.TabIndex = 100; this.linkLabel2.TabStop = true; this.linkLabel2.Text = "(c) 2005-07 to Marcos Meli"; this.linkLabel2.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel2_LinkClicked); // // linkLabel1 // this.linkLabel1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.linkLabel1.BackColor = System.Drawing.Color.Transparent; this.linkLabel1.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.linkLabel1.LinkBehavior = System.Windows.Forms.LinkBehavior.HoverUnderline; this.linkLabel1.LinkColor = System.Drawing.Color.Black; this.linkLabel1.Location = new System.Drawing.Point(464, 6); this.linkLabel1.Name = "linkLabel1"; this.linkLabel1.Size = new System.Drawing.Size(136, 16); this.linkLabel1.TabIndex = 101; this.linkLabel1.TabStop = true; this.linkLabel1.Text = "www.filehelpers.net"; this.linkLabel1.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel1_LinkClicked); // // pictureBox3 // this.pictureBox3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.pictureBox3.Cursor = System.Windows.Forms.Cursors.Hand; this.pictureBox3.Image = global::FileHelpersSamples.Properties.Resources.donate; this.pictureBox3.Location = new System.Drawing.Point(339, 4); this.pictureBox3.Name = "pictureBox3"; this.pictureBox3.Size = new System.Drawing.Size(85, 40); this.pictureBox3.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize; this.pictureBox3.TabIndex = 3; this.pictureBox3.TabStop = false; this.pictureBox3.Click += new System.EventHandler(this.pictureBox3_Click); // // frmFather // this.AutoScaleBaseSize = new System.Drawing.Size(5, 14); this.ClientSize = new System.Drawing.Size(592, 382); this.Controls.Add(this.pictureBox3); this.Controls.Add(this.panel1); this.Controls.Add(this.pictureBox1); this.Controls.Add(this.pictureBox2); this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.Name = "frmFather"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "FileHelpers - Demos"; ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit(); this.panel1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.pictureBox3)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private Color mColor1 = Color.FromArgb(30, 110, 175); private Color mColor2 = Color.FromArgb(20, 50, 130); protected override void OnPaint(PaintEventArgs e) { LinearGradientBrush b = new LinearGradientBrush(this.ClientRectangle, // Color.FromArgb(120, 180, 250), Color.FromArgb(10, 35, 100), LinearGradientMode.ForwardDiagonal); Color1, Color2, LinearGradientMode.BackwardDiagonal); e.Graphics.FillRectangle(b, e.ClipRectangle); b.Dispose(); } private void panel1_Paint(object sender, PaintEventArgs e) { LinearGradientBrush b = new LinearGradientBrush(panel1.ClientRectangle, SystemColors.Control, Color.DarkGray, LinearGradientMode.Vertical); e.Graphics.FillRectangle(b, e.ClipRectangle); e.Graphics.DrawLine(Pens.DimGray, 0, 0, panel1.Width, 0); b.Dispose(); } private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { ProcessStartInfo info = new ProcessStartInfo("explorer", "\"http://www.filehelpers.net\""); info.CreateNoWindow = false; info.UseShellExecute = true; Process.Start(info); } private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { ProcessStartInfo info = new ProcessStartInfo("explorer", "https://github.com/MarcosMeli/FileHelpers/issues/new"); info.CreateNoWindow = true; info.UseShellExecute = true; Process.Start(info); } private DateTime mLastOpen = DateTime.Today.AddDays(-1); private void pictureBox1_Click(object sender, EventArgs e) { if (DateTime.Now > mLastOpen.AddSeconds(10)) { Process.Start("explorer", "\"http://www.filehelpers.net\""); mLastOpen = DateTime.Now; } } private void pictureBox3_Click(object sender, System.EventArgs e) { Process.Start("explorer", "\"http://www.filehelpers.net/donate/\""); } private bool mExitOnEsc = true; protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { if (mExitOnEsc && keyData == Keys.Escape) { this.Close(); return true; } return base.ProcessCmdKey(ref msg, keyData); } private void linkLabel3_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e) { ProcessStartInfo info = new ProcessStartInfo("explorer", "\"http://www.devoo.net\""); Process.Start(info); } public bool ExitOnEsc { get { return mExitOnEsc; } set { mExitOnEsc = value; } } public Color Color1 { get { return mColor1; } set { mColor1 = value; this.Invalidate(); } } public Color Color2 { get { return mColor2; } set { mColor2 = value; this.Invalidate(); } } } }
// This code is part of the Fungus library (https://github.com/snozbot/fungus) // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE) using UnityEngine; namespace Fungus { /// <summary> /// Writes text in a dialog box. /// </summary> [CommandInfo("Narrative", "Say", "Writes text in a dialog box.")] [AddComponentMenu("")] public class Say : Command, ILocalizable { // Removed this tooltip as users's reported it obscures the text box [TextArea(5,10)] [SerializeField] protected string storyText = ""; [Tooltip("Notes about this story text for other authors, localization, etc.")] [SerializeField] protected string description = ""; [Tooltip("Character that is speaking")] [SerializeField] protected Character character; [Tooltip("Portrait that represents speaking character")] [SerializeField] protected Sprite portrait; [Tooltip("Voiceover audio to play when writing the text")] [SerializeField] protected AudioClip voiceOverClip; [Tooltip("Always show this Say text when the command is executed multiple times")] [SerializeField] protected bool showAlways = true; [Tooltip("Number of times to show this Say text when the command is executed multiple times")] [SerializeField] protected int showCount = 1; [Tooltip("Type this text in the previous dialog box.")] [SerializeField] protected bool extendPrevious = false; [Tooltip("Fade out the dialog box when writing has finished and not waiting for input.")] [SerializeField] protected bool fadeWhenDone = true; [Tooltip("Wait for player to click before continuing.")] [SerializeField] protected bool waitForClick = true; [Tooltip("Stop playing voiceover when text finishes writing.")] [SerializeField] protected bool stopVoiceover = true; [Tooltip("Wait for the Voice Over to complete before continuing")] [SerializeField] protected bool waitForVO = false; //add wait for vo that overrides stopvo [Tooltip("Sets the active Say dialog with a reference to a Say Dialog object in the scene. All story text will now display using this Say Dialog.")] [SerializeField] protected SayDialog setSayDialog; protected int executionCount; #region Public members /// <summary> /// Character that is speaking. /// </summary> public virtual Character _Character { get { return character; } } /// <summary> /// Portrait that represents speaking character. /// </summary> public virtual Sprite Portrait { get { return portrait; } set { portrait = value; } } /// <summary> /// Type this text in the previous dialog box. /// </summary> public virtual bool ExtendPrevious { get { return extendPrevious; } } public override void OnEnter() { if (!showAlways && executionCount >= showCount) { Continue(); return; } executionCount++; // Override the active say dialog if needed if (character != null && character.SetSayDialog != null) { SayDialog.ActiveSayDialog = character.SetSayDialog; } if (setSayDialog != null) { SayDialog.ActiveSayDialog = setSayDialog; } var sayDialog = SayDialog.GetSayDialog(); if (sayDialog == null) { Continue(); return; } var flowchart = GetFlowchart(); sayDialog.SetActive(true); sayDialog.SetCharacter(character); sayDialog.SetCharacterImage(portrait); string displayText = storyText; var activeCustomTags = CustomTag.activeCustomTags; for (int i = 0; i < activeCustomTags.Count; i++) { var ct = activeCustomTags[i]; displayText = displayText.Replace(ct.TagStartSymbol, ct.ReplaceTagStartWith); if (ct.TagEndSymbol != "" && ct.ReplaceTagEndWith != "") { displayText = displayText.Replace(ct.TagEndSymbol, ct.ReplaceTagEndWith); } } string subbedText = flowchart.SubstituteVariables(displayText); sayDialog.Say(subbedText, !extendPrevious, waitForClick, fadeWhenDone, stopVoiceover, waitForVO, voiceOverClip, delegate { Continue(); }); } public override string GetSummary() { string namePrefix = ""; if (character != null) { namePrefix = character.NameText + ": "; } if (extendPrevious) { namePrefix = "EXTEND" + ": "; } return namePrefix + "\"" + storyText + "\""; } public override Color GetButtonColor() { return new Color32(184, 210, 235, 255); } public override void OnReset() { executionCount = 0; } public override void OnStopExecuting() { var sayDialog = SayDialog.GetSayDialog(); if (sayDialog == null) { return; } sayDialog.Stop(); } #endregion #region ILocalizable implementation public virtual string GetStandardText() { return storyText; } public virtual void SetStandardText(string standardText) { storyText = standardText; } public virtual string GetDescription() { return description; } public virtual string GetStringId() { // String id for Say commands is SAY.<Localization Id>.<Command id>.[Character Name] string stringId = "SAY." + GetFlowchartLocalizationId() + "." + itemId + "."; if (character != null) { stringId += character.NameText; } return stringId; } #endregion } }
// 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.IO; using System.Linq; using System.Security; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.GeneratedCodeRecognition; using Microsoft.CodeAnalysis.GenerateType; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.ProjectManagement; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.GenerateType { internal class GenerateTypeDialogViewModel : AbstractNotifyPropertyChanged { private Document _document; private INotificationService _notificationService; private IProjectManagementService _projectManagementService; private ISyntaxFactsService _syntaxFactsService; private IGeneratedCodeRecognitionService _generatedCodeService; private GenerateTypeDialogOptions _generateTypeDialogOptions; private string _typeName; private bool _isNewFile; private Dictionary<string, Accessibility> _accessListMap; private Dictionary<string, TypeKind> _typeKindMap; private List<string> _csharpAccessList; private List<string> _visualBasicAccessList; private List<string> _csharpTypeKindList; private List<string> _visualBasicTypeKindList; private string _csharpExtension = ".cs"; private string _visualBasicExtension = ".vb"; // reserved names that cannot be a folder name or filename private string[] _reservedKeywords = new string[] { "con", "prn", "aux", "nul", "com1", "com2", "com3", "com4", "com5", "com6", "com7", "com8", "com9", "lpt1", "lpt2", "lpt3", "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9", "clock$" }; // Below code details with the Access List and the manipulation public List<string> AccessList { get; private set; } private int _accessSelectIndex; public int AccessSelectIndex { get { return _accessSelectIndex; } set { SetProperty(ref _accessSelectIndex, value); } } private string _selectedAccessibilityString; public string SelectedAccessibilityString { get { return _selectedAccessibilityString; } set { SetProperty(ref _selectedAccessibilityString, value); } } public Accessibility SelectedAccessibility { get { Contract.Assert(_accessListMap.ContainsKey(SelectedAccessibilityString), "The Accessibility Key String not present"); return _accessListMap[SelectedAccessibilityString]; } } private List<string> _kindList; public List<string> KindList { get { return _kindList; } set { SetProperty(ref _kindList, value); } } private int _kindSelectIndex; public int KindSelectIndex { get { return _kindSelectIndex; } set { SetProperty(ref _kindSelectIndex, value); } } private string _selectedTypeKindString; public string SelectedTypeKindString { get { return _selectedTypeKindString; } set { SetProperty(ref _selectedTypeKindString, value); } } public TypeKind SelectedTypeKind { get { Contract.Assert(_typeKindMap.ContainsKey(SelectedTypeKindString), "The TypeKind Key String not present"); return _typeKindMap[SelectedTypeKindString]; } } private void PopulateTypeKind(TypeKind typeKind, string csharpKey, string visualBasicKey) { _typeKindMap.Add(visualBasicKey, typeKind); _typeKindMap.Add(csharpKey, typeKind); _csharpTypeKindList.Add(csharpKey); _visualBasicTypeKindList.Add(visualBasicKey); } private void PopulateTypeKind(TypeKind typeKind, string visualBasicKey) { _typeKindMap.Add(visualBasicKey, typeKind); _visualBasicTypeKindList.Add(visualBasicKey); } private void PopulateAccessList(string key, Accessibility accessibility, string languageName = null) { if (languageName == null) { _csharpAccessList.Add(key); _visualBasicAccessList.Add(key); } else if (languageName == LanguageNames.CSharp) { _csharpAccessList.Add(key); } else { Contract.Assert(languageName == LanguageNames.VisualBasic, "Currently only C# and VB are supported"); _visualBasicAccessList.Add(key); } _accessListMap.Add(key, accessibility); } private void InitialSetup(string languageName) { _accessListMap = new Dictionary<string, Accessibility>(); _typeKindMap = new Dictionary<string, TypeKind>(); _csharpAccessList = new List<string>(); _visualBasicAccessList = new List<string>(); _csharpTypeKindList = new List<string>(); _visualBasicTypeKindList = new List<string>(); // Populate the AccessListMap if (!_generateTypeDialogOptions.IsPublicOnlyAccessibility) { PopulateAccessList("Default", Accessibility.NotApplicable); PopulateAccessList("internal", Accessibility.Internal, LanguageNames.CSharp); PopulateAccessList("Friend", Accessibility.Internal, LanguageNames.VisualBasic); } PopulateAccessList("public", Accessibility.Public, LanguageNames.CSharp); PopulateAccessList("Public", Accessibility.Public, LanguageNames.VisualBasic); // Populate the TypeKind PopulateTypeKind(); } private void PopulateTypeKind() { Contract.Assert(_generateTypeDialogOptions.TypeKindOptions != TypeKindOptions.None); if (TypeKindOptionsHelper.IsClass(_generateTypeDialogOptions.TypeKindOptions)) { PopulateTypeKind(TypeKind.Class, "class", "Class"); } if (TypeKindOptionsHelper.IsEnum(_generateTypeDialogOptions.TypeKindOptions)) { PopulateTypeKind(TypeKind.Enum, "enum", "Enum"); } if (TypeKindOptionsHelper.IsStructure(_generateTypeDialogOptions.TypeKindOptions)) { PopulateTypeKind(TypeKind.Structure, "struct", "Structure"); } if (TypeKindOptionsHelper.IsInterface(_generateTypeDialogOptions.TypeKindOptions)) { PopulateTypeKind(TypeKind.Interface, "interface", "Interface"); } if (TypeKindOptionsHelper.IsDelegate(_generateTypeDialogOptions.TypeKindOptions)) { PopulateTypeKind(TypeKind.Delegate, "delegate", "Delegate"); } if (TypeKindOptionsHelper.IsModule(_generateTypeDialogOptions.TypeKindOptions)) { _shouldChangeTypeKindListSelectedIndex = true; PopulateTypeKind(TypeKind.Module, "Module"); } } internal bool TrySubmit() { if (this.IsNewFile) { var trimmedFileName = FileName.Trim(); // Case : \\Something if (trimmedFileName.StartsWith(@"\\", StringComparison.Ordinal)) { SendFailureNotification(ServicesVSResources.IllegalCharactersInPath); return false; } // Case : something\ if (string.IsNullOrWhiteSpace(trimmedFileName) || trimmedFileName.EndsWith(@"\", StringComparison.Ordinal)) { SendFailureNotification(ServicesVSResources.PathCannotHaveEmptyFileName); return false; } if (trimmedFileName.IndexOfAny(Path.GetInvalidPathChars()) >= 0) { SendFailureNotification(ServicesVSResources.IllegalCharactersInPath); return false; } var isRootOfTheProject = trimmedFileName.StartsWith(@"\", StringComparison.Ordinal); string implicitFilePath = null; // Construct the implicit file path if (isRootOfTheProject || this.SelectedProject != _document.Project) { if (!TryGetImplicitFilePath(this.SelectedProject.FilePath ?? string.Empty, ServicesVSResources.IllegalPathForProject, out implicitFilePath)) { return false; } } else { if (!TryGetImplicitFilePath(_document.FilePath, ServicesVSResources.IllegalPathForDocument, out implicitFilePath)) { return false; } } // Remove the '\' at the beginning if present trimmedFileName = trimmedFileName.StartsWith(@"\", StringComparison.Ordinal) ? trimmedFileName.Substring(1) : trimmedFileName; // Construct the full path of the file to be created this.FullFilePath = implicitFilePath + @"\" + trimmedFileName; try { this.FullFilePath = Path.GetFullPath(this.FullFilePath); } catch (ArgumentNullException e) { SendFailureNotification(e.Message); return false; } catch (ArgumentException e) { SendFailureNotification(e.Message); return false; } catch (SecurityException e) { SendFailureNotification(e.Message); return false; } catch (NotSupportedException e) { SendFailureNotification(e.Message); return false; } catch (PathTooLongException e) { SendFailureNotification(e.Message); return false; } // Path.GetFullPath does not remove the spaces infront of the filename or folder name . So remove it var lastIndexOfSeparatorInFullPath = this.FullFilePath.LastIndexOf('\\'); if (lastIndexOfSeparatorInFullPath != -1) { var fileNameInFullPathInContainers = this.FullFilePath.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries); this.FullFilePath = string.Join("\\", fileNameInFullPathInContainers.Select(str => str.TrimStart())); } string projectRootPath = null; if (this.SelectedProject.FilePath == null) { projectRootPath = string.Empty; } else if (!TryGetImplicitFilePath(this.SelectedProject.FilePath, ServicesVSResources.IllegalPathForProject, out projectRootPath)) { return false; } if (this.FullFilePath.StartsWith(projectRootPath, StringComparison.Ordinal)) { // The new file will be within the root of the project var folderPath = this.FullFilePath.Substring(projectRootPath.Length); var containers = folderPath.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries); // Folder name was mentioned if (containers.Length > 1) { _fileName = containers.Last(); Folders = new List<string>(containers); Folders.RemoveAt(Folders.Count - 1); if (Folders.Any(folder => !(_syntaxFactsService.IsValidIdentifier(folder) || _syntaxFactsService.IsVerbatimIdentifier(folder)))) { _areFoldersValidIdentifiers = false; } } else if (containers.Length == 1) { // File goes at the root of the Directory _fileName = containers[0]; Folders = null; } else { SendFailureNotification(ServicesVSResources.IllegalCharactersInPath); return false; } } else { // The new file will be outside the root of the project and folders will be null Folders = null; var lastIndexOfSeparator = this.FullFilePath.LastIndexOf('\\'); if (lastIndexOfSeparator == -1) { SendFailureNotification(ServicesVSResources.IllegalCharactersInPath); return false; } _fileName = this.FullFilePath.Substring(lastIndexOfSeparator + 1); } // Check for reserved words in the folder or filename if (this.FullFilePath.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries).Any(s => _reservedKeywords.Contains(s, StringComparer.OrdinalIgnoreCase))) { SendFailureNotification(ServicesVSResources.FilePathCannotUseReservedKeywords); return false; } // We check to see if file path of the new file matches the filepath of any other existing file or if the Folders and FileName matches any of the document then // we say that the file already exists. if (this.SelectedProject.Documents.Where(n => n != null).Where(n => n.FilePath == FullFilePath).Any() || (this.Folders != null && this.FileName != null && this.SelectedProject.Documents.Where(n => n.Name != null && n.Folders.Count > 0 && n.Name == this.FileName && this.Folders.SequenceEqual(n.Folders)).Any()) || File.Exists(FullFilePath)) { SendFailureNotification(ServicesVSResources.FileAlreadyExists); return false; } } return true; } private bool TryGetImplicitFilePath(string implicitPathContainer, string message, out string implicitPath) { var indexOfLastSeparator = implicitPathContainer.LastIndexOf('\\'); if (indexOfLastSeparator == -1) { SendFailureNotification(message); implicitPath = null; return false; } implicitPath = implicitPathContainer.Substring(0, indexOfLastSeparator); return true; } private void SendFailureNotification(string message) { _notificationService.SendNotification(message, severity: NotificationSeverity.Information); } private Project _selectedProject; public Project SelectedProject { get { return _selectedProject; } set { var previousProject = _selectedProject; if (SetProperty(ref _selectedProject, value)) { NotifyPropertyChanged("DocumentList"); this.DocumentSelectIndex = 0; this.ProjectSelectIndex = this.ProjectList.FindIndex(p => p.Project == _selectedProject); if (_selectedProject != _document.Project) { // Restrict the Access List Options // 3 in the list represent the Public. 1-based array. this.AccessSelectIndex = this.AccessList.IndexOf("public") == -1 ? this.AccessList.IndexOf("Public") : this.AccessList.IndexOf("public"); Contract.Assert(this.AccessSelectIndex != -1); this.IsAccessListEnabled = false; } else { // Remove restriction this.IsAccessListEnabled = true; } if (previousProject != null && _projectManagementService != null) { this.ProjectFolders = _projectManagementService.GetFolders(this.SelectedProject.Id, this.SelectedProject.Solution.Workspace); } // Update the TypeKindList if required if (previousProject != null && previousProject.Language != _selectedProject.Language) { if (_selectedProject.Language == LanguageNames.CSharp) { var previousSelectedIndex = _kindSelectIndex; this.KindList = _csharpTypeKindList; if (_shouldChangeTypeKindListSelectedIndex) { this.KindSelectIndex = 0; } else { this.KindSelectIndex = previousSelectedIndex; } } else { var previousSelectedIndex = _kindSelectIndex; this.KindList = _visualBasicTypeKindList; if (_shouldChangeTypeKindListSelectedIndex) { this.KindSelectIndex = 0; } else { this.KindSelectIndex = previousSelectedIndex; } } } // Update File Extension UpdateFileNameExtension(); } } } private int _projectSelectIndex; public int ProjectSelectIndex { get { return _projectSelectIndex; } set { SetProperty(ref _projectSelectIndex, value); } } public List<ProjectSelectItem> ProjectList { get; private set; } private Project _previouslyPopulatedProject = null; private List<DocumentSelectItem> _previouslyPopulatedDocumentList = null; public IEnumerable<DocumentSelectItem> DocumentList { get { if (_previouslyPopulatedProject == _selectedProject) { return _previouslyPopulatedDocumentList; } _previouslyPopulatedProject = _selectedProject; _previouslyPopulatedDocumentList = new List<DocumentSelectItem>(); // Check for the current project if (_selectedProject == _document.Project) { // populate the current document _previouslyPopulatedDocumentList.Add(new DocumentSelectItem(_document, "<Current File>")); // Set the initial selected Document this.SelectedDocument = _document; // Populate the rest of the documents for the project _previouslyPopulatedDocumentList.AddRange(_document.Project.Documents .Where(d => d != _document && !_generatedCodeService.IsGeneratedCode(d)) .Select(d => new DocumentSelectItem(d))); } else { _previouslyPopulatedDocumentList.AddRange(_selectedProject.Documents .Where(d => !_generatedCodeService.IsGeneratedCode(d)) .Select(d => new DocumentSelectItem(d))); this.SelectedDocument = _selectedProject.Documents.FirstOrDefault(); } this.IsExistingFileEnabled = _previouslyPopulatedDocumentList.Count == 0 ? false : true; this.IsNewFile = this.IsExistingFileEnabled ? this.IsNewFile : true; return _previouslyPopulatedDocumentList; } } private bool _isExistingFileEnabled = true; public bool IsExistingFileEnabled { get { return _isExistingFileEnabled; } set { SetProperty(ref _isExistingFileEnabled, value); } } private int _documentSelectIndex; public int DocumentSelectIndex { get { return _documentSelectIndex; } set { SetProperty(ref _documentSelectIndex, value); } } private Document _selectedDocument; public Document SelectedDocument { get { return _selectedDocument; } set { SetProperty(ref _selectedDocument, value); } } private string _fileName; public string FileName { get { return _fileName; } set { SetProperty(ref _fileName, value); } } public List<string> Folders; public string TypeName { get { return _typeName; } set { SetProperty(ref _typeName, value); } } public bool IsNewFile { get { return _isNewFile; } set { SetProperty(ref _isNewFile, value); } } public bool IsExistingFile { get { return !_isNewFile; } set { SetProperty(ref _isNewFile, !value); } } private bool _isAccessListEnabled; private bool _shouldChangeTypeKindListSelectedIndex = false; public bool IsAccessListEnabled { get { return _isAccessListEnabled; } set { SetProperty(ref _isAccessListEnabled, value); } } private bool _areFoldersValidIdentifiers = true; public bool AreFoldersValidIdentifiers { get { if (_areFoldersValidIdentifiers) { var workspace = this.SelectedProject.Solution.Workspace as VisualStudioWorkspaceImpl; var project = workspace?.GetHostProject(this.SelectedProject.Id) as AbstractProject; return !(project?.IsWebSite == true); } return false; } } public IList<string> ProjectFolders { get; private set; } public string FullFilePath { get; private set; } internal void UpdateFileNameExtension() { var currentFileName = this.FileName.Trim(); if (!string.IsNullOrWhiteSpace(currentFileName) && !currentFileName.EndsWith("\\", StringComparison.Ordinal)) { if (this.SelectedProject.Language == LanguageNames.CSharp) { // For CSharp currentFileName = UpdateExtension(currentFileName, _csharpExtension, _visualBasicExtension); } else { // For Visual Basic currentFileName = UpdateExtension(currentFileName, _visualBasicExtension, _csharpExtension); } } this.FileName = currentFileName; } private string UpdateExtension(string currentFileName, string desiredFileExtension, string undesiredFileExtension) { if (currentFileName.EndsWith(desiredFileExtension, StringComparison.OrdinalIgnoreCase)) { // No change required return currentFileName; } // Remove the undesired extension if (currentFileName.EndsWith(undesiredFileExtension, StringComparison.OrdinalIgnoreCase)) { currentFileName = currentFileName.Substring(0, currentFileName.Length - undesiredFileExtension.Length); } // Append the desired extension return currentFileName + desiredFileExtension; } internal GenerateTypeDialogViewModel( Document document, INotificationService notificationService, IProjectManagementService projectManagementService, ISyntaxFactsService syntaxFactsService, IGeneratedCodeRecognitionService generatedCodeService, GenerateTypeDialogOptions generateTypeDialogOptions, string typeName, string fileExtension, bool isNewFile, string accessSelectString, string typeKindSelectString) { _generateTypeDialogOptions = generateTypeDialogOptions; InitialSetup(document.Project.Language); var dependencyGraph = document.Project.Solution.GetProjectDependencyGraph(); // Initialize the dependencies var projectListing = new List<ProjectSelectItem>(); // Populate the project list // Add the current project projectListing.Add(new ProjectSelectItem(document.Project)); // Add the rest of the projects // Adding dependency graph to avoid cyclic dependency projectListing.AddRange(document.Project.Solution.Projects .Where(p => p != document.Project && !dependencyGraph.GetProjectsThatThisProjectTransitivelyDependsOn(p.Id).Contains(document.Project.Id)) .Select(p => new ProjectSelectItem(p))); this.ProjectList = projectListing; const string attributeSuffix = "Attribute"; _typeName = generateTypeDialogOptions.IsAttribute && !typeName.EndsWith(attributeSuffix, StringComparison.Ordinal) ? typeName + attributeSuffix : typeName; this.FileName = typeName + fileExtension; _document = document; this.SelectedProject = document.Project; this.SelectedDocument = document; _notificationService = notificationService; _generatedCodeService = generatedCodeService; this.AccessList = document.Project.Language == LanguageNames.CSharp ? _csharpAccessList : _visualBasicAccessList; this.AccessSelectIndex = this.AccessList.Contains(accessSelectString) ? this.AccessList.IndexOf(accessSelectString) : 0; this.IsAccessListEnabled = true; this.KindList = document.Project.Language == LanguageNames.CSharp ? _csharpTypeKindList : _visualBasicTypeKindList; this.KindSelectIndex = this.KindList.Contains(typeKindSelectString) ? this.KindList.IndexOf(typeKindSelectString) : 0; this.ProjectSelectIndex = 0; this.DocumentSelectIndex = 0; _isNewFile = isNewFile; _syntaxFactsService = syntaxFactsService; _projectManagementService = projectManagementService; if (projectManagementService != null) { this.ProjectFolders = _projectManagementService.GetFolders(this.SelectedProject.Id, this.SelectedProject.Solution.Workspace); } else { this.ProjectFolders = SpecializedCollections.EmptyList<string>(); } } public class ProjectSelectItem { private Project _project; public string Name { get { return _project.Name; } } public Project Project { get { return _project; } } public ProjectSelectItem(Project project) { _project = project; } } public class DocumentSelectItem { private Document _document; public Document Document { get { return _document; } } private string _name; public string Name { get { return _name; } } public DocumentSelectItem(Document document, string documentName) { _document = document; _name = documentName; } public DocumentSelectItem(Document document) { _document = document; if (document.Folders.Count == 0) { _name = document.Name; } else { _name = string.Join("\\", document.Folders) + "\\" + document.Name; } } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.AccessControl; using System.Security.Principal; using Sitecore.Diagnostics.Base; using JetBrains.Annotations; namespace SIM.FileSystem { using Sitecore.Diagnostics.Logging; using SIM.Extensions; public static class SecurityExtensions { #region Fields private static Type SecurityIdentifier { get; } = typeof(SecurityIdentifier); #endregion #region Public methods public static bool CompareTo(this IdentityReference left, IdentityReference right) { return left != null && right != null ? left.Translate(SecurityIdentifier).ToString().EqualsIgnoreCase(right.Translate(SecurityIdentifier).ToString()) : left == right; } #endregion } public class SecurityProvider { #region Fields protected IdentityReference Everyone { get; } = new SecurityIdentifier("S-1-1-0").Translate(typeof(NTAccount)); protected IdentityReference LocalService { get; } = new SecurityIdentifier("S-1-5-19").Translate(typeof(NTAccount)); protected IdentityReference LocalSystem { get; } = new SecurityIdentifier("S-1-5-18").Translate(typeof(NTAccount)); protected IdentityReference NetworkService { get; } = new SecurityIdentifier("S-1-5-20").Translate(typeof(NTAccount)); protected FileSystem FileSystem { get; } #endregion #region Constructors public SecurityProvider(FileSystem fileSystem) { FileSystem = fileSystem; } #endregion #region Public methods public virtual void EnsurePermissions([NotNull] string path, [NotNull] string identity) { Assert.ArgumentNotNullOrEmpty(path, nameof(path)); Assert.ArgumentNotNullOrEmpty(identity, nameof(identity)); var identityReference = GetIdentityReference(identity); Assert.IsNotNull(identityReference, $"Cannot find {identity} identity reference"); if (FileSystem.Directory.Exists(path)) { EnsureDirectoryPermissions(path, identityReference); return; } if (FileSystem.File.Exists(path)) { EnsureFilePermissions(path, identityReference); return; } throw new InvalidOperationException("File or directory not found: " + path); } [CanBeNull] public virtual IdentityReference GetIdentityReference([NotNull] string name) { Assert.ArgumentNotNullOrEmpty(name, nameof(name)); IdentityReference reference = null; if (name.EndsWith("NetworkService", StringComparison.OrdinalIgnoreCase) || name.EndsWith("Network Service", StringComparison.OrdinalIgnoreCase)) { reference = NetworkService; } else if (name.EndsWith("LocalSystem", StringComparison.OrdinalIgnoreCase) || name.EndsWith("Local System", StringComparison.OrdinalIgnoreCase)) { reference = LocalSystem; } else if (name.EndsWith("LocalService", StringComparison.OrdinalIgnoreCase) || name.EndsWith("Local Service", StringComparison.OrdinalIgnoreCase)) { reference = LocalService; } else { try { if (!name.Contains("\\")) { name = Environment.MachineName + "\\" + name.TrimStart("\\"); } else if (name.StartsWith(".\\")) { name = Environment.MachineName + "\\" + name.TrimStart(".\\"); } reference = new SecurityIdentifier(name).Translate(typeof(NTAccount)); } catch (Exception ex) { Log.Warn(ex, $"An error occurred during paring {name} security identifier"); try { reference = new NTAccount(name); } catch (Exception ex1) { Log.Warn(ex, $"An error occurred during parsing {ex1} user account"); } } } Assert.IsNotNull(reference, "The '" + name + "' isn't valid NTAccount"); return reference; } public virtual bool HasPermissions(string path, string identity, FileSystemRights permissions) { Assert.ArgumentNotNullOrEmpty(path, nameof(path)); Assert.ArgumentNotNullOrEmpty(identity, nameof(identity)); Assert.ArgumentNotNull(permissions, nameof(permissions)); if (FileSystem.Directory.Exists(path)) { return HasDirectoryPermissions(path, GetIdentityReference(identity), permissions); } if (FileSystem.File.Exists(path)) { return HasFilePermissions(path, GetIdentityReference(identity), permissions); } throw new InvalidOperationException("File or directory not found: " + path); } #endregion #region Protected methods protected virtual void EnsureDirectoryPermissions([NotNull] string path, [NotNull] IdentityReference identity) { Assert.ArgumentNotNull(path, nameof(path)); Assert.ArgumentNotNull(identity, nameof(identity)); DirectoryInfo dirInfo = new DirectoryInfo(path); DirectorySecurity dirSecurity = dirInfo.GetAccessControl(AccessControlSections.Access); AuthorizationRuleCollection rules = dirSecurity.GetAccessRules(true, true, typeof(NTAccount)); if (!HasPermissions(rules, identity, FileSystemRights.FullControl)) { Log.Info(string.Format("Granting full access for '{0}' identity to the '{1}' folder", identity, path, typeof(FileSystem))); FileSystemAccessRule rule = new FileSystemAccessRule(identity, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow); dirSecurity.AddAccessRule(rule); dirInfo.SetAccessControl(dirSecurity); dirSecurity = dirInfo.GetAccessControl(AccessControlSections.Access); rules = dirSecurity.GetAccessRules(true, true, typeof(NTAccount)); Assert.IsTrue(HasPermissions(rules, identity, FileSystemRights.FullControl), "The Full Control access to the '" + path + "' folder isn't permitted for " + identity.Value + ". Please fix it and then restart the process"); } } protected virtual void EnsureFilePermissions([NotNull] string path, [NotNull] IdentityReference identity) { Assert.ArgumentNotNull(path, nameof(path)); Assert.ArgumentNotNull(identity, nameof(identity)); var fileInfo = new FileInfo(path); var dirSecurity = fileInfo.GetAccessControl(AccessControlSections.Access); AuthorizationRuleCollection rules = dirSecurity.GetAccessRules(true, true, typeof(NTAccount)); if (!HasPermissions(rules, identity, FileSystemRights.FullControl)) { Log.Info(string.Format("Granting full access for '{0}' identity to the '{1}' file", identity, path, typeof(FileSystem))); var rule = new FileSystemAccessRule(identity, FileSystemRights.FullControl, AccessControlType.Allow); dirSecurity.AddAccessRule(rule); fileInfo.SetAccessControl(dirSecurity); dirSecurity = fileInfo.GetAccessControl(AccessControlSections.Access); rules = dirSecurity.GetAccessRules(true, true, typeof(NTAccount)); Assert.IsTrue(HasPermissions(rules, identity, FileSystemRights.FullControl), "The Full Control access to the '" + path + "' file isn't permitted for " + identity.Value + ". Please fix it and then restart the process"); } } [NotNull] protected virtual IEnumerable<AuthorizationRule> GetRules([NotNull] AuthorizationRuleCollection rules, [NotNull] IdentityReference identity) { Assert.ArgumentNotNull(rules, nameof(rules)); Assert.ArgumentNotNull(identity, nameof(identity)); try { return rules.Cast<AuthorizationRule>().Where(rule => rule.IdentityReference.CompareTo(identity) || rule.IdentityReference.CompareTo(Everyone)); } catch (Exception ex) { Log.Warn(ex, $"Cannot get rules. {ex.Message}"); return new AuthorizationRule[0]; } } protected virtual bool HasDirectoryPermissions(string path, IdentityReference identity, FileSystemRights permissions) { DirectoryInfo dirInfo = new DirectoryInfo(path); DirectorySecurity dirSecurity = dirInfo.GetAccessControl(AccessControlSections.Access); AuthorizationRuleCollection rules = dirSecurity.GetAccessRules(true, true, typeof(NTAccount)); return HasPermissions(rules, identity, permissions); } protected virtual bool HasFilePermissions(string path, IdentityReference identity, FileSystemRights permissions) { var dirInfo = new FileInfo(path); var dirSecurity = dirInfo.GetAccessControl(AccessControlSections.Access); AuthorizationRuleCollection rules = dirSecurity.GetAccessRules(true, true, typeof(NTAccount)); return HasPermissions(rules, identity, permissions); } protected virtual bool HasPermissions([NotNull] AuthorizationRuleCollection rules, [NotNull] IdentityReference identity, FileSystemRights permissions) { Assert.ArgumentNotNull(rules, nameof(rules)); Assert.ArgumentNotNull(identity, nameof(identity)); try { return GetRules(rules, identity).Any( rule => (((FileSystemAccessRule)rule).FileSystemRights & permissions) > 0); } catch (Exception ex) { Log.Warn(ex, "Cannot get permissions for rules collection"); return false; } } #endregion } }
using System; using System.Buffers; using System.Diagnostics; using System.IO; using System.Text; using System.Text.Unicode; using BenchmarkDotNet.Attributes; using Lidgren.Network; using NetSerializer; namespace Content.Benchmarks { // Code for the *Slow and *Unsafe implementations taken from NetSerializer, licensed under the MIT license. [MemoryDiagnoser] public sealed class NetSerializerStringBenchmark { private const int StringByteBufferLength = 256; private const int StringCharBufferLength = 128; private string _toSerialize; [Params(8, 64, 256, 1024)] public int StringLength { get; set; } private readonly MemoryStream _outputStream = new(2048); private readonly MemoryStream _inputStream = new(2048); [GlobalSetup] public void Setup() { Span<byte> buf = stackalloc byte[StringLength / 2]; new Random().NextBytes(buf); _toSerialize = NetUtility.ToHexString(buf); Primitives.WritePrimitive(_inputStream, _toSerialize); } [Benchmark] public void BenchWriteCore() { _outputStream.Position = 0; WritePrimitiveCore(_outputStream, _toSerialize); } [Benchmark] public void BenchReadCore() { _inputStream.Position = 0; ReadPrimitiveCore(_inputStream, out string _); } [Benchmark] public void BenchWriteUnsafe() { _outputStream.Position = 0; WritePrimitiveUnsafe(_outputStream, _toSerialize); } [Benchmark] public void BenchReadUnsafe() { _inputStream.Position = 0; ReadPrimitiveUnsafe(_inputStream, out string _); } [Benchmark] public void BenchWriteSlow() { _outputStream.Position = 0; WritePrimitiveSlow(_outputStream, _toSerialize); } [Benchmark] public void BenchReadSlow() { _inputStream.Position = 0; ReadPrimitiveSlow(_inputStream, out string _); } public static void WritePrimitiveCore(Stream stream, string value) { if (value == null) { Primitives.WritePrimitive(stream, (uint)0); return; } if (value.Length == 0) { Primitives.WritePrimitive(stream, (uint)1); return; } Span<byte> buf = stackalloc byte[StringByteBufferLength]; var totalChars = value.Length; var totalBytes = Encoding.UTF8.GetByteCount(value); Primitives.WritePrimitive(stream, (uint)totalBytes + 1); Primitives.WritePrimitive(stream, (uint)totalChars); var totalRead = 0; ReadOnlySpan<char> span = value; for (;;) { var finalChunk = totalRead + totalChars >= totalChars; Utf8.FromUtf16(span, buf, out var read, out var wrote, isFinalBlock: finalChunk); stream.Write(buf.Slice(0, wrote)); totalRead += read; if (read >= totalChars) { break; } span = span[read..]; totalChars -= read; } } private static readonly SpanAction<char, (int, Stream)> _stringSpanRead = StringSpanRead; public static void ReadPrimitiveCore(Stream stream, out string value) { Primitives.ReadPrimitive(stream, out uint totalBytes); if (totalBytes == 0) { value = null; return; } if (totalBytes == 1) { value = string.Empty; return; } totalBytes -= 1; Primitives.ReadPrimitive(stream, out uint totalChars); value = string.Create((int) totalChars, ((int) totalBytes, stream), _stringSpanRead); } private static void StringSpanRead(Span<char> span, (int totalBytes, Stream stream) tuple) { Span<byte> buf = stackalloc byte[StringByteBufferLength]; // ReSharper disable VariableHidesOuterVariable var (totalBytes, stream) = tuple; // ReSharper restore VariableHidesOuterVariable var totalBytesRead = 0; var totalCharsRead = 0; var writeBufStart = 0; while (totalBytesRead < totalBytes) { var bytesLeft = totalBytes - totalBytesRead; var bytesReadLeft = Math.Min(buf.Length, bytesLeft); var writeSlice = buf.Slice(writeBufStart, bytesReadLeft - writeBufStart); var bytesInBuffer = stream.Read(writeSlice); if (bytesInBuffer == 0) throw new EndOfStreamException(); var readFromStream = bytesInBuffer + writeBufStart; var final = readFromStream == bytesLeft; var status = Utf8.ToUtf16(buf[..readFromStream], span[totalCharsRead..], out var bytesRead, out var charsRead, isFinalBlock: final); totalBytesRead += bytesRead; totalCharsRead += charsRead; writeBufStart = 0; if (status == OperationStatus.DestinationTooSmall) { // Malformed data? throw new InvalidDataException(); } if (status == OperationStatus.NeedMoreData) { // We got cut short in the middle of a multi-byte UTF-8 sequence. // So we need to move it to the bottom of the span, then read the next bit *past* that. // This copy should be fine because we're only ever gonna be copying up to 4 bytes // from the end of the buffer to the start. // So no chance of overlap. buf[bytesRead..].CopyTo(buf); writeBufStart = bytesReadLeft - bytesRead; continue; } Debug.Assert(status == OperationStatus.Done); } } public static void WritePrimitiveSlow(Stream stream, string value) { if (value == null) { Primitives.WritePrimitive(stream, (uint)0); return; } else if (value.Length == 0) { Primitives.WritePrimitive(stream, (uint)1); return; } var encoding = new UTF8Encoding(false, true); int len = encoding.GetByteCount(value); Primitives.WritePrimitive(stream, (uint)len + 1); Primitives.WritePrimitive(stream, (uint)value.Length); var buf = new byte[len]; encoding.GetBytes(value, 0, value.Length, buf, 0); stream.Write(buf, 0, len); } public static void ReadPrimitiveSlow(Stream stream, out string value) { uint len; Primitives.ReadPrimitive(stream, out len); if (len == 0) { value = null; return; } else if (len == 1) { value = string.Empty; return; } uint totalChars; Primitives.ReadPrimitive(stream, out totalChars); len -= 1; var encoding = new UTF8Encoding(false, true); var buf = new byte[len]; int l = 0; while (l < len) { int r = stream.Read(buf, l, (int)len - l); if (r == 0) throw new EndOfStreamException(); l += r; } value = encoding.GetString(buf); } sealed class StringHelper { public StringHelper() { this.Encoding = new UTF8Encoding(false, true); } Encoder m_encoder; Decoder m_decoder; byte[] m_byteBuffer; char[] m_charBuffer; public UTF8Encoding Encoding { get; private set; } public Encoder Encoder { get { if (m_encoder == null) m_encoder = this.Encoding.GetEncoder(); return m_encoder; } } public Decoder Decoder { get { if (m_decoder == null) m_decoder = this.Encoding.GetDecoder(); return m_decoder; } } public byte[] ByteBuffer { get { if (m_byteBuffer == null) m_byteBuffer = new byte[StringByteBufferLength]; return m_byteBuffer; } } public char[] CharBuffer { get { if (m_charBuffer == null) m_charBuffer = new char[StringCharBufferLength]; return m_charBuffer; } } } [ThreadStatic] static StringHelper s_stringHelper; public unsafe static void WritePrimitiveUnsafe(Stream stream, string value) { if (value == null) { Primitives.WritePrimitive(stream, (uint)0); return; } else if (value.Length == 0) { Primitives.WritePrimitive(stream, (uint)1); return; } var helper = s_stringHelper; if (helper == null) s_stringHelper = helper = new StringHelper(); var encoder = helper.Encoder; var buf = helper.ByteBuffer; int totalChars = value.Length; int totalBytes; fixed (char* ptr = value) totalBytes = encoder.GetByteCount(ptr, totalChars, true); Primitives.WritePrimitive(stream, (uint)totalBytes + 1); Primitives.WritePrimitive(stream, (uint)totalChars); int p = 0; bool completed = false; while (completed == false) { int charsConverted; int bytesConverted; fixed (char* src = value) fixed (byte* dst = buf) { encoder.Convert(src + p, totalChars - p, dst, buf.Length, true, out charsConverted, out bytesConverted, out completed); } stream.Write(buf, 0, bytesConverted); p += charsConverted; } } public static void ReadPrimitiveUnsafe(Stream stream, out string value) { uint totalBytes; Primitives.ReadPrimitive(stream, out totalBytes); if (totalBytes == 0) { value = null; return; } else if (totalBytes == 1) { value = string.Empty; return; } totalBytes -= 1; uint totalChars; Primitives.ReadPrimitive(stream, out totalChars); var helper = s_stringHelper; if (helper == null) s_stringHelper = helper = new StringHelper(); var decoder = helper.Decoder; var buf = helper.ByteBuffer; char[] chars; if (totalChars <= StringCharBufferLength) chars = helper.CharBuffer; else chars = new char[totalChars]; int streamBytesLeft = (int)totalBytes; int cp = 0; while (streamBytesLeft > 0) { int bytesInBuffer = stream.Read(buf, 0, Math.Min(buf.Length, streamBytesLeft)); if (bytesInBuffer == 0) throw new EndOfStreamException(); streamBytesLeft -= bytesInBuffer; bool flush = streamBytesLeft == 0 ? true : false; bool completed = false; int p = 0; while (completed == false) { int charsConverted; int bytesConverted; decoder.Convert(buf, p, bytesInBuffer - p, chars, cp, (int)totalChars - cp, flush, out bytesConverted, out charsConverted, out completed); p += bytesConverted; cp += charsConverted; } } value = new string(chars, 0, (int)totalChars); } } }
namespace Volante.Impl { using System; using System.Collections; using Volante; using System.Diagnostics; using Link = Volante.ILink<IPersistent>; class RtreePage : Persistent { const int card = (Page.pageSize - ObjectHeader.Sizeof - 4 * 3) / (4 * 4 + 4); const int minFill = card / 2; internal int n; internal Rectangle[] b; internal Link branch; internal RtreePage(IDatabase db, IPersistent obj, Rectangle r) { branch = db.CreateLink<IPersistent>(card); branch.Length = card; b = new Rectangle[card]; setBranch(0, new Rectangle(r), obj); n = 1; for (int i = 1; i < card; i++) { b[i] = new Rectangle(); } } internal RtreePage(IDatabase db, RtreePage root, RtreePage p) { branch = db.CreateLink<IPersistent>(card); branch.Length = card; b = new Rectangle[card]; n = 2; setBranch(0, root.cover(), root); setBranch(1, p.cover(), p); for (int i = 2; i < card; i++) { b[i] = new Rectangle(); } } internal RtreePage() { } internal RtreePage insert(IDatabase db, Rectangle r, IPersistent obj, int level) { Modify(); if (--level != 0) { // not leaf page int i, mini = 0; long minIncr = long.MaxValue; long minArea = long.MaxValue; for (i = 0; i < n; i++) { long area = b[i].Area(); long incr = Rectangle.JoinArea(b[i], r) - area; if (incr < minIncr) { minIncr = incr; minArea = area; mini = i; } else if (incr == minIncr && area < minArea) { minArea = area; mini = i; } } RtreePage p = (RtreePage)branch[mini]; RtreePage q = p.insert(db, r, obj, level); if (q == null) { // child was not split b[mini].Join(r); return null; } else { // child was split setBranch(mini, p.cover(), p); return addBranch(db, q.cover(), q); } } else { return addBranch(db, new Rectangle(r), obj); } } internal int remove(Rectangle r, IPersistent obj, int level, ArrayList reinsertList) { if (--level != 0) { for (int i = 0; i < n; i++) { if (r.Intersects(b[i])) { RtreePage pg = (RtreePage)branch[i]; int reinsertLevel = pg.remove(r, obj, level, reinsertList); if (reinsertLevel >= 0) { if (pg.n >= minFill) { setBranch(i, pg.cover(), pg); Modify(); } else { // not enough entries in child reinsertList.Add(pg); reinsertLevel = level - 1; removeBranch(i); } return reinsertLevel; } } } } else { for (int i = 0; i < n; i++) { if (branch.ContainsElement(i, obj)) { removeBranch(i); return 0; } } } return -1; } internal void find(Rectangle r, ArrayList result, int level) { if (--level != 0) { /* this is an internal node in the tree */ for (int i = 0; i < n; i++) { if (r.Intersects(b[i])) { ((RtreePage)branch[i]).find(r, result, level); } } } else { /* this is a leaf node */ for (int i = 0; i < n; i++) { if (r.Intersects(b[i])) { result.Add(branch[i]); } } } } internal void purge(int level) { if (--level != 0) { /* this is an internal node in the tree */ for (int i = 0; i < n; i++) { ((RtreePage)branch[i]).purge(level); } } Deallocate(); } void setBranch(int i, Rectangle r, IPersistent obj) { b[i] = r; branch[i] = obj; } void removeBranch(int i) { n -= 1; Array.Copy(b, i + 1, b, i, n - i); branch.RemoveAt(i); branch.Length = card; Modify(); } RtreePage addBranch(IDatabase db, Rectangle r, IPersistent obj) { if (n < card) { setBranch(n++, r, obj); return null; } else { return splitPage(db, r, obj); } } RtreePage splitPage(IDatabase db, Rectangle r, IPersistent obj) { int i, j, seed0 = 0, seed1 = 0; long[] rectArea = new long[card + 1]; long waste; long worstWaste = long.MinValue; // // As the seeds for the two groups, find two rectangles which waste // the most area if covered by a single rectangle. // rectArea[0] = r.Area(); for (i = 0; i < card; i++) { rectArea[i + 1] = b[i].Area(); } Rectangle bp = r; for (i = 0; i < card; i++) { for (j = i + 1; j <= card; j++) { waste = Rectangle.JoinArea(bp, b[j - 1]) - rectArea[i] - rectArea[j]; if (waste > worstWaste) { worstWaste = waste; seed0 = i; seed1 = j; } } bp = b[i]; } byte[] taken = new byte[card]; Rectangle group0, group1; long groupArea0, groupArea1; int groupCard0, groupCard1; RtreePage pg; taken[seed1 - 1] = 2; group1 = new Rectangle(b[seed1 - 1]); if (seed0 == 0) { group0 = new Rectangle(r); pg = new RtreePage(db, obj, r); } else { group0 = new Rectangle(b[seed0 - 1]); pg = new RtreePage(db, branch.GetRaw(seed0 - 1), group0); setBranch(seed0 - 1, r, obj); } groupCard0 = groupCard1 = 1; groupArea0 = rectArea[seed0]; groupArea1 = rectArea[seed1]; // // Split remaining rectangles between two groups. // The one chosen is the one with the greatest difference in area // expansion depending on which group - the rect most strongly // attracted to one group and repelled from the other. // while (groupCard0 + groupCard1 < card + 1 && groupCard0 < card + 1 - minFill && groupCard1 < card + 1 - minFill) { int betterGroup = -1, chosen = -1; long biggestDiff = -1; for (i = 0; i < card; i++) { if (taken[i] == 0) { long diff = (Rectangle.JoinArea(group0, b[i]) - groupArea0) - (Rectangle.JoinArea(group1, b[i]) - groupArea1); if (diff > biggestDiff || -diff > biggestDiff) { chosen = i; if (diff < 0) { betterGroup = 0; biggestDiff = -diff; } else { betterGroup = 1; biggestDiff = diff; } } } } Debug.Assert(chosen >= 0); if (betterGroup == 0) { group0.Join(b[chosen]); groupArea0 = group0.Area(); taken[chosen] = 1; pg.setBranch(groupCard0++, b[chosen], branch.GetRaw(chosen)); } else { groupCard1 += 1; group1.Join(b[chosen]); groupArea1 = group1.Area(); taken[chosen] = 2; } } // // If one group gets too full, then remaining rectangle are // split between two groups in such way to balance cards of two groups. // if (groupCard0 + groupCard1 < card + 1) { for (i = 0; i < card; i++) { if (taken[i] == 0) { if (groupCard0 >= groupCard1) { taken[i] = 2; groupCard1 += 1; } else { taken[i] = 1; pg.setBranch(groupCard0++, b[i], branch.GetRaw(i)); } } } } pg.n = groupCard0; n = groupCard1; for (i = 0, j = 0; i < groupCard1; j++) { if (taken[j] == 2) { setBranch(i++, b[j], branch.GetRaw(j)); } } return pg; } internal Rectangle cover() { Rectangle r = new Rectangle(b[0]); for (int i = 1; i < n; i++) { r.Join(b[i]); } return r; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using System.Threading; using Timer = System.Timers.Timer; using log4net; using Nini.Config; using Mono.Addins; using OpenMetaverse; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Framework; using OpenSim.Services.Interfaces; namespace OpenSim.Region.OptionalModules.World.NPC { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "NPCModule")] public class NPCModule : INPCModule, ISharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private Dictionary<UUID, NPCAvatar> m_avatars = new Dictionary<UUID, NPCAvatar>(); private NPCOptionsFlags m_NPCOptionFlags; public NPCOptionsFlags NPCOptionFlags {get {return m_NPCOptionFlags;}} public bool Enabled { get; private set; } public void Initialise(IConfigSource source) { IConfig config = source.Configs["NPC"]; Enabled = (config != null && config.GetBoolean("Enabled", false)); m_NPCOptionFlags = NPCOptionsFlags.None; if(Enabled) { if(config.GetBoolean("AllowNotOwned", true)) m_NPCOptionFlags |= NPCOptionsFlags.AllowNotOwned; if(config.GetBoolean("AllowSenseAsAvatar", true)) m_NPCOptionFlags |= NPCOptionsFlags.AllowSenseAsAvatar; if(config.GetBoolean("AllowCloneOtherAvatars", true)) m_NPCOptionFlags |= NPCOptionsFlags.AllowCloneOtherAvatars; if(config.GetBoolean("NoNPCGroup", true)) m_NPCOptionFlags |= NPCOptionsFlags.NoNPCGroup; } } public void AddRegion(Scene scene) { if (Enabled) scene.RegisterModuleInterface<INPCModule>(this); } public void RegionLoaded(Scene scene) { } public void PostInitialise() { } public void RemoveRegion(Scene scene) { scene.UnregisterModuleInterface<INPCModule>(this); } public void Close() { } public string Name { get { return "NPCModule"; } } public Type ReplaceableInterface { get { return null; } } public bool IsNPC(UUID agentId, Scene scene) { // FIXME: This implementation could not just use the // ScenePresence.PresenceType (and callers could inspect that // directly). ScenePresence sp = scene.GetScenePresence(agentId); if (sp == null || sp.IsChildAgent) return false; lock (m_avatars) return m_avatars.ContainsKey(agentId); } public bool SetNPCAppearance(UUID agentId, AvatarAppearance appearance, Scene scene) { ScenePresence npc = scene.GetScenePresence(agentId); if (npc == null || npc.IsChildAgent) return false; lock (m_avatars) if (!m_avatars.ContainsKey(agentId)) return false; // Delete existing npc attachments if(scene.AttachmentsModule != null) scene.AttachmentsModule.DeleteAttachmentsFromScene(npc, false); // XXX: We can't just use IAvatarFactoryModule.SetAppearance() yet // since it doesn't transfer attachments AvatarAppearance npcAppearance = new AvatarAppearance(appearance, true); npc.Appearance = npcAppearance; // Rez needed npc attachments if (scene.AttachmentsModule != null) scene.AttachmentsModule.RezAttachments(npc); IAvatarFactoryModule module = scene.RequestModuleInterface<IAvatarFactoryModule>(); module.SendAppearance(npc.UUID); return true; } public UUID CreateNPC(string firstname, string lastname, Vector3 position, UUID owner, bool senseAsAgent, Scene scene, AvatarAppearance appearance) { return CreateNPC(firstname, lastname, position, UUID.Zero, owner, "", UUID.Zero, senseAsAgent, scene, appearance); } public UUID CreateNPC(string firstname, string lastname, Vector3 position, UUID agentID, UUID owner, string groupTitle, UUID groupID, bool senseAsAgent, Scene scene, AvatarAppearance appearance) { NPCAvatar npcAvatar = null; string born = DateTime.UtcNow.ToString(); try { if (agentID == UUID.Zero) npcAvatar = new NPCAvatar(firstname, lastname, position, owner, senseAsAgent, scene); else npcAvatar = new NPCAvatar(firstname, lastname, agentID, position, owner, senseAsAgent, scene); } catch (Exception e) { m_log.Info("[NPC MODULE]: exception creating NPC avatar: " + e.ToString()); return UUID.Zero; } npcAvatar.CircuitCode = (uint)Util.RandomClass.Next(0, int.MaxValue); // m_log.DebugFormat( // "[NPC MODULE]: Creating NPC {0} {1} {2}, owner={3}, senseAsAgent={4} at {5} in {6}", // firstname, lastname, npcAvatar.AgentId, owner, senseAsAgent, position, scene.RegionInfo.RegionName); AgentCircuitData acd = new AgentCircuitData(); acd.AgentID = npcAvatar.AgentId; acd.firstname = firstname; acd.lastname = lastname; acd.ServiceURLs = new Dictionary<string, object>(); AvatarAppearance npcAppearance = new AvatarAppearance(appearance, true); acd.Appearance = npcAppearance; /* for (int i = 0; i < acd.Appearance.Texture.FaceTextures.Length; i++) { m_log.DebugFormat( "[NPC MODULE]: NPC avatar {0} has texture id {1} : {2}", acd.AgentID, i, acd.Appearance.Texture.FaceTextures[i]); } */ // ManualResetEvent ev = new ManualResetEvent(false); // Util.FireAndForget(delegate(object x) { lock (m_avatars) { scene.AuthenticateHandler.AddNewCircuit(npcAvatar.CircuitCode, acd); scene.AddNewAgent(npcAvatar, PresenceType.Npc); ScenePresence sp; if (scene.TryGetScenePresence(npcAvatar.AgentId, out sp)) { npcAvatar.Born = born; npcAvatar.ActiveGroupId = groupID; sp.CompleteMovement(npcAvatar, false); sp.Grouptitle = groupTitle; m_avatars.Add(npcAvatar.AgentId, npcAvatar); // m_log.DebugFormat("[NPC MODULE]: Created NPC {0} {1}", npcAvatar.AgentId, sp.Name); } } // ev.Set(); // }); // ev.WaitOne(); // m_log.DebugFormat("[NPC MODULE]: Created NPC with id {0}", npcAvatar.AgentId); return npcAvatar.AgentId; } public bool MoveToTarget(UUID agentID, Scene scene, Vector3 pos, bool noFly, bool landAtTarget, bool running) { lock (m_avatars) { if (m_avatars.ContainsKey(agentID)) { ScenePresence sp; if (scene.TryGetScenePresence(agentID, out sp)) { if (sp.IsSatOnObject || sp.SitGround) return false; // m_log.DebugFormat( // "[NPC MODULE]: Moving {0} to {1} in {2}, noFly {3}, landAtTarget {4}", // sp.Name, pos, scene.RegionInfo.RegionName, // noFly, landAtTarget); sp.MoveToTarget(pos, noFly, landAtTarget); sp.SetAlwaysRun = running; return true; } } } return false; } public bool StopMoveToTarget(UUID agentID, Scene scene) { lock (m_avatars) { if (m_avatars.ContainsKey(agentID)) { ScenePresence sp; if (scene.TryGetScenePresence(agentID, out sp)) { sp.Velocity = Vector3.Zero; sp.ResetMoveToTarget(); return true; } } } return false; } public bool Say(UUID agentID, Scene scene, string text) { return Say(agentID, scene, text, 0); } public bool Say(UUID agentID, Scene scene, string text, int channel) { lock (m_avatars) { if (m_avatars.ContainsKey(agentID)) { m_avatars[agentID].Say(channel, text); return true; } } return false; } public bool Shout(UUID agentID, Scene scene, string text, int channel) { lock (m_avatars) { if (m_avatars.ContainsKey(agentID)) { m_avatars[agentID].Shout(channel, text); return true; } } return false; } public bool Sit(UUID agentID, UUID partID, Scene scene) { lock (m_avatars) { if (m_avatars.ContainsKey(agentID)) { ScenePresence sp; if (scene.TryGetScenePresence(agentID, out sp)) { sp.HandleAgentRequestSit(m_avatars[agentID], agentID, partID, Vector3.Zero); return true; } } } return false; } public bool Whisper(UUID agentID, Scene scene, string text, int channel) { lock (m_avatars) { if (m_avatars.ContainsKey(agentID)) { m_avatars[agentID].Whisper(channel, text); return true; } } return false; } public bool Stand(UUID agentID, Scene scene) { lock (m_avatars) { if (m_avatars.ContainsKey(agentID)) { ScenePresence sp; if (scene.TryGetScenePresence(agentID, out sp)) { sp.StandUp(); return true; } } } return false; } public bool Touch(UUID agentID, UUID objectID) { lock (m_avatars) { if (m_avatars.ContainsKey(agentID)) return m_avatars[agentID].Touch(objectID); return false; } } public UUID GetOwner(UUID agentID) { lock (m_avatars) { NPCAvatar av; if (m_avatars.TryGetValue(agentID, out av)) return av.OwnerID; } return UUID.Zero; } public INPC GetNPC(UUID agentID, Scene scene) { lock (m_avatars) { if (m_avatars.ContainsKey(agentID)) return m_avatars[agentID]; else return null; } } public bool DeleteNPC(UUID agentID, Scene scene) { bool doRemove = false; NPCAvatar av; lock (m_avatars) { if (m_avatars.TryGetValue(agentID, out av)) { /* m_log.DebugFormat("[NPC MODULE]: Found {0} {1} to remove", agentID, av.Name); */ doRemove = true; } } if (doRemove) { scene.CloseAgent(agentID, false); lock (m_avatars) { m_avatars.Remove(agentID); } m_log.DebugFormat("[NPC MODULE]: Removed NPC {0} {1}", agentID, av.Name); return true; } /* m_log.DebugFormat("[NPC MODULE]: Could not find {0} to remove", agentID); */ return false; } public bool CheckPermissions(UUID npcID, UUID callerID) { lock (m_avatars) { NPCAvatar av; if (m_avatars.TryGetValue(npcID, out av)) { if (npcID == callerID) return true; return CheckPermissions(av, callerID); } else { return false; } } } /// <summary> /// Check if the caller has permission to manipulate the given NPC. /// </summary> /// <remarks> /// A caller has permission if /// * The caller UUID given is UUID.Zero. /// * The avatar is unowned (owner is UUID.Zero). /// * The avatar is owned and the owner and callerID match. /// * The avatar is owned and the callerID matches its agentID. /// </remarks> /// <param name="av"></param> /// <param name="callerID"></param> /// <returns>true if they do, false if they don't.</returns> private bool CheckPermissions(NPCAvatar av, UUID callerID) { return callerID == UUID.Zero || av.OwnerID == UUID.Zero || av.OwnerID == callerID || av.AgentId == callerID; } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.WindowsAzure.Management.SiteRecovery; using Microsoft.WindowsAzure.Management.SiteRecovery.Models; namespace Microsoft.WindowsAzure.Management.SiteRecovery { public static partial class SiteOperationsExtensions { /// <summary> /// Get the Site object by Id. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.SiteRecovery.ISiteOperations. /// </param> /// <param name='input'> /// Required. Site Creation Input. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the Job details object. /// </returns> public static JobResponse Create(this ISiteOperations operations, SiteCreationInput input, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((ISiteOperations)s).CreateAsync(input, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get the Site object by Id. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.SiteRecovery.ISiteOperations. /// </param> /// <param name='input'> /// Required. Site Creation Input. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the Job details object. /// </returns> public static Task<JobResponse> CreateAsync(this ISiteOperations operations, SiteCreationInput input, CustomRequestHeaders customRequestHeaders) { return operations.CreateAsync(input, customRequestHeaders, CancellationToken.None); } /// <summary> /// Get the Site object by Id. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.SiteRecovery.ISiteOperations. /// </param> /// <param name='siteId'> /// Required. Site ID. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the Job details object. /// </returns> public static JobResponse Delete(this ISiteOperations operations, string siteId, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((ISiteOperations)s).DeleteAsync(siteId, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get the Site object by Id. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.SiteRecovery.ISiteOperations. /// </param> /// <param name='siteId'> /// Required. Site ID. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the Job details object. /// </returns> public static Task<JobResponse> DeleteAsync(this ISiteOperations operations, string siteId, CustomRequestHeaders customRequestHeaders) { return operations.DeleteAsync(siteId, customRequestHeaders, CancellationToken.None); } /// <summary> /// Get the Site object by Id. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.SiteRecovery.ISiteOperations. /// </param> /// <param name='siteId'> /// Required. Site ID. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the Site object /// </returns> public static SiteResponse Get(this ISiteOperations operations, string siteId, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((ISiteOperations)s).GetAsync(siteId, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get the Site object by Id. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.SiteRecovery.ISiteOperations. /// </param> /// <param name='siteId'> /// Required. Site ID. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the Site object /// </returns> public static Task<SiteResponse> GetAsync(this ISiteOperations operations, string siteId, CustomRequestHeaders customRequestHeaders) { return operations.GetAsync(siteId, customRequestHeaders, CancellationToken.None); } /// <summary> /// Get the list of all Sites under the vault. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.SiteRecovery.ISiteOperations. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the list Sites operation. /// </returns> public static SiteListResponse List(this ISiteOperations operations, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((ISiteOperations)s).ListAsync(customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get the list of all Sites under the vault. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.SiteRecovery.ISiteOperations. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the list Sites operation. /// </returns> public static Task<SiteListResponse> ListAsync(this ISiteOperations operations, CustomRequestHeaders customRequestHeaders) { return operations.ListAsync(customRequestHeaders, CancellationToken.None); } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Globalization; using System.Reflection; namespace Microsoft.Management.UI.Internal { /// <summary> /// The BuiltinDataErrorInfoValidationRuleFactory creates default settings for the /// builtin FilterRules. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public class DefaultFilterRuleCustomizationFactory : FilterRuleCustomizationFactory { private IPropertyValueGetter propertyValueGetter; /// <summary> /// Gets or sets a <see cref="IPropertyValueGetter"/> that can retrieve the values of properties on a given object. /// </summary> public override IPropertyValueGetter PropertyValueGetter { get { if (this.propertyValueGetter == null) { this.propertyValueGetter = new PropertyValueGetter(); } return this.propertyValueGetter; } set { if (value == null) { throw new ArgumentNullException("value"); } this.propertyValueGetter = value; } } /// <summary> /// Returns a collection containing the default rules used by a PropertyValueSelectorFilterRule /// for type t. /// </summary> /// <typeparam name="T"> /// The type used to determine what rules to include. /// </typeparam> /// <returns> /// Returns a collection of FilterRules. /// </returns> public override ICollection<FilterRule> CreateDefaultFilterRulesForPropertyValueSelectorFilterRule<T>() { Collection<FilterRule> rules = new Collection<FilterRule>(); Type t = typeof(T); if (t == typeof(string)) { rules.Add(new TextContainsFilterRule()); rules.Add(new TextDoesNotContainFilterRule()); rules.Add(new TextStartsWithFilterRule()); rules.Add(new TextEqualsFilterRule()); rules.Add(new TextDoesNotEqualFilterRule()); rules.Add(new TextEndsWithFilterRule()); rules.Add(new IsEmptyFilterRule()); rules.Add(new IsNotEmptyFilterRule()); } else if (t == typeof(bool)) { rules.Add(new EqualsFilterRule<T>()); } else if (t.IsEnum) { rules.Add(new EqualsFilterRule<T>()); rules.Add(new DoesNotEqualFilterRule<T>()); } else { rules.Add(new IsLessThanFilterRule<T>()); rules.Add(new IsGreaterThanFilterRule<T>()); rules.Add(new IsBetweenFilterRule<T>()); rules.Add(new EqualsFilterRule<T>()); rules.Add(new DoesNotEqualFilterRule<T>()); rules.Add(new TextContainsFilterRule()); rules.Add(new TextDoesNotContainFilterRule()); } return rules; } /// <summary> /// Transfers the values from the old rule into the new rule. /// </summary> /// <param name="oldRule"> /// The old filter rule. /// </param> /// <param name="newRule"> /// The new filter rule. /// </param> public override void TransferValues(FilterRule oldRule, FilterRule newRule) { if (oldRule == null) { throw new ArgumentNullException("oldRule"); } if (newRule == null) { throw new ArgumentNullException("newRule"); } if (this.TryTransferValuesAsSingleValueComparableValueFilterRule(oldRule, newRule)) { return; } } /// <summary> /// Clears the values from the filter rule. /// </summary> /// <param name="rule"> /// The rule to clear. /// </param> public override void ClearValues(FilterRule rule) { if (rule == null) { throw new ArgumentNullException("rule"); } if (this.TryClearValueFromSingleValueComparableValueFilterRule(rule)) { return; } if (this.TryClearIsBetweenFilterRule(rule)) { return; } } /// <summary> /// Get an error message to display to a user when they /// provide a string value that cannot be parsed to type /// typeToParseTo. /// </summary> /// <param name="value"> /// The value entered by the user. /// </param> /// <param name="typeToParseTo"> /// The desired type to parse value to. /// </param> /// <returns> /// An error message to a user to explain how they can /// enter a valid value. /// </returns> public override string GetErrorMessageForInvalidValue(string value, Type typeToParseTo) { if (typeToParseTo == null) { throw new ArgumentNullException("typeToParseTo"); } bool isNumericType = typeToParseTo == typeof(byte) || typeToParseTo == typeof(sbyte) || typeToParseTo == typeof(short) || typeToParseTo == typeof(ushort) || typeToParseTo == typeof(int) || typeToParseTo == typeof(uint) || typeToParseTo == typeof(long) || typeToParseTo == typeof(ulong) || typeToParseTo == typeof(Single) || typeToParseTo == typeof(double); if (isNumericType) { return string.Format(CultureInfo.CurrentCulture, UICultureResources.ErrorMessageForUnparsableNumericType); } if (typeToParseTo == typeof(DateTime)) { return string.Format(CultureInfo.CurrentCulture, UICultureResources.ErrorMessageForUnparsableDateTimeType, CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern); } return string.Format(CultureInfo.CurrentCulture, UICultureResources.ErrorTextBoxTypeConversionErrorText, typeToParseTo.Name); } #region Private Methods #region Helpers private bool TryGetGenericParameterForComparableValueFilterRule(FilterRule rule, out Type genericParameter) { genericParameter = null; TextFilterRule textRule = rule as TextFilterRule; if (textRule != null) { genericParameter = typeof(string); return true; } Type ruleType = rule.GetType(); if (!ruleType.IsGenericType) { return false; } genericParameter = ruleType.GetGenericArguments()[0]; return true; } private object GetValueFromValidatingValue(FilterRule rule, string propertyName) { Debug.Assert(rule != null && !string.IsNullOrEmpty(propertyName), "rule and propertyname are not null"); // NOTE: This isn't needed but OACR is complaining if (rule == null) { throw new ArgumentNullException("rule"); } Type ruleType = rule.GetType(); PropertyInfo property = ruleType.GetProperty(propertyName); object validatingValue = property.GetValue(rule, null); property = property.PropertyType.GetProperty("Value"); return property.GetValue(validatingValue, null); } private void SetValueOnValidatingValue(FilterRule rule, string propertyName, object value) { Debug.Assert(rule != null && !string.IsNullOrEmpty(propertyName), "rule and propertyname are not null"); // NOTE: This isn't needed but OACR is complaining if (rule == null) { throw new ArgumentNullException("rule"); } Type ruleType = rule.GetType(); PropertyInfo property = ruleType.GetProperty(propertyName); object validatingValue = property.GetValue(rule, null); property = property.PropertyType.GetProperty("Value"); property.SetValue(validatingValue, value, null); } #endregion Helpers #region SingleValueComparableValueFilterRule private bool TryTransferValuesAsSingleValueComparableValueFilterRule(FilterRule oldRule, FilterRule newRule) { Debug.Assert(oldRule != null && newRule != null, "oldrule and newrule are not null"); bool areCorrectType = this.IsSingleValueComparableValueFilterRule(oldRule) && this.IsSingleValueComparableValueFilterRule(newRule); if (!areCorrectType) { return false; } object value = this.GetValueFromValidatingValue(oldRule, "Value"); this.SetValueOnValidatingValue(newRule, "Value", value); return true; } private bool TryClearValueFromSingleValueComparableValueFilterRule(FilterRule rule) { Debug.Assert(rule != null, "rule is not null"); if (!this.IsSingleValueComparableValueFilterRule(rule)) { return false; } this.SetValueOnValidatingValue(rule, "Value", null); return true; } private bool IsSingleValueComparableValueFilterRule(FilterRule rule) { Debug.Assert(rule != null, "rule is not null"); Type genericParameter; if (!this.TryGetGenericParameterForComparableValueFilterRule(rule, out genericParameter)) { return false; } Type ruleType = rule.GetType(); Type baseGenericType = typeof(SingleValueComparableValueFilterRule<>); Type baseType = baseGenericType.MakeGenericType(genericParameter); return baseType.Equals(ruleType) || ruleType.IsSubclassOf(baseType); } #endregion SingleValueComparableValueFilterRule #region IsBetweenFilterRule private bool TryClearIsBetweenFilterRule(FilterRule rule) { Debug.Assert(rule != null, "rule is not null"); if (!this.IsIsBetweenFilterRule(rule)) { return false; } this.SetValueOnValidatingValue(rule, "StartValue", null); this.SetValueOnValidatingValue(rule, "EndValue", null); return true; } private bool IsIsBetweenFilterRule(FilterRule rule) { Debug.Assert(rule != null, "rule is not null"); Type genericParameter; if (!this.TryGetGenericParameterForComparableValueFilterRule(rule, out genericParameter)) { return false; } Type ruleType = rule.GetType(); Type baseGenericType = typeof(IsBetweenFilterRule<>); Type baseType = baseGenericType.MakeGenericType(genericParameter); return baseType.Equals(ruleType) || ruleType.IsSubclassOf(baseType); } #endregion IsBetweenFilterRule #endregion Private Methods } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Collections; using System.Globalization; using Xunit; using SortedList_SortedListUtils; namespace SortedListCtorIKeyComp { public class Driver<KeyType, ValueType> { private Test m_test; public Driver(Test test) { m_test = test; } private CultureInfo _english = new CultureInfo("en"); private CultureInfo _german = new CultureInfo("de"); private CultureInfo _danish = new CultureInfo("da"); private CultureInfo _turkish = new CultureInfo("tr"); //CompareString lcid_en-US, EMPTY_FLAGS, "AE", 0, 2, "\u00C4", 0, 1, 1, NULL_STRING //CompareString 0x10407, EMPTY_FLAGS, "AE", 0, 2, "\u00C4", 0, 1, 0, NULL_STRING //CompareString lcid_da-DK, "NORM_IGNORECASE", "aA", 0, 2, "Aa", 0, 2, -1, NULL_STRING //CompareString lcid_en-US, "NORM_IGNORECASE", "aA", 0, 2, "Aa", 0, 2, 0, NULL_STRING //CompareString lcid_tr-TR, "NORM_IGNORECASE", "\u0131", 0, 1, "\u0049", 0, 1, 0, NULL_STRING private const String strAE = "AE"; private const String strUC4 = "\u00C4"; private const String straA = "aA"; private const String strAa = "Aa"; private const String strI = "I"; private const String strTurkishUpperI = "\u0131"; private const String strBB = "BB"; private const String strbb = "bb"; private const String value = "Default_Value"; public void TestEnum() { SortedList<String, String> _dic; IComparer<String> comparer; IComparer<String>[] predefinedComparers = new IComparer<String>[] { StringComparer.CurrentCulture, StringComparer.CurrentCultureIgnoreCase, StringComparer.OrdinalIgnoreCase, StringComparer.Ordinal}; foreach (IComparer<String> predefinedComparer in predefinedComparers) { _dic = new SortedList<String, String>(predefinedComparer); m_test.Eval(_dic.Comparer == predefinedComparer, String.Format("Err_4568aijueud! Comparer differ expected: {0} actual: {1}", predefinedComparer, _dic.Comparer)); m_test.Eval(_dic.Count == 0, String.Format("Err_23497sg! Count different: {0}", _dic.Count)); m_test.Eval(_dic.Keys.Count == 0, String.Format("Err_25ag! Count different: {0}", _dic.Keys.Count)); m_test.Eval(_dic.Values.Count == 0, String.Format("Err_23agd! Count different: {0}", _dic.Values.Count)); } //Current culture CultureInfo.DefaultThreadCurrentCulture = _english; comparer = StringComparer.CurrentCulture; _dic = new SortedList<String, String>(comparer); m_test.Eval(_dic.Comparer == comparer, String.Format("Err_30641ajhied! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer)); _dic.Add(strAE, value); m_test.Eval(!_dic.ContainsKey(strUC4), String.Format("Err_235rdag! Wrong result returned: {0}", _dic.ContainsKey(strUC4))); //bug #11263 in NDPWhidbey CultureInfo.DefaultThreadCurrentCulture = _german; comparer = StringComparer.CurrentCulture; _dic = new SortedList<String, String>(comparer); m_test.Eval(_dic.Comparer == comparer, String.Format("Err_54089ahued! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer)); _dic.Add(strAE, value); // same result in Desktop m_test.Eval(!_dic.ContainsKey(strUC4), String.Format("Err_23r7ag! Wrong result returned: {0}", CultureInfo.CurrentCulture.ToString()));// _dic.ContainsKey(strUC4))); //CurrentCultureIgnoreCase CultureInfo.DefaultThreadCurrentCulture = _english; comparer = StringComparer.CurrentCultureIgnoreCase; _dic = new SortedList<String, String>(comparer); m_test.Eval(_dic.Comparer == comparer, String.Format("Err_48856aied! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer)); _dic.Add(straA, value); m_test.Eval(_dic.ContainsKey(strAa), String.Format("Err_237g! Wrong result returned: {0}", _dic.ContainsKey(strAa))); CultureInfo.DefaultThreadCurrentCulture = _danish; comparer = StringComparer.CurrentCultureIgnoreCase; _dic = new SortedList<String, String>(comparer); m_test.Eval(_dic.Comparer == comparer, String.Format("Err_55685akdh! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer)); _dic.Add(straA, value); m_test.Eval(!_dic.ContainsKey(strAa), String.Format("Err_0723f! Wrong result returned: {0}", _dic.ContainsKey(strAa))); //InvariantCultureIgnoreCase CultureInfo.DefaultThreadCurrentCulture = _english; comparer = StringComparer.OrdinalIgnoreCase; _dic = new SortedList<String, String>(comparer); m_test.Eval(_dic.Comparer == comparer, String.Format("Err_546488ajhie! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer)); _dic.Add(strI, value); m_test.Eval(!_dic.ContainsKey(strTurkishUpperI), String.Format("Err_234qf! Wrong result returned: {0}", _dic.ContainsKey(strTurkishUpperI))); CultureInfo.DefaultThreadCurrentCulture = _turkish; comparer = StringComparer.OrdinalIgnoreCase; _dic = new SortedList<String, String>(comparer); m_test.Eval(_dic.Comparer == comparer, String.Format("Err_1884ahied! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer)); _dic.Add(strI, value); m_test.Eval(!_dic.ContainsKey(strTurkishUpperI), String.Format("Err_234ra7g! Wrong result returned: {0}", _dic.ContainsKey(strTurkishUpperI))); //Ordinal - not that many meaningful test CultureInfo.DefaultThreadCurrentCulture = _english; comparer = StringComparer.Ordinal; _dic = new SortedList<String, String>(comparer); m_test.Eval(_dic.Comparer == comparer, String.Format("Err_0177aued! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer)); _dic.Add(strBB, value); m_test.Eval(!_dic.ContainsKey(strbb), String.Format("Err_1244sd! Wrong result returned: {0}", _dic.ContainsKey(strbb))); CultureInfo.DefaultThreadCurrentCulture = _danish; comparer = StringComparer.Ordinal; _dic = new SortedList<String, String>(comparer); m_test.Eval(_dic.Comparer == comparer, String.Format("Err_8978005aheud! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer)); _dic.Add(strBB, value); m_test.Eval(!_dic.ContainsKey(strbb), String.Format("Err_235aeg! Wrong result returned: {0}", _dic.ContainsKey(strbb))); } public void TestParm() { //passing null will revert to the default comparison mechanism SortedList<String, String> _dic; IComparer<String> comparer = null; try { CultureInfo.DefaultThreadCurrentCulture = _english; _dic = new SortedList<String, String>(comparer); _dic.Add(straA, value); m_test.Eval(!_dic.ContainsKey(strAa), String.Format("Err_9237g! Wrong result returned: {0}", _dic.ContainsKey(strAa))); CultureInfo.DefaultThreadCurrentCulture = _danish; _dic = new SortedList<String, String>(comparer); _dic.Add(straA, value); m_test.Eval(!_dic.ContainsKey(strAa), String.Format("Err_90723f! Wrong result returned: {0}", _dic.ContainsKey(strAa))); } catch (Exception ex) { m_test.Eval(false, String.Format("Err_387tsg! Wrong exception thrown: {0}", ex)); } } public void IkeyComparerOwnImplementation() { //This just ensure that we can call our own implementation SortedList<String, String> _dic; IComparer<String> comparer = new MyOwnIKeyImplementation<String>(); try { CultureInfo.DefaultThreadCurrentCulture = _english; _dic = new SortedList<String, String>(comparer); _dic.Add(straA, value); m_test.Eval(!_dic.ContainsKey(strAa), String.Format("Err_0237g! Wrong result returned: {0}", _dic.ContainsKey(strAa))); CultureInfo.DefaultThreadCurrentCulture = _danish; _dic = new SortedList<String, String>(comparer); _dic.Add(straA, value); m_test.Eval(!_dic.ContainsKey(strAa), String.Format("Err_00723f! Wrong result returned: {0}", _dic.ContainsKey(strAa))); } catch (Exception ex) { m_test.Eval(false, String.Format("Err_387tsg! Wrong exception thrown: {0}", ex)); } } } public class Constructor_IKeyComparer { [Fact] public static void RunTests() { //This mostly follows the format established by the original author of these tests Test test = new Test(); Driver<String, String> driver1 = new Driver<String, String>(test); //Scenario 1: Pass all the enum values and ensure that the behavior is correct driver1.TestEnum(); //Scenario 2: Parm validation: null driver1.TestParm(); //Scenario 3: Implement our own IKeyComparer and check driver1.IkeyComparerOwnImplementation(); Assert.True(test.result); } } // [Serializable] internal class MyOwnIKeyImplementation<KeyType> : IComparer<KeyType> { public int GetHashCode(KeyType key) { //We cannot get the hascode that is culture aware here since TextInfo doesn't expose this functionality publicly return key.GetHashCode(); } public int Compare(KeyType key1, KeyType key2) { //We cannot get the hascode that is culture aware here since TextInfo doesn't expose this functionality publicly return key1.GetHashCode(); } public bool Equals(KeyType key1, KeyType key2) { return key1.Equals(key2); } } }
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.IO; using System.Drawing; namespace UnrealControls { /// <summary> /// This delegate is for creating filtered documents. /// </summary> /// <param name="Line">The line of text that is being checked for filtering.</param> /// <param name="Data">User supplied data that may control filtering.</param> /// <returns>True if the line of text is to be filtered out of the document.</returns> public delegate bool OutputWindowDocumentFilterDelegate(OutputWindowDocument.ReadOnlyDocumentLine Line, object Data); /// <summary> /// A document that can be viewed by multiple <see cref="OutputWindowView"/>'s. /// </summary> public class OutputWindowDocument { /// <summary> /// Represents a line of colored text within a document. /// </summary> internal class DocumentLine : ICloneable { //StringBuilder mText = new StringBuilder(); StringBuilder mBldrText = new StringBuilder(); string mFinalText; List<ColoredTextRange> mColorRanges = new List<ColoredTextRange>(); ICloneable mUserData; /// <summary> /// Gets the length of the line in characters. /// </summary> public int Length { get { return mFinalText == null ? mBldrText.Length : mFinalText.Length; } } /// <summary> /// Gets the character at the specified index. /// </summary> /// <param name="Index">The index of the character to get.</param> /// <returns>The character at the specified index.</returns> public char this[int Index] { get { return mFinalText == null ? mBldrText[Index] : mFinalText[Index]; } } /// <summary> /// Gets/Sets the user data associated with the line. /// </summary> public ICloneable UserData { get { return mUserData; } set { mUserData = value; } } /// <summary> /// Appends a character to the line of text. /// </summary> /// <param name="TxtColor">The color of the character.</param> /// <param name="CharToAppend">The character to append.</param> public void Append(Color? TxtColor, char CharToAppend) { System.Diagnostics.Debug.Assert(mBldrText != null); if(mColorRanges.Count == 0) { mColorRanges.Add(new ColoredTextRange(TxtColor, null, 0, 1)); } else { int CurColorIndex = mColorRanges.Count - 1; if(mColorRanges[CurColorIndex].ForeColor != TxtColor) { mColorRanges.Add(new ColoredTextRange(TxtColor, null, mBldrText.Length, 1)); } else { ++mColorRanges[CurColorIndex].Length; } } mBldrText.Append(CharToAppend); System.Diagnostics.Debug.Assert(CountEOL() <= 1); } /// <summary> /// This is a debug function that counts the number of EOL's in a line. There should only ever be 1. /// </summary> /// <returns>The number of EOL's in the line.</returns> int CountEOL() { System.Diagnostics.Debug.Assert(mBldrText != null); int NumEOL = 0; for(int i = 0; i < mBldrText.Length; ++i) { if(mBldrText[i] == '\n' && i > 0 && mBldrText[i - 1] == '\r') { ++NumEOL; } } return NumEOL; } /// <summary> /// Appends text to the end of the line. /// </summary> /// <param name="TxtColor">The color of the text.</param> /// <param name="TxtToAppend">The text to append.</param> public void Append(Color? TxtColor, string TxtToAppend) { System.Diagnostics.Debug.Assert(mBldrText != null); if(mColorRanges.Count == 0) { mColorRanges.Add(new ColoredTextRange(TxtColor, null, 0, TxtToAppend.Length)); } else { int CurColorIndex = mColorRanges.Count - 1; if(mColorRanges[CurColorIndex].ForeColor != TxtColor) { mColorRanges.Add(new ColoredTextRange(TxtColor, null, mBldrText.Length, TxtToAppend.Length)); } else { mColorRanges[CurColorIndex].Length += TxtToAppend.Length; } } mBldrText.Append(TxtToAppend); System.Diagnostics.Debug.Assert(CountEOL() <= 1); } /// <summary> /// Gets an array of colored line segments that can be used for drawing. /// </summary> /// <returns>An array of colored line segments.</returns> public ColoredDocumentLineSegment[] GetLineSegments() { ColoredDocumentLineSegment[] Segments = new ColoredDocumentLineSegment[mColorRanges.Count]; int CurSegment = 0; foreach(ColoredTextRange CurRange in mColorRanges) { Segments[CurSegment] = new ColoredDocumentLineSegment(new ColorPair(CurRange.BackColor, CurRange.ForeColor), this.ToString(CurRange.StartIndex, CurRange.Length)); } return Segments; } /// <summary> /// Gets an array of colored line segments that can be used for drawing. /// </summary> /// <param name="StartIndex">The starting character at which to begin generating segments.</param> /// <param name="Length">The number of characters to include in segment generation.</param> /// <returns>An array of colored line segments.</returns> public ColoredDocumentLineSegment[] GetLineSegments(int StartIndex, int Length) { List<ColoredDocumentLineSegment> Segments = new List<ColoredDocumentLineSegment>(mColorRanges.Count); int CharsToCopy = 0; bool bFoundStartSegment = false; foreach(ColoredTextRange CurRange in mColorRanges) { if(bFoundStartSegment) { CharsToCopy = Math.Min(Length, CurRange.Length); Segments.Add(new ColoredDocumentLineSegment(new ColorPair(CurRange.BackColor, CurRange.ForeColor), this.ToString(CurRange.StartIndex, CharsToCopy))); Length -= CharsToCopy; if(Length <= 0) { break; } } else { if(CurRange.StartIndex <= StartIndex) { bFoundStartSegment = true; CharsToCopy = Math.Min(Length, CurRange.Length); Segments.Add(new ColoredDocumentLineSegment(new ColorPair(CurRange.BackColor, CurRange.ForeColor), this.ToString(Math.Max(StartIndex, CurRange.StartIndex), CharsToCopy))); Length -= CharsToCopy; if(Length <= 0) { break; } } } } return Segments.ToArray(); } /// <summary> /// Gets an array of colored line segments that can be used for drawing. /// </summary> /// <remarks> /// If the line of text contains any instances of <paramref name="FindText"/> they will be replaced with new line segments that contain <paramref name="InsertionColors"/> for drawing. /// </remarks> /// <param name="StartIndex">The starting character at which to begin generating segments.</param> /// <param name="Length">The number of characters to include in segment generation.</param> /// <param name="FindText">Text to search for that requires special coloring.</param> /// <param name="InsertionColors">The colors to use when drawing <paramref name="FindText"/>.</param> /// <param name="ComparisonType">The type of string comparison that will be conducted when searching for <paramref name="FindText"/>.</param> /// <param name="bHasFindText">Set to True if <paramref name="FindText"/> exists within the line segments.</param> /// <returns>An array of colored line segments.</returns> public ColoredDocumentLineSegment[] GetLineSegmentsWithFindString(int StartIndex, int Length, string FindText, ColorPair InsertionColors, StringComparison ComparisonType, out bool bHasFindText) { string LineText = this.ToString(); int FindTextIndex = LineText.IndexOf(FindText, ComparisonType); int EndLineIndex = StartIndex + Length; List<ColoredTextRange> FindTextSegments = new List<ColoredTextRange>(mColorRanges.Count); List<ColoredDocumentLineSegment> Segments = new List<ColoredDocumentLineSegment>(mColorRanges.Count * 2); while(FindTextIndex != -1) { if(FindTextIndex >= EndLineIndex) { break; } // If any part of the text is past StartIndex it will be visible so add it to the array if(FindTextIndex + FindText.Length > StartIndex) { if(FindTextIndex >= StartIndex) { FindTextSegments.Add(new ColoredTextRange(InsertionColors.ForeColor, InsertionColors.BackColor, FindTextIndex, FindText.Length)); } else { FindTextSegments.Add(new ColoredTextRange(InsertionColors.ForeColor, InsertionColors.BackColor, StartIndex, (FindTextIndex + FindText.Length) - StartIndex)); } } FindTextIndex = LineText.IndexOf(FindText, FindTextIndex + FindText.Length, ComparisonType); } bHasFindText = FindTextSegments.Count > 0; int CurrentFindTextSegmentIndex = 0; bool bHasOverlap = false; foreach(ColoredTextRange TextRange in this.mColorRanges) { if(TextRange.StartIndex < StartIndex && TextRange.StartIndex + TextRange.Length <= StartIndex) { continue; } else if(TextRange.StartIndex >= EndLineIndex) { break; } int CurTextRangeStart = Math.Max(StartIndex, TextRange.StartIndex); if(CurrentFindTextSegmentIndex < FindTextSegments.Count) { int CurTextRangeEnd = Math.Min(TextRange.StartIndex + TextRange.Length, EndLineIndex); // check to see if it's an overlapping find segment if(bHasOverlap) { // if it is then it has already been added so reassign the start point CurTextRangeStart = FindTextSegments[CurrentFindTextSegmentIndex].StartIndex + FindTextSegments[CurrentFindTextSegmentIndex].Length; ++CurrentFindTextSegmentIndex; bHasOverlap = false; } while(CurrentFindTextSegmentIndex < FindTextSegments.Count && CurTextRangeStart < EndLineIndex && FindTextSegments[CurrentFindTextSegmentIndex].StartIndex >= CurTextRangeStart && FindTextSegments[CurrentFindTextSegmentIndex].StartIndex < CurTextRangeEnd) { if(FindTextSegments[CurrentFindTextSegmentIndex].StartIndex > CurTextRangeStart) { Segments.Add(new ColoredDocumentLineSegment(new ColorPair(TextRange.BackColor, TextRange.ForeColor), this.ToString(CurTextRangeStart, Math.Min(FindTextSegments[CurrentFindTextSegmentIndex].StartIndex - CurTextRangeStart, EndLineIndex - CurTextRangeStart)))); } if(FindTextSegments[CurrentFindTextSegmentIndex].StartIndex < EndLineIndex) { Segments.Add(new ColoredDocumentLineSegment(InsertionColors, this.ToString(FindTextSegments[CurrentFindTextSegmentIndex].StartIndex, Math.Min(FindTextSegments[CurrentFindTextSegmentIndex].Length, EndLineIndex - FindTextSegments[CurrentFindTextSegmentIndex].StartIndex)))); } CurTextRangeStart = FindTextSegments[CurrentFindTextSegmentIndex].StartIndex + FindTextSegments[CurrentFindTextSegmentIndex].Length; // if the beginning of the next segment is within the current text range move onto the next "find" segment // if not that means the current "find" text segment overlaps into the next regular text segment if(CurTextRangeStart < CurTextRangeEnd) { ++CurrentFindTextSegmentIndex; } else { bHasOverlap = true; } } // if there was text remaining in the current text range after the last segment then add it now if(CurTextRangeStart < CurTextRangeEnd && CurTextRangeStart < EndLineIndex) { Segments.Add(new ColoredDocumentLineSegment(new ColorPair(TextRange.BackColor, TextRange.ForeColor), this.ToString(CurTextRangeStart, Math.Min(CurTextRangeEnd - CurTextRangeStart, EndLineIndex - CurTextRangeStart)))); } } else { Segments.Add(new ColoredDocumentLineSegment(new ColorPair(TextRange.BackColor, TextRange.ForeColor), this.ToString(CurTextRangeStart, Math.Min(TextRange.Length, EndLineIndex - CurTextRangeStart)))); } } return Segments.ToArray(); } /// <summary> /// Finishes construction of the line so that reads and searches may be optimized. /// </summary> public void FinishBuilding() { if(mFinalText == null) { mFinalText = mBldrText.ToString(); mBldrText = null; } } /// <summary> /// Returns the text associated with the line. /// </summary> /// <returns>The text associated with the line.</returns> public override string ToString() { return mFinalText == null ? mBldrText.ToString() : mFinalText; } /// <summary> /// Returns the text associated with the line. /// </summary> /// <param name="StartIndex">The character index that the returned text will start at.</param> /// <param name="Length">The number of characters to return.</param> /// <returns>A string containing the text within the specified range of the line.</returns> public string ToString(int StartIndex, int Length) { if(mFinalText == null) { return mBldrText.ToString(StartIndex, Length); } return mFinalText.Substring(StartIndex, Length); } #region ICloneable Members public object Clone() { DocumentLine NewLine = new DocumentLine(); if(mBldrText != null) { NewLine.mBldrText.Append(mBldrText.ToString()); } else { NewLine.mBldrText = null; } NewLine.mFinalText = mFinalText; NewLine.mColorRanges = new List<ColoredTextRange>(mColorRanges); if(mUserData != null) { NewLine.mUserData = mUserData.Clone() as ICloneable; } return NewLine; } #endregion } /// <summary> /// This structure represents a read only document line. /// </summary> /// <remarks> /// This is a structure for performance reasons. This will be allocated for every line that is completed for the OnLineAdded event and if it was a class it would increase GC pressure. /// </remarks> public struct ReadOnlyDocumentLine { DocumentLine mDocLine; internal ReadOnlyDocumentLine(DocumentLine DocLine) { mDocLine = DocLine; } /// <summary> /// Gets the length of the line in characters. /// </summary> public int Length { get { return mDocLine.Length; } } /// <summary> /// Gets/Sets the user data associated with the line. /// </summary> public ICloneable UserData { get { return mDocLine.UserData; } set { mDocLine.UserData = value; } } /// <summary> /// Gets the character at the specified index. /// </summary> /// <param name="Index">The index of the character to get.</param> /// <returns>The character at the specified index.</returns> public char this[int Index] { get { return mDocLine[Index]; } } /// <summary> /// Gets an array of colored line segments that can be used for drawing. /// </summary> /// <returns>An array of colored line segments.</returns> public ColoredDocumentLineSegment[] GetLineSegments() { return mDocLine.GetLineSegments(); } /// <summary> /// Gets an array of colored line segments that can be used for drawing. /// </summary> /// <param name="StartIndex">The starting character at which to begin generating segments.</param> /// <param name="Length">The number of characters to include in segment generation.</param> /// <returns>An array of colored line segments.</returns> public ColoredDocumentLineSegment[] GetLineSegments(int StartIndex, int Length) { return mDocLine.GetLineSegments(StartIndex, Length); } /// <summary> /// Returns the text associated with the line. /// </summary> /// <returns>The text associated with the line.</returns> public override string ToString() { return mDocLine.ToString(); } /// <summary> /// Returns the text associated with the line. /// </summary> /// <param name="StartIndex">The character index that the returned text will start at.</param> /// <param name="Length">The number of characters to return.</param> /// <returns>A string containing the text within the specified range of the line.</returns> public string ToString(int StartIndex, int Length) { return mDocLine.ToString(StartIndex, Length); } } List<DocumentLine> mLines = new List<DocumentLine>(); int mLongestLineLength; EventHandler<OutputWindowDocumentLineAddedEventArgs> mOnLineAdded; EventHandler<EventArgs> mOnModified; /// <summary> /// Triggered when a full line of text has been added to the document. /// </summary> public event EventHandler<OutputWindowDocumentLineAddedEventArgs> LineAdded { add { mOnLineAdded += value; } remove { mOnLineAdded -= value; } } /// <summary> /// Triggered when the document has been modified. /// </summary> public event EventHandler<EventArgs> Modified { add { mOnModified += value; } remove { mOnModified -= value; } } /// <summary> /// Gets/Sets the text in the document. /// </summary> public string Text { set { if(value == null) { throw new ArgumentNullException("value"); } Clear(); AppendText(null, value); } get { StringBuilder Bldr = new StringBuilder(); foreach(DocumentLine CurLine in mLines) { Bldr.Append(CurLine.ToString()); } return Bldr.ToString(); } } /// <summary> /// Gets the lines associated with the document. /// </summary> public string[] Lines { get { string[] Ret = new string[mLines.Count]; for(int i = 0; i < mLines.Count; ++i) { Ret[i] = mLines[i].ToString(); } return Ret; } } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { return mLines.Count; } } /// <summary> /// Gets the length in characters of the longest line in the document. /// </summary> public int LongestLineLength { get { return mLongestLineLength; } } /// <summary> /// Gets the <see cref="TextLocation"/> of the beginning of the document. /// </summary> public TextLocation BeginningOfDocument { get { return new TextLocation(0, 0); } } /// <summary> /// Gets the <see cref="TextLocation"/> of the end of the document. /// </summary> public TextLocation EndOfDocument { get { int LineIndex = Math.Max(0, mLines.Count - 1); return new TextLocation(LineIndex, GetLineLength(LineIndex)); } } /// <summary> /// Constructor. /// </summary> public OutputWindowDocument() { // The document always has at least 1 line. mLines.Add(new DocumentLine()); } /// <summary> /// Appends text of the specified color to the document. /// </summary> /// <param name="TxtColor">The color of the text to be appended</param> /// <param name="Txt">The text to be appended</param> public void AppendText(Color? TxtColor, string Txt) { if(Txt.Length == 0) { return; } DocumentLine CurLine; int CurLineLength = 0; if(mLines.Count == 0) { CurLine = new DocumentLine(); mLines.Add(CurLine); } else { CurLine = mLines[mLines.Count - 1]; } char LastChar = (char)0; // Break the Text in to multiple lines String[] Lines = System.Text.RegularExpressions.Regex.Split(Txt, "\r\n"); foreach (String Line in Lines) { // Skip empty lines if (Line.Length == 0) { continue; } // Put back the \r\n String ThisLine = Line + "\r\n"; Color? CurrColor = TxtColor; // Check for keywords if (ThisLine.Contains("Error")) { CurrColor = Color.Red; } else if (ThisLine.Contains("Warning")) { CurrColor = Color.Orange; } // Append the line foreach (char CurChar in ThisLine) { if (CurChar == '\n' && LastChar != '\r') { CurLine.Append(CurrColor, '\r'); } // replace tabs with 4 spaces if (CurChar == '\t') { CurLine.Append(CurrColor, " "); } else { CurLine.Append(CurrColor, CurChar); } if (CurChar == '\n') { // only count displayable characters (cut \r\n) CurLineLength = CurLine.Length - 2; if (CurLineLength > mLongestLineLength) { mLongestLineLength = CurLineLength; } // This isn't required but it enables readonly optimizations CurLine.FinishBuilding(); // A full line has been created so trigger the line added event OnLineAdded(new OutputWindowDocumentLineAddedEventArgs(mLines.Count - 1, new ReadOnlyDocumentLine(CurLine))); // Then begin our new line CurLine = new DocumentLine(); mLines.Add(CurLine); } LastChar = CurChar; } } // NOTE: This line hasn't been terminated yet so we don't have to account for \r\n at the end CurLineLength = CurLine.Length; if(CurLineLength > mLongestLineLength) { mLongestLineLength = CurLineLength; } OnModified(new EventArgs()); } /// <summary> /// Appends a line of colored text to the document. /// </summary> /// <param name="TxtColor">The color of the text to be appended.</param> /// <param name="Txt">The text to append.</param> public void AppendLine(Color? TxtColor, string Txt) { AppendText(TxtColor, Txt + Environment.NewLine); } /// <summary> /// Retrieves a line of text from the document. /// </summary> /// <param name="Index">The index of the line to retrieve.</param> /// <param name="bIncludeEOL">True if the line includes the EOL characters.</param> /// <returns>A string containing the text of the specified line.</returns> public string GetLine(int Index, bool bIncludeEOL) { DocumentLine Line = mLines[Index]; if(!bIncludeEOL && Line.Length >= 2 && Line[Line.Length - 1] == '\n' && Line[Line.Length - 2] == '\r') { return Line.ToString(0, Line.Length - 2); } return Line.ToString(); } /// <summary> /// Retrieves a line of text from the document. /// </summary> /// <param name="LineIndex">The index of the line to retrieve.</param> /// <param name="CharOffset">The character to start copying.</param> /// <param name="Length">The number of characters to copy.</param> /// <returns>A string containing the specified range of text text in the specified line.</returns> public string GetLine(int LineIndex, int CharOffset, int Length) { return mLines[LineIndex].ToString(CharOffset, Length); } /// <summary> /// Gets the length of the line in characters at the specified index. /// </summary> /// <param name="Index">The index of the line to retrieve length information for.</param> /// <returns>The length of the line in characters at the specified index.</returns> public int GetLineLength(int Index) { if(Index >= 0 && Index < mLines.Count) { return GetLineLength(mLines[Index]); } return 0; } /// <summary> /// Gets the length of the line in characters. /// </summary> /// <param name="Line">The line whose length is to be retrieved.</param> /// <returns>The length of the line with the EOL characters removed (if they exist).</returns> private static int GetLineLength(DocumentLine Line) { if(Line.Length >= 2 && Line[Line.Length - 1] == '\n' && Line[Line.Length - 2] == '\r') { return Line.Length - 2; } else { return Line.Length; } } /// <summary> /// Clears the document. /// </summary> public void Clear() { mLines.Clear(); mLongestLineLength = 0; OnModified(new EventArgs()); } /// <summary> /// Finds the first occurence of the specified string within the document if it exists. /// </summary> /// <param name="Txt">The string to find.</param> /// <param name="StartLoc">The position within the document to begin searching.</param> /// <param name="EndLoc">The position within the document to end searching.</param> /// <param name="Flags">Flags telling the document how to conduct its search.</param> /// <param name="Result">The location within the document of the supplied text.</param> /// <returns>True if the text was found.</returns> public bool Find(string Txt, TextLocation StartLoc, TextLocation EndLoc, RichTextBoxFinds Flags, out FindResult Result) { if((Flags & RichTextBoxFinds.Reverse) == RichTextBoxFinds.Reverse) { return FindReverse(Txt, ref StartLoc, ref EndLoc, Flags, out Result); } else { return FindForward(Txt, ref StartLoc, ref EndLoc, Flags, out Result); } } /// <summary> /// Looks forward in the document from the specified location for the supplied text. /// </summary> /// <param name="Txt">The text to find.</param> /// <param name="StartLoc">The location to start searching from.</param> /// <param name="EndLoc">The location to stop searching at.</param> /// <param name="Flags">Flags that control how the search is performed.</param> /// <param name="Result">Receives the result.</param> /// <returns>True if a match was found.</returns> private bool FindForward(string Txt, ref TextLocation StartLoc, ref TextLocation EndLoc, RichTextBoxFinds Flags, out FindResult Result) { bool bMatchWord; bool bFound = false; bool bIsWord; StringComparison ComparisonFlags; SetupFindState(Txt, ref StartLoc, ref EndLoc, Flags, out Result, out bIsWord, out ComparisonFlags, out bMatchWord); for(int CurLineIndex = StartLoc.Line; CurLineIndex <= EndLoc.Line && !bFound; ++CurLineIndex) { if(GetLineLength(CurLineIndex) == 0) { continue; } DocumentLine CurLineBldr = mLines[CurLineIndex]; string LineTxt; int ColumnIndex = 0; if(CurLineIndex == StartLoc.Line && StartLoc.Column > 0) { LineTxt = CurLineBldr.ToString(StartLoc.Column, CurLineBldr.Length - StartLoc.Column); ColumnIndex = StartLoc.Column; } else if(CurLineIndex == EndLoc.Line && EndLoc.Column < GetLineLength(CurLineIndex)) { LineTxt = CurLineBldr.ToString(0, EndLoc.Column + 1); } else { LineTxt = CurLineBldr.ToString(); } int Index = LineTxt.IndexOf(Txt, ComparisonFlags); if(Index != -1) { ColumnIndex += Index; CheckForWholeWord(Txt, ref Result, bMatchWord, ref bFound, bIsWord, CurLineIndex, CurLineBldr, ColumnIndex, Index); } } return bFound; } /// <summary> /// Checks to see if a text location is a matching word. /// </summary> /// <param name="Txt">The text being searched for.</param> /// <param name="Result">Receives the result if the text location is a matching word.</param> /// <param name="bMatchWord">True if an entire word is to be matched.</param> /// <param name="bFound">Set to true if a matching word is found.</param> /// <param name="bIsWord">True if <paramref name="Txt"/> is a valid word.</param> /// <param name="CurLineIndex">The index of the current line.</param> /// <param name="CurLineBldr">The text of the current line.</param> /// <param name="ColumnIndex">The character index within the line of text where the matching will begin.</param> /// <param name="Index">The index of a match within the range of searchable characters for the current line. The true line index is <paramref name="ColumnIndex"/> + <paramref name="Index"/>.</param> private static void CheckForWholeWord(string Txt, ref FindResult Result, bool bMatchWord, ref bool bFound, bool bIsWord, int CurLineIndex, DocumentLine CurLine, int ColumnIndex, int Index) { int FinalCharIndex = ColumnIndex + Txt.Length; if(bMatchWord && bIsWord) { if((FinalCharIndex >= CurLine.Length || !IsWordCharacter(CurLine[FinalCharIndex])) && (ColumnIndex == 0 || !IsWordCharacter(CurLine[ColumnIndex - 1]))) { bFound = true; } } else { bFound = true; } if(bFound) { Result.Line = CurLineIndex; Result.Column = ColumnIndex; Result.Length = Txt.Length; } } /// <summary> /// Checks to see if a character is valid within a word. /// </summary> /// <param name="CharToCheck">The character to check.</param> /// <returns>True if the character is valid within a word.</returns> private static bool IsWordCharacter(char CharToCheck) { return char.IsLetterOrDigit(CharToCheck) || CharToCheck == '_'; } /// <summary> /// Performs general housekeeping for setting up a search. /// </summary> /// <param name="Txt">The text to search for.</param> /// <param name="StartLoc">The location to begin searching from.</param> /// <param name="EndLoc">The location to stop searching at.</param> /// <param name="Flags">Flags controlling how the search is performed.</param> /// <param name="Result">Receives the resulting location if a match is found.</param> /// <param name="bIsWord">Set to true if <paramref name="Txt"/> is a valid word.</param> /// <param name="ComparisonFlags">Receives flags controlling how strings are compared.</param> /// <param name="bMatchWord">Is set to true if only full words are to be matched.</param> private void SetupFindState(string Txt, ref TextLocation StartLoc, ref TextLocation EndLoc, RichTextBoxFinds Flags, out FindResult Result, out bool bIsWord, out StringComparison ComparisonFlags, out bool bMatchWord) { Result = FindResult.Empty; if(!IsValidTextLocation(StartLoc)) { throw new ArgumentException("StartLoc is an invalid text location!"); } if(!IsValidTextLocation(EndLoc)) { throw new ArgumentException("EndLoc is an invalid text location!"); } if((Flags & RichTextBoxFinds.Reverse) == RichTextBoxFinds.Reverse) { if(StartLoc < EndLoc) { throw new ArgumentException("StartLoc must be greater than EndLoc when doing a reverse search!"); } } else { if(StartLoc > EndLoc) { throw new ArgumentException("StartLoc must be less than EndLoc when doing a forward search!"); } } bMatchWord = (Flags & RichTextBoxFinds.WholeWord) == RichTextBoxFinds.WholeWord; bIsWord = IsWord(0, Txt); ComparisonFlags = StringComparison.OrdinalIgnoreCase; if((Flags & RichTextBoxFinds.MatchCase) == RichTextBoxFinds.MatchCase) { ComparisonFlags = StringComparison.Ordinal; } } /// <summary> /// Checks a string to see if it contains a valid word. /// </summary> /// <param name="Index">The index to start validating at.</param> /// <param name="Txt">The text to be validated.</param> /// <returns>True if all text including and after <paramref name="Index"/> are part of a valid word.</returns> private static bool IsWord(int Index, string Txt) { for(; Index < Txt.Length; ++Index) { char CurChar = Txt[Index]; if(!char.IsLetterOrDigit(CurChar) && CurChar != '_') { return false; } } return true; } /// <summary> /// Searches for a string in the reverse direction of <see cref="FindForward"/>. /// </summary> /// <param name="Txt">The text to search for.</param> /// <param name="StartLoc">The starting location of the search.</param> /// <param name="EndLoc">The ending location of the search.</param> /// <param name="Flags">Flags controlling how the searching is conducted.</param> /// <param name="Result">Receives the results of the search.</param> /// <returns>True if a match was found.</returns> private bool FindReverse(string Txt, ref TextLocation StartLoc, ref TextLocation EndLoc, RichTextBoxFinds Flags, out FindResult Result) { bool bFound = false; bool bMatchWord; bool bIsWord; StringComparison ComparisonFlags; SetupFindState(Txt, ref StartLoc, ref EndLoc, Flags, out Result, out bIsWord, out ComparisonFlags, out bMatchWord); for(int CurLineIndex = StartLoc.Line; CurLineIndex >= EndLoc.Line && !bFound; --CurLineIndex) { if(GetLineLength(CurLineIndex) == 0) { continue; } DocumentLine CurLineBldr = mLines[CurLineIndex]; string LineTxt; int ColumnIndex = 0; if(CurLineIndex == StartLoc.Line && StartLoc.Column < GetLineLength(CurLineIndex)) { LineTxt = CurLineBldr.ToString(0, StartLoc.Column); } else if(CurLineIndex == EndLoc.Line && EndLoc.Column > 0) { LineTxt = CurLineBldr.ToString(EndLoc.Column, CurLineBldr.Length - EndLoc.Column); ColumnIndex = EndLoc.Column; } else { LineTxt = CurLineBldr.ToString(); } int Index = LineTxt.LastIndexOf(Txt, ComparisonFlags); if(Index != -1) { ColumnIndex += Index; CheckForWholeWord(Txt, ref Result, bMatchWord, ref bFound, bIsWord, CurLineIndex, CurLineBldr, ColumnIndex, Index); } } return bFound; } /// <summary> /// Saves the document to disk. /// </summary> /// <param name="Name">The path to a file that the document will be written to.</param> public void SaveToFile(string Name) { using(StreamWriter Writer = new StreamWriter(File.Open(Name, FileMode.Create, FileAccess.Write, FileShare.Read))) { foreach(DocumentLine CurLine in mLines) { Writer.Write(CurLine.ToString()); } } } /// <summary> /// Determines whether a location within the document is valid. /// </summary> /// <param name="Loc">The location to validate.</param> /// <returns>True if the supplied location is within the bounds of the document.</returns> public bool IsValidTextLocation(TextLocation Loc) { bool bResult = false; if(Loc.Line >= 0 && Loc.Line < mLines.Count && Loc.Column >= 0 && Loc.Column <= GetLineLength(Loc.Line)) { bResult = true; } return bResult; } /// <summary> /// Gets an array of line segments for the line at the specified index. /// </summary> /// <param name="LineIndex">The index of the line to retrieve the segments for.</param> /// <returns>An array of line segments.</returns> public ColoredDocumentLineSegment[] GetLineSegments(int LineIndex) { return mLines[LineIndex].GetLineSegments(); } /// <summary> /// Gets an array of line segments for the line at the specified index. /// </summary> /// <param name="LineIndex">The index of the line to retrieve the segments for.</param> /// <param name="StartIndex">The starting character at which to begin generating segments.</param> /// <param name="Length">The number of characters to include in segment generation.</param> /// <returns>An array of line segments.</returns> public ColoredDocumentLineSegment[] GetLineSegments(int LineIndex, int StartIndex, int Length) { return mLines[LineIndex].GetLineSegments(StartIndex, Length); } /// <summary> /// Gets an array of colored line segments that can be used for drawing. /// </summary> /// <remarks> /// If the line of text contains any instances of <paramref name="FindText"/> they will be replaced with new line segments that contain <paramref name="InsertionColors"/> for drawing. /// </remarks> /// <param name="LineIndex">The index of the line to retrieve the segments for.</param> /// <param name="StartIndex">The starting character at which to begin generating segments.</param> /// <param name="Length">The number of characters to include in segment generation.</param> /// <param name="FindText">Text to search for that requires special coloring.</param> /// <param name="InsertionColors">The colors to use when drawing <paramref name="FindText"/>.</param> /// <param name="ComparisonType">The type of string comparison that will be conducted when searching for <paramref name="FindText"/>.</param> /// <param name="bHasFindText">Set to True if <paramref name="FindText"/> exists within the line segments.</param> /// <returns>An array of colored line segments.</returns> public ColoredDocumentLineSegment[] GetLineSegmentsWithFindString(int LineIndex, int StartIndex, int Length, string FindText, ColorPair InsertionColors, StringComparison ComparisonType, out bool bHasFindText) { return mLines[LineIndex].GetLineSegmentsWithFindString(StartIndex, Length, FindText, InsertionColors, ComparisonType, out bHasFindText); } /// <summary> /// Event handler for when a full line of text has been added to the document. /// </summary> /// <param name="e">Information about the event.</param> protected virtual void OnLineAdded(OutputWindowDocumentLineAddedEventArgs e) { if(mOnLineAdded != null) { mOnLineAdded(this, e); } } /// <summary> /// Event handler for when the document has been modified. /// </summary> /// <param name="e">Information about the event.</param> protected virtual void OnModified(EventArgs e) { if(mOnModified != null) { mOnModified(this, e); } } /// <summary> /// Creates a new document by filtering out the lines of the current document using the supplied filter function. /// </summary> /// <param name="Filter">The function that will filter the lines out of the current document.</param> /// <param name="Data">User supplied data that may control filtering.</param> /// <returns>A new document containing filtered lines from the current document.</returns> public OutputWindowDocument CreateFilteredDocument(OutputWindowDocumentFilterDelegate Filter, object Data) { if(Filter == null) { throw new ArgumentNullException("Filter"); } OutputWindowDocument NewDoc = new OutputWindowDocument(); NewDoc.mLines.Capacity = mLines.Capacity; DocumentLine LastLine = null; foreach(DocumentLine CurLine in mLines) { if(!Filter(new ReadOnlyDocumentLine(CurLine), Data)) { DocumentLine NewLine = (DocumentLine)CurLine.Clone(); NewDoc.mLines.Add(NewLine); int LineLength = GetLineLength(NewLine); if(LineLength > NewDoc.mLongestLineLength) { NewDoc.mLongestLineLength = LineLength; } LastLine = NewLine; } } // If the last line is a full line we need to append an empty line because the empty line has been filtered out if(LastLine != null && LastLine.ToString().EndsWith(Environment.NewLine)) { NewDoc.mLines.Add(new DocumentLine()); } return NewDoc; } } }
/* 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; using System.Collections.Generic; using System.Linq; using Orleans.Runtime; using Orleans.Streams; namespace Orleans.Providers.Streams.Common { internal class CacheBucket { // For backpressure detection we maintain a histogram of 10 buckets. // Every buckets recors how many items are in the cache in that bucket // and how many cursors are poinmting to an item in that bucket. // We update the NumCurrentItems when we add and remove cache item (potentially opening or removing a bucket) // We update NumCurrentCursors every time we move a cursor // If the first (most outdated bucket) has at least one cursor pointing to it, we say we are under back pressure (in a full cache). internal int NumCurrentItems { get; private set; } internal int NumCurrentCursors { get; private set; } internal void UpdateNumItems(int val) { NumCurrentItems = NumCurrentItems + val; } internal void UpdateNumCursors(int val) { NumCurrentCursors = NumCurrentCursors + val; } } internal struct SimpleQueueCacheItem { internal IBatchContainer Batch; internal StreamSequenceToken SequenceToken; internal CacheBucket CacheBucket; } public class SimpleQueueCache : IQueueCache { private readonly LinkedList<SimpleQueueCacheItem> cachedMessages; private readonly int maxCacheSize; private readonly Logger logger; private readonly List<CacheBucket> cacheCursorHistogram; // for backpressure detection private const int NUM_CACHE_HISTOGRAM_BUCKETS = 10; private readonly int CACHE_HISTOGRAM_MAX_BUCKET_SIZE; public QueueId Id { get; private set; } public int Size { get { return cachedMessages.Count; } } public int MaxAddCount { get { return CACHE_HISTOGRAM_MAX_BUCKET_SIZE; } } public SimpleQueueCache(QueueId queueId, int cacheSize, Logger logger) { Id = queueId; cachedMessages = new LinkedList<SimpleQueueCacheItem>(); maxCacheSize = cacheSize; this.logger = logger; cacheCursorHistogram = new List<CacheBucket>(); CACHE_HISTOGRAM_MAX_BUCKET_SIZE = Math.Max(cacheSize / NUM_CACHE_HISTOGRAM_BUCKETS, 1); // we have 10 buckets } public bool IsUnderPressure() { if (cachedMessages.Count == 0) return false; // empty cache if (Size < maxCacheSize) return false; // there is still space in cache if (cacheCursorHistogram.Count == 0) return false; // no cursors yet - zero consumers basically yet. // cache is full. Check how many cursors we have in the oldest bucket. int numCursorsInLastBucket = cacheCursorHistogram[0].NumCurrentCursors; return numCursorsInLastBucket > 0; } public virtual void AddToCache(IList<IBatchContainer> msgs) { if (msgs == null) throw new ArgumentNullException("msgs"); Log(logger, "AddToCache: added {0} items to cache.", msgs.Count); foreach (var message in msgs) { Add(message, message.SequenceToken); } } public virtual IQueueCacheCursor GetCacheCursor(Guid streamGuid, string streamNamespace, StreamSequenceToken token) { if (token != null && !(token is EventSequenceToken)) { // Null token can come from a stream subscriber that is just interested to start consuming from latest (the most recent event added to the cache). throw new ArgumentOutOfRangeException("token", "token must be of type EventSequenceToken"); } var cursor = new SimpleQueueCacheCursor(this, streamGuid, streamNamespace, logger); InitializeCursor(cursor, token); return cursor; } private void InitializeCursor(SimpleQueueCacheCursor cursor, StreamSequenceToken sequenceToken) { Log(logger, "InitializeCursor: {0} to sequenceToken {1}", cursor, sequenceToken); if (cachedMessages.Count == 0) // nothing in cache { ResetCursor(cursor, sequenceToken); return; } // if offset is not set, iterate from newest (first) message in cache, but not including the irst message itself if (sequenceToken == null) { LinkedListNode<SimpleQueueCacheItem> firstMessage = cachedMessages.First; ResetCursor(cursor, ((EventSequenceToken)firstMessage.Value.SequenceToken).NextSequenceNumber()); return; } if (sequenceToken.Newer(cachedMessages.First.Value.SequenceToken)) // sequenceId is too new to be in cache { ResetCursor(cursor, sequenceToken); return; } LinkedListNode<SimpleQueueCacheItem> lastMessage = cachedMessages.Last; // Check to see if offset is too old to be in cache if (sequenceToken.Older(lastMessage.Value.SequenceToken)) { // throw cache miss exception throw new QueueCacheMissException(sequenceToken, cachedMessages.Last.Value.SequenceToken, cachedMessages.First.Value.SequenceToken); } // Now the requested sequenceToken is set and is also within the limits of the cache. // Find first message at or below offset // Events are ordered from newest to oldest, so iterate from start of list until we hit a node at a previous offset, or the end. LinkedListNode<SimpleQueueCacheItem> node = cachedMessages.First; while (node != null && node.Value.SequenceToken.Newer(sequenceToken)) { // did we get to the end? if (node.Next == null) // node is the last message break; // if sequenceId is between the two, take the higher if (node.Next.Value.SequenceToken.Older(sequenceToken)) break; node = node.Next; } // return cursor from start. SetCursor(cursor, node); } /// <summary> /// Aquires the next message in the cache at the provided cursor /// </summary> /// <param name="cursor"></param> /// <param name="batch"></param> /// <returns></returns> internal bool TryGetNextMessage(SimpleQueueCacheCursor cursor, out IBatchContainer batch) { Log(logger, "TryGetNextMessage: {0}", cursor); batch = null; if (cursor == null) throw new ArgumentNullException("cursor"); //if not set, try to set and then get next if (!cursor.IsSet) { InitializeCursor(cursor, cursor.SequenceToken); return cursor.IsSet && TryGetNextMessage(cursor, out batch); } // has this message been purged if (cursor.SequenceToken.Older(cachedMessages.Last.Value.SequenceToken)) { throw new QueueCacheMissException(cursor.SequenceToken, cachedMessages.Last.Value.SequenceToken, cachedMessages.First.Value.SequenceToken); } // Cursor now points to a valid message in the cache. Get it! // Capture the current element and advance to the next one. batch = cursor.Element.Value.Batch; // Advance to next: if (cursor.Element == cachedMessages.First) { // If we are at the end of the cache unset cursor and move offset one forward ResetCursor(cursor, ((EventSequenceToken)cursor.SequenceToken).NextSequenceNumber()); } else // move to next { UpdateCursor(cursor, cursor.Element.Previous); } return true; } private void UpdateCursor(SimpleQueueCacheCursor cursor, LinkedListNode<SimpleQueueCacheItem> item) { Log(logger, "UpdateCursor: {0} to item {1}", cursor, item.Value.Batch); cursor.Element.Value.CacheBucket.UpdateNumCursors(-1); // remove from prev bucket cursor.Set(item); cursor.Element.Value.CacheBucket.UpdateNumCursors(1); // add to next bucket } internal void SetCursor(SimpleQueueCacheCursor cursor, LinkedListNode<SimpleQueueCacheItem> item) { Log(logger, "SetCursor: {0} to item {1}", cursor, item.Value.Batch); cursor.Set(item); cursor.Element.Value.CacheBucket.UpdateNumCursors(1); // add to next bucket } internal void ResetCursor(SimpleQueueCacheCursor cursor, StreamSequenceToken token) { Log(logger, "ResetCursor: {0} to token {1}", cursor, token); if (cursor.IsSet) { cursor.Element.Value.CacheBucket.UpdateNumCursors(-1); } cursor.Reset(token); } private void Add(IBatchContainer batch, StreamSequenceToken sequenceToken) { if (batch == null) throw new ArgumentNullException("batch"); CacheBucket cacheBucket = null; if (cacheCursorHistogram.Count == 0) { cacheBucket = new CacheBucket(); cacheCursorHistogram.Add(cacheBucket); } else { cacheBucket = cacheCursorHistogram[cacheCursorHistogram.Count - 1]; // last one } if (cacheBucket.NumCurrentItems == CACHE_HISTOGRAM_MAX_BUCKET_SIZE) // last bucket is full, open a new one { cacheBucket = new CacheBucket(); cacheCursorHistogram.Add(cacheBucket); } cacheBucket.UpdateNumItems(1); // Add message to linked list var item = new SimpleQueueCacheItem { Batch = batch, SequenceToken = sequenceToken, CacheBucket = cacheBucket }; cachedMessages.AddFirst(new LinkedListNode<SimpleQueueCacheItem>(item)); if (Size > maxCacheSize) { //var last = cachedMessages.Last; cachedMessages.RemoveLast(); var bucket = cacheCursorHistogram[0]; // same as: var bucket = last.Value.CacheBucket; bucket.UpdateNumItems(-1); if (bucket.NumCurrentItems == 0) { cacheCursorHistogram.RemoveAt(0); } } } internal static void Log(Logger logger, string format, params object[] args) { if (logger.IsVerbose) logger.Verbose(format, args); //if(logger.IsInfo) logger.Info(format, args); } } }
using System; using System.Collections.Generic; using System.Linq; using Appccelerate.EventBroker; using Appccelerate.EventBroker.Handlers; using Eto.Forms; using Ninject; using SharpFlame.Core; using SharpFlame.Core.Collections; using SharpFlame.Domain; using SharpFlame.FileIO; using SharpFlame.Mapping; using SharpFlame.Mapping.Objects; using SharpFlame.Mapping.Tools; using SharpFlame.Maths; using SharpFlame.MouseTools; using SharpFlame.Settings; using Z.ExtensionMethods.ObjectExtensions; namespace SharpFlame.Gui.Sections { public class ObjectTab : TabPage { [Inject] internal ToolOptions ToolOptions { get; set; } [Inject] internal ObjectManager ObjectManager { get; set; } [Inject] internal IEventBroker EventBroker { get; set; } private Label lblObjectName; private Map map; private GroupBox grpPlayers; private NumericUpDown txtRotation; private TextBox txtId; private TextBox txtLabel; private NumericUpDown txtHealth; private DropDown ddlType; private DropDown ddlBody; private DropDown ddlProp; private DropDown ddlTurret1; private DropDown ddlTurret2; private DropDown ddlTurret3; private NumericUpDown nudTurrets; private CheckBox chkDesignable; public ObjectTab () { XomlReader.Load(this); } private StackLayout slTurret1; private StackLayout slTurret2; private StackLayout slTurret3; protected override void OnPreLoad(EventArgs e) { base.OnPreLoad(e); this.slTurret1.Bind(t => t.Visible, this.nudTurrets.ValueBinding.Convert(d => d >= 1)); this.slTurret2.Bind(t => t.Visible, this.nudTurrets.ValueBinding.Convert(d => d >= 2)); this.slTurret3.Bind(t => t.Visible, this.nudTurrets.ValueBinding.Convert(d => d >= 3)); this.lblObjectName.TextBinding.BindDataContext<Map>(getValue: m => { if( m.SelectedUnits.Count == 0 ) { return "<none selected>"; } if( m.SelectedUnits.Count > 1 ) { return "Multiple Objects"; } if( m.SelectedUnits.Count == 1 ) { var u = m.SelectedUnits[0]; return u.TypeBase.GetDisplayTextCode(); } return string.Empty; }, setValue: (m, s) => { }, mode: DualBindingMode.OneWay); this.txtId.TextBinding.BindDataContext<Map>(getValue: m => { if( m.SelectedUnits.Count == 1 ) { this.txtId.Enabled = true; var u = m.SelectedUnits[0]; return u.ID.ToStringInvariant(); } this.txtId.Enabled = false; return string.Empty; }, setValue: null, mode: DualBindingMode.OneWay); this.txtLabel.TextBinding.BindDataContext<Map>(getValue: m => { if( m.SelectedUnits.Count == 1 ) { var u = m.SelectedUnits[0]; var labelEnabled = u.TypeBase.Type != UnitType.PlayerStructure; if( labelEnabled ) { this.txtLabel.Enabled = true; return u.Label; } } this.txtLabel.Enabled = false; return string.Empty; }, setValue: null, mode: DualBindingMode.OneWay); //this.txtLabel.BindDataContext(t => t.Enabled, Binding.Delegate((Map m) => // { // if( m.SelectedUnits.Count == 1 ) // { // var u = m.SelectedUnits[0]; // return u.TypeBase.Type != UnitType.PlayerStructure; // } // return false; // }, setValue: null), mode: DualBindingMode.OneWay); this.txtHealth.ValueBinding.BindDataContext<Map>(getValue: m => { if( m.SelectedUnits.Count == 1 ) { this.txtHealth.Enabled = true; var u = m.SelectedUnits[0]; return u.Health; } this.txtHealth.Enabled = false; return 1; }, setValue: null, defaultGetValue:100, mode: DualBindingMode.OneWay); this.grpDroidEditor.BindDataContext(t => t.Enabled, Binding.Delegate((Map m) => { DroidDesign droidType = null; if( TryGetDroidDesign(out droidType) ) { return !droidType.IsTemplate; } return false; }, setValue: null), mode: DualBindingMode.OneWay); this.ddlType.SelectedIndexBinding.BindDataContext(getValue: (Map m) => { DroidDesign droidType = null; if( TryGetDroidDesign(out droidType) && droidType.TemplateDroidType != null ) { return droidType.TemplateDroidType.Num; } return -1; } , setValue: (m, val)=> ddlType_Set(m), defaultGetValue: -1); this.ddlBody.SelectedKeyBinding.BindDataContext( getValue: (Map m) => { DroidDesign droidType = null; if( TryGetDroidDesign(out droidType) && droidType.Body != null ) { return droidType.Body?.Code; } return null; } , setValue: (m, val) => ddlBody_Set(m)); this.ddlProp.SelectedKeyBinding.BindDataContext(getValue: (Map m) => { DroidDesign droidType = null; if( TryGetDroidDesign(out droidType) ) { return droidType.Propulsion?.Code; } return null; } , setValue: (m, val) => ddlProp_Set(m)); this.nudTurrets.ValueBinding.BindDataContext<Map>(getValue: m => { DroidDesign droidType = null; if( TryGetDroidDesign(out droidType) ) { return droidType.TurretCount; } return 0; }, setValue: (m, val) => nudTurrets_Set(m, val)); this.ddlTurret1.SelectedKeyBinding.BindDataContext(getValue: (Map m) => { DroidDesign droidType = null; if( TryGetDroidDesign(out droidType) ) { return droidType.Turret1?.Code; } return null; } , setValue: (m,val)=> ddlTurret_Set(m, this.ddlTurret1)); this.ddlTurret2.SelectedKeyBinding.BindDataContext(getValue: (Map m) => { DroidDesign droidType = null; if( TryGetDroidDesign(out droidType) ) { return droidType.Turret2?.Code; } return null; } , setValue: (m, val) => ddlTurret_Set(m, this.ddlTurret2)); this.ddlTurret3.SelectedKeyBinding.BindDataContext(getValue: (Map m) => { DroidDesign droidType = null; if( TryGetDroidDesign(out droidType) ) { return droidType.Turret3?.Code; } return null; } , setValue: (m, val) => ddlTurret_Set(m, this.ddlTurret3)); this.cmdConvertToDroid.BindDataContext(t => t.Enabled, Binding.Delegate((Map m) => { DroidDesign droidType = null; if( TryGetDroidDesign(out droidType) ) { return droidType.IsTemplate; } return false; }, setValue: null), mode: DualBindingMode.OneWay); } private void nudTurrets_Set(Map m, double val) { if( m == null ) return; if( m.SelectedUnits.Count <= 0 ) return; if( m.SelectedUnits.Count > 1 ) { if( MessageBox.Show("Change number of turrets of multiple droids?", "", MessageBoxButtons.OKCancel, MessageBoxType.Question) != DialogResult.Ok ) { return; } } var ObjectTurretCount = new clsObjectTurretCount(); ObjectTurretCount.Map = m; ObjectTurretCount.TurretCount = val.ToByte(); m.SelectedUnitsAction(ObjectTurretCount); this.EventBroker.SelectedUnitsChanged(this); if( ObjectTurretCount.ActionPerformed ) { m.UndoStepCreate("Object Number Of Turrets Changed"); this.EventBroker.DrawLater(this); } } private void ddlType_Set(Map m) { if( !CanSetDesign(m, "type", this.ddlType) ) return; var NewType = App.TemplateDroidTypes[this.ddlType.SelectedIndex]; var ObjectDroidType = new clsObjectDroidType(); ObjectDroidType.Map = m; ObjectDroidType.DroidType = NewType; m.SelectedUnitsAction(ObjectDroidType); this.EventBroker.SelectedUnitsChanged(this); if( ObjectDroidType.ActionPerformed ) { m.UndoStepCreate("Object Number Of Turrets Changed"); this.EventBroker.DrawLater(this); } } private void ddlTurret_Set(Map m, DropDown ddl) { if( !CanSetDesign(m, "turret", ddl) ) return; var objectTurret = new clsObjectTurret(); objectTurret.Map = m; objectTurret.Turret = this.turrets[ddl.SelectedIndex]; objectTurret.TurretNum = ddl.ID.ExtractInt32() - 1; m.SelectedUnitsAction(objectTurret); this.EventBroker.SelectedUnitsChanged(this); if( objectTurret.ActionPerformed ) { m.UndoStepCreate("Object Turret Changed"); this.EventBroker.DrawLater(this); } } private void ddlProp_Set(Map m) { if( !CanSetDesign(m, "propulsion", this.ddlProp) ) return; var objectPropulsion = new clsObjectPropulsion(); objectPropulsion.Map = m; objectPropulsion.Propulsion = this.propulsion[ddlProp.SelectedIndex]; m.SelectedUnitsAction(objectPropulsion); this.EventBroker.SelectedUnitsChanged(this); if( objectPropulsion.ActionPerformed ) { m.UndoStepCreate("Object Body Changed"); this.EventBroker.DrawLater(this); } this.EventBroker.SelectedUnitsChanged(this); if( objectPropulsion.ActionPerformed ) { m.UndoStepCreate("Object Propulsion Changed"); this.EventBroker.DrawLater(this); } } private bool CanSetDesign(Map m, string checktype, DropDown ddl) { if( m == null ) return false; if( !ddl.Enabled ) return false; if( ddl.SelectedIndex < 0 ) return false; if( m.SelectedUnits.Count <= 0 ) return false; if( m.SelectedUnits.Count > 1 ) { if( MessageBox.Show($"Change {checktype} of multiple droids?", "", MessageBoxButtons.OKCancel, MessageBoxType.Question) != DialogResult.Ok ) { return false; } } return true; } private void ddlBody_Set(Map m) { if( !CanSetDesign(m, "body", this.ddlBody) ) return; var objectBody = new clsObjectBody(); objectBody.Map = m; objectBody.Body = bodies[ddlBody.SelectedIndex]; this.map.SelectedUnitsAction(objectBody); this.EventBroker.SelectedUnitsChanged(this); if( objectBody.ActionPerformed ) { this.map.UndoStepCreate("Object Body Changed"); this.EventBroker.DrawLater(this); } } private Button cmdConvertToDroid; private GroupBox grpDroidEditor; private List<Body> bodies; private List<Propulsion> propulsion; private List<Turret> turrets; private bool TryGetUnit(out Unit u) { u = this.map.SelectedUnits[0]; return u != null; } private bool TryGetDroidDesign(out DroidDesign dd) { dd = null; if( this.map.SelectedUnits.Count == 1 ) { var u = map.SelectedUnits[0]; if( u.TypeBase.Type == UnitType.PlayerDroid ) { dd = (DroidDesign)u.TypeBase; } } return dd != null; } public void Tab_Click(object sender, EventArgs e) { ToolOptions.MouseTool = MouseTool.ObjectSelect; } [EventSubscription(EventTopics.OnMapLoad, typeof(OnPublisher))] public void HandleMapLoad(Map args) { this.map = args; //load preset groups this.grpPlayers.Children.OfType<Button>() .ForEach(b => { if( b.Text.StartsWith("P") ) { var player = b.Text.Substring(1).ToInt32(); b.Tag = this.map.UnitGroups[player]; } else if( b.Text.StartsWith("Scav") ) { b.Tag = this.map.ScavengerUnitGroup; } }); } [EventSubscription(EventTopics.OnObjectManagerLoaded, typeof(OnPublisher))] public void HandleObjectManagerLoaded( object sender, EventArgs e) { this.RefreshDroidEditor(); } public void RefreshDroidEditor() { if( App.ObjectData == null ) return; var types = App.TemplateDroidTypes .Select(t => new ListItem { Key = t.TemplateCode, Text = t.Name, Tag = t }) .ToList(); this.ddlType.DataStore = types; bodies = this.ObjectManager.ObjectData.Bodies .Where(b => b.Designable || !this.chkDesignable.Checked.Value) .ToList(); this.ddlBody.DataStore = bodies.Select(b => new ListItem { Key = b.Code, Text = "({0}) {1}".FormatWith(b.Name, b.Code), Tag = b }).ToList(); this.propulsion = this.ObjectManager.ObjectData.Propulsions .Where(p => p.Designable || !this.chkDesignable.Checked.Value).ToList(); ddlProp.DataStore = propulsion.Select(p => new ListItem { Key = p.Code, Text = "({0}) {1}".FormatWith(p.Name, p.Code), Tag = p }).ToList(); this.turrets = this.ObjectManager.ObjectData.Turrets .Where(t => t.Designable || !this.chkDesignable.Checked.Value) .ToList(); var turretItems = this.turrets.Select(t => { var typeName = string.Empty; t.GetTurretTypeName(ref typeName); var l = new ListItem { Key = t.Code, Text = "({0} - {1}) {2}".FormatWith( typeName, t.Name, t.Code), Tag = t }; return l; }).ToList(); this.ddlTurret1.DataStore = turretItems; this.ddlTurret2.DataStore = turretItems; this.ddlTurret3.DataStore = turretItems; } [EventSubscription(EventTopics.OnSelectedObjectChanged, typeof(OnPublisher))] public void SelectedObject_Changed(object sender, EventArgs e) { this.DataContext = this.map; this.OnDataContextChanged(EventArgs.Empty); } void cmdRealign_Click(object sender, EventArgs e) { if( this.map == null ) return; var align = new clsObjectAlignment { Map = this.map }; this.map.SelectedUnits.CopyList().PerformTool(align); this.EventBroker.UpdateMap(this); this.map.UndoStepCreate("Align Objects"); } void cmdFlatten_Click(object sender, EventArgs e) { if( this.map == null ) return; var flatten = new clsObjectFlattenTerrain(); this.map.SelectedUnits.CopyList().PerformTool(flatten); this.EventBroker.UpdateMap(this); this.map.UndoStepCreate("Flatten Under Structures"); } void cmdConvertToDroid_Click(object sender, EventArgs e) { if( this.map == null ) { return; } if( this.map.SelectedUnits.Count <= 0 ) { return; } if( this.map.SelectedUnits.Count > 1 ) { if( MessageBox.Show("Change design of multiple droids?", "", MessageBoxButtons.OKCancel,MessageBoxType.Question) != DialogResult.Ok ) { return; } } else { if( MessageBox.Show("Change design of a droid?", "", MessageBoxButtons.OKCancel, MessageBoxType.Question) != DialogResult.Ok ) { return; } } var ObjectTemplateToDesign = new clsObjectTemplateToDesign(); ObjectTemplateToDesign.Map = this.map; this.map.SelectedUnitsAction(ObjectTemplateToDesign); this.EventBroker.SelectedUnitsChanged(this); if( ObjectTemplateToDesign.ActionPerformed ) { this.map.UndoStepCreate("Object Template Removed"); this.EventBroker.DrawLater(this); } } void txtRotation_ValueChanged(object sender, EventArgs e) { var angleInt = Convert.ToInt32(this.txtRotation.Value); var angle = MathUtil.ClampInt(angleInt, 0, 359); if( this.map.SelectedUnits.Count > 1 ) { if( MessageBox.Show(this, "Change rotation of multiple objects?", MessageBoxButtons.YesNo) != DialogResult.Yes ) { return; } } var objRotation = new clsObjectRotation { Angle = angle, Map = this.map }; this.map.SelectedUnitsAction(objRotation); this.EventBroker.UpdateMap(this); this.EventBroker.SelectedUnitsChanged(this); this.map.UndoStepCreate("Object Rotation"); this.EventBroker.DrawLater(this); } void AnyPlayer_Click(object sender, EventArgs e) { if( this.map == null ) return; this.grpPlayers.DataContext = sender; if( this.map.SelectedUnits.Count <= 0 ) { return; } if( this.grpPlayers.DataContext == null ) { return; } if( this.map.SelectedUnits.Count > 1 ) { if( MessageBox.Show("Change player of multiple objects?", "", MessageBoxButtons.OKCancel) != DialogResult.Ok ) { //SelectedObject_Changed() //todo return; } } var button = sender as Button; var group = button.Tag.To<clsUnitGroup>(); var ObjectUnitGroup = new clsObjectUnitGroup(); ObjectUnitGroup.Map = this.map; ObjectUnitGroup.UnitGroup = group; this.map.SelectedUnitsAction(ObjectUnitGroup); this.EventBroker.SelectedUnitsChanged(this); this.map.UndoStepCreate("Object Player Changed"); if( App.SettingsManager.MinimapTeamColours ) { // Map.MinimapMakeLater(); } this.EventBroker.DrawLater(this); } void AnyPlayer_PreLoad(object sender, EventArgs e) { var button = sender as Button; button.Bind(b => b.Enabled, Binding.Delegate(() => this.grpPlayers.DataContext != button, addChangeEvent: handlerToExecuteWhenSourceChanges => this.grpPlayers.DataContextChanged += handlerToExecuteWhenSourceChanges, removeChangeEvent: handlerToExecuteWhenSourceChanges => this.grpPlayers.DataContextChanged += handlerToExecuteWhenSourceChanges)); button.Bind(b => b.BackgroundColor, Binding.Delegate(() => { if( this.grpPlayers.DataContext == button ) { return Eto.Drawing.Colors.SkyBlue; } return Eto.Drawing.Colors.Transparent; }, addChangeEvent: h => this.grpPlayers.DataContextChanged += h, removeChangeEvent: h => this.grpPlayers.DataContextChanged += h)); } } }
//------------------------------------------------------------------------------ // <license file="Token.cs"> // // The use and distribution terms for this software are contained in the file // named 'LICENSE', which can be found in the resources directory of this // distribution. // // By using this software in any fashion, you are agreeing to be bound by the // terms of this license. // // </license> //------------------------------------------------------------------------------ using System; namespace EcmaScript.NET { /// <summary> This class implements the JavaScript scanner. /// /// It is based on the C source files jsscan.c and jsscan.h /// in the jsref package. /// /// </summary> public class Token { // debug flags internal static readonly bool printTrees = false; // TODO: make me a preprocessor directive internal static readonly bool printICode = false; // TODO: make me a preprocessor directive internal static readonly bool printNames = printTrees || printICode; /// <summary> /// Token types. /// /// These values correspond to JSTokenType values in /// jsscan.c. /// </summary> public const int ERROR = -1; /* well-known as the only code < EOF */ public const int EOF = 0; /* end of file */ public const int EOL = 1; /* end of line */ public const int FIRST_BYTECODE_TOKEN = 2; public const int ENTERWITH = 2; public const int LEAVEWITH = 3; public const int RETURN = 4; public const int GOTO = 5; public const int IFEQ = 6; public const int IFNE = 7; public const int SETNAME = 8; public const int BITOR = 9; public const int BITXOR = 10; public const int BITAND = 11; public const int EQ = 12; public const int NE = 13; public const int LT = 14; public const int LE = 15; public const int GT = 16; public const int GE = 17; public const int LSH = 18; public const int RSH = 19; public const int URSH = 20; public const int ADD = 21; public const int SUB = 22; public const int MUL = 23; public const int DIV = 24; public const int MOD = 25; public const int NOT = 26; public const int BITNOT = 27; public const int POS = 28; public const int NEG = 29; public const int NEW = 30; public const int DELPROP = 31; public const int TYPEOF = 32; public const int GETPROP = 33; public const int SETPROP = 34; public const int GETELEM = 35; public const int SETELEM = 36; public const int CALL = 37; public const int NAME = 38; public const int NUMBER = 39; public const int STRING = 40; public const int NULL = 41; public const int THIS = 42; public const int FALSE = 43; public const int TRUE = 44; public const int SHEQ = 45; public const int SHNE = 46; public const int REGEXP = 47; public const int BINDNAME = 48; public const int THROW = 49; public const int RETHROW = 50; public const int IN = 51; public const int INSTANCEOF = 52; public const int LOCAL_LOAD = 53; public const int GETVAR = 54; public const int SETVAR = 55; public const int CATCH_SCOPE = 56; public const int ENUM_INIT_KEYS = 57; public const int ENUM_INIT_VALUES = 58; public const int ENUM_NEXT = 59; public const int ENUM_ID = 60; public const int THISFN = 61; public const int RETURN_RESULT = 62; public const int ARRAYLIT = 63; public const int OBJECTLIT = 64; public const int GET_REF = 65; public const int SET_REF = 66; public const int DEL_REF = 67; public const int REF_CALL = 68; public const int REF_SPECIAL = 69; public const int DEFAULTNAMESPACE = 70; public const int ESCXMLATTR = 71; public const int ESCXMLTEXT = 72; public const int REF_MEMBER = 73; public const int REF_NS_MEMBER = 74; public const int REF_NAME = 75; public const int REF_NS_NAME = 76; // Reference for ns::y, @ns::y@[y] etc. public const int SETPROP_GETTER = 77; public const int SETPROP_SETTER = 78; // End of interpreter bytecodes public const int LAST_BYTECODE_TOKEN = SETPROP_SETTER; public const int TRY = LAST_BYTECODE_TOKEN + 1; public const int SEMI = LAST_BYTECODE_TOKEN + 2; public const int LB = LAST_BYTECODE_TOKEN + 3; public const int RB = LAST_BYTECODE_TOKEN + 4; public const int LC = LAST_BYTECODE_TOKEN + 5; public const int RC = LAST_BYTECODE_TOKEN + 6; public const int LP = LAST_BYTECODE_TOKEN + 7; public const int RP = LAST_BYTECODE_TOKEN + 8; public const int COMMA = LAST_BYTECODE_TOKEN + 9; public const int ASSIGN = LAST_BYTECODE_TOKEN + 10; public const int ASSIGN_BITOR = LAST_BYTECODE_TOKEN + 11; public const int ASSIGN_BITXOR = LAST_BYTECODE_TOKEN + 12; public const int ASSIGN_BITAND = LAST_BYTECODE_TOKEN + 13; public const int ASSIGN_LSH = LAST_BYTECODE_TOKEN + 14; public const int ASSIGN_RSH = LAST_BYTECODE_TOKEN + 15; public const int ASSIGN_URSH = LAST_BYTECODE_TOKEN + 16; public const int ASSIGN_ADD = LAST_BYTECODE_TOKEN + 17; public const int ASSIGN_SUB = LAST_BYTECODE_TOKEN + 18; public const int ASSIGN_MUL = LAST_BYTECODE_TOKEN + 19; public const int ASSIGN_DIV = LAST_BYTECODE_TOKEN + 20; public const int ASSIGN_MOD = LAST_BYTECODE_TOKEN + 21; // %= public const int FIRST_ASSIGN = ASSIGN; public const int LAST_ASSIGN = ASSIGN_MOD; public const int HOOK = LAST_BYTECODE_TOKEN + 22; public const int COLON = LAST_BYTECODE_TOKEN + 23; public const int OR = LAST_BYTECODE_TOKEN + 24; public const int AND = LAST_BYTECODE_TOKEN + 25; public const int INC = LAST_BYTECODE_TOKEN + 26; public const int DEC = LAST_BYTECODE_TOKEN + 27; public const int DOT = LAST_BYTECODE_TOKEN + 28; public const int FUNCTION = LAST_BYTECODE_TOKEN + 29; public const int EXPORT = LAST_BYTECODE_TOKEN + 30; public const int IMPORT = LAST_BYTECODE_TOKEN + 31; public const int IF = LAST_BYTECODE_TOKEN + 32; public const int ELSE = LAST_BYTECODE_TOKEN + 33; public const int SWITCH = LAST_BYTECODE_TOKEN + 34; public const int CASE = LAST_BYTECODE_TOKEN + 35; public const int DEFAULT = LAST_BYTECODE_TOKEN + 36; public const int WHILE = LAST_BYTECODE_TOKEN + 37; public const int DO = LAST_BYTECODE_TOKEN + 38; public const int FOR = LAST_BYTECODE_TOKEN + 39; public const int BREAK = LAST_BYTECODE_TOKEN + 40; public const int CONTINUE = LAST_BYTECODE_TOKEN + 41; public const int VAR = LAST_BYTECODE_TOKEN + 42; public const int WITH = LAST_BYTECODE_TOKEN + 43; public const int CATCH = LAST_BYTECODE_TOKEN + 44; public const int FINALLY = LAST_BYTECODE_TOKEN + 45; public const int VOID = LAST_BYTECODE_TOKEN + 46; public const int RESERVED = LAST_BYTECODE_TOKEN + 47; public const int EMPTY = LAST_BYTECODE_TOKEN + 48; public const int BLOCK = LAST_BYTECODE_TOKEN + 49; public const int LABEL = LAST_BYTECODE_TOKEN + 50; public const int TARGET = LAST_BYTECODE_TOKEN + 51; public const int LOOP = LAST_BYTECODE_TOKEN + 52; public const int EXPR_VOID = LAST_BYTECODE_TOKEN + 53; public const int EXPR_RESULT = LAST_BYTECODE_TOKEN + 54; public const int JSR = LAST_BYTECODE_TOKEN + 55; public const int SCRIPT = LAST_BYTECODE_TOKEN + 56; public const int TYPEOFNAME = LAST_BYTECODE_TOKEN + 57; public const int USE_STACK = LAST_BYTECODE_TOKEN + 58; public const int SETPROP_OP = LAST_BYTECODE_TOKEN + 59; public const int SETELEM_OP = LAST_BYTECODE_TOKEN + 60; public const int LOCAL_BLOCK = LAST_BYTECODE_TOKEN + 61; public const int SET_REF_OP = LAST_BYTECODE_TOKEN + 62; public const int DOTDOT = LAST_BYTECODE_TOKEN + 63; public const int COLONCOLON = LAST_BYTECODE_TOKEN + 64; public const int XML = LAST_BYTECODE_TOKEN + 65; public const int DOTQUERY = LAST_BYTECODE_TOKEN + 66; public const int XMLATTR = LAST_BYTECODE_TOKEN + 67; public const int XMLEND = LAST_BYTECODE_TOKEN + 68; public const int TO_OBJECT = LAST_BYTECODE_TOKEN + 69; public const int TO_DOUBLE = LAST_BYTECODE_TOKEN + 70; public const int GET = LAST_BYTECODE_TOKEN + 71; // JS 1.5 get pseudo keyword public const int SET = LAST_BYTECODE_TOKEN + 72; // JS 1.5 set pseudo keyword public const int CONST = LAST_BYTECODE_TOKEN + 73; public const int SETCONST = LAST_BYTECODE_TOKEN + 74; public const int SETCONSTVAR = LAST_BYTECODE_TOKEN + 75; public const int CONDCOMMENT = LAST_BYTECODE_TOKEN + 76; // JScript conditional comment public const int KEEPCOMMENT = LAST_BYTECODE_TOKEN + 77; // /*! ... */ comment public const int DEBUGGER = LAST_BYTECODE_TOKEN + 78; public const int LAST_TOKEN = LAST_BYTECODE_TOKEN + 79; public static string name (int token) { //if (!printNames) { // return Convert.ToString (token); //} switch (token) { case ERROR: return "ERROR"; case EOF: return "EOF"; case EOL: return "EOL"; case ENTERWITH: return "ENTERWITH"; case LEAVEWITH: return "LEAVEWITH"; case RETURN: return "RETURN"; case GOTO: return "GOTO"; case IFEQ: return "IFEQ"; case IFNE: return "IFNE"; case SETNAME: return "SETNAME"; case BITOR: return "BITOR"; case BITXOR: return "BITXOR"; case BITAND: return "BITAND"; case EQ: return "EQ"; case NE: return "NE"; case LT: return "LT"; case LE: return "LE"; case GT: return "GT"; case GE: return "GE"; case LSH: return "LSH"; case RSH: return "RSH"; case URSH: return "URSH"; case ADD: return "ADD"; case SUB: return "SUB"; case MUL: return "MUL"; case DIV: return "DIV"; case MOD: return "MOD"; case NOT: return "NOT"; case BITNOT: return "BITNOT"; case POS: return "POS"; case NEG: return "NEG"; case NEW: return "NEW"; case DELPROP: return "DELPROP"; case TYPEOF: return "TYPEOF"; case GETPROP: return "GETPROP"; case SETPROP: return "SETPROP"; case GETELEM: return "GETELEM"; case SETELEM: return "SETELEM"; case CALL: return "CALL"; case NAME: return "NAME"; case NUMBER: return "NUMBER"; case STRING: return "STRING"; case NULL: return "NULL"; case THIS: return "THIS"; case FALSE: return "FALSE"; case TRUE: return "TRUE"; case SHEQ: return "SHEQ"; case SHNE: return "SHNE"; case REGEXP: return "OBJECT"; case BINDNAME: return "BINDNAME"; case THROW: return "THROW"; case RETHROW: return "RETHROW"; case IN: return "IN"; case INSTANCEOF: return "INSTANCEOF"; case LOCAL_LOAD: return "LOCAL_LOAD"; case GETVAR: return "GETVAR"; case SETVAR: return "SETVAR"; case CATCH_SCOPE: return "CATCH_SCOPE"; case ENUM_INIT_KEYS: return "ENUM_INIT_KEYS"; case ENUM_INIT_VALUES: return "ENUM_INIT_VALUES"; case ENUM_NEXT: return "ENUM_NEXT"; case ENUM_ID: return "ENUM_ID"; case THISFN: return "THISFN"; case RETURN_RESULT: return "RETURN_RESULT"; case ARRAYLIT: return "ARRAYLIT"; case OBJECTLIT: return "OBJECTLIT"; case GET_REF: return "GET_REF"; case SET_REF: return "SET_REF"; case DEL_REF: return "DEL_REF"; case REF_CALL: return "REF_CALL"; case REF_SPECIAL: return "REF_SPECIAL"; case DEFAULTNAMESPACE: return "DEFAULTNAMESPACE"; case ESCXMLTEXT: return "ESCXMLTEXT"; case ESCXMLATTR: return "ESCXMLATTR"; case REF_MEMBER: return "REF_MEMBER"; case REF_NS_MEMBER: return "REF_NS_MEMBER"; case REF_NAME: return "REF_NAME"; case REF_NS_NAME: return "REF_NS_NAME"; case TRY: return "TRY"; case SEMI: return "SEMI"; case LB: return "LB"; case RB: return "RB"; case LC: return "LC"; case RC: return "RC"; case LP: return "LP"; case RP: return "RP"; case COMMA: return "COMMA"; case ASSIGN: return "ASSIGN"; case ASSIGN_BITOR: return "ASSIGN_BITOR"; case ASSIGN_BITXOR: return "ASSIGN_BITXOR"; case ASSIGN_BITAND: return "ASSIGN_BITAND"; case ASSIGN_LSH: return "ASSIGN_LSH"; case ASSIGN_RSH: return "ASSIGN_RSH"; case ASSIGN_URSH: return "ASSIGN_URSH"; case ASSIGN_ADD: return "ASSIGN_ADD"; case ASSIGN_SUB: return "ASSIGN_SUB"; case ASSIGN_MUL: return "ASSIGN_MUL"; case ASSIGN_DIV: return "ASSIGN_DIV"; case ASSIGN_MOD: return "ASSIGN_MOD"; case HOOK: return "HOOK"; case COLON: return "COLON"; case OR: return "OR"; case AND: return "AND"; case INC: return "INC"; case DEC: return "DEC"; case DOT: return "DOT"; case FUNCTION: return "FUNCTION"; case EXPORT: return "EXPORT"; case IMPORT: return "IMPORT"; case IF: return "IF"; case ELSE: return "ELSE"; case SWITCH: return "SWITCH"; case CASE: return "CASE"; case DEFAULT: return "DEFAULT"; case WHILE: return "WHILE"; case DO: return "DO"; case FOR: return "FOR"; case BREAK: return "BREAK"; case CONTINUE: return "CONTINUE"; case VAR: return "VAR"; case WITH: return "WITH"; case CATCH: return "CATCH"; case FINALLY: return "FINALLY"; case RESERVED: return "RESERVED"; case EMPTY: return "EMPTY"; case BLOCK: return "BLOCK"; case LABEL: return "LABEL"; case TARGET: return "TARGET"; case LOOP: return "LOOP"; case EXPR_VOID: return "EXPR_VOID"; case EXPR_RESULT: return "EXPR_RESULT"; case JSR: return "JSR"; case SCRIPT: return "SCRIPT"; case TYPEOFNAME: return "TYPEOFNAME"; case USE_STACK: return "USE_STACK"; case SETPROP_OP: return "SETPROP_OP"; case SETELEM_OP: return "SETELEM_OP"; case LOCAL_BLOCK: return "LOCAL_BLOCK"; case SET_REF_OP: return "SET_REF_OP"; case DOTDOT: return "DOTDOT"; case COLONCOLON: return "COLONCOLON"; case XML: return "XML"; case DOTQUERY: return "DOTQUERY"; case XMLATTR: return "XMLATTR"; case XMLEND: return "XMLEND"; case TO_OBJECT: return "TO_OBJECT"; case TO_DOUBLE: return "TO_DOUBLE"; case GET: return "GET"; case SET: return "SET"; case CONST: return "CONST"; case SETCONST: return "SETCONST"; case SETCONSTVAR: return "SETCONSTVAR"; case CONDCOMMENT: return "CONDCOMMENT"; case KEEPCOMMENT: return "KEEPCOMMENT"; case DEBUGGER: return "DEBUGGER"; default: return "UNKNOWN Token Type"; } // Token without name throw new ApplicationException ("Unknown token: " + Convert.ToString (token)); } } }
// 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. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Dynamic; using System.Linq.Expressions; using System.Reflection; using Microsoft.Scripting.Generation; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; using AstUtils = Microsoft.Scripting.Ast.Utils; namespace Microsoft.Scripting.Actions.Calls { /// <summary> /// MethodCandidate represents the different possible ways of calling a method or a set of method overloads. /// A single method can result in multiple MethodCandidates. Some reasons include: /// - Every optional parameter or parameter with a default value will result in a candidate /// - The presence of ref and out parameters will add a candidate for languages which want to return the updated values as return values. /// - ArgumentKind.List and ArgumentKind.Dictionary can result in a new candidate per invocation since the list might be different every time. /// /// Each MethodCandidate represents the parameter type for the candidate using ParameterWrapper. /// </summary> public sealed class MethodCandidate { private readonly List<ParameterWrapper> _parameters; private readonly ParameterWrapper _paramsDict; private readonly InstanceBuilder _instanceBuilder; internal MethodCandidate(OverloadResolver resolver, OverloadInfo method, List<ParameterWrapper> parameters, ParameterWrapper paramsDict, ReturnBuilder returnBuilder, InstanceBuilder instanceBuilder, IList<ArgBuilder> argBuilders, Dictionary<DynamicMetaObject, BindingRestrictions> restrictions) { Assert.NotNull(resolver, method, instanceBuilder, returnBuilder); Assert.NotNullItems(parameters); Assert.NotNullItems(argBuilders); Resolver = resolver; Overload = method; _instanceBuilder = instanceBuilder; ArgBuilders = argBuilders; ReturnBuilder = returnBuilder; _parameters = parameters; _paramsDict = paramsDict; Restrictions = restrictions; ParamsArrayIndex = ParameterWrapper.IndexOfParamsArray(parameters); parameters.TrimExcess(); } internal MethodCandidate ReplaceMethod(OverloadInfo newMethod, List<ParameterWrapper> parameters, IList<ArgBuilder> argBuilders, Dictionary<DynamicMetaObject, BindingRestrictions> restrictions) { return new MethodCandidate(Resolver, newMethod, parameters, _paramsDict, ReturnBuilder, _instanceBuilder, argBuilders, restrictions); } internal ReturnBuilder ReturnBuilder { get; } internal IList<ArgBuilder> ArgBuilders { get; } public OverloadResolver Resolver { get; } [Obsolete("Use Overload instead")] public MethodBase Method => Overload.ReflectionInfo; public OverloadInfo Overload { get; } internal Dictionary<DynamicMetaObject, BindingRestrictions> Restrictions { get; } public Type ReturnType => ReturnBuilder.ReturnType; public int ParamsArrayIndex { get; } public bool HasParamsArray => ParamsArrayIndex != -1; public bool HasParamsDictionary => _paramsDict != null; public ActionBinder Binder => Resolver.Binder; internal ParameterWrapper GetParameter(int argumentIndex, ArgumentBinding namesBinding) { return _parameters[namesBinding.ArgumentToParameter(argumentIndex)]; } internal ParameterWrapper GetParameter(int parameterIndex) { return _parameters[parameterIndex]; } internal int ParameterCount => _parameters.Count; internal int IndexOfParameter(string name) { for (int i = 0; i < _parameters.Count; i++) { if (_parameters[i].Name == name) { return i; } } return -1; } internal int PositionOfParameter(string name) { for (int i = 0, p = 1; i < _parameters.Count; i++) { var parameter = _parameters[i]; if (parameter.IsHidden) { if (parameter.Name == name) { return 0; } } else { if (parameter.Name == name) { return p; } p++; } } return -1; } public int GetVisibleParameterCount() { int result = 0; foreach (var parameter in _parameters) { if (!parameter.IsHidden) { result++; } } return result; } public IList<ParameterWrapper> GetParameters() { return new ReadOnlyCollection<ParameterWrapper>(_parameters); } /// <summary> /// Builds a new MethodCandidate which takes count arguments and the provided list of keyword arguments. /// /// The basic idea here is to figure out which parameters map to params or a dictionary params and /// fill in those spots w/ extra ParameterWrapper's. /// </summary> internal MethodCandidate MakeParamsExtended(int count, IList<string> names) { Debug.Assert(Overload.IsVariadic); List<ParameterWrapper> newParameters = new List<ParameterWrapper>(count); // keep track of which named args map to a real argument, and which ones // map to the params dictionary. List<string> unusedNames = new List<string>(names); List<int> unusedNameIndexes = new List<int>(); for (int i = 0; i < unusedNames.Count; i++) { unusedNameIndexes.Add(i); } // if we don't have a param array we'll have a param dict which is type object ParameterWrapper paramsArrayParameter = null; int paramsArrayIndex = -1; for (int i = 0; i < _parameters.Count; i++) { ParameterWrapper parameter = _parameters[i]; if (parameter.IsParamsArray) { paramsArrayParameter = parameter; paramsArrayIndex = i; } else { int j = unusedNames.IndexOf(parameter.Name); if (j != -1) { unusedNames.RemoveAt(j); unusedNameIndexes.RemoveAt(j); } newParameters.Add(parameter); } } if (paramsArrayIndex != -1) { ParameterWrapper expanded = paramsArrayParameter.Expand(); while (newParameters.Count < (count - unusedNames.Count)) { newParameters.Insert(System.Math.Min(paramsArrayIndex, newParameters.Count), expanded); } } if (_paramsDict != null) { var flags = (Overload.ProhibitsNullItems(_paramsDict.ParameterInfo.Position) ? ParameterBindingFlags.ProhibitNull : 0) | (_paramsDict.IsHidden ? ParameterBindingFlags.IsHidden : 0); foreach (string name in unusedNames) { newParameters.Add(new ParameterWrapper(_paramsDict.ParameterInfo, typeof(object), name, flags)); } } else if (unusedNames.Count != 0) { // unbound kw args and no where to put them, can't call... // TODO: We could do better here because this results in an incorrect arg # error message. return null; } // if we have too many or too few args we also can't call if (count != newParameters.Count) { return null; } return MakeParamsExtended(unusedNames.ToArray(), unusedNameIndexes.ToArray(), newParameters); } private MethodCandidate MakeParamsExtended(string[] names, int[] nameIndices, List<ParameterWrapper> parameters) { Debug.Assert(Overload.IsVariadic); List<ArgBuilder> newArgBuilders = new List<ArgBuilder>(ArgBuilders.Count); // current argument that we consume, initially skip this if we have it. int curArg = Overload.IsStatic ? 0 : 1; int kwIndex = -1; ArgBuilder paramsDictBuilder = null; foreach (ArgBuilder ab in ArgBuilders) { // TODO: define a virtual method on ArgBuilder implementing this functionality: if (ab is SimpleArgBuilder sab) { // we consume one or more incoming argument(s) if (sab.IsParamsArray) { // consume all the extra arguments int paramsUsed = parameters.Count - GetConsumedArguments() - names.Length + (Overload.IsStatic ? 1 : 0); newArgBuilders.Add(new ParamsArgBuilder( sab.ParameterInfo, sab.Type.GetElementType(), curArg, paramsUsed )); curArg += paramsUsed; } else if (sab.IsParamsDict) { // consume all the kw arguments kwIndex = newArgBuilders.Count; paramsDictBuilder = sab; } else { // consume the argument, adjust its position: newArgBuilders.Add(sab.MakeCopy(curArg++)); } } else if (ab is KeywordArgBuilder) { newArgBuilders.Add(ab); curArg++; } else { // CodeContext, null, default, etc... we don't consume an // actual incoming argument. newArgBuilders.Add(ab); } } if (kwIndex != -1) { newArgBuilders.Insert(kwIndex, new ParamsDictArgBuilder(paramsDictBuilder.ParameterInfo, curArg, names, nameIndices)); } return new MethodCandidate(Resolver, Overload, parameters, null, ReturnBuilder, _instanceBuilder, newArgBuilders, null); } private int GetConsumedArguments() { int consuming = 0; foreach (ArgBuilder argb in ArgBuilders) { if (argb is SimpleArgBuilder sab && !sab.IsParamsDict || argb is KeywordArgBuilder) { consuming++; } } return consuming; } public Type[] GetParameterTypes() { List<Type> res = new List<Type>(ArgBuilders.Count); for (int i = 0; i < ArgBuilders.Count; i++) { Type t = ArgBuilders[i].Type; if (t != null) { res.Add(t); } } return res.ToArray(); } #region MakeExpression internal Expression MakeExpression(RestrictedArguments restrictedArgs) { Expression[] callArgs = GetArgumentExpressions(restrictedArgs, out bool[] usageMarkers, out Expression[] spilledArgs); Expression call; MethodBase mb = Overload.ReflectionInfo; // TODO: make MakeExpression virtual on OverloadInfo? if (mb == null) { throw new InvalidOperationException("Cannot generate an expression for an overload w/o MethodBase"); } MethodInfo mi = mb as MethodInfo; if (mi != null) { Expression instance; if (mi.IsStatic) { instance = null; } else { Debug.Assert(mi != null); instance = _instanceBuilder.ToExpression(ref mi, Resolver, restrictedArgs, usageMarkers); Debug.Assert(instance != null, "Can't skip instance expression"); } if (CompilerHelpers.IsVisible(mi)) { call = AstUtils.SimpleCallHelper(instance, mi, callArgs); } else { call = Expression.Call( typeof(BinderOps).GetMethod(nameof(BinderOps.InvokeMethod)), AstUtils.Constant(mi), instance != null ? AstUtils.Convert(instance, typeof(object)) : AstUtils.Constant(null), AstUtils.NewArrayHelper(typeof(object), callArgs) ); } } else { ConstructorInfo ci = (ConstructorInfo)mb; if (CompilerHelpers.IsVisible(ci)) { call = AstUtils.SimpleNewHelper(ci, callArgs); } else { call = Expression.Call( typeof(BinderOps).GetMethod(nameof(BinderOps.InvokeConstructor)), AstUtils.Constant(ci), AstUtils.NewArrayHelper(typeof(object), callArgs) ); } } if (spilledArgs != null) { call = Expression.Block(spilledArgs.AddLast(call)); } Expression ret = ReturnBuilder.ToExpression(Resolver, ArgBuilders, restrictedArgs, call); List<Expression> updates = null; for (int i = 0; i < ArgBuilders.Count; i++) { Expression next = ArgBuilders[i].UpdateFromReturn(Resolver, restrictedArgs); if (next != null) { if (updates == null) { updates = new List<Expression>(); } updates.Add(next); } } if (updates != null) { if (ret.Type != typeof(void)) { ParameterExpression temp = Expression.Variable(ret.Type, "$ret"); updates.Insert(0, Expression.Assign(temp, ret)); updates.Add(temp); ret = Expression.Block(new[] { temp }, updates.ToArray()); } else { updates.Insert(0, ret); ret = Expression.Block(typeof(void), updates.ToArray()); } } if (Resolver.Temps != null) { ret = Expression.Block(Resolver.Temps, ret); } return ret; } private Expression[] GetArgumentExpressions(RestrictedArguments restrictedArgs, out bool[] usageMarkers, out Expression[] spilledArgs) { int minPriority = int.MaxValue; int maxPriority = int.MinValue; foreach (ArgBuilder ab in ArgBuilders) { minPriority = Math.Min(minPriority, ab.Priority); maxPriority = Math.Max(maxPriority, ab.Priority); } var args = new Expression[ArgBuilders.Count]; Expression[] actualArgs = null; usageMarkers = new bool[restrictedArgs.Length]; for (int priority = minPriority; priority <= maxPriority; priority++) { for (int i = 0; i < ArgBuilders.Count; i++) { if (ArgBuilders[i].Priority == priority) { args[i] = ArgBuilders[i].ToExpression(Resolver, restrictedArgs, usageMarkers); // see if this has a temp that needs to be passed as the actual argument Expression byref = ArgBuilders[i].ByRefArgument; if (byref != null) { if (actualArgs == null) { actualArgs = new Expression[ArgBuilders.Count]; } actualArgs[i] = byref; } } } } if (actualArgs != null) { for (int i = 0; i < args.Length; i++) { if (args[i] != null && actualArgs[i] == null) { actualArgs[i] = Resolver.GetTemporary(args[i].Type, null); args[i] = Expression.Assign(actualArgs[i], args[i]); } } spilledArgs = RemoveNulls(args); return RemoveNulls(actualArgs); } spilledArgs = null; return RemoveNulls(args); } private static Expression[] RemoveNulls(Expression[] args) { int newLength = args.Length; for (int i = 0; i < args.Length; i++) { if (args[i] == null) { newLength--; } } var result = new Expression[newLength]; for (int i = 0, j = 0; i < args.Length; i++) { if (args[i] != null) { result[j++] = args[i]; } } return result; } #endregion public override string ToString() { return $"MethodCandidate({Overload.ReflectionInfo} on {Overload.DeclaringType.FullName})"; } } }
// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.TextManager.Interop; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Designer.Interfaces; using Microsoft.VisualStudio.Shell; using Microsoft.Win32; using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Data; using System.Diagnostics; using System.Runtime.InteropServices; using System.Windows.Forms; using Microsoft.VisualStudio; using System.Globalization; using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; using IServiceProvider = System.IServiceProvider; namespace Microsoft.VisualStudio.FSharp.LanguageService { internal enum IndentingStyle { None, Block, Smart } /// <summary> /// LanguagePreferences encapsulates the standard General and Tab settings for a language service /// and provides a way of getting and setting the values. It is expected that you /// will have one global LanguagePreferences created by your package. The General and Tabs /// settings are automatically persisted in .vssettings files by the core editor package. /// All you need to do is register your language under AutomationProperties/TextEditor /// and specify: /// <code> /// YourLanguage = s '%YourLocalizedName%' /// { /// val Name = s 'YourLanguage' /// val Package = s '{F5E7E720-1401-11D1-883B-0000F87579D2}' /// val ProfileSave = d 1 /// val ResourcePackage = s '%YourPackage%' /// } /// </code> /// Therefore this class hides all it's properties from user setting persistence using /// DesignerSerializationVisibility.Hidden. This is so that if you give this object /// to the Package.ExportSettings method as the AutomationObject then it will only /// write out your new settings which is what you want, otherwise the General and Tab /// settings will appear in two places in the .vsssettings file. /// </summary> [CLSCompliant(false), ComVisible(true), Guid("934a92fd-b63a-49c7-9284-11aec8c1e03f")] public class LanguagePreferences : IVsTextManagerEvents2, IDisposable { IServiceProvider site; Guid langSvc; LANGPREFERENCES2 prefs; NativeMethods.ConnectionPointCookie connection; bool enableCodeSense; bool enableMatchBraces; bool enableQuickInfo; bool enableShowMatchingBrace; bool enableMatchBracesAtCaret; bool enableFormatSelection; bool enableCommenting; int maxErrorMessages; int codeSenseDelay; bool enableAsyncCompletion; bool autoOutlining; int maxRegionTime; _HighlightMatchingBraceFlags braceFlags; string name; /// <summary> /// Gets the language preferences. /// </summary> internal LanguagePreferences(IServiceProvider site, Guid langSvc, string name) { this.site = site; this.langSvc = langSvc; this.name = name; } internal LanguagePreferences() { } protected string LanguageName { get { return this.name; } set { this.name = value; } } /// <summary> /// This property is not public for a reason. If it were public it would /// get called during LoadSettingsFromStorage which will break it. /// Instead use GetSite(). /// </summary> protected IServiceProvider Site { get { return this.site; } set { this.site = value; } } public IServiceProvider GetSite() { return this.site; } // Our base language service perferences (from Babel originally) [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool EnableCodeSense { get { return this.enableCodeSense; } set { this.enableCodeSense = value; } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool EnableMatchBraces { get { return this.enableMatchBraces; } set { this.enableMatchBraces = value; } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool EnableQuickInfo { get { return this.enableQuickInfo; } set { this.enableQuickInfo = value; } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool EnableShowMatchingBrace { get { return this.enableShowMatchingBrace; } set { this.enableShowMatchingBrace = value; } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool EnableMatchBracesAtCaret { get { return this.enableMatchBracesAtCaret; } set { this.enableMatchBracesAtCaret = value; } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public int MaxErrorMessages { get { return this.maxErrorMessages; } set { this.maxErrorMessages = value; } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public int CodeSenseDelay { get { return this.codeSenseDelay; } set { this.codeSenseDelay = value; } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool EnableAsyncCompletion { get { return this.enableAsyncCompletion; } set { this.enableAsyncCompletion = value; } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool EnableFormatSelection { get { return this.enableFormatSelection; } set { this.enableFormatSelection = value; } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool EnableCommenting { get { return this.enableCommenting; } set { this.enableCommenting = value; } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public int MaxRegionTime { get { return this.maxRegionTime; } set { this.maxRegionTime = value; } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public _HighlightMatchingBraceFlags HighlightMatchingBraceFlags { get { return this.braceFlags; } set { this.braceFlags = value; } } public virtual void Init() { ILocalRegistry3 localRegistry = site.GetService(typeof(SLocalRegistry)) as ILocalRegistry3; string root = null; if (localRegistry != null) { NativeMethods.ThrowOnFailure(localRegistry.GetLocalRegistryRoot(out root)); } if (root != null) { using (RegistryKey key = Registry.LocalMachine.OpenSubKey(root, false)) { if (key != null) { InitMachinePreferences(key, name); } } using (RegistryKey key = Registry.CurrentUser.OpenSubKey(root, false)) { if (key != null) { InitUserPreferences(key, name); } } } Connect(); localRegistry = null; } public virtual void InitUserPreferences(RegistryKey key, string name) { this.GetLanguagePreferences(); } public int GetIntegerValue(RegistryKey key, string name, int def) { object o = key.GetValue(name); if (o is int) return (int)o; if (o is string) return int.Parse((string)o, CultureInfo.InvariantCulture); return def; } public bool GetBooleanValue(RegistryKey key, string name, bool def) { object o = key.GetValue(name); if (o is int) return ((int)o != 0); if (o is string) return bool.Parse((string)o); return def; } public virtual void InitMachinePreferences(RegistryKey key, string name) { using (RegistryKey keyLanguage = key.OpenSubKey("languages\\language services\\" + name, false)) { if (keyLanguage != null) { this.EnableCodeSense = GetBooleanValue(keyLanguage, "CodeSense", true); this.EnableMatchBraces = GetBooleanValue(keyLanguage, "MatchBraces", true); this.EnableQuickInfo = GetBooleanValue(keyLanguage, "QuickInfo", true); this.EnableShowMatchingBrace = GetBooleanValue(keyLanguage, "ShowMatchingBrace", true); this.EnableMatchBracesAtCaret = GetBooleanValue(keyLanguage, "MatchBracesAtCaret", true); this.MaxErrorMessages = GetIntegerValue(keyLanguage, "MaxErrorMessages", 10); this.CodeSenseDelay = GetIntegerValue(keyLanguage, "CodeSenseDelay", 1000); this.EnableAsyncCompletion = GetBooleanValue(keyLanguage, "EnableAsyncCompletion", true); this.EnableFormatSelection = GetBooleanValue(keyLanguage, "EnableFormatSelection", false); this.EnableCommenting = GetBooleanValue(keyLanguage, "EnableCommenting", true); this.AutoOutlining = GetBooleanValue(keyLanguage, "AutoOutlining", true); this.MaxRegionTime = GetIntegerValue(keyLanguage, "MaxRegionTime", 2000); // 2 seconds this.braceFlags = (_HighlightMatchingBraceFlags)GetIntegerValue(keyLanguage, "HighlightMatchingBraceFlags", (int)_HighlightMatchingBraceFlags.HMB_USERECTANGLEBRACES); } } } public virtual void Dispose() { Disconnect(); site = null; } // General tab [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool AutoListMembers { get { return prefs.fAutoListMembers != 0; } set { prefs.fAutoListMembers = (uint)(value ? 1 : 0); } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool HideAdvancedMembers { get { return prefs.fHideAdvancedAutoListMembers != 0; } set { prefs.fHideAdvancedAutoListMembers = (uint)(value ? 1 : 0); } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool ParameterInformation { get { return prefs.fAutoListParams != 0; } set { prefs.fAutoListParams = (uint)(value ? 1 : 0); } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool VirtualSpace { get { return prefs.fVirtualSpace != 0; } set { prefs.fVirtualSpace = (uint)(value ? 1 : 0); } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool WordWrap { get { return prefs.fWordWrap != 0; } set { prefs.fWordWrap = (uint)(value ? 1 : 0); } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool WordWrapGlyphs { get { return (int)prefs.fWordWrapGlyphs != 0; } set { prefs.fWordWrapGlyphs = (uint)(value ? 1 : 0); } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool CutCopyBlankLines { get { return (int)prefs.fCutCopyBlanks != 0; } set { prefs.fCutCopyBlanks = (uint)(value ? 1 : 0); } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool LineNumbers { get { return prefs.fLineNumbers != 0; } set { prefs.fLineNumbers = (uint)(value ? 1 : 0); } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool EnableLeftClickForURLs { get { return prefs.fHotURLs != 0; } set { prefs.fHotURLs = (uint)(value ? 1 : 0); } } // Tabs tab [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] internal IndentingStyle IndentStyle { get { return (IndentingStyle)prefs.IndentStyle; } set { prefs.IndentStyle = (vsIndentStyle)value; } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public int TabSize { get { return (int)prefs.uTabSize; } set { prefs.uTabSize = (uint)value; } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public int IndentSize { get { return (int)prefs.uIndentSize; } set { prefs.uIndentSize = (uint)value; } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool InsertTabs { get { return prefs.fInsertTabs != 0; } set { prefs.fInsertTabs = (uint)(value ? 1 : 0); } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool ShowNavigationBar { get { return (int)prefs.fDropdownBar != 0; } set { prefs.fDropdownBar = (uint)(value ? 1 : 0); } } public bool AutoOutlining { get { return this.autoOutlining; } set { this.autoOutlining = value; } } public virtual void GetLanguagePreferences() { IVsTextManager textMgr = site.GetService(typeof(SVsTextManager)) as IVsTextManager; if (textMgr != null) { this.prefs.guidLang = langSvc; IVsTextManager2 textMgr2 = site.GetService(typeof(SVsTextManager)) as IVsTextManager2; if (textMgr2 != null) { LANGPREFERENCES2[] langPrefs2 = new LANGPREFERENCES2[1]; langPrefs2[0] = this.prefs; if (NativeMethods.Succeeded(textMgr2.GetUserPreferences2(null, null, langPrefs2, null))) { this.prefs = langPrefs2[0]; } else { Debug.Assert(false, "textMgr2.GetUserPreferences2"); } } } } public virtual void Apply() { IVsTextManager2 textMgr2 = site.GetService(typeof(SVsTextManager)) as IVsTextManager2; if (textMgr2 != null) { this.prefs.guidLang = langSvc; LANGPREFERENCES2[] langPrefs2 = new LANGPREFERENCES2[1]; langPrefs2[0] = this.prefs; if (!NativeMethods.Succeeded(textMgr2.SetUserPreferences2(null, null, langPrefs2, null))) { Debug.Assert(false, "textMgr2.SetUserPreferences2"); } } } private void Connect() { if (this.connection == null && this.site != null) { IVsTextManager2 textMgr2 = this.site.GetService(typeof(SVsTextManager)) as IVsTextManager2; if (textMgr2 != null) { this.connection = new NativeMethods.ConnectionPointCookie(textMgr2, (IVsTextManagerEvents2)this, typeof(IVsTextManagerEvents2)); } } } private void Disconnect() { if (this.connection != null) { this.connection.Dispose(); this.connection = null; } } public virtual int OnRegisterMarkerType(int iMarkerType) { return NativeMethods.S_OK; } public virtual int OnRegisterView(IVsTextView view) { return NativeMethods.S_OK; } public virtual int OnUnregisterView(IVsTextView view) { return NativeMethods.S_OK; } public virtual int OnReplaceAllInFilesBegin() { return NativeMethods.S_OK; } public virtual int OnReplaceAllInFilesEnd() { return NativeMethods.S_OK; } public virtual int OnUserPreferencesChanged2(VIEWPREFERENCES2[] viewPrefs, FRAMEPREFERENCES2[] framePrefs, LANGPREFERENCES2[] langPrefs, FONTCOLORPREFERENCES2[] fontColorPrefs) { if (langPrefs != null && langPrefs.Length > 0 && langPrefs[0].guidLang == this.langSvc) { this.prefs = langPrefs[0]; } return NativeMethods.S_OK; } } }
using System; using System.Text; namespace Eflat { public class CTranspiler { /// <summary> /// Our reference to the syntax tree. /// </summary> private readonly SyntaxTree Ast; /// <summary> /// The string that contains the output C code. /// </summary> private readonly StringBuilder Output; /// <summary> /// The number of indents we are currently outputting. /// </summary> private int IndentLevel; public CTranspiler(SyntaxTree ast) { Ast = ast; Output = new StringBuilder(); IndentLevel = 0; } /// <summary> /// Transpile the Ast into C code. /// </summary> public string Transpile() { foreach (FuncDecl func in Ast.Functions) { WriteFunction(func); } return Output.ToString(); } /// <summary> /// Write a function to the output. /// </summary> private void WriteFunction(FuncDecl func) { WriteType(func.ReturnType); Output.Append(' '); Output.Append(func.Name); // Output parameters. Output.Append('('); for (int i = 0; i < func.Parameters.Count; i++) { DefineNode param = func.Parameters[i]; WriteType(param.Type); Output.Append(' '); Output.Append(param.Identifier.String); if (i != func.Parameters.Count - 1) { Output.Append(", "); } } Output.Append(')'); Output.Append(' '); Output.Append('{'); IndentLevel += 1; Output.Append('\n'); foreach (Statement stmt in func.Scope.Statements) { Indent(); WriteStatement(stmt); Output.Append('\n'); } IndentLevel -= 1; Output.Append('}'); } private void Indent() { for (int i = 0; i < IndentLevel; i++) { Output.Append(" "); } } /// <summary> /// Write a statement to the Ouptut. /// </summary> /// <param name="stmt"></param> private void WriteStatement(Statement stmt) { switch (stmt) { case DefineStatement defstmt: WriteDefineStatement(defstmt); break; case WhileStatement whilestmt: WriteWhileStatement(whilestmt); break; case IfStatement ifstmt: WriteIfStatement(ifstmt); break; case StatementList stmtlist: WriteStatementList(stmtlist); break; default: throw new NotImplementedException(); } } private void WriteIfStatement(IfStatement ifstmt) { Output.Append("if"); Output.Append(' '); // Output condition: Output.Append('('); WriteExpression(ifstmt.Condition); Output.Append(')'); Output.Append(' '); // Output ifTrue statement: WriteStatement(ifstmt.IfTrue.Statement); // Output the ifFalse statement if it exists. ifstmt.IfFalse.IfSome((scopedStatement) => { Output.Append(' '); Output.Append("else"); Output.Append(' '); WriteStatement(scopedStatement.Statement); }); } private void WriteStatementList(StatementList stmtlist) { Output.Append('{'); Output.Append('\n'); IndentLevel += 1; foreach (Statement stmt in stmtlist.Scope.Statements) { Indent(); WriteStatement(stmt); Output.Append('\n'); } IndentLevel -= 1; Indent(); Output.Append('}'); } private void WriteWhileStatement(WhileStatement whilestmt) { Output.Append("while"); Output.Append(' '); // Output condition: Output.Append('('); WriteExpression(whilestmt.Condition); Output.Append(')'); Output.Append(' '); // Output statement: WriteStatement(whilestmt.WhileTrue.Statement); } /// <summary> /// Write a Define statement. /// </summary> /// <param name="defstmt"></param> private void WriteDefineStatement(DefineStatement defstmt) { WriteType(defstmt.Define.Type); Output.Append(" "); Output.Append(defstmt.Define.Identifier.String); defstmt.InitialValue.IfSome((expr) => { Output.Append(" = "); WriteExpression(expr); }); Output.Append(';'); } /// <summary> /// Writes an expression. /// </summary> private void WriteExpression(Expression expr) { switch (expr) { case IntegerLiteral i: Output.Append(i.Value); break; case BooleanLiteral b: Output.Append(b.Value ? "true" : "false"); break; default: throw new NotImplementedException(); } } /// <summary> /// Write the type of the function. /// </summary> private void WriteType(Type type) { switch (type) { case Types.Void _: Output.Append("void"); break; case Types.Integer _: // TODO(zac, 23/08/2017): In future, we want to support ints of different sizes. Output.Append("int"); break; case Types.Boolean _: Output.Append("bool"); break; default: throw new NotImplementedException(); } } } }
//----------------------------------------------------------------------- // <copyright file="TangoARScreen.cs" company="Google"> // // Copyright 2015 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // </copyright> //----------------------------------------------------------------------- using System.Collections; using UnityEngine; using Tango; /// <summary> /// TangoARScreen takes the YUV image from the API, resize the image plane and passes /// the YUV data and vertices data to the YUV2RGB shader to produce a properly /// sized RGBA image. /// /// Please note that all the YUV to RGB conversion is done through the YUV2RGB /// shader, no computation is in this class, this class only passes the data to /// shader. /// </summary> [RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))] public class TangoARScreen : MonoBehaviour, ITangoLifecycle { /// <summary> /// If set, m_updatePointsMesh in PointCloud also gets set. Then PointCloud material's renderqueue is set to background-1 /// so that PointCloud data gets written to Z buffer for Depth test with virtual /// objects in scene. Note 1: This is a very rudimentary way of doing occlusion and limited by the capabilities of /// depth camera. Note 2: To enable occlusion TangoPointCloud prefab must be present in the scene as well. /// </summary> public bool m_enableOcclusion; /// <summary> /// Set this to the AR Screen material. /// </summary> public Material m_screenMaterial; /// <summary> /// The most recent time (in seconds) the screen was updated. /// </summary> [HideInInspector] public double m_screenUpdateTime; /// <summary> /// The Background renderqueue's number. /// </summary> private const int BACKGROUND_RENDER_QUEUE = 1000; /// <summary> /// Point size of PointCloud data when projected on to image plane. /// </summary> private const int POINTCLOUD_SPLATTER_UPSAMPLE_SIZE = 30; private TangoApplication m_tangoApplication; private YUVTexture m_textures; private ARCameraPostProcess m_arCameraPostProcess; /// <summary> /// Initialize the AR Screen. /// </summary> public void Start() { m_tangoApplication = FindObjectOfType<TangoApplication>(); m_arCameraPostProcess = gameObject.GetComponent<ARCameraPostProcess>(); if (m_tangoApplication != null) { m_tangoApplication.Register(this); // Pass YUV textures to shader for process. m_textures = m_tangoApplication.GetVideoOverlayTextureYUV(); m_screenMaterial.SetTexture("_YTex", m_textures.m_videoOverlayTextureY); m_screenMaterial.SetTexture("_UTex", m_textures.m_videoOverlayTextureCb); m_screenMaterial.SetTexture("_VTex", m_textures.m_videoOverlayTextureCr); } if (m_enableOcclusion) { TangoPointCloud pointCloud = FindObjectOfType<TangoPointCloud>(); if (pointCloud != null) { Renderer renderer = pointCloud.GetComponent<Renderer>(); renderer.enabled = true; // Set the renderpass as background renderqueue's number minus one. YUV2RGB shader executes in // Background queue which is 1000. // But since we want to write depth data to Z buffer before YUV2RGB shader executes so that YUV2RGB // data ignores Ztest from the depth data we set renderqueue of PointCloud as 999. renderer.material.renderQueue = BACKGROUND_RENDER_QUEUE - 1; renderer.material.SetFloat("point_size", POINTCLOUD_SPLATTER_UPSAMPLE_SIZE); pointCloud.m_updatePointsMesh = true; } else { Debug.Log("Point Cloud data is not available, occlusion is not possible."); } } } /// <summary> /// Unity update function, we update our texture from here. /// </summary> public void Update() { m_screenUpdateTime = VideoOverlayProvider.RenderLatestFrame(TangoEnums.TangoCameraId.TANGO_CAMERA_COLOR); // Rendering the latest frame changes a bunch of OpenGL state. Ensure Unity knows the current OpenGL state. GL.InvalidateState(); } /// <summary> /// This is called when the permission granting process is finished. /// </summary> /// <param name="permissionsGranted"><c>true</c> if permissions were granted, otherwise <c>false</c>.</param> public void OnTangoPermissions(bool permissionsGranted) { } /// <summary> /// This is called when succesfully connected to the Tango service. /// </summary> public void OnTangoServiceConnected() { // Set up the size of ARScreen based on camera intrinsics. TangoCameraIntrinsics intrinsics = new TangoCameraIntrinsics(); VideoOverlayProvider.GetIntrinsics(TangoEnums.TangoCameraId.TANGO_CAMERA_COLOR, intrinsics); if (intrinsics.width != 0 && intrinsics.height != 0) { m_arCameraPostProcess.SetupIntrinsic(intrinsics); Camera.main.projectionMatrix = ProjectionMatrixForCameraIntrinsics((float)intrinsics.width, (float)intrinsics.height, (float)intrinsics.fx, (float)intrinsics.fy, (float)intrinsics.cx, (float)intrinsics.cy, 0.1f, 1000.0f); // Here we are scaling the image plane to make sure the image plane's ratio is set as the // color camera image ratio. // If we don't do this, because we are drawing the texture fullscreen, the image plane will // be set to the screen's ratio. float widthRatio = (float)Screen.width / (float)intrinsics.width; float heightRatio = (float)Screen.height / (float)intrinsics.height; if (widthRatio >= heightRatio) { float normalizedOffset = ((widthRatio / heightRatio) - 1.0f) / 2.0f; _SetScreenVertices(0, normalizedOffset); } else { float normalizedOffset = ((heightRatio / widthRatio) - 1.0f) / 2.0f; _SetScreenVertices(normalizedOffset, 0); } } else { m_arCameraPostProcess.enabled = false; } } /// <summary> /// This is called when disconnected from the Tango service. /// </summary> public void OnTangoServiceDisconnected() { } /// <summary> /// Set the screen (video overlay image plane) size and vertices. The image plane is not /// applying any project matrix or view matrix. So it's drawing space is the normalized /// screen space, that is [-1.0f, 1.0f] for both width and height. /// </summary> /// <param name="normalizedOffsetX">Horizontal padding to add to the left and right edges.</param> /// <param name="normalizedOffsetY">Vertical padding to add to top and bottom edges.</param> private void _SetScreenVertices(float normalizedOffsetX, float normalizedOffsetY) { // Set the vertices base on the offset, note that the offset is used to compensate // the ratio differences between the camera image and device screen. Vector3[] verts = new Vector3[4]; verts[0] = new Vector3(-1.0f - normalizedOffsetX, -1.0f - normalizedOffsetY, 1.0f); verts[1] = new Vector3(-1.0f - normalizedOffsetX, 1.0f + normalizedOffsetY, 1.0f); verts[2] = new Vector3(1.0f + normalizedOffsetX, 1.0f + normalizedOffsetY, 1.0f); verts[3] = new Vector3(1.0f + normalizedOffsetX, -1.0f - normalizedOffsetY, 1.0f); // Set indices. int[] indices = new int[6]; indices[0] = 0; indices[1] = 2; indices[2] = 3; indices[3] = 1; indices[4] = 2; indices[5] = 0; // Set UVs. Vector2[] uvs = new Vector2[4]; uvs[0] = new Vector2(0, 0); uvs[1] = new Vector2(0, 1f); uvs[2] = new Vector2(1f, 1f); uvs[3] = new Vector2(1f, 0); Mesh mesh = GetComponent<MeshFilter>().mesh; mesh.Clear(); mesh.vertices = verts; mesh.triangles = indices; mesh.uv = uvs; // Make this mesh never fail the occlusion cull mesh.bounds = new Bounds(Vector3.zero, new Vector3(float.MaxValue, float.MaxValue, float.MaxValue)); } /// <summary> /// Compute a projection matrix from window size, camera intrinsics, and clip settings. /// </summary> /// <returns>Projection matrix.</returns> /// <param name="width">The width of the camera image.</param> /// <param name="height">The height of the camera image.</param> /// <param name="fx">The x-axis focal length of the camera.</param> /// <param name="fy">The y-axis focal length of the camera.</param> /// <param name="cx">The x-coordinate principal point in pixels.</param> /// <param name="cy">The y-coordinate principal point in pixels.</param> /// <param name="near">The desired near z-clipping plane.</param> /// <param name="far">The desired far z-clipping plane.</param> private Matrix4x4 ProjectionMatrixForCameraIntrinsics(float width, float height, float fx, float fy, float cx, float cy, float near, float far) { float xscale = near / fx; float yscale = near / fy; float xoffset = (cx - (width / 2.0f)) * xscale; // OpenGL coordinates has y pointing downwards so we negate this term. float yoffset = -(cy - (height / 2.0f)) * yscale; return Frustum((xscale * -width / 2.0f) - xoffset, (xscale * +width / 2.0f) - xoffset, (yscale * -height / 2.0f) - yoffset, (yscale * +height / 2.0f) - yoffset, near, far); } /// <summary> /// Compute a projection matrix for a frustum. /// /// This function's implementation is same as glFrustum. /// </summary> /// <returns>Projection matrix.</returns> /// <param name="left">Specify the coordinates for the left vertical clipping planes.</param> /// <param name="right">Specify the coordinates for the right vertical clipping planes.</param> /// <param name="bottom">Specify the coordinates for the bottom horizontal clipping planes.</param> /// <param name="top">Specify the coordinates for the top horizontal clipping planes.</param> /// <param name="zNear">Specify the distances to the near depth clipping planes. Both distances must be positive.</param> /// <param name="zFar">Specify the distances to the far depth clipping planes. Both distances must be positive.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.SpacingRules", "*", Justification = "Matrix visibility is more important.")] private Matrix4x4 Frustum(float left, float right, float bottom, float top, float zNear, float zFar) { Matrix4x4 m = new Matrix4x4(); m.SetRow(0, new Vector4(2.0f * zNear / (right - left), 0.0f, (right + left) / (right - left) , 0.0f)); m.SetRow(1, new Vector4(0.0f, 2.0f * zNear / (top - bottom), (top + bottom) / (top - bottom) , 0.0f)); m.SetRow(2, new Vector4(0.0f, 0.0f, -(zFar + zNear) / (zFar - zNear), -(2 * zFar * zNear) / (zFar - zNear))); m.SetRow(3, new Vector4(0.0f, 0.0f, -1.0f, 0.0f)); return m; } }
/* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC Copyright (C) 2011 Peter Gill <[email protected]> This file is part of the fyiReporting RDL project. 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. For additional information, email [email protected] or visit the website www.fyiReporting.com. */ using System; using System.Xml; using System.Collections; using System.Collections.Specialized; using System.Collections.Generic; using System.IO; using System.Globalization; using System.Data; using System.Data.SqlClient; using fyiReporting.RDL; namespace fyiReporting.RDL { ///<summary> /// Main Report definition; this is the top of the tree that contains the complete /// definition of a instance of a report. ///</summary> public class Report { // private definitions ReportDefn _Report; DataSources _DataSources; DataSets _DataSets; int _RuntimeName=0; // used for the generation of unique runtime names IDictionary _LURuntimeName; // Runtime names ICollection _UserParameters; // User parameters internal ReportLog rl; // report log RCache _Cache; // Some report runtime variables private string _Folder; // folder name private string _ReportName; // report name private string _CSS; // after rendering ASPHTML; this is separate private string _JavaScript; // after rendering ASPHTML; this is separate private object _CodeInstance; // Instance of the class generated for the Code element private Page _CurrentPage; // needed for page header/footer references private string _UserID; // UserID of client executing the report private string _ClientLanguage; // Language code of the client executing the report. private DataSourcesDefn _ParentConnections; // When running subreport with merge transactions this is parent report connections internal int PageNumber=1; // current page number internal int TotalPages=1; // total number of pages in report internal DateTime ExecutionTime; // start time of report execution // - Added due to Embedded font bug. Solution posted by sinnovasoft. http://www.fyireporting.com/forum/viewtopic.php?t=1049 private bool _itextpdf = true; /// <summary> /// True: Renderpdf will use Add elements by itextsharp code; /// False : Render pdf by the old way if my code gets error or don't need font embedded. /// </summary> public bool ItextPDF { get { return _itextpdf; } set { _itextpdf = value; } } /// <summary> /// Construct a runtime Report object using the compiled report definition. /// </summary> /// <param name="r"></param> public Report(ReportDefn r) { _Report = r; _Cache = new RCache(); rl = new ReportLog(r.rl); _ReportName = r.Name; _UserParameters = null; _LURuntimeName = new ListDictionary(); // shouldn't be very many of these if (r.Code != null) _CodeInstance = r.Code.Load(this); if (r.Classes != null) r.Classes.Load(this); } // Event for Subreport data retrieval /// <summary> /// Event invoked just prior to obtaining data for the subreport. Setting DataSet /// and DataConnection information during this event affects only this instance /// of the Subreport. /// </summary> public event EventHandler<SubreportDataRetrievalEventArgs> SubreportDataRetrieval; protected virtual void OnSubreportDataRetrieval(SubreportDataRetrievalEventArgs e) { if (SubreportDataRetrieval != null) SubreportDataRetrieval(this, e); } internal void SubreportDataRetrievalTriggerEvent() { if (SubreportDataRetrieval != null) { OnSubreportDataRetrieval(new SubreportDataRetrievalEventArgs(this)); } } internal bool IsSubreportDataRetrievalDefined { get { return SubreportDataRetrieval != null; } } internal Page CurrentPage { get {return _CurrentPage;} set {_CurrentPage = value;} } internal Rows GetPageExpressionRows(string exprname) { if (_CurrentPage == null) return null; return _CurrentPage.GetPageExpressionRows(exprname); } /// <summary> /// Read all the DataSets in the report /// </summary> /// <param name="parms"></param> public bool RunGetData(IDictionary parms) { ExecutionTime = DateTime.Now; bool bRows = _Report.RunGetData(this, parms); return bRows; } /// <summary> /// Renders the report using the requested presentation type. /// </summary> /// <param name="sg">IStreamGen for generating result stream</param> /// <param name="type">Presentation type: HTML, XML, PDF, or ASP compatible HTML</param> public void RunRender(IStreamGen sg, OutputPresentationType type) { RunRender(sg, type, ""); } /// <summary> /// Renders the report using the requested presentation type. /// </summary> /// <param name="sg">IStreamGen for generating result stream</param> /// <param name="type">Presentation type: HTML, XML, PDF, MHT, or ASP compatible HTML</param> /// <param name="prefix">For HTML puts prefix allowing unique name generation</param> public void RunRender(IStreamGen sg, OutputPresentationType type, string prefix) { if (sg == null) throw new ArgumentException("IStreamGen argument cannot be null.", "sg"); RenderHtml rh=null; PageNumber = 1; // reset page numbers TotalPages = 1; IPresent ip; MemoryStreamGen msg = null; switch (type) { case OutputPresentationType.PDF: case OutputPresentationType.RenderPdf_iTextSharp: ip =new RenderPdf_iTextSharp(this, sg); _Report.Run(ip); break; case OutputPresentationType.PDFOldStyle: ip = new RenderPdf(this, sg); this.ItextPDF = false; _Report.Run(ip); break; case OutputPresentationType.TIF: ip = new RenderTif(this, sg); _Report.Run(ip); break; case OutputPresentationType.TIFBW: RenderTif rtif = new RenderTif(this, sg); rtif.RenderColor = false; ip = rtif; _Report.Run(ip); break; case OutputPresentationType.XML: if (_Report.DataTransform != null && _Report.DataTransform.Length > 0) { msg = new MemoryStreamGen(); ip = new RenderXml(this, msg); _Report.Run(ip); RunRenderXmlTransform(sg, msg); } else { ip = new RenderXml(this, sg); _Report.Run(ip); } break; case OutputPresentationType.MHTML: this.RunRenderMht(sg); break; case OutputPresentationType.CSV: ip = new RenderCsv(this, sg); _Report.Run(ip); break; case OutputPresentationType.RTF: ip = new RenderRtf(this, sg); _Report.Run(ip); break; case OutputPresentationType.ExcelTableOnly: ip = new RenderExcel(this, sg); _Report.Run(ip); break; case OutputPresentationType.Excel2007: ip = new RenderExcel2007(this, sg); _Report.Run(ip); break; case OutputPresentationType.ASPHTML: case OutputPresentationType.HTML: default: ip = rh = new RenderHtml(this, sg); rh.Asp = (type == OutputPresentationType.ASPHTML); rh.Prefix = prefix; _Report.Run(ip); // Retain the CSS and JavaScript if (rh != null) { _CSS = rh.CSS; _JavaScript = rh.JavaScript; } break; } sg.CloseMainStream(); _Cache = new RCache(); return; } private void RunRenderMht(IStreamGen sg) { OneFileStreamGen temp = null; FileStream fs=null; try { string tempHtmlReportFileName = Path.ChangeExtension(Path.GetTempFileName(), "htm"); temp = new OneFileStreamGen(tempHtmlReportFileName, true); RunRender(temp, OutputPresentationType.HTML); temp.CloseMainStream(); // Create the mht file (into a temporary file position) MhtBuilder mhtConverter = new MhtBuilder(); string fileName = Path.ChangeExtension(Path.GetTempFileName(), "mht"); mhtConverter.SavePageArchive(fileName, "file://" + tempHtmlReportFileName); // clean up the temporary files foreach (string tempFileName in temp.FileList) { try { File.Delete(tempFileName); } catch{} } // Copy the mht file to the requested stream Stream os = sg.GetStream(); fs = File.OpenRead(fileName); byte[] ba = new byte[4096]; int rb=0; while ((rb = fs.Read(ba, 0, ba.Length)) > 0) { os.Write(ba, 0, rb); } } catch (Exception ex) { rl.LogError(8, "Error converting HTML to MHTML " + ex.Message + Environment.NewLine + ex.StackTrace); } finally { if (temp != null) temp.CloseMainStream(); if (fs != null) fs.Close(); _Cache = new RCache(); } } /// <summary> /// RunRenderPdf will render a Pdf given the page structure /// </summary> /// <param name="sg"></param> /// <param name="pgs"></param> public void RunRenderPdf(IStreamGen sg, Pages pgs) { PageNumber = 1; // reset page numbers TotalPages = 1; IPresent ip; if (this.ItextPDF) ip = new RenderPdf_iTextSharp(this, sg); else ip=new RenderPdf(this, sg); try { ip.Start(); ip.RunPages(pgs); ip.End(); } finally { pgs.CleanUp(); // always want to make sure we cleanup to reduce resource usage _Cache = new RCache(); } return; } /// <summary> /// RunRenderTif will render a TIF given the page structure /// </summary> /// <param name="sg"></param> /// <param name="pgs"></param> public void RunRenderTif(IStreamGen sg, Pages pgs, bool bColor) { PageNumber = 1; // reset page numbers TotalPages = 1; RenderTif ip = new RenderTif(this, sg); ip.RenderColor = bColor; try { ip.Start(); ip.RunPages(pgs); ip.End(); } finally { pgs.CleanUp(); // always want to make sure we cleanup to reduce resource usage _Cache = new RCache(); } return; } private void RunRenderXmlTransform(IStreamGen sg, MemoryStreamGen msg) { try { string file; if (_Report.DataTransform[0] != Path.DirectorySeparatorChar) file = this.Folder + Path.DirectorySeparatorChar + _Report.DataTransform; else file = this.Folder + _Report.DataTransform; XmlUtil.XslTrans(file, msg.GetText(), sg.GetStream()); } catch (Exception ex) { rl.LogError(8, "Error processing DataTransform " + ex.Message + "\r\n" + ex.StackTrace); } finally { msg.Dispose(); } return; } /// <summary> /// Build the Pages for this report. /// </summary> /// <returns></returns> public Pages BuildPages() { PageNumber = 1; // reset page numbers TotalPages = 1; Pages pgs = new Pages(this); pgs.PageHeight = _Report.PageHeight.Points; pgs.PageWidth = _Report.PageWidth.Points; try { Page p = new Page(1); // kick it off with a new page pgs.AddPage(p); // Create all the pages _Report.Body.RunPage(pgs); if (pgs.LastPage.IsEmpty() && pgs.PageCount > 1) // get rid of extraneous pages which pgs.RemoveLastPage(); // can be caused by region page break at end // Now create the headers and footers for all the pages (as needed) if (_Report.PageHeader != null) _Report.PageHeader.RunPage(pgs); if (_Report.PageFooter != null) _Report.PageFooter.RunPage(pgs); // clear out any runtime clutter foreach (Page pg in pgs) pg.ResetPageExpressions(); pgs.SortPageItems(); // Handle ZIndex ordering of pages } catch (Exception e) { rl.LogError(8, "Exception running report\r\n" + e.Message + "\r\n" + e.StackTrace); } finally { pgs.CleanUp(); // always want to make sure we clean this up since _Cache = new RCache(); } return pgs; } public NeedPassword GetDataSourceReferencePassword { get {return _Report.GetDataSourceReferencePassword;} set {_Report.GetDataSourceReferencePassword = value;} } public ReportDefn ReportDefinition { get {return this._Report;} } internal void SetReportDefinition(ReportDefn r) { _Report = r; _UserParameters = null; // force recalculation of user parameters _DataSets = null; // force reload of datasets } public string Description { get { return _Report.Description; } } public string Author { get { return _Report.Author; } } public string CSS { get { return _CSS; } } public string JavaScript { get { return _JavaScript; } } internal object CodeInstance { get {return this._CodeInstance;} } internal string CreateRuntimeName(object ro) { _RuntimeName++; // increment the name generator string name = "o" + _RuntimeName.ToString(); _LURuntimeName.Add(name, ro); return name; } public DataSources DataSources { get { if (_Report.DataSourcesDefn == null) return null; if (_DataSources == null) _DataSources = new DataSources(this, _Report.DataSourcesDefn); return _DataSources; } } public DataSets DataSets { get { if (_Report.DataSetsDefn == null) return null; if (_DataSets == null) _DataSets = new DataSets(this, _Report.DataSetsDefn); return _DataSets; } } /// <summary> /// User provided parameters to the report. IEnumerable is a list of UserReportParameter. /// </summary> public ICollection UserReportParameters { get { if (_UserParameters != null) // only create this once return _UserParameters; // since it can be expensive to build if (ReportDefinition.ReportParameters == null || ReportDefinition.ReportParameters.Count <= 0) { List<UserReportParameter> parms = new List<UserReportParameter>(1); _UserParameters = parms; } else { List<UserReportParameter> parms = new List<UserReportParameter>(ReportDefinition.ReportParameters.Count); foreach (ReportParameter p in ReportDefinition.ReportParameters) { UserReportParameter urp = new UserReportParameter(this, p); parms.Add(urp); } parms.TrimExcess(); _UserParameters = parms; } return _UserParameters; } } /// <summary> /// Get/Set the folder containing the report. /// </summary> public string Folder { get { return _Folder==null? _Report.ParseFolder: _Folder; } set { _Folder = value; } } /// <summary> /// Get/Set the report name. Usually this is the file name of the report sans extension. /// </summary> public string Name { get { return _ReportName; } set { _ReportName = value; } } /// <summary> /// Returns the height of the page in points. /// </summary> public float PageHeightPoints { get { return _Report.PageHeight.Points; } } /// <summary> /// Returns the width of the page in points. /// </summary> public float PageWidthPoints { get { return _Report.PageWidthPoints; } } /// <summary> /// Returns the left margin size in points. /// </summary> public float LeftMarginPoints { get { return _Report.LeftMargin.Points; } } /// <summary> /// Returns the right margin size in points. /// </summary> public float RightMarginPoints { get { return _Report.RightMargin.Points; } } /// <summary> /// Returns the top margin size in points. /// </summary> public float TopMarginPoints { get { return _Report.TopMargin.Points; } } /// <summary> /// Returns the bottom margin size in points. /// </summary> public float BottomMarginPoints { get { return _Report.BottomMargin.Points; } } /// <summary> /// Returns the maximum severity of any error. 4 or less indicating report continues running. /// </summary> public int ErrorMaxSeverity { get { if (this.rl == null) return 0; else return rl.MaxSeverity; } } /// <summary> /// List of errors encountered so far. /// </summary> public IList ErrorItems { get { if (this.rl == null) return null; else return rl.ErrorItems; } } /// <summary> /// Clear all errors generated up to now. /// </summary> public void ErrorReset() { if (this.rl == null) return; rl.Reset(); return; } /// <summary> /// Get/Set the UserID, that is the running user. /// </summary> public string UserID { get { return _UserID == null? Environment.UserName: _UserID; } set { _UserID = value; } } /// <summary> /// Get/Set the three letter ISO language of the client of the report. /// </summary> public string ClientLanguage { get { if (_Report.Language != null) return _Report.Language.EvaluateString(this, null); if (_ClientLanguage != null) return _ClientLanguage; return CultureInfo.CurrentCulture.ThreeLetterISOLanguageName; } set { _ClientLanguage = value; } } internal DataSourcesDefn ParentConnections { get {return _ParentConnections; } set {_ParentConnections = value; } } internal RCache Cache { get {return _Cache;} } } internal class RCache { Hashtable _RunCache; internal RCache() { _RunCache = new Hashtable(); } internal void Add(ReportLink rl, string name, object o) { _RunCache.Add(GetKey(rl,name), o); } internal void AddReplace(ReportLink rl, string name, object o) { string key = GetKey(rl,name); _RunCache.Remove(key); _RunCache.Add(key, o); } internal object Get(ReportLink rl, string name) { return _RunCache[GetKey(rl,name)]; } internal void Remove(ReportLink rl, string name) { _RunCache.Remove(GetKey(rl,name)); } internal void Add(ReportDefn rd, string name, object o) { _RunCache.Add(GetKey(rd,name), o); } internal void AddReplace(ReportDefn rd, string name, object o) { string key = GetKey(rd,name); _RunCache.Remove(key); _RunCache.Add(key, o); } internal object Get(ReportDefn rd, string name) { return _RunCache[GetKey(rd,name)]; } internal void Remove(ReportDefn rd, string name) { _RunCache.Remove(GetKey(rd,name)); } internal void Add(string key, object o) { _RunCache.Add(key, o); } internal void AddReplace(string key, object o) { _RunCache.Remove(key); _RunCache.Add(key, o); } internal object Get(string key) { return _RunCache[key]; } internal void Remove(string key) { _RunCache.Remove(key); } internal object Get(int i, string name) { return _RunCache[GetKey(i,name)]; } internal void Remove(int i, string name) { _RunCache.Remove(GetKey(i,name)); } string GetKey(ReportLink rl, string name) { return GetKey(rl.ObjectNumber, name); } string GetKey(ReportDefn rd, string name) { if (rd.Subreport == null) // top level report use 0 { return GetKey(0, name); } else // Use the subreports object number { return GetKey(rd.Subreport.ObjectNumber, name); } } string GetKey(int onum, string name) { return name + onum.ToString(); } } // holder objects for value types internal class ODateTime { internal DateTime dt; internal ODateTime(DateTime adt) { dt = adt; } } internal class ODecimal { internal decimal d; internal ODecimal(decimal ad) { d = ad; } } internal class ODouble { internal double d; internal ODouble(double ad) { d = ad; } } internal class OFloat { internal float f; internal OFloat(float af) { f = af; } } internal class OInt { internal int i; internal OInt(int ai) { i = ai; } } public class SubreportDataRetrievalEventArgs : EventArgs { public readonly Report Report; public SubreportDataRetrievalEventArgs(Report r) { Report = r; } } }
// 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.Text; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.IO.Compression.Tests { public class DeflateStreamTests { static string gzTestFile(string fileName) => Path.Combine("GZTestData", fileName); [Fact] public void BaseStream1() { var writeStream = new MemoryStream(); var zip = new DeflateStream(writeStream, CompressionMode.Compress); Assert.Same(zip.BaseStream, writeStream); writeStream.Dispose(); } [Fact] public void BaseStream2() { var ms = new MemoryStream(); var zip = new DeflateStream(ms, CompressionMode.Decompress); Assert.Same(zip.BaseStream, ms); ms.Dispose(); } [Fact] public async Task ModifyBaseStream() { var ms = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.txt.gz")); var newMs = StripHeaderAndFooter.Strip(ms); var zip = new DeflateStream(newMs, CompressionMode.Decompress); int size = 1024; byte[] bytes = new byte[size]; zip.BaseStream.Read(bytes, 0, size); // This will throw if the underlying stream is not writable as expected zip.BaseStream.Position = 0; await zip.BaseStream.ReadAsync(bytes, 0, size); } [Fact] public void DecompressCanRead() { var ms = new MemoryStream(); var zip = new DeflateStream(ms, CompressionMode.Decompress); Assert.True(zip.CanRead); zip.Dispose(); Assert.False(zip.CanRead); } [Fact] public void CompressCanWrite() { var ms = new MemoryStream(); var zip = new DeflateStream(ms, CompressionMode.Compress); Assert.True(zip.CanWrite); zip.Dispose(); Assert.False(zip.CanWrite); } [Fact] public void CanDisposeBaseStream() { var ms = new MemoryStream(); var zip = new DeflateStream(ms, CompressionMode.Compress); ms.Dispose(); // This would throw if this was invalid } [Fact] public void CanDisposeDeflateStream() { var ms = new MemoryStream(); var zip = new DeflateStream(ms, CompressionMode.Compress); zip.Dispose(); // Base Stream should be null after dispose Assert.Null(zip.BaseStream); zip.Dispose(); // Should be a no-op } [Fact] public async Task CanReadBaseStreamAfterDispose() { var ms = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.txt.gz")); var newMs = StripHeaderAndFooter.Strip(ms); var zip = new DeflateStream(newMs, CompressionMode.Decompress, leaveOpen: true); var baseStream = zip.BaseStream; zip.Dispose(); int size = 1024; byte[] bytes = new byte[size]; baseStream.Read(bytes, 0, size); // This will throw if the underlying stream is not writable as expected baseStream.Position = 0; await baseStream.ReadAsync(bytes, 0, size); } [Fact] public async Task DecompressFailsWithRealGzStream() { string[] files = { gzTestFile("GZTestDocument.doc.gz"), gzTestFile("GZTestDocument.txt.gz") }; foreach (string fileName in files) { var baseStream = await LocalMemoryStream.readAppFileAsync(fileName); var zip = new DeflateStream(baseStream, CompressionMode.Decompress); int _bufferSize = 2048; var bytes = new byte[_bufferSize]; Assert.Throws<InvalidDataException>(() => { zip.Read(bytes, 0, _bufferSize); }); zip.Dispose(); } } [Fact] public void DisposedBaseStreamThrows() { var ms = new MemoryStream(); ms.Dispose(); Assert.Throws<ArgumentException>(() => { var deflate = new DeflateStream(ms, CompressionMode.Decompress); }); Assert.Throws<ArgumentException>(() => { var deflate = new DeflateStream(ms, CompressionMode.Compress); }); } [Fact] public void ReadOnlyStreamThrowsOnCompress() { var ms = new LocalMemoryStream(); ms.SetCanWrite(false); Assert.Throws<ArgumentException>(() => { var gzip = new DeflateStream(ms, CompressionMode.Compress); }); } [Fact] public void WriteOnlyStreamThrowsOnDecompress() { var ms = new LocalMemoryStream(); ms.SetCanRead(false); Assert.Throws<ArgumentException>(() => { var gzip = new DeflateStream(ms, CompressionMode.Decompress); }); } [Fact] public void TestCtors() { CompressionLevel[] legalValues = new CompressionLevel[] { CompressionLevel.Optimal, CompressionLevel.Fastest, CompressionLevel.NoCompression }; foreach (CompressionLevel level in legalValues) { bool[] boolValues = new bool[] { true, false }; foreach (bool remainsOpen in boolValues) { TestCtor(level, remainsOpen); } } } [Fact] public void TestLevelOptimial() { TestCtor(CompressionLevel.Optimal); } [Fact] public void TestLevelNoCompression() { TestCtor(CompressionLevel.NoCompression); } [Fact] public void TestLevelFastest() { TestCtor(CompressionLevel.Fastest); } private static void TestCtor(CompressionLevel level, bool? leaveOpen = null) { //Create the DeflateStream int _bufferSize = 1024; var bytes = new byte[_bufferSize]; var baseStream = new MemoryStream(bytes, writable: true); DeflateStream ds; if (leaveOpen == null) { ds = new DeflateStream(baseStream, level); } else { ds = new DeflateStream(baseStream, level, leaveOpen ?? false); } //Write some data and Close the stream string strData = "Test Data"; var encoding = Encoding.UTF8; byte[] data = encoding.GetBytes(strData); ds.Write(data, 0, data.Length); ds.Flush(); ds.Dispose(); if (leaveOpen != true) { //Check that Close has really closed the underlying stream Assert.Throws<ObjectDisposedException>(() => { baseStream.Write(bytes, 0, bytes.Length); }); } //Read the data byte[] data2 = new byte[_bufferSize]; baseStream = new MemoryStream(bytes, writable: false); ds = new DeflateStream(baseStream, CompressionMode.Decompress); int size = ds.Read(data2, 0, _bufferSize - 5); //Verify the data roundtripped for (int i = 0; i < size + 5; i++) { if (i < data.Length) { Assert.Equal(data[i], data2[i]); } else { Assert.Equal(data2[i], (byte)0); } } } [Fact] public void CtorArgumentValidation() { Assert.Throws<ArgumentNullException>(() => new DeflateStream(null, CompressionLevel.Fastest)); Assert.Throws<ArgumentNullException>(() => new DeflateStream(null, CompressionMode.Decompress)); Assert.Throws<ArgumentNullException>(() => new DeflateStream(null, CompressionMode.Compress)); Assert.Throws<ArgumentNullException>(() => new DeflateStream(null, CompressionLevel.Fastest, true)); Assert.Throws<ArgumentNullException>(() => new DeflateStream(null, CompressionMode.Decompress, false)); Assert.Throws<ArgumentNullException>(() => new DeflateStream(null, CompressionMode.Compress, true)); Assert.Throws<ArgumentException>(() => new DeflateStream(new MemoryStream(), (CompressionMode)42)); Assert.Throws<ArgumentException>(() => new DeflateStream(new MemoryStream(), (CompressionMode)43, true)); Assert.Throws<ArgumentException>(() => new DeflateStream(new MemoryStream(new byte[1], writable: false), CompressionLevel.Optimal)); } [Fact] public async Task Flush() { var ms = new MemoryStream(); var ds = new DeflateStream(ms, CompressionMode.Compress); ds.Flush(); await ds.FlushAsync(); } [Fact] public void DoubleFlush() { var ms = new MemoryStream(); var ds = new DeflateStream(ms, CompressionMode.Compress); ds.Flush(); ds.Flush(); } [Fact] public void DoubleDispose() { var ms = new MemoryStream(); var ds = new DeflateStream(ms, CompressionMode.Compress); ds.Dispose(); ds.Dispose(); } [Fact] public void FlushThenDispose() { var ms = new MemoryStream(); var ds = new DeflateStream(ms, CompressionMode.Compress); ds.Flush(); ds.Dispose(); } [Fact] public void FlushFailsAfterDispose() { var ms = new MemoryStream(); var ds = new DeflateStream(ms, CompressionMode.Compress); ds.Dispose(); Assert.Throws<ObjectDisposedException>(() => { ds.Flush(); }); } [Fact] public async Task FlushAsyncFailsAfterDispose() { var ms = new MemoryStream(); var ds = new DeflateStream(ms, CompressionMode.Compress); ds.Dispose(); await Assert.ThrowsAsync<ObjectDisposedException>(async () => { await ds.FlushAsync(); }); } [Fact] public void TestSeekMethodsDecompress() { var ms = new MemoryStream(); var zip = new DeflateStream(ms, CompressionMode.Decompress); Assert.False(zip.CanSeek, "CanSeek should be false"); Assert.Throws<NotSupportedException>(delegate { long value = zip.Length; }); Assert.Throws<NotSupportedException>(delegate { long value = zip.Position; }); Assert.Throws<NotSupportedException>(delegate { zip.Position = 100L; }); Assert.Throws<NotSupportedException>(delegate { zip.SetLength(100L); }); Assert.Throws<NotSupportedException>(delegate { zip.Seek(100L, SeekOrigin.Begin); }); } [Fact] public void TestSeekMethodsCompress() { var ms = new MemoryStream(); var zip = new DeflateStream(ms, CompressionMode.Compress); Assert.False(zip.CanSeek, "CanSeek should be false"); Assert.Throws<NotSupportedException>(delegate { long value = zip.Length; }); Assert.Throws<NotSupportedException>(delegate { long value = zip.Position; }); Assert.Throws<NotSupportedException>(delegate { zip.Position = 100L; }); Assert.Throws<NotSupportedException>(delegate { zip.SetLength(100L); }); Assert.Throws<NotSupportedException>(delegate { zip.Seek(100L, SeekOrigin.Begin); }); } [Fact] public void ReadWriteArgumentValidation() { using (var ds = new DeflateStream(new MemoryStream(), CompressionMode.Compress)) { Assert.Throws<ArgumentNullException>(() => ds.Write(null, 0, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ds.Write(new byte[1], -1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ds.Write(new byte[1], 0, -1)); Assert.Throws<ArgumentException>(() => ds.Write(new byte[1], 0, 2)); Assert.Throws<ArgumentException>(() => ds.Write(new byte[1], 1, 1)); Assert.Throws<InvalidOperationException>(() => ds.Read(new byte[1], 0, 1)); ds.Write(new byte[1], 0, 0); } using (var ds = new DeflateStream(new MemoryStream(), CompressionMode.Compress)) { Assert.Throws<ArgumentNullException>(() => { ds.WriteAsync(null, 0, 0); }); Assert.Throws<ArgumentOutOfRangeException>(() => { ds.WriteAsync(new byte[1], -1, 0); }); Assert.Throws<ArgumentOutOfRangeException>(() => { ds.WriteAsync(new byte[1], 0, -1); }); Assert.Throws<ArgumentException>(() => { ds.WriteAsync(new byte[1], 0, 2); }); Assert.Throws<ArgumentException>(() => { ds.WriteAsync(new byte[1], 1, 1); }); Assert.Throws<InvalidOperationException>(() => { ds.Read(new byte[1], 0, 1); }); } using (var ds = new DeflateStream(new MemoryStream(), CompressionMode.Decompress)) { Assert.Throws<ArgumentNullException>(() => ds.Read(null, 0, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ds.Read(new byte[1], -1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ds.Read(new byte[1], 0, -1)); Assert.Throws<ArgumentException>(() => ds.Read(new byte[1], 0, 2)); Assert.Throws<ArgumentException>(() => ds.Read(new byte[1], 1, 1)); Assert.Throws<InvalidOperationException>(() => ds.Write(new byte[1], 0, 1)); var data = new byte[1] { 42 }; Assert.Equal(0, ds.Read(data, 0, 0)); Assert.Equal(42, data[0]); } using (var ds = new DeflateStream(new MemoryStream(), CompressionMode.Decompress)) { Assert.Throws<ArgumentNullException>(() => { ds.ReadAsync(null, 0, 0); }); Assert.Throws<ArgumentOutOfRangeException>(() => { ds.ReadAsync(new byte[1], -1, 0); }); Assert.Throws<ArgumentOutOfRangeException>(() => { ds.ReadAsync(new byte[1], 0, -1); }); Assert.Throws<ArgumentException>(() => { ds.ReadAsync(new byte[1], 0, 2); }); Assert.Throws<ArgumentException>(() => { ds.ReadAsync(new byte[1], 1, 1); }); Assert.Throws<InvalidOperationException>(() => { ds.Write(new byte[1], 0, 1); }); } } [Fact] public void CopyToAsyncArgumentValidation() { using (DeflateStream ds = new DeflateStream(new MemoryStream(), CompressionMode.Decompress)) { AssertExtensions.Throws<ArgumentNullException>("destination", () => { ds.CopyToAsync(null); }); AssertExtensions.Throws<ArgumentOutOfRangeException>("bufferSize", () => { ds.CopyToAsync(new MemoryStream(), 0); }); Assert.Throws<NotSupportedException>(() => { ds.CopyToAsync(new MemoryStream(new byte[1], writable: false)); }); ds.Dispose(); Assert.Throws<ObjectDisposedException>(() => { ds.CopyToAsync(new MemoryStream()); }); } using (DeflateStream ds = new DeflateStream(new MemoryStream(), CompressionMode.Compress)) { Assert.Throws<NotSupportedException>(() => { ds.CopyToAsync(new MemoryStream()); }); } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Full Framework Flush is a no-op.")] public void Precancellation() { var ms = new MemoryStream(); using (DeflateStream ds = new DeflateStream(ms, CompressionMode.Compress, leaveOpen: true)) { Assert.True(ds.WriteAsync(new byte[1], 0, 1, new CancellationToken(true)).IsCanceled); Assert.True(ds.FlushAsync(new CancellationToken(true)).IsCanceled); } using (DeflateStream ds = new DeflateStream(ms, CompressionMode.Decompress, leaveOpen: true)) { Assert.True(ds.ReadAsync(new byte[1], 0, 1, new CancellationToken(true)).IsCanceled); } } [Fact] public async Task RoundtripCompressDecompress() { await RoundtripCompressDecompress(useAsync: false, useGzip: false, chunkSize: 1, totalSize: 10, level: CompressionLevel.Fastest); await RoundtripCompressDecompress(useAsync: true, useGzip: true, chunkSize: 1024, totalSize: 8192, level: CompressionLevel.Optimal); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Full Framework Flush is a no-op.")] public async Task RoundTripWithFlush() { await RoundTripWithFlush(useAsync: false, useGzip: false, chunkSize: 1, totalSize: 10, level: CompressionLevel.Fastest); await RoundTripWithFlush(useAsync: true, useGzip: true, chunkSize: 1024, totalSize: 8192, level: CompressionLevel.Optimal); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Full Framework Flush is a no-op.")] public async Task WriteAfterFlushing() { await WriteAfterFlushing(useAsync: false, useGzip: false, chunkSize: 1, totalSize: 10, level: CompressionLevel.Fastest); await WriteAfterFlushing(useAsync: true, useGzip: true, chunkSize: 1024, totalSize: 8192, level: CompressionLevel.Optimal); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Full Framework Flush is a no-op.")] public async Task FlushBeforeFirstWrites() { await FlushBeforeFirstWrites(useAsync: false, useGzip: false, chunkSize: 1, totalSize: 10, level: CompressionLevel.Fastest); await FlushBeforeFirstWrites(useAsync: true, useGzip: true, chunkSize: 1024, totalSize: 8192, level: CompressionLevel.Optimal); } public static IEnumerable<object[]> RoundtripCompressDecompressOuterData { get { foreach (bool useAsync in new[] { true, false }) // whether to use Read/Write or ReadAsync/WriteAsync { foreach (bool useGzip in new[] { true, false }) // whether to add on gzip headers/footers { foreach (var level in new[] { CompressionLevel.Fastest, CompressionLevel.Optimal, CompressionLevel.NoCompression }) // compression level { yield return new object[] { useAsync, useGzip, 1, 5, level }; // smallest possible writes yield return new object[] { useAsync, useGzip, 1023, 1023 * 10, level }; // overflowing internal buffer yield return new object[] { useAsync, useGzip, 1024 * 1024, 1024 * 1024, level }; // large single write } } } } } [OuterLoop] [Theory] [MemberData(nameof(RoundtripCompressDecompressOuterData))] public async Task RoundtripCompressDecompress(bool useAsync, bool useGzip, int chunkSize, int totalSize, CompressionLevel level) { byte[] data = new byte[totalSize]; new Random(42).NextBytes(data); var compressed = new MemoryStream(); using (var compressor = useGzip ? (Stream)new GZipStream(compressed, level, true) : new DeflateStream(compressed, level, true)) { for (int i = 0; i < data.Length; i += chunkSize) // not using CopyTo{Async} due to optimizations in MemoryStream's implementation that avoid what we're trying to test { switch (useAsync) { case true: await compressor.WriteAsync(data, i, chunkSize); break; case false: compressor.Write(data, i, chunkSize); break; } } } compressed.Position = 0; await ValidateCompressedData(useAsync, useGzip, chunkSize, compressed, data); compressed.Dispose(); } [OuterLoop] [Theory] [MemberData(nameof(RoundtripCompressDecompressOuterData))] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Full Framework Flush is a no-op.")] public async Task RoundTripWithFlush(bool useAsync, bool useGzip, int chunkSize, int totalSize, CompressionLevel level) { byte[] data = new byte[totalSize]; new Random(42).NextBytes(data); using (var compressed = new MemoryStream()) using (var compressor = useGzip ? (Stream)new GZipStream(compressed, level, true) : new DeflateStream(compressed, level, true)) { for (int i = 0; i < data.Length; i += chunkSize) // not using CopyTo{Async} due to optimizations in MemoryStream's implementation that avoid what we're trying to test { switch (useAsync) { case true: await compressor.WriteAsync(data, i, chunkSize); break; case false: compressor.Write(data, i, chunkSize); break; } } switch (useAsync) { case true: await compressor.FlushAsync(); break; case false: compressor.Flush(); break; } compressed.Position = 0; await ValidateCompressedData(useAsync, useGzip, chunkSize, compressed, data); } } [OuterLoop] [Theory] [MemberData(nameof(RoundtripCompressDecompressOuterData))] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Full Framework Flush is a no-op.")] public async Task WriteAfterFlushing(bool useAsync, bool useGzip, int chunkSize, int totalSize, CompressionLevel level) { byte[] data = new byte[totalSize]; List<byte> expected = new List<byte>(); new Random(42).NextBytes(data); using (var compressed = new MemoryStream()) using (var compressor = useGzip ? (Stream)new GZipStream(compressed, level, true) : new DeflateStream(compressed, level, true)) { for (int i = 0; i < data.Length; i += chunkSize) // not using CopyTo{Async} due to optimizations in MemoryStream's implementation that avoid what we're trying to test { switch (useAsync) { case true: await compressor.WriteAsync(data, i, chunkSize); break; case false: compressor.Write(data, i, chunkSize); break; } for (int j = i; j < i + chunkSize; j++) expected.Insert(j, data[j]); switch (useAsync) { case true: await compressor.FlushAsync(); break; case false: compressor.Flush(); break; } MemoryStream partiallyCompressed = new MemoryStream(compressed.ToArray()); partiallyCompressed.Position = 0; await ValidateCompressedData(useAsync, useGzip, chunkSize, partiallyCompressed, expected.ToArray()); } } } [OuterLoop] [Theory] [MemberData(nameof(RoundtripCompressDecompressOuterData))] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Full Framework Flush is a no-op.")] public async Task FlushBeforeFirstWrites(bool useAsync, bool useGzip, int chunkSize, int totalSize, CompressionLevel level) { byte[] data = new byte[totalSize]; new Random(42).NextBytes(data); using (var compressed = new MemoryStream()) using (var compressor = useGzip ? (Stream)new GZipStream(compressed, level, true) : new DeflateStream(compressed, level, true)) { switch (useAsync) { case true: await compressor.FlushAsync(); break; case false: compressor.Flush(); break; } for (int i = 0; i < data.Length; i += chunkSize) // not using CopyTo{Async} due to optimizations in MemoryStream's implementation that avoid what we're trying to test { switch (useAsync) { case true: await compressor.WriteAsync(data, i, chunkSize); break; case false: compressor.Write(data, i, chunkSize); break; } } switch (useAsync) { case true: await compressor.FlushAsync(); break; case false: compressor.Flush(); break; } compressed.Position = 0; await ValidateCompressedData(useAsync, useGzip, chunkSize, compressed, data); } } /// <summary> /// Given a MemoryStream of compressed data and a byte array of desired output, decompresses /// the stream and validates that it is equal to the expected array. /// </summary> private async Task ValidateCompressedData(bool useAsync, bool useGzip, int chunkSize, MemoryStream compressed, byte[] expected) { using (MemoryStream decompressed = new MemoryStream()) using (Stream decompressor = useGzip ? (Stream)new GZipStream(compressed, CompressionMode.Decompress, true) : new DeflateStream(compressed, CompressionMode.Decompress, true)) { if (useAsync) decompressor.CopyTo(decompressed, chunkSize); else await decompressor.CopyToAsync(decompressed, chunkSize, CancellationToken.None); Assert.Equal<byte>(expected, decompressed.ToArray()); } } [Fact] public void SequentialReadsOnMemoryStream_Return_SameBytes() { byte[] data = new byte[1024 * 10]; new Random(42).NextBytes(data); var compressed = new MemoryStream(); using (var compressor = new DeflateStream(compressed, CompressionMode.Compress, true)) { for (int i = 0; i < data.Length; i += 1024) { compressor.Write(data, i, 1024); } } compressed.Position = 0; using (var decompressor = new DeflateStream(compressed, CompressionMode.Decompress, true)) { int i, j; byte[] array = new byte[100]; byte[] array2 = new byte[100]; // only read in the first 100 bytes decompressor.Read(array, 0, array.Length); for (i = 0; i < array.Length; i++) Assert.Equal(data[i], array[i]); // read in the next 100 bytes and make sure nothing is missing decompressor.Read(array2, 0, array2.Length); for (j = 0; j < array2.Length; j++) Assert.Equal(data[j], array[j]); } } [Fact] public void Roundtrip_Write_ReadByte() { byte[] data = new byte[1024 * 10]; new Random(42).NextBytes(data); var compressed = new MemoryStream(); using (var compressor = new DeflateStream(compressed, CompressionMode.Compress, true)) { compressor.Write(data, 0, data.Length); } compressed.Position = 0; using (var decompressor = new DeflateStream(compressed, CompressionMode.Decompress, true)) { for (int i = 0; i < data.Length; i++) Assert.Equal(data[i], decompressor.ReadByte()); } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Full Framework Flush is a no-op.")] public async Task WrapNullReturningTasksStream() { using (var ds = new DeflateStream(new BadWrappedStream(BadWrappedStream.Mode.ReturnNullTasks), CompressionMode.Decompress)) await Assert.ThrowsAsync<InvalidOperationException>(() => ds.ReadAsync(new byte[1024], 0, 1024)); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Full Framework Flush is a no-op.")] public async Task WrapStreamReturningBadReadValues() { using (var ds = new DeflateStream(new BadWrappedStream(BadWrappedStream.Mode.ReturnTooLargeCounts), CompressionMode.Decompress)) Assert.Throws<InvalidDataException>(() => ds.Read(new byte[1024], 0, 1024)); using (var ds = new DeflateStream(new BadWrappedStream(BadWrappedStream.Mode.ReturnTooLargeCounts), CompressionMode.Decompress)) await Assert.ThrowsAsync<InvalidDataException>(() => ds.ReadAsync(new byte[1024], 0, 1024)); using (var ds = new DeflateStream(new BadWrappedStream(BadWrappedStream.Mode.ReturnTooSmallCounts), CompressionMode.Decompress)) Assert.Equal(0, ds.Read(new byte[1024], 0, 1024)); using (var ds = new DeflateStream(new BadWrappedStream(BadWrappedStream.Mode.ReturnTooSmallCounts), CompressionMode.Decompress)) Assert.Equal(0, await ds.ReadAsync(new byte[1024], 0, 1024)); } public static IEnumerable<object[]> CopyToAsync_Roundtrip_OutputMatchesInput_MemberData() { var rand = new Random(); foreach (int dataSize in new[] { 1, 1024, 4095, 1024 * 1024 }) { var data = new byte[dataSize]; rand.NextBytes(data); var compressed = new MemoryStream(); using (var ds = new DeflateStream(compressed, CompressionMode.Compress, leaveOpen: true)) { ds.Write(data, 0, data.Length); } byte[] compressedData = compressed.ToArray(); foreach (int copyBufferSize in new[] { 1, 4096, 80 * 1024 }) { // Memory source var m = new MemoryStream(compressedData, writable: false); yield return new object[] { data, copyBufferSize, m }; // File sources, sync and async foreach (bool useAsync in new[] { true, false }) { string path = Path.GetTempFileName(); File.WriteAllBytes(path, compressedData); FileOptions options = FileOptions.DeleteOnClose; if (useAsync) options |= FileOptions.Asynchronous; yield return new object[] { data, copyBufferSize, new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 0x1000, options) }; } } } } [Theory] [MemberData(nameof(CopyToAsync_Roundtrip_OutputMatchesInput_MemberData))] public async Task CopyToAsync_Roundtrip_OutputMatchesInput(byte[] expectedDecrypted, int copyBufferSize, Stream source) { var m = new MemoryStream(); using (DeflateStream ds = new DeflateStream(source, CompressionMode.Decompress)) { await ds.CopyToAsync(m); } Assert.Equal(expectedDecrypted, m.ToArray()); } private sealed class BadWrappedStream : Stream { public enum Mode { Default, ReturnNullTasks, ReturnTooSmallCounts, ReturnTooLargeCounts, } private readonly Mode _mode; public BadWrappedStream(Mode mode) { _mode = mode; } public override int Read(byte[] buffer, int offset, int count) { switch (_mode) { case Mode.ReturnTooSmallCounts: return -1; case Mode.ReturnTooLargeCounts: return buffer.Length + 1; default: return 0; } } public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { return _mode == Mode.ReturnNullTasks ? null : base.ReadAsync(buffer, offset, count, cancellationToken); } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { return _mode == Mode.ReturnNullTasks ? null : base.WriteAsync(buffer, offset, count, cancellationToken); } public override void Write(byte[] buffer, int offset, int count) { } public override void Flush() { } public override bool CanRead { get { return true; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return true; } } public override long Length { get { throw new NotSupportedException(); } } public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); } } } public class ManualSyncMemoryStream : MemoryStream { private bool isSync; public ManualResetEventSlim manualResetEvent = new ManualResetEventSlim(initialState: false); public bool ReadHit = false; // For validation of the async methods we want to ensure they correctly delegate the async public bool WriteHit = false; // methods of the underlying stream. This bool acts as a toggle to check that they're being used. public static async Task<ManualSyncMemoryStream> GetStreamFromFileAsync(string testFile, bool sync = false, bool strip = false) { var baseStream = await StreamHelpers.CreateTempCopyStream(testFile); if (strip) { baseStream = StripHeaderAndFooter.Strip(baseStream); } var ms = new ManualSyncMemoryStream(sync); await baseStream.CopyToAsync(ms); ms.Position = 0; return ms; } public ManualSyncMemoryStream(bool sync = false) : base() { isSync = sync; } public override async Task<int> ReadAsync(byte[] array, int offset, int count, CancellationToken cancellationToken) { ReadHit = true; if (isSync) { manualResetEvent.Wait(cancellationToken); } else { await Task.Run(() => manualResetEvent.Wait(cancellationToken)); } return await base.ReadAsync(array, offset, count, cancellationToken); } public override async Task WriteAsync(byte[] array, int offset, int count, CancellationToken cancellationToken) { WriteHit = true; if (isSync) { manualResetEvent.Wait(cancellationToken); } else { await Task.Run(() => manualResetEvent.Wait(cancellationToken)); } await base.WriteAsync(array, offset, count, cancellationToken); } } }
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 MVCServer.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; } } }
#region Copyright notice and license // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using Google.Protobuf.Collections; using Google.Protobuf.WellKnownTypes; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using System.Threading; using static Google.Protobuf.Reflection.SourceCodeInfo.Types; namespace Google.Protobuf.Reflection { /// <summary> /// The syntax of a .proto file /// </summary> public enum Syntax { /// <summary> /// Proto2 syntax /// </summary> Proto2, /// <summary> /// Proto3 syntax /// </summary> Proto3, /// <summary> /// An unknown declared syntax /// </summary> Unknown } /// <summary> /// Describes a .proto file, including everything defined within. /// IDescriptor is implemented such that the File property returns this descriptor, /// and the FullName is the same as the Name. /// </summary> public sealed class FileDescriptor : IDescriptor { // Prevent linker failures when using IL2CPP with the well-known types. static FileDescriptor() { ForceReflectionInitialization<Syntax>(); ForceReflectionInitialization<NullValue>(); ForceReflectionInitialization<Field.Types.Cardinality>(); ForceReflectionInitialization<Field.Types.Kind>(); ForceReflectionInitialization<Value.KindOneofCase>(); } private readonly Lazy<Dictionary<IDescriptor, DescriptorDeclaration>> declarations; private FileDescriptor(ByteString descriptorData, FileDescriptorProto proto, IEnumerable<FileDescriptor> dependencies, DescriptorPool pool, bool allowUnknownDependencies, GeneratedClrTypeInfo generatedCodeInfo) { SerializedData = descriptorData; DescriptorPool = pool; Proto = proto; Dependencies = new ReadOnlyCollection<FileDescriptor>(dependencies.ToList()); PublicDependencies = DeterminePublicDependencies(this, proto, dependencies, allowUnknownDependencies); pool.AddPackage(Package, this); MessageTypes = DescriptorUtil.ConvertAndMakeReadOnly(proto.MessageType, (message, index) => new MessageDescriptor(message, this, null, index, generatedCodeInfo?.NestedTypes[index])); EnumTypes = DescriptorUtil.ConvertAndMakeReadOnly(proto.EnumType, (enumType, index) => new EnumDescriptor(enumType, this, null, index, generatedCodeInfo?.NestedEnums[index])); Services = DescriptorUtil.ConvertAndMakeReadOnly(proto.Service, (service, index) => new ServiceDescriptor(service, this, index)); Extensions = new ExtensionCollection(this, generatedCodeInfo?.Extensions); declarations = new Lazy<Dictionary<IDescriptor, DescriptorDeclaration>>(CreateDeclarationMap, LazyThreadSafetyMode.ExecutionAndPublication); if (!proto.HasSyntax || proto.Syntax == "proto2") { Syntax = Syntax.Proto2; } else if (proto.Syntax == "proto3") { Syntax = Syntax.Proto3; } else { Syntax = Syntax.Unknown; } } private Dictionary<IDescriptor, DescriptorDeclaration> CreateDeclarationMap() { var dictionary = new Dictionary<IDescriptor, DescriptorDeclaration>(); foreach (var location in Proto.SourceCodeInfo?.Location ?? Enumerable.Empty<Location>()) { var descriptor = FindDescriptorForPath(location.Path); if (descriptor != null) { dictionary[descriptor] = DescriptorDeclaration.FromProto(descriptor, location); } } return dictionary; } private IDescriptor FindDescriptorForPath(IList<int> path) { // All complete declarations have an even, non-empty path length // (There can be an empty path for a descriptor declaration, but that can't have any comments, // so we currently ignore it.) if (path.Count == 0 || (path.Count & 1) != 0) { return null; } IReadOnlyList<DescriptorBase> topLevelList = GetNestedDescriptorListForField(path[0]); DescriptorBase current = GetDescriptorFromList(topLevelList, path[1]); for (int i = 2; current != null && i < path.Count; i += 2) { var list = current.GetNestedDescriptorListForField(path[i]); current = GetDescriptorFromList(list, path[i + 1]); } return current; } private DescriptorBase GetDescriptorFromList(IReadOnlyList<DescriptorBase> list, int index) { // This is fine: it may be a newer version of protobuf than we understand, with a new descriptor // field. if (list == null) { return null; } // We *could* return null to silently continue, but this is basically data corruption. if (index < 0 || index >= list.Count) { // We don't have much extra information to give at this point unfortunately. If this becomes a problem, // we can pass in the complete path and report that and the file name. throw new InvalidProtocolBufferException($"Invalid descriptor location path: index out of range"); } return list[index]; } private IReadOnlyList<DescriptorBase> GetNestedDescriptorListForField(int fieldNumber) { switch (fieldNumber) { case FileDescriptorProto.ServiceFieldNumber: return (IReadOnlyList<DescriptorBase>) Services; case FileDescriptorProto.MessageTypeFieldNumber: return (IReadOnlyList<DescriptorBase>) MessageTypes; case FileDescriptorProto.EnumTypeFieldNumber: return (IReadOnlyList<DescriptorBase>) EnumTypes; default: return null; } } internal DescriptorDeclaration GetDeclaration(IDescriptor descriptor) { DescriptorDeclaration declaration; declarations.Value.TryGetValue(descriptor, out declaration); return declaration; } /// <summary> /// Computes the full name of a descriptor within this file, with an optional parent message. /// </summary> internal string ComputeFullName(MessageDescriptor parent, string name) { if (parent != null) { return parent.FullName + "." + name; } if (Package.Length > 0) { return Package + "." + name; } return name; } /// <summary> /// Extracts public dependencies from direct dependencies. This is a static method despite its /// first parameter, as the value we're in the middle of constructing is only used for exceptions. /// </summary> private static IList<FileDescriptor> DeterminePublicDependencies(FileDescriptor @this, FileDescriptorProto proto, IEnumerable<FileDescriptor> dependencies, bool allowUnknownDependencies) { var nameToFileMap = dependencies.ToDictionary(file => file.Name); var publicDependencies = new List<FileDescriptor>(); for (int i = 0; i < proto.PublicDependency.Count; i++) { int index = proto.PublicDependency[i]; if (index < 0 || index >= proto.Dependency.Count) { throw new DescriptorValidationException(@this, "Invalid public dependency index."); } string name = proto.Dependency[index]; FileDescriptor file; if (!nameToFileMap.TryGetValue(name, out file)) { if (!allowUnknownDependencies) { throw new DescriptorValidationException(@this, "Invalid public dependency: " + name); } // Ignore unknown dependencies. } else { publicDependencies.Add(file); } } return new ReadOnlyCollection<FileDescriptor>(publicDependencies); } /// <value> /// The descriptor in its protocol message representation. /// </value> internal FileDescriptorProto Proto { get; } /// <summary> /// The syntax of the file /// </summary> public Syntax Syntax { get; } /// <value> /// The file name. /// </value> public string Name => Proto.Name; /// <summary> /// The package as declared in the .proto file. This may or may not /// be equivalent to the .NET namespace of the generated classes. /// </summary> public string Package => Proto.Package; /// <value> /// Unmodifiable list of top-level message types declared in this file. /// </value> public IList<MessageDescriptor> MessageTypes { get; } /// <value> /// Unmodifiable list of top-level enum types declared in this file. /// </value> public IList<EnumDescriptor> EnumTypes { get; } /// <value> /// Unmodifiable list of top-level services declared in this file. /// </value> public IList<ServiceDescriptor> Services { get; } /// <summary> /// Unmodifiable list of top-level extensions declared in this file. /// Note that some extensions may be incomplete (FieldDescriptor.Extension may be null) /// if this descriptor was generated using a version of protoc that did not fully /// support extensions in C#. /// </summary> public ExtensionCollection Extensions { get; } /// <value> /// Unmodifiable list of this file's dependencies (imports). /// </value> public IList<FileDescriptor> Dependencies { get; } /// <value> /// Unmodifiable list of this file's public dependencies (public imports). /// </value> public IList<FileDescriptor> PublicDependencies { get; } /// <value> /// The original serialized binary form of this descriptor. /// </value> public ByteString SerializedData { get; } /// <value> /// Implementation of IDescriptor.FullName - just returns the same as Name. /// </value> string IDescriptor.FullName => Name; /// <value> /// Implementation of IDescriptor.File - just returns this descriptor. /// </value> FileDescriptor IDescriptor.File => this; /// <value> /// Pool containing symbol descriptors. /// </value> internal DescriptorPool DescriptorPool { get; } /// <summary> /// Finds a type (message, enum, service or extension) in the file by name. Does not find nested types. /// </summary> /// <param name="name">The unqualified type name to look for.</param> /// <typeparam name="T">The type of descriptor to look for</typeparam> /// <returns>The type's descriptor, or null if not found.</returns> public T FindTypeByName<T>(String name) where T : class, IDescriptor { // Don't allow looking up nested types. This will make optimization // easier later. if (name.IndexOf('.') != -1) { return null; } if (Package.Length > 0) { name = Package + "." + name; } T result = DescriptorPool.FindSymbol<T>(name); if (result != null && result.File == this) { return result; } return null; } /// <summary> /// Builds a FileDescriptor from its protocol buffer representation. /// </summary> /// <param name="descriptorData">The original serialized descriptor data. /// We have only limited proto2 support, so serializing FileDescriptorProto /// would not necessarily give us this.</param> /// <param name="proto">The protocol message form of the FileDescriptor.</param> /// <param name="dependencies">FileDescriptors corresponding to all of the /// file's dependencies, in the exact order listed in the .proto file. May be null, /// in which case it is treated as an empty array.</param> /// <param name="allowUnknownDependencies">Whether unknown dependencies are ignored (true) or cause an exception to be thrown (false).</param> /// <param name="generatedCodeInfo">Details about generated code, for the purposes of reflection.</param> /// <exception cref="DescriptorValidationException">If <paramref name="proto"/> is not /// a valid descriptor. This can occur for a number of reasons, such as a field /// having an undefined type or because two messages were defined with the same name.</exception> private static FileDescriptor BuildFrom(ByteString descriptorData, FileDescriptorProto proto, FileDescriptor[] dependencies, bool allowUnknownDependencies, GeneratedClrTypeInfo generatedCodeInfo) { // Building descriptors involves two steps: translating and linking. // In the translation step (implemented by FileDescriptor's // constructor), we build an object tree mirroring the // FileDescriptorProto's tree and put all of the descriptors into the // DescriptorPool's lookup tables. In the linking step, we look up all // type references in the DescriptorPool, so that, for example, a // FieldDescriptor for an embedded message contains a pointer directly // to the Descriptor for that message's type. We also detect undefined // types in the linking step. if (dependencies == null) { dependencies = new FileDescriptor[0]; } DescriptorPool pool = new DescriptorPool(dependencies); FileDescriptor result = new FileDescriptor(descriptorData, proto, dependencies, pool, allowUnknownDependencies, generatedCodeInfo); // Validate that the dependencies we've been passed (as FileDescriptors) are actually the ones we // need. if (dependencies.Length != proto.Dependency.Count) { throw new DescriptorValidationException( result, "Dependencies passed to FileDescriptor.BuildFrom() don't match " + "those listed in the FileDescriptorProto."); } result.CrossLink(); return result; } private void CrossLink() { foreach (MessageDescriptor message in MessageTypes) { message.CrossLink(); } foreach (ServiceDescriptor service in Services) { service.CrossLink(); } Extensions.CrossLink(); } /// <summary> /// Creates a descriptor for generated code. /// </summary> /// <remarks> /// This method is only designed to be used by the results of generating code with protoc, /// which creates the appropriate dependencies etc. It has to be public because the generated /// code is "external", but should not be called directly by end users. /// </remarks> public static FileDescriptor FromGeneratedCode( byte[] descriptorData, FileDescriptor[] dependencies, GeneratedClrTypeInfo generatedCodeInfo) { ExtensionRegistry registry = new ExtensionRegistry(); registry.AddRange(GetAllExtensions(dependencies, generatedCodeInfo)); FileDescriptorProto proto; try { proto = FileDescriptorProto.Parser.WithExtensionRegistry(registry).ParseFrom(descriptorData); } catch (InvalidProtocolBufferException e) { throw new ArgumentException("Failed to parse protocol buffer descriptor for generated code.", e); } try { // When building descriptors for generated code, we allow unknown // dependencies by default. return BuildFrom(ByteString.CopyFrom(descriptorData), proto, dependencies, true, generatedCodeInfo); } catch (DescriptorValidationException e) { throw new ArgumentException($"Invalid embedded descriptor for \"{proto.Name}\".", e); } } private static IEnumerable<Extension> GetAllExtensions(FileDescriptor[] dependencies, GeneratedClrTypeInfo generatedInfo) { return dependencies.SelectMany(GetAllDependedExtensions).Distinct(ExtensionRegistry.ExtensionComparer.Instance).Concat(GetAllGeneratedExtensions(generatedInfo)); } private static IEnumerable<Extension> GetAllGeneratedExtensions(GeneratedClrTypeInfo generated) { return generated.Extensions.Concat(generated.NestedTypes.Where(t => t != null).SelectMany(GetAllGeneratedExtensions)); } private static IEnumerable<Extension> GetAllDependedExtensions(FileDescriptor descriptor) { return descriptor.Extensions.UnorderedExtensions .Select(s => s.Extension) .Where(e => e != null) .Concat(descriptor.Dependencies.Concat(descriptor.PublicDependencies).SelectMany(GetAllDependedExtensions)) .Concat(descriptor.MessageTypes.SelectMany(GetAllDependedExtensionsFromMessage)); } private static IEnumerable<Extension> GetAllDependedExtensionsFromMessage(MessageDescriptor descriptor) { return descriptor.Extensions.UnorderedExtensions .Select(s => s.Extension) .Where(e => e != null) .Concat(descriptor.NestedTypes.SelectMany(GetAllDependedExtensionsFromMessage)); } /// <summary> /// Converts the given descriptor binary data into FileDescriptor objects. /// Note: reflection using the returned FileDescriptors is not currently supported. /// </summary> /// <param name="descriptorData">The binary file descriptor proto data. Must not be null, and any /// dependencies must come before the descriptor which depends on them. (If A depends on B, and B /// depends on C, then the descriptors must be presented in the order C, B, A.) This is compatible /// with the order in which protoc provides descriptors to plugins.</param> /// <param name="registry">The extension registry to use when parsing, or null if no extensions are required.</param> /// <returns>The file descriptors corresponding to <paramref name="descriptorData"/>.</returns> public static IReadOnlyList<FileDescriptor> BuildFromByteStrings(IEnumerable<ByteString> descriptorData, ExtensionRegistry registry) { ProtoPreconditions.CheckNotNull(descriptorData, nameof(descriptorData)); var parser = FileDescriptorProto.Parser.WithExtensionRegistry(registry); // TODO: See if we can build a single DescriptorPool instead of building lots of them. // This will all behave correctly, but it's less efficient than we'd like. var descriptors = new List<FileDescriptor>(); var descriptorsByName = new Dictionary<string, FileDescriptor>(); foreach (var data in descriptorData) { var proto = parser.ParseFrom(data); var dependencies = new List<FileDescriptor>(); foreach (var dependencyName in proto.Dependency) { FileDescriptor dependency; if (!descriptorsByName.TryGetValue(dependencyName, out dependency)) { throw new ArgumentException($"Dependency missing: {dependencyName}"); } dependencies.Add(dependency); } var pool = new DescriptorPool(dependencies); FileDescriptor descriptor = new FileDescriptor( data, proto, dependencies, pool, allowUnknownDependencies: false, generatedCodeInfo: null); descriptor.CrossLink(); descriptors.Add(descriptor); if (descriptorsByName.ContainsKey(descriptor.Name)) { throw new ArgumentException($"Duplicate descriptor name: {descriptor.Name}"); } descriptorsByName.Add(descriptor.Name, descriptor); } return new ReadOnlyCollection<FileDescriptor>(descriptors); } /// <summary> /// Converts the given descriptor binary data into FileDescriptor objects. /// Note: reflection using the returned FileDescriptors is not currently supported. /// </summary> /// <param name="descriptorData">The binary file descriptor proto data. Must not be null, and any /// dependencies must come before the descriptor which depends on them. (If A depends on B, and B /// depends on C, then the descriptors must be presented in the order C, B, A.) This is compatible /// with the order in which protoc provides descriptors to plugins.</param> /// <returns>The file descriptors corresponding to <paramref name="descriptorData"/>.</returns> public static IReadOnlyList<FileDescriptor> BuildFromByteStrings(IEnumerable<ByteString> descriptorData) => BuildFromByteStrings(descriptorData, null); /// <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 $"FileDescriptor for {Name}"; } /// <summary> /// Returns the file descriptor for descriptor.proto. /// </summary> /// <remarks> /// This is used for protos which take a direct dependency on <c>descriptor.proto</c>, typically for /// annotations. While <c>descriptor.proto</c> is a proto2 file, it is built into the Google.Protobuf /// runtime for reflection purposes. The messages are internal to the runtime as they would require /// proto2 semantics for full support, but the file descriptor is available via this property. The /// C# codegen in protoc automatically uses this property when it detects a dependency on <c>descriptor.proto</c>. /// </remarks> /// <value> /// The file descriptor for <c>descriptor.proto</c>. /// </value> public static FileDescriptor DescriptorProtoFileDescriptor { get { return DescriptorReflection.Descriptor; } } /// <summary> /// The (possibly empty) set of custom options for this file. /// </summary> [Obsolete("CustomOptions are obsolete. Use the GetOptions() method.")] public CustomOptions CustomOptions => new CustomOptions(Proto.Options?._extensions?.ValuesByNumber); /// <summary> /// The <c>FileOptions</c>, defined in <c>descriptor.proto</c>. /// If the options message is not present (i.e. there are no options), <c>null</c> is returned. /// Custom options can be retrieved as extensions of the returned message. /// NOTE: A defensive copy is created each time this property is retrieved. /// </summary> public FileOptions GetOptions() => Proto.Options?.Clone(); /// <summary> /// Gets a single value file option for this descriptor /// </summary> [Obsolete("GetOption is obsolete. Use the GetOptions() method.")] public T GetOption<T>(Extension<FileOptions, T> extension) { var value = Proto.Options.GetExtension(extension); return value is IDeepCloneable<T> ? (value as IDeepCloneable<T>).Clone() : value; } /// <summary> /// Gets a repeated value file option for this descriptor /// </summary> [Obsolete("GetOption is obsolete. Use the GetOptions() method.")] public RepeatedField<T> GetOption<T>(RepeatedExtension<FileOptions, T> extension) { return Proto.Options.GetExtension(extension).Clone(); } /// <summary> /// Performs initialization for the given generic type argument. /// </summary> /// <remarks> /// This method is present for the sake of AOT compilers. It allows code (whether handwritten or generated) /// to make calls into the reflection machinery of this library to express an intention to use that type /// reflectively (e.g. for JSON parsing and formatting). The call itself does almost nothing, but AOT compilers /// attempting to determine which generic type arguments need to be handled will spot the code path and act /// accordingly. /// </remarks> /// <typeparam name="T">The type to force initialization for.</typeparam> public static void ForceReflectionInitialization<T>() => ReflectionUtil.ForceInitialize<T>(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Globalization { using System; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using Microsoft.Win32; using PermissionSet = System.Security.PermissionSet; using System.Security.Permissions; /*=================================JapaneseCalendar========================== ** ** JapaneseCalendar is based on Gregorian calendar. The month and day values are the same as ** Gregorian calendar. However, the year value is an offset to the Gregorian ** year based on the era. ** ** This system is adopted by Emperor Meiji in 1868. The year value is counted based on the reign of an emperor, ** and the era begins on the day an emperor ascends the throne and continues until his death. ** The era changes at 12:00AM. ** ** For example, the current era is Heisei. It started on 1989/1/8 A.D. Therefore, Gregorian year 1989 is also Heisei 1st. ** 1989/1/8 A.D. is also Heisei 1st 1/8. ** ** Any date in the year during which era is changed can be reckoned in either era. For example, ** 1989/1/1 can be 1/1 Heisei 1st year or 1/1 Showa 64th year. ** ** Note: ** The DateTime can be represented by the JapaneseCalendar are limited to two factors: ** 1. The min value and max value of DateTime class. ** 2. The available era information. ** ** Calendar support range: ** Calendar Minimum Maximum ** ========== ========== ========== ** Gregorian 1868/09/08 9999/12/31 ** Japanese Meiji 01/01 Heisei 8011/12/31 ============================================================================*/ [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public class JapaneseCalendar : Calendar { internal static readonly DateTime calendarMinValue = new DateTime(1868, 9, 8); [System.Runtime.InteropServices.ComVisible(false)] public override DateTime MinSupportedDateTime { get { return (calendarMinValue); } } [System.Runtime.InteropServices.ComVisible(false)] public override DateTime MaxSupportedDateTime { get { return (DateTime.MaxValue); } } // Return the type of the Japanese calendar. // [System.Runtime.InteropServices.ComVisible(false)] public override CalendarAlgorithmType AlgorithmType { get { return CalendarAlgorithmType.SolarCalendar; } } // // Using a field initializer rather than a static constructor so that the whole class can be lazy // init. static internal volatile EraInfo[] japaneseEraInfo; // // Read our era info // // m_EraInfo must be listed in reverse chronological order. The most recent era // should be the first element. // That is, m_EraInfo[0] contains the most recent era. // // We know about 4 built-in eras, however users may add additional era(s) from the // registry, by adding values to HKLM\SYSTEM\CurrentControlSet\Control\Nls\Calendars\Japanese\Eras // // Registry values look like: // yyyy.mm.dd=era_abbrev_english_englishabbrev // // Where yyyy.mm.dd is the registry value name, and also the date of the era start. // yyyy, mm, and dd are the year, month & day the era begins (4, 2 & 2 digits long) // era is the Japanese Era name // abbrev is the Abbreviated Japanese Era Name // english is the English name for the Era (unused) // englishabbrev is the Abbreviated English name for the era. // . is a delimiter, but the value of . doesn't matter. // '_' marks the space between the japanese era name, japanese abbreviated era name // english name, and abbreviated english names. // internal static EraInfo[] GetEraInfo() { // See if we need to build it if (japaneseEraInfo == null) { // See if we have any eras from the registry japaneseEraInfo = GetErasFromRegistry(); // See if we have to use the built-in eras if (japaneseEraInfo == null) { // We know about some built-in ranges EraInfo[] defaultEraRanges = new EraInfo[4]; defaultEraRanges[0] = new EraInfo( 4, 1989, 1, 8, 1988, 1, GregorianCalendar.MaxYear - 1988, "\x5e73\x6210", "\x5e73", "H"); // era #4 start year/month/day, yearOffset, minEraYear defaultEraRanges[1] = new EraInfo( 3, 1926, 12, 25, 1925, 1, 1989-1925, "\x662d\x548c", "\x662d", "S"); // era #3,start year/month/day, yearOffset, minEraYear defaultEraRanges[2] = new EraInfo( 2, 1912, 7, 30, 1911, 1, 1926-1911, "\x5927\x6b63", "\x5927", "T"); // era #2,start year/month/day, yearOffset, minEraYear defaultEraRanges[3] = new EraInfo( 1, 1868, 1, 1, 1867, 1, 1912-1867, "\x660e\x6cbb", "\x660e", "M"); // era #1,start year/month/day, yearOffset, minEraYear // Remember the ranges we built japaneseEraInfo = defaultEraRanges; } } // return the era we found/made return japaneseEraInfo; } #if FEATURE_WIN32_REGISTRY private const string c_japaneseErasHive = @"System\CurrentControlSet\Control\Nls\Calendars\Japanese\Eras"; private const string c_japaneseErasHivePermissionList = @"HKEY_LOCAL_MACHINE\" + c_japaneseErasHive; // // GetErasFromRegistry() // // We know about 4 built-in eras, however users may add additional era(s) from the // registry, by adding values to HKLM\SYSTEM\CurrentControlSet\Control\Nls\Calendars\Japanese\Eras // // Registry values look like: // yyyy.mm.dd=era_abbrev_english_englishabbrev // // Where yyyy.mm.dd is the registry value name, and also the date of the era start. // yyyy, mm, and dd are the year, month & day the era begins (4, 2 & 2 digits long) // era is the Japanese Era name // abbrev is the Abbreviated Japanese Era Name // english is the English name for the Era (unused) // englishabbrev is the Abbreviated English name for the era. // . is a delimiter, but the value of . doesn't matter. // '_' marks the space between the japanese era name, japanese abbreviated era name // english name, and abbreviated english names. private static EraInfo[] GetErasFromRegistry() { // Look in the registry key and see if we can find any ranges int iFoundEras = 0; EraInfo[] registryEraRanges = null; try { // Need to access registry PermissionSet permSet = new PermissionSet(PermissionState.None); permSet.AddPermission(new RegistryPermission(RegistryPermissionAccess.Read, c_japaneseErasHivePermissionList)); permSet.Assert(); RegistryKey key = Registry.LocalMachine.OpenSubKey(c_japaneseErasHive, writable: false); // Abort if we didn't find anything if (key == null) return null; // Look up the values in our reg key String[] valueNames = key.GetValueNames(); if (valueNames != null && valueNames.Length > 0) { registryEraRanges = new EraInfo[valueNames.Length]; // Loop through the registry and read in all the values for (int i = 0; i < valueNames.Length; i++) { // See if the era is a valid date EraInfo era = GetEraFromValue(valueNames[i], key.GetValue(valueNames[i]).ToString()); // continue if not valid if (era == null) continue; // Remember we found one. registryEraRanges[iFoundEras] = era; iFoundEras++; } } } catch (System.Security.SecurityException) { // If we weren't allowed to read, then just ignore the error return null; } catch (System.IO.IOException) { // If key is being deleted just ignore the error return null; } catch (System.UnauthorizedAccessException) { // Registry access rights permissions, just ignore the error return null; } // // If we didn't have valid eras, then fail // should have at least 4 eras // if (iFoundEras < 4) return null; // // Now we have eras, clean them up. // // Clean up array length Array.Resize(ref registryEraRanges, iFoundEras); // Sort them Array.Sort(registryEraRanges, CompareEraRanges); // Clean up era information for (int i = 0; i < registryEraRanges.Length; i++) { // eras count backwards from length to 1 (and are 1 based indexes into string arrays) registryEraRanges[i].era = registryEraRanges.Length - i; // update max era year if (i == 0) { // First range is 'til the end of the calendar registryEraRanges[0].maxEraYear = GregorianCalendar.MaxYear - registryEraRanges[0].yearOffset; } else { // Rest are until the next era (remember most recent era is first in array) registryEraRanges[i].maxEraYear = registryEraRanges[i-1].yearOffset + 1 - registryEraRanges[i].yearOffset; } } // Return our ranges return registryEraRanges; } #else private static EraInfo[] GetErasFromRegistry() { return null; } #endif // // Compare two era ranges, eg just the ticks // Remember the era array is supposed to be in reverse chronological order // private static int CompareEraRanges(EraInfo a, EraInfo b) { return b.ticks.CompareTo(a.ticks); } // // GetEraFromValue // // Parse the registry value name/data pair into an era // // Registry values look like: // yyyy.mm.dd=era_abbrev_english_englishabbrev // // Where yyyy.mm.dd is the registry value name, and also the date of the era start. // yyyy, mm, and dd are the year, month & day the era begins (4, 2 & 2 digits long) // era is the Japanese Era name // abbrev is the Abbreviated Japanese Era Name // english is the English name for the Era (unused) // englishabbrev is the Abbreviated English name for the era. // . is a delimiter, but the value of . doesn't matter. // '_' marks the space between the japanese era name, japanese abbreviated era name // english name, and abbreviated english names. private static EraInfo GetEraFromValue(String value, String data) { // Need inputs if (value == null || data == null) return null; // // Get Date // // Need exactly 10 characters in name for date // yyyy.mm.dd although the . can be any character if (value.Length != 10) return null; int year; int month; int day; if (!Number.TryParseInt32(value.Substring(0,4), NumberStyles.None, NumberFormatInfo.InvariantInfo, out year) || !Number.TryParseInt32(value.Substring(5,2), NumberStyles.None, NumberFormatInfo.InvariantInfo, out month) || !Number.TryParseInt32(value.Substring(8,2), NumberStyles.None, NumberFormatInfo.InvariantInfo, out day)) { // Couldn't convert integer, fail return null; } // // Get Strings // // Needs to be a certain length e_a_E_A at least (7 chars, exactly 4 groups) String[] names = data.Split('_'); // Should have exactly 4 parts // 0 - Era Name // 1 - Abbreviated Era Name // 2 - English Era Name // 3 - Abbreviated English Era Name if (names.Length != 4) return null; // Each part should have data in it if (names[0].Length == 0 || names[1].Length == 0 || names[2].Length == 0 || names[3].Length == 0) return null; // // Now we have an era we can build // Note that the era # and max era year need cleaned up after sorting // Don't use the full English Era Name (names[2]) // return new EraInfo( 0, year, month, day, year - 1, 1, 0, names[0], names[1], names[3]); } internal static volatile Calendar s_defaultInstance; internal GregorianCalendarHelper helper; /*=================================GetDefaultInstance========================== **Action: Internal method to provide a default intance of JapaneseCalendar. Used by NLS+ implementation ** and other calendars. **Returns: **Arguments: **Exceptions: ============================================================================*/ internal static Calendar GetDefaultInstance() { if (s_defaultInstance == null) { s_defaultInstance = new JapaneseCalendar(); } return (s_defaultInstance); } public JapaneseCalendar() { try { new CultureInfo("ja-JP"); } catch (ArgumentException e) { throw new TypeInitializationException(this.GetType().FullName, e); } helper = new GregorianCalendarHelper(this, GetEraInfo()); } internal override int ID { get { return (CAL_JAPAN); } } public override DateTime AddMonths(DateTime time, int months) { return (helper.AddMonths(time, months)); } public override DateTime AddYears(DateTime time, int years) { return (helper.AddYears(time, years)); } /*=================================GetDaysInMonth========================== **Action: Returns the number of days in the month given by the year and month arguments. **Returns: The number of days in the given month. **Arguments: ** year The year in Japanese calendar. ** month The month ** era The Japanese era value. **Exceptions ** ArgumentException If month is less than 1 or greater * than 12. ============================================================================*/ public override int GetDaysInMonth(int year, int month, int era) { return (helper.GetDaysInMonth(year, month, era)); } public override int GetDaysInYear(int year, int era) { return (helper.GetDaysInYear(year, era)); } public override int GetDayOfMonth(DateTime time) { return (helper.GetDayOfMonth(time)); } public override DayOfWeek GetDayOfWeek(DateTime time) { return (helper.GetDayOfWeek(time)); } public override int GetDayOfYear(DateTime time) { return (helper.GetDayOfYear(time)); } public override int GetMonthsInYear(int year, int era) { return (helper.GetMonthsInYear(year, era)); } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. [System.Runtime.InteropServices.ComVisible(false)] public override int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek) { return (helper.GetWeekOfYear(time, rule, firstDayOfWeek)); } /*=================================GetEra========================== **Action: Get the era value of the specified time. **Returns: The era value for the specified time. **Arguments: ** time the specified date time. **Exceptions: ArgumentOutOfRangeException if time is out of the valid era ranges. ============================================================================*/ public override int GetEra(DateTime time) { return (helper.GetEra(time)); } public override int GetMonth(DateTime time) { return (helper.GetMonth(time)); } public override int GetYear(DateTime time) { return (helper.GetYear(time)); } public override bool IsLeapDay(int year, int month, int day, int era) { return (helper.IsLeapDay(year, month, day, era)); } public override bool IsLeapYear(int year, int era) { return (helper.IsLeapYear(year, era)); } // Returns the leap month in a calendar year of the specified era. This method returns 0 // if this calendar does not have leap month, or this year is not a leap year. // [System.Runtime.InteropServices.ComVisible(false)] public override int GetLeapMonth(int year, int era) { return (helper.GetLeapMonth(year, era)); } public override bool IsLeapMonth(int year, int month, int era) { return (helper.IsLeapMonth(year, month, era)); } public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { return (helper.ToDateTime(year, month, day, hour, minute, second, millisecond, era)); } // For Japanese calendar, four digit year is not used. Few emperors will live for more than one hundred years. // Therefore, for any two digit number, we just return the original number. public override int ToFourDigitYear(int year) { if (year <= 0) { throw new ArgumentOutOfRangeException(nameof(year), Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); } Contract.EndContractBlock(); if (year > helper.MaxYear) { throw new ArgumentOutOfRangeException( nameof(year), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, helper.MaxYear)); } return (year); } public override int[] Eras { get { return (helper.Eras); } } // // Return the various era strings // Note: The arrays are backwards of the eras // internal static String[] EraNames() { EraInfo[] eras = GetEraInfo(); String[] eraNames = new String[eras.Length]; for (int i = 0; i < eras.Length; i++) { // Strings are in chronological order, eras are backwards order. eraNames[i] = eras[eras.Length - i - 1].eraName; } return eraNames; } internal static String[] AbbrevEraNames() { EraInfo[] eras = GetEraInfo(); String[] erasAbbrev = new String[eras.Length]; for (int i = 0; i < eras.Length; i++) { // Strings are in chronological order, eras are backwards order. erasAbbrev[i] = eras[eras.Length - i - 1].abbrevEraName; } return erasAbbrev; } internal static String[] EnglishEraNames() { EraInfo[] eras = GetEraInfo(); String[] erasEnglish = new String[eras.Length]; for (int i = 0; i < eras.Length; i++) { // Strings are in chronological order, eras are backwards order. erasEnglish[i] = eras[eras.Length - i - 1].englishEraName; } return erasEnglish; } private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 99; internal override bool IsValidYear(int year, int era) { return helper.IsValidYear(year, era); } public override int TwoDigitYearMax { get { if (twoDigitYearMax == -1) { twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX); } return (twoDigitYearMax); } set { VerifyWritable(); if (value < 99 || value > helper.MaxYear) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 99, helper.MaxYear)); } twoDigitYearMax = value; } } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; namespace Cassandra.Mapping.TypeConversion { /// <summary> /// A factory for retrieving Functions capable of converting between two Types. To use custom Type conversions, inheritors /// should derive from this class and implement the <see cref="GetUserDefinedFromDbConverter{TDatabase,TPoco}"/> and /// <see cref="GetUserDefinedToDbConverter{TPoco,TDatabase}"/> methods. /// </summary> public abstract class TypeConverter { private const BindingFlags PrivateStatic = BindingFlags.NonPublic | BindingFlags.Static; private const BindingFlags PrivateInstance = BindingFlags.NonPublic | BindingFlags.Instance; private static readonly MethodInfo FindFromDbConverterMethod = typeof (TypeConverter).GetMethod("FindFromDbConverter", PrivateInstance); private static readonly MethodInfo FindToDbConverterMethod = typeof (TypeConverter).GetMethod("FindToDbConverter", PrivateInstance); private static readonly MethodInfo ConvertToDictionaryMethod = typeof (TypeConverter).GetMethod("ConvertToDictionary", PrivateStatic); private static readonly MethodInfo ConvertToHashSetMethod = typeof(TypeConverter).GetMethod("ConvertToHashSet", PrivateStatic); private static readonly MethodInfo ConvertToSortedSetMethod = typeof(TypeConverter).GetMethod("ConvertToSortedSet", PrivateStatic); private static readonly MethodInfo ConvertToArrayMethod = typeof(Enumerable).GetMethod("ToArray", BindingFlags.Public | BindingFlags.Static); private readonly ConcurrentDictionary<Tuple<Type, Type>, Delegate> _fromDbConverterCache; private readonly ConcurrentDictionary<Tuple<Type, Type>, Delegate> _toDbConverterCache; /// <summary> /// Creates a new TypeConverter instance. /// </summary> protected TypeConverter() { _fromDbConverterCache = new ConcurrentDictionary<Tuple<Type, Type>, Delegate>(); _toDbConverterCache = new ConcurrentDictionary<Tuple<Type, Type>, Delegate>(); } /// <summary> /// Converts a value of Type <typeparamref name="TValue"/> to a value of Type <typeparamref name="TDatabase"/> using any available converters that would /// normally be used when converting a value for storage in Cassandra. If no converter is available, wlll throw an InvalidOperationException. /// </summary> /// <typeparam name="TValue">The value's original Type.</typeparam> /// <typeparam name="TDatabase">The Type expected by the database for the parameter.</typeparam> /// <param name="value">The value to be converted.</param> /// <returns>The converted value.</returns> internal TDatabase ConvertCqlArgument<TValue, TDatabase>(TValue value) { var converter = (Func<TValue, TDatabase>) GetToDbConverter(typeof (TValue), typeof (TDatabase)); if (converter == null) { throw new InvalidOperationException(string.Format("No converter is available from Type {0} to Type {1}", typeof(TValue).Name, typeof(TDatabase).Name)); } return converter(value); } /// <summary> /// Gets a Function that can convert a source type value from the database to a destination type value on a POCO. /// </summary> internal Delegate GetFromDbConverter(Type dbType, Type pocoType) { return _fromDbConverterCache.GetOrAdd(Tuple.Create(dbType, pocoType), // Invoke the generic method below with our two type parameters _ => (Delegate) FindFromDbConverterMethod.MakeGenericMethod(dbType, pocoType).Invoke(this, null)); } /// <summary> /// Gets a Function that can convert a source type value on a POCO to a destination type value for storage in C*. /// </summary> internal Delegate GetToDbConverter(Type pocoType, Type dbType) { return _toDbConverterCache.GetOrAdd(Tuple.Create(pocoType, dbType), _ => (Delegate) FindToDbConverterMethod.MakeGenericMethod(pocoType, dbType).Invoke(this, null)); } /// <summary> /// This method is generic because it seems like a good idea to enforce that the abstract method that returns a user-defined Func returns /// one with the correct type parameters, so we'd be invoking that abstract method generically via reflection anyway each time. So we might /// as well make this method generic and invoke it via reflection (it also makes the code for returning the built-in EnumStringMapper func /// simpler since that class is generic). /// </summary> // ReSharper disable once UnusedMember.Local (invoked via reflection) private Delegate FindFromDbConverter<TDatabase, TPoco>() { // Allow for user-defined conversions Delegate converter = GetUserDefinedFromDbConverter<TDatabase, TPoco>(); if (converter != null) return converter; Type dbType = typeof (TDatabase); Type pocoType = typeof (TPoco); // Allow strings from the database to be converted to an enum/nullable enum property on a POCO if (dbType == typeof(string)) { if (pocoType.IsEnum) { Func<string, TPoco> enumMapper = EnumStringMapper<TPoco>.MapStringToEnum; return enumMapper; } var underlyingPocoType = Nullable.GetUnderlyingType(pocoType); if (underlyingPocoType != null && underlyingPocoType.IsEnum) { Func<string, TPoco> enumMapper = NullableEnumStringMapper<TPoco>.MapStringToEnum; return enumMapper; } } if (dbType == typeof(DateTimeOffset)) { if (pocoType == typeof(DateTime)) { Func<DateTimeOffset, DateTime> dateMapper = d => d.DateTime; return dateMapper; } if (pocoType == typeof(DateTime?)) { Func<DateTimeOffset, DateTime?> dateMapper = d => d.DateTime; return dateMapper; } } if (dbType.IsGenericType && (pocoType.IsGenericType || pocoType.IsArray)) { Type sourceGenericDefinition = dbType.GetGenericTypeDefinition(); Type[] sourceGenericArgs = dbType.GetGenericArguments(); // Allow conversion from IDictionary<,> -> Dictionary<,> since C* driver uses SortedDictionary which can't be cast to Dictionary if (sourceGenericDefinition == typeof(IDictionary<,>) && pocoType == typeof(Dictionary<,>).MakeGenericType(sourceGenericArgs)) { return ConvertToDictionaryMethod.MakeGenericMethod(sourceGenericArgs).CreateDelegate(); } // IEnumerable<> could be a Set or a List from Cassandra if (sourceGenericDefinition == typeof (IEnumerable<>)) { // For some reason, the driver uses List<> to represent Sets so allow conversion to HashSet<>, SortedSet<>, and ISet<> if (pocoType == typeof (HashSet<>).MakeGenericType(sourceGenericArgs)) { return ConvertToHashSetMethod.MakeGenericMethod(sourceGenericArgs).CreateDelegate(); } if (pocoType == typeof (SortedSet<>).MakeGenericType(sourceGenericArgs) || pocoType == typeof (ISet<>).MakeGenericType(sourceGenericArgs)) { return ConvertToSortedSetMethod.MakeGenericMethod(sourceGenericArgs).CreateDelegate(); } // Allow converting from set/list's IEnumerable<T> to T[] if (pocoType == sourceGenericArgs[0].MakeArrayType()) { return ConvertToArrayMethod.MakeGenericMethod(sourceGenericArgs).CreateDelegate(); } } } return null; } /// <summary> /// See note above on why this is generic. /// </summary> // ReSharper disable once UnusedMember.Local (invoked via reflection) private Delegate FindToDbConverter<TPoco, TDatabase>() { // Allow for user-defined conversions Delegate converter = GetUserDefinedToDbConverter<TPoco, TDatabase>(); if (converter != null) { return converter; } Type pocoType = typeof (TPoco); Type dbType = typeof (TDatabase); // Support enum/nullable enum => string conversion if (dbType == typeof (string)) { if (pocoType.IsEnum) { // Just call ToStirng() on the enum value from the POCO Func<TPoco, string> enumConverter = prop => prop.ToString(); return enumConverter; } Type underlyingPocoType = Nullable.GetUnderlyingType(pocoType); if (underlyingPocoType != null && underlyingPocoType.IsEnum) { Func<TPoco, string> enumConverter = NullableEnumStringMapper<TPoco>.MapEnumToString; return enumConverter; } } return null; } // ReSharper disable UnusedMember.Local // (these methods are invoked via reflection above) private static Dictionary<TKey, TValue> ConvertToDictionary<TKey, TValue>(IDictionary<TKey, TValue> mapFromDatabase) { return new Dictionary<TKey, TValue>(mapFromDatabase); } private static HashSet<T> ConvertToHashSet<T>(IEnumerable<T> setFromDatabase) { return new HashSet<T>(setFromDatabase); } private static SortedSet<T> ConvertToSortedSet<T>(IEnumerable<T> setFromDatabase) { return new SortedSet<T>(setFromDatabase); } // ReSharper restore UnusedMember.Local /// <summary> /// Gets any user defined conversion functions that can convert a value of type <typeparamref name="TDatabase"/> (coming from Cassandra) to a /// type of <typeparamref name="TPoco"/> (a field or property on a POCO). Return null if no conversion Func is available. /// </summary> /// <typeparam name="TDatabase">The Type of the source value from Cassandra to be converted.</typeparam> /// <typeparam name="TPoco">The Type of the destination value on the POCO.</typeparam> /// <returns>A Func that can convert between the two types or null if one is not available.</returns> protected abstract Func<TDatabase, TPoco> GetUserDefinedFromDbConverter<TDatabase, TPoco>(); /// <summary> /// Gets any user defined conversion functions that can convert a value of type <typeparamref name="TPoco"/> (coming from a property/field on a /// POCO) to a type of <typeparamref name="TDatabase"/> (the Type expected by Cassandra for the database column). Return null if no conversion /// Func is available. /// </summary> /// <typeparam name="TPoco">The Type of the source value from the POCO property/field to be converted.</typeparam> /// <typeparam name="TDatabase">The Type expected by C* for the database column.</typeparam> /// <returns>A Func that can converter between the two Types or null if one is not available.</returns> protected abstract Func<TPoco, TDatabase> GetUserDefinedToDbConverter<TPoco, TDatabase>(); } internal static class ReflectionUtils { public static Delegate CreateDelegate(this MethodInfo method) { if (method == null) { throw new ArgumentNullException("method"); } if (!method.IsStatic) { throw new ArgumentException("The provided method must be static.", "method"); } var delegateType = Expression.GetFuncType(method.GetParameters().Select(p => p.ParameterType).ToArray()); return Delegate.CreateDelegate(delegateType, null, method); } } }
using System; using TrueCraft.API.Logic; using TrueCraft.API; using TrueCraft.API.Networking; using TrueCraft.API.World; using TrueCraft.Core.Windows; using TrueCraft.API.Windows; using System.Collections.Generic; using fNbt; using TrueCraft.API.Server; using TrueCraft.Core.Networking.Packets; using TrueCraft.Core.Entities; namespace TrueCraft.Core.Logic.Blocks { public class FurnaceBlock : BlockProvider, ICraftingRecipe { protected class FurnaceState { public short BurnTimeRemaining { get; set; } public short BurnTimeTotal { get; set; } public short CookTime { get; set; } public ItemStack[] Items { get; set; } public FurnaceState() { Items = new ItemStack[3]; } } protected class FurnaceEventSubject : IEventSubject { public event EventHandler Disposed; public void Dispose() { if (Disposed != null) Dispose(); } } public static readonly byte BlockID = 0x3D; public override byte ID { get { return 0x3D; } } public override double BlastResistance { get { return 17.5; } } public override double Hardness { get { return 3.5; } } public override byte Luminance { get { return 0; } } public override string DisplayName { get { return "Furnace"; } } public override ToolType EffectiveTools { get { return ToolType.Pickaxe; } } protected override ItemStack[] GetDrop(BlockDescriptor descriptor, ItemStack item) { return new[] { new ItemStack(BlockID) }; } protected static Dictionary<Coordinates3D, FurnaceEventSubject> TrackedFurnaces { get; set; } protected static Dictionary<Coordinates3D, List<IWindow>> TrackedFurnaceWindows { get; set; } public FurnaceBlock() { TrackedFurnaces = new Dictionary<Coordinates3D, FurnaceEventSubject>(); TrackedFurnaceWindows = new Dictionary<Coordinates3D, List<IWindow>>(); } private NbtCompound CreateTileEntity() { return new NbtCompound(new NbtTag[] { new NbtShort("BurnTime", 0), new NbtShort("BurnTotal", 0), new NbtShort("CookTime", -1), new NbtList("Items", new[] { ItemStack.EmptyStack.ToNbt(), ItemStack.EmptyStack.ToNbt(), ItemStack.EmptyStack.ToNbt() }, NbtTagType.Compound) }); } private FurnaceState GetState(IWorld world, Coordinates3D coords) { var tileEntity = world.GetTileEntity(coords); if (tileEntity == null) tileEntity = CreateTileEntity(); var burnTime = tileEntity.Get<NbtShort>("BurnTime"); var burnTotal = tileEntity.Get<NbtShort>("BurnTotal"); var cookTime = tileEntity.Get<NbtShort>("CookTime"); var state = new FurnaceState { BurnTimeTotal = burnTotal == null ? (short)0 : burnTotal.Value, BurnTimeRemaining = burnTime == null ? (short)0 : burnTime.Value, CookTime = cookTime == null ? (short)200 : cookTime.Value }; var items = tileEntity.Get<NbtList>("Items"); if (items != null) { int i = 0; foreach (var item in items) state.Items[i++] = ItemStack.FromNbt((NbtCompound)item); } return state; } private void UpdateWindows(Coordinates3D coords, FurnaceState state) { if (TrackedFurnaceWindows.ContainsKey(coords)) { Handling = true; foreach (var window in TrackedFurnaceWindows[coords]) { window[0] = state.Items[0]; window[1] = state.Items[1]; window[2] = state.Items[2]; window.Client.QueuePacket(new UpdateProgressPacket( window.ID, UpdateProgressPacket.ProgressTarget.ItemCompletion, state.CookTime)); var burnProgress = state.BurnTimeRemaining / (double)state.BurnTimeTotal; var burn = (short)(burnProgress * 250); window.Client.QueuePacket(new UpdateProgressPacket( window.ID, UpdateProgressPacket.ProgressTarget.AvailableHeat, burn)); } Handling = false; } } private void SetState(IWorld world, Coordinates3D coords, FurnaceState state) { world.SetTileEntity(coords, new NbtCompound(new NbtTag[] { new NbtShort("BurnTime", state.BurnTimeRemaining), new NbtShort("BurnTotal", state.BurnTimeTotal), new NbtShort("CookTime", state.CookTime), new NbtList("Items", new[] { state.Items[0].ToNbt(), state.Items[1].ToNbt(), state.Items[2].ToNbt() }, NbtTagType.Compound) })); UpdateWindows(coords, state); } public override void BlockLoadedFromChunk(Coordinates3D coords, IMultiplayerServer server, IWorld world) { var state = GetState(world, coords); TryInitializeFurnace(state, server.Scheduler, world, coords, server.ItemRepository); } public override void BlockMined(BlockDescriptor descriptor, BlockFace face, IWorld world, IRemoteClient user) { var entity = world.GetTileEntity(descriptor.Coordinates); if (entity != null) { foreach (var item in (NbtList)entity["Items"]) { var manager = user.Server.GetEntityManagerForWorld(world); var slot = ItemStack.FromNbt((NbtCompound)item); manager.SpawnEntity(new ItemEntity(descriptor.Coordinates + new Vector3(0.5), slot)); } world.SetTileEntity(descriptor.Coordinates, null); } base.BlockMined(descriptor, face, world, user); } public override bool BlockRightClicked(BlockDescriptor descriptor, BlockFace face, IWorld world, IRemoteClient user) { var window = new FurnaceWindow(user.Server.Scheduler, descriptor.Coordinates, user.Server.ItemRepository, (InventoryWindow)user.Inventory); var state = GetState(world, descriptor.Coordinates); for (int i = 0; i < state.Items.Length; i++) window[i] = state.Items[i]; user.OpenWindow(window); if (!TrackedFurnaceWindows.ContainsKey(descriptor.Coordinates)) TrackedFurnaceWindows[descriptor.Coordinates] = new List<IWindow>(); TrackedFurnaceWindows[descriptor.Coordinates].Add(window); window.Disposed += (sender, e) => TrackedFurnaceWindows.Remove(descriptor.Coordinates); UpdateWindows(descriptor.Coordinates, state); // TODO: Set window progress appropriately window.WindowChange += (sender, e) => FurnaceWindowChanged(sender, e, world); return false; } private bool Handling = false; protected void FurnaceWindowChanged(object sender, WindowChangeEventArgs e, IWorld world) { if (Handling) return; var window = sender as FurnaceWindow; var index = e.SlotIndex; if (index >= FurnaceWindow.MainIndex) return; Handling = true; e.Handled = true; window[index] = e.Value; var state = GetState(world, window.Coordinates); state.Items[0] = window[0]; state.Items[1] = window[1]; state.Items[2] = window[2]; SetState(world, window.Coordinates, state); Handling = true; if (!TrackedFurnaces.ContainsKey(window.Coordinates)) { // Set up the initial state TryInitializeFurnace(state, window.EventScheduler, world, window.Coordinates, window.ItemRepository); } Handling = false; } private void TryInitializeFurnace(FurnaceState state, IEventScheduler scheduler, IWorld world, Coordinates3D coords, IItemRepository itemRepository) { if (TrackedFurnaces.ContainsKey(coords)) return; var inputStack = state.Items[FurnaceWindow.IngredientIndex]; var fuelStack = state.Items[FurnaceWindow.FuelIndex]; var outputStack = state.Items[FurnaceWindow.OutputIndex]; var input = itemRepository.GetItemProvider(inputStack.ID) as ISmeltableItem; var fuel = itemRepository.GetItemProvider(fuelStack.ID) as IBurnableItem; if (state.BurnTimeRemaining > 0) { if (state.CookTime == -1 && input != null && (outputStack.Empty || outputStack.CanMerge(input.SmeltingOutput))) { state.CookTime = 0; SetState(world, coords, state); } var subject = new FurnaceEventSubject(); TrackedFurnaces[coords] = subject; scheduler.ScheduleEvent("smelting", subject, TimeSpan.FromSeconds(1), server => UpdateFurnace(server.Scheduler, world, coords, itemRepository)); return; } if (fuel != null && input != null) // We can maybe start { if (outputStack.Empty || outputStack.CanMerge(input.SmeltingOutput)) { // We can definitely start state.BurnTimeRemaining = state.BurnTimeTotal = (short)(fuel.BurnTime.TotalSeconds * 20); state.CookTime = 0; state.Items[FurnaceWindow.FuelIndex].Count--; SetState(world, coords, state); world.SetBlockID(coords, LitFurnaceBlock.BlockID); var subject = new FurnaceEventSubject(); TrackedFurnaces[coords] = subject; scheduler.ScheduleEvent("smelting", subject, TimeSpan.FromSeconds(1), server => UpdateFurnace(server.Scheduler, world, coords, itemRepository)); } } } private void UpdateFurnace(IEventScheduler scheduler, IWorld world, Coordinates3D coords, IItemRepository itemRepository) { if (TrackedFurnaces.ContainsKey(coords)) TrackedFurnaces.Remove(coords); if (world.GetBlockID(coords) != FurnaceBlock.BlockID && world.GetBlockID(coords) != LitFurnaceBlock.BlockID) { /*if (window != null && !window.IsDisposed) window.Dispose();*/ return; } var state = GetState(world, coords); var inputStack = state.Items[FurnaceWindow.IngredientIndex]; var outputStack = state.Items[FurnaceWindow.OutputIndex]; var input = itemRepository.GetItemProvider(inputStack.ID) as ISmeltableItem; // Update burn time var burnTime = state.BurnTimeRemaining; if (state.BurnTimeRemaining > 0) { state.BurnTimeRemaining -= 20; // ticks if (state.BurnTimeRemaining <= 0) { state.BurnTimeRemaining = 0; state.BurnTimeTotal = 0; world.SetBlockID(coords, FurnaceBlock.BlockID); } } // Update cook time if (state.CookTime < 200 && state.CookTime >= 0) { state.CookTime += 20; // ticks if (state.CookTime >= 200) state.CookTime = 200; } // Are we done cooking? if (state.CookTime == 200 && burnTime > 0) { state.CookTime = -1; if (input != null && (outputStack.Empty || outputStack.CanMerge(input.SmeltingOutput))) { if (outputStack.Empty) outputStack = input.SmeltingOutput; else if (outputStack.CanMerge(input.SmeltingOutput)) outputStack.Count += input.SmeltingOutput.Count; state.Items[FurnaceWindow.OutputIndex] = outputStack; state.Items[FurnaceWindow.IngredientIndex].Count--; } } SetState(world, coords, state); TryInitializeFurnace(state, scheduler, world, coords, itemRepository); } public override Tuple<int, int> GetTextureMap(byte metadata) { return new Tuple<int, int>(13, 2); } public ItemStack[,] Pattern { get { return new[,] { { new ItemStack(CobblestoneBlock.BlockID), new ItemStack(CobblestoneBlock.BlockID), new ItemStack(CobblestoneBlock.BlockID) }, { new ItemStack(CobblestoneBlock.BlockID), ItemStack.EmptyStack, new ItemStack(CobblestoneBlock.BlockID) }, { new ItemStack(CobblestoneBlock.BlockID), new ItemStack(CobblestoneBlock.BlockID), new ItemStack(CobblestoneBlock.BlockID) } }; } } public ItemStack Output { get { return new ItemStack(BlockID); } } public bool SignificantMetadata { get { return false; } } public override void BlockPlaced(BlockDescriptor descriptor, BlockFace face, IWorld world, IRemoteClient user) { world.SetMetadata(descriptor.Coordinates, (byte)MathHelper.DirectionByRotationFlat(user.Entity.Yaw, true)); } } public class LitFurnaceBlock : FurnaceBlock { public static readonly new byte BlockID = 0x3E; public override byte ID { get { return 0x3E; } } public override byte Luminance { get { return 13; } } public override bool Opaque { get { return false; } } public override string DisplayName { get { return "Furnace (lit)"; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace System.Linq.Tests { public class ToDictionaryTests : EnumerableTests { private class CustomComparer<T> : IEqualityComparer<T> { public bool Equals(T x, T y) { return EqualityComparer<T>.Default.Equals(x, y); } public int GetHashCode(T obj) { return EqualityComparer<T>.Default.GetHashCode(obj); } } [Fact] public void ToDictionary_AlwaysCreateACopy() { Dictionary<int, int> source = new Dictionary<int, int>() { { 1, 1 }, { 2, 2 }, { 3, 3 } }; Dictionary<int, int> result = source.ToDictionary(key => key.Key, val => val.Value); Assert.NotSame(source, result); Assert.Equal(source, result); } private void RunToDictionaryOnAllCollectionTypes<T>(T[] items, Action<Dictionary<T, T>> validation) { validation(Enumerable.ToDictionary(items, key => key)); validation(Enumerable.ToDictionary(items, key => key, value => value)); validation(Enumerable.ToDictionary(new List<T>(items), key => key)); validation(Enumerable.ToDictionary(new List<T>(items), key => key, value => value)); validation(new TestEnumerable<T>(items).ToDictionary(key => key)); validation(new TestEnumerable<T>(items).ToDictionary(key => key, value => value)); validation(new TestReadOnlyCollection<T>(items).ToDictionary(key => key)); validation(new TestReadOnlyCollection<T>(items).ToDictionary(key => key, value => value)); validation(new TestCollection<T>(items).ToDictionary(key => key)); validation(new TestCollection<T>(items).ToDictionary(key => key, value => value)); } [Fact] public void ToDictionary_WorkWithEmptyCollection() { RunToDictionaryOnAllCollectionTypes(new int[0], resultDictionary => { Assert.NotNull(resultDictionary); Assert.Equal(0, resultDictionary.Count); }); } [Fact] public void ToDictionary_ProduceCorrectDictionary() { int[] sourceArray = new int[] { 1, 2, 3, 4, 5, 6, 7 }; RunToDictionaryOnAllCollectionTypes(sourceArray, resultDictionary => { Assert.Equal(sourceArray.Length, resultDictionary.Count); Assert.Equal(sourceArray, resultDictionary.Keys); Assert.Equal(sourceArray, resultDictionary.Values); }); string[] sourceStringArray = new string[] { "1", "2", "3", "4", "5", "6", "7", "8" }; RunToDictionaryOnAllCollectionTypes(sourceStringArray, resultDictionary => { Assert.Equal(sourceStringArray.Length, resultDictionary.Count); for (int i = 0; i < sourceStringArray.Length; i++) Assert.Same(sourceStringArray[i], resultDictionary[sourceStringArray[i]]); }); } [Fact] public void RunOnce() { Assert.Equal( new Dictionary<int, string> {{1, "0"}, {2, "1"}, {3, "2"}, {4, "3"}}, Enumerable.Range(0, 4).RunOnce().ToDictionary(i => i + 1, i => i.ToString())); } [Fact] public void ToDictionary_PassCustomComparer() { CustomComparer<int> comparer = new CustomComparer<int>(); TestCollection<int> collection = new TestCollection<int>(new int[] { 1, 2, 3, 4, 5, 6 }); Dictionary<int, int> result1 = collection.ToDictionary(key => key, comparer); Assert.Same(comparer, result1.Comparer); Dictionary<int, int> result2 = collection.ToDictionary(key => key, val => val, comparer); Assert.Same(comparer, result2.Comparer); } [Fact] public void ToDictionary_UseDefaultComparerOnNull() { CustomComparer<int> comparer = null; TestCollection<int> collection = new TestCollection<int>(new int[] { 1, 2, 3, 4, 5, 6 }); Dictionary<int, int> result1 = collection.ToDictionary(key => key, comparer); Assert.Same(EqualityComparer<int>.Default, result1.Comparer); Dictionary<int, int> result2 = collection.ToDictionary(key => key, val => val, comparer); Assert.Same(EqualityComparer<int>.Default, result2.Comparer); } [Fact] public void ToDictionary_KeyValueSelectorsWork() { TestCollection<int> collection = new TestCollection<int>(new int[] { 1, 2, 3, 4, 5, 6 }); Dictionary<int, int> result = collection.ToDictionary(key => key + 10, val => val + 100); Assert.Equal(collection.Items.Select(o => o + 10), result.Keys); Assert.Equal(collection.Items.Select(o => o + 100), result.Values); } [Fact] public void ToDictionary_ThrowArgumentNullExceptionWhenSourceIsNull() { int[] source = null; AssertExtensions.Throws<ArgumentNullException>("source", () => source.ToDictionary(key => key)); } [Fact] public void ToDictionary_ThrowArgumentNullExceptionWhenKeySelectorIsNull() { int[] source = new int[0]; Func<int, int> keySelector = null; AssertExtensions.Throws<ArgumentNullException>("keySelector", () => source.ToDictionary(keySelector)); } [Fact] public void ToDictionary_ThrowArgumentNullExceptionWhenValueSelectorIsNull() { int[] source = new int[0]; Func<int, int> keySelector = key => key; Func<int, int> valueSelector = null; AssertExtensions.Throws<ArgumentNullException>("elementSelector", () => source.ToDictionary(keySelector, valueSelector)); } [Fact] public void ToDictionary_ThrowArgumentNullExceptionWhenSourceIsNullElementSelector() { int[] source = null; AssertExtensions.Throws<ArgumentNullException>("source", () => source.ToDictionary(key => key, e => e)); } [Fact] public void ToDictionary_ThrowArgumentNullExceptionWhenKeySelectorIsNullElementSelector() { int[] source = new int[0]; Func<int, int> keySelector = null; AssertExtensions.Throws<ArgumentNullException>("keySelector", () => source.ToDictionary(keySelector, e => e)); } [Fact] public void ToDictionary_KeySelectorThrowException() { int[] source = new int[] { 1, 2, 3 }; Func<int, int> keySelector = key => { if (key == 1) throw new InvalidOperationException(); return key; }; Assert.Throws<InvalidOperationException>(() => source.ToDictionary(keySelector)); } [Fact] public void ToDictionary_ThrowWhenKeySelectorReturnNull() { int[] source = new int[] { 1, 2, 3 }; Func<int, string> keySelector = key => null; AssertExtensions.Throws<ArgumentNullException>("key", () => source.ToDictionary(keySelector)); } [Fact] public void ToDictionary_ThrowWhenKeySelectorReturnSameValueTwice() { int[] source = new int[] { 1, 2, 3 }; Func<int, int> keySelector = key => 1; Assert.Throws<ArgumentException>(() => source.ToDictionary(keySelector)); } [Fact] public void ToDictionary_ValueSelectorThrowException() { int[] source = new int[] { 1, 2, 3 }; Func<int, int> keySelector = key => key; Func<int, int> valueSelector = value => { if (value == 1) throw new InvalidOperationException(); return value; }; Assert.Throws<InvalidOperationException>(() => source.ToDictionary(keySelector, valueSelector)); } [Fact] public void ThrowsOnNullKey() { var source = new[] { new { Name = "Chris", Score = 50 }, new { Name = "Bob", Score = 95 }, new { Name = "null", Score = 55 } }; source.ToDictionary(e => e.Name); // Doesn't throw; source = new[] { new { Name = "Chris", Score = 50 }, new { Name = "Bob", Score = 95 }, new { Name = default(string), Score = 55 } }; AssertExtensions.Throws<ArgumentNullException>("key", () => source.ToDictionary(e => e.Name)); } [Fact] public void ThrowsOnNullKeyCustomComparer() { var source = new[] { new { Name = "Chris", Score = 50 }, new { Name = "Bob", Score = 95 }, new { Name = "null", Score = 55 } }; source.ToDictionary(e => e.Name, new AnagramEqualityComparer()); // Doesn't throw; source = new[] { new { Name = "Chris", Score = 50 }, new { Name = "Bob", Score = 95 }, new { Name = default(string), Score = 55 } }; AssertExtensions.Throws<ArgumentNullException>("key", () => source.ToDictionary(e => e.Name, new AnagramEqualityComparer())); } [Fact] public void ThrowsOnNullKeyValueSelector() { var source = new[] { new { Name = "Chris", Score = 50 }, new { Name = "Bob", Score = 95 }, new { Name = "null", Score = 55 } }; source.ToDictionary(e => e.Name, e => e); // Doesn't throw; source = new[] { new { Name = "Chris", Score = 50 }, new { Name = "Bob", Score = 95 }, new { Name = default(string), Score = 55 } }; AssertExtensions.Throws<ArgumentNullException>("key", () => source.ToDictionary(e => e.Name, e => e)); } [Fact] public void ThrowsOnNullKeyCustomComparerValueSelector() { var source = new[] { new { Name = "Chris", Score = 50 }, new { Name = "Bob", Score = 95 }, new { Name = "null", Score = 55 } }; source.ToDictionary(e => e.Name, e => e, new AnagramEqualityComparer()); // Doesn't throw; source = new[] { new { Name = "Chris", Score = 50 }, new { Name = "Bob", Score = 95 }, new { Name = default(string), Score = 55 } }; AssertExtensions.Throws<ArgumentNullException>("key", () => source.ToDictionary(e => e.Name, e => e, new AnagramEqualityComparer())); } [Fact] public void ThrowsOnDuplicateKeys() { var source = new[] { new { Name = "Chris", Score = 50 }, new { Name = "Bob", Score = 95 }, new { Name = "Bob", Score = 55 } }; Assert.Throws<ArgumentException>(() => source.ToDictionary(e => e.Name, e => e, new AnagramEqualityComparer())); } private static void AssertMatches<K, E>(IEnumerable<K> keys, IEnumerable<E> values, Dictionary<K, E> dict) { Assert.NotNull(dict); Assert.NotNull(keys); Assert.NotNull(values); using (var ke = keys.GetEnumerator()) { foreach(var value in values) { Assert.True(ke.MoveNext()); var key = ke.Current; E dictValue; Assert.True(dict.TryGetValue(key, out dictValue)); Assert.Equal(value, dictValue); dict.Remove(key); } Assert.False(ke.MoveNext()); Assert.Equal(0, dict.Count()); } } [Fact] public void EmtpySource() { int[] elements = new int[] { }; string[] keys = new string[] { }; var source = keys.Zip(elements, (k, e) => new { Name = k, Score = e }); AssertMatches(keys, elements, source.ToDictionary(e => e.Name, e => e.Score, new AnagramEqualityComparer())); } [Fact] public void OneElementNullComparer() { int[] elements = new int[] { 5 }; string[] keys = new string[] { "Bob" }; var source = new [] { new { Name = keys[0], Score = elements[0] } }; AssertMatches(keys, elements, source.ToDictionary(e => e.Name, e => e.Score, null)); } [Fact] public void SeveralElementsCustomComparerer() { string[] keys = new string[] { "Bob", "Zen", "Prakash", "Chris", "Sachin" }; var source = new [] { new { Name = "Bbo", Score = 95 }, new { Name = keys[1], Score = 45 }, new { Name = keys[2], Score = 100 }, new { Name = keys[3], Score = 90 }, new { Name = keys[4], Score = 45 } }; AssertMatches(keys, source, source.ToDictionary(e => e.Name, new AnagramEqualityComparer())); } [Fact] public void NullCoalescedKeySelector() { string[] elements = new string[] { null }; string[] keys = new string[] { string.Empty }; string[] source = new string[] { null }; AssertMatches(keys, elements, source.ToDictionary(e => e ?? string.Empty, e => e, EqualityComparer<string>.Default)); } } }
using System; using System.Drawing; using Aspose.Cells; namespace Aspose.Cells.Examples.CSharp.Articles { // ExStart:1 /// <summary> /// AsposeFormatWorksheet /// Use Aspose.Cells to perform the task /// </summary> class FormatWorksheetCells { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] public static void Run() { string filename = RunExamples.Get_OutputDirectory() + "outputFormatWorksheetCells.xlsx"; CreateSalesReport(filename); Console.WriteLine("FormatWorksheetCells executed successfully.\r\n"); } private static void CreateSalesReport(string filename) { // Create a new Workbook. Workbook workbook = new Workbook(); /* * Note: Since Excel color palette has 56 colors on it. * The colors are indexed 0-55. * Please check: http:// Www.aspose.com/Products/Aspose.Cells/Api/Aspose.Cells.Workbook.ChangePalette.html * If a color is not present on the palette, we have to add it * To the palette, so that we may use. * Add a few custom colors to the palette. */ workbook.ChangePalette(Color.FromArgb(155, 204, 255), 55); workbook.ChangePalette(Color.FromArgb(0, 51, 105), 54); workbook.ChangePalette(Color.FromArgb(250, 250, 200), 53); workbook.ChangePalette(Color.FromArgb(124, 199, 72), 52); CreateReportData(workbook); CreateCellsFormatting(workbook); // Get the first worksheet in the book. Worksheet worksheet = workbook.Worksheets[0]; // Name the worksheet. worksheet.Name = "Sales Report"; // Save the excel file. workbook.Save(filename); } private static void CreateReportData(Workbook workbook) { // Obtain the cells of the first worksheet. Cells cells = workbook.Worksheets[0].Cells; // Input the title on B1 cell. cells["B1"].PutValue("Western Product Sales 2006"); // Insert some column headings in the second row. Cell cell = cells["B2"]; cell.PutValue("January"); cell = cells["C2"]; cell.PutValue("February"); cell = cells["D2"]; cell.PutValue("March"); cell = cells["E2"]; cell.PutValue("April"); cell = cells["F2"]; cell.PutValue("May"); cell = cells["G2"]; cell.PutValue("June"); cell = cells["H2"]; cell.PutValue("July"); cell = cells["I2"]; cell.PutValue("August"); cell = cells["J2"]; cell.PutValue("September"); cell = cells["K2"]; cell.PutValue("October"); cell = cells["L2"]; cell.PutValue("November"); cell = cells["M2"]; cell.PutValue("December"); cell = cells["N2"]; cell.PutValue("Total"); // Insert product names. cells["A3"].PutValue("Biscuits"); cells["A4"].PutValue("Coffee"); cells["A5"].PutValue("Tofu"); cells["A6"].PutValue("Ikura"); cells["A7"].PutValue("Choclade"); cells["A8"].PutValue("Maxilaku"); cells["A9"].PutValue("Scones"); cells["A10"].PutValue("Sauce"); cells["A11"].PutValue("Syrup"); cells["A12"].PutValue("Spegesild"); cells["A13"].PutValue("Filo Mix"); cells["A14"].PutValue("Pears"); cells["A15"].PutValue("Konbu"); cells["A16"].PutValue("Kaviar"); cells["A17"].PutValue("Zaanse"); cells["A18"].PutValue("Cabrales"); cells["A19"].PutValue("Gnocchi"); cells["A20"].PutValue("Wimmers"); cells["A21"].PutValue("Breads"); cells["A22"].PutValue("Lager"); cells["A23"].PutValue("Gravad"); cells["A24"].PutValue("Telino"); cells["A25"].PutValue("Pavlova"); cells["A26"].PutValue("Total"); // Input porduct sales data (B3:M25). cells["B3"].PutValue(5000); cells["C3"].PutValue(4500); cells["D3"].PutValue(6010); cells["E3"].PutValue(7230); cells["F3"].PutValue(5400); cells["G3"].PutValue(5030); cells["H3"].PutValue(3000); cells["I3"].PutValue(6000); cells["J3"].PutValue(9000); cells["K3"].PutValue(3300); cells["L3"].PutValue(2500); cells["M3"].PutValue(5510); cells["B4"].PutValue(4000); cells["C4"].PutValue(2500); cells["D4"].PutValue(6000); cells["E4"].PutValue(5300); cells["F4"].PutValue(7400); cells["G4"].PutValue(7030); cells["H4"].PutValue(4000); cells["I4"].PutValue(4000); cells["J4"].PutValue(5500); cells["K4"].PutValue(4500); cells["L4"].PutValue(2500); cells["M4"].PutValue(2510); cells["B5"].PutValue(2000); cells["C5"].PutValue(1500); cells["D5"].PutValue(3000); cells["E5"].PutValue(2500); cells["F5"].PutValue(3400); cells["G5"].PutValue(4030); cells["H5"].PutValue(2000); cells["I5"].PutValue(2000); cells["J5"].PutValue(1500); cells["K5"].PutValue(2200); cells["L5"].PutValue(2100); cells["M5"].PutValue(2310); cells["B6"].PutValue(1000); cells["C6"].PutValue(1300); cells["D6"].PutValue(2000); cells["E6"].PutValue(2600); cells["F6"].PutValue(5400); cells["G6"].PutValue(2030); cells["H6"].PutValue(2100); cells["I6"].PutValue(4000); cells["J6"].PutValue(6500); cells["K6"].PutValue(5600); cells["L6"].PutValue(3300); cells["M6"].PutValue(5110); cells["B7"].PutValue(3000); cells["C7"].PutValue(3500); cells["D7"].PutValue(1000); cells["E7"].PutValue(4500); cells["F7"].PutValue(5400); cells["G7"].PutValue(2030); cells["H7"].PutValue(3000); cells["I7"].PutValue(3000); cells["J7"].PutValue(4500); cells["K7"].PutValue(6000); cells["L7"].PutValue(3000); cells["M7"].PutValue(3000); cells["B8"].PutValue(5000); cells["C8"].PutValue(5500); cells["D8"].PutValue(5000); cells["E8"].PutValue(5500); cells["F8"].PutValue(5400); cells["G8"].PutValue(5030); cells["H8"].PutValue(5000); cells["I8"].PutValue(2500); cells["J8"].PutValue(5500); cells["K8"].PutValue(5200); cells["L8"].PutValue(5500); cells["M8"].PutValue(2510); cells["B9"].PutValue(4100); cells["C9"].PutValue(1500); cells["D9"].PutValue(1000); cells["E9"].PutValue(2300); cells["F9"].PutValue(3300); cells["G9"].PutValue(4030); cells["H9"].PutValue(5000); cells["I9"].PutValue(6000); cells["J9"].PutValue(3500); cells["K9"].PutValue(4300); cells["L9"].PutValue(2300); cells["M9"].PutValue(2110); cells["B10"].PutValue(2000); cells["C10"].PutValue(2300); cells["D10"].PutValue(3000); cells["E10"].PutValue(3300); cells["F10"].PutValue(3400); cells["G10"].PutValue(3030); cells["H10"].PutValue(3000); cells["I10"].PutValue(3000); cells["J10"].PutValue(3500); cells["K10"].PutValue(3500); cells["L10"].PutValue(3500); cells["M10"].PutValue(3510); cells["B11"].PutValue(4400); cells["C11"].PutValue(4500); cells["D11"].PutValue(4000); cells["E11"].PutValue(4300); cells["F11"].PutValue(4400); cells["G11"].PutValue(4030); cells["H11"].PutValue(5000); cells["I11"].PutValue(5000); cells["J11"].PutValue(4500); cells["K11"].PutValue(4400); cells["L11"].PutValue(4400); cells["M11"].PutValue(4510); cells["B12"].PutValue(2000); cells["C12"].PutValue(1500); cells["D12"].PutValue(3000); cells["E12"].PutValue(2300); cells["F12"].PutValue(3400); cells["G12"].PutValue(3030); cells["H12"].PutValue(3000); cells["I12"].PutValue(3000); cells["J12"].PutValue(2500); cells["K12"].PutValue(2500); cells["L12"].PutValue(1500); cells["M12"].PutValue(5110); cells["B13"].PutValue(4000); cells["C13"].PutValue(1400); cells["D13"].PutValue(1400); cells["E13"].PutValue(3300); cells["F13"].PutValue(3300); cells["G13"].PutValue(3730); cells["H13"].PutValue(3800); cells["I13"].PutValue(3600); cells["J13"].PutValue(2600); cells["K13"].PutValue(4600); cells["L13"].PutValue(1400); cells["M13"].PutValue(2660); cells["B14"].PutValue(3000); cells["C14"].PutValue(3500); cells["D14"].PutValue(3333); cells["E14"].PutValue(2330); cells["F14"].PutValue(3430); cells["G14"].PutValue(3040); cells["H14"].PutValue(3040); cells["I14"].PutValue(3030); cells["J14"].PutValue(1509); cells["K14"].PutValue(4503); cells["L14"].PutValue(1503); cells["M14"].PutValue(3113); cells["B15"].PutValue(2010); cells["C15"].PutValue(1520); cells["D15"].PutValue(3030); cells["E15"].PutValue(2320); cells["F15"].PutValue(3410); cells["G15"].PutValue(3000); cells["H15"].PutValue(3000); cells["I15"].PutValue(3020); cells["J15"].PutValue(2520); cells["K15"].PutValue(2520); cells["L15"].PutValue(1520); cells["M15"].PutValue(5120); cells["B16"].PutValue(2220); cells["C16"].PutValue(1200); cells["D16"].PutValue(3220); cells["E16"].PutValue(1320); cells["F16"].PutValue(1400); cells["G16"].PutValue(1030); cells["H16"].PutValue(3200); cells["I16"].PutValue(3020); cells["J16"].PutValue(2100); cells["K16"].PutValue(2100); cells["L16"].PutValue(1100); cells["M16"].PutValue(5210); cells["B17"].PutValue(1444); cells["C17"].PutValue(1540); cells["D17"].PutValue(3040); cells["E17"].PutValue(2340); cells["F17"].PutValue(1440); cells["G17"].PutValue(1030); cells["H17"].PutValue(3000); cells["I17"].PutValue(4000); cells["J17"].PutValue(4500); cells["K17"].PutValue(2500); cells["L17"].PutValue(4500); cells["M17"].PutValue(5550); cells["B18"].PutValue(4000); cells["C18"].PutValue(5500); cells["D18"].PutValue(3000); cells["E18"].PutValue(3300); cells["F18"].PutValue(3330); cells["G18"].PutValue(5330); cells["H18"].PutValue(3400); cells["I18"].PutValue(3040); cells["J18"].PutValue(2540); cells["K18"].PutValue(4500); cells["L18"].PutValue(4500); cells["M18"].PutValue(2110); cells["B19"].PutValue(2000); cells["C19"].PutValue(2500); cells["D19"].PutValue(3200); cells["E19"].PutValue(3200); cells["F19"].PutValue(2330); cells["G19"].PutValue(5230); cells["H19"].PutValue(2400); cells["I19"].PutValue(3240); cells["J19"].PutValue(2240); cells["K19"].PutValue(4300); cells["L19"].PutValue(4100); cells["M19"].PutValue(2310); cells["B20"].PutValue(7000); cells["C20"].PutValue(8500); cells["D20"].PutValue(8000); cells["E20"].PutValue(5300); cells["F20"].PutValue(6330); cells["G20"].PutValue(7330); cells["H20"].PutValue(3600); cells["I20"].PutValue(3940); cells["J20"].PutValue(2940); cells["K20"].PutValue(4600); cells["L20"].PutValue(6500); cells["M20"].PutValue(8710); cells["B21"].PutValue(4000); cells["C21"].PutValue(4500); cells["D21"].PutValue(2000); cells["E21"].PutValue(2200); cells["F21"].PutValue(2000); cells["G21"].PutValue(3000); cells["H21"].PutValue(3000); cells["I21"].PutValue(3000); cells["J21"].PutValue(4330); cells["K21"].PutValue(4420); cells["L21"].PutValue(4500); cells["M21"].PutValue(1330); cells["B22"].PutValue(2050); cells["C22"].PutValue(3520); cells["D22"].PutValue(1030); cells["E22"].PutValue(2000); cells["F22"].PutValue(3000); cells["G22"].PutValue(2000); cells["H22"].PutValue(2010); cells["I22"].PutValue(2210); cells["J22"].PutValue(2230); cells["K22"].PutValue(4240); cells["L22"].PutValue(3330); cells["M22"].PutValue(2000); cells["B23"].PutValue(1222); cells["C23"].PutValue(3000); cells["D23"].PutValue(3020); cells["E23"].PutValue(2770); cells["F23"].PutValue(3011); cells["G23"].PutValue(2000); cells["H23"].PutValue(6000); cells["I23"].PutValue(9000); cells["J23"].PutValue(4000); cells["K23"].PutValue(2000); cells["L23"].PutValue(5000); cells["M23"].PutValue(6333); cells["B24"].PutValue(1000); cells["C24"].PutValue(2000); cells["D24"].PutValue(1000); cells["E24"].PutValue(1300); cells["F24"].PutValue(1330); cells["G24"].PutValue(1390); cells["H24"].PutValue(1600); cells["I24"].PutValue(1900); cells["J24"].PutValue(1400); cells["K24"].PutValue(1650); cells["L24"].PutValue(1520); cells["M24"].PutValue(1910); cells["B25"].PutValue(2000); cells["C25"].PutValue(6600); cells["D25"].PutValue(3300); cells["E25"].PutValue(8300); cells["F25"].PutValue(2000); cells["G25"].PutValue(3000); cells["H25"].PutValue(6000); cells["I25"].PutValue(4000); cells["J25"].PutValue(7000); cells["K25"].PutValue(2000); cells["L25"].PutValue(5000); cells["M25"].PutValue(5500); // Add Monthwise Summary formulas. cells["B26"].Formula = "=SUM(B3:B25)"; cells["C26"].Formula = "=SUM(C3:C25)"; cells["D26"].Formula = "=SUM(D3:D25)"; cells["E26"].Formula = "=SUM(E3:E25)"; cells["F26"].Formula = "=SUM(F3:F25)"; cells["G26"].Formula = "=SUM(G3:G25)"; cells["H26"].Formula = "=SUM(H3:H25)"; cells["I26"].Formula = "=SUM(I3:I25)"; cells["J26"].Formula = "=SUM(J3:J25)"; cells["K26"].Formula = "=SUM(K3:K25)"; cells["L26"].Formula = "=SUM(L3:L25)"; cells["M26"].Formula = "=SUM(M3:M25)"; // Add Productwise Summary formulas. cells["N3"].Formula = "=SUM(B3:M3)"; cells["N4"].Formula = "=SUM(B4:M4)"; cells["N5"].Formula = "=SUM(B5:M5)"; cells["N6"].Formula = "=SUM(B6:M6)"; cells["N7"].Formula = "=SUM(B7:M7)"; cells["N8"].Formula = "=SUM(B8:M8)"; cells["N9"].Formula = "=SUM(B9:M9)"; cells["N10"].Formula = "=SUM(B10:M10)"; cells["N11"].Formula = "=SUM(B11:M11)"; cells["N12"].Formula = "=SUM(B12:M12)"; cells["N13"].Formula = "=SUM(B13:M13)"; cells["N14"].Formula = "=SUM(B14:M14)"; cells["N15"].Formula = "=SUM(B15:M15)"; cells["N16"].Formula = "=SUM(B16:M16)"; cells["N17"].Formula = "=SUM(B17:M17)"; cells["N18"].Formula = "=SUM(B18:M18)"; cells["N19"].Formula = "=SUM(B19:M19)"; cells["N20"].Formula = "=SUM(B20:M20)"; cells["N21"].Formula = "=SUM(B21:M21)"; cells["N22"].Formula = "=SUM(B22:M22)"; cells["N23"].Formula = "=SUM(B23:M23)"; cells["N24"].Formula = "=SUM(B24:M24)"; cells["N25"].Formula = "=SUM(B25:M25)"; // Add Grand Total. cells["N26"].Formula = "=SUM(N3:N25)"; } private static void CreateCellsFormatting(Workbook workbook) { // Define a style object adding a new style to the collection list. Style stl0 = workbook.CreateStyle(); // Set a custom shading color of the cells. stl0.ForegroundColor = Color.FromArgb(155, 204, 255); stl0.Pattern = BackgroundType.Solid; stl0.Font.Name = "Trebuchet MS"; stl0.Font.Size = 18; stl0.Font.Color = Color.Maroon; stl0.Font.IsBold = true; stl0.Font.IsItalic = true; // Define a style flag struct. StyleFlag flag = new StyleFlag(); flag.CellShading = true; flag.FontName = true; flag.FontSize = true; flag.FontColor = true; flag.FontBold = true; flag.FontItalic = true; // Get the first row in the first worksheet. Row row = workbook.Worksheets[0].Cells.Rows[0]; // Apply the style to it. row.ApplyStyle(stl0, flag); // Obtain the cells of the first worksheet. Cells cells = workbook.Worksheets[0].Cells; // Set the height of the first row. cells.SetRowHeight(0, 30); // Define a style object adding a new style to the collection list. Style stl1 = workbook.CreateStyle(); // Set the rotation angle of the text. stl1.RotationAngle = 45; // Set the custom fill color of the cells. stl1.ForegroundColor = Color.FromArgb(0, 51, 105); stl1.Pattern = BackgroundType.Solid; stl1.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin; stl1.Borders[BorderType.LeftBorder].Color = Color.White; stl1.HorizontalAlignment = TextAlignmentType.Center; stl1.VerticalAlignment = TextAlignmentType.Center; stl1.Font.Name = "Times New Roman"; stl1.Font.Size = 10; stl1.Font.Color = Color.White; stl1.Font.IsBold = true; // Set a style flag struct. flag = new StyleFlag(); flag.LeftBorder = true; flag.Rotation = true; flag.CellShading = true; flag.HorizontalAlignment = true; flag.VerticalAlignment = true; flag.FontName = true; flag.FontSize = true; flag.FontColor = true; flag.FontBold = true; row = workbook.Worksheets[0].Cells.Rows[1]; // Apply the style to it. row.ApplyStyle(stl1, flag); // Set the height of the second row. cells.SetRowHeight(1, 48); // Define a style object adding a new style to the collection list. Style stl2 = workbook.CreateStyle(); // Set the custom cell shading color. stl2.ForegroundColor = Color.FromArgb(155, 204, 255); stl2.Pattern = BackgroundType.Solid; stl2.Font.Name = "Trebuchet MS"; stl2.Font.Color = Color.Maroon; stl2.Font.Size = 10; flag = new StyleFlag(); flag.CellShading = true; flag.FontName = true; flag.FontColor = true; flag.FontSize = true; // Get the first column in the first worksheet. Column col = workbook.Worksheets[0].Cells.Columns[0]; // Apply the style to it. col.ApplyStyle(stl2, flag); // Define a style object adding a new style to the collection list. Style stl3 = workbook.CreateStyle(); // Set the custom cell filling color. stl3.ForegroundColor = Color.FromArgb(124, 199, 72); stl3.Pattern = BackgroundType.Solid; cells["A2"].SetStyle(stl3); // Define a style object adding a new style to the collection list. Style stl4 = workbook.CreateStyle(); // Set the custom font text color. stl4.Font.Color = Color.FromArgb(0, 51, 105); stl4.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin; stl4.Borders[BorderType.BottomBorder].Color = Color.FromArgb(124, 199, 72); stl4.ForegroundColor = Color.White; stl4.Pattern = BackgroundType.Solid; // Set custom number format. stl4.Custom = "$#,##0.0"; // Set a style flag struct. flag = new StyleFlag(); flag.FontColor = true; flag.CellShading = true; flag.NumberFormat = true; flag.BottomBorder = true; // Define a style object adding a new style to the collection list. Style stl5 = workbook.CreateStyle(); stl5.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin; stl5.Borders[BorderType.BottomBorder].Color = Color.FromArgb(124, 199, 72); stl5.ForegroundColor = Color.FromArgb(250, 250, 200); stl5.Pattern = BackgroundType.Solid; // Set custom number format. stl5.Custom = "$#,##0.0"; stl5.Font.Color = Color.Maroon; // Create a named range of cells (B3:M25)in the first worksheet. Range range = workbook.Worksheets[0].Cells.CreateRange("B3", "M25"); // Name the range. range.Name = "MyRange"; // Apply the style to cells in the named range. range.ApplyStyle(stl4, flag); // Apply different style to alternative rows in the range. for (int i = 0; i <= 22; i++) { for (int j = 0; j < 12; j++) { if (i % 2 == 0) { range[i, j].SetStyle(stl5); } } } // Define a style object adding a new style to the collection list. Style stl6 = workbook.CreateStyle(); // Set the custom fill color of the cells. stl6.ForegroundColor = Color.FromArgb(0, 51, 105); stl6.Pattern = BackgroundType.Solid; stl6.Font.Name = "Arial"; stl6.Font.Size = 10; stl6.Font.Color = Color.White; stl6.Font.IsBold = true; // Set the custom number format. stl6.Custom = "$#,##0.0"; // Set the style flag struct. flag = new StyleFlag(); flag.CellShading = true; flag.FontName = true; flag.FontSize = true; flag.FontColor = true; flag.FontBold = true; flag.NumberFormat = true; // Get the 26th row in the first worksheet which produces totals. row = workbook.Worksheets[0].Cells.Rows[25]; // Apply the style to it. row.ApplyStyle(stl6, flag); // Now apply this style to those cells (N3:N25) which has productwise sales totals. for (int i = 2; i < 25; i++) { cells[i, 13].SetStyle(stl6); } // Set N column's width to fit the contents. workbook.Worksheets[0].Cells.SetColumnWidth(13, 9.33); } } // ExEnd:1 }
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Windows.Forms; using PCSComUtils.Common; using PCSComUtils.Common.BO; using PCSComUtils.PCSExc; using PCSUtils.Log; using PCSUtils.Utils; namespace PCSUtils.Framework.ReportFrame { /// <summary> /// Summary description for UserCCNList. /// </summary> public class UserCCNList : Form { private CheckedListBox chlList; /// <summary> /// Required designer variable. /// </summary> private Container components = null; private Button btnOK; private Button btnClose; private const string THIS = "PCSUtils.Framework.ReportFrame.UserCCNList"; private DataTable tblData; private ArrayList marrReturnsList; public ArrayList ReturnList { get { return this.marrReturnsList; } } private string strDisplayMember; private C1.C1Report.C1Report c1Report1; private C1.C1Preview.C1PrintDocument c1PrintDocument1; private C1.Win.C1Preview.C1PrintPreviewDialog c1PrintPreviewDialog1; private string strValueMember; public UserCCNList(string strTableName) { const string METHOD_NAME = THIS + ".ctor()"; // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // marrReturnsList = new ArrayList(); try { UtilsBO boUtils = new UtilsBO(); switch (strTableName) { case MST_CCNTable.TABLE_NAME: strDisplayMember = MST_CCNTable.CODE_FLD; strValueMember = MST_CCNTable.CCNID_FLD; // list all CCN to list tblData = boUtils.ListCCNForCheckListBox(); break; case Sys_UserTable.TABLE_NAME: strDisplayMember = Sys_UserTable.USERNAME_FLD; strValueMember = Sys_UserTable.USERNAME_FLD; // list all User to list tblData = boUtils.ListUser(); break; } } catch (PCSException ex) { // displays the error message. PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error); } } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error); } } } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(UserCCNList)); this.c1PrintPreviewDialog1 = new C1.Win.C1Preview.C1PrintPreviewDialog(); this.chlList = new System.Windows.Forms.CheckedListBox(); this.btnOK = new System.Windows.Forms.Button(); this.btnClose = new System.Windows.Forms.Button(); this.c1Report1 = new C1.C1Report.C1Report(); this.c1PrintDocument1 = new C1.C1Preview.C1PrintDocument(); ((System.ComponentModel.ISupportInitialize)(this.c1PrintPreviewDialog1.PrintPreviewControl)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.c1PrintPreviewDialog1.PrintPreviewControl.PreviewPane)).BeginInit(); this.c1PrintPreviewDialog1.PrintPreviewControl.SuspendLayout(); this.c1PrintPreviewDialog1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.c1Report1)).BeginInit(); this.SuspendLayout(); // // c1PrintPreviewDialog1 // resources.ApplyResources(this.c1PrintPreviewDialog1, "c1PrintPreviewDialog1"); this.c1PrintPreviewDialog1.Name = "C1PrintPreviewDialog"; // // c1PrintPreviewDialog1.PrintPreviewControl // // // c1PrintPreviewDialog1.PrintPreviewControl.OutlineView // resources.ApplyResources(this.c1PrintPreviewDialog1.PrintPreviewControl.PreviewOutlineView, "c1PrintPreviewDialog1.PrintPreviewControl.OutlineView"); this.c1PrintPreviewDialog1.PrintPreviewControl.PreviewOutlineView.LineColor = System.Drawing.Color.Empty; this.c1PrintPreviewDialog1.PrintPreviewControl.PreviewOutlineView.Name = "OutlineView"; // // c1PrintPreviewDialog1.PrintPreviewControl.PreviewPane // this.c1PrintPreviewDialog1.PrintPreviewControl.PreviewPane.IntegrateExternalTools = true; resources.ApplyResources(this.c1PrintPreviewDialog1.PrintPreviewControl.PreviewPane, "c1PrintPreviewDialog1.PrintPreviewControl.PreviewPane"); // // c1PrintPreviewDialog1.PrintPreviewControl.PreviewTextSearchPanel // resources.ApplyResources(this.c1PrintPreviewDialog1.PrintPreviewControl.PreviewTextSearchPanel, "c1PrintPreviewDialog1.PrintPreviewControl.PreviewTextSearchPanel"); this.c1PrintPreviewDialog1.PrintPreviewControl.PreviewTextSearchPanel.MinimumSize = new System.Drawing.Size(200, 240); this.c1PrintPreviewDialog1.PrintPreviewControl.PreviewTextSearchPanel.Name = "PreviewTextSearchPanel"; // // c1PrintPreviewDialog1.PrintPreviewControl.ThumbnailView // resources.ApplyResources(this.c1PrintPreviewDialog1.PrintPreviewControl.PreviewThumbnailView, "c1PrintPreviewDialog1.PrintPreviewControl.ThumbnailView"); this.c1PrintPreviewDialog1.PrintPreviewControl.PreviewThumbnailView.Name = "ThumbnailView"; this.c1PrintPreviewDialog1.PrintPreviewControl.PreviewThumbnailView.UseImageAsThumbnail = false; resources.ApplyResources(this.c1PrintPreviewDialog1.PrintPreviewControl, "c1PrintPreviewDialog1.PrintPreviewControl"); // // // this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.Open.Image = ((System.Drawing.Image)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.Open.Image"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.Open.ImageTransparentColor = ((System.Drawing.Color)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.Open.ImageTransparentColo" + "r"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.Open.Name = "btnFileOpen"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.Open.Size = ((System.Drawing.Size)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.Open.Size"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.Open.Tag = "C1PreviewActionEnum.FileOpen"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.Open.ToolTipText = resources.GetString("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.Open.ToolTipText"); // // // this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.PageSetup.Image = ((System.Drawing.Image)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.PageSetup.Image"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.PageSetup.ImageTransparentColor = ((System.Drawing.Color)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.PageSetup.ImageTransparen" + "tColor"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.PageSetup.Name = "btnPageSetup"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.PageSetup.Size = ((System.Drawing.Size)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.PageSetup.Size"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.PageSetup.Tag = "C1PreviewActionEnum.PageSetup"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.PageSetup.ToolTipText = resources.GetString("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.PageSetup.ToolTipText"); // // // this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.Print.Image = ((System.Drawing.Image)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.Print.Image"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.Print.ImageTransparentColor = ((System.Drawing.Color)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.Print.ImageTransparentCol" + "or"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.Print.Name = "btnPrint"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.Print.Size = ((System.Drawing.Size)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.Print.Size"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.Print.Tag = "C1PreviewActionEnum.Print"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.Print.ToolTipText = resources.GetString("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.Print.ToolTipText"); // // // this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.Reflow.Image = ((System.Drawing.Image)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.Reflow.Image"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.Reflow.ImageTransparentColor = ((System.Drawing.Color)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.Reflow.ImageTransparentCo" + "lor"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.Reflow.Name = "btnReflow"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.Reflow.Size = ((System.Drawing.Size)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.Reflow.Size"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.Reflow.Tag = "C1PreviewActionEnum.Reflow"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.Reflow.ToolTipText = resources.GetString("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.Reflow.ToolTipText"); // // // this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.Save.Image = ((System.Drawing.Image)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.Save.Image"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.Save.ImageTransparentColor = ((System.Drawing.Color)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.Save.ImageTransparentColo" + "r"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.Save.Name = "btnFileSave"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.Save.Size = ((System.Drawing.Size)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.Save.Size"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.Save.Tag = "C1PreviewActionEnum.FileSave"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.Save.ToolTipText = resources.GetString("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.File.Save.ToolTipText"); // // // this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.GoFirst.Image = ((System.Drawing.Image)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.GoFirst.Image"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.GoFirst.ImageTransparentColor = ((System.Drawing.Color)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.GoFirst.ImageTransp" + "arentColor"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.GoFirst.Name = "btnGoFirst"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.GoFirst.Size = ((System.Drawing.Size)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.GoFirst.Size"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.GoFirst.Tag = "C1PreviewActionEnum.GoFirst"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.GoFirst.ToolTipText = resources.GetString("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.GoFirst.ToolTipText" + ""); // // // this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.GoLast.Image = ((System.Drawing.Image)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.GoLast.Image"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.GoLast.ImageTransparentColor = ((System.Drawing.Color)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.GoLast.ImageTranspa" + "rentColor"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.GoLast.Name = "btnGoLast"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.GoLast.Size = ((System.Drawing.Size)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.GoLast.Size"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.GoLast.Tag = "C1PreviewActionEnum.GoLast"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.GoLast.ToolTipText = resources.GetString("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.GoLast.ToolTipText"); // // // this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.GoNext.Image = ((System.Drawing.Image)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.GoNext.Image"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.GoNext.ImageTransparentColor = ((System.Drawing.Color)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.GoNext.ImageTranspa" + "rentColor"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.GoNext.Name = "btnGoNext"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.GoNext.Size = ((System.Drawing.Size)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.GoNext.Size"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.GoNext.Tag = "C1PreviewActionEnum.GoNext"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.GoNext.ToolTipText = resources.GetString("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.GoNext.ToolTipText"); // // // this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.GoPrev.Image = ((System.Drawing.Image)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.GoPrev.Image"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.GoPrev.ImageTransparentColor = ((System.Drawing.Color)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.GoPrev.ImageTranspa" + "rentColor"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.GoPrev.Name = "btnGoPrev"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.GoPrev.Size = ((System.Drawing.Size)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.GoPrev.Size"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.GoPrev.Tag = "C1PreviewActionEnum.GoPrev"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.GoPrev.ToolTipText = resources.GetString("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.GoPrev.ToolTipText"); // // // this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.HistoryNext.Image = ((System.Drawing.Image)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.HistoryNext.Image"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.HistoryNext.ImageTransparentColor = ((System.Drawing.Color)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.HistoryNext.ImageTr" + "ansparentColor"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.HistoryNext.Name = "btnHistoryNext"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.HistoryNext.Size = ((System.Drawing.Size)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.HistoryNext.Size"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.HistoryNext.Tag = "C1PreviewActionEnum.HistoryNext"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.HistoryNext.ToolTipText = resources.GetString("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.HistoryNext.ToolTip" + "Text"); // // // this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.HistoryPrev.Image = ((System.Drawing.Image)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.HistoryPrev.Image"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.HistoryPrev.ImageTransparentColor = ((System.Drawing.Color)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.HistoryPrev.ImageTr" + "ansparentColor"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.HistoryPrev.Name = "btnHistoryPrev"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.HistoryPrev.Size = ((System.Drawing.Size)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.HistoryPrev.Size"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.HistoryPrev.Tag = "C1PreviewActionEnum.HistoryPrev"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.HistoryPrev.ToolTipText = resources.GetString("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.HistoryPrev.ToolTip" + "Text"); // // // this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.LblOfPages.Name = "lblOfPages"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.LblOfPages.Size = ((System.Drawing.Size)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.LblOfPages.Size"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.LblOfPages.Tag = "C1PreviewActionEnum.GoPageCount"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.LblOfPages.Text = resources.GetString("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.LblOfPages.Text"); // // // this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.LblPage.Name = "lblPage"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.LblPage.Size = ((System.Drawing.Size)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.LblPage.Size"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.LblPage.Tag = "C1PreviewActionEnum.GoPageLabel"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.LblPage.Text = resources.GetString("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.LblPage.Text"); // // // this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.PageNo.Name = "txtPageNo"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.PageNo.Size = ((System.Drawing.Size)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.PageNo.Size"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.PageNo.Tag = "C1PreviewActionEnum.GoPageNumber"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.PageNo.Text = resources.GetString("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.PageNo.Text"); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Navigation.ToolTipPageNo = null; // // // this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Page.Continuous.Checked = true; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Page.Continuous.CheckState = System.Windows.Forms.CheckState.Checked; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Page.Continuous.Image = ((System.Drawing.Image)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Page.Continuous.Image"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Page.Continuous.ImageTransparentColor = ((System.Drawing.Color)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Page.Continuous.ImageTranspare" + "ntColor"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Page.Continuous.Name = "btnPageContinuous"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Page.Continuous.Size = ((System.Drawing.Size)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Page.Continuous.Size"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Page.Continuous.Tag = "C1PreviewActionEnum.PageContinuous"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Page.Continuous.ToolTipText = resources.GetString("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Page.Continuous.ToolTipText"); // // // this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Page.Facing.Image = ((System.Drawing.Image)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Page.Facing.Image"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Page.Facing.ImageTransparentColor = ((System.Drawing.Color)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Page.Facing.ImageTransparentCo" + "lor"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Page.Facing.Name = "btnPageFacing"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Page.Facing.Size = ((System.Drawing.Size)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Page.Facing.Size"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Page.Facing.Tag = "C1PreviewActionEnum.PageFacing"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Page.Facing.ToolTipText = resources.GetString("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Page.Facing.ToolTipText"); // // // this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Page.FacingContinuous.Image = ((System.Drawing.Image)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Page.FacingContinuous.Image"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Page.FacingContinuous.ImageTransparentColor = ((System.Drawing.Color)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Page.FacingContinuous.ImageTra" + "nsparentColor"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Page.FacingContinuous.Name = "btnPageFacingContinuous"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Page.FacingContinuous.Size = ((System.Drawing.Size)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Page.FacingContinuous.Size"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Page.FacingContinuous.Tag = "C1PreviewActionEnum.PageFacingContinuous"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Page.FacingContinuous.ToolTipText = resources.GetString("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Page.FacingContinuous.ToolTipT" + "ext"); // // // this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Page.Single.Image = ((System.Drawing.Image)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Page.Single.Image"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Page.Single.ImageTransparentColor = ((System.Drawing.Color)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Page.Single.ImageTransparentCo" + "lor"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Page.Single.Name = "btnPageSingle"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Page.Single.Size = ((System.Drawing.Size)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Page.Single.Size"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Page.Single.Tag = "C1PreviewActionEnum.PageSingle"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Page.Single.ToolTipText = resources.GetString("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Page.Single.ToolTipText"); // // // this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Text.Find.Image = ((System.Drawing.Image)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Text.Find.Image"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Text.Find.ImageTransparentColor = ((System.Drawing.Color)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Text.Find.ImageTransparentColo" + "r"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Text.Find.Name = "btnFind"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Text.Find.Size = ((System.Drawing.Size)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Text.Find.Size"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Text.Find.Tag = "C1PreviewActionEnum.Find"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Text.Find.ToolTipText = resources.GetString("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Text.Find.ToolTipText"); // // // this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Text.Hand.Checked = true; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Text.Hand.CheckState = System.Windows.Forms.CheckState.Checked; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Text.Hand.Image = ((System.Drawing.Image)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Text.Hand.Image"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Text.Hand.ImageTransparentColor = ((System.Drawing.Color)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Text.Hand.ImageTransparentColo" + "r"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Text.Hand.Name = "btnHandTool"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Text.Hand.Size = ((System.Drawing.Size)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Text.Hand.Size"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Text.Hand.Tag = "C1PreviewActionEnum.HandTool"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Text.Hand.ToolTipText = resources.GetString("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Text.Hand.ToolTipText"); // // // this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Text.SelectText.Image = ((System.Drawing.Image)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Text.SelectText.Image"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Text.SelectText.ImageTransparentColor = ((System.Drawing.Color)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Text.SelectText.ImageTranspare" + "ntColor"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Text.SelectText.Name = "btnSelectTextTool"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Text.SelectText.Size = ((System.Drawing.Size)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Text.SelectText.Size"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Text.SelectText.Tag = "C1PreviewActionEnum.SelectTextTool"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Text.SelectText.ToolTipText = resources.GetString("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Text.SelectText.ToolTipText"); // // // this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Zoom.DropZoomFactor.Name = "dropZoomFactor"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Zoom.DropZoomFactor.Size = ((System.Drawing.Size)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Zoom.DropZoomFactor.Size"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Zoom.DropZoomFactor.Tag = "C1PreviewActionEnum.ZoomFactor"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Zoom.ToolTipZoomFactor = null; // // // this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Zoom.ZoomFactor.Name = "txtZoomFactor"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Zoom.ZoomFactor.Size = ((System.Drawing.Size)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Zoom.ZoomFactor.Size"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Zoom.ZoomFactor.Tag = "C1PreviewActionEnum.ZoomFactor"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Zoom.ZoomFactor.Text = resources.GetString("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Zoom.ZoomFactor.Text"); // // // this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Zoom.ZoomIn.Image = ((System.Drawing.Image)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Zoom.ZoomIn.Image"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Zoom.ZoomIn.ImageTransparentColor = ((System.Drawing.Color)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Zoom.ZoomIn.ImageTransparentCo" + "lor"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Zoom.ZoomIn.Name = "btnZoomIn"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Zoom.ZoomIn.Size = ((System.Drawing.Size)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Zoom.ZoomIn.Size"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Zoom.ZoomIn.Tag = "C1PreviewActionEnum.ZoomIn"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Zoom.ZoomIn.ToolTipText = resources.GetString("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Zoom.ZoomIn.ToolTipText"); // // // this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Zoom.ZoomOut.Image = ((System.Drawing.Image)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Zoom.ZoomOut.Image"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Zoom.ZoomOut.ImageTransparentColor = ((System.Drawing.Color)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Zoom.ZoomOut.ImageTransparentC" + "olor"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Zoom.ZoomOut.Name = "btnZoomOut"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Zoom.ZoomOut.Size = ((System.Drawing.Size)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Zoom.ZoomOut.Size"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Zoom.ZoomOut.Tag = "C1PreviewActionEnum.ZoomOut"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Zoom.ZoomOut.ToolTipText = resources.GetString("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Zoom.ZoomOut.ToolTipText"); // // // this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Zoom.ZoomTool.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Zoom.ZoomInTool, this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Zoom.ZoomOutTool}); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Zoom.ZoomTool.Image = ((System.Drawing.Image)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Zoom.ZoomTool.Image"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Zoom.ZoomTool.ImageTransparentColor = ((System.Drawing.Color)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Zoom.ZoomTool.ImageTransparent" + "Color"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Zoom.ZoomTool.Name = "btnZoomTool"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Zoom.ZoomTool.Size = ((System.Drawing.Size)(resources.GetObject("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Zoom.ZoomTool.Size"))); this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Zoom.ZoomTool.Tag = "C1PreviewActionEnum.ZoomInTool"; this.c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Zoom.ZoomTool.ToolTipText = resources.GetString("c1PrintPreviewDialog1.PrintPreviewControl.ToolBars.Zoom.ZoomTool.ToolTipText"); this.c1PrintPreviewDialog1.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Auto; // // chlList // resources.ApplyResources(this.chlList, "chlList"); this.chlList.Name = "chlList"; // // btnOK // resources.ApplyResources(this.btnOK, "btnOK"); this.btnOK.Name = "btnOK"; this.btnOK.Click += new System.EventHandler(this.btnOK_Click); // // btnClose // this.btnClose.DialogResult = System.Windows.Forms.DialogResult.Cancel; resources.ApplyResources(this.btnClose, "btnClose"); this.btnClose.Name = "btnClose"; this.btnClose.Click += new System.EventHandler(this.btnClose_Click); // // c1Report1 // this.c1Report1.ReportDefinition = resources.GetString("c1Report1.ReportDefinition"); this.c1Report1.ReportName = "c1Report1"; // // c1PrintDocument1 // this.c1PrintDocument1.DocumentInfo.Creator = "C1Reports Engine version 2.6.20101.54005"; // // UserCCNList // resources.ApplyResources(this, "$this"); this.CancelButton = this.btnClose; this.Controls.Add(this.btnClose); this.Controls.Add(this.btnOK); this.Controls.Add(this.chlList); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D; this.MaximizeBox = false; this.Name = "UserCCNList"; this.Load += new System.EventHandler(this.UserCCNList_Load); ((System.ComponentModel.ISupportInitialize)(this.c1PrintPreviewDialog1.PrintPreviewControl.PreviewPane)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.c1PrintPreviewDialog1.PrintPreviewControl)).EndInit(); this.c1PrintPreviewDialog1.PrintPreviewControl.ResumeLayout(false); this.c1PrintPreviewDialog1.PrintPreviewControl.PerformLayout(); this.c1PrintPreviewDialog1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.c1Report1)).EndInit(); this.ResumeLayout(false); } #endregion private void UserCCNList_Load(object sender, EventArgs e) { // Code Inserted Automatically #region Code Inserted Automatically this.Cursor = Cursors.WaitCursor; #endregion Code Inserted Automatically const string METHOD_NAME = THIS + ".UserCCNList_Load()"; try { #region Security //Set authorization for user Security objSecurity = new Security(); this.Name = THIS; if(objSecurity.SetRightForUserOnForm(this, SystemProperty.UserName) == 0) { this.Close(); // You don't have the right to view this item PCSMessageBox.Show(ErrorCode.MESSAGE_YOU_HAVE_NO_RIGHT_TO_VIEW); // Code Inserted Automatically #region Code Inserted Automatically this.Cursor = Cursors.Default; #endregion Code Inserted Automatically return; } #endregion chlList.DataSource = tblData; chlList.DisplayMember = strDisplayMember; chlList.ValueMember = strValueMember; } catch (PCSException ex) { // displays the error message. PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error); } } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error); } } // Code Inserted Automatically #region Code Inserted Automatically this.Cursor = Cursors.Default; #endregion Code Inserted Automatically } private void btnOK_Click(object sender, EventArgs e) { // Code Inserted Automatically #region Code Inserted Automatically this.Cursor = Cursors.WaitCursor; #endregion Code Inserted Automatically const string METHOD_NAME = THIS + ".btnOK_Click()"; try { // get all checked item and add to arraylist foreach (int intIndex in chlList.CheckedIndices) { marrReturnsList.Add(tblData.Rows[intIndex][strValueMember]); } marrReturnsList.TrimToSize(); // close the form this.Close(); } catch (PCSException ex) { // displays the error message. PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error); } } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error); } } // Code Inserted Automatically #region Code Inserted Automatically this.Cursor = Cursors.Default; #endregion Code Inserted Automatically } private void btnClose_Click(object sender, EventArgs e) { // Code Inserted Automatically #region Code Inserted Automatically this.Cursor = Cursors.WaitCursor; #endregion Code Inserted Automatically this.Close(); // Code Inserted Automatically #region Code Inserted Automatically this.Cursor = Cursors.Default; #endregion Code Inserted Automatically } } }
#if OS_WINDOWS using Microsoft.VisualStudio.Services.Agent; using Microsoft.VisualStudio.Services.Agent.Util; using Microsoft.TeamFoundation.DistributedTask.WebApi; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Security.Principal; using System.Threading; using System.Threading.Tasks; namespace Microsoft.VisualStudio.Services.Agent.Listener.Configuration { [ServiceLocator(Default = typeof(AutoLogonManager))] public interface IAutoLogonManager : IAgentService { Task ConfigureAsync(CommandSettings command); void Unconfigure(); } public class AutoLogonManager : AgentService, IAutoLogonManager { private ITerminal _terminal; private INativeWindowsServiceHelper _windowsServiceHelper; private IAutoLogonRegistryManager _autoLogonRegManager; private IConfigurationStore _store; public override void Initialize(IHostContext hostContext) { base.Initialize(hostContext); _terminal = hostContext.GetService<ITerminal>(); _windowsServiceHelper = hostContext.GetService<INativeWindowsServiceHelper>(); _autoLogonRegManager = HostContext.GetService<IAutoLogonRegistryManager>(); _store = hostContext.GetService<IConfigurationStore>(); } public async Task ConfigureAsync(CommandSettings command) { if (!_windowsServiceHelper.IsRunningInElevatedMode()) { Trace.Error("Needs Administrator privileges to configure agent with AutoLogon capability."); throw new SecurityException(StringUtil.Loc("NeedAdminForAutologonCapability")); } string domainName; string userName; string logonAccount; string logonPassword; while (true) { logonAccount = command.GetWindowsLogonAccount(defaultValue: string.Empty, descriptionMsg: StringUtil.Loc("AutoLogonAccountNameDescription")); GetAccountSegments(logonAccount, out domainName, out userName); if ((string.IsNullOrEmpty(domainName) || domainName.Equals(".", StringComparison.CurrentCultureIgnoreCase)) && !logonAccount.Contains("@")) { logonAccount = String.Format("{0}\\{1}", Environment.MachineName, userName); } Trace.Info("LogonAccount after transforming: {0}, user: {1}, domain: {2}", logonAccount, userName, domainName); logonPassword = command.GetWindowsLogonPassword(logonAccount); if (_windowsServiceHelper.IsValidAutoLogonCredential(domainName, userName, logonPassword)) { Trace.Info("Credential validation succeeded"); break; } if (command.Unattended) { throw new SecurityException(StringUtil.Loc("InvalidAutoLogonCredential")); } Trace.Error("Invalid credential entered."); _terminal.WriteError(StringUtil.Loc("InvalidAutoLogonCredential")); } _autoLogonRegManager.GetAutoLogonUserDetails(out string currentAutoLogonUserDomainName, out string currentAutoLogonUserName); if (currentAutoLogonUserName != null && !userName.Equals(currentAutoLogonUserName, StringComparison.CurrentCultureIgnoreCase) && !domainName.Equals(currentAutoLogonUserDomainName, StringComparison.CurrentCultureIgnoreCase)) { string currentAutoLogonAccount = String.Format("{0}\\{1}", currentAutoLogonUserDomainName, currentAutoLogonUserName); if (string.IsNullOrEmpty(currentAutoLogonUserDomainName) || currentAutoLogonUserDomainName.Equals(".", StringComparison.CurrentCultureIgnoreCase)) { currentAutoLogonAccount = String.Format("{0}\\{1}", Environment.MachineName, currentAutoLogonUserName); } Trace.Warning($"AutoLogon already enabled for {currentAutoLogonAccount}."); if(!command.GetOverwriteAutoLogonSettings(currentAutoLogonAccount)) { Trace.Error("Marking the agent configuration as failed due to the denial of autologon setting overwriting by the user."); throw new Exception(StringUtil.Loc("AutoLogonOverwriteDeniedError", currentAutoLogonAccount)); } Trace.Info($"Continuing with the autologon configuration."); } _autoLogonRegManager.UpdateRegistrySettings(command, domainName, userName, logonPassword); _windowsServiceHelper.SetAutoLogonPassword(logonPassword); await ConfigurePowerOptions(); SaveAutoLogonSettings(domainName, userName); RestartBasedOnUserInput(command); } public void Unconfigure() { if (!_windowsServiceHelper.IsRunningInElevatedMode()) { Trace.Error("Needs Administrator privileges to unconfigure an agent running with AutoLogon capability."); throw new SecurityException(StringUtil.Loc("NeedAdminForAutologonRemoval")); } var autoLogonSettings = _store.GetAutoLogonSettings(); _autoLogonRegManager.RevertRegistrySettings(autoLogonSettings.UserDomainName, autoLogonSettings.UserName); _windowsServiceHelper.ResetAutoLogonPassword(); Trace.Info("Deleting the autologon settings now."); _store.DeleteAutoLogonSettings(); Trace.Info("Successfully deleted the autologon settings."); } private void SaveAutoLogonSettings(string domainName, string userName) { Trace.Entering(); var settings = new AutoLogonSettings() { UserDomainName = domainName, UserName = userName }; _store.SaveAutoLogonSettings(settings); Trace.Info("Saved the autologon settings"); } private async Task ConfigurePowerOptions() { var whichUtil = HostContext.GetService<IWhichUtil>(); var filePath = whichUtil.Which("powercfg.exe", require:true); string[] commands = new string[] {"/Change monitor-timeout-ac 0", "/Change monitor-timeout-dc 0"}; foreach (var command in commands) { try { Trace.Info($"Running powercfg.exe with {command}"); using (var processInvoker = HostContext.CreateService<IProcessInvoker>()) { processInvoker.OutputDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message) { Trace.Info(message.Data); }; processInvoker.ErrorDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message) { Trace.Error(message.Data); _terminal.WriteError(message.Data); }; await processInvoker.ExecuteAsync( workingDirectory: string.Empty, fileName: filePath, arguments: command, environment: null, cancellationToken: CancellationToken.None); } } catch(Exception ex) { //we will not stop the configuration. just show the warning and continue _terminal.WriteError(StringUtil.Loc("PowerOptionsConfigError")); Trace.Error(ex); } } } private void RestartBasedOnUserInput(CommandSettings command) { Trace.Info("Asking the user to restart the machine to launch agent and for autologon settings to take effect."); _terminal.WriteLine(StringUtil.Loc("RestartMessage")); var noRestart = command.GetNoRestart(); if (!noRestart) { var whichUtil = HostContext.GetService<IWhichUtil>(); var shutdownExePath = whichUtil.Which("shutdown.exe"); Trace.Info("Restarting the machine in 15 seconds"); _terminal.WriteLine(StringUtil.Loc("RestartIn15SecMessage")); string msg = StringUtil.Loc("ShutdownMessage"); //we are not using ProcessInvoker here as today it is not designed for 'fire and forget' pattern //ExecuteAsync API of ProcessInvoker waits for the process to exit var args = $@"-r -t 15 -c ""{msg}"""; Trace.Info($"Shutdown.exe path: {shutdownExePath}. Arguments: {args}"); Process.Start(shutdownExePath, $@"{args}"); } else { _terminal.WriteLine(StringUtil.Loc("NoRestartSuggestion")); } } //todo: move it to a utility class so that at other places it can be re-used private void GetAccountSegments(string account, out string domain, out string user) { string[] segments = account.Split('\\'); domain = string.Empty; user = account; if (segments.Length == 2) { domain = segments[0]; user = segments[1]; } } } } #endif
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; using Xunit; namespace System.Reflection.Emit.Tests { public class TypeBuilderSize { [Fact] public void TestSizeAssignedInGenericTypeBuilder() { TypeBuilder myBuilder = CreateTypeBuilderWithGenericFilledSize(); Assert.Equal(100, myBuilder.Size); } [Fact] public void TestDefaultSizeIsZeroInGenericTypeBuilder() { TypeBuilder myBuilder = CreateTypeBuilderWithGenericIgnoreSize(); Assert.Equal(0, myBuilder.Size); } [Fact] public void TestSizeAssignedInNonGenericTypeBuilder() { TypeBuilder myBuilder = CreateTypeBuilderWithoutGenericFilledSize(); Assert.Equal(100, myBuilder.Size); } [Fact] public void TestDefaultSizeIsZeroInNonGenericTypeBuilder() { TypeBuilder myBuilder = CreateTypeBuilderWithoutGenericFilledSize(); Assert.Equal(100, myBuilder.Size); } [Fact] public void TestSizeAssignedInNestedTypeBuilder() { TypeBuilder myBuilder = GetNestedTypeBuilder(); Assert.Equal(100, myBuilder.Size); } private TypeBuilder CreateTypeBuilderWithGenericFilledSize() { AssemblyName myAsmName = new AssemblyName("TypeBuilderGetFieldExample"); AssemblyBuilder myAssembly = AssemblyBuilder.DefineDynamicAssembly( myAsmName, AssemblyBuilderAccess.Run); ModuleBuilder myModule = TestLibrary.Utilities.GetModuleBuilder(myAssembly, "Module1"); TypeBuilder myType = myModule.DefineType("Sample", TypeAttributes.Class | TypeAttributes.Public, null, 100); string[] typeParamNames = { "T" }; GenericTypeParameterBuilder[] typeParams = myType.DefineGenericParameters(typeParamNames); ConstructorBuilder ctor = myType.DefineDefaultConstructor( MethodAttributes.PrivateScope | MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName); FieldBuilder myField = myType.DefineField("Field", typeParams[0].AsType(), FieldAttributes.Public); MethodBuilder genMethod = myType.DefineMethod("GM", MethodAttributes.Public | MethodAttributes.Static); string[] methodParamNames = { "U" }; GenericTypeParameterBuilder[] methodParams = genMethod.DefineGenericParameters(methodParamNames); genMethod.SetSignature(null, null, null, new Type[] { methodParams[0].AsType() }, null, null); ILGenerator ilg = genMethod.GetILGenerator(); Type SampleOfU = myType.MakeGenericType(methodParams[0].AsType()); ilg.DeclareLocal(SampleOfU); ConstructorInfo ctorOfU = TypeBuilder.GetConstructor( SampleOfU, ctor); ilg.Emit(OpCodes.Newobj, ctorOfU); ilg.Emit(OpCodes.Stloc_0); ilg.Emit(OpCodes.Ldloc_0); ilg.Emit(OpCodes.Ldarg_0); FieldInfo FieldOfU = TypeBuilder.GetField( SampleOfU, myField); ilg.Emit(OpCodes.Stfld, FieldOfU); ilg.Emit(OpCodes.Ldloc_0); ilg.Emit(OpCodes.Ldfld, FieldOfU); ilg.Emit(OpCodes.Box, methodParams[0].AsType()); MethodInfo writeLineObj = typeof(Console).GetMethod("WriteLine", new Type[] { typeof(object) }); ilg.EmitCall(OpCodes.Call, writeLineObj, null); ilg.Emit(OpCodes.Ret); TypeBuilder dummy = myModule.DefineType("Dummy", TypeAttributes.Class | TypeAttributes.NotPublic); MethodBuilder entryPoint = dummy.DefineMethod("Main", MethodAttributes.Public | MethodAttributes.Static, null, null); ilg = entryPoint.GetILGenerator(); Type SampleOfInt = myType.MakeGenericType(typeof(int)); MethodInfo SampleOfIntGM = TypeBuilder.GetMethod(SampleOfInt, genMethod); MethodInfo GMOfString = SampleOfIntGM.MakeGenericMethod(typeof(string)); ilg.Emit(OpCodes.Ldstr, "Hello, world!"); ilg.EmitCall(OpCodes.Call, GMOfString, null); ilg.Emit(OpCodes.Ret); myType.CreateTypeInfo().AsType(); return myType; } private TypeBuilder CreateTypeBuilderWithGenericIgnoreSize() { AssemblyName myAsmName = new AssemblyName("TypeBuilderGetFieldExample"); AssemblyBuilder myAssembly = AssemblyBuilder.DefineDynamicAssembly( myAsmName, AssemblyBuilderAccess.Run); ModuleBuilder myModule = TestLibrary.Utilities.GetModuleBuilder(myAssembly, "Module1"); TypeBuilder myType = myModule.DefineType("Sample", TypeAttributes.Class | TypeAttributes.Public); string[] typeParamNames = { "T" }; GenericTypeParameterBuilder[] typeParams = myType.DefineGenericParameters(typeParamNames); ConstructorBuilder ctor = myType.DefineDefaultConstructor( MethodAttributes.PrivateScope | MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName); FieldBuilder myField = myType.DefineField("Field", typeParams[0].AsType(), FieldAttributes.Public); MethodBuilder genMethod = myType.DefineMethod("GM", MethodAttributes.Public | MethodAttributes.Static); string[] methodParamNames = { "U" }; GenericTypeParameterBuilder[] methodParams = genMethod.DefineGenericParameters(methodParamNames); genMethod.SetSignature(null, null, null, new Type[] { methodParams[0].AsType() }, null, null); ILGenerator ilg = genMethod.GetILGenerator(); Type SampleOfU = myType.MakeGenericType(methodParams[0].AsType()); ilg.DeclareLocal(SampleOfU); ConstructorInfo ctorOfU = TypeBuilder.GetConstructor( SampleOfU, ctor); ilg.Emit(OpCodes.Newobj, ctorOfU); ilg.Emit(OpCodes.Stloc_0); ilg.Emit(OpCodes.Ldloc_0); ilg.Emit(OpCodes.Ldarg_0); FieldInfo FieldOfU = TypeBuilder.GetField( SampleOfU, myField); ilg.Emit(OpCodes.Stfld, FieldOfU); ilg.Emit(OpCodes.Ldloc_0); ilg.Emit(OpCodes.Ldfld, FieldOfU); ilg.Emit(OpCodes.Box, methodParams[0].AsType()); MethodInfo writeLineObj = typeof(Console).GetMethod("WriteLine", new Type[] { typeof(object) }); ilg.EmitCall(OpCodes.Call, writeLineObj, null); ilg.Emit(OpCodes.Ret); TypeBuilder dummy = myModule.DefineType("Dummy", TypeAttributes.Class | TypeAttributes.NotPublic); MethodBuilder entryPoint = dummy.DefineMethod("Main", MethodAttributes.Public | MethodAttributes.Static, null, null); ilg = entryPoint.GetILGenerator(); Type SampleOfInt = myType.MakeGenericType(typeof(int)); MethodInfo SampleOfIntGM = TypeBuilder.GetMethod(SampleOfInt, genMethod); MethodInfo GMOfString = SampleOfIntGM.MakeGenericMethod(typeof(string)); ilg.Emit(OpCodes.Ldstr, "Hello, world!"); ilg.EmitCall(OpCodes.Call, GMOfString, null); ilg.Emit(OpCodes.Ret); myType.CreateTypeInfo().AsType(); return myType; } private TypeBuilder CreateTypeBuilderWithoutGenericFilledSize() { AssemblyName myAsmName = new AssemblyName("TestTypeBuilder"); AssemblyBuilder myAssembly = AssemblyBuilder.DefineDynamicAssembly( myAsmName, AssemblyBuilderAccess.Run); ModuleBuilder myModule = TestLibrary.Utilities.GetModuleBuilder(myAssembly, "Module1"); TypeBuilder TestType = myModule.DefineType("Test", TypeAttributes.Class | TypeAttributes.Public, null, 100); MethodBuilder entry = TestType.DefineMethod("Main", MethodAttributes.Public | MethodAttributes.Static, null, null); ILGenerator ilg = entry.GetILGenerator(); ilg.Emit(OpCodes.Ldstr, "Test string here."); MethodInfo writeObj = typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }); ilg.EmitCall(OpCodes.Call, writeObj, null); ilg.Emit(OpCodes.Ret); TestType.CreateTypeInfo().AsType(); return TestType; } private TypeBuilder CreateTypeBuilderWithoutGenericIgnoreSize() { AssemblyName myAsmName = new AssemblyName("TestTypeBuilder"); AssemblyBuilder myAssembly = AssemblyBuilder.DefineDynamicAssembly( myAsmName, AssemblyBuilderAccess.Run); ModuleBuilder myModule = TestLibrary.Utilities.GetModuleBuilder(myAssembly, "Module1"); TypeBuilder TestType = myModule.DefineType("Test", TypeAttributes.Class | TypeAttributes.Public); MethodBuilder entry = TestType.DefineMethod("Main", MethodAttributes.Public | MethodAttributes.Static, null, null); ILGenerator ilg = entry.GetILGenerator(); ilg.Emit(OpCodes.Ldstr, "Test string here."); MethodInfo writeObj = typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }); ilg.EmitCall(OpCodes.Call, writeObj, null); ilg.Emit(OpCodes.Ret); TestType.CreateTypeInfo().AsType(); return TestType; } private TypeBuilder GetNestedTypeBuilder() { ModuleBuilder myModule = BuildModule(); TypeBuilder myBuilder = myModule.DefineType("Test", TypeAttributes.Abstract | TypeAttributes.Public | TypeAttributes.Class, null, 200); TypeBuilder myNestedBuilder = myBuilder.DefineNestedType("Lily", TypeAttributes.Class | TypeAttributes.Abstract | TypeAttributes.NestedPublic, null, 100); MethodBuilder mainBuilder = myBuilder.DefineMethod("Main", MethodAttributes.Public | MethodAttributes.Static, null, null); ILGenerator ilg = mainBuilder.GetILGenerator(); MethodInfo writeLineObj = typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }); ilg.Emit(OpCodes.Ldstr, "Test string here."); ilg.EmitCall(OpCodes.Call, writeLineObj, null); ilg.Emit(OpCodes.Ret); myBuilder.AsType(); myNestedBuilder.AsType(); return myNestedBuilder; } private ModuleBuilder BuildModule() { AssemblyName myAsmName = new AssemblyName("MyTypeBuilder"); AssemblyBuilder myAssembly = AssemblyBuilder.DefineDynamicAssembly( myAsmName, AssemblyBuilderAccess.Run); ModuleBuilder myModule = TestLibrary.Utilities.GetModuleBuilder(myAssembly, "Module1"); return myModule; } } }
using MasterDevs.ChromeDevTools; namespace MasterDevs.ChromeDevTools.Protocol.Chrome { public static class ProtocolName { public static class Schema { public const string GetDomains = "Schema.getDomains"; } public static class Runtime { public const string Evaluate = "Runtime.evaluate"; public const string AwaitPromise = "Runtime.awaitPromise"; public const string CallFunctionOn = "Runtime.callFunctionOn"; public const string GetProperties = "Runtime.getProperties"; public const string ReleaseObject = "Runtime.releaseObject"; public const string ReleaseObjectGroup = "Runtime.releaseObjectGroup"; public const string RunIfWaitingForDebugger = "Runtime.runIfWaitingForDebugger"; public const string Enable = "Runtime.enable"; public const string Disable = "Runtime.disable"; public const string DiscardConsoleEntries = "Runtime.discardConsoleEntries"; public const string SetCustomObjectFormatterEnabled = "Runtime.setCustomObjectFormatterEnabled"; public const string CompileScript = "Runtime.compileScript"; public const string RunScript = "Runtime.runScript"; public const string QueryObjects = "Runtime.queryObjects"; public const string ExecutionContextCreated = "Runtime.executionContextCreated"; public const string ExecutionContextDestroyed = "Runtime.executionContextDestroyed"; public const string ExecutionContextsCleared = "Runtime.executionContextsCleared"; public const string ExceptionThrown = "Runtime.exceptionThrown"; public const string ExceptionRevoked = "Runtime.exceptionRevoked"; public const string ConsoleAPICalled = "Runtime.consoleAPICalled"; public const string InspectRequested = "Runtime.inspectRequested"; } public static class Debugger { public const string Enable = "Debugger.enable"; public const string Disable = "Debugger.disable"; public const string SetBreakpointsActive = "Debugger.setBreakpointsActive"; public const string SetSkipAllPauses = "Debugger.setSkipAllPauses"; public const string SetBreakpointByUrl = "Debugger.setBreakpointByUrl"; public const string SetBreakpoint = "Debugger.setBreakpoint"; public const string RemoveBreakpoint = "Debugger.removeBreakpoint"; public const string GetPossibleBreakpoints = "Debugger.getPossibleBreakpoints"; public const string ContinueToLocation = "Debugger.continueToLocation"; public const string StepOver = "Debugger.stepOver"; public const string StepInto = "Debugger.stepInto"; public const string StepOut = "Debugger.stepOut"; public const string Pause = "Debugger.pause"; public const string ScheduleStepIntoAsync = "Debugger.scheduleStepIntoAsync"; public const string Resume = "Debugger.resume"; public const string SearchInContent = "Debugger.searchInContent"; public const string SetScriptSource = "Debugger.setScriptSource"; public const string RestartFrame = "Debugger.restartFrame"; public const string GetScriptSource = "Debugger.getScriptSource"; public const string SetPauseOnExceptions = "Debugger.setPauseOnExceptions"; public const string EvaluateOnCallFrame = "Debugger.evaluateOnCallFrame"; public const string SetVariableValue = "Debugger.setVariableValue"; public const string SetAsyncCallStackDepth = "Debugger.setAsyncCallStackDepth"; public const string SetBlackboxPatterns = "Debugger.setBlackboxPatterns"; public const string SetBlackboxedRanges = "Debugger.setBlackboxedRanges"; public const string ScriptParsed = "Debugger.scriptParsed"; public const string ScriptFailedToParse = "Debugger.scriptFailedToParse"; public const string BreakpointResolved = "Debugger.breakpointResolved"; public const string Paused = "Debugger.paused"; public const string Resumed = "Debugger.resumed"; } public static class Console { public const string Enable = "Console.enable"; public const string Disable = "Console.disable"; public const string ClearMessages = "Console.clearMessages"; public const string MessageAdded = "Console.messageAdded"; } public static class Profiler { public const string Enable = "Profiler.enable"; public const string Disable = "Profiler.disable"; public const string SetSamplingInterval = "Profiler.setSamplingInterval"; public const string Start = "Profiler.start"; public const string Stop = "Profiler.stop"; public const string StartPreciseCoverage = "Profiler.startPreciseCoverage"; public const string StopPreciseCoverage = "Profiler.stopPreciseCoverage"; public const string TakePreciseCoverage = "Profiler.takePreciseCoverage"; public const string GetBestEffortCoverage = "Profiler.getBestEffortCoverage"; public const string ConsoleProfileStarted = "Profiler.consoleProfileStarted"; public const string ConsoleProfileFinished = "Profiler.consoleProfileFinished"; } public static class HeapProfiler { public const string Enable = "HeapProfiler.enable"; public const string Disable = "HeapProfiler.disable"; public const string StartTrackingHeapObjects = "HeapProfiler.startTrackingHeapObjects"; public const string StopTrackingHeapObjects = "HeapProfiler.stopTrackingHeapObjects"; public const string TakeHeapSnapshot = "HeapProfiler.takeHeapSnapshot"; public const string CollectGarbage = "HeapProfiler.collectGarbage"; public const string GetObjectByHeapObjectId = "HeapProfiler.getObjectByHeapObjectId"; public const string AddInspectedHeapObject = "HeapProfiler.addInspectedHeapObject"; public const string GetHeapObjectId = "HeapProfiler.getHeapObjectId"; public const string StartSampling = "HeapProfiler.startSampling"; public const string StopSampling = "HeapProfiler.stopSampling"; public const string AddHeapSnapshotChunk = "HeapProfiler.addHeapSnapshotChunk"; public const string ResetProfiles = "HeapProfiler.resetProfiles"; public const string ReportHeapSnapshotProgress = "HeapProfiler.reportHeapSnapshotProgress"; public const string LastSeenObjectId = "HeapProfiler.lastSeenObjectId"; public const string HeapStatsUpdate = "HeapProfiler.heapStatsUpdate"; } public static class Inspector { public const string Enable = "Inspector.enable"; public const string Disable = "Inspector.disable"; public const string Detached = "Inspector.detached"; public const string TargetCrashed = "Inspector.targetCrashed"; } public static class Memory { public const string GetDOMCounters = "Memory.getDOMCounters"; public const string PrepareForLeakDetection = "Memory.prepareForLeakDetection"; public const string SetPressureNotificationsSuppressed = "Memory.setPressureNotificationsSuppressed"; public const string SimulatePressureNotification = "Memory.simulatePressureNotification"; } public static class Performance { public const string Enable = "Performance.enable"; public const string Disable = "Performance.disable"; public const string GetMetrics = "Performance.getMetrics"; public const string Metrics = "Performance.metrics"; } public static class Page { public const string Enable = "Page.enable"; public const string Disable = "Page.disable"; public const string AddScriptToEvaluateOnLoad = "Page.addScriptToEvaluateOnLoad"; public const string RemoveScriptToEvaluateOnLoad = "Page.removeScriptToEvaluateOnLoad"; public const string AddScriptToEvaluateOnNewDocument = "Page.addScriptToEvaluateOnNewDocument"; public const string RemoveScriptToEvaluateOnNewDocument = "Page.removeScriptToEvaluateOnNewDocument"; public const string SetAutoAttachToCreatedPages = "Page.setAutoAttachToCreatedPages"; public const string Reload = "Page.reload"; public const string SetAdBlockingEnabled = "Page.setAdBlockingEnabled"; public const string Navigate = "Page.navigate"; public const string StopLoading = "Page.stopLoading"; public const string GetNavigationHistory = "Page.getNavigationHistory"; public const string NavigateToHistoryEntry = "Page.navigateToHistoryEntry"; public const string GetCookies = "Page.getCookies"; public const string DeleteCookie = "Page.deleteCookie"; public const string GetResourceTree = "Page.getResourceTree"; public const string GetResourceContent = "Page.getResourceContent"; public const string SearchInResource = "Page.searchInResource"; public const string SetDocumentContent = "Page.setDocumentContent"; public const string SetDeviceMetricsOverride = "Page.setDeviceMetricsOverride"; public const string ClearDeviceMetricsOverride = "Page.clearDeviceMetricsOverride"; public const string SetGeolocationOverride = "Page.setGeolocationOverride"; public const string ClearGeolocationOverride = "Page.clearGeolocationOverride"; public const string SetDeviceOrientationOverride = "Page.setDeviceOrientationOverride"; public const string ClearDeviceOrientationOverride = "Page.clearDeviceOrientationOverride"; public const string SetTouchEmulationEnabled = "Page.setTouchEmulationEnabled"; public const string CaptureScreenshot = "Page.captureScreenshot"; public const string PrintToPDF = "Page.printToPDF"; public const string StartScreencast = "Page.startScreencast"; public const string StopScreencast = "Page.stopScreencast"; public const string ScreencastFrameAck = "Page.screencastFrameAck"; public const string HandleJavaScriptDialog = "Page.handleJavaScriptDialog"; public const string GetAppManifest = "Page.getAppManifest"; public const string RequestAppBanner = "Page.requestAppBanner"; public const string GetLayoutMetrics = "Page.getLayoutMetrics"; public const string CreateIsolatedWorld = "Page.createIsolatedWorld"; public const string BringToFront = "Page.bringToFront"; public const string SetDownloadBehavior = "Page.setDownloadBehavior"; public const string DomContentEventFired = "Page.domContentEventFired"; public const string LoadEventFired = "Page.loadEventFired"; public const string LifecycleEvent = "Page.lifecycleEvent"; public const string FrameAttached = "Page.frameAttached"; public const string FrameNavigated = "Page.frameNavigated"; public const string FrameDetached = "Page.frameDetached"; public const string FrameStartedLoading = "Page.frameStartedLoading"; public const string FrameStoppedLoading = "Page.frameStoppedLoading"; public const string FrameScheduledNavigation = "Page.frameScheduledNavigation"; public const string FrameClearedScheduledNavigation = "Page.frameClearedScheduledNavigation"; public const string FrameResized = "Page.frameResized"; public const string JavascriptDialogOpening = "Page.javascriptDialogOpening"; public const string JavascriptDialogClosed = "Page.javascriptDialogClosed"; public const string ScreencastFrame = "Page.screencastFrame"; public const string ScreencastVisibilityChanged = "Page.screencastVisibilityChanged"; public const string InterstitialShown = "Page.interstitialShown"; public const string InterstitialHidden = "Page.interstitialHidden"; } public static class Overlay { public const string Enable = "Overlay.enable"; public const string Disable = "Overlay.disable"; public const string SetShowPaintRects = "Overlay.setShowPaintRects"; public const string SetShowDebugBorders = "Overlay.setShowDebugBorders"; public const string SetShowFPSCounter = "Overlay.setShowFPSCounter"; public const string SetShowScrollBottleneckRects = "Overlay.setShowScrollBottleneckRects"; public const string SetShowViewportSizeOnResize = "Overlay.setShowViewportSizeOnResize"; public const string SetPausedInDebuggerMessage = "Overlay.setPausedInDebuggerMessage"; public const string SetSuspended = "Overlay.setSuspended"; public const string SetInspectMode = "Overlay.setInspectMode"; public const string HighlightRect = "Overlay.highlightRect"; public const string HighlightQuad = "Overlay.highlightQuad"; public const string HighlightNode = "Overlay.highlightNode"; public const string HighlightFrame = "Overlay.highlightFrame"; public const string HideHighlight = "Overlay.hideHighlight"; public const string GetHighlightObjectForTest = "Overlay.getHighlightObjectForTest"; public const string NodeHighlightRequested = "Overlay.nodeHighlightRequested"; public const string InspectNodeRequested = "Overlay.inspectNodeRequested"; public const string ScreenshotRequested = "Overlay.screenshotRequested"; } public static class Emulation { public const string SetDeviceMetricsOverride = "Emulation.setDeviceMetricsOverride"; public const string ClearDeviceMetricsOverride = "Emulation.clearDeviceMetricsOverride"; public const string ResetPageScaleFactor = "Emulation.resetPageScaleFactor"; public const string SetPageScaleFactor = "Emulation.setPageScaleFactor"; public const string SetVisibleSize = "Emulation.setVisibleSize"; public const string SetScriptExecutionDisabled = "Emulation.setScriptExecutionDisabled"; public const string SetGeolocationOverride = "Emulation.setGeolocationOverride"; public const string ClearGeolocationOverride = "Emulation.clearGeolocationOverride"; public const string SetTouchEmulationEnabled = "Emulation.setTouchEmulationEnabled"; public const string SetEmitTouchEventsForMouse = "Emulation.setEmitTouchEventsForMouse"; public const string SetEmulatedMedia = "Emulation.setEmulatedMedia"; public const string SetCPUThrottlingRate = "Emulation.setCPUThrottlingRate"; public const string CanEmulate = "Emulation.canEmulate"; public const string SetVirtualTimePolicy = "Emulation.setVirtualTimePolicy"; public const string SetDefaultBackgroundColorOverride = "Emulation.setDefaultBackgroundColorOverride"; public const string VirtualTimeBudgetExpired = "Emulation.virtualTimeBudgetExpired"; public const string VirtualTimePaused = "Emulation.virtualTimePaused"; } public static class Security { public const string Enable = "Security.enable"; public const string Disable = "Security.disable"; public const string HandleCertificateError = "Security.handleCertificateError"; public const string SetOverrideCertificateErrors = "Security.setOverrideCertificateErrors"; public const string SecurityStateChanged = "Security.securityStateChanged"; public const string CertificateError = "Security.certificateError"; } public static class Audits { public const string GetEncodedResponse = "Audits.getEncodedResponse"; } public static class Network { public const string Enable = "Network.enable"; public const string Disable = "Network.disable"; public const string SetUserAgentOverride = "Network.setUserAgentOverride"; public const string SetExtraHTTPHeaders = "Network.setExtraHTTPHeaders"; public const string GetResponseBody = "Network.getResponseBody"; public const string SetBlockedURLs = "Network.setBlockedURLs"; public const string ReplayXHR = "Network.replayXHR"; public const string CanClearBrowserCache = "Network.canClearBrowserCache"; public const string ClearBrowserCache = "Network.clearBrowserCache"; public const string CanClearBrowserCookies = "Network.canClearBrowserCookies"; public const string ClearBrowserCookies = "Network.clearBrowserCookies"; public const string GetCookies = "Network.getCookies"; public const string GetAllCookies = "Network.getAllCookies"; public const string DeleteCookies = "Network.deleteCookies"; public const string SetCookie = "Network.setCookie"; public const string SetCookies = "Network.setCookies"; public const string CanEmulateNetworkConditions = "Network.canEmulateNetworkConditions"; public const string EmulateNetworkConditions = "Network.emulateNetworkConditions"; public const string SetCacheDisabled = "Network.setCacheDisabled"; public const string SetBypassServiceWorker = "Network.setBypassServiceWorker"; public const string SetDataSizeLimitsForTest = "Network.setDataSizeLimitsForTest"; public const string GetCertificate = "Network.getCertificate"; public const string SetRequestInterceptionEnabled = "Network.setRequestInterceptionEnabled"; public const string ContinueInterceptedRequest = "Network.continueInterceptedRequest"; public const string ResourceChangedPriority = "Network.resourceChangedPriority"; public const string RequestWillBeSent = "Network.requestWillBeSent"; public const string RequestServedFromCache = "Network.requestServedFromCache"; public const string ResponseReceived = "Network.responseReceived"; public const string DataReceived = "Network.dataReceived"; public const string LoadingFinished = "Network.loadingFinished"; public const string LoadingFailed = "Network.loadingFailed"; public const string WebSocketWillSendHandshakeRequest = "Network.webSocketWillSendHandshakeRequest"; public const string WebSocketHandshakeResponseReceived = "Network.webSocketHandshakeResponseReceived"; public const string WebSocketCreated = "Network.webSocketCreated"; public const string WebSocketClosed = "Network.webSocketClosed"; public const string WebSocketFrameReceived = "Network.webSocketFrameReceived"; public const string WebSocketFrameError = "Network.webSocketFrameError"; public const string WebSocketFrameSent = "Network.webSocketFrameSent"; public const string EventSourceMessageReceived = "Network.eventSourceMessageReceived"; public const string RequestIntercepted = "Network.requestIntercepted"; } public static class Database { public const string Enable = "Database.enable"; public const string Disable = "Database.disable"; public const string GetDatabaseTableNames = "Database.getDatabaseTableNames"; public const string ExecuteSQL = "Database.executeSQL"; public const string AddDatabase = "Database.addDatabase"; } public static class IndexedDB { public const string Enable = "IndexedDB.enable"; public const string Disable = "IndexedDB.disable"; public const string RequestDatabaseNames = "IndexedDB.requestDatabaseNames"; public const string RequestDatabase = "IndexedDB.requestDatabase"; public const string RequestData = "IndexedDB.requestData"; public const string ClearObjectStore = "IndexedDB.clearObjectStore"; public const string DeleteDatabase = "IndexedDB.deleteDatabase"; } public static class CacheStorage { public const string RequestCacheNames = "CacheStorage.requestCacheNames"; public const string RequestEntries = "CacheStorage.requestEntries"; public const string DeleteCache = "CacheStorage.deleteCache"; public const string DeleteEntry = "CacheStorage.deleteEntry"; public const string RequestCachedResponse = "CacheStorage.requestCachedResponse"; } public static class DOMStorage { public const string Enable = "DOMStorage.enable"; public const string Disable = "DOMStorage.disable"; public const string Clear = "DOMStorage.clear"; public const string GetDOMStorageItems = "DOMStorage.getDOMStorageItems"; public const string SetDOMStorageItem = "DOMStorage.setDOMStorageItem"; public const string RemoveDOMStorageItem = "DOMStorage.removeDOMStorageItem"; public const string DomStorageItemsCleared = "DOMStorage.domStorageItemsCleared"; public const string DomStorageItemRemoved = "DOMStorage.domStorageItemRemoved"; public const string DomStorageItemAdded = "DOMStorage.domStorageItemAdded"; public const string DomStorageItemUpdated = "DOMStorage.domStorageItemUpdated"; } public static class ApplicationCache { public const string GetFramesWithManifests = "ApplicationCache.getFramesWithManifests"; public const string Enable = "ApplicationCache.enable"; public const string GetManifestForFrame = "ApplicationCache.getManifestForFrame"; public const string GetApplicationCacheForFrame = "ApplicationCache.getApplicationCacheForFrame"; public const string ApplicationCacheStatusUpdated = "ApplicationCache.applicationCacheStatusUpdated"; public const string NetworkStateUpdated = "ApplicationCache.networkStateUpdated"; } public static class DOM { public const string Enable = "DOM.enable"; public const string Disable = "DOM.disable"; public const string GetDocument = "DOM.getDocument"; public const string GetFlattenedDocument = "DOM.getFlattenedDocument"; public const string CollectClassNamesFromSubtree = "DOM.collectClassNamesFromSubtree"; public const string RequestChildNodes = "DOM.requestChildNodes"; public const string QuerySelector = "DOM.querySelector"; public const string QuerySelectorAll = "DOM.querySelectorAll"; public const string SetNodeName = "DOM.setNodeName"; public const string SetNodeValue = "DOM.setNodeValue"; public const string RemoveNode = "DOM.removeNode"; public const string SetAttributeValue = "DOM.setAttributeValue"; public const string SetAttributesAsText = "DOM.setAttributesAsText"; public const string RemoveAttribute = "DOM.removeAttribute"; public const string GetOuterHTML = "DOM.getOuterHTML"; public const string SetOuterHTML = "DOM.setOuterHTML"; public const string PerformSearch = "DOM.performSearch"; public const string GetSearchResults = "DOM.getSearchResults"; public const string DiscardSearchResults = "DOM.discardSearchResults"; public const string RequestNode = "DOM.requestNode"; public const string HighlightRect = "DOM.highlightRect"; public const string HighlightNode = "DOM.highlightNode"; public const string HideHighlight = "DOM.hideHighlight"; public const string PushNodeByPathToFrontend = "DOM.pushNodeByPathToFrontend"; public const string PushNodesByBackendIdsToFrontend = "DOM.pushNodesByBackendIdsToFrontend"; public const string SetInspectedNode = "DOM.setInspectedNode"; public const string ResolveNode = "DOM.resolveNode"; public const string GetAttributes = "DOM.getAttributes"; public const string CopyTo = "DOM.copyTo"; public const string MoveTo = "DOM.moveTo"; public const string Undo = "DOM.undo"; public const string Redo = "DOM.redo"; public const string MarkUndoableState = "DOM.markUndoableState"; public const string Focus = "DOM.focus"; public const string SetFileInputFiles = "DOM.setFileInputFiles"; public const string GetBoxModel = "DOM.getBoxModel"; public const string GetNodeForLocation = "DOM.getNodeForLocation"; public const string GetRelayoutBoundary = "DOM.getRelayoutBoundary"; public const string DescribeNode = "DOM.describeNode"; public const string DocumentUpdated = "DOM.documentUpdated"; public const string SetChildNodes = "DOM.setChildNodes"; public const string AttributeModified = "DOM.attributeModified"; public const string AttributeRemoved = "DOM.attributeRemoved"; public const string InlineStyleInvalidated = "DOM.inlineStyleInvalidated"; public const string CharacterDataModified = "DOM.characterDataModified"; public const string ChildNodeCountUpdated = "DOM.childNodeCountUpdated"; public const string ChildNodeInserted = "DOM.childNodeInserted"; public const string ChildNodeRemoved = "DOM.childNodeRemoved"; public const string ShadowRootPushed = "DOM.shadowRootPushed"; public const string ShadowRootPopped = "DOM.shadowRootPopped"; public const string PseudoElementAdded = "DOM.pseudoElementAdded"; public const string PseudoElementRemoved = "DOM.pseudoElementRemoved"; public const string DistributedNodesUpdated = "DOM.distributedNodesUpdated"; } public static class CSS { public const string Enable = "CSS.enable"; public const string Disable = "CSS.disable"; public const string GetMatchedStylesForNode = "CSS.getMatchedStylesForNode"; public const string GetInlineStylesForNode = "CSS.getInlineStylesForNode"; public const string GetComputedStyleForNode = "CSS.getComputedStyleForNode"; public const string GetPlatformFontsForNode = "CSS.getPlatformFontsForNode"; public const string GetStyleSheetText = "CSS.getStyleSheetText"; public const string CollectClassNames = "CSS.collectClassNames"; public const string SetStyleSheetText = "CSS.setStyleSheetText"; public const string SetRuleSelector = "CSS.setRuleSelector"; public const string SetKeyframeKey = "CSS.setKeyframeKey"; public const string SetStyleTexts = "CSS.setStyleTexts"; public const string SetMediaText = "CSS.setMediaText"; public const string CreateStyleSheet = "CSS.createStyleSheet"; public const string AddRule = "CSS.addRule"; public const string ForcePseudoState = "CSS.forcePseudoState"; public const string GetMediaQueries = "CSS.getMediaQueries"; public const string SetEffectivePropertyValueForNode = "CSS.setEffectivePropertyValueForNode"; public const string GetBackgroundColors = "CSS.getBackgroundColors"; public const string StartRuleUsageTracking = "CSS.startRuleUsageTracking"; public const string TakeCoverageDelta = "CSS.takeCoverageDelta"; public const string StopRuleUsageTracking = "CSS.stopRuleUsageTracking"; public const string MediaQueryResultChanged = "CSS.mediaQueryResultChanged"; public const string FontsUpdated = "CSS.fontsUpdated"; public const string StyleSheetChanged = "CSS.styleSheetChanged"; public const string StyleSheetAdded = "CSS.styleSheetAdded"; public const string StyleSheetRemoved = "CSS.styleSheetRemoved"; } public static class DOMSnapshot { public const string GetSnapshot = "DOMSnapshot.getSnapshot"; } public static class IO { public const string Read = "IO.read"; public const string Close = "IO.close"; public const string ResolveBlob = "IO.resolveBlob"; } public static class DOMDebugger { public const string SetDOMBreakpoint = "DOMDebugger.setDOMBreakpoint"; public const string RemoveDOMBreakpoint = "DOMDebugger.removeDOMBreakpoint"; public const string SetEventListenerBreakpoint = "DOMDebugger.setEventListenerBreakpoint"; public const string RemoveEventListenerBreakpoint = "DOMDebugger.removeEventListenerBreakpoint"; public const string SetInstrumentationBreakpoint = "DOMDebugger.setInstrumentationBreakpoint"; public const string RemoveInstrumentationBreakpoint = "DOMDebugger.removeInstrumentationBreakpoint"; public const string SetXHRBreakpoint = "DOMDebugger.setXHRBreakpoint"; public const string RemoveXHRBreakpoint = "DOMDebugger.removeXHRBreakpoint"; public const string GetEventListeners = "DOMDebugger.getEventListeners"; } public static class Target { public const string SetDiscoverTargets = "Target.setDiscoverTargets"; public const string SetAutoAttach = "Target.setAutoAttach"; public const string SetAttachToFrames = "Target.setAttachToFrames"; public const string SetRemoteLocations = "Target.setRemoteLocations"; public const string SendMessageToTarget = "Target.sendMessageToTarget"; public const string GetTargetInfo = "Target.getTargetInfo"; public const string ActivateTarget = "Target.activateTarget"; public const string CloseTarget = "Target.closeTarget"; public const string AttachToTarget = "Target.attachToTarget"; public const string DetachFromTarget = "Target.detachFromTarget"; public const string CreateBrowserContext = "Target.createBrowserContext"; public const string DisposeBrowserContext = "Target.disposeBrowserContext"; public const string CreateTarget = "Target.createTarget"; public const string GetTargets = "Target.getTargets"; public const string TargetCreated = "Target.targetCreated"; public const string TargetInfoChanged = "Target.targetInfoChanged"; public const string TargetDestroyed = "Target.targetDestroyed"; public const string AttachedToTarget = "Target.attachedToTarget"; public const string DetachedFromTarget = "Target.detachedFromTarget"; public const string ReceivedMessageFromTarget = "Target.receivedMessageFromTarget"; } public static class ServiceWorker { public const string Enable = "ServiceWorker.enable"; public const string Disable = "ServiceWorker.disable"; public const string Unregister = "ServiceWorker.unregister"; public const string UpdateRegistration = "ServiceWorker.updateRegistration"; public const string StartWorker = "ServiceWorker.startWorker"; public const string SkipWaiting = "ServiceWorker.skipWaiting"; public const string StopWorker = "ServiceWorker.stopWorker"; public const string InspectWorker = "ServiceWorker.inspectWorker"; public const string SetForceUpdateOnPageLoad = "ServiceWorker.setForceUpdateOnPageLoad"; public const string DeliverPushMessage = "ServiceWorker.deliverPushMessage"; public const string DispatchSyncEvent = "ServiceWorker.dispatchSyncEvent"; public const string WorkerRegistrationUpdated = "ServiceWorker.workerRegistrationUpdated"; public const string WorkerVersionUpdated = "ServiceWorker.workerVersionUpdated"; public const string WorkerErrorReported = "ServiceWorker.workerErrorReported"; } public static class Input { public const string SetIgnoreInputEvents = "Input.setIgnoreInputEvents"; public const string DispatchKeyEvent = "Input.dispatchKeyEvent"; public const string DispatchMouseEvent = "Input.dispatchMouseEvent"; public const string DispatchTouchEvent = "Input.dispatchTouchEvent"; public const string EmulateTouchFromMouseEvent = "Input.emulateTouchFromMouseEvent"; public const string SynthesizePinchGesture = "Input.synthesizePinchGesture"; public const string SynthesizeScrollGesture = "Input.synthesizeScrollGesture"; public const string SynthesizeTapGesture = "Input.synthesizeTapGesture"; } public static class LayerTree { public const string Enable = "LayerTree.enable"; public const string Disable = "LayerTree.disable"; public const string CompositingReasons = "LayerTree.compositingReasons"; public const string MakeSnapshot = "LayerTree.makeSnapshot"; public const string LoadSnapshot = "LayerTree.loadSnapshot"; public const string ReleaseSnapshot = "LayerTree.releaseSnapshot"; public const string ProfileSnapshot = "LayerTree.profileSnapshot"; public const string ReplaySnapshot = "LayerTree.replaySnapshot"; public const string SnapshotCommandLog = "LayerTree.snapshotCommandLog"; public const string LayerTreeDidChange = "LayerTree.layerTreeDidChange"; public const string LayerPainted = "LayerTree.layerPainted"; } public static class DeviceOrientation { public const string SetDeviceOrientationOverride = "DeviceOrientation.setDeviceOrientationOverride"; public const string ClearDeviceOrientationOverride = "DeviceOrientation.clearDeviceOrientationOverride"; } public static class Tracing { public const string Start = "Tracing.start"; public const string End = "Tracing.end"; public const string GetCategories = "Tracing.getCategories"; public const string RequestMemoryDump = "Tracing.requestMemoryDump"; public const string RecordClockSyncMarker = "Tracing.recordClockSyncMarker"; public const string DataCollected = "Tracing.dataCollected"; public const string TracingComplete = "Tracing.tracingComplete"; public const string BufferUsage = "Tracing.bufferUsage"; } public static class Animation { public const string Enable = "Animation.enable"; public const string Disable = "Animation.disable"; public const string GetPlaybackRate = "Animation.getPlaybackRate"; public const string SetPlaybackRate = "Animation.setPlaybackRate"; public const string GetCurrentTime = "Animation.getCurrentTime"; public const string SetPaused = "Animation.setPaused"; public const string SetTiming = "Animation.setTiming"; public const string SeekAnimations = "Animation.seekAnimations"; public const string ReleaseAnimations = "Animation.releaseAnimations"; public const string ResolveAnimation = "Animation.resolveAnimation"; public const string AnimationCreated = "Animation.animationCreated"; public const string AnimationStarted = "Animation.animationStarted"; public const string AnimationCanceled = "Animation.animationCanceled"; } public static class Accessibility { public const string GetPartialAXTree = "Accessibility.getPartialAXTree"; } public static class Storage { public const string ClearDataForOrigin = "Storage.clearDataForOrigin"; public const string GetUsageAndQuota = "Storage.getUsageAndQuota"; public const string TrackCacheStorageForOrigin = "Storage.trackCacheStorageForOrigin"; public const string UntrackCacheStorageForOrigin = "Storage.untrackCacheStorageForOrigin"; public const string CacheStorageListUpdated = "Storage.cacheStorageListUpdated"; public const string CacheStorageContentUpdated = "Storage.cacheStorageContentUpdated"; } public static class Log { public const string Enable = "Log.enable"; public const string Disable = "Log.disable"; public const string Clear = "Log.clear"; public const string StartViolationsReport = "Log.startViolationsReport"; public const string StopViolationsReport = "Log.stopViolationsReport"; public const string EntryAdded = "Log.entryAdded"; } public static class SystemInfo { public const string GetInfo = "SystemInfo.getInfo"; } public static class Tethering { public const string Bind = "Tethering.bind"; public const string Unbind = "Tethering.unbind"; public const string Accepted = "Tethering.accepted"; } public static class Browser { public const string GetWindowForTarget = "Browser.getWindowForTarget"; public const string GetVersion = "Browser.getVersion"; public const string SetWindowBounds = "Browser.setWindowBounds"; public const string GetWindowBounds = "Browser.getWindowBounds"; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Management.Automation; using System.Management.Automation.Runspaces; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace Microsoft.PowerShell.ScheduledJob { /// <summary> /// This cmdlet updates a scheduled job definition object based on the provided /// parameter values and saves changes to job store and Task Scheduler. /// </summary> [Cmdlet(VerbsCommon.Set, "ScheduledJob", DefaultParameterSetName = SetScheduledJobCommand.ScriptBlockParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=223924")] [OutputType(typeof(ScheduledJobDefinition))] public sealed class SetScheduledJobCommand : ScheduleJobCmdletBase { #region Parameters private const string ExecutionParameterSet = "Execution"; private const string ScriptBlockParameterSet = "ScriptBlock"; private const string FilePathParameterSet = "FilePath"; /// <summary> /// Name of scheduled job definition. /// </summary> [Parameter(ParameterSetName = SetScheduledJobCommand.FilePathParameterSet)] [Parameter(ParameterSetName = SetScheduledJobCommand.ScriptBlockParameterSet)] [ValidateNotNullOrEmpty] public string Name { get { return _name; } set { _name = value; } } private string _name; /// <summary> /// File path for script to be run in job. /// </summary> [Parameter(ParameterSetName = SetScheduledJobCommand.FilePathParameterSet)] [Alias("Path")] [ValidateNotNullOrEmpty] public string FilePath { get { return _filePath; } set { _filePath = value; } } private string _filePath; /// <summary> /// ScriptBlock containing script to run in job. /// </summary> [Parameter(ParameterSetName = SetScheduledJobCommand.ScriptBlockParameterSet)] [ValidateNotNull] public ScriptBlock ScriptBlock { get { return _scriptBlock; } set { _scriptBlock = value; } } private ScriptBlock _scriptBlock; /// <summary> /// Triggers to define when job will run. /// </summary> [Parameter(ParameterSetName = SetScheduledJobCommand.ScriptBlockParameterSet)] [Parameter(ParameterSetName = SetScheduledJobCommand.FilePathParameterSet)] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public ScheduledJobTrigger[] Trigger { get { return _triggers; } set { _triggers = value; } } private ScheduledJobTrigger[] _triggers; /// <summary> /// Initialization script to run before the job starts. /// </summary> [Parameter(ParameterSetName = SetScheduledJobCommand.ScriptBlockParameterSet)] [Parameter(ParameterSetName = SetScheduledJobCommand.FilePathParameterSet)] [ValidateNotNull] public ScriptBlock InitializationScript { get { return _initializationScript; } set { _initializationScript = value; } } private ScriptBlock _initializationScript; /// <summary> /// Runs the job in a 32-bit PowerShell process. /// </summary> [Parameter(ParameterSetName = SetScheduledJobCommand.ScriptBlockParameterSet)] [Parameter(ParameterSetName = SetScheduledJobCommand.FilePathParameterSet)] public SwitchParameter RunAs32 { get { return _runAs32; } set { _runAs32 = value; } } private SwitchParameter _runAs32; /// <summary> /// Credentials for job. /// </summary> [Parameter(ParameterSetName = SetScheduledJobCommand.ScriptBlockParameterSet)] [Parameter(ParameterSetName = SetScheduledJobCommand.FilePathParameterSet)] [Credential()] public PSCredential Credential { get { return _credential; } set { _credential = value; } } private PSCredential _credential; /// <summary> /// Authentication mechanism to use for job. /// </summary> [Parameter(ParameterSetName = SetScheduledJobCommand.ScriptBlockParameterSet)] [Parameter(ParameterSetName = SetScheduledJobCommand.FilePathParameterSet)] public AuthenticationMechanism Authentication { get { return _authenticationMechanism; } set { _authenticationMechanism = value; } } private AuthenticationMechanism _authenticationMechanism; /// <summary> /// Scheduling options for job. /// </summary> [Parameter(ParameterSetName = SetScheduledJobCommand.ScriptBlockParameterSet)] [Parameter(ParameterSetName = SetScheduledJobCommand.FilePathParameterSet)] [ValidateNotNull] public ScheduledJobOptions ScheduledJobOption { get { return _options; } set { _options = value; } } private ScheduledJobOptions _options; /// <summary> /// Input for the job. /// </summary> [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ParameterSetName = SetScheduledJobCommand.ScriptBlockParameterSet)] [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ParameterSetName = SetScheduledJobCommand.FilePathParameterSet)] [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ParameterSetName = SetScheduledJobCommand.ExecutionParameterSet)] [ValidateNotNull] public ScheduledJobDefinition InputObject { get { return _definition; } set { _definition = value; } } private ScheduledJobDefinition _definition; /// <summary> /// ClearExecutionHistory. /// </summary> [Parameter(ParameterSetName = SetScheduledJobCommand.ExecutionParameterSet)] public SwitchParameter ClearExecutionHistory { get { return _clearExecutionHistory; } set { _clearExecutionHistory = value; } } private SwitchParameter _clearExecutionHistory; /// <summary> /// Maximum number of job results allowed in job store. /// </summary> [Parameter(ParameterSetName = SetScheduledJobCommand.ScriptBlockParameterSet)] [Parameter(ParameterSetName = SetScheduledJobCommand.FilePathParameterSet)] public int MaxResultCount { get { return _executionHistoryLength; } set { _executionHistoryLength = value; } } private int _executionHistoryLength; /// <summary> /// Pass the ScheduledJobDefinition object through to output. /// </summary> [Parameter(ParameterSetName = SetScheduledJobCommand.ScriptBlockParameterSet)] [Parameter(ParameterSetName = SetScheduledJobCommand.FilePathParameterSet)] [Parameter(ParameterSetName = SetScheduledJobCommand.ExecutionParameterSet)] public SwitchParameter PassThru { get { return _passThru; } set { _passThru = value; } } private SwitchParameter _passThru; /// <summary> /// Argument list. /// </summary> [Parameter(ParameterSetName = SetScheduledJobCommand.ScriptBlockParameterSet)] [Parameter(ParameterSetName = SetScheduledJobCommand.FilePathParameterSet)] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public object[] ArgumentList { get { return _arguments; } set { _arguments = value; } } private object[] _arguments; /// <summary> /// Runs scheduled job immediately after successfully setting job definition. /// </summary> [Parameter(ParameterSetName = SetScheduledJobCommand.ScriptBlockParameterSet)] [Parameter(ParameterSetName = SetScheduledJobCommand.FilePathParameterSet)] public SwitchParameter RunNow { get { return _runNow; } set { _runNow = value; } } private SwitchParameter _runNow; /// <summary> /// Runs scheduled job at the repetition interval indicated by the /// TimeSpan value for an unending duration. /// </summary> [Parameter(ParameterSetName = SetScheduledJobCommand.ScriptBlockParameterSet)] [Parameter(ParameterSetName = SetScheduledJobCommand.FilePathParameterSet)] public TimeSpan RunEvery { get { return _runEvery; } set { _runEvery = value; } } private TimeSpan _runEvery; #endregion #region Cmdlet Overrides /// <summary> /// Process input. /// </summary> protected override void ProcessRecord() { switch (ParameterSetName) { case ExecutionParameterSet: UpdateExecutionDefinition(); break; case ScriptBlockParameterSet: case FilePathParameterSet: UpdateDefinition(); break; } try { // If RunEvery parameter is specified then create a job trigger for the definition that // runs the job at the requested interval. bool addedTrigger = false; if (MyInvocation.BoundParameters.ContainsKey(nameof(RunEvery))) { AddRepetitionJobTriggerToDefinition( _definition, RunEvery, false); addedTrigger = true; } if (Trigger != null || ScheduledJobOption != null || Credential != null || addedTrigger) { // Save definition to file and update WTS. _definition.Save(); } else { // No WTS changes. Save definition to store only. _definition.SaveToStore(); } if (_runNow) { _definition.RunAsTask(); } } catch (ScheduledJobException e) { ErrorRecord errorRecord; if (e.InnerException != null && e.InnerException is System.UnauthorizedAccessException) { string msg = StringUtil.Format(ScheduledJobErrorStrings.NoAccessOnSetJobDefinition, _definition.Name); errorRecord = new ErrorRecord(new RuntimeException(msg, e), "NoAccessFailureOnSetJobDefinition", ErrorCategory.InvalidOperation, _definition); } else if (e.InnerException != null && e.InnerException is System.IO.IOException) { string msg = StringUtil.Format(ScheduledJobErrorStrings.IOFailureOnSetJobDefinition, _definition.Name); errorRecord = new ErrorRecord(new RuntimeException(msg, e), "IOFailureOnSetJobDefinition", ErrorCategory.InvalidOperation, _definition); } else { string msg = StringUtil.Format(ScheduledJobErrorStrings.CantSetJobDefinition, _definition.Name); errorRecord = new ErrorRecord(new RuntimeException(msg, e), "CantSetPropertiesToScheduledJobDefinition", ErrorCategory.InvalidOperation, _definition); } WriteError(errorRecord); } if (_passThru) { WriteObject(_definition); } } #endregion #region Private Methods private void UpdateExecutionDefinition() { if (_clearExecutionHistory) { _definition.ClearExecutionHistory(); } } private void UpdateDefinition() { if (_name != null && string.Compare(_name, _definition.Name, StringComparison.OrdinalIgnoreCase) != 0) { _definition.RenameAndSave(_name); } UpdateJobInvocationInfo(); if (MyInvocation.BoundParameters.ContainsKey(nameof(MaxResultCount))) { _definition.SetExecutionHistoryLength(MaxResultCount, false); } if (Credential != null) { _definition.Credential = Credential; } if (Trigger != null) { _definition.SetTriggers(Trigger, false); } if (ScheduledJobOption != null) { _definition.UpdateOptions(ScheduledJobOption, false); } } /// <summary> /// Create new ScheduledJobInvocationInfo object with update information and /// update the job definition object. /// </summary> private void UpdateJobInvocationInfo() { Dictionary<string, object> parameters = UpdateParameters(); string name = _definition.Name; string command; if (ScriptBlock != null) { command = ScriptBlock.ToString(); } else if (FilePath != null) { command = FilePath; } else { command = _definition.InvocationInfo.Command; } JobDefinition jobDefinition = new JobDefinition(typeof(ScheduledJobSourceAdapter), command, name); jobDefinition.ModuleName = ModuleName; JobInvocationInfo jobInvocationInfo = new ScheduledJobInvocationInfo(jobDefinition, parameters); _definition.UpdateJobInvocationInfo(jobInvocationInfo, false); } /// <summary> /// Creates a new parameter dictionary with update parameters. /// </summary> /// <returns>Updated parameters.</returns> private Dictionary<string, object> UpdateParameters() { Debug.Assert(_definition.InvocationInfo.Parameters.Count != 0, "ScheduledJobDefinition must always have some job invocation parameters"); Dictionary<string, object> newParameters = new Dictionary<string, object>(); foreach (CommandParameter parameter in _definition.InvocationInfo.Parameters[0]) { newParameters.Add(parameter.Name, parameter.Value); } // RunAs32 if (MyInvocation.BoundParameters.ContainsKey(nameof(RunAs32))) { if (newParameters.ContainsKey(ScheduledJobInvocationInfo.RunAs32Parameter)) { newParameters[ScheduledJobInvocationInfo.RunAs32Parameter] = RunAs32.ToBool(); } else { newParameters.Add(ScheduledJobInvocationInfo.RunAs32Parameter, RunAs32.ToBool()); } } // Authentication if (MyInvocation.BoundParameters.ContainsKey(nameof(Authentication))) { if (newParameters.ContainsKey(ScheduledJobInvocationInfo.AuthenticationParameter)) { newParameters[ScheduledJobInvocationInfo.AuthenticationParameter] = Authentication; } else { newParameters.Add(ScheduledJobInvocationInfo.AuthenticationParameter, Authentication); } } // InitializationScript if (InitializationScript == null) { if (newParameters.ContainsKey(ScheduledJobInvocationInfo.InitializationScriptParameter)) { newParameters.Remove(ScheduledJobInvocationInfo.InitializationScriptParameter); } } else { if (newParameters.ContainsKey(ScheduledJobInvocationInfo.InitializationScriptParameter)) { newParameters[ScheduledJobInvocationInfo.InitializationScriptParameter] = InitializationScript; } else { newParameters.Add(ScheduledJobInvocationInfo.InitializationScriptParameter, InitializationScript); } } // ScriptBlock if (ScriptBlock != null) { // FilePath cannot also be specified. if (newParameters.ContainsKey(ScheduledJobInvocationInfo.FilePathParameter)) { newParameters.Remove(ScheduledJobInvocationInfo.FilePathParameter); } if (newParameters.ContainsKey(ScheduledJobInvocationInfo.ScriptBlockParameter)) { newParameters[ScheduledJobInvocationInfo.ScriptBlockParameter] = ScriptBlock; } else { newParameters.Add(ScheduledJobInvocationInfo.ScriptBlockParameter, ScriptBlock); } } // FilePath if (FilePath != null) { // ScriptBlock cannot also be specified. if (newParameters.ContainsKey(ScheduledJobInvocationInfo.ScriptBlockParameter)) { newParameters.Remove(ScheduledJobInvocationInfo.ScriptBlockParameter); } if (newParameters.ContainsKey(ScheduledJobInvocationInfo.FilePathParameter)) { newParameters[ScheduledJobInvocationInfo.FilePathParameter] = FilePath; } else { newParameters.Add(ScheduledJobInvocationInfo.FilePathParameter, FilePath); } } // ArgumentList if (ArgumentList == null) { // Clear existing argument list only if new scriptblock or script file path was specified // (in this case old argument list is invalid). if (newParameters.ContainsKey(ScheduledJobInvocationInfo.ArgumentListParameter) && (ScriptBlock != null || FilePath != null)) { newParameters.Remove(ScheduledJobInvocationInfo.ArgumentListParameter); } } else { if (newParameters.ContainsKey(ScheduledJobInvocationInfo.ArgumentListParameter)) { newParameters[ScheduledJobInvocationInfo.ArgumentListParameter] = ArgumentList; } else { newParameters.Add(ScheduledJobInvocationInfo.ArgumentListParameter, ArgumentList); } } return newParameters; } #endregion } }
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // namespace DiscUtils.Vmdk { using System; using System.Collections.Generic; using System.IO; internal sealed class VmfsSparseExtentBuilder : StreamBuilder { private SparseStream _content; public VmfsSparseExtentBuilder(SparseStream content) { _content = content; } internal override List<BuilderExtent> FixExtents(out long totalLength) { List<BuilderExtent> extents = new List<BuilderExtent>(); ServerSparseExtentHeader header = DiskImageFile.CreateServerSparseExtentHeader(_content.Length); GlobalDirectoryExtent gdExtent = new GlobalDirectoryExtent(header); long grainTableStart = (header.GdOffset * Sizes.Sector) + gdExtent.Length; long grainTableCoverage = header.NumGTEsPerGT * header.GrainSize * Sizes.Sector; foreach (var grainTableRange in StreamExtent.Blocks(_content.Extents, grainTableCoverage)) { for (int i = 0; i < grainTableRange.Count; ++i) { long grainTable = grainTableRange.Offset + i; long dataStart = grainTable * grainTableCoverage; GrainTableExtent gtExtent = new GrainTableExtent(grainTableStart, new SubStream(_content, dataStart, Math.Min(grainTableCoverage, _content.Length - dataStart)), header); extents.Add(gtExtent); gdExtent.SetEntry((int)grainTable, (uint)(grainTableStart / Sizes.Sector)); grainTableStart += gtExtent.Length; } } extents.Insert(0, gdExtent); header.FreeSector = (uint)(grainTableStart / Sizes.Sector); byte[] buffer = header.GetBytes(); extents.Insert(0, new BuilderBufferExtent(0, buffer)); totalLength = grainTableStart; return extents; } private class GlobalDirectoryExtent : BuilderExtent { private byte[] _buffer; private MemoryStream _streamView; public GlobalDirectoryExtent(ServerSparseExtentHeader header) : base(header.GdOffset * Sizes.Sector, Utilities.RoundUp(header.NumGdEntries * 4, Sizes.Sector)) { _buffer = new byte[Length]; } public override void Dispose() { if (_streamView != null) { _streamView.Dispose(); _streamView = null; } } public void SetEntry(int index, uint grainTableSector) { Utilities.WriteBytesLittleEndian(grainTableSector, _buffer, index * 4); } internal override void PrepareForRead() { _streamView = new MemoryStream(_buffer, 0, _buffer.Length, false); } internal override int Read(long diskOffset, byte[] block, int offset, int count) { _streamView.Position = diskOffset - Start; return _streamView.Read(block, offset, count); } internal override void DisposeReadState() { if (_streamView != null) { _streamView.Dispose(); _streamView = null; } } } private class GrainTableExtent : BuilderExtent { private SparseStream _content; private Ownership _contentOwnership; private ServerSparseExtentHeader _header; private MemoryStream _grainTableStream; private List<long> _grainMapping; private List<long> _grainContiguousRangeMapping; public GrainTableExtent(long outputStart, SparseStream content, ServerSparseExtentHeader header) : this(outputStart, content, Ownership.None, header) { } public GrainTableExtent(long outputStart, SparseStream content, Ownership contentOwnership, ServerSparseExtentHeader header) : base(outputStart, CalcSize(content, header)) { _content = content; _contentOwnership = contentOwnership; _header = header; } public override void Dispose() { if (_content != null && _contentOwnership == Ownership.Dispose) { _content.Dispose(); _content = null; } if (_grainTableStream != null) { _grainTableStream.Dispose(); _grainTableStream = null; } } internal override void PrepareForRead() { byte[] grainTable = new byte[Utilities.RoundUp(_header.NumGTEsPerGT * 4, Sizes.Sector)]; long dataSector = (Start + grainTable.Length) / Sizes.Sector; _grainMapping = new List<long>(); _grainContiguousRangeMapping = new List<long>(); foreach (var grainRange in StreamExtent.Blocks(_content.Extents, _header.GrainSize * Sizes.Sector)) { for (int i = 0; i < grainRange.Count; ++i) { Utilities.WriteBytesLittleEndian((uint)dataSector, grainTable, (int)(4 * (grainRange.Offset + i))); dataSector += _header.GrainSize; _grainMapping.Add(grainRange.Offset + i); _grainContiguousRangeMapping.Add(grainRange.Count - i); } } _grainTableStream = new MemoryStream(grainTable, 0, grainTable.Length, false); } internal override int Read(long diskOffset, byte[] block, int offset, int count) { long relOffset = diskOffset - Start; if (relOffset < _grainTableStream.Length) { _grainTableStream.Position = relOffset; return _grainTableStream.Read(block, offset, count); } else { long grainSize = _header.GrainSize * Sizes.Sector; int grainIdx = (int)((relOffset - _grainTableStream.Length) / grainSize); long grainOffset = (relOffset - _grainTableStream.Length) - (grainIdx * grainSize); int maxToRead = (int)Math.Min(count, (grainSize * _grainContiguousRangeMapping[grainIdx]) - grainOffset); _content.Position = (_grainMapping[grainIdx] * grainSize) + grainOffset; return _content.Read(block, offset, maxToRead); } } internal override void DisposeReadState() { if (_grainTableStream != null) { _grainTableStream.Dispose(); _grainTableStream = null; } _grainMapping = null; _grainContiguousRangeMapping = null; } private static long CalcSize(SparseStream content, ServerSparseExtentHeader header) { long numDataGrains = StreamExtent.BlockCount(content.Extents, header.GrainSize * Sizes.Sector); long grainTableSectors = Utilities.Ceil(header.NumGTEsPerGT * 4, Sizes.Sector); return (grainTableSectors + (numDataGrains * header.GrainSize)) * Sizes.Sector; } } } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <[email protected]> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !SILVERLIGHT && !UNITY3D_WEB namespace NLog.Internal.FileAppenders { using System; using System.IO; using System.Security; using System.Security.AccessControl; using System.Security.Cryptography; using System.Security.Principal; using System.Text; using System.Threading; using NLog.Common; /// <summary> /// Provides a multiprocess-safe atomic file appends while /// keeping the files open. /// </summary> /// <remarks> /// On Unix you can get all the appends to be atomic, even when multiple /// processes are trying to write to the same file, because setting the file /// pointer to the end of the file and appending can be made one operation. /// On Win32 we need to maintain some synchronization between processes /// (global named mutex is used for this) /// </remarks> [SecuritySafeCritical] internal class MutexMultiProcessFileAppender : BaseFileAppender { public static readonly IFileAppenderFactory TheFactory = new Factory(); private FileStream file; private Mutex mutex; /// <summary> /// Initializes a new instance of the <see cref="MutexMultiProcessFileAppender" /> class. /// </summary> /// <param name="fileName">Name of the file.</param> /// <param name="parameters">The parameters.</param> public MutexMultiProcessFileAppender(string fileName, ICreateFileParameters parameters) : base(fileName, parameters) { try { this.mutex = CreateSharableMutex(GetMutexName(fileName)); this.file = CreateFileStream(true); } catch { if (this.mutex != null) { this.mutex.Close(); this.mutex = null; } if (this.file != null) { this.file.Close(); this.file = null; } throw; } } /// <summary> /// Writes the specified bytes. /// </summary> /// <param name="bytes">The bytes to be written.</param> public override void Write(byte[] bytes) { if (this.mutex == null) { return; } try { this.mutex.WaitOne(); } catch (AbandonedMutexException) { // ignore the exception, another process was killed without properly releasing the mutex // the mutex has been acquired, so proceed to writing // See: http://msdn.microsoft.com/en-us/library/system.threading.abandonedmutexexception.aspx } try { this.file.Seek(0, SeekOrigin.End); this.file.Write(bytes, 0, bytes.Length); this.file.Flush(); FileTouched(); } finally { this.mutex.ReleaseMutex(); } } /// <summary> /// Closes this instance. /// </summary> public override void Close() { InternalLogger.Trace("Closing '{0}'", FileName); if (this.mutex != null) { this.mutex.Close(); } if (this.file != null) { this.file.Close(); } this.mutex = null; this.file = null; FileTouched(); } /// <summary> /// Flushes this instance. /// </summary> public override void Flush() { // do nothing, the stream is always flushed } /// <summary> /// Gets the file info. /// </summary> /// <param name="lastWriteTime">The last write time.</param> /// <param name="fileLength">Length of the file.</param> /// <returns> /// True if the operation succeeded, false otherwise. /// </returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Runtime.InteropServices.SafeHandle.DangerousGetHandle", Justification = "Optimization")] public override bool GetFileInfo(out DateTime lastWriteTime, out long fileLength) { return FileInfoHelper.Helper.GetFileInfo(FileName, this.file.SafeFileHandle.DangerousGetHandle(), out lastWriteTime, out fileLength); } private static Mutex CreateSharableMutex(string name) { // Creates a mutex sharable by more than one process var mutexSecurity = new MutexSecurity(); var everyoneSid = new SecurityIdentifier(WellKnownSidType.WorldSid, null); mutexSecurity.AddAccessRule(new MutexAccessRule(everyoneSid, MutexRights.FullControl, AccessControlType.Allow)); // The constructor will either create new mutex or open // an existing one, in a thread-safe manner bool createdNew; return new Mutex(false, name, out createdNew, mutexSecurity); } private static string GetMutexName(string fileName) { // The global kernel object namespace is used so the mutex // can be shared among processes in all sessions const string mutexNamePrefix = @"Global\NLog-FileLock-"; const int maxMutexNameLength = 260; string canonicalName = Path.GetFullPath(fileName).ToLowerInvariant(); // Mutex names must not contain a backslash, it's the namespace separator, // but all other are OK canonicalName = canonicalName.Replace('\\', '/'); // A mutex name must not exceed MAX_PATH (260) characters if (mutexNamePrefix.Length + canonicalName.Length <= maxMutexNameLength) { return mutexNamePrefix + canonicalName; } // The unusual case of the path being too long; let's hash the canonical name, // so it can be safely shortened and still remain unique string hash; using (MD5 md5 = MD5.Create()) { byte[] bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(canonicalName)); hash = Convert.ToBase64String(bytes); } // The hash makes the name unique, but also add the end of the path, // so the end of the name tells us which file it is (for debugging) int cutOffIndex = canonicalName.Length - (maxMutexNameLength - mutexNamePrefix.Length - hash.Length); return mutexNamePrefix + hash + canonicalName.Substring(cutOffIndex); } /// <summary> /// Factory class. /// </summary> private class Factory : IFileAppenderFactory { /// <summary> /// Opens the appender for given file name and parameters. /// </summary> /// <param name="fileName">Name of the file.</param> /// <param name="parameters">Creation parameters.</param> /// <returns> /// Instance of <see cref="BaseFileAppender"/> which can be used to write to the file. /// </returns> BaseFileAppender IFileAppenderFactory.Open(string fileName, ICreateFileParameters parameters) { return new MutexMultiProcessFileAppender(fileName, parameters); } } } } #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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateVariable { internal abstract partial class AbstractGenerateVariableService<TService, TSimpleNameSyntax, TExpressionSyntax> { private partial class GenerateVariableCodeAction : CodeAction { private readonly TService _service; private readonly State _state; private readonly bool _generateProperty; private readonly bool _isReadonly; private readonly bool _isConstant; private readonly Document _document; private readonly string _equivalenceKey; public GenerateVariableCodeAction( TService service, Document document, State state, bool generateProperty, bool isReadonly, bool isConstant) { _service = service; _document = document; _state = state; _generateProperty = generateProperty; _isReadonly = isReadonly; _isConstant = isConstant; _equivalenceKey = Title; } protected override async Task<Document> GetChangedDocumentAsync(CancellationToken cancellationToken) { var syntaxTree = await _document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var generateUnsafe = _state.TypeMemberType.IsUnsafe() && !_state.IsContainedInUnsafeType; if (_generateProperty) { var getAccessor = CodeGenerationSymbolFactory.CreateAccessorSymbol( attributes: null, accessibility: DetermineMaximalAccessibility(_state), statements: null); var setAccessor = _isReadonly ? null : CodeGenerationSymbolFactory.CreateAccessorSymbol( attributes: null, accessibility: DetermineMinimalAccessibility(_state), statements: null); var result = await CodeGenerator.AddPropertyDeclarationAsync( _document.Project.Solution, _state.TypeToGenerateIn, CodeGenerationSymbolFactory.CreatePropertySymbol( attributes: null, accessibility: DetermineMaximalAccessibility(_state), modifiers: new DeclarationModifiers(isStatic: _state.IsStatic, isUnsafe: generateUnsafe), type: _state.TypeMemberType, explicitInterfaceSymbol: null, name: _state.IdentifierToken.ValueText, isIndexer: _state.IsIndexer, parameters: _state.Parameters, getMethod: getAccessor, setMethod: setAccessor), new CodeGenerationOptions(contextLocation: _state.IdentifierToken.GetLocation()), cancellationToken: cancellationToken) .ConfigureAwait(false); return result; } else { var result = await CodeGenerator.AddFieldDeclarationAsync( _document.Project.Solution, _state.TypeToGenerateIn, CodeGenerationSymbolFactory.CreateFieldSymbol( attributes: null, accessibility: DetermineMinimalAccessibility(_state), modifiers: _isConstant ? new DeclarationModifiers(isConst: true, isUnsafe: generateUnsafe) : new DeclarationModifiers(isStatic: _state.IsStatic, isReadOnly: _isReadonly, isUnsafe: generateUnsafe), type: _state.TypeMemberType, name: _state.IdentifierToken.ValueText), new CodeGenerationOptions(contextLocation: _state.IdentifierToken.GetLocation()), cancellationToken: cancellationToken) .ConfigureAwait(false); return result; } } private Accessibility DetermineMaximalAccessibility(State state) { if (state.TypeToGenerateIn.TypeKind == TypeKind.Interface) { return Accessibility.NotApplicable; } var accessibility = Accessibility.Public; // Ensure that we're not overly exposing a type. var containingTypeAccessibility = state.TypeToGenerateIn.DetermineMinimalAccessibility(); var effectiveAccessibility = AccessibilityUtilities.Minimum( containingTypeAccessibility, accessibility); var returnTypeAccessibility = state.TypeMemberType.DetermineMinimalAccessibility(); if (AccessibilityUtilities.Minimum(effectiveAccessibility, returnTypeAccessibility) != effectiveAccessibility) { return returnTypeAccessibility; } return accessibility; } private Accessibility DetermineMinimalAccessibility(State state) { if (state.TypeToGenerateIn.TypeKind == TypeKind.Interface) { return Accessibility.NotApplicable; } // Otherwise, figure out what accessibility modifier to use and optionally mark // it as static. var syntaxFacts = _document.GetLanguageService<ISyntaxFactsService>(); if (syntaxFacts.IsAttributeNamedArgumentIdentifier(state.SimpleNameOrMemberAccessExpressionOpt)) { return Accessibility.Public; } else if (state.ContainingType.IsContainedWithin(state.TypeToGenerateIn)) { return Accessibility.Private; } else if (DerivesFrom(state, state.ContainingType) && state.IsStatic) { // NOTE(cyrusn): We only generate protected in the case of statics. Consider // the case where we're generating into one of our base types. i.e.: // // class B : A { void Foo() { A a; a.Foo(); } // // In this case we can *not* mark the method as protected. 'B' can only // access protected members of 'A' through an instance of 'B' (or a subclass // of B). It can not access protected members through an instance of the // superclass. In this case we need to make the method public or internal. // // However, this does not apply if the method will be static. i.e. // // class B : A { void Foo() { A.Foo(); } // // B can access the protected statics of A, and so we generate 'Foo' as // protected. return Accessibility.Protected; } else if (state.ContainingType.ContainingAssembly.IsSameAssemblyOrHasFriendAccessTo(state.TypeToGenerateIn.ContainingAssembly)) { return Accessibility.Internal; } else { // TODO: Code coverage - we need a unit-test that generates across projects return Accessibility.Public; } } private bool DerivesFrom(State state, INamedTypeSymbol containingType) { return containingType.GetBaseTypes().Select(t => t.OriginalDefinition) .Contains(state.TypeToGenerateIn); } public override string Title { get { var text = _isConstant ? FeaturesResources.GenerateConstantIn : _generateProperty ? _isReadonly ? FeaturesResources.GenerateReadonlyProperty : FeaturesResources.GeneratePropertyIn : _isReadonly ? FeaturesResources.GenerateReadonlyField : FeaturesResources.GenerateFieldIn; return string.Format( text, _state.IdentifierToken.ValueText, _state.TypeToGenerateIn.Name); } } public override string EquivalenceKey { get { return _equivalenceKey; } } } } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.LayoutRenderers { using System; using NLog.Config; using Xunit; [Obsolete("Replaced by ScopeContext.PushNestedState or Logger.PushScopeNested using ${scopenested}. Marked obsolete on NLog 5.0")] public class NDCTests : NLogTestBase { [Fact] public void NDCTest() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${ndc} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); NestedDiagnosticsContext.Clear(); LogManager.GetLogger("A").Debug("0"); AssertDebugLastMessage("debug", " 0"); using (NestedDiagnosticsContext.Push("ala")) { LogManager.GetLogger("A").Debug("a"); AssertDebugLastMessage("debug", "ala a"); using (NestedDiagnosticsContext.Push("ma")) { LogManager.GetLogger("A").Debug("b"); AssertDebugLastMessage("debug", "ala ma b"); using (NestedDiagnosticsContext.Push("kota")) { LogManager.GetLogger("A").Debug("c"); AssertDebugLastMessage("debug", "ala ma kota c"); using (NestedDiagnosticsContext.Push("kopytko")) { LogManager.GetLogger("A").Debug("d"); AssertDebugLastMessage("debug", "ala ma kota kopytko d"); } LogManager.GetLogger("A").Debug("c"); AssertDebugLastMessage("debug", "ala ma kota c"); } LogManager.GetLogger("A").Debug("b"); AssertDebugLastMessage("debug", "ala ma b"); } LogManager.GetLogger("A").Debug("a"); AssertDebugLastMessage("debug", "ala a"); } LogManager.GetLogger("A").Debug("0"); AssertDebugLastMessage("debug", " 0"); } [Fact] public void NDCTopTestTest() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${ndc:topframes=2} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); NestedDiagnosticsContext.Clear(); LogManager.GetLogger("A").Debug("0"); AssertDebugLastMessage("debug", " 0"); using (NestedDiagnosticsContext.Push("ala")) { LogManager.GetLogger("A").Debug("a"); AssertDebugLastMessage("debug", "ala a"); using (NestedDiagnosticsContext.Push("ma")) { LogManager.GetLogger("A").Debug("b"); AssertDebugLastMessage("debug", "ala ma b"); using (NestedDiagnosticsContext.Push("kota")) { LogManager.GetLogger("A").Debug("c"); AssertDebugLastMessage("debug", "ma kota c"); using (NestedDiagnosticsContext.Push("kopytko")) { LogManager.GetLogger("A").Debug("d"); AssertDebugLastMessage("debug", "kota kopytko d"); } LogManager.GetLogger("A").Debug("c"); AssertDebugLastMessage("debug", "ma kota c"); } LogManager.GetLogger("A").Debug("b"); AssertDebugLastMessage("debug", "ala ma b"); } LogManager.GetLogger("A").Debug("a"); AssertDebugLastMessage("debug", "ala a"); } LogManager.GetLogger("A").Debug("0"); AssertDebugLastMessage("debug", " 0"); } [Fact] public void NDCTop1TestTest() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${ndc:topframes=1} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); NestedDiagnosticsContext.Clear(); LogManager.GetLogger("A").Debug("0"); AssertDebugLastMessage("debug", " 0"); using (NestedDiagnosticsContext.Push("ala")) { LogManager.GetLogger("A").Debug("a"); AssertDebugLastMessage("debug", "ala a"); using (NestedDiagnosticsContext.Push("ma")) { LogManager.GetLogger("A").Debug("b"); AssertDebugLastMessage("debug", "ma b"); using (NestedDiagnosticsContext.Push("kota")) { LogManager.GetLogger("A").Debug("c"); AssertDebugLastMessage("debug", "kota c"); NestedDiagnosticsContext.Push("kopytko"); LogManager.GetLogger("A").Debug("d"); AssertDebugLastMessage("debug", "kopytko d"); Assert.Equal("kopytko", NestedDiagnosticsContext.Pop()); // manual pop LogManager.GetLogger("A").Debug("c"); AssertDebugLastMessage("debug", "kota c"); } LogManager.GetLogger("A").Debug("b"); AssertDebugLastMessage("debug", "ma b"); } LogManager.GetLogger("A").Debug("a"); AssertDebugLastMessage("debug", "ala a"); } LogManager.GetLogger("A").Debug("0"); AssertDebugLastMessage("debug", " 0"); Assert.Equal(string.Empty, NestedDiagnosticsContext.Pop()); Assert.Equal(string.Empty, NestedDiagnosticsContext.TopMessage); NestedDiagnosticsContext.Push("zzz"); Assert.Equal("zzz", NestedDiagnosticsContext.TopMessage); NestedDiagnosticsContext.Clear(); Assert.Equal(string.Empty, NestedDiagnosticsContext.Pop()); Assert.Equal(string.Empty, NestedDiagnosticsContext.TopMessage); } [Fact] public void NDCBottomTest() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${ndc:bottomframes=2} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); NestedDiagnosticsContext.Clear(); LogManager.GetLogger("A").Debug("0"); AssertDebugLastMessage("debug", " 0"); using (NestedDiagnosticsContext.Push("ala")) { LogManager.GetLogger("A").Debug("a"); AssertDebugLastMessage("debug", "ala a"); using (NestedDiagnosticsContext.Push("ma")) { LogManager.GetLogger("A").Debug("b"); AssertDebugLastMessage("debug", "ala ma b"); using (NestedDiagnosticsContext.Push("kota")) { LogManager.GetLogger("A").Debug("c"); AssertDebugLastMessage("debug", "ala ma c"); using (NestedDiagnosticsContext.Push("kopytko")) { LogManager.GetLogger("A").Debug("d"); AssertDebugLastMessage("debug", "ala ma d"); } LogManager.GetLogger("A").Debug("c"); AssertDebugLastMessage("debug", "ala ma c"); } LogManager.GetLogger("A").Debug("b"); AssertDebugLastMessage("debug", "ala ma b"); } LogManager.GetLogger("A").Debug("a"); AssertDebugLastMessage("debug", "ala a"); } LogManager.GetLogger("A").Debug("0"); AssertDebugLastMessage("debug", " 0"); } [Fact] public void NDCSeparatorTest() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${ndc:separator=\:} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); NestedDiagnosticsContext.Clear(); LogManager.GetLogger("A").Debug("0"); AssertDebugLastMessage("debug", " 0"); using (NestedDiagnosticsContext.Push("ala")) { LogManager.GetLogger("A").Debug("a"); AssertDebugLastMessage("debug", "ala a"); using (NestedDiagnosticsContext.Push("ma")) { LogManager.GetLogger("A").Debug("b"); AssertDebugLastMessage("debug", "ala:ma b"); using (NestedDiagnosticsContext.Push("kota")) { LogManager.GetLogger("A").Debug("c"); AssertDebugLastMessage("debug", "ala:ma:kota c"); using (NestedDiagnosticsContext.Push("kopytko")) { LogManager.GetLogger("A").Debug("d"); AssertDebugLastMessage("debug", "ala:ma:kota:kopytko d"); } LogManager.GetLogger("A").Debug("c"); AssertDebugLastMessage("debug", "ala:ma:kota c"); } LogManager.GetLogger("A").Debug("b"); AssertDebugLastMessage("debug", "ala:ma b"); } LogManager.GetLogger("A").Debug("a"); AssertDebugLastMessage("debug", "ala a"); } LogManager.GetLogger("A").Debug("0"); AssertDebugLastMessage("debug", " 0"); } } }
using System; using System.Collections.Generic; using Android.Runtime; namespace Org.Webrtc { // Metadata.xml XPath class reference: path="/api/package[@name='org.webrtc']/class[@name='PeerConnectionFactory']" [global::Android.Runtime.Register ("org/webrtc/PeerConnectionFactory", DoNotGenerateAcw=true)] public partial class PeerConnectionFactory : global::Java.Lang.Object { // Metadata.xml XPath class reference: path="/api/package[@name='org.webrtc']/class[@name='PeerConnectionFactory.Options']" [global::Android.Runtime.Register ("org/webrtc/PeerConnectionFactory$Options", DoNotGenerateAcw=true)] public partial class Options : global::Java.Lang.Object { static IntPtr disableEncryption_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='PeerConnectionFactory.Options']/field[@name='disableEncryption']" [Register ("disableEncryption")] public bool DisableEncryption { get { if (disableEncryption_jfieldId == IntPtr.Zero) disableEncryption_jfieldId = JNIEnv.GetFieldID (class_ref, "disableEncryption", "Z"); return JNIEnv.GetBooleanField (Handle, disableEncryption_jfieldId); } set { if (disableEncryption_jfieldId == IntPtr.Zero) disableEncryption_jfieldId = JNIEnv.GetFieldID (class_ref, "disableEncryption", "Z"); try { JNIEnv.SetField (Handle, disableEncryption_jfieldId, value); } finally { } } } static IntPtr networkIgnoreMask_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='PeerConnectionFactory.Options']/field[@name='networkIgnoreMask']" [Register ("networkIgnoreMask")] public int NetworkIgnoreMask { get { if (networkIgnoreMask_jfieldId == IntPtr.Zero) networkIgnoreMask_jfieldId = JNIEnv.GetFieldID (class_ref, "networkIgnoreMask", "I"); return JNIEnv.GetIntField (Handle, networkIgnoreMask_jfieldId); } set { if (networkIgnoreMask_jfieldId == IntPtr.Zero) networkIgnoreMask_jfieldId = JNIEnv.GetFieldID (class_ref, "networkIgnoreMask", "I"); try { JNIEnv.SetField (Handle, networkIgnoreMask_jfieldId, value); } finally { } } } internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("org/webrtc/PeerConnectionFactory$Options", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (Options); } } protected Options (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor; // Metadata.xml XPath constructor reference: path="/api/package[@name='org.webrtc']/class[@name='PeerConnectionFactory.Options']/constructor[@name='PeerConnectionFactory.Options' and count(parameter)=0]" [Register (".ctor", "()V", "")] public unsafe Options () : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (Handle != IntPtr.Zero) return; try { if (GetType () != typeof (Options)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "()V"), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "()V"); return; } if (id_ctor == IntPtr.Zero) id_ctor = JNIEnv.GetMethodID (class_ref, "<init>", "()V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor); } finally { } } } internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("org/webrtc/PeerConnectionFactory", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (PeerConnectionFactory); } } protected PeerConnectionFactory (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor; // Metadata.xml XPath constructor reference: path="/api/package[@name='org.webrtc']/class[@name='PeerConnectionFactory']/constructor[@name='PeerConnectionFactory' and count(parameter)=0]" [Register (".ctor", "()V", "")] public unsafe PeerConnectionFactory () : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (Handle != IntPtr.Zero) return; try { if (GetType () != typeof (PeerConnectionFactory)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "()V"), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "()V"); return; } if (id_ctor == IntPtr.Zero) id_ctor = JNIEnv.GetMethodID (class_ref, "<init>", "()V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor); } finally { } } static Delegate cb_createAudioSource_Lorg_webrtc_MediaConstraints_; #pragma warning disable 0169 static Delegate GetCreateAudioSource_Lorg_webrtc_MediaConstraints_Handler () { if (cb_createAudioSource_Lorg_webrtc_MediaConstraints_ == null) cb_createAudioSource_Lorg_webrtc_MediaConstraints_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, IntPtr>) n_CreateAudioSource_Lorg_webrtc_MediaConstraints_); return cb_createAudioSource_Lorg_webrtc_MediaConstraints_; } static IntPtr n_CreateAudioSource_Lorg_webrtc_MediaConstraints_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Org.Webrtc.PeerConnectionFactory __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.PeerConnectionFactory> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Org.Webrtc.MediaConstraints p0 = global::Java.Lang.Object.GetObject<global::Org.Webrtc.MediaConstraints> (native_p0, JniHandleOwnership.DoNotTransfer); IntPtr __ret = JNIEnv.ToLocalJniHandle (__this.CreateAudioSource (p0)); return __ret; } #pragma warning restore 0169 static IntPtr id_createAudioSource_Lorg_webrtc_MediaConstraints_; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='PeerConnectionFactory']/method[@name='createAudioSource' and count(parameter)=1 and parameter[1][@type='org.webrtc.MediaConstraints']]" [Register ("createAudioSource", "(Lorg/webrtc/MediaConstraints;)Lorg/webrtc/AudioSource;", "GetCreateAudioSource_Lorg_webrtc_MediaConstraints_Handler")] public virtual unsafe global::Org.Webrtc.AudioSource CreateAudioSource (global::Org.Webrtc.MediaConstraints p0) { if (id_createAudioSource_Lorg_webrtc_MediaConstraints_ == IntPtr.Zero) id_createAudioSource_Lorg_webrtc_MediaConstraints_ = JNIEnv.GetMethodID (class_ref, "createAudioSource", "(Lorg/webrtc/MediaConstraints;)Lorg/webrtc/AudioSource;"); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (p0); global::Org.Webrtc.AudioSource __ret; if (GetType () == ThresholdType) __ret = global::Java.Lang.Object.GetObject<global::Org.Webrtc.AudioSource> (JNIEnv.CallObjectMethod (Handle, id_createAudioSource_Lorg_webrtc_MediaConstraints_, __args), JniHandleOwnership.TransferLocalRef); else __ret = global::Java.Lang.Object.GetObject<global::Org.Webrtc.AudioSource> (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "createAudioSource", "(Lorg/webrtc/MediaConstraints;)Lorg/webrtc/AudioSource;"), __args), JniHandleOwnership.TransferLocalRef); return __ret; } finally { } } static Delegate cb_createAudioTrack_Ljava_lang_String_Lorg_webrtc_AudioSource_; #pragma warning disable 0169 static Delegate GetCreateAudioTrack_Ljava_lang_String_Lorg_webrtc_AudioSource_Handler () { if (cb_createAudioTrack_Ljava_lang_String_Lorg_webrtc_AudioSource_ == null) cb_createAudioTrack_Ljava_lang_String_Lorg_webrtc_AudioSource_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, IntPtr, IntPtr>) n_CreateAudioTrack_Ljava_lang_String_Lorg_webrtc_AudioSource_); return cb_createAudioTrack_Ljava_lang_String_Lorg_webrtc_AudioSource_; } static IntPtr n_CreateAudioTrack_Ljava_lang_String_Lorg_webrtc_AudioSource_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, IntPtr native_p1) { global::Org.Webrtc.PeerConnectionFactory __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.PeerConnectionFactory> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer); global::Org.Webrtc.AudioSource p1 = global::Java.Lang.Object.GetObject<global::Org.Webrtc.AudioSource> (native_p1, JniHandleOwnership.DoNotTransfer); IntPtr __ret = JNIEnv.ToLocalJniHandle (__this.CreateAudioTrack (p0, p1)); return __ret; } #pragma warning restore 0169 static IntPtr id_createAudioTrack_Ljava_lang_String_Lorg_webrtc_AudioSource_; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='PeerConnectionFactory']/method[@name='createAudioTrack' and count(parameter)=2 and parameter[1][@type='java.lang.String'] and parameter[2][@type='org.webrtc.AudioSource']]" [Register ("createAudioTrack", "(Ljava/lang/String;Lorg/webrtc/AudioSource;)Lorg/webrtc/AudioTrack;", "GetCreateAudioTrack_Ljava_lang_String_Lorg_webrtc_AudioSource_Handler")] public virtual unsafe global::Org.Webrtc.AudioTrack CreateAudioTrack (string p0, global::Org.Webrtc.AudioSource p1) { if (id_createAudioTrack_Ljava_lang_String_Lorg_webrtc_AudioSource_ == IntPtr.Zero) id_createAudioTrack_Ljava_lang_String_Lorg_webrtc_AudioSource_ = JNIEnv.GetMethodID (class_ref, "createAudioTrack", "(Ljava/lang/String;Lorg/webrtc/AudioSource;)Lorg/webrtc/AudioTrack;"); IntPtr native_p0 = JNIEnv.NewString (p0); try { JValue* __args = stackalloc JValue [2]; __args [0] = new JValue (native_p0); __args [1] = new JValue (p1); global::Org.Webrtc.AudioTrack __ret; if (GetType () == ThresholdType) __ret = global::Java.Lang.Object.GetObject<global::Org.Webrtc.AudioTrack> (JNIEnv.CallObjectMethod (Handle, id_createAudioTrack_Ljava_lang_String_Lorg_webrtc_AudioSource_, __args), JniHandleOwnership.TransferLocalRef); else __ret = global::Java.Lang.Object.GetObject<global::Org.Webrtc.AudioTrack> (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "createAudioTrack", "(Ljava/lang/String;Lorg/webrtc/AudioSource;)Lorg/webrtc/AudioTrack;"), __args), JniHandleOwnership.TransferLocalRef); return __ret; } finally { JNIEnv.DeleteLocalRef (native_p0); } } static Delegate cb_createLocalMediaStream_Ljava_lang_String_; #pragma warning disable 0169 static Delegate GetCreateLocalMediaStream_Ljava_lang_String_Handler () { if (cb_createLocalMediaStream_Ljava_lang_String_ == null) cb_createLocalMediaStream_Ljava_lang_String_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, IntPtr>) n_CreateLocalMediaStream_Ljava_lang_String_); return cb_createLocalMediaStream_Ljava_lang_String_; } static IntPtr n_CreateLocalMediaStream_Ljava_lang_String_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Org.Webrtc.PeerConnectionFactory __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.PeerConnectionFactory> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer); IntPtr __ret = JNIEnv.ToLocalJniHandle (__this.CreateLocalMediaStream (p0)); return __ret; } #pragma warning restore 0169 static IntPtr id_createLocalMediaStream_Ljava_lang_String_; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='PeerConnectionFactory']/method[@name='createLocalMediaStream' and count(parameter)=1 and parameter[1][@type='java.lang.String']]" [Register ("createLocalMediaStream", "(Ljava/lang/String;)Lorg/webrtc/MediaStream;", "GetCreateLocalMediaStream_Ljava_lang_String_Handler")] public virtual unsafe global::Org.Webrtc.MediaStream CreateLocalMediaStream (string p0) { if (id_createLocalMediaStream_Ljava_lang_String_ == IntPtr.Zero) id_createLocalMediaStream_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "createLocalMediaStream", "(Ljava/lang/String;)Lorg/webrtc/MediaStream;"); IntPtr native_p0 = JNIEnv.NewString (p0); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (native_p0); global::Org.Webrtc.MediaStream __ret; if (GetType () == ThresholdType) __ret = global::Java.Lang.Object.GetObject<global::Org.Webrtc.MediaStream> (JNIEnv.CallObjectMethod (Handle, id_createLocalMediaStream_Ljava_lang_String_, __args), JniHandleOwnership.TransferLocalRef); else __ret = global::Java.Lang.Object.GetObject<global::Org.Webrtc.MediaStream> (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "createLocalMediaStream", "(Ljava/lang/String;)Lorg/webrtc/MediaStream;"), __args), JniHandleOwnership.TransferLocalRef); return __ret; } finally { JNIEnv.DeleteLocalRef (native_p0); } } static Delegate cb_createPeerConnection_Ljava_util_List_Lorg_webrtc_MediaConstraints_Lorg_webrtc_PeerConnection_Observer_; #pragma warning disable 0169 static Delegate GetCreatePeerConnection_Ljava_util_List_Lorg_webrtc_MediaConstraints_Lorg_webrtc_PeerConnection_Observer_Handler () { if (cb_createPeerConnection_Ljava_util_List_Lorg_webrtc_MediaConstraints_Lorg_webrtc_PeerConnection_Observer_ == null) cb_createPeerConnection_Ljava_util_List_Lorg_webrtc_MediaConstraints_Lorg_webrtc_PeerConnection_Observer_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, IntPtr, IntPtr, IntPtr>) n_CreatePeerConnection_Ljava_util_List_Lorg_webrtc_MediaConstraints_Lorg_webrtc_PeerConnection_Observer_); return cb_createPeerConnection_Ljava_util_List_Lorg_webrtc_MediaConstraints_Lorg_webrtc_PeerConnection_Observer_; } static IntPtr n_CreatePeerConnection_Ljava_util_List_Lorg_webrtc_MediaConstraints_Lorg_webrtc_PeerConnection_Observer_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, IntPtr native_p1, IntPtr native_p2) { global::Org.Webrtc.PeerConnectionFactory __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.PeerConnectionFactory> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); var p0 = global::Android.Runtime.JavaList<global::Org.Webrtc.PeerConnection.IceServer>.FromJniHandle (native_p0, JniHandleOwnership.DoNotTransfer); global::Org.Webrtc.MediaConstraints p1 = global::Java.Lang.Object.GetObject<global::Org.Webrtc.MediaConstraints> (native_p1, JniHandleOwnership.DoNotTransfer); global::Org.Webrtc.PeerConnection.IObserver p2 = (global::Org.Webrtc.PeerConnection.IObserver)global::Java.Lang.Object.GetObject<global::Org.Webrtc.PeerConnection.IObserver> (native_p2, JniHandleOwnership.DoNotTransfer); IntPtr __ret = JNIEnv.ToLocalJniHandle (__this.CreatePeerConnection (p0, p1, p2)); return __ret; } #pragma warning restore 0169 static IntPtr id_createPeerConnection_Ljava_util_List_Lorg_webrtc_MediaConstraints_Lorg_webrtc_PeerConnection_Observer_; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='PeerConnectionFactory']/method[@name='createPeerConnection' and count(parameter)=3 and parameter[1][@type='java.util.List&lt;org.webrtc.PeerConnection.IceServer&gt;'] and parameter[2][@type='org.webrtc.MediaConstraints'] and parameter[3][@type='org.webrtc.PeerConnection.Observer']]" [Register ("createPeerConnection", "(Ljava/util/List;Lorg/webrtc/MediaConstraints;Lorg/webrtc/PeerConnection$Observer;)Lorg/webrtc/PeerConnection;", "GetCreatePeerConnection_Ljava_util_List_Lorg_webrtc_MediaConstraints_Lorg_webrtc_PeerConnection_Observer_Handler")] public virtual unsafe global::Org.Webrtc.PeerConnection CreatePeerConnection (global::System.Collections.Generic.IList<global::Org.Webrtc.PeerConnection.IceServer> p0, global::Org.Webrtc.MediaConstraints p1, global::Org.Webrtc.PeerConnection.IObserver p2) { if (id_createPeerConnection_Ljava_util_List_Lorg_webrtc_MediaConstraints_Lorg_webrtc_PeerConnection_Observer_ == IntPtr.Zero) id_createPeerConnection_Ljava_util_List_Lorg_webrtc_MediaConstraints_Lorg_webrtc_PeerConnection_Observer_ = JNIEnv.GetMethodID (class_ref, "createPeerConnection", "(Ljava/util/List;Lorg/webrtc/MediaConstraints;Lorg/webrtc/PeerConnection$Observer;)Lorg/webrtc/PeerConnection;"); IntPtr native_p0 = global::Android.Runtime.JavaList<global::Org.Webrtc.PeerConnection.IceServer>.ToLocalJniHandle (p0); try { JValue* __args = stackalloc JValue [3]; __args [0] = new JValue (native_p0); __args [1] = new JValue (p1); __args [2] = new JValue (p2); global::Org.Webrtc.PeerConnection __ret; if (GetType () == ThresholdType) __ret = global::Java.Lang.Object.GetObject<global::Org.Webrtc.PeerConnection> (JNIEnv.CallObjectMethod (Handle, id_createPeerConnection_Ljava_util_List_Lorg_webrtc_MediaConstraints_Lorg_webrtc_PeerConnection_Observer_, __args), JniHandleOwnership.TransferLocalRef); else __ret = global::Java.Lang.Object.GetObject<global::Org.Webrtc.PeerConnection> (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "createPeerConnection", "(Ljava/util/List;Lorg/webrtc/MediaConstraints;Lorg/webrtc/PeerConnection$Observer;)Lorg/webrtc/PeerConnection;"), __args), JniHandleOwnership.TransferLocalRef); return __ret; } finally { JNIEnv.DeleteLocalRef (native_p0); } } static Delegate cb_createPeerConnection_Lorg_webrtc_PeerConnection_RTCConfiguration_Lorg_webrtc_MediaConstraints_Lorg_webrtc_PeerConnection_Observer_; #pragma warning disable 0169 static Delegate GetCreatePeerConnection_Lorg_webrtc_PeerConnection_RTCConfiguration_Lorg_webrtc_MediaConstraints_Lorg_webrtc_PeerConnection_Observer_Handler () { if (cb_createPeerConnection_Lorg_webrtc_PeerConnection_RTCConfiguration_Lorg_webrtc_MediaConstraints_Lorg_webrtc_PeerConnection_Observer_ == null) cb_createPeerConnection_Lorg_webrtc_PeerConnection_RTCConfiguration_Lorg_webrtc_MediaConstraints_Lorg_webrtc_PeerConnection_Observer_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, IntPtr, IntPtr, IntPtr>) n_CreatePeerConnection_Lorg_webrtc_PeerConnection_RTCConfiguration_Lorg_webrtc_MediaConstraints_Lorg_webrtc_PeerConnection_Observer_); return cb_createPeerConnection_Lorg_webrtc_PeerConnection_RTCConfiguration_Lorg_webrtc_MediaConstraints_Lorg_webrtc_PeerConnection_Observer_; } static IntPtr n_CreatePeerConnection_Lorg_webrtc_PeerConnection_RTCConfiguration_Lorg_webrtc_MediaConstraints_Lorg_webrtc_PeerConnection_Observer_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, IntPtr native_p1, IntPtr native_p2) { global::Org.Webrtc.PeerConnectionFactory __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.PeerConnectionFactory> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Org.Webrtc.PeerConnection.RTCConfiguration p0 = global::Java.Lang.Object.GetObject<global::Org.Webrtc.PeerConnection.RTCConfiguration> (native_p0, JniHandleOwnership.DoNotTransfer); global::Org.Webrtc.MediaConstraints p1 = global::Java.Lang.Object.GetObject<global::Org.Webrtc.MediaConstraints> (native_p1, JniHandleOwnership.DoNotTransfer); global::Org.Webrtc.PeerConnection.IObserver p2 = (global::Org.Webrtc.PeerConnection.IObserver)global::Java.Lang.Object.GetObject<global::Org.Webrtc.PeerConnection.IObserver> (native_p2, JniHandleOwnership.DoNotTransfer); IntPtr __ret = JNIEnv.ToLocalJniHandle (__this.CreatePeerConnection (p0, p1, p2)); return __ret; } #pragma warning restore 0169 static IntPtr id_createPeerConnection_Lorg_webrtc_PeerConnection_RTCConfiguration_Lorg_webrtc_MediaConstraints_Lorg_webrtc_PeerConnection_Observer_; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='PeerConnectionFactory']/method[@name='createPeerConnection' and count(parameter)=3 and parameter[1][@type='org.webrtc.PeerConnection.RTCConfiguration'] and parameter[2][@type='org.webrtc.MediaConstraints'] and parameter[3][@type='org.webrtc.PeerConnection.Observer']]" [Register ("createPeerConnection", "(Lorg/webrtc/PeerConnection$RTCConfiguration;Lorg/webrtc/MediaConstraints;Lorg/webrtc/PeerConnection$Observer;)Lorg/webrtc/PeerConnection;", "GetCreatePeerConnection_Lorg_webrtc_PeerConnection_RTCConfiguration_Lorg_webrtc_MediaConstraints_Lorg_webrtc_PeerConnection_Observer_Handler")] public virtual unsafe global::Org.Webrtc.PeerConnection CreatePeerConnection (global::Org.Webrtc.PeerConnection.RTCConfiguration p0, global::Org.Webrtc.MediaConstraints p1, global::Org.Webrtc.PeerConnection.IObserver p2) { if (id_createPeerConnection_Lorg_webrtc_PeerConnection_RTCConfiguration_Lorg_webrtc_MediaConstraints_Lorg_webrtc_PeerConnection_Observer_ == IntPtr.Zero) id_createPeerConnection_Lorg_webrtc_PeerConnection_RTCConfiguration_Lorg_webrtc_MediaConstraints_Lorg_webrtc_PeerConnection_Observer_ = JNIEnv.GetMethodID (class_ref, "createPeerConnection", "(Lorg/webrtc/PeerConnection$RTCConfiguration;Lorg/webrtc/MediaConstraints;Lorg/webrtc/PeerConnection$Observer;)Lorg/webrtc/PeerConnection;"); try { JValue* __args = stackalloc JValue [3]; __args [0] = new JValue (p0); __args [1] = new JValue (p1); __args [2] = new JValue (p2); global::Org.Webrtc.PeerConnection __ret; if (GetType () == ThresholdType) __ret = global::Java.Lang.Object.GetObject<global::Org.Webrtc.PeerConnection> (JNIEnv.CallObjectMethod (Handle, id_createPeerConnection_Lorg_webrtc_PeerConnection_RTCConfiguration_Lorg_webrtc_MediaConstraints_Lorg_webrtc_PeerConnection_Observer_, __args), JniHandleOwnership.TransferLocalRef); else __ret = global::Java.Lang.Object.GetObject<global::Org.Webrtc.PeerConnection> (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "createPeerConnection", "(Lorg/webrtc/PeerConnection$RTCConfiguration;Lorg/webrtc/MediaConstraints;Lorg/webrtc/PeerConnection$Observer;)Lorg/webrtc/PeerConnection;"), __args), JniHandleOwnership.TransferLocalRef); return __ret; } finally { } } static Delegate cb_createVideoSource_Lorg_webrtc_VideoCapturer_Lorg_webrtc_MediaConstraints_; #pragma warning disable 0169 static Delegate GetCreateVideoSource_Lorg_webrtc_VideoCapturer_Lorg_webrtc_MediaConstraints_Handler () { if (cb_createVideoSource_Lorg_webrtc_VideoCapturer_Lorg_webrtc_MediaConstraints_ == null) cb_createVideoSource_Lorg_webrtc_VideoCapturer_Lorg_webrtc_MediaConstraints_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, IntPtr, IntPtr>) n_CreateVideoSource_Lorg_webrtc_VideoCapturer_Lorg_webrtc_MediaConstraints_); return cb_createVideoSource_Lorg_webrtc_VideoCapturer_Lorg_webrtc_MediaConstraints_; } static IntPtr n_CreateVideoSource_Lorg_webrtc_VideoCapturer_Lorg_webrtc_MediaConstraints_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, IntPtr native_p1) { global::Org.Webrtc.PeerConnectionFactory __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.PeerConnectionFactory> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Org.Webrtc.VideoCapturer p0 = global::Java.Lang.Object.GetObject<global::Org.Webrtc.VideoCapturer> (native_p0, JniHandleOwnership.DoNotTransfer); global::Org.Webrtc.MediaConstraints p1 = global::Java.Lang.Object.GetObject<global::Org.Webrtc.MediaConstraints> (native_p1, JniHandleOwnership.DoNotTransfer); IntPtr __ret = JNIEnv.ToLocalJniHandle (__this.CreateVideoSource (p0, p1)); return __ret; } #pragma warning restore 0169 static IntPtr id_createVideoSource_Lorg_webrtc_VideoCapturer_Lorg_webrtc_MediaConstraints_; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='PeerConnectionFactory']/method[@name='createVideoSource' and count(parameter)=2 and parameter[1][@type='org.webrtc.VideoCapturer'] and parameter[2][@type='org.webrtc.MediaConstraints']]" [Register ("createVideoSource", "(Lorg/webrtc/VideoCapturer;Lorg/webrtc/MediaConstraints;)Lorg/webrtc/VideoSource;", "GetCreateVideoSource_Lorg_webrtc_VideoCapturer_Lorg_webrtc_MediaConstraints_Handler")] public virtual unsafe global::Org.Webrtc.VideoSource CreateVideoSource (global::Org.Webrtc.VideoCapturer p0, global::Org.Webrtc.MediaConstraints p1) { if (id_createVideoSource_Lorg_webrtc_VideoCapturer_Lorg_webrtc_MediaConstraints_ == IntPtr.Zero) id_createVideoSource_Lorg_webrtc_VideoCapturer_Lorg_webrtc_MediaConstraints_ = JNIEnv.GetMethodID (class_ref, "createVideoSource", "(Lorg/webrtc/VideoCapturer;Lorg/webrtc/MediaConstraints;)Lorg/webrtc/VideoSource;"); try { JValue* __args = stackalloc JValue [2]; __args [0] = new JValue (p0); __args [1] = new JValue (p1); global::Org.Webrtc.VideoSource __ret; if (GetType () == ThresholdType) __ret = global::Java.Lang.Object.GetObject<global::Org.Webrtc.VideoSource> (JNIEnv.CallObjectMethod (Handle, id_createVideoSource_Lorg_webrtc_VideoCapturer_Lorg_webrtc_MediaConstraints_, __args), JniHandleOwnership.TransferLocalRef); else __ret = global::Java.Lang.Object.GetObject<global::Org.Webrtc.VideoSource> (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "createVideoSource", "(Lorg/webrtc/VideoCapturer;Lorg/webrtc/MediaConstraints;)Lorg/webrtc/VideoSource;"), __args), JniHandleOwnership.TransferLocalRef); return __ret; } finally { } } static Delegate cb_createVideoTrack_Ljava_lang_String_Lorg_webrtc_VideoSource_; #pragma warning disable 0169 static Delegate GetCreateVideoTrack_Ljava_lang_String_Lorg_webrtc_VideoSource_Handler () { if (cb_createVideoTrack_Ljava_lang_String_Lorg_webrtc_VideoSource_ == null) cb_createVideoTrack_Ljava_lang_String_Lorg_webrtc_VideoSource_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, IntPtr, IntPtr>) n_CreateVideoTrack_Ljava_lang_String_Lorg_webrtc_VideoSource_); return cb_createVideoTrack_Ljava_lang_String_Lorg_webrtc_VideoSource_; } static IntPtr n_CreateVideoTrack_Ljava_lang_String_Lorg_webrtc_VideoSource_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, IntPtr native_p1) { global::Org.Webrtc.PeerConnectionFactory __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.PeerConnectionFactory> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer); global::Org.Webrtc.VideoSource p1 = global::Java.Lang.Object.GetObject<global::Org.Webrtc.VideoSource> (native_p1, JniHandleOwnership.DoNotTransfer); IntPtr __ret = JNIEnv.ToLocalJniHandle (__this.CreateVideoTrack (p0, p1)); return __ret; } #pragma warning restore 0169 static IntPtr id_createVideoTrack_Ljava_lang_String_Lorg_webrtc_VideoSource_; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='PeerConnectionFactory']/method[@name='createVideoTrack' and count(parameter)=2 and parameter[1][@type='java.lang.String'] and parameter[2][@type='org.webrtc.VideoSource']]" [Register ("createVideoTrack", "(Ljava/lang/String;Lorg/webrtc/VideoSource;)Lorg/webrtc/VideoTrack;", "GetCreateVideoTrack_Ljava_lang_String_Lorg_webrtc_VideoSource_Handler")] public virtual unsafe global::Org.Webrtc.VideoTrack CreateVideoTrack (string p0, global::Org.Webrtc.VideoSource p1) { if (id_createVideoTrack_Ljava_lang_String_Lorg_webrtc_VideoSource_ == IntPtr.Zero) id_createVideoTrack_Ljava_lang_String_Lorg_webrtc_VideoSource_ = JNIEnv.GetMethodID (class_ref, "createVideoTrack", "(Ljava/lang/String;Lorg/webrtc/VideoSource;)Lorg/webrtc/VideoTrack;"); IntPtr native_p0 = JNIEnv.NewString (p0); try { JValue* __args = stackalloc JValue [2]; __args [0] = new JValue (native_p0); __args [1] = new JValue (p1); global::Org.Webrtc.VideoTrack __ret; if (GetType () == ThresholdType) __ret = global::Java.Lang.Object.GetObject<global::Org.Webrtc.VideoTrack> (JNIEnv.CallObjectMethod (Handle, id_createVideoTrack_Ljava_lang_String_Lorg_webrtc_VideoSource_, __args), JniHandleOwnership.TransferLocalRef); else __ret = global::Java.Lang.Object.GetObject<global::Org.Webrtc.VideoTrack> (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "createVideoTrack", "(Ljava/lang/String;Lorg/webrtc/VideoSource;)Lorg/webrtc/VideoTrack;"), __args), JniHandleOwnership.TransferLocalRef); return __ret; } finally { JNIEnv.DeleteLocalRef (native_p0); } } static Delegate cb_dispose; #pragma warning disable 0169 static Delegate GetDisposeHandler () { if (cb_dispose == null) cb_dispose = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr>) n_Dispose); return cb_dispose; } static void n_Dispose (IntPtr jnienv, IntPtr native__this) { global::Org.Webrtc.PeerConnectionFactory __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.PeerConnectionFactory> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); __this.Dispose (); } #pragma warning restore 0169 static IntPtr id_dispose; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='PeerConnectionFactory']/method[@name='dispose' and count(parameter)=0]" [Register ("dispose", "()V", "GetDisposeHandler")] public virtual unsafe void Dispose () { if (id_dispose == IntPtr.Zero) id_dispose = JNIEnv.GetMethodID (class_ref, "dispose", "()V"); try { if (GetType () == ThresholdType) JNIEnv.CallVoidMethod (Handle, id_dispose); else JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "dispose", "()V")); } finally { } } static IntPtr id_initializeAndroidGlobals_Ljava_lang_Object_ZZZLjava_lang_Object_; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='PeerConnectionFactory']/method[@name='initializeAndroidGlobals' and count(parameter)=5 and parameter[1][@type='java.lang.Object'] and parameter[2][@type='boolean'] and parameter[3][@type='boolean'] and parameter[4][@type='boolean'] and parameter[5][@type='java.lang.Object']]" [Register ("initializeAndroidGlobals", "(Ljava/lang/Object;ZZZLjava/lang/Object;)Z", "")] public static unsafe bool InitializeAndroidGlobals (global::Java.Lang.Object p0, bool p1, bool p2, bool p3, global::Java.Lang.Object p4) { if (id_initializeAndroidGlobals_Ljava_lang_Object_ZZZLjava_lang_Object_ == IntPtr.Zero) id_initializeAndroidGlobals_Ljava_lang_Object_ZZZLjava_lang_Object_ = JNIEnv.GetStaticMethodID (class_ref, "initializeAndroidGlobals", "(Ljava/lang/Object;ZZZLjava/lang/Object;)Z"); try { JValue* __args = stackalloc JValue [5]; __args [0] = new JValue (p0); __args [1] = new JValue (p1); __args [2] = new JValue (p2); __args [3] = new JValue (p3); __args [4] = new JValue (p4); bool __ret = JNIEnv.CallStaticBooleanMethod (class_ref, id_initializeAndroidGlobals_Ljava_lang_Object_ZZZLjava_lang_Object_, __args); return __ret; } finally { } } static IntPtr id_initializeFieldTrials_Ljava_lang_String_; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='PeerConnectionFactory']/method[@name='initializeFieldTrials' and count(parameter)=1 and parameter[1][@type='java.lang.String']]" [Register ("initializeFieldTrials", "(Ljava/lang/String;)V", "")] public static unsafe void InitializeFieldTrials (string p0) { if (id_initializeFieldTrials_Ljava_lang_String_ == IntPtr.Zero) id_initializeFieldTrials_Ljava_lang_String_ = JNIEnv.GetStaticMethodID (class_ref, "initializeFieldTrials", "(Ljava/lang/String;)V"); IntPtr native_p0 = JNIEnv.NewString (p0); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (native_p0); JNIEnv.CallStaticVoidMethod (class_ref, id_initializeFieldTrials_Ljava_lang_String_, __args); } finally { JNIEnv.DeleteLocalRef (native_p0); } } static Delegate cb_nativeSetOptions_JLorg_webrtc_PeerConnectionFactory_Options_; #pragma warning disable 0169 static Delegate GetNativeSetOptions_JLorg_webrtc_PeerConnectionFactory_Options_Handler () { if (cb_nativeSetOptions_JLorg_webrtc_PeerConnectionFactory_Options_ == null) cb_nativeSetOptions_JLorg_webrtc_PeerConnectionFactory_Options_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, long, IntPtr>) n_NativeSetOptions_JLorg_webrtc_PeerConnectionFactory_Options_); return cb_nativeSetOptions_JLorg_webrtc_PeerConnectionFactory_Options_; } static void n_NativeSetOptions_JLorg_webrtc_PeerConnectionFactory_Options_ (IntPtr jnienv, IntPtr native__this, long p0, IntPtr native_p1) { global::Org.Webrtc.PeerConnectionFactory __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.PeerConnectionFactory> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Org.Webrtc.PeerConnectionFactory.Options p1 = global::Java.Lang.Object.GetObject<global::Org.Webrtc.PeerConnectionFactory.Options> (native_p1, JniHandleOwnership.DoNotTransfer); __this.NativeSetOptions (p0, p1); } #pragma warning restore 0169 static IntPtr id_nativeSetOptions_JLorg_webrtc_PeerConnectionFactory_Options_; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='PeerConnectionFactory']/method[@name='nativeSetOptions' and count(parameter)=2 and parameter[1][@type='long'] and parameter[2][@type='org.webrtc.PeerConnectionFactory.Options']]" [Register ("nativeSetOptions", "(JLorg/webrtc/PeerConnectionFactory$Options;)V", "GetNativeSetOptions_JLorg_webrtc_PeerConnectionFactory_Options_Handler")] public virtual unsafe void NativeSetOptions (long p0, global::Org.Webrtc.PeerConnectionFactory.Options p1) { if (id_nativeSetOptions_JLorg_webrtc_PeerConnectionFactory_Options_ == IntPtr.Zero) id_nativeSetOptions_JLorg_webrtc_PeerConnectionFactory_Options_ = JNIEnv.GetMethodID (class_ref, "nativeSetOptions", "(JLorg/webrtc/PeerConnectionFactory$Options;)V"); try { JValue* __args = stackalloc JValue [2]; __args [0] = new JValue (p0); __args [1] = new JValue (p1); if (GetType () == ThresholdType) JNIEnv.CallVoidMethod (Handle, id_nativeSetOptions_JLorg_webrtc_PeerConnectionFactory_Options_, __args); else JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "nativeSetOptions", "(JLorg/webrtc/PeerConnectionFactory$Options;)V"), __args); } finally { } } static Delegate cb_setOptions_Lorg_webrtc_PeerConnectionFactory_Options_; #pragma warning disable 0169 static Delegate GetSetOptions_Lorg_webrtc_PeerConnectionFactory_Options_Handler () { if (cb_setOptions_Lorg_webrtc_PeerConnectionFactory_Options_ == null) cb_setOptions_Lorg_webrtc_PeerConnectionFactory_Options_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_SetOptions_Lorg_webrtc_PeerConnectionFactory_Options_); return cb_setOptions_Lorg_webrtc_PeerConnectionFactory_Options_; } static void n_SetOptions_Lorg_webrtc_PeerConnectionFactory_Options_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Org.Webrtc.PeerConnectionFactory __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.PeerConnectionFactory> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Org.Webrtc.PeerConnectionFactory.Options p0 = global::Java.Lang.Object.GetObject<global::Org.Webrtc.PeerConnectionFactory.Options> (native_p0, JniHandleOwnership.DoNotTransfer); __this.SetOptions (p0); } #pragma warning restore 0169 static IntPtr id_setOptions_Lorg_webrtc_PeerConnectionFactory_Options_; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='PeerConnectionFactory']/method[@name='setOptions' and count(parameter)=1 and parameter[1][@type='org.webrtc.PeerConnectionFactory.Options']]" [Register ("setOptions", "(Lorg/webrtc/PeerConnectionFactory$Options;)V", "GetSetOptions_Lorg_webrtc_PeerConnectionFactory_Options_Handler")] public virtual unsafe void SetOptions (global::Org.Webrtc.PeerConnectionFactory.Options p0) { if (id_setOptions_Lorg_webrtc_PeerConnectionFactory_Options_ == IntPtr.Zero) id_setOptions_Lorg_webrtc_PeerConnectionFactory_Options_ = JNIEnv.GetMethodID (class_ref, "setOptions", "(Lorg/webrtc/PeerConnectionFactory$Options;)V"); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (p0); if (GetType () == ThresholdType) JNIEnv.CallVoidMethod (Handle, id_setOptions_Lorg_webrtc_PeerConnectionFactory_Options_, __args); else JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "setOptions", "(Lorg/webrtc/PeerConnectionFactory$Options;)V"), __args); } finally { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; using Xunit; namespace System.Tests { public static partial class EnumTests { [Theory] [MemberData(nameof(Parse_TestData))] public static void Parse_NetCoreApp11<T>(string value, bool ignoreCase, T expected) where T : struct { object result; if (!ignoreCase) { Assert.True(Enum.TryParse(expected.GetType(), value, out result)); Assert.Equal(expected, result); Assert.Equal(expected, Enum.Parse<T>(value)); } Assert.True(Enum.TryParse(expected.GetType(), value, ignoreCase, out result)); Assert.Equal(expected, result); Assert.Equal(expected, Enum.Parse<T>(value, ignoreCase)); } [Theory] [MemberData(nameof(Parse_Invalid_TestData))] public static void Parse_Invalid_NetCoreApp11(Type enumType, string value, bool ignoreCase, Type exceptionType) { Type typeArgument = enumType == null || !enumType.GetTypeInfo().IsEnum ? typeof(SimpleEnum) : enumType; MethodInfo parseMethod = typeof(EnumTests).GetTypeInfo().GetMethod(nameof(Parse_Generic_Invalid_NetCoreApp11)).MakeGenericMethod(typeArgument); parseMethod.Invoke(null, new object[] { enumType, value, ignoreCase, exceptionType }); } public static void Parse_Generic_Invalid_NetCoreApp11<T>(Type enumType, string value, bool ignoreCase, Type exceptionType) where T : struct { object result = null; if (!ignoreCase) { if (enumType != null && enumType.IsEnum) { Assert.False(Enum.TryParse(enumType, value, out result)); Assert.Equal(default(object), result); Assert.Throws(exceptionType, () => Enum.Parse<T>(value)); } else { Assert.Throws(exceptionType, () => Enum.TryParse(enumType, value, out result)); Assert.Equal(default(object), result); } } if (enumType != null && enumType.IsEnum) { Assert.False(Enum.TryParse(enumType, value, ignoreCase, out result)); Assert.Equal(default(object), result); Assert.Throws(exceptionType, () => Enum.Parse<T>(value, ignoreCase)); } else { Assert.Throws(exceptionType, () => Enum.TryParse(enumType, value, ignoreCase, out result)); Assert.Equal(default(object), result); } } public static IEnumerable<object[]> UnsupportedEnumType_TestData() { yield return new object[] { s_floatEnumType, 1.0f }; yield return new object[] { s_doubleEnumType, 1.0 }; yield return new object[] { s_intPtrEnumType, (IntPtr)1 }; yield return new object[] { s_uintPtrEnumType, (UIntPtr)1 }; } [Theory] [MemberData(nameof(UnsupportedEnumType_TestData))] public static void GetName_Unsupported_ThrowsArgumentException(Type enumType, object value) { AssertExtensions.Throws<ArgumentException>("value", () => Enum.GetName(enumType, value)); } [Theory] [MemberData(nameof(UnsupportedEnumType_TestData))] public static void IsDefined_UnsupportedEnumType_ThrowsInvalidOperationException(Type enumType, object value) { // A Contract.Assert(false, "...") is hit for certain unsupported primitives Exception ex = Assert.ThrowsAny<Exception>(() => Enum.IsDefined(enumType, value)); string exName = ex.GetType().Name; Assert.True(exName == nameof(InvalidOperationException) || exName == "ContractException"); } [Fact] public static void ToString_InvalidUnicodeChars() { // TODO: move into ToString_Format_TestData when dotnet/buildtools#1091 is fixed ToString_Format((Enum)Enum.ToObject(s_charEnumType, char.MaxValue), "D", char.MaxValue.ToString()); ToString_Format((Enum)Enum.ToObject(s_charEnumType, char.MaxValue), "X", "FFFF"); ToString_Format((Enum)Enum.ToObject(s_charEnumType, char.MaxValue), "F", char.MaxValue.ToString()); ToString_Format((Enum)Enum.ToObject(s_charEnumType, char.MaxValue), "G", char.MaxValue.ToString()); } public static IEnumerable<object[]> UnsupportedEnum_TestData() { yield return new object[] { Enum.ToObject(s_floatEnumType, 1) }; yield return new object[] { Enum.ToObject(s_doubleEnumType, 2) }; yield return new object[] { Enum.ToObject(s_intPtrEnumType, 1) }; yield return new object[] { Enum.ToObject(s_uintPtrEnumType, 2) }; } [Theory] [MemberData(nameof(UnsupportedEnum_TestData))] public static void ToString_UnsupportedEnumType_ThrowsArgumentException(Enum e) { // A Contract.Assert(false, "...") is hit for certain unsupported primitives Exception formatXException = Assert.ThrowsAny<Exception>(() => e.ToString("X")); string formatXExceptionName = formatXException.GetType().Name; Assert.True(formatXExceptionName == nameof(InvalidOperationException) || formatXExceptionName == "ContractException"); } [Theory] [MemberData(nameof(UnsupportedEnumType_TestData))] public static void Format_UnsupportedEnumType_ThrowsArgumentException(Type enumType, object value) { // A Contract.Assert(false, "...") is hit for certain unsupported primitives Exception formatGException = Assert.ThrowsAny<Exception>(() => Enum.Format(enumType, value, "G")); string formatGExceptionName = formatGException.GetType().Name; Assert.True(formatGExceptionName == nameof(InvalidOperationException) || formatGExceptionName == "ContractException"); Exception formatXException = Assert.ThrowsAny<Exception>(() => Enum.Format(enumType, value, "X")); string formatXExceptionName = formatXException.GetType().Name; Assert.True(formatXExceptionName == nameof(InvalidOperationException) || formatXExceptionName == "ContractException"); Exception formatFException = Assert.ThrowsAny<Exception>(() => Enum.Format(enumType, value, "F")); string formatFExceptionName = formatFException.GetType().Name; Assert.True(formatFExceptionName == nameof(InvalidOperationException) || formatFExceptionName == "ContractException"); } private static EnumBuilder GetNonRuntimeEnumTypeBuilder(Type underlyingType) { AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Name"), AssemblyBuilderAccess.Run); ModuleBuilder module = assembly.DefineDynamicModule("Name"); return module.DefineEnum("TestName_" + underlyingType.Name, TypeAttributes.Public, underlyingType); } private static Type s_boolEnumType = GetBoolEnumType(); private static Type GetBoolEnumType() { EnumBuilder enumBuilder = GetNonRuntimeEnumTypeBuilder(typeof(bool)); enumBuilder.DefineLiteral("Value1", true); enumBuilder.DefineLiteral("Value2", false); return enumBuilder.CreateTypeInfo().AsType(); } private static Type s_charEnumType = GetCharEnumType(); private static Type GetCharEnumType() { EnumBuilder enumBuilder = GetNonRuntimeEnumTypeBuilder(typeof(char)); enumBuilder.DefineLiteral("Value1", (char)1); enumBuilder.DefineLiteral("Value2", (char)2); enumBuilder.DefineLiteral("Value0x3f06", (char)0x3f06); enumBuilder.DefineLiteral("Value0x3000", (char)0x3000); enumBuilder.DefineLiteral("Value0x0f06", (char)0x0f06); enumBuilder.DefineLiteral("Value0x1000", (char)0x1000); enumBuilder.DefineLiteral("Value0x0000", (char)0x0000); enumBuilder.DefineLiteral("Value0x0010", (char)0x0010); enumBuilder.DefineLiteral("Value0x3f16", (char)0x3f16); return enumBuilder.CreateTypeInfo().AsType(); } private static Type s_floatEnumType = GetFloatEnumType(); private static Type GetFloatEnumType() { EnumBuilder enumBuilder = GetNonRuntimeEnumTypeBuilder(typeof(float)); enumBuilder.DefineLiteral("Value1", 1.0f); enumBuilder.DefineLiteral("Value2", 2.0f); enumBuilder.DefineLiteral("Value0x3f06", (float)0x3f06); enumBuilder.DefineLiteral("Value0x3000", (float)0x3000); enumBuilder.DefineLiteral("Value0x0f06", (float)0x0f06); enumBuilder.DefineLiteral("Value0x1000", (float)0x1000); enumBuilder.DefineLiteral("Value0x0000", (float)0x0000); enumBuilder.DefineLiteral("Value0x0010", (float)0x0010); enumBuilder.DefineLiteral("Value0x3f16", (float)0x3f16); return enumBuilder.CreateTypeInfo().AsType(); } private static Type s_doubleEnumType = GetDoubleEnumType(); private static Type GetDoubleEnumType() { EnumBuilder enumBuilder = GetNonRuntimeEnumTypeBuilder(typeof(double)); enumBuilder.DefineLiteral("Value1", 1.0); enumBuilder.DefineLiteral("Value2", 2.0); enumBuilder.DefineLiteral("Value0x3f06", (double)0x3f06); enumBuilder.DefineLiteral("Value0x3000", (double)0x3000); enumBuilder.DefineLiteral("Value0x0f06", (double)0x0f06); enumBuilder.DefineLiteral("Value0x1000", (double)0x1000); enumBuilder.DefineLiteral("Value0x0000", (double)0x0000); enumBuilder.DefineLiteral("Value0x0010", (double)0x0010); enumBuilder.DefineLiteral("Value0x3f16", (double)0x3f16); return enumBuilder.CreateTypeInfo().AsType(); } private static Type s_intPtrEnumType = GetIntPtrEnumType(); private static Type GetIntPtrEnumType() { EnumBuilder enumBuilder = GetNonRuntimeEnumTypeBuilder(typeof(IntPtr)); return enumBuilder.CreateTypeInfo().AsType(); } private static Type s_uintPtrEnumType = GetUIntPtrEnumType(); private static Type GetUIntPtrEnumType() { EnumBuilder enumBuilder = GetNonRuntimeEnumTypeBuilder(typeof(UIntPtr)); return enumBuilder.CreateTypeInfo().AsType(); } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using NUnit.Framework; using osu.Framework.Screens; using osu.Game.Beatmaps; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Replays; using osu.Game.Rulesets.Judgements; using osu.Game.Rulesets.Mania.Objects; using osu.Game.Rulesets.Mania.Replays; using osu.Game.Rulesets.Replays; using osu.Game.Rulesets.Scoring; using osu.Game.Scoring; using osu.Game.Screens.Play; using osu.Game.Tests.Visual; namespace osu.Game.Rulesets.Mania.Tests { public class TestSceneHoldNoteInput : RateAdjustedBeatmapTestScene { private const double time_before_head = 250; private const double time_head = 1500; private const double time_during_hold_1 = 2500; private const double time_tail = 4000; private const double time_after_tail = 5250; private List<JudgementResult> judgementResults; private bool allJudgedFired; /// <summary> /// -----[ ]----- /// o o /// </summary> [Test] public void TestNoInput() { performTest(new List<ReplayFrame> { new ManiaReplayFrame(time_before_head), new ManiaReplayFrame(time_after_tail), }); assertHeadJudgement(HitResult.Miss); assertTickJudgement(HitResult.Miss); assertTailJudgement(HitResult.Miss); assertNoteJudgement(HitResult.Perfect); } /// <summary> /// -----[ ]----- /// x o /// </summary> [Test] public void TestPressTooEarlyAndReleaseAfterTail() { performTest(new List<ReplayFrame> { new ManiaReplayFrame(time_before_head, ManiaAction.Key1), new ManiaReplayFrame(time_after_tail, ManiaAction.Key1), }); assertHeadJudgement(HitResult.Miss); assertTickJudgement(HitResult.Miss); assertTailJudgement(HitResult.Miss); } /// <summary> /// -----[ ]----- /// x o /// </summary> [Test] public void TestPressTooEarlyAndReleaseAtTail() { performTest(new List<ReplayFrame> { new ManiaReplayFrame(time_before_head, ManiaAction.Key1), new ManiaReplayFrame(time_tail), }); assertHeadJudgement(HitResult.Miss); assertTickJudgement(HitResult.Miss); assertTailJudgement(HitResult.Miss); } /// <summary> /// -----[ ]----- /// xo x o /// </summary> [Test] public void TestPressTooEarlyThenPressAtStartAndReleaseAfterTail() { performTest(new List<ReplayFrame> { new ManiaReplayFrame(time_before_head, ManiaAction.Key1), new ManiaReplayFrame(time_before_head + 10), new ManiaReplayFrame(time_head, ManiaAction.Key1), new ManiaReplayFrame(time_after_tail), }); assertHeadJudgement(HitResult.Perfect); assertTickJudgement(HitResult.Perfect); assertTailJudgement(HitResult.Miss); } /// <summary> /// -----[ ]----- /// xo x o /// </summary> [Test] public void TestPressTooEarlyThenPressAtStartAndReleaseAtTail() { performTest(new List<ReplayFrame> { new ManiaReplayFrame(time_before_head, ManiaAction.Key1), new ManiaReplayFrame(time_before_head + 10), new ManiaReplayFrame(time_head, ManiaAction.Key1), new ManiaReplayFrame(time_tail), }); assertHeadJudgement(HitResult.Perfect); assertTickJudgement(HitResult.Perfect); assertTailJudgement(HitResult.Perfect); } /// <summary> /// -----[ ]----- /// xo o /// </summary> [Test] public void TestPressAtStartAndBreak() { performTest(new List<ReplayFrame> { new ManiaReplayFrame(time_head, ManiaAction.Key1), new ManiaReplayFrame(time_head + 10), new ManiaReplayFrame(time_after_tail), }); assertHeadJudgement(HitResult.Perfect); assertTickJudgement(HitResult.Miss); assertTailJudgement(HitResult.Miss); } /// <summary> /// -----[ ]----- /// xo x o /// </summary> [Test] public void TestPressAtStartThenBreakThenRepressAndReleaseAfterTail() { performTest(new List<ReplayFrame> { new ManiaReplayFrame(time_head, ManiaAction.Key1), new ManiaReplayFrame(time_head + 10), new ManiaReplayFrame(time_during_hold_1, ManiaAction.Key1), new ManiaReplayFrame(time_after_tail), }); assertHeadJudgement(HitResult.Perfect); assertTickJudgement(HitResult.Perfect); assertTailJudgement(HitResult.Miss); } /// <summary> /// -----[ ]----- /// xo x o o /// </summary> [Test] public void TestPressAtStartThenBreakThenRepressAndReleaseAtTail() { performTest(new List<ReplayFrame> { new ManiaReplayFrame(time_head, ManiaAction.Key1), new ManiaReplayFrame(time_head + 10), new ManiaReplayFrame(time_during_hold_1, ManiaAction.Key1), new ManiaReplayFrame(time_tail), }); assertHeadJudgement(HitResult.Perfect); assertTickJudgement(HitResult.Perfect); assertTailJudgement(HitResult.Meh); } /// <summary> /// -----[ ]----- /// x o /// </summary> [Test] public void TestPressDuringNoteAndReleaseAfterTail() { performTest(new List<ReplayFrame> { new ManiaReplayFrame(time_during_hold_1, ManiaAction.Key1), new ManiaReplayFrame(time_after_tail), }); assertHeadJudgement(HitResult.Miss); assertTickJudgement(HitResult.Perfect); assertTailJudgement(HitResult.Miss); } /// <summary> /// -----[ ]----- /// x o o /// </summary> [Test] public void TestPressDuringNoteAndReleaseAtTail() { performTest(new List<ReplayFrame> { new ManiaReplayFrame(time_during_hold_1, ManiaAction.Key1), new ManiaReplayFrame(time_tail), }); assertHeadJudgement(HitResult.Miss); assertTickJudgement(HitResult.Perfect); assertTailJudgement(HitResult.Meh); } /// <summary> /// -----[ ]----- /// xo o /// </summary> [Test] public void TestPressAndReleaseAtTail() { performTest(new List<ReplayFrame> { new ManiaReplayFrame(time_tail, ManiaAction.Key1), new ManiaReplayFrame(time_tail + 10), }); assertHeadJudgement(HitResult.Miss); assertTickJudgement(HitResult.Miss); assertTailJudgement(HitResult.Meh); } private void assertHeadJudgement(HitResult result) => AddAssert($"head judged as {result}", () => judgementResults[0].Type == result); private void assertTailJudgement(HitResult result) => AddAssert($"tail judged as {result}", () => judgementResults[^2].Type == result); private void assertNoteJudgement(HitResult result) => AddAssert($"hold note judged as {result}", () => judgementResults[^1].Type == result); private void assertTickJudgement(HitResult result) => AddAssert($"tick judged as {result}", () => judgementResults[6].Type == result); // arbitrary tick private ScoreAccessibleReplayPlayer currentPlayer; private void performTest(List<ReplayFrame> frames) { AddStep("load player", () => { Beatmap.Value = CreateWorkingBeatmap(new Beatmap<ManiaHitObject> { HitObjects = { new HoldNote { StartTime = time_head, Duration = time_tail - time_head, Column = 0, } }, BeatmapInfo = { BaseDifficulty = new BeatmapDifficulty { SliderTickRate = 4 }, Ruleset = new ManiaRuleset().RulesetInfo }, }); Beatmap.Value.Beatmap.ControlPointInfo.Add(0, new DifficultyControlPoint { SpeedMultiplier = 0.1f }); var p = new ScoreAccessibleReplayPlayer(new Score { Replay = new Replay { Frames = frames } }); p.OnLoadComplete += _ => { p.ScoreProcessor.NewJudgement += result => { if (currentPlayer == p) judgementResults.Add(result); }; p.ScoreProcessor.AllJudged += () => { if (currentPlayer == p) allJudgedFired = true; }; }; LoadScreen(currentPlayer = p); allJudgedFired = false; judgementResults = new List<JudgementResult>(); }); AddUntilStep("Beatmap at 0", () => Beatmap.Value.Track.CurrentTime == 0); AddUntilStep("Wait until player is loaded", () => currentPlayer.IsCurrentScreen()); AddUntilStep("Wait for all judged", () => allJudgedFired); } private class ScoreAccessibleReplayPlayer : ReplayPlayer { public new ScoreProcessor ScoreProcessor => base.ScoreProcessor; protected override bool PauseOnFocusLost => false; public ScoreAccessibleReplayPlayer(Score score) : base(score, false, false) { } } } }
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.Data.SqlClient; using CrystalDecisions.Shared; namespace WebApplication2 { /// <summary> /// Summary description for frmEmergencyProcedures. /// </summary> public partial class frmOrgLocations : System.Web.UI.Page { private static string strURL = System.Configuration.ConfigurationSettings.AppSettings["local_url"]; private static string strDB = System.Configuration.ConfigurationSettings.AppSettings["local_db"]; protected System.Web.UI.WebControls.Label Label2; protected System.Web.UI.WebControls.Button btnAddTemp; public SqlConnection epsDbConn=new SqlConnection(strDB); protected void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here Load_Procedures(); } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.DataGrid1.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.processCommand); } #endregion private void Load_Procedures() { DataGrid1.Columns[5].Visible = false; if (Session["startForm"].ToString() == "frmMainBMgr") { lblOrg.Text=Session["MgrName"].ToString(); DataGrid1.Columns[3].Visible=false; } else { lblOrg.Text=Session["OrgName"].ToString(); } /*lblBd.Text="Budget: " + Session["BudName"].ToString() +" - " + Session["CurrName"].ToString();*/ if (!IsPostBack) { loadData(); } } private void loadData () { SqlCommand cmd=new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="wms_RetrieveOrgLocations"; cmd.Connection=this.epsDbConn; cmd.Parameters.Add ("@OrgId",SqlDbType.Int); if (Session["startForm"].ToString() == "frmMainBMgr") { cmd.Parameters["@OrgId"].Value=Session["MgrId"].ToString(); } else { cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString(); } DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter(cmd); da.Fill(ds,"Locs"); if (ds.Tables["Locs"].Rows.Count == 1) { if (Session["CallType"] == null) { Session["CallType"] = "Forward"; Session["OrgLocId"] = ds.Tables["Locs"].Rows[0][0]; Session["LocationName"] = ds.Tables["Locs"].Rows[0][1]; Session["ProfileId"] = ds.Tables["Locs"].Rows[0][2]; Session["LocationsId"] = ds.Tables["Locs"].Rows[0][3]; Session["COrgLocServices"] = "frmOrgLocations"; Response.Redirect(strURL + "frmOrgLocServices.aspx?"); } else { Session["CallType"] = null; Exit(); } } else if (ds.Tables["Locs"].Rows.Count > 1) { lblContents.Text="Click on the button titled '" + "Services' to identify services delivered from from a given location."; } else { lblContents.Text="Sorry, there are no budget details " + "available for this organization."; DataGrid1.Visible=false; } Session["ds"] = ds; DataGrid1.DataSource=ds; DataGrid1.DataBind(); } private void processCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e) { if (e.CommandName == "Services") { Session["COrgLocServices"]="frmOrgLocations"; Session["ProfileId"]=e.Item.Cells[4].Text; Session["LocationName"]=e.Item.Cells[1].Text; Session["OrgLocId"]=e.Item.Cells[0].Text; Session["LocationsId"] = e.Item.Cells[6].Text; Response.Redirect (strURL + "frmOrgLocServices.aspx?"); } else if (e.CommandName == "Mgrs") { Session["CMgr"]="frmOrgLocations"; Session["LocationName"]=e.Item.Cells[1].Text; Session["ProfileServices"]=e.Item.Cells[0].Text; Session["OrgLocId"]=e.Item.Cells[0].Text; Response.Redirect (strURL + "frmOrgLocMgrs.aspx?"); } else if (e.CommandName == "Clients") { /*Session["COrgLocServices"]="frmOrgLocations"; Session["LocId"]=e.Item.Cells[3].Text; Session["LocationName"]=e.Item.Cells[1].Text; Response.Redirect (strURL + "frmOrgLocServices.aspx?");*/ } else if (e.CommandName == "rptWP3") { ParameterFields paramFields = new ParameterFields(); ParameterField paramField1 = new ParameterField(); ParameterDiscreteValue discreteval1 = new ParameterDiscreteValue(); paramField1.ParameterFieldName = "OrgLocId"; discreteval1.Value = e.Item.Cells[0].Text; paramField1.CurrentValues.Add (discreteval1); paramFields.Add (paramField1); Session["ReportParameters"] = paramFields; Session["ReportName"] = "rptWP3.rpt"; rpts(); } else if (e.CommandName == "Remove") { SqlCommand cmd=new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; cmd.Connection=this.epsDbConn; cmd.CommandText="wms_DeleteOrgLocation"; cmd.Parameters.Add ("@Id", SqlDbType.Int); cmd.Parameters["@Id"].Value=e.Item.Cells[0].Text; cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); loadData(); } } private void rpts() { Session["cRG"]="frmPSEventsInd"; Response.Redirect (strURL + "frmReportGen.aspx?"); } protected void btnAdd_Click(object sender, System.EventArgs e) { redirectNow(); } private void redirectNow() { Session["CLocsAll"]="frmOrgLocations"; Response.Redirect (strURL + "frmLocsAll.aspx?"); } protected void btnExit_Click(object sender, System.EventArgs e) { Exit(); } private void Exit() { Response.Redirect(strURL + Session["COrgLocs"].ToString() + ".aspx?"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Runtime.InteropServices; namespace System.Management { //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// /// <summary> /// <para> Represents the set of properties of a WMI object.</para> /// </summary> /// <example> /// <code lang='C#'>using System; /// using System.Management; /// /// // This sample demonstrates how to enumerate properties /// // in a ManagementObject object. /// class Sample_PropertyDataCollection /// { /// public static int Main(string[] args) { /// ManagementObject disk = new ManagementObject("win32_logicaldisk.deviceid = \"c:\""); /// PropertyDataCollection diskProperties = disk.Properties; /// foreach (PropertyData diskProperty in diskProperties) { /// Console.WriteLine("Property = " + diskProperty.Name); /// } /// return 0; /// } /// } /// </code> /// <code lang='VB'>Imports System /// Imports System.Management /// /// ' This sample demonstrates how to enumerate properties /// ' in a ManagementObject object. /// Class Sample_PropertyDataCollection /// Overloads Public Shared Function Main(args() As String) As Integer /// Dim disk As New ManagementObject("win32_logicaldisk.deviceid=""c:""") /// Dim diskProperties As PropertyDataCollection = disk.Properties /// Dim diskProperty As PropertyData /// For Each diskProperty In diskProperties /// Console.WriteLine("Property = " &amp; diskProperty.Name) /// Next diskProperty /// Return 0 /// End Function /// End Class /// </code> /// </example> //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// public class PropertyDataCollection : ICollection, IEnumerable { private ManagementBaseObject parent; bool isSystem; internal PropertyDataCollection(ManagementBaseObject parent, bool isSystem) : base() { this.parent = parent; this.isSystem = isSystem; } // //ICollection // /// <summary> /// <para>Gets or sets the number of objects in the <see cref='System.Management.PropertyDataCollection'/>.</para> /// </summary> /// <value> /// <para>The number of objects in the collection.</para> /// </value> public int Count { get { string[] propertyNames = null; object qualVal = null; int flag; if (isSystem) flag = (int)tag_WBEM_CONDITION_FLAG_TYPE.WBEM_FLAG_SYSTEM_ONLY; else flag = (int)tag_WBEM_CONDITION_FLAG_TYPE.WBEM_FLAG_NONSYSTEM_ONLY; flag |= (int)tag_WBEM_CONDITION_FLAG_TYPE.WBEM_FLAG_ALWAYS; int status = parent.wbemObject.GetNames_(null, flag, ref qualVal, out propertyNames); if (status < 0) { if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } return propertyNames.Length; } } /// <summary> /// <para>Gets or sets a value indicating whether the object is synchronized.</para> /// </summary> /// <value> /// <para><see langword='true'/> if the object is synchronized; /// otherwise, <see langword='false'/>.</para> /// </value> public bool IsSynchronized { get { return false; } } /// <summary> /// <para>Gets or sets the object to be used for synchronization.</para> /// </summary> /// <value> /// <para>The object to be used for synchronization.</para> /// </value> public object SyncRoot { get { return this; } } /// <overload> /// <para>Copies the <see cref='System.Management.PropertyDataCollection'/> into an array.</para> /// </overload> /// <summary> /// <para>Copies the <see cref='System.Management.PropertyDataCollection'/> into an array.</para> /// </summary> /// <param name='array'>The array to which to copy the <see cref='System.Management.PropertyDataCollection'/>. </param> /// <param name='index'>The index from which to start copying. </param> public void CopyTo(Array array, Int32 index) { if (null == array) throw new ArgumentNullException("array"); if ((index < array.GetLowerBound(0)) || (index > array.GetUpperBound(0))) throw new ArgumentOutOfRangeException("index"); // Get the names of the properties string[] nameArray = null; object dummy = null; int flag = 0; if (isSystem) flag |= (int)tag_WBEM_CONDITION_FLAG_TYPE.WBEM_FLAG_SYSTEM_ONLY; else flag |= (int)tag_WBEM_CONDITION_FLAG_TYPE.WBEM_FLAG_NONSYSTEM_ONLY; flag |= (int)tag_WBEM_CONDITION_FLAG_TYPE.WBEM_FLAG_ALWAYS; int status = this.parent.wbemObject.GetNames_(null, flag, ref dummy, out nameArray); if (status >= 0) { if ((index + nameArray.Length) > array.Length) throw new ArgumentException(null,"index"); foreach (string propertyName in nameArray) array.SetValue(new PropertyData(parent, propertyName), index++); } if (status < 0) { if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } return; } /// <summary> /// <para>Copies the <see cref='System.Management.PropertyDataCollection'/> to a specialized <see cref='System.Management.PropertyData'/> object /// array.</para> /// </summary> /// <param name='propertyArray'>The destination array to contain the copied <see cref='System.Management.PropertyDataCollection'/>.</param> /// <param name=' index'>The index in the destination array from which to start copying.</param> public void CopyTo(PropertyData[] propertyArray, Int32 index) { CopyTo((Array)propertyArray, index); } // // IEnumerable // IEnumerator IEnumerable.GetEnumerator() { return (IEnumerator)(new PropertyDataEnumerator(parent, isSystem)); } /// <summary> /// <para>Returns the enumerator for this <see cref='System.Management.PropertyDataCollection'/>.</para> /// </summary> /// <returns> /// <para>An <see cref='System.Collections.IEnumerator'/> /// that can be used to iterate through the collection.</para> /// </returns> public PropertyDataEnumerator GetEnumerator() { return new PropertyDataEnumerator(parent, isSystem); } //Enumerator class /// <summary> /// <para>Represents the enumerator for <see cref='System.Management.PropertyData'/> /// objects in the <see cref='System.Management.PropertyDataCollection'/>.</para> /// </summary> /// <example> /// <code lang='C#'>using System; /// using System.Management; /// /// // This sample demonstrates how to enumerate all properties in a /// // ManagementObject using the PropertyDataEnumerator object. /// class Sample_PropertyDataEnumerator /// { /// public static int Main(string[] args) { /// ManagementObject disk = new ManagementObject("Win32_LogicalDisk.DeviceID='C:'"); /// PropertyDataCollection.PropertyDataEnumerator propertyEnumerator = disk.Properties.GetEnumerator(); /// while(propertyEnumerator.MoveNext()) { /// PropertyData p = (PropertyData)propertyEnumerator.Current; /// Console.WriteLine("Property found: " + p.Name); /// } /// return 0; /// } /// } /// </code> /// <code lang='VB'>Imports System /// Imports System.Management /// /// ' This sample demonstrates how to enumerate all properties in a /// ' ManagementObject using PropertyDataEnumerator object. /// Class Sample_PropertyDataEnumerator /// Overloads Public Shared Function Main(args() As String) As Integer /// Dim disk As New ManagementObject("Win32_LogicalDisk.DeviceID='C:'") /// Dim propertyEnumerator As _ /// PropertyDataCollection.PropertyDataEnumerator = disk.Properties.GetEnumerator() /// While propertyEnumerator.MoveNext() /// Dim p As PropertyData = _ /// CType(propertyEnumerator.Current, PropertyData) /// Console.WriteLine("Property found: " &amp; p.Name) /// End While /// Return 0 /// End Function /// End Class /// </code> /// </example> public class PropertyDataEnumerator : IEnumerator { private ManagementBaseObject parent; private string[] propertyNames; private int index; internal PropertyDataEnumerator(ManagementBaseObject parent, bool isSystem) { this.parent = parent; propertyNames = null; index = -1; int flag; object qualVal = null; if (isSystem) flag = (int)tag_WBEM_CONDITION_FLAG_TYPE.WBEM_FLAG_SYSTEM_ONLY; else flag = (int)tag_WBEM_CONDITION_FLAG_TYPE.WBEM_FLAG_NONSYSTEM_ONLY; flag |= (int)tag_WBEM_CONDITION_FLAG_TYPE.WBEM_FLAG_ALWAYS; int status = parent.wbemObject.GetNames_(null, flag, ref qualVal, out propertyNames); if (status < 0) { if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } } /// <internalonly/> object IEnumerator.Current { get { return (object)this.Current; } } /// <summary> /// <para>Gets the current <see cref='System.Management.PropertyData'/> in the <see cref='System.Management.PropertyDataCollection'/> enumeration.</para> /// </summary> /// <value> /// The current <see cref='System.Management.PropertyData'/> /// element in the collection. /// </value> public PropertyData Current { get { if ((index == -1) || (index == propertyNames.Length)) throw new InvalidOperationException(); else return new PropertyData(parent, propertyNames[index]); } } /// <summary> /// <para> Moves to the next element in the <see cref='System.Management.PropertyDataCollection'/> /// enumeration.</para> /// </summary> /// <returns> /// <para><see langword='true'/> if the enumerator was successfully advanced to the next element; /// <see langword='false'/> if the enumerator has passed the end of the collection.</para> /// </returns> public bool MoveNext() { if (index == propertyNames.Length) //passed the end of the array return false; //don't advance the index any more index++; return (index == propertyNames.Length) ? false : true; } /// <summary> /// <para>Resets the enumerator to the beginning of the <see cref='System.Management.PropertyDataCollection'/> /// enumeration.</para> /// </summary> public void Reset() { index = -1; } }//PropertyDataEnumerator // // Methods // /// <summary> /// <para> Returns the specified property from the <see cref='System.Management.PropertyDataCollection'/>, using [] syntax.</para> /// </summary> /// <param name='propertyName'>The name of the property to retrieve.</param> /// <value> /// <para> A <see cref='System.Management.PropertyData'/>, based on /// the name specified.</para> /// </value> /// <example> /// <code lang='C#'>ManagementObject o = new ManagementObject("Win32_LogicalDisk.Name = 'C:'"); /// Console.WriteLine("Free space on C: drive is: ", c.Properties["FreeSpace"].Value); /// </code> /// <code lang='VB'>Dim o As New ManagementObject("Win32_LogicalDisk.Name=""C:""") /// Console.WriteLine("Free space on C: drive is: " &amp; c.Properties("FreeSpace").Value) /// </code> /// </example> public virtual PropertyData this[string propertyName] { get { if (null == propertyName) throw new ArgumentNullException("propertyName"); return new PropertyData(parent, propertyName); } } /// <summary> /// <para>Removes a <see cref='System.Management.PropertyData'/> from the <see cref='System.Management.PropertyDataCollection'/>.</para> /// </summary> /// <param name='propertyName'>The name of the property to be removed.</param> /// <remarks> /// <para> Properties can only be removed from class definitions, /// not from instances. This method is only valid when invoked on a property /// collection in a <see cref='System.Management.ManagementClass'/>.</para> /// </remarks> /// <example> /// <code lang='C#'>ManagementClass c = new ManagementClass("MyClass"); /// c.Properties.Remove("PropThatIDontWantOnThisClass"); /// </code> /// <code lang='VB'>Dim c As New ManagementClass("MyClass") /// c.Properties.Remove("PropThatIDontWantOnThisClass") /// </code> /// </example> public virtual void Remove(string propertyName) { // On instances, reset the property to the default value for the class. if (parent.GetType() == typeof(ManagementObject)) { ManagementClass cls = new ManagementClass(parent.ClassPath); parent.SetPropertyValue(propertyName, cls.GetPropertyValue(propertyName)); } else { int status = parent.wbemObject.Delete_(propertyName); if (status < 0) { if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } } } /// <overload> /// <para>Adds a new <see cref='System.Management.PropertyData'/> with the specified value.</para> /// </overload> /// <summary> /// <para>Adds a new <see cref='System.Management.PropertyData'/> with the specified value. The value cannot /// be null and must be convertable to a CIM type.</para> /// </summary> /// <param name='propertyName'>The name of the new property.</param> /// <param name='propertyValue'>The value of the property (cannot be null).</param> /// <remarks> /// <para> Properties can only be added to class definitions, not /// to instances. This method is only valid when invoked on a <see cref='System.Management.PropertyDataCollection'/> /// in /// a <see cref='System.Management.ManagementClass'/>.</para> /// </remarks> public virtual void Add(string propertyName, Object propertyValue) { if (null == propertyValue) throw new ArgumentNullException("propertyValue"); if (parent.GetType() == typeof(ManagementObject)) //can't add properties to instance throw new InvalidOperationException(); CimType cimType = 0; bool isArray = false; object wmiValue = PropertyData.MapValueToWmiValue(propertyValue, out isArray, out cimType); int wmiCimType = (int)cimType; if (isArray) wmiCimType |= (int)tag_CIMTYPE_ENUMERATION.CIM_FLAG_ARRAY; int status = parent.wbemObject.Put_(propertyName, 0, ref wmiValue, wmiCimType); if (status < 0) { if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } } /// <summary> /// <para>Adds a new <see cref='System.Management.PropertyData'/> with the specified value and CIM type.</para> /// </summary> /// <param name='propertyName'>The name of the property.</param> /// <param name='propertyValue'>The value of the property (which can be null).</param> /// <param name='propertyType'>The CIM type of the property.</param> /// <remarks> /// <para> Properties can only be added to class definitions, not /// to instances. This method is only valid when invoked on a <see cref='System.Management.PropertyDataCollection'/> /// in /// a <see cref='System.Management.ManagementClass'/>.</para> /// </remarks> public void Add(string propertyName, Object propertyValue, CimType propertyType) { if (null == propertyName) throw new ArgumentNullException("propertyName"); if (parent.GetType() == typeof(ManagementObject)) //can't add properties to instance throw new InvalidOperationException(); int wmiCimType = (int)propertyType; bool isArray = false; if ((null != propertyValue) && propertyValue.GetType().IsArray) { isArray = true; wmiCimType = (wmiCimType | (int)tag_CIMTYPE_ENUMERATION.CIM_FLAG_ARRAY); } object wmiValue = PropertyData.MapValueToWmiValue(propertyValue, propertyType, isArray); int status = parent.wbemObject.Put_(propertyName, 0, ref wmiValue, wmiCimType); if (status < 0) { if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } } /// <summary> /// <para>Adds a new <see cref='System.Management.PropertyData'/> with no assigned value.</para> /// </summary> /// <param name='propertyName'>The name of the property.</param> /// <param name='propertyType'>The CIM type of the property.</param> /// <param name='isArray'><see langword='true'/> to specify that the property is an array type; otherwise, <see langword='false'/>.</param> /// <remarks> /// <para> Properties can only be added to class definitions, not /// to instances. This method is only valid when invoked on a <see cref='System.Management.PropertyDataCollection'/> /// in /// a <see cref='System.Management.ManagementClass'/>.</para> /// </remarks> public void Add(string propertyName, CimType propertyType, bool isArray) { if (null == propertyName) throw new ArgumentNullException(propertyName); if (parent.GetType() == typeof(ManagementObject)) //can't add properties to instance throw new InvalidOperationException(); int wmiCimType = (int)propertyType; if (isArray) wmiCimType = (wmiCimType | (int)tag_CIMTYPE_ENUMERATION.CIM_FLAG_ARRAY); object dummyObj = System.DBNull.Value; int status = parent.wbemObject.Put_(propertyName, 0, ref dummyObj, wmiCimType); if (status < 0) { if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } } }//PropertyDataCollection }
//------------------------------------------------------------------------------ // <copyright file="Component.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.ComponentModel { using System; ////using System.ComponentModel.Design; ////using System.ComponentModel.Design.Serialization; using System.Runtime.InteropServices; using System.Security.Permissions; /// <devdoc> /// <para>Provides the default implementation for the /// <see cref='System.ComponentModel.IComponent'/> /// interface and enables object-sharing between applications.</para> /// </devdoc> ////[ComVisible( true )] ////[ClassInterface( ClassInterfaceType.AutoDispatch )] ////[DesignerCategory( "Component" )] public class Component : MarshalByRefObject, IComponent { /// <devdoc> /// <para>Static hask key for the Disposed event. This field is read-only.</para> /// </devdoc> private static readonly object EventDisposed = new object(); private ISite site; private EventHandlerList events; ~Component() { Dispose( false ); } /// <devdoc> /// This property returns true if the component is in a mode that supports /// raising events. By default, components always support raising their events /// and therefore this method always returns true. You can override this method /// in a deriving class and change it to return false when needed. if the return /// value of this method is false, the EventList collection returned by the Events /// property will always return null for an event. Events can still be added and /// removed from the collection, but retrieving them through the collection's Item /// property will always return null. /// </devdoc> protected virtual bool CanRaiseEvents { get { return true; } } /// <devdoc> /// Internal API that allows the event handler list class to access the /// CanRaiseEvents property. /// </devdoc> internal bool CanRaiseEventsInternal { get { return CanRaiseEvents; } } /// <devdoc> /// <para>Adds a event handler to listen to the Disposed event on the component.</para> /// </devdoc> //// [Browsable( false )] [EditorBrowsable( EditorBrowsableState.Advanced )] public event EventHandler Disposed { add { Events.AddHandler( EventDisposed, value ); } remove { Events.RemoveHandler( EventDisposed, value ); } } /// <devdoc> /// <para>Gets the list of event handlers that are attached to this component.</para> /// </devdoc> protected EventHandlerList Events { get { if(events == null) { events = new EventHandlerList( this ); } return events; } } /// <devdoc> /// <para> /// Gets or sets the site of the <see cref='System.ComponentModel.Component'/> /// . /// </para> /// </devdoc> //// [Browsable( false )] //// [DesignerSerializationVisibility( DesignerSerializationVisibility.Hidden )] public virtual ISite Site { get { return site; } set { site = value; } } /// <devdoc> /// <para> /// Disposes of the <see cref='System.ComponentModel.Component'/> /// . /// </para> /// </devdoc> [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed" )] public void Dispose() { Dispose( true ); GC.SuppressFinalize( this ); } /// <devdoc> /// <para> /// Disposes all the resources associated with this component. /// If disposing is false then you must never touch any other /// managed objects, as they may already be finalized. When /// in this state you should dispose any native resources /// that you have a reference to. /// </para> /// <para> /// When disposing is true then you should dispose all data /// and objects you have references to. The normal implementation /// of this method would look something like: /// </para> /// <code> /// public void Dispose() { /// Dispose(true); /// GC.SuppressFinalize(this); /// } /// /// protected virtual void Dispose(bool disposing) { /// if (disposing) { /// if (myobject != null) { /// myobject.Dispose(); /// myobject = null; /// } /// } /// if (myhandle != IntPtr.Zero) { /// NativeMethods.Release(myhandle); /// myhandle = IntPtr.Zero; /// } /// } /// /// ~MyClass() { /// Dispose(false); /// } /// </code> /// <para> /// For base classes, you should never override the Finalier (~Class in C#) /// or the Dispose method that takes no arguments, rather you should /// always override the Dispose method that takes a bool. /// </para> /// <code> /// protected override void Dispose(bool disposing) { /// if (disposing) { /// if (myobject != null) { /// myobject.Dispose(); /// myobject = null; /// } /// } /// if (myhandle != IntPtr.Zero) { /// NativeMethods.Release(myhandle); /// myhandle = IntPtr.Zero; /// } /// base.Dispose(disposing); /// } /// </code> /// </devdoc> protected virtual void Dispose( bool disposing ) { if(disposing) { lock(this) { if(site != null && site.Container != null) { site.Container.Remove( this ); } if(events != null) { EventHandler handler = (EventHandler)events[EventDisposed]; if(handler != null) handler( this, EventArgs.Empty ); } } } } // Returns the component's container. // /// <devdoc> /// <para> /// Returns the <see cref='System.ComponentModel.IContainer'/> /// that contains the <see cref='System.ComponentModel.Component'/> /// . /// </para> /// </devdoc> //// [Browsable( false )] //// [DesignerSerializationVisibility( DesignerSerializationVisibility.Hidden )] public IContainer Container { get { ISite s = site; return s == null ? null : s.Container; } } /// <devdoc> /// <para> /// Returns an object representing a service provided by /// the <see cref='System.ComponentModel.Component'/> /// . /// </para> /// </devdoc> protected virtual object GetService( Type service ) { ISite s = site; return ((s == null) ? null : s.GetService( service )); } /// <devdoc> /// <para> /// Gets a value indicating whether the <see cref='System.ComponentModel.Component'/> /// is currently in design mode. /// </para> /// </devdoc> //// [Browsable( false )] //// [DesignerSerializationVisibility( DesignerSerializationVisibility.Hidden )] protected bool DesignMode { get { ISite s = site; return (s == null) ? false : s.DesignMode; } } /// <internalonly/> /// <devdoc> /// <para> /// Returns a <see cref='System.String'/> containing the name of the <see cref='System.ComponentModel.Component'/> , if any. This method should not be /// overridden. For /// internal use only. /// </para> /// </devdoc> public override String ToString() { ISite s = site; if(s != null) return s.Name + " [" + GetType().FullName + "]"; else return GetType().FullName; } } }
using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using PWLib.FileSyncLib; namespace AutoUSBBackup.GUI { public class MainFormEventController { Control mInvokeControl; ToolStripProgressBar mProgressBar; NotifyIcon mNotifyIcon; public event EventHandler SpineInitialised; public event VolumeBackupHandler BackupStarted; public event VolumeBackupHandler BackupFinished; public event VolumeRestoreHandler RestoreStarted; public event VolumeRestoreHandler RestoreFinished; public event EventHandler FormatUsbFinished; public event VolumeDescriptorChangedHandler VolumeNeedsRefreshing; public MainFormEventController( Control invokeControl, ToolStripProgressBar progressBar, NotifyIcon notifyIcon ) { mInvokeControl = invokeControl; mProgressBar = progressBar; mNotifyIcon = notifyIcon; } public void HookSpineEvents( VolumeEventController eventController ) { eventController.VolumeDescriptorActiveStateChanged += new VolumeDescriptorChangedHandler( eventController_VolumeDescriptorActiveStateChanged ); eventController.VolumeSourceActiveStateChanged += new VolumeSourceActiveChangedHandler( eventController_VolumeSourceActiveStateChanged ); eventController.BackupStarted += new VolumeBackupHandler( Spine_BackupStarted ); eventController.BackupFinished += new VolumeBackupHandler( Spine_BackupFinished ); eventController.BackupProgress += new VolumeBackupProgressHandler( Spine_BackupFileFinished ); eventController.RestoreStarted += new VolumeRestoreHandler( spine_RestoreInitStarted ); eventController.RestoreFinished += new VolumeRestoreHandler( Spine_RestoreFinished ); eventController.RestoreProgress += new VolumeRestoreProgressHandler( spine_RestoreFileFinished ); eventController.ApplicationInitialised += new EventHandler( Spine_SpineInitialised ); eventController.FormatUsbFinished += new EventHandler( Spine_FormatUsbFinished ); MainForm.Instance.SetDefaultStatusText(); } void eventController_VolumeSourceActiveStateChanged( Volume volume, bool isActive ) { mInvokeControl.Invoke( new VolumeDescriptorChangedHandler( eventController_VolumeDescriptorActiveStateChanged_WinThread ), volume.Descriptor, isActive ); } void eventController_VolumeDescriptorActiveStateChanged( VolumeDescriptor volume, bool isActive ) { mInvokeControl.Invoke( new VolumeDescriptorChangedHandler( eventController_VolumeDescriptorActiveStateChanged_WinThread ), volume, isActive ); } void eventController_VolumeDescriptorActiveStateChanged_WinThread( VolumeDescriptor volume, bool isActive ) { if ( VolumeNeedsRefreshing != null ) VolumeNeedsRefreshing( volume, isActive ); } void ShowBalloonTip( string text ) { if ( MainForm.Instance.WindowState == FormWindowState.Minimized ) { mNotifyIcon.BalloonTipText = text; mNotifyIcon.BalloonTipTitle = "AutoBackup"; mNotifyIcon.ShowBalloonTip( 5000 ); } } #region Spine events #region Restore events void spine_RestoreFileFinished( Volume volume, VolumeSnapshot snapshot, ulong fileNum, ulong fileCount, ulong bytesTranferred, ulong totalBytes ) { mInvokeControl.Invoke( new VolumeBackupProgressHandler( spine_RestoreFileFinishedWinThread ), volume, snapshot, fileNum, fileCount, bytesTranferred, totalBytes ); } void spine_RestoreFileFinishedWinThread( Volume volume, VolumeSnapshot snapshot, ulong fileNum, ulong fileCount, ulong bytesTranferred, ulong totalBytes ) { while ( totalBytes > int.MaxValue ) { totalBytes /= 10; bytesTranferred /= 10; } mProgressBar.Maximum = ( int )totalBytes + 1; mProgressBar.Value = ( int )bytesTranferred; int percentComplete = (int)(((float)bytesTranferred / (float)(totalBytes + 1)) * 100.0f ); MainForm.Instance.SetTitleText( "Restoring", percentComplete ); Log.WriteLine( LogType.DebugLog | LogType.TextLog, "File: " + fileNum.ToString() + "/" + fileCount.ToString() + " Progress: " + bytesTranferred.ToString() + "/" + totalBytes.ToString() ); } void spine_RestoreInitStarted( Volume volume, VolumeSnapshot snapshot ) { mInvokeControl.Invoke( new VolumeRestoreHandler( spine_RestoreInitStartedWinThread ), volume, snapshot ); } void spine_RestoreInitStartedWinThread( Volume volume, VolumeSnapshot snapshot ) { // ShowBalloonTip( "Restore of " + volume.Descriptor.Identifier.Name + " started" ); MainForm.Instance.SetStatusText("Restoring..."); MainForm.Instance.SetTitleText( "Restoring", 0 ); if ( RestoreStarted != null ) RestoreStarted( volume, snapshot ); } void Spine_RestoreFinished( Volume volume, VolumeSnapshot snapshot ) { mInvokeControl.Invoke( new VolumeRestoreHandler( Spine_RestoreFinishedWinThread ), volume, snapshot ); } void Spine_RestoreFinishedWinThread( Volume volume, VolumeSnapshot snapshot ) { ShowBalloonTip( "Restore of " + volume.Descriptor.VolumeName + " finished" ); mProgressBar.Value = 0; MainForm.Instance.SetDefaultStatusText(); MainForm.Instance.SetTitleText( "", 0 ); Log.WriteLine( LogType.AppLog | LogType.TextLog | LogType.DebugLog, "Restoration of '" + volume.Descriptor.VolumeName + "' complete" ); if (RestoreFinished != null) RestoreFinished( volume, snapshot ); } #endregion #region Backup events void Spine_BackupFileFinished( Volume volume, VolumeSnapshot snapshot, ulong fileNum, ulong fileCount, ulong bytesTranferred, ulong totalBytes ) { mInvokeControl.Invoke( new VolumeBackupProgressHandler( Spine_BackupFileFinishedWinThread ), volume, snapshot, fileNum, fileCount, bytesTranferred, totalBytes ); } void Spine_BackupFileFinishedWinThread( Volume volume, VolumeSnapshot snapshot, ulong fileNum, ulong fileCount, ulong bytesTranferred, ulong totalBytes ) { try { while ( totalBytes >= int.MaxValue ) { totalBytes /= 10; bytesTranferred /= 10; } mProgressBar.Maximum = ( int )totalBytes + 1; mProgressBar.Value = ( int )bytesTranferred; int percentComplete = (int)(((float)bytesTranferred / (float)(totalBytes + 1)) * 100.0f); MainForm.Instance.SetTitleText( "Backing up", percentComplete ); } catch ( System.Exception ) { throw; } } void Spine_BackupFinished( Volume volume, VolumeSnapshot snapshot, bool snapshotHasBeenSaved, bool firstBackupOnLoad ) { mInvokeControl.Invoke( new VolumeBackupHandler( Spine_BackupFinishedWinThread ), volume, snapshot, snapshotHasBeenSaved, firstBackupOnLoad ); } void Spine_BackupStarted( Volume volume, VolumeSnapshot snapshot, bool snapshotHasBeenSaved, bool firstBackupOnLoad ) { mInvokeControl.Invoke( new VolumeBackupHandler( Spine_BackupStartedWinThread ), volume, snapshot, snapshotHasBeenSaved, firstBackupOnLoad ); } void Spine_BackupFinishedWinThread( Volume volume, VolumeSnapshot snapshot, bool snapshotHasBeenSaved, bool firstBackupOnLoad ) { if ( !firstBackupOnLoad && snapshotHasBeenSaved ) ShowBalloonTip( "Backup of " + volume.Descriptor.VolumeName + " finished" ); MainForm.Instance.SetDefaultStatusText(); mProgressBar.Value = 0; MainForm.Instance.SetTitleText( "", 0 ); if ( snapshotHasBeenSaved ) Log.WriteLine( LogType.AppLog | LogType.TextLog | LogType.DebugLog, "Backup of '" + volume.Descriptor.VolumeName + "' complete" ); if ( BackupFinished != null ) BackupFinished( volume, snapshot, snapshotHasBeenSaved, firstBackupOnLoad ); } void Spine_BackupStartedWinThread( Volume volume, VolumeSnapshot snapshot, bool snapshotHasBeenSaved, bool firstBackupOnLoad ) { MainForm.Instance.SetStatusText( "Backing up..." ); if ( BackupStarted != null ) BackupStarted( volume, snapshot, snapshotHasBeenSaved, firstBackupOnLoad ); mProgressBar.Value = 0; MainForm.Instance.SetTitleText( "Backing up", 0 ); // if ( !firstBackupOnLoad ) // ShowBalloonTip( "Backup of " + volume.Descriptor.Identifier.Name + " started" ); } #endregion #region Format USB events void Spine_FormatUsbFinished( object sender, EventArgs e ) { mInvokeControl.Invoke( new EventHandler( Spine_FormatUsbFinishedWinThread ), sender, e ); } void Spine_FormatUsbFinishedWinThread( object sender, EventArgs e ) { MainForm.Instance.SetDefaultStatusText(); if ( FormatUsbFinished != null ) FormatUsbFinished( sender, e ); } #endregion #region Spine events void Spine_SpineInitialised( object sender, EventArgs e ) { mInvokeControl.Invoke( new EventHandler( Spine_SpineInitialisedWinThread ), sender, e ); } void Spine_SpineInitialisedWinThread( object sender, EventArgs e ) { MainForm.Instance.SetDefaultStatusText(); if ( SpineInitialised != null ) SpineInitialised( sender, e ); } #endregion #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Localization; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.Localization; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using OrchardCore.Admin; using OrchardCore.DisplayManagement; using OrchardCore.DisplayManagement.ModelBinding; using OrchardCore.DisplayManagement.Notify; using OrchardCore.Navigation; using OrchardCore.Routing; using OrchardCore.Settings; using OrchardCore.Workflows.Helpers; using OrchardCore.Workflows.Indexes; using OrchardCore.Workflows.Models; using OrchardCore.Workflows.Services; using OrchardCore.Workflows.ViewModels; using YesSql; using YesSql.Services; namespace OrchardCore.Workflows.Controllers { [Admin] public class WorkflowController : Controller { private readonly ISiteService _siteService; private readonly ISession _session; private readonly IWorkflowManager _workflowManager; private readonly IWorkflowTypeStore _workflowTypeStore; private readonly IWorkflowStore _workflowStore; private readonly IAuthorizationService _authorizationService; private readonly IActivityDisplayManager _activityDisplayManager; private readonly INotifier _notifier; private readonly IUpdateModelAccessor _updateModelAccessor; private readonly IHtmlLocalizer H; private readonly IStringLocalizer S; public WorkflowController( ISiteService siteService, ISession session, IWorkflowManager workflowManager, IWorkflowTypeStore workflowTypeStore, IWorkflowStore workflowStore, IAuthorizationService authorizationService, IActivityDisplayManager activityDisplayManager, IShapeFactory shapeFactory, INotifier notifier, IHtmlLocalizer<WorkflowController> htmlLocalizer, IStringLocalizer<WorkflowController> stringLocalizer, IUpdateModelAccessor updateModelAccessor) { _siteService = siteService; _session = session; _workflowManager = workflowManager; _workflowTypeStore = workflowTypeStore; _workflowStore = workflowStore; _authorizationService = authorizationService; _activityDisplayManager = activityDisplayManager; _notifier = notifier; _updateModelAccessor = updateModelAccessor; New = shapeFactory; H = htmlLocalizer; S = stringLocalizer; } private dynamic New { get; } public async Task<IActionResult> Index(int workflowTypeId, WorkflowIndexViewModel model, PagerParameters pagerParameters, string returnUrl = null) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageWorkflows)) { return Forbid(); } if (!Url.IsLocalUrl(returnUrl)) { returnUrl = Url.Action(nameof(Index), "WorkflowType"); } var workflowType = await _workflowTypeStore.GetAsync(workflowTypeId); var siteSettings = await _siteService.GetSiteSettingsAsync(); var query = _session.Query<Workflow, WorkflowIndex>(); query = query.Where(x => x.WorkflowTypeId == workflowType.WorkflowTypeId); switch (model.Options.Filter) { case WorkflowFilter.Finished: query = query.Where(x => x.WorkflowStatus == WorkflowStatus.Finished); break; case WorkflowFilter.Faulted: query = query.Where(x => x.WorkflowStatus == WorkflowStatus.Faulted); break; case WorkflowFilter.All: default: break; } switch (model.Options.OrderBy) { case WorkflowOrder.CreatedDesc: query = query.OrderByDescending(x => x.CreatedUtc); break; case WorkflowOrder.Created: query = query.OrderBy(x => x.CreatedUtc); break; default: query = query.OrderByDescending(x => x.CreatedUtc); break; } var pager = new Pager(pagerParameters, siteSettings.PageSize); var routeData = new RouteData(); routeData.Values.Add("Filter", model.Options.Filter); var pagerShape = (await New.Pager(pager)).TotalItemCount(await query.CountAsync()).RouteData(routeData); var pageOfItems = await query.Skip(pager.GetStartIndex()).Take(pager.PageSize).ListAsync(); var viewModel = new WorkflowIndexViewModel { WorkflowType = workflowType, Workflows = pageOfItems.Select(x => new WorkflowEntry { Workflow = x, Id = x.Id }).ToList(), Options = model.Options, Pager = pagerShape, ReturnUrl = returnUrl }; model.Options.WorkflowsSorts = new List<SelectListItem>() { new SelectListItem() { Text = S["Recently created"], Value = nameof(WorkflowOrder.CreatedDesc) }, new SelectListItem() { Text = S["Least recently created"], Value = nameof(WorkflowOrder.Created) } }; model.Options.WorkflowsStatuses = new List<SelectListItem>() { new SelectListItem() { Text = S["All"], Value = nameof(WorkflowFilter.All) }, new SelectListItem() { Text = S["Faulted"], Value = nameof(WorkflowFilter.Faulted) }, new SelectListItem() { Text = S["Finished"], Value = nameof(WorkflowFilter.Finished) } }; viewModel.Options.WorkflowsBulkAction = new List<SelectListItem>() { new SelectListItem() { Text = S["Delete"], Value = nameof(WorkflowBulkAction.Delete) } }; return View(viewModel); } [HttpPost, ActionName("Index")] [FormValueRequired("submit.Filter")] public ActionResult IndexFilterPOST(WorkflowIndexViewModel model) { return RedirectToAction("Index", new RouteValueDictionary { { "Options.Filter", model.Options.Filter }, { "Options.OrderBy", model.Options.OrderBy } }); } public async Task<IActionResult> Details(int id) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageWorkflows)) { return Forbid(); } var workflow = await _workflowStore.GetAsync(id); if (workflow == null) { return NotFound(); } var workflowType = await _workflowTypeStore.GetAsync(workflow.WorkflowTypeId); var blockingActivities = workflow.BlockingActivities.ToDictionary(x => x.ActivityId); var workflowContext = await _workflowManager.CreateWorkflowExecutionContextAsync(workflowType, workflow); var activityContexts = await Task.WhenAll(workflowType.Activities.Select(async x => await _workflowManager.CreateActivityExecutionContextAsync(x, x.Properties))); var activityDesignShapes = new List<dynamic>(); foreach (var activityContext in activityContexts) { activityDesignShapes.Add(await BuildActivityDisplayAsync(activityContext, workflowType.Id, blockingActivities.ContainsKey(activityContext.ActivityRecord.ActivityId), "Design")); } var activitiesDataQuery = activityContexts.Select(x => new { Id = x.ActivityRecord.ActivityId, X = x.ActivityRecord.X, Y = x.ActivityRecord.Y, Name = x.ActivityRecord.Name, IsStart = x.ActivityRecord.IsStart, IsEvent = x.Activity.IsEvent(), IsBlocking = workflow.BlockingActivities.Any(a => a.ActivityId == x.ActivityRecord.ActivityId), Outcomes = x.Activity.GetPossibleOutcomes(workflowContext, x).ToArray() }); var workflowTypeData = new { Id = workflowType.Id, Name = workflowType.Name, IsEnabled = workflowType.IsEnabled, Activities = activitiesDataQuery.ToArray(), Transitions = workflowType.Transitions }; var jsonSerializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }; var viewModel = new WorkflowViewModel { Workflow = workflow, WorkflowType = workflowType, WorkflowTypeJson = JsonConvert.SerializeObject(workflowTypeData, Formatting.None, jsonSerializerSettings), WorkflowJson = JsonConvert.SerializeObject(workflow, Formatting.Indented, jsonSerializerSettings), ActivityDesignShapes = activityDesignShapes }; return View(viewModel); } [HttpPost] public async Task<IActionResult> Delete(int id) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageWorkflows)) { return Forbid(); } var workflow = await _workflowStore.GetAsync(id); if (workflow == null) { return NotFound(); } var workflowType = await _workflowTypeStore.GetAsync(workflow.WorkflowTypeId); await _workflowStore.DeleteAsync(workflow); _notifier.Success(H["Workflow {0} has been deleted.", id]); return RedirectToAction("Index", new { workflowTypeId = workflowType.Id }); } [HttpPost] [ActionName(nameof(Index))] [FormValueRequired("submit.BulkAction")] public async Task<IActionResult> BulkEdit(int workflowTypeId, WorkflowIndexOptions options, PagerParameters pagerParameters, IEnumerable<int> itemIds) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageWorkflows)) { return Forbid(); } if (itemIds?.Count() > 0) { var checkedEntries = await _session.Query<Workflow, WorkflowIndex>().Where(x => x.DocumentId.IsIn(itemIds)).ListAsync(); switch (options.BulkAction) { case WorkflowBulkAction.None: break; case WorkflowBulkAction.Delete: foreach (var entry in checkedEntries) { var workflow = await _workflowStore.GetAsync(entry.Id); if (workflow != null) { await _workflowStore.DeleteAsync(workflow); _notifier.Success(H["Workflow {0} has been deleted.", workflow.Id]); } } break; default: throw new ArgumentOutOfRangeException(); } } return RedirectToAction("Index", new { workflowTypeId, page = pagerParameters.Page, pageSize = pagerParameters.PageSize }); } private async Task<dynamic> BuildActivityDisplayAsync(ActivityContext activityContext, int workflowTypeId, bool isBlocking, string displayType) { dynamic activityShape = await _activityDisplayManager.BuildDisplayAsync(activityContext.Activity, _updateModelAccessor.ModelUpdater, displayType); activityShape.Metadata.Type = $"Activity_{displayType}ReadOnly"; activityShape.Activity = activityContext.Activity; activityShape.ActivityRecord = activityContext.ActivityRecord; activityShape.WorkflowTypeId = workflowTypeId; activityShape.IsBlocking = isBlocking; return activityShape; } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Globalization; using System.Linq; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Audio.Sample; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.Textures; using osu.Game.Audio; using osu.Game.Graphics; using osu.Game.Graphics.Sprites; using osu.Game.Skinning; using osuTK; using osuTK.Graphics; namespace osu.Game.Tests.Visual.Gameplay { public class TestSceneSkinnableDrawable : OsuTestScene { [Test] public void TestConfineScaleDown() { FillFlowContainer<ExposedSkinnableDrawable> fill = null; AddStep("setup layout larger source", () => { Child = new SkinProvidingContainer(new SizedSource(50)) { RelativeSizeAxes = Axes.Both, Child = fill = new FillFlowContainer<ExposedSkinnableDrawable> { Size = new Vector2(30), Anchor = Anchor.Centre, Origin = Anchor.Centre, Spacing = new Vector2(10), Children = new[] { new ExposedSkinnableDrawable("default", _ => new DefaultBox(), _ => true), new ExposedSkinnableDrawable("available", _ => new DefaultBox(), _ => true), new ExposedSkinnableDrawable("available", _ => new DefaultBox(), _ => true, ConfineMode.NoScaling) } }, }; }); AddAssert("check sizes", () => fill.Children.Select(c => c.Drawable.DrawWidth).SequenceEqual(new float[] { 30, 30, 50 })); AddStep("adjust scale", () => fill.Scale = new Vector2(2)); AddAssert("check sizes unchanged by scale", () => fill.Children.Select(c => c.Drawable.DrawWidth).SequenceEqual(new float[] { 30, 30, 50 })); } [Test] public void TestConfineScaleUp() { FillFlowContainer<ExposedSkinnableDrawable> fill = null; AddStep("setup layout larger source", () => { Child = new SkinProvidingContainer(new SizedSource(30)) { RelativeSizeAxes = Axes.Both, Child = fill = new FillFlowContainer<ExposedSkinnableDrawable> { Size = new Vector2(50), Anchor = Anchor.Centre, Origin = Anchor.Centre, Spacing = new Vector2(10), Children = new[] { new ExposedSkinnableDrawable("default", _ => new DefaultBox(), _ => true), new ExposedSkinnableDrawable("available", _ => new DefaultBox(), _ => true, ConfineMode.ScaleToFit), new ExposedSkinnableDrawable("available", _ => new DefaultBox(), _ => true, ConfineMode.NoScaling) } }, }; }); AddAssert("check sizes", () => fill.Children.Select(c => c.Drawable.DrawWidth).SequenceEqual(new float[] { 50, 50, 30 })); AddStep("adjust scale", () => fill.Scale = new Vector2(2)); AddAssert("check sizes unchanged by scale", () => fill.Children.Select(c => c.Drawable.DrawWidth).SequenceEqual(new float[] { 50, 50, 30 })); } [Test] public void TestInitialLoad() { var secondarySource = new SecondarySource(); SkinConsumer consumer = null; AddStep("setup layout", () => { Child = new SkinSourceContainer { RelativeSizeAxes = Axes.Both, Child = new SkinProvidingContainer(secondarySource) { RelativeSizeAxes = Axes.Both, Child = consumer = new SkinConsumer("test", name => new NamedBox("Default Implementation"), source => true) } }; }); AddAssert("consumer using override source", () => consumer.Drawable is SecondarySourceBox); AddAssert("skinchanged only called once", () => consumer.SkinChangedCount == 1); } [Test] public void TestOverride() { var secondarySource = new SecondarySource(); SkinConsumer consumer = null; Container target = null; AddStep("setup layout", () => { Child = new SkinSourceContainer { RelativeSizeAxes = Axes.Both, Child = target = new SkinProvidingContainer(secondarySource) { RelativeSizeAxes = Axes.Both, } }; }); AddStep("add permissive", () => target.Add(consumer = new SkinConsumer("test", name => new NamedBox("Default Implementation"), source => true))); AddAssert("consumer using override source", () => consumer.Drawable is SecondarySourceBox); AddAssert("skinchanged only called once", () => consumer.SkinChangedCount == 1); } [Test] public void TestSwitchOff() { SkinConsumer consumer = null; SwitchableSkinProvidingContainer target = null; AddStep("setup layout", () => { Child = new SkinSourceContainer { RelativeSizeAxes = Axes.Both, Child = target = new SwitchableSkinProvidingContainer(new SecondarySource()) { RelativeSizeAxes = Axes.Both, } }; }); AddStep("add permissive", () => target.Add(consumer = new SkinConsumer("test", name => new NamedBox("Default Implementation"), source => true))); AddAssert("consumer using override source", () => consumer.Drawable is SecondarySourceBox); AddStep("disable", () => target.Disable()); AddAssert("consumer using base source", () => consumer.Drawable is BaseSourceBox); } private class SwitchableSkinProvidingContainer : SkinProvidingContainer { private bool allow = true; protected override bool AllowDrawableLookup(ISkinComponent component) => allow; public void Disable() { allow = false; TriggerSourceChanged(); } public SwitchableSkinProvidingContainer(ISkin skin) : base(skin) { } } private class ExposedSkinnableDrawable : SkinnableDrawable { public new Drawable Drawable => base.Drawable; public ExposedSkinnableDrawable(string name, Func<ISkinComponent, Drawable> defaultImplementation, Func<ISkinSource, bool> allowFallback = null, ConfineMode confineMode = ConfineMode.ScaleToFit) : base(new TestSkinComponent(name), defaultImplementation, allowFallback, confineMode) { } } private class DefaultBox : DrawWidthBox { public DefaultBox() { RelativeSizeAxes = Axes.Both; } } private class DrawWidthBox : Container { private readonly OsuSpriteText text; public DrawWidthBox() { Children = new Drawable[] { new Box { Colour = Color4.Gray, RelativeSizeAxes = Axes.Both, }, text = new OsuSpriteText { Anchor = Anchor.Centre, Origin = Anchor.Centre, } }; } protected override void UpdateAfterChildren() { base.UpdateAfterChildren(); text.Text = DrawWidth.ToString(CultureInfo.InvariantCulture); } } private class NamedBox : Container { public NamedBox(string name) { Children = new Drawable[] { new Box { Colour = Color4.Black, RelativeSizeAxes = Axes.Both, }, new OsuSpriteText { Font = OsuFont.Default.With(size: 40), Anchor = Anchor.Centre, Origin = Anchor.Centre, Text = name } }; } } private class SkinConsumer : SkinnableDrawable { public new Drawable Drawable => base.Drawable; public int SkinChangedCount { get; private set; } public SkinConsumer(string name, Func<ISkinComponent, Drawable> defaultImplementation, Func<ISkinSource, bool> allowFallback = null) : base(new TestSkinComponent(name), defaultImplementation, allowFallback) { } protected override void SkinChanged(ISkinSource skin, bool allowFallback) { base.SkinChanged(skin, allowFallback); SkinChangedCount++; } } private class BaseSourceBox : NamedBox { public BaseSourceBox() : base("Base Source") { } } private class SecondarySourceBox : NamedBox { public SecondarySourceBox() : base("Secondary Source") { } } private class SizedSource : ISkin { private readonly float size; public SizedSource(float size) { this.size = size; } public Drawable GetDrawableComponent(ISkinComponent componentName) => componentName.LookupName == "available" ? new DrawWidthBox { Colour = Color4.Yellow, Size = new Vector2(size) } : null; public Texture GetTexture(string componentName) => throw new NotImplementedException(); public SampleChannel GetSample(ISampleInfo sampleInfo) => throw new NotImplementedException(); public IBindable<TValue> GetConfig<TLookup, TValue>(TLookup lookup) => throw new NotImplementedException(); } private class SecondarySource : ISkin { public Drawable GetDrawableComponent(ISkinComponent componentName) => new SecondarySourceBox(); public Texture GetTexture(string componentName) => throw new NotImplementedException(); public SampleChannel GetSample(ISampleInfo sampleInfo) => throw new NotImplementedException(); public IBindable<TValue> GetConfig<TLookup, TValue>(TLookup lookup) => throw new NotImplementedException(); } [Cached(typeof(ISkinSource))] private class SkinSourceContainer : Container, ISkinSource { public Drawable GetDrawableComponent(ISkinComponent componentName) => new BaseSourceBox(); public Texture GetTexture(string componentName) => throw new NotImplementedException(); public SampleChannel GetSample(ISampleInfo sampleInfo) => throw new NotImplementedException(); public IBindable<TValue> GetConfig<TLookup, TValue>(TLookup lookup) => throw new NotImplementedException(); public event Action SourceChanged { add { } remove { } } } private class TestSkinComponent : ISkinComponent { public TestSkinComponent(string name) { LookupName = name; } public string ComponentGroup => string.Empty; public string LookupName { get; } } } }
/******************************************************************************* * Copyright (c) 2013, Daniel Murphy * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ /** *.created at 3:31:07 PM Jan 14, 2011 */ using System; using SharpBox2D.Callbacks; using SharpBox2D.Collision; using SharpBox2D.Collision.Shapes; using SharpBox2D.Common; using SharpBox2D.Dynamics; using SharpBox2D.Dynamics.Contacts; using SharpBox2D.Dynamics.Joints; using SharpBox2D.TestBed.Framework; namespace SharpBox2D.TestBed.Tests { /** * @author Daniel Murphy */ public class EdgeShapes : TestbedTest { private const int e_maxBodies = 256; private int m_bodyIndex; private Body[] m_bodies = new Body[e_maxBodies]; private PolygonShape[] m_polygons = new PolygonShape[4]; private CircleShape m_circle; private float m_angle; public override void initTest(bool argDeserialized) { for (int i = 0; i < m_bodies.Length; i++) { m_bodies[i] = null; } // Ground body { BodyDef bd = new BodyDef(); Body ground = getWorld().createBody(bd); float x1 = -20.0f; float y1 = 2.0f*MathUtils.cos(x1/10.0f*MathUtils.PI); for (int i = 0; i < 80; ++i) { float x2 = x1 + 0.5f; float y2 = 2.0f*MathUtils.cos(x2/10.0f*MathUtils.PI); EdgeShape shape = new EdgeShape(); shape.set(new Vec2(x1, y1), new Vec2(x2, y2)); ground.createFixture(shape, 0.0f); x1 = x2; y1 = y2; } } { Vec2[] vertices = new Vec2[3]; vertices[0] = new Vec2(-0.5f, 0.0f); vertices[1] = new Vec2(0.5f, 0.0f); vertices[2] = new Vec2(0.0f, 1.5f); m_polygons[0] = new PolygonShape(); m_polygons[0].set(vertices, 3); } { Vec2[] vertices = new Vec2[3]; vertices[0] = new Vec2(-0.1f, 0.0f); vertices[1] = new Vec2(0.1f, 0.0f); vertices[2] = new Vec2(0.0f, 1.5f); m_polygons[1] = new PolygonShape(); m_polygons[1].set(vertices, 3); } { float w = 1.0f; float b = w/(2.0f + MathUtils.sqrt(2.0f)); float s = MathUtils.sqrt(2.0f)*b; Vec2[] vertices = new Vec2[8]; vertices[0] = new Vec2(0.5f*s, 0.0f); vertices[1] = new Vec2(0.5f*w, b); vertices[2] = new Vec2(0.5f*w, b + s); vertices[3] = new Vec2(0.5f*s, w); vertices[4] = new Vec2(-0.5f*s, w); vertices[5] = new Vec2(-0.5f*w, b + s); vertices[6] = new Vec2(-0.5f*w, b); vertices[7] = new Vec2(-0.5f*s, 0.0f); m_polygons[2] = new PolygonShape(); m_polygons[2].set(vertices, 8); } { m_polygons[3] = new PolygonShape(); m_polygons[3].setAsBox(0.5f, 0.5f); } { m_circle = new CircleShape(); m_circle.m_radius = 0.5f; } m_bodyIndex = 0; m_angle = 0.0f; } private void Create(int index) { if (m_bodies[m_bodyIndex] != null) { getWorld().destroyBody(m_bodies[m_bodyIndex]); m_bodies[m_bodyIndex] = null; } BodyDef bd = new BodyDef(); float x = MathUtils.randomFloat(-10.0f, 10.0f); float y = MathUtils.randomFloat(10.0f, 20.0f); bd.position.set(x, y); bd.angle = MathUtils.randomFloat(-MathUtils.PI, MathUtils.PI); bd.type = BodyType.DYNAMIC; if (index == 4) { bd.angularDamping = 0.02f; } m_bodies[m_bodyIndex] = getWorld().createBody(bd); if (index < 4) { FixtureDef fd = new FixtureDef(); fd.shape = m_polygons[index]; fd.friction = 0.3f; fd.density = 20.0f; m_bodies[m_bodyIndex].createFixture(fd); } else { FixtureDef fd = new FixtureDef(); fd.shape = m_circle; fd.friction = 0.3f; fd.density = 20.0f; m_bodies[m_bodyIndex].createFixture(fd); } m_bodyIndex = (m_bodyIndex + 1)%e_maxBodies; } private void DestroyBody() { for (int i = 0; i < e_maxBodies; ++i) { if (m_bodies[i] != null) { getWorld().destroyBody(m_bodies[i]); m_bodies[i] = null; return; } } } public override void keyPressed(char argKeyChar, int argKeyCode) { switch (argKeyChar) { case '1': case '2': case '3': case '4': case '5': Create(argKeyChar - '1'); break; case 'd': DestroyBody(); break; } } private EdgeShapesCallback callback = new EdgeShapesCallback(); public override void step(TestbedSettings settings) { bool advanceRay = settings.pause == false || settings.singleStep; base.step(settings); addTextLine("Press 1-5 to drop stuff"); float L = 25.0f; Vec2 point1 = new Vec2(0.0f, 10.0f); Vec2 d = new Vec2(L*MathUtils.cos(m_angle), -L*MathUtils.abs(MathUtils.sin(m_angle))); Vec2 point2 = point1.add(d); callback.m_fixture = null; getWorld().raycast(callback, point1, point2); if (callback.m_fixture != null) { getDebugDraw().drawPoint(callback.m_point, 5.0f, new Color4f(0.4f, 0.9f, 0.4f)); getDebugDraw().drawSegment(point1, callback.m_point, new Color4f(0.8f, 0.8f, 0.8f)); callback.m_normal.mul(.5f); callback.m_normal.addLocal(callback.m_point); Vec2 head = callback.m_normal; getDebugDraw().drawSegment(callback.m_point, head, new Color4f(0.9f, 0.9f, 0.4f)); } else { getDebugDraw().drawSegment(point1, point2, new Color4f(0.8f, 0.8f, 0.8f)); } if (advanceRay) { m_angle += 0.25f*MathUtils.PI/180.0f; } } public override string getTestName() { return "Edge Shapes"; } } internal class EdgeShapesCallback : RayCastCallback { internal EdgeShapesCallback() { m_fixture = null; } public float reportFixture(Fixture fixture, Vec2 point, Vec2 normal, float fraction) { m_fixture = fixture; m_point = point; m_normal = normal; return fraction; } internal Fixture m_fixture; internal Vec2 m_point; internal Vec2 m_normal; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net.Security; using System.Runtime.CompilerServices; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; using CURLAUTH = Interop.Http.CURLAUTH; using CURLcode = Interop.Http.CURLcode; using CURLMcode = Interop.Http.CURLMcode; using CURLoption = Interop.Http.CURLoption; namespace System.Net.Http { // Object model: // ------------- // CurlHandler provides an HttpMessageHandler implementation that wraps libcurl. The core processing for CurlHandler // is handled via a CurlHandler.MultiAgent instance, where currently a CurlHandler instance stores and uses a single // MultiAgent for the lifetime of the handler (with the MultiAgent lazily initialized on first use, so that it can // be initialized with all of the configured options on the handler). The MultiAgent is named as such because it wraps // a libcurl multi handle that's responsible for handling all requests on the instance. When a request arrives, it's // queued to the MultiAgent, which ensures that a thread is running to continually loop and process all work associated // with the multi handle until no more work is required; at that point, the thread is retired until more work arrives, // at which point another thread will be spun up. Any number of requests will have their handling multiplexed onto // this one event loop thread. Each request is represented by a CurlHandler.EasyRequest, so named because it wraps // a libcurl easy handle, libcurl's representation of a request. The EasyRequest stores all state associated with // the request, including the CurlHandler.CurlResponseMessage and CurlHandler.CurlResponseStream that are handed // back to the caller to provide access to the HTTP response information. // // Lifetime: // --------- // The MultiAgent is initialized on first use and is kept referenced by the CurlHandler for the remainder of the // handler's lifetime. Both are disposable, and disposing of the CurlHandler will dispose of the MultiAgent. // However, libcurl is not thread safe in that two threads can't be using the same multi or easy handles concurrently, // so any interaction with the multi handle must happen on the MultiAgent's thread. For this reason, the // SafeHandle storing the underlying multi handle has its ref count incremented when the MultiAgent worker is running // and decremented when it stops running, enabling any disposal requests to be delayed until the worker has quiesced. // To enable that to happen quickly when a dispose operation occurs, an "incoming request" (how all other threads // communicate with the MultiAgent worker) is queued to the worker to request a shutdown; upon receiving that request, // the worker will exit and allow the multi handle to be disposed of. // // An EasyRequest itself doesn't govern its own lifetime. Since an easy handle is added to a multi handle for // the multi handle to process, the easy handle must not be destroyed until after it's been removed from the multi handle. // As such, once the SafeHandle for an easy handle is created, although its stored in the EasyRequest instance, // it's also stored into a dictionary on the MultiAgent and has its ref count incremented to prevent it from being // disposed of while it's in use by the multi handle. // // When a request is made to the CurlHandler, callbacks are registered with libcurl, including state that will // be passed back into managed code and used to identify the associated EasyRequest. This means that the native // code needs to be able both to keep the EasyRequest alive and to refer to it using an IntPtr. For this, we // use a GCHandle to the EasyRequest. However, the native code needs to be able to refer to the EasyRequest for the // lifetime of the request, but we also need to avoid keeping the EasyRequest (and all state it references) alive artificially. // For the beginning phase of the request, the native code may be the only thing referencing the managed objects, since // when a caller invokes "Task<HttpResponseMessage> SendAsync(...)", there's nothing handed back to the caller that represents // the request until at least the HTTP response headers are received and the returned Task is completed with the response // message object. However, after that point, if the caller drops the HttpResponseMessage, we also want to cancel and // dispose of the associated state, which means something needs to be finalizable and not kept rooted while at the same // time still allowing the native code to continue using its GCHandle and lookup the associated state as long as it's alive. // Yet then when an async read is made on the response message, we want to postpone such finalization and ensure that the async // read can be appropriately completed with control and reference ownership given back to the reader. As such, we do two things: // we make the response stream finalizable, and we make the GCHandle be to a wrapper object for the EasyRequest rather than to // the EasyRequest itself. That wrapper object maintains a weak reference to the EasyRequest as well as sometimes maintaining // a strong reference. When the request starts out, the GCHandle is created to the wrapper, which has a strong reference to // the EasyRequest (which also back references to the wrapper so that the wrapper can be accessed via it). The GCHandle is // thus keeping the EasyRequest and all of the state it references alive, e.g. the CurlResponseStream, which itself has a reference // back to the EasyRequest. Once the request progresses to the point of receiving HTTP response headers and the HttpResponseMessage // is handed back to the caller, the wrapper object drops its strong reference and maintains only a weak reference. At this // point, if the caller were to drop its HttpResponseMessage object, that would also drop the only strong reference to the // CurlResponseStream; the CurlResponseStream would be available for collection and finalization, and its finalization would // request cancellation of the easy request to the multi agent. The multi agent would then in response remove the easy handle // from the multi handle and decrement the ref count on the SafeHandle for the easy handle, allowing it to be finalized and // the underlying easy handle released. If instead of dropping the HttpResponseMessage the caller makes a read request on the // response stream, the wrapper object is transitioned back to having a strong reference, so that even if the caller then drops // the HttpResponseMessage, the read Task returned from the read operation will still be completed eventually, at which point // the wrapper will transition back to being a weak reference. // // Even with that, of course, Dispose is still the recommended way of cleaning things up. Disposing the CurlResponseMessage // will Dispose the CurlResponseStream, which will Dispose of the SafeHandle for the easy handle and request that the MultiAgent // cancel the operation. Once canceled and removed, the SafeHandle will have its ref count decremented and the previous disposal // will proceed to release the underlying handle. internal partial class CurlHandler : HttpMessageHandler { #region Constants private const char SpaceChar = ' '; private const int StatusCodeLength = 3; private const string UriSchemeHttp = "http"; private const string UriSchemeHttps = "https"; private const string EncodingNameGzip = "gzip"; private const string EncodingNameDeflate = "deflate"; private const int MaxRequestBufferSize = 16384; // Default used by libcurl private const string NoTransferEncoding = HttpKnownHeaderNames.TransferEncoding + ":"; private const string NoContentType = HttpKnownHeaderNames.ContentType + ":"; private const string NoExpect = HttpKnownHeaderNames.Expect + ":"; private const int CurlAge = 5; private const int MinCurlAge = 3; #endregion #region Fields private static readonly KeyValuePair<string,CURLAUTH>[] s_orderedAuthTypes = new KeyValuePair<string, CURLAUTH>[] { new KeyValuePair<string,CURLAUTH>("Negotiate", CURLAUTH.Negotiate), new KeyValuePair<string,CURLAUTH>("NTLM", CURLAUTH.NTLM), new KeyValuePair<string,CURLAUTH>("Digest", CURLAUTH.Digest), new KeyValuePair<string,CURLAUTH>("Basic", CURLAUTH.Basic), }; // Max timeout value used by WinHttp handler, so mapping to that here. private static readonly TimeSpan s_maxTimeout = TimeSpan.FromMilliseconds(int.MaxValue); private static readonly char[] s_newLineCharArray = new char[] { HttpRuleParser.CR, HttpRuleParser.LF }; private static readonly bool s_supportsAutomaticDecompression; private static readonly bool s_supportsSSL; private static readonly bool s_supportsHttp2Multiplexing; private static volatile StrongBox<CURLMcode> s_supportsMaxConnectionsPerServer; private static string s_curlVersionDescription; private static string s_curlSslVersionDescription; private static readonly DiagnosticListener s_diagnosticListener = new DiagnosticListener(HttpHandlerLoggingStrings.DiagnosticListenerName); private readonly MultiAgent _agent; private volatile bool _anyOperationStarted; private volatile bool _disposed; private IWebProxy _proxy = null; private ICredentials _serverCredentials = null; private bool _useProxy = HttpHandlerDefaults.DefaultUseProxy; private ICredentials _defaultProxyCredentials = null; private DecompressionMethods _automaticDecompression = HttpHandlerDefaults.DefaultAutomaticDecompression; private bool _preAuthenticate = HttpHandlerDefaults.DefaultPreAuthenticate; private CredentialCache _credentialCache = null; // protected by LockObject private CookieContainer _cookieContainer = new CookieContainer(); private bool _useCookie = HttpHandlerDefaults.DefaultUseCookies; private TimeSpan _connectTimeout = Timeout.InfiniteTimeSpan; private bool _automaticRedirection = HttpHandlerDefaults.DefaultAutomaticRedirection; private int _maxAutomaticRedirections = HttpHandlerDefaults.DefaultMaxAutomaticRedirections; private int _maxConnectionsPerServer = HttpHandlerDefaults.DefaultMaxConnectionsPerServer; private int _maxResponseHeadersLength = HttpHandlerDefaults.DefaultMaxResponseHeaderLength; private ClientCertificateOption _clientCertificateOption = HttpHandlerDefaults.DefaultClientCertificateOption; private X509Certificate2Collection _clientCertificates; private Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> _serverCertificateValidationCallback; private bool _checkCertificateRevocationList; private SslProtocols _sslProtocols = SslProtocols.None; // use default private IDictionary<String, Object> _properties; // Only create dictionary when required. private object LockObject { get { return _agent; } } #endregion static CurlHandler() { // curl_global_init call handled by Interop.LibCurl's cctor Interop.Http.CurlFeatures features = Interop.Http.GetSupportedFeatures(); s_supportsSSL = (features & Interop.Http.CurlFeatures.CURL_VERSION_SSL) != 0; s_supportsAutomaticDecompression = (features & Interop.Http.CurlFeatures.CURL_VERSION_LIBZ) != 0; s_supportsHttp2Multiplexing = (features & Interop.Http.CurlFeatures.CURL_VERSION_HTTP2) != 0 && Interop.Http.GetSupportsHttp2Multiplexing(); if (HttpEventSource.Log.IsEnabled()) { EventSourceTrace($"libcurl: {CurlVersionDescription} {CurlSslVersionDescription} {features}"); } } public CurlHandler() { _agent = new MultiAgent(this); } #region Properties private static string CurlVersionDescription => s_curlVersionDescription ?? (s_curlVersionDescription = Interop.Http.GetVersionDescription() ?? string.Empty); private static string CurlSslVersionDescription => s_curlSslVersionDescription ?? (s_curlSslVersionDescription = Interop.Http.GetSslVersionDescription() ?? string.Empty); internal bool AutomaticRedirection { get { return _automaticRedirection; } set { CheckDisposedOrStarted(); _automaticRedirection = value; } } internal bool SupportsProxy => true; internal bool SupportsRedirectConfiguration => true; internal bool UseProxy { get { return _useProxy; } set { CheckDisposedOrStarted(); _useProxy = value; } } internal IWebProxy Proxy { get { return _proxy; } set { CheckDisposedOrStarted(); _proxy = value; } } internal ICredentials DefaultProxyCredentials { get { return _defaultProxyCredentials; } set { CheckDisposedOrStarted(); _defaultProxyCredentials = value; } } internal ICredentials Credentials { get { return _serverCredentials; } set { _serverCredentials = value; } } internal ClientCertificateOption ClientCertificateOptions { get { return _clientCertificateOption; } set { if (value != ClientCertificateOption.Manual && value != ClientCertificateOption.Automatic) { throw new ArgumentOutOfRangeException(nameof(value)); } CheckDisposedOrStarted(); _clientCertificateOption = value; } } internal X509Certificate2Collection ClientCertificates => _clientCertificates ?? (_clientCertificates = new X509Certificate2Collection()); internal Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> ServerCertificateValidationCallback { get { return _serverCertificateValidationCallback; } set { CheckDisposedOrStarted(); _serverCertificateValidationCallback = value; } } internal bool CheckCertificateRevocationList { get { return _checkCertificateRevocationList; } set { CheckDisposedOrStarted(); _checkCertificateRevocationList = value; } } internal SslProtocols SslProtocols { get { return _sslProtocols; } set { SecurityProtocol.ThrowOnNotAllowed(value, allowNone: true); CheckDisposedOrStarted(); _sslProtocols = value; } } private SslProtocols ActualSslProtocols => this.SslProtocols != SslProtocols.None ? this.SslProtocols : SecurityProtocol.DefaultSecurityProtocols; internal bool SupportsAutomaticDecompression => s_supportsAutomaticDecompression; internal DecompressionMethods AutomaticDecompression { get { return _automaticDecompression; } set { CheckDisposedOrStarted(); _automaticDecompression = value; } } internal bool PreAuthenticate { get { return _preAuthenticate; } set { CheckDisposedOrStarted(); _preAuthenticate = value; if (value && _credentialCache == null) { _credentialCache = new CredentialCache(); } } } internal bool UseCookie { get { return _useCookie; } set { CheckDisposedOrStarted(); _useCookie = value; } } internal CookieContainer CookieContainer { get { return _cookieContainer; } set { CheckDisposedOrStarted(); _cookieContainer = value; } } internal int MaxAutomaticRedirections { get { return _maxAutomaticRedirections; } set { if (value <= 0) { throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0)); } CheckDisposedOrStarted(); _maxAutomaticRedirections = value; } } internal int MaxConnectionsPerServer { get { return _maxConnectionsPerServer; } set { if (value < 1) { throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0)); } // Make sure the libcurl version we're using supports the option, by setting the value on a temporary multi handle. // We do this once and cache the result. StrongBox<CURLMcode> supported = s_supportsMaxConnectionsPerServer; // benign race condition to read and set this if (supported == null) { using (Interop.Http.SafeCurlMultiHandle multiHandle = Interop.Http.MultiCreate()) { s_supportsMaxConnectionsPerServer = supported = new StrongBox<CURLMcode>( Interop.Http.MultiSetOptionLong(multiHandle, Interop.Http.CURLMoption.CURLMOPT_MAX_HOST_CONNECTIONS, value)); } } if (supported.Value != CURLMcode.CURLM_OK) { throw new PlatformNotSupportedException(CurlException.GetCurlErrorString((int)supported.Value, isMulti: true)); } CheckDisposedOrStarted(); _maxConnectionsPerServer = value; } } internal int MaxResponseHeadersLength { get { return _maxResponseHeadersLength; } set { if (value <= 0) { throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0)); } CheckDisposedOrStarted(); _maxResponseHeadersLength = value; } } internal bool UseDefaultCredentials { get { return false; } set { } } public IDictionary<string, object> Properties { get { if (_properties == null) { _properties = new Dictionary<String, object>(); } return _properties; } } #endregion protected override void Dispose(bool disposing) { _disposed = true; if (disposing) { _agent.Dispose(); } base.Dispose(disposing); } protected internal override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { if (request == null) { throw new ArgumentNullException(nameof(request), SR.net_http_handler_norequest); } if (request.RequestUri.Scheme == UriSchemeHttps) { if (!s_supportsSSL) { throw new PlatformNotSupportedException(SR.Format(SR.net_http_unix_https_support_unavailable_libcurl, CurlVersionDescription)); } } else { Debug.Assert(request.RequestUri.Scheme == UriSchemeHttp, "HttpClient expected to validate scheme as http or https."); } if (request.Headers.TransferEncodingChunked.GetValueOrDefault() && (request.Content == null)) { throw new InvalidOperationException(SR.net_http_chunked_not_allowed_with_empty_content); } if (_useCookie && _cookieContainer == null) { throw new InvalidOperationException(SR.net_http_invalid_cookiecontainer); } CheckDisposed(); SetOperationStarted(); // Do an initial cancellation check to avoid initiating the async operation if // cancellation has already been requested. After this, we'll rely on CancellationToken.Register // to notify us of cancellation requests and shut down the operation if possible. if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<HttpResponseMessage>(cancellationToken); } Guid loggingRequestId = s_diagnosticListener.LogHttpRequest(request); // Create the easy request. This associates the easy request with this handler and configures // it based on the settings configured for the handler. var easy = new EasyRequest(this, request, cancellationToken); try { EventSourceTrace("{0}", request, easy: easy, agent: _agent); _agent.Queue(new MultiAgent.IncomingRequest { Easy = easy, Type = MultiAgent.IncomingRequestType.New }); } catch (Exception exc) { easy.CleanupAndFailRequest(exc); } s_diagnosticListener.LogHttpResponse(easy.Task, loggingRequestId); return easy.Task; } #region Private methods private void SetOperationStarted() { if (!_anyOperationStarted) { _anyOperationStarted = true; } } private KeyValuePair<NetworkCredential, CURLAUTH> GetCredentials(Uri requestUri) { // If preauthentication is enabled, we may have populated our internal credential cache, // so first check there to see if we have any credentials for this uri. if (_preAuthenticate) { KeyValuePair<NetworkCredential, CURLAUTH> ncAndScheme; lock (LockObject) { Debug.Assert(_credentialCache != null, "Expected non-null credential cache"); ncAndScheme = GetCredentials(requestUri, _credentialCache, s_orderedAuthTypes); } if (ncAndScheme.Key != null) { return ncAndScheme; } } // We either weren't preauthenticating or we didn't have any cached credentials // available, so check the credentials on the handler. return GetCredentials(requestUri, _serverCredentials, s_orderedAuthTypes); } private void TransferCredentialsToCache(Uri serverUri, CURLAUTH serverAuthAvail) { if (_serverCredentials == null) { // No credentials, nothing to put into the cache. return; } lock (LockObject) { // For each auth type we allow, check whether it's one supported by the server. KeyValuePair<string, CURLAUTH>[] validAuthTypes = s_orderedAuthTypes; for (int i = 0; i < validAuthTypes.Length; i++) { // Is it supported by the server? if ((serverAuthAvail & validAuthTypes[i].Value) != 0) { // And do we have a credential for it? NetworkCredential nc = _serverCredentials.GetCredential(serverUri, validAuthTypes[i].Key); if (nc != null) { // We have a credential for it, so add it, and we're done. Debug.Assert(_credentialCache != null, "Expected non-null credential cache"); try { _credentialCache.Add(serverUri, validAuthTypes[i].Key, nc); } catch (ArgumentException) { // Ignore the case of key already present } break; } } } } } private void AddResponseCookies(EasyRequest state, string cookieHeader) { if (!_useCookie) { return; } try { _cookieContainer.SetCookies(state._requestMessage.RequestUri, cookieHeader); state.SetCookieOption(state._requestMessage.RequestUri); } catch (CookieException e) { EventSourceTrace( "Malformed cookie parsing failed: {0}, server: {1}, cookie: {2}", e.Message, state._requestMessage.RequestUri, cookieHeader, easy: state); } } private static KeyValuePair<NetworkCredential, CURLAUTH> GetCredentials(Uri requestUri, ICredentials credentials, KeyValuePair<string, CURLAUTH>[] validAuthTypes) { NetworkCredential nc = null; CURLAUTH curlAuthScheme = CURLAUTH.None; if (credentials != null) { // For each auth type we consider valid, try to get a credential for it. // Union together the auth types for which we could get credentials, but validate // that the found credentials are all the same, as libcurl doesn't support differentiating // by auth type. for (int i = 0; i < validAuthTypes.Length; i++) { NetworkCredential networkCredential = credentials.GetCredential(requestUri, validAuthTypes[i].Key); if (networkCredential != null) { curlAuthScheme |= validAuthTypes[i].Value; if (nc == null) { nc = networkCredential; } else if(!AreEqualNetworkCredentials(nc, networkCredential)) { throw new PlatformNotSupportedException(SR.Format(SR.net_http_unix_invalid_credential, CurlVersionDescription)); } } } } EventSourceTrace("Authentication scheme: {0}", curlAuthScheme); return new KeyValuePair<NetworkCredential, CURLAUTH>(nc, curlAuthScheme); ; } private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(GetType().FullName); } } private void CheckDisposedOrStarted() { CheckDisposed(); if (_anyOperationStarted) { throw new InvalidOperationException(SR.net_http_operation_started); } } private static void ThrowIfCURLEError(CURLcode error) { if (error != CURLcode.CURLE_OK) // success { string msg = CurlException.GetCurlErrorString((int)error, isMulti: false); EventSourceTrace(msg); switch (error) { case CURLcode.CURLE_OPERATION_TIMEDOUT: throw new OperationCanceledException(msg); case CURLcode.CURLE_OUT_OF_MEMORY: throw new OutOfMemoryException(msg); case CURLcode.CURLE_SEND_FAIL_REWIND: throw new InvalidOperationException(msg); default: throw new CurlException((int)error, msg); } } } private static void ThrowIfCURLMError(CURLMcode error) { if (error != CURLMcode.CURLM_OK && // success error != CURLMcode.CURLM_CALL_MULTI_PERFORM) // success + a hint to try curl_multi_perform again { string msg = CurlException.GetCurlErrorString((int)error, isMulti: true); EventSourceTrace(msg); switch (error) { case CURLMcode.CURLM_ADDED_ALREADY: case CURLMcode.CURLM_BAD_EASY_HANDLE: case CURLMcode.CURLM_BAD_HANDLE: case CURLMcode.CURLM_BAD_SOCKET: throw new ArgumentException(msg); case CURLMcode.CURLM_UNKNOWN_OPTION: throw new ArgumentOutOfRangeException(msg); case CURLMcode.CURLM_OUT_OF_MEMORY: throw new OutOfMemoryException(msg); case CURLMcode.CURLM_INTERNAL_ERROR: default: throw new CurlException((int)error, msg); } } } private static bool AreEqualNetworkCredentials(NetworkCredential credential1, NetworkCredential credential2) { Debug.Assert(credential1 != null && credential2 != null, "arguments are non-null in network equality check"); return credential1.UserName == credential2.UserName && credential1.Domain == credential2.Domain && string.Equals(credential1.Password, credential2.Password, StringComparison.Ordinal); } private static bool EventSourceTracingEnabled { get { return HttpEventSource.Log.IsEnabled(); } } // PERF NOTE: // These generic overloads of EventSourceTrace (and similar wrapper methods in some of the other CurlHandler // nested types) exist to allow call sites to call EventSourceTrace without boxing and without checking // EventSourceTracingEnabled. Do not remove these without fixing the call sites accordingly. private static void EventSourceTrace<TArg0>( string formatMessage, TArg0 arg0, MultiAgent agent = null, EasyRequest easy = null, [CallerMemberName] string memberName = null) { if (EventSourceTracingEnabled) { EventSourceTraceCore(string.Format(formatMessage, arg0), agent, easy, memberName); } } private static void EventSourceTrace<TArg0, TArg1, TArg2> (string formatMessage, TArg0 arg0, TArg1 arg1, TArg2 arg2, MultiAgent agent = null, EasyRequest easy = null, [CallerMemberName] string memberName = null) { if (EventSourceTracingEnabled) { EventSourceTraceCore(string.Format(formatMessage, arg0, arg1, arg2), agent, easy, memberName); } } private static void EventSourceTrace( string message, MultiAgent agent = null, EasyRequest easy = null, [CallerMemberName] string memberName = null) { if (EventSourceTracingEnabled) { EventSourceTraceCore(message, agent, easy, memberName); } } private static void EventSourceTraceCore(string message, MultiAgent agent, EasyRequest easy, string memberName) { // If we weren't handed a multi agent, see if we can get one from the EasyRequest if (agent == null && easy != null) { agent = easy._associatedMultiAgent; } HttpEventSource.Log.HandlerMessage( (agent?.RunningWorkerId).GetValueOrDefault(), easy != null ? easy.Task.Id : 0, memberName, message); } private static HttpRequestException CreateHttpRequestException(Exception inner) { return new HttpRequestException(SR.net_http_client_execution_error, inner); } private static IOException MapToReadWriteIOException(Exception error, bool isRead) { return new IOException( isRead ? SR.net_http_io_read : SR.net_http_io_write, error is HttpRequestException && error.InnerException != null ? error.InnerException : error); } private static void SetChunkedModeForSend(HttpRequestMessage request) { bool chunkedMode = request.Headers.TransferEncodingChunked.GetValueOrDefault(); HttpContent requestContent = request.Content; Debug.Assert(requestContent != null, "request is null"); // Deal with conflict between 'Content-Length' vs. 'Transfer-Encoding: chunked' semantics. // libcurl adds a Transfer-Encoding header by default and the request fails if both are set. if (requestContent.Headers.ContentLength.HasValue) { if (chunkedMode) { // Same behaviour as WinHttpHandler requestContent.Headers.ContentLength = null; } else { // Prevent libcurl from adding Transfer-Encoding header request.Headers.TransferEncodingChunked = false; } } else if (!chunkedMode) { // Make sure Transfer-Encoding: chunked header is set, // as we have content to send but no known length for it. request.Headers.TransferEncodingChunked = true; } } #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. namespace System.Drawing { /** * Represents a dimension in 2D coordinate space */ /// <summary> /// <para> /// Represents the size of a rectangular region /// with an ordered pair of width and height. /// </para> /// </summary> public struct SizeF { /// <summary> /// Initializes a new instance of the <see cref='System.Drawing.SizeF'/> class. /// </summary> public static readonly SizeF Empty = new SizeF(); private float _width; private float _height; /** * Create a new SizeF object from another size object */ /// <summary> /// Initializes a new instance of the <see cref='System.Drawing.SizeF'/> class /// from the specified existing <see cref='System.Drawing.SizeF'/>. /// </summary> public SizeF(SizeF size) { _width = size._width; _height = size._height; } /** * Create a new SizeF object from a point */ /// <summary> /// <para> /// Initializes a new instance of the <see cref='System.Drawing.SizeF'/> class from /// the specified <see cref='System.Drawing.PointF'/>. /// </para> /// </summary> public SizeF(PointF pt) { _width = pt.X; _height = pt.Y; } /** * Create a new SizeF object of the specified dimension */ /// <summary> /// <para> /// Initializes a new instance of the <see cref='System.Drawing.SizeF'/> class from /// the specified dimensions. /// </para> /// </summary> public SizeF(float width, float height) { _width = width; _height = height; } /// <summary> /// <para> /// Performs vector addition of two <see cref='System.Drawing.SizeF'/> objects. /// </para> /// </summary> public static SizeF operator +(SizeF sz1, SizeF sz2) { return Add(sz1, sz2); } /// <summary> /// <para> /// Contracts a <see cref='System.Drawing.SizeF'/> by another <see cref='System.Drawing.SizeF'/> /// </para> /// </summary> public static SizeF operator -(SizeF sz1, SizeF sz2) { return Subtract(sz1, sz2); } /// <summary> /// Tests whether two <see cref='System.Drawing.SizeF'/> objects /// are identical. /// </summary> public static bool operator ==(SizeF sz1, SizeF sz2) { return sz1.Width == sz2.Width && sz1.Height == sz2.Height; } /// <summary> /// <para> /// Tests whether two <see cref='System.Drawing.SizeF'/> objects are different. /// </para> /// </summary> public static bool operator !=(SizeF sz1, SizeF sz2) { return !(sz1 == sz2); } /// <summary> /// <para> /// Converts the specified <see cref='System.Drawing.SizeF'/> to a /// <see cref='System.Drawing.PointF'/>. /// </para> /// </summary> public static explicit operator PointF(SizeF size) { return new PointF(size.Width, size.Height); } /// <summary> /// <para> /// Tests whether this <see cref='System.Drawing.SizeF'/> has zero /// width and height. /// </para> /// </summary> public bool IsEmpty { get { return _width == 0 && _height == 0; } } /** * Horizontal dimension */ /// <summary> /// <para> /// Represents the horizontal component of this /// <see cref='System.Drawing.SizeF'/>. /// </para> /// </summary> public float Width { get { return _width; } set { _width = value; } } /** * Vertical dimension */ /// <summary> /// <para> /// Represents the vertical component of this /// <see cref='System.Drawing.SizeF'/>. /// </para> /// </summary> public float Height { get { return _height; } set { _height = value; } } /// <summary> /// <para> /// Performs vector addition of two <see cref='System.Drawing.SizeF'/> objects. /// </para> /// </summary> public static SizeF Add(SizeF sz1, SizeF sz2) { return new SizeF(sz1.Width + sz2.Width, sz1.Height + sz2.Height); } /// <summary> /// <para> /// Contracts a <see cref='System.Drawing.SizeF'/> by another <see cref='System.Drawing.SizeF'/> /// . /// </para> /// </summary> public static SizeF Subtract(SizeF sz1, SizeF sz2) { return new SizeF(sz1.Width - sz2.Width, sz1.Height - sz2.Height); } /// <summary> /// <para> /// Tests to see whether the specified object is a /// <see cref='System.Drawing.SizeF'/> /// with the same dimensions as this <see cref='System.Drawing.SizeF'/>. /// </para> /// </summary> public override bool Equals(object obj) { if (!(obj is SizeF)) return false; SizeF comp = (SizeF)obj; return (comp.Width == Width) && (comp.Height == Height); } public override int GetHashCode() { return base.GetHashCode(); } public PointF ToPointF() { return (PointF)this; } public Size ToSize() { return Size.Truncate(this); } /// <summary> /// <para> /// Creates a human-readable string that represents this /// <see cref='System.Drawing.SizeF'/>. /// </para> /// </summary> public override string ToString() { return "{Width=" + _width.ToString() + ", Height=" + _height.ToString() + "}"; } } }