context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Collections.Generic; using Microsoft.Azure.Management.RecoveryServices.SiteRecovery; using Microsoft.Azure.Management.RecoveryServices.SiteRecovery.Models; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using Xunit; using System.Linq; using SiteRecovery.Tests; using Microsoft.Rest.Azure.OData; namespace RecoveryServices.SiteRecovery.Tests { public class ASRTests : SiteRecoveryTestsBase { private const string targetResourceGroup = "/subscriptions/c183865e-6077-46f2-a3b1-deb0f4f4650a/resourceGroups/siterecoveryprod1"; private const string storageAccountId = "/subscriptions/c183865e-6077-46f2-a3b1-deb0f4f4650a/resourceGroups/siterecoveryprod1/providers/Microsoft.Storage/storageAccounts/storavrai"; private const string azureNetworkId = "/subscriptions/c183865e-6077-46f2-a3b1-deb0f4f4650a/resourceGroups/siterecoveryProd1/providers/Microsoft.Network/virtualNetworks/vnetavrai"; private const string siteName = "SiteRecoveryTestSite1"; private const string vmmFabric = "d188dc378a78c819bfb8b1f07eba2c15511e1788c41ba27792d9433fc6a4e087"; private const string location = "westus"; private const string providerName = "ba2a2d25-377f-4f4b-94a4-2981c79b0998"; private const string policyName = "protectionprofile1"; private const string recoveryCloud = "Microsoft Azure"; private const string protectionContainerMappingName = "PCMapping"; private const string networkMappingName = "NWMapping"; private const string vmName = "vm1"; private const string vmId = "f8491e4f-817a-40dd-a90c-af773978c75b"; private const string vmName2 = "vm2"; private const string rpName = "rpTest1"; private const string emailAddress = "ronehr@microsoft.com"; private const string alertSettingName = "defaultAlertSetting"; private const string vmNetworkName = "c41eda86-96d5-4541-a6f8-c47d4b75a24a"; private const string a2aPrimaryLocation = "westeurope"; private const string a2aRecoveryLocation = "northeurope"; private const string a2aPrimaryFabricName = "primaryFabric"; private const string a2aRecoveryFabricName = "recoveryFabric"; private const string a2aPrimaryContainerName = "primaryContainer"; private const string a2aRecoveryContainerName = "recoveryContainer"; private const string a2aPolicyName = "a2aPolicy"; private const string a2aPrimaryRecoveryContainerMappingName = "primaryToRecovery"; private const string a2aRecoveryPrimaryContainerMappingName = "recoveryToPrimary"; private const string a2aVirtualMachineToProtect = "/subscriptions/a7d8f9d0-930c-4dc8-9c14-1526ba255c20/resourceGroups/sdkTestVmRG/providers/Microsoft.Compute/virtualMachines/sdkTestVm1"; private const string a2aVirtualMachineDiskToProtect = "/subscriptions/a7d8f9d0-930c-4dc8-9c14-1526ba255c20/resourceGroups/SDKTESTVMRG/providers/Microsoft.Compute/disks/sdkTestVm1_OsDisk_1_3b1dd430d52044f18fb996d34617f609"; private const string a2aStagingStorageAccount = "/subscriptions/a7d8f9d0-930c-4dc8-9c14-1526ba255c20/resourceGroups/siterecoveryprod1/providers/Microsoft.Storage/storageAccounts/do00nssdkvaultasrcache"; private const string a2aRecoveryResourceGroup = "/subscriptions/a7d8f9d0-930c-4dc8-9c14-1526ba255c20/resourceGroups/sdkTestVmRG-asr"; private const string a2aReplicationProtectedItemName = "sdkTestVm1"; private const string a2aVirtualMachineToValidate = "testVm1"; TestHelper testHelper { get; set; } public ASRTests() { testHelper = new TestHelper(); } [Fact] public void CreateA2APolicy() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var a2aPolicyCreationInput = new A2APolicyCreationInput { AppConsistentFrequencyInMinutes = 60, RecoveryPointHistory = 720, MultiVmSyncStatus = "Enable" }; var createPolicyInput = new CreatePolicyInput { Properties = new CreatePolicyInputProperties() }; createPolicyInput.Properties.ProviderSpecificInput = a2aPolicyCreationInput; var policy = client.ReplicationPolicies.Create(a2aPolicyName, createPolicyInput); Assert.True( policy.Name == a2aPolicyName, "Resource name can not be different."); } } [Fact] public void CreateA2AFabrics() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var fabricCreationInput = new FabricCreationInput(); fabricCreationInput.Properties = new FabricCreationInputProperties(); var azureFabricCreationInput = new AzureFabricCreationInput(); // Create primary fabric. azureFabricCreationInput.Location = a2aPrimaryLocation; fabricCreationInput.Properties.CustomDetails = azureFabricCreationInput; var primaryFabric = client.ReplicationFabrics.Create(a2aPrimaryFabricName, fabricCreationInput); // var response = client.ReplicationFabrics.Get(a2aPrimaryFabricName); Assert.True( primaryFabric.Name == a2aPrimaryFabricName, "Resource name can not be different."); // Create recovery fabric. azureFabricCreationInput.Location = a2aRecoveryLocation; fabricCreationInput.Properties.CustomDetails = azureFabricCreationInput; var recoveryFabric = client.ReplicationFabrics.Create(a2aRecoveryFabricName, fabricCreationInput); // response = client.ReplicationFabrics.Get(a2aRecoveryFabricName); Assert.True( recoveryFabric.Name == a2aRecoveryFabricName, "Resource name can not be different."); } } [Fact] public void CreateA2AContainers() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var createProtectionContainerInput = new CreateProtectionContainerInput { Properties = new CreateProtectionContainerInputProperties() }; var primaryContainer = client.ReplicationProtectionContainers.Create( a2aPrimaryFabricName, a2aPrimaryContainerName, createProtectionContainerInput); Assert.True( primaryContainer.Name == a2aPrimaryContainerName, "Resource name can not be different."); var recoveryContainer = client.ReplicationProtectionContainers.Create( a2aRecoveryFabricName, a2aRecoveryContainerName, createProtectionContainerInput); Assert.True( recoveryContainer.Name == a2aRecoveryContainerName, "Resource name can not be different."); } } [Fact] public void CreateA2AContainerMappings() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var createProtectionContainerMappingInput = new CreateProtectionContainerMappingInput { Properties = new CreateProtectionContainerMappingInputProperties() }; var policy = client.ReplicationPolicies.Get(a2aPolicyName); var primaryContainer = client.ReplicationProtectionContainers.Get( a2aPrimaryFabricName, a2aPrimaryContainerName); var recoveryContainer = client.ReplicationProtectionContainers.Get( a2aRecoveryFabricName, a2aRecoveryContainerName); // Create primary to recovery container mapping createProtectionContainerMappingInput.Properties.PolicyId = policy.Id; createProtectionContainerMappingInput.Properties.TargetProtectionContainerId = recoveryContainer.Id; createProtectionContainerMappingInput.Properties.ProviderSpecificInput = new ReplicationProviderSpecificContainerMappingInput(); var primaryRecoveryContainerMapping = client.ReplicationProtectionContainerMappings.Create( a2aPrimaryFabricName, a2aPrimaryContainerName, a2aPrimaryRecoveryContainerMappingName, createProtectionContainerMappingInput); Assert.True( primaryRecoveryContainerMapping.Name == a2aPrimaryRecoveryContainerMappingName, "Resource name can not be different."); // Create primary to recovery container mapping createProtectionContainerMappingInput.Properties.TargetProtectionContainerId = primaryContainer.Id; var recoveryPrimaryContainerMapping = client.ReplicationProtectionContainerMappings.Create( a2aRecoveryFabricName, a2aRecoveryContainerName, a2aRecoveryPrimaryContainerMappingName, createProtectionContainerMappingInput); Assert.True( recoveryPrimaryContainerMapping.Name == a2aRecoveryPrimaryContainerMappingName, "Resource name can not be different."); } } [Fact] public void CreateA2AReplicationProtectedItem() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var policy = client.ReplicationPolicies.Get(a2aPolicyName); var recoveryContainer = client.ReplicationProtectionContainers.Get( a2aRecoveryFabricName, a2aRecoveryContainerName); var a2aEnableProtectionInput = new A2AEnableProtectionInput(); a2aEnableProtectionInput.FabricObjectId = a2aVirtualMachineToProtect; a2aEnableProtectionInput.RecoveryContainerId = recoveryContainer.Id; a2aEnableProtectionInput.RecoveryResourceGroupId = a2aRecoveryResourceGroup; a2aEnableProtectionInput.VmManagedDisks = new List<A2AVmManagedDiskInputDetails>(); var a2aVmManagedDiskInputDetails = new A2AVmManagedDiskInputDetails { DiskId = a2aVirtualMachineDiskToProtect, PrimaryStagingAzureStorageAccountId = a2aStagingStorageAccount, RecoveryResourceGroupId = a2aRecoveryResourceGroup, RecoveryTargetDiskAccountType = "Standard_LRS", RecoveryReplicaDiskAccountType = "Standard_LRS" }; a2aEnableProtectionInput.VmManagedDisks.Add(a2aVmManagedDiskInputDetails); var enableProtectionInput = new EnableProtectionInput { Properties = new EnableProtectionInputProperties() }; enableProtectionInput.Properties.PolicyId = policy.Id; enableProtectionInput.Properties.ProviderSpecificDetails = a2aEnableProtectionInput; var replicationProtectedItem = client.ReplicationProtectedItems.Create( a2aPrimaryFabricName, a2aPrimaryContainerName, a2aReplicationProtectedItemName, enableProtectionInput); Assert.True( replicationProtectedItem.Name == a2aReplicationProtectedItemName, "Resource name can not be different."); } } [Fact] public void GetA2AResources() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var policy = client.ReplicationPolicies.Get(a2aPolicyName); Assert.True(policy.Name == a2aPolicyName, "Resource name can not be different."); var primaryFabric = client.ReplicationFabrics.Get(a2aPrimaryFabricName); Assert.True( primaryFabric.Name == a2aPrimaryFabricName, "Resource name can not be different."); var recoveryFabric = client.ReplicationFabrics.Get(a2aRecoveryFabricName); Assert.True( recoveryFabric.Name == a2aRecoveryFabricName, "Resource name can not be different."); var primaryContainer = client.ReplicationProtectionContainers.Get( a2aPrimaryFabricName, a2aPrimaryContainerName); Assert.True( primaryContainer.Name == a2aPrimaryContainerName, "Resource name can not be different."); var recoveryContainer = client.ReplicationProtectionContainers.Get( a2aRecoveryFabricName, a2aRecoveryContainerName); Assert.True( recoveryContainer.Name == a2aRecoveryContainerName, "Resource name can not be different."); var primaryRecoveryContainerMapping = client.ReplicationProtectionContainerMappings.Get( a2aPrimaryFabricName, a2aPrimaryContainerName, a2aPrimaryRecoveryContainerMappingName); Assert.True( primaryRecoveryContainerMapping.Name == a2aPrimaryRecoveryContainerMappingName, "Resource name can not be different."); var recoveryPrimaryContainerMapping = client.ReplicationProtectionContainerMappings.Get( a2aRecoveryFabricName, a2aRecoveryContainerName, a2aRecoveryPrimaryContainerMappingName); Assert.True( recoveryPrimaryContainerMapping.Name == a2aRecoveryPrimaryContainerMappingName, "Resource name can not be different."); var replicationProtectedItem = client.ReplicationProtectedItems.Get( a2aPrimaryFabricName, a2aPrimaryContainerName, a2aReplicationProtectedItemName); Assert.True( replicationProtectedItem.Name == a2aReplicationProtectedItemName, "Resource name can not be different."); } } [Fact] public void ListA2AResources() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var policies= client.ReplicationPolicies.List(); Assert.True(policies.Count() == 1, "Only 1 policy got created via test."); var fabrics = client.ReplicationFabrics.List(); Assert.True(fabrics.Count() == 2, "Only 2 fabrics got created via test."); var containers = client.ReplicationProtectionContainers.List(); Assert.True(containers.Count() == 2, "Only 2 containers got created via test."); var containerMappings = client.ReplicationProtectionContainerMappings.List(); Assert.True( containerMappings.Count() == 2, "Only 2 container mappings got created via test."); var replicationProtectedItems = client.ReplicationProtectedItems.List(); Assert.True( replicationProtectedItems.Count() == 1, "Only 1 replicationProtectedItem got created via test."); } } [Fact] public void DeleteA2AReplicationProtectedItem() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var disableProtectionInput = new DisableProtectionInput { Properties = new DisableProtectionInputProperties() }; disableProtectionInput.Properties.ReplicationProviderInput = new DisableProtectionProviderSpecificInput(); client.ReplicationProtectedItems.Delete( a2aPrimaryFabricName, a2aPrimaryContainerName, a2aReplicationProtectedItemName, disableProtectionInput); var replicationProtectedItems = client.ReplicationProtectedItems.List(); Assert.True( replicationProtectedItems.Count() == 0, "Delted the replicationProtectedItem that got created via test."); } } [Fact] public void DeleteA2AContainerMappings() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var removeProtectionContainerMappingInput = new RemoveProtectionContainerMappingInput { Properties = new RemoveProtectionContainerMappingInputProperties() }; removeProtectionContainerMappingInput.Properties.ProviderSpecificInput = new ReplicationProviderContainerUnmappingInput(); client.ReplicationProtectionContainerMappings.Delete( a2aPrimaryFabricName, a2aPrimaryContainerName, a2aPrimaryRecoveryContainerMappingName, removeProtectionContainerMappingInput); client.ReplicationProtectionContainerMappings.Delete( a2aRecoveryFabricName, a2aRecoveryContainerName, a2aRecoveryPrimaryContainerMappingName, removeProtectionContainerMappingInput); var containerMappings = client.ReplicationProtectionContainerMappings.List(); Assert.True( containerMappings.Count() == 0, "Delted 2 container mappings that got created via test."); } } [Fact] public void DeleteA2AContainers() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; client.ReplicationProtectionContainers.Delete( a2aPrimaryFabricName, a2aPrimaryContainerName); client.ReplicationProtectionContainers.Delete( a2aRecoveryFabricName, a2aRecoveryContainerName); var containers = client.ReplicationProtectionContainers.List(); Assert.True( containers.Count() == 0, "Delted 2 containers that got created via test."); } } [Fact] public void DeleteA2AFabrics() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; client.ReplicationFabrics.Delete(a2aPrimaryFabricName); client.ReplicationFabrics.Delete(a2aRecoveryFabricName); var fabrics = client.ReplicationFabrics.List(); Assert.True(fabrics.Count() == 0, "Delted 2 fabrics that got created via test."); } } [Fact] public void DeleteA2APolicy() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; client.ReplicationPolicies.Delete(a2aPolicyName); var policies = client.ReplicationPolicies.List(); Assert.True(policies.Count() == 0, "Delted the policy that got created via test."); } } [Fact] public void CreateSite() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); FabricCreationInput siteInput = new FabricCreationInput(); siteInput.Properties = new FabricCreationInputProperties(); var client = testHelper.SiteRecoveryClient; var site = client.ReplicationFabrics.Create(siteName, siteInput); var response = client.ReplicationFabrics.Get(siteName); Assert.True(response.Name == siteName, "Site Name can not be different"); } } [Fact] public void GetSite() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var fabric = client.ReplicationFabrics.Get(siteName); Assert.NotNull(fabric.Id); } } [Fact] public void ListSite() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var fabricList = client.ReplicationFabrics.List(); Assert.True(fabricList.Count() > 0, "Atleast one fabric should be present"); } } [Fact] public void DeleteSite() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; client.ReplicationFabrics.Delete(siteName); } } [Fact] public void PurgeSite() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; client.ReplicationFabrics.Purge(siteName); } } [Fact] public void CheckConsistency() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; client.ReplicationFabrics.CheckConsistency(siteName); var fabric = client.ReplicationFabrics.Get(siteName); } } [Fact(Skip = "ReRecord due to CR change")] [Trait("ReRecord", "CR Changes")] public void RenewCertificate() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; RenewCertificateInputProperties inputProperties = new RenewCertificateInputProperties() { RenewCertificateType = "Cloud" }; RenewCertificateInput input = new RenewCertificateInput() { Properties = inputProperties }; client.ReplicationFabrics.RenewCertificate(siteName, input); var fabric = client.ReplicationFabrics.Get(siteName); } } [Fact] public void GetRSP() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var fabric = client.ReplicationFabrics.Get(siteName); var recoveryServivesProviderResponse = client.ReplicationRecoveryServicesProviders.Get(fabric.Name, providerName); Assert.NotNull(recoveryServivesProviderResponse.Properties.FriendlyName); Assert.NotNull(recoveryServivesProviderResponse.Name); Assert.NotNull(recoveryServivesProviderResponse.Id); } } [Fact] public void ListRspByFabric() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var fabric = client.ReplicationFabrics.Get(siteName); var rspList = client.ReplicationRecoveryServicesProviders.ListByReplicationFabrics(fabric.Name); Assert.True(rspList.Count() > 0, "Atleast one replication recovery services provider should be present"); } } [Fact] public void ListRsp() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var rspList = client.ReplicationRecoveryServicesProviders.List(); Assert.True(rspList.Count() > 0, "Atleast one replication recovery services provider should be present"); } } [Fact] public void DeleteRsp() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var fabric = client.ReplicationFabrics.Get(siteName); client.ReplicationRecoveryServicesProviders.Delete(fabric.Name, providerName); } } [Fact] public void PurgeRsp() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; string rspName = "74ef040f-fa15-4f71-9652-c27d5d19d575"; var fabric = client.ReplicationFabrics.Get(siteName); client.ReplicationRecoveryServicesProviders.Purge(fabric.Name, rspName); } } [Fact] public void RefreshRsp() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var fabric = client.ReplicationFabrics.Get(siteName); client.ReplicationRecoveryServicesProviders.RefreshProvider(fabric.Name, providerName); var rsp = client.ReplicationRecoveryServicesProviders.Get(fabric.Name, providerName); Assert.NotNull(rsp.Id); } } [Fact] public void GetContainer() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var fabricResponse = client.ReplicationFabrics.Get(siteName); var protectionContainerList = client.ReplicationProtectionContainers.ListByReplicationFabrics(fabricResponse.Name).ToList(); var protectionContainer = client.ReplicationProtectionContainers.Get(fabricResponse.Name, protectionContainerList.FirstOrDefault().Name); Assert.NotNull(protectionContainer.Properties.FriendlyName); Assert.NotNull(protectionContainer.Name); Assert.NotNull(protectionContainer.Id); } } [Fact] public void EnumerateContainer() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var fabricResponse = client.ReplicationFabrics.Get(siteName); var protectionContainerList = client.ReplicationProtectionContainers.ListByReplicationFabrics(fabricResponse.Name).ToList(); Assert.True(protectionContainerList.Count > 0, "Atleast one container should be present."); } } [Fact] public void ListAllContainers() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var fabricResponse = client.ReplicationFabrics.Get(siteName); var protectionContainerList = client.ReplicationProtectionContainers.List().ToList(); Assert.True(protectionContainerList.Count > 0, "Atleast one container should be present."); } } [Fact] public void CreatePolicy() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; HyperVReplicaAzurePolicyInput h2ASpecificInput = new HyperVReplicaAzurePolicyInput() { RecoveryPointHistoryDuration = 4, ApplicationConsistentSnapshotFrequencyInHours = 2, ReplicationInterval = 300, OnlineReplicationStartTime = null, StorageAccounts = new List<string>() { storageAccountId } }; CreatePolicyInputProperties inputProperties = new CreatePolicyInputProperties() { ProviderSpecificInput = h2ASpecificInput }; CreatePolicyInput input = new CreatePolicyInput() { Properties = inputProperties }; var response = client.ReplicationPolicies.Create(policyName, input); var policy = client.ReplicationPolicies.Get(policyName); } } [Fact] public void GetPolicy() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var policy = client.ReplicationPolicies.Get(policyName); Assert.NotNull(policy.Id); Assert.NotNull(policy.Name); } } [Fact] public void ListPolicy() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var policyList = client.ReplicationPolicies.List(); } } [Fact] public void UpdatePolicy() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; HyperVReplicaAzurePolicyInput h2ASpecificInput = new HyperVReplicaAzurePolicyInput() { RecoveryPointHistoryDuration = 3, ApplicationConsistentSnapshotFrequencyInHours = 2, ReplicationInterval = 300, OnlineReplicationStartTime = null, StorageAccounts = new List<string>() { "/subscriptions/c183865e-6077-46f2-a3b1-deb0f4f4650a/resourceGroups/siterecoveryprod1/providers/Microsoft.Storage/storageAccounts/storavrai" } }; UpdatePolicyInputProperties inputProperties = new UpdatePolicyInputProperties() { ReplicationProviderSettings = h2ASpecificInput }; UpdatePolicyInput input = new UpdatePolicyInput() { Properties = inputProperties }; var policy = client.ReplicationPolicies.Update(policyName, input); var response = client.ReplicationPolicies.Get(policyName); Assert.NotNull(response.Id); Assert.NotNull(response.Name); } } [Fact] public void DeletePolicy() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; client.ReplicationPolicies.Delete(policyName); } } [Fact] public void CreatePCMapping() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var fabric = client.ReplicationFabrics.Get(siteName); var protectionContainerList = client.ReplicationProtectionContainers.ListByReplicationFabrics(fabric.Name).ToList(); var protectionContainer = client.ReplicationProtectionContainers.Get(fabric.Name, protectionContainerList.FirstOrDefault().Name); var policy = client.ReplicationPolicies.Get(policyName); CreateProtectionContainerMappingInputProperties containerMappingInputProperties = new CreateProtectionContainerMappingInputProperties() { PolicyId = policy.Id, ProviderSpecificInput = new ReplicationProviderSpecificContainerMappingInput(), TargetProtectionContainerId = recoveryCloud }; CreateProtectionContainerMappingInput containerMappingInput = new CreateProtectionContainerMappingInput() { Properties = containerMappingInputProperties }; var response = client.ReplicationProtectionContainerMappings.Create( fabric.Name, protectionContainer.Name, protectionContainerMappingName, containerMappingInput); var protectionContainerMapping = client.ReplicationProtectionContainerMappings.Get( fabric.Name, protectionContainer.Name, protectionContainerMappingName); Assert.NotNull(protectionContainerMapping.Id); } } [Fact] public void GetPCMapping() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var fabric = client.ReplicationFabrics.Get(siteName); var protectionContainerList = client.ReplicationProtectionContainers.ListByReplicationFabrics(fabric.Name).ToList(); var protectionContainer = client.ReplicationProtectionContainers.Get(fabric.Name, protectionContainerList.FirstOrDefault().Name); var protectionContainerMapping = client.ReplicationProtectionContainerMappings.Get( fabric.Name, protectionContainer.Name, protectionContainerMappingName); Assert.NotNull(protectionContainerMapping.Id); } } [Fact] public void EnumeratePCMapping() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var fabric = client.ReplicationFabrics.Get(siteName); var protectionContainer = client.ReplicationProtectionContainers.ListByReplicationFabrics(fabric.Name).FirstOrDefault(); var protectionContainerMapping = client.ReplicationProtectionContainerMappings.ListByReplicationProtectionContainers(fabric.Name, protectionContainer.Name); } } [Fact] public void ListAllPCMapping() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var protectionContainerMapping = client.ReplicationProtectionContainerMappings.List(); } } [Fact] public void DeletePCMapping() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var fabric = client.ReplicationFabrics.Get(siteName); var protectionContainerList = client.ReplicationProtectionContainers.ListByReplicationFabrics(fabric.Name).ToList(); var protectionContainer = client.ReplicationProtectionContainers.Get(fabric.Name, protectionContainerList.FirstOrDefault().Name); client.ReplicationProtectionContainerMappings.Delete( fabric.Name, protectionContainer.Name, protectionContainerMappingName, new RemoveProtectionContainerMappingInput()); } } [Fact] public void PurgePCMapping() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var fabric = client.ReplicationFabrics.Get(siteName); var protectionContainer = client.ReplicationProtectionContainers.ListByReplicationFabrics(fabric.Name).FirstOrDefault(); client.ReplicationProtectionContainerMappings.Purge(fabric.Name, protectionContainer.Name, protectionContainerMappingName); } } [Fact] public void GetProtectableItem() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var fabric = client.ReplicationFabrics.Get(siteName); var protectionContainerList = client.ReplicationProtectionContainers.ListByReplicationFabrics(fabric.Name).ToList(); var protectionContainer = client.ReplicationProtectionContainers.Get(fabric.Name, protectionContainerList.FirstOrDefault().Name); var protectableItemList = client.ReplicationProtectableItems.ListByReplicationProtectionContainers( fabric.Name, protectionContainer.Name); var protectableItem = protectableItemList.First(item => item.Properties.FriendlyName.Equals(vmName, StringComparison.OrdinalIgnoreCase)); Assert.NotNull(protectableItem.Id); } } [Fact] public void EnumerateProtectableItem() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var fabric = client.ReplicationFabrics.Get(siteName); var protectionContainerList = client.ReplicationProtectionContainers.ListByReplicationFabrics(fabric.Name).ToList(); var protectionContainer = client.ReplicationProtectionContainers.Get(fabric.Name, protectionContainerList.FirstOrDefault().Name); var protectableItemList = client.ReplicationProtectableItems.ListByReplicationProtectionContainers( fabric.Name, protectionContainer.Name).ToList(); Assert.True(protectableItemList.Count > 0, "Atleast one protectable item should be present."); } } [Fact] public void CreateProtectedItem() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var fabric = client.ReplicationFabrics.Get(siteName); var policy = client.ReplicationPolicies.Get(policyName); var protectionContainer = client.ReplicationProtectionContainers.ListByReplicationFabrics(fabric.Name).FirstOrDefault(); var protectableItemList = client.ReplicationProtectableItems.ListByReplicationProtectionContainers( fabric.Name, protectionContainer.Name).ToList(); var protectableItem = protectableItemList.First(item => item.Properties.FriendlyName.Equals(vmName2, StringComparison.OrdinalIgnoreCase)); var vhdId = (protectableItem.Properties.CustomDetails as HyperVVirtualMachineDetails).DiskDetails[0].VhdId; DiskDetails osDisk = (protectableItem.Properties.CustomDetails as HyperVVirtualMachineDetails).DiskDetails .FirstOrDefault(item => item.VhdType == "OperatingSystem"); if (osDisk != null) { vhdId = osDisk.VhdId; } HyperVReplicaAzureEnableProtectionInput h2AEnableDRInput = new HyperVReplicaAzureEnableProtectionInput() { HvHostVmId = (protectableItem.Properties.CustomDetails as HyperVVirtualMachineDetails).SourceItemId, OsType = "Windows", VhdId = vhdId, VmName = protectableItem.Properties.FriendlyName, TargetStorageAccountId = (policy.Properties.ProviderSpecificDetails as HyperVReplicaAzurePolicyDetails) .ActiveStorageAccountId, TargetAzureV2ResourceGroupId = targetResourceGroup, TargetAzureVmName = protectableItem.Properties.FriendlyName }; EnableProtectionInputProperties enableDRInputProperties = new EnableProtectionInputProperties() { PolicyId = policy.Id, ProtectableItemId = protectableItem.Id, ProviderSpecificDetails = h2AEnableDRInput }; EnableProtectionInput enableDRInput = new EnableProtectionInput() { Properties = enableDRInputProperties }; client.ReplicationProtectedItems.Create(fabric.Name, protectionContainer.Name, protectableItem.Properties.FriendlyName, enableDRInput); var protectedItem = client.ReplicationProtectedItems.Get(siteName, protectionContainer.Name, vmName2); } } [Fact] public void GetProtectedItem() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var protectionContainerList = client.ReplicationProtectionContainers.ListByReplicationFabrics(siteName).ToList(); var protectionContainer = client.ReplicationProtectionContainers.Get(siteName, protectionContainerList.FirstOrDefault().Name); var protectedItem = client.ReplicationProtectedItems.Get(siteName, protectionContainer.Name, vmName); Assert.NotNull(protectedItem.Id); } } [Fact] public void EnumerateProtectedItem() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var protectionContainer = client.ReplicationProtectionContainers.ListByReplicationFabrics(siteName).FirstOrDefault(); var protectedItemsList = client.ReplicationProtectedItems.ListByReplicationProtectionContainers(siteName, protectionContainer.Name); Assert.NotNull(protectedItemsList); } } [Fact] public void ListAllProtectedItem() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var protectedItemsList = client.ReplicationProtectedItems.List(); Assert.NotNull(protectedItemsList); } } [Fact] public void UpdateProtectedItem() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var protectionContainer = client.ReplicationProtectionContainers.ListByReplicationFabrics(siteName).FirstOrDefault(); var protectedItem = client.ReplicationProtectedItems.Get(siteName, protectionContainer.Name, vmName2); VMNicInputDetails nicInput = new VMNicInputDetails() { NicId = (protectedItem.Properties.ProviderSpecificDetails as HyperVReplicaAzureReplicationDetails).VmNics[0].NicId, RecoveryVMSubnetName = "Subnet1", SelectionType = "SelectedByUser" }; UpdateReplicationProtectedItemInputProperties updateInputProperties = new UpdateReplicationProtectedItemInputProperties() { RecoveryAzureVMName = protectedItem.Properties.FriendlyName, RecoveryAzureVMSize = "Basic_A0", SelectedRecoveryAzureNetworkId = azureNetworkId, VmNics = new List<VMNicInputDetails>() { nicInput }, LicenseType = LicenseType.WindowsServer, ProviderSpecificDetails = new HyperVReplicaAzureUpdateReplicationProtectedItemInput() { RecoveryAzureV2ResourceGroupId = targetResourceGroup } }; UpdateReplicationProtectedItemInput updateInput = new UpdateReplicationProtectedItemInput() { Properties = updateInputProperties }; var response = client.ReplicationProtectedItems.Update(siteName, protectionContainer.Name, vmName2, updateInput); var updatedProtecteditem = client.ReplicationProtectedItems.Get(siteName, protectionContainer.Name, vmName2); } } [Fact] public void DeleteProtectedItem() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var protectionContainer = client.ReplicationProtectionContainers.ListByReplicationFabrics(siteName).FirstOrDefault(); DisableProtectionInputProperties inputProperties = new DisableProtectionInputProperties() { DisableProtectionReason = DisableProtectionReason.NotSpecified, ReplicationProviderInput = new DisableProtectionProviderSpecificInput() }; DisableProtectionInput input = new DisableProtectionInput() { Properties = inputProperties }; client.ReplicationProtectedItems.Delete(siteName, protectionContainer.Name, vmName2, input); } } [Fact] public void PurgeProtectedItem() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var protectionContainer = client.ReplicationProtectionContainers.ListByReplicationFabrics(siteName).FirstOrDefault(); client.ReplicationProtectedItems.Purge(siteName, protectionContainer.Name, vmName); } } [Fact(Skip = "ReRecord due to CR change")] public void RepairReplication() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var protectionContainer = client.ReplicationProtectionContainers.ListByReplicationFabrics(siteName).FirstOrDefault(); client.ReplicationProtectedItems.RepairReplication(siteName, protectionContainer.Name, vmName2); var protectedItem = client.ReplicationProtectedItems.Get(siteName, protectionContainer.Name, vmName2); Assert.NotNull(protectedItem.Id); } } [Fact(Skip = "ReRecord due to CR change")] public void TestFailover() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var protectionContainer = client.ReplicationProtectionContainers.ListByReplicationFabrics(siteName).FirstOrDefault(); var protectedItem = client.ReplicationProtectedItems.Get(siteName, protectionContainer.Name, vmName); string networkId = (protectedItem.Properties.ProviderSpecificDetails as HyperVReplicaAzureReplicationDetails) .SelectedRecoveryAzureNetworkId; HyperVReplicaAzureFailoverProviderInput h2AFOInput = new HyperVReplicaAzureFailoverProviderInput() { VaultLocation = "West US", }; TestFailoverInputProperties tfoInputProperties = new TestFailoverInputProperties() { NetworkId = networkId, NetworkType = string.IsNullOrEmpty(networkId) ? null : "VmNetworkAsInput", SkipTestFailoverCleanup = true.ToString(), ProviderSpecificDetails = h2AFOInput }; TestFailoverInput tfoInput = new TestFailoverInput() { Properties = tfoInputProperties }; var response = client.ReplicationProtectedItems.TestFailover(siteName, protectionContainer.Name, vmName, tfoInput); } } [Fact(Skip = "ReRecord due to CR change")] public void TestFailoverCleanup() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var protectionContainer = client.ReplicationProtectionContainers.ListByReplicationFabrics(siteName).FirstOrDefault(); var protectedItem = client.ReplicationProtectedItems.Get(siteName, protectionContainer.Name, vmName); TestFailoverCleanupInputProperties inputProperties = new TestFailoverCleanupInputProperties() { Comments = "Cleaning up" }; TestFailoverCleanupInput input = new TestFailoverCleanupInput() { Properties = inputProperties }; client.ReplicationProtectedItems.TestFailoverCleanup( siteName, protectionContainer.Name, vmName, input); } } [Fact] public void PlannedFailover() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var protectionContainer = client.ReplicationProtectionContainers.ListByReplicationFabrics(siteName).FirstOrDefault(); var protectedItem = client.ReplicationProtectedItems.Get(siteName, protectionContainer.Name, vmName2); PlannedFailoverInputProperties inputProperties = new PlannedFailoverInputProperties(); if (protectedItem.Properties.ActiveLocation == "Recovery") { HyperVReplicaAzureFailbackProviderInput h2AFailbackInput = new HyperVReplicaAzureFailbackProviderInput() { RecoveryVmCreationOption = "NoAction", DataSyncOption = "ForSynchronization" }; inputProperties.ProviderSpecificDetails = h2AFailbackInput; } else { HyperVReplicaAzureFailoverProviderInput h2AFailoverInput = new HyperVReplicaAzureFailoverProviderInput() { VaultLocation = "West US" }; inputProperties.ProviderSpecificDetails = h2AFailoverInput; } PlannedFailoverInput input = new PlannedFailoverInput() { Properties = inputProperties }; client.ReplicationProtectedItems.PlannedFailover(siteName, protectionContainer.Name, vmName2, input); } } [Fact(Skip = "ReRecord due to CR change")] public void UnplannedFailover() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var protectionContainer = client.ReplicationProtectionContainers.ListByReplicationFabrics(siteName).FirstOrDefault(); var protectedItem = client.ReplicationProtectedItems.Get(siteName, protectionContainer.Name, vmName2); HyperVReplicaAzureFailoverProviderInput h2AFailoverInput = new HyperVReplicaAzureFailoverProviderInput() { VaultLocation = "West US" }; UnplannedFailoverInputProperties inputProperties = new UnplannedFailoverInputProperties() { FailoverDirection = "PrimaryToRecovery", SourceSiteOperations = "NotRequired", ProviderSpecificDetails = h2AFailoverInput }; UnplannedFailoverInput input = new UnplannedFailoverInput() { Properties = inputProperties }; var response = client.ReplicationProtectedItems.UnplannedFailover(siteName, protectionContainer.Name, vmName2, input); var updatedProtectedItem = client.ReplicationProtectedItems.Get(siteName, protectionContainer.Name, vmName2); } } [Fact] public void CommitFailover() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var protectionContainer = client.ReplicationProtectionContainers.ListByReplicationFabrics(siteName).FirstOrDefault(); client.ReplicationProtectedItems.FailoverCommit(siteName, protectionContainer.Name, vmName2); } } [Fact(Skip = "ReRecord due to CR change")] public void Reprotect() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var protectionContainer = client.ReplicationProtectionContainers.ListByReplicationFabrics(siteName).FirstOrDefault(); var protectableItem = client.ReplicationProtectableItems.ListByReplicationProtectionContainers( siteName, protectionContainer.Name).FirstOrDefault(item => item.Properties.FriendlyName.Equals(vmName2, StringComparison.OrdinalIgnoreCase)); var protectedItem = client.ReplicationProtectedItems.Get(siteName, protectionContainer.Name, vmName2); var vhdId = (protectableItem.Properties.CustomDetails as HyperVVirtualMachineDetails).DiskDetails[0].VhdId; DiskDetails osDisk = (protectableItem.Properties.CustomDetails as HyperVVirtualMachineDetails).DiskDetails .FirstOrDefault(item => item.VhdType == "OperatingSystem"); if (osDisk != null) { vhdId = osDisk.VhdId; } HyperVReplicaAzureReprotectInput h2AInput = new HyperVReplicaAzureReprotectInput() { HvHostVmId = (protectableItem.Properties.CustomDetails as HyperVVirtualMachineDetails).SourceItemId, OsType = "Windows", VHDId = vhdId, VmName = protectableItem.Properties.FriendlyName, StorageAccountId = (protectedItem.Properties.ProviderSpecificDetails as HyperVReplicaAzureReplicationDetails).RecoveryAzureStorageAccount }; ReverseReplicationInputProperties inputProperties = new ReverseReplicationInputProperties() { FailoverDirection = "PrimaryToRecovery", ProviderSpecificDetails = h2AInput }; ReverseReplicationInput input = new ReverseReplicationInput() { Properties = inputProperties }; client.ReplicationProtectedItems.Reprotect(siteName, protectionContainer.Name, vmName2, input); } } [Fact] public void GetRecoveryPoints() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var protectionContainer = client.ReplicationProtectionContainers.ListByReplicationFabrics(siteName).FirstOrDefault(); var rps = client.RecoveryPoints.ListByReplicationProtectedItems(siteName, protectionContainer.Name, vmName2).ToList(); var recoveryPoint = client.RecoveryPoints.Get(siteName, protectionContainer.Name, vmName2, rps[rps.Count() / 2].Name); } } [Fact] public void ListRecoveryPoints() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var protectionContainer = client.ReplicationProtectionContainers.ListByReplicationFabrics(siteName).FirstOrDefault(); var rps = client.RecoveryPoints.ListByReplicationProtectedItems(siteName, protectionContainer.Name, vmName); } } [Fact] public void ApplyRecoveryPoint() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var protectionContainer = client.ReplicationProtectionContainers.ListByReplicationFabrics(siteName).FirstOrDefault(); var rps = client.RecoveryPoints.ListByReplicationProtectedItems(siteName, protectionContainer.Name, vmName2).ToList(); HyperVReplicaAzureApplyRecoveryPointInput h2APitInput = new HyperVReplicaAzureApplyRecoveryPointInput() { VaultLocation = "West US" }; ApplyRecoveryPointInputProperties inputProperties = new ApplyRecoveryPointInputProperties() { RecoveryPointId = rps[rps.Count()/2].Id, ProviderSpecificDetails = h2APitInput }; ApplyRecoveryPointInput input = new ApplyRecoveryPointInput() { Properties = inputProperties }; client.ReplicationProtectedItems.ApplyRecoveryPoint(siteName, protectionContainer.Name, vmName2, input); } } [Fact] public void CreateRecoveryPlan() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var fabric = client.ReplicationFabrics.Get(siteName); var protectionContainer = client.ReplicationProtectionContainers.ListByReplicationFabrics(siteName).FirstOrDefault(); var protectedItem1 = client.ReplicationProtectedItems.Get(siteName, protectionContainer.Name, vmName); RecoveryPlanProtectedItem rpVm1 = new RecoveryPlanProtectedItem() { Id = protectedItem1.Id, VirtualMachineId = protectedItem1.Name }; RecoveryPlanGroup rpGroup = new RecoveryPlanGroup() { GroupType = RecoveryPlanGroupType.Boot, ReplicationProtectedItems = new List<RecoveryPlanProtectedItem>() { rpVm1}, StartGroupActions = new List<RecoveryPlanAction>(), EndGroupActions = new List<RecoveryPlanAction>() }; CreateRecoveryPlanInputProperties inputProperties = new CreateRecoveryPlanInputProperties() { PrimaryFabricId = fabric.Id, RecoveryFabricId = recoveryCloud, FailoverDeploymentModel = FailoverDeploymentModel.ResourceManager, Groups = new List<RecoveryPlanGroup>() { rpGroup } }; CreateRecoveryPlanInput input = new CreateRecoveryPlanInput() { Properties = inputProperties }; client.ReplicationRecoveryPlans.Create(rpName, input); var rp = client.ReplicationRecoveryPlans.Get(rpName); } } [Fact] public void GetRecoveryPlan() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var rp = client.ReplicationRecoveryPlans.Get(rpName); } } [Fact] public void UpdateRecoveryPlan() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var fabric = client.ReplicationFabrics.Get(siteName); var protectionContainer = client.ReplicationProtectionContainers.ListByReplicationFabrics(siteName).FirstOrDefault(); var protectedItem2 = client.ReplicationProtectedItems.Get(siteName, protectionContainer.Name, vmName2); RecoveryPlanProtectedItem rpVm2 = new RecoveryPlanProtectedItem() { Id = protectedItem2.Id, VirtualMachineId = protectedItem2.Name }; RecoveryPlanGroup rpGroup = new RecoveryPlanGroup() { GroupType = RecoveryPlanGroupType.Boot, ReplicationProtectedItems = new List<RecoveryPlanProtectedItem>() { rpVm2 }, StartGroupActions = new List<RecoveryPlanAction>(), EndGroupActions = new List<RecoveryPlanAction>() }; UpdateRecoveryPlanInputProperties inputProperties = new UpdateRecoveryPlanInputProperties() { Groups = new List<RecoveryPlanGroup>() { rpGroup } }; UpdateRecoveryPlanInput input = new UpdateRecoveryPlanInput() { Properties = inputProperties }; client.ReplicationRecoveryPlans.Update(rpName, input); var rp = client.ReplicationRecoveryPlans.Get(rpName); } } [Fact] public void DeleteRecoveryPlan() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; client.ReplicationRecoveryPlans.Delete(rpName); } } [Fact(Skip = "ReRecord due to CR change")] public void RPTestFailover() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; RecoveryPlanHyperVReplicaAzureFailoverInput h2AInput = new RecoveryPlanHyperVReplicaAzureFailoverInput() { VaultLocation = "West US" }; RecoveryPlanTestFailoverInputProperties inputProperties = new RecoveryPlanTestFailoverInputProperties() { NetworkId = azureNetworkId, NetworkType = string.IsNullOrEmpty(azureNetworkId) ? null : "VmNetworkAsInput", SkipTestFailoverCleanup = true.ToString(), ProviderSpecificDetails = new List<RecoveryPlanProviderSpecificFailoverInput>() { h2AInput } }; RecoveryPlanTestFailoverInput input = new RecoveryPlanTestFailoverInput() { Properties = inputProperties }; client.ReplicationRecoveryPlans.TestFailover(rpName, input); var rp = client.ReplicationRecoveryPlans.Get(rpName); } } [Fact(Skip = "ReRecord due to CR change")] public void RPTestFailoverCleanup() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; RecoveryPlanTestFailoverCleanupInputProperties inputProperties = new RecoveryPlanTestFailoverCleanupInputProperties() { Comments = "Cleaning up" }; RecoveryPlanTestFailoverCleanupInput input = new RecoveryPlanTestFailoverCleanupInput() { Properties = inputProperties }; client.ReplicationRecoveryPlans.TestFailoverCleanup(rpName, input); var rp = client.ReplicationRecoveryPlans.Get(rpName); } } [Fact(Skip = "ReRecord due to CR change")] public void RPPlannedFailover() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; RecoveryPlanHyperVReplicaAzureFailoverInput h2AInput = new RecoveryPlanHyperVReplicaAzureFailoverInput() { VaultLocation = "West US" }; RecoveryPlanPlannedFailoverInputProperties inputProperties = new RecoveryPlanPlannedFailoverInputProperties() { FailoverDirection = PossibleOperationsDirections.PrimaryToRecovery, ProviderSpecificDetails = new List<RecoveryPlanProviderSpecificFailoverInput>() { h2AInput } }; RecoveryPlanPlannedFailoverInput input = new RecoveryPlanPlannedFailoverInput() { Properties = inputProperties }; client.ReplicationRecoveryPlans.PlannedFailover(rpName, input); var rp = client.ReplicationRecoveryPlans.Get(rpName); } } [Fact(Skip = "ReRecord due to CR change")] public void RPUnplannedFailover() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; RecoveryPlanHyperVReplicaAzureFailoverInput h2AInput = new RecoveryPlanHyperVReplicaAzureFailoverInput() { VaultLocation = "West US" }; RecoveryPlanUnplannedFailoverInputProperties inputProperties = new RecoveryPlanUnplannedFailoverInputProperties() { FailoverDirection = PossibleOperationsDirections.PrimaryToRecovery, SourceSiteOperations = SourceSiteOperations.NotRequired, ProviderSpecificDetails = new List<RecoveryPlanProviderSpecificFailoverInput>() { h2AInput } }; RecoveryPlanUnplannedFailoverInput input = new RecoveryPlanUnplannedFailoverInput() { Properties = inputProperties }; client.ReplicationRecoveryPlans.UnplannedFailover(rpName, input); var rp = client.ReplicationRecoveryPlans.Get(rpName); } } [Fact(Skip = "ReRecord due to CR change")] public void RPFailoverCommit() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; client.ReplicationRecoveryPlans.FailoverCommit(rpName); var rp = client.ReplicationRecoveryPlans.Get(rpName); } } [Fact(Skip = "ReRecord due to CR change")] public void RPFailback() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; RecoveryPlanHyperVReplicaAzureFailbackInput h2AInput = new RecoveryPlanHyperVReplicaAzureFailbackInput() { DataSyncOption = DataSyncStatus.ForSynchronization, RecoveryVmCreationOption = AlternateLocationRecoveryOption.NoAction }; RecoveryPlanPlannedFailoverInputProperties inputProperties = new RecoveryPlanPlannedFailoverInputProperties() { FailoverDirection = PossibleOperationsDirections.RecoveryToPrimary, ProviderSpecificDetails = new List<RecoveryPlanProviderSpecificFailoverInput>() { h2AInput } }; RecoveryPlanPlannedFailoverInput input = new RecoveryPlanPlannedFailoverInput() { Properties = inputProperties }; client.ReplicationRecoveryPlans.PlannedFailover(rpName, input); var rp = client.ReplicationRecoveryPlans.Get(rpName); } } [Fact(Skip = "ReRecord due to CR change")] public void RPReprotect() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; client.ReplicationRecoveryPlans.Reprotect(rpName); var rp = client.ReplicationRecoveryPlans.Get(rpName); } } [Fact] public void CreateAlertSettings() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; ConfigureAlertRequestProperties properties = new ConfigureAlertRequestProperties() { SendToOwners = false.ToString(), CustomEmailAddresses = new List<string>() { emailAddress }, Locale = "en-US" }; ConfigureAlertRequest request = new ConfigureAlertRequest() { Properties = properties }; client.ReplicationAlertSettings.Create(alertSettingName, request); var alertSetting = client.ReplicationAlertSettings.Get(alertSettingName); } } [Fact] public void GetAlertSettings() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var alertSetting = client.ReplicationAlertSettings.Get(alertSettingName); } } [Fact] public void ListAlertSettings() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var alertSetting = client.ReplicationAlertSettings.List(); } } [Fact] public void GetReplicationEvent() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var events = client.ReplicationEvents.List().ToList(); var replicationEvent = client.ReplicationEvents.Get(events[0].Name); } } [Fact] public void ListReplicationEvent() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var events = client.ReplicationEvents.List(); } } [Fact] public void GetNetworks() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var network = client.ReplicationNetworks.Get(vmmFabric, vmNetworkName); } } [Fact] public void ListNetworks() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var networkList = client.ReplicationNetworks.List(); } } [Fact] public void EnumerateNetworks() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var networkList = client.ReplicationNetworks.ListByReplicationFabrics(vmmFabric); } } [Fact] public void CreateNetworkMapping() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var network = client.ReplicationNetworks.Get(vmmFabric, vmNetworkName); CreateNetworkMappingInputProperties inputProperties = new CreateNetworkMappingInputProperties() { RecoveryFabricName = recoveryCloud, RecoveryNetworkId = azureNetworkId, FabricSpecificDetails = new VmmToAzureCreateNetworkMappingInput() }; CreateNetworkMappingInput input = new CreateNetworkMappingInput() { Properties = inputProperties }; client.ReplicationNetworkMappings.Create(vmmFabric, vmNetworkName, networkMappingName, input); var networkMapping = client.ReplicationNetworkMappings.Get(vmmFabric, vmNetworkName, networkMappingName); } } [Fact] public void GetNetworkMapping() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var networkMapping = client.ReplicationNetworkMappings.Get(vmmFabric, vmNetworkName, networkMappingName); } } [Fact] public void ListNetworkMapping() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var networkMappingList = client.ReplicationNetworkMappings.List(); } } [Fact] public void EnumerateNetworkMapping() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; var networkMappingList = client.ReplicationNetworkMappings.ListByReplicationNetworks(vmmFabric, vmNetworkName); } } [Fact] public void UpdateNetworkMapping() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; UpdateNetworkMappingInputProperties inputProperties = new UpdateNetworkMappingInputProperties() { RecoveryFabricName = recoveryCloud, RecoveryNetworkId = azureNetworkId, FabricSpecificDetails = new VmmToAzureUpdateNetworkMappingInput() }; UpdateNetworkMappingInput input = new UpdateNetworkMappingInput() { Properties = inputProperties }; client.ReplicationNetworkMappings.Update(vmmFabric, vmNetworkName, networkMappingName, input); var networkMapping = client.ReplicationNetworkMappings.Get(vmmFabric, vmNetworkName, networkMappingName); } } [Fact] public void DeleteNetworkMapping() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context); var client = testHelper.SiteRecoveryClient; client.ReplicationNetworkMappings.Delete(vmmFabric, vmNetworkName, networkMappingName); } } [Fact] public void MigrateToAad() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context, "canaryexproute", "IbizaV2ATest"); var client = testHelper.SiteRecoveryClient; client.ReplicationFabrics.MigrateToAad("38de67c62c2b231fb647b060df06a8a69da7e305c44db6646693b7470d709c87"); } } [Fact] public void ListEventByQuery() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context, "canaryexproute", "IbizaV2ATest"); var client = testHelper.SiteRecoveryClient; var querydata = new ODataQuery<EventQueryParameter>("Severity eq 'Critical'"); client.ReplicationEvents.List(querydata); } } [Fact] public void GetHealthDetails() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context, "canaryexproute", "IbizaV2ATest"); var client = testHelper.SiteRecoveryClient; client.ReplicationVaultHealth.Get(); } } [Fact] public void GetReplicationEligibilityResults() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context, "testRg1", ""); var client = testHelper.SiteRecoveryClient; var replicationEligibilityResults = client.ReplicationEligibilityResults.Get(a2aVirtualMachineToValidate); Assert.NotNull(replicationEligibilityResults); } } [Fact] public void EnumerateReplicationEligibilityResults() { using (var context = MockContext.Start(this.GetType())) { testHelper.Initialize(context, "testRg1", ""); var client = testHelper.SiteRecoveryClient; var replicationEligibilityResultsCollection = client.ReplicationEligibilityResults.List(a2aVirtualMachineToValidate); Assert.NotNull(replicationEligibilityResultsCollection); } } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Trybot.CircuitBreaker; using Trybot.CircuitBreaker.Exceptions; namespace Trybot.Tests.CircuitBreakerTests { [TestClass] public class CircuitBreakerTests { private IBotPolicy<TResult> CreatePolicy<TResult>(CircuitBreakerConfiguration<TResult> conf, DefaultCircuitBreakerStrategyConfiguration strConf) => new BotPolicy<TResult>(config => config .Configure(botconfig => botconfig .CircuitBreaker(conf, strConf))); private CircuitBreakerConfiguration<TResult> CreateConfiguration<TResult>(TimeSpan openDuration) => new CircuitBreakerConfiguration<TResult>() .BrakeWhenExceptionOccurs(ex => true) .DurationOfOpen(openDuration); private DefaultCircuitBreakerStrategyConfiguration CreateStrategyConfiguration(int failure, int success) => new DefaultCircuitBreakerStrategyConfiguration() .FailureThresholdBeforeOpen(failure) .SuccessThresholdInHalfOpen(success); [TestMethod] public void CircuitBreakerTests_Ok() { var mockStore = new Mock<ICircuitStateHandler>(); mockStore.Setup(s => s.Read()).Returns(CircuitState.Closed).Verifiable(); var policy = new BotPolicy<int>(config => config .Configure(botconfig => botconfig .CircuitBreaker(conf => conf .WithStateHandler(mockStore.Object) .DurationOfOpen(TimeSpan.FromMilliseconds(200)), defConfig => defConfig .FailureThresholdBeforeOpen(2) .SuccessThresholdInHalfOpen(2)))); var counter = 0; policy.Execute((ex, t) => counter++, CancellationToken.None); Assert.AreEqual(1, counter); } [TestMethod] public async Task CircuitBreakerTests_Ok_Async() { var policy = this.CreatePolicy(this.CreateConfiguration<int>(TimeSpan.FromMilliseconds(200)), this.CreateStrategyConfiguration(2, 2)); var counter = 0; await policy.ExecuteAsync((ex, t) => counter++, CancellationToken.None); Assert.AreEqual(1, counter); } [TestMethod] public async Task CircuitBreakerTests_Ok_Async_Task() { var policy = this.CreatePolicy(this.CreateConfiguration<int>(TimeSpan.FromMilliseconds(200)), this.CreateStrategyConfiguration(2, 2)); var counter = 0; await policy.ExecuteAsync((ex, t) => { counter++; return Task.FromResult(0); }, CancellationToken.None); Assert.AreEqual(1, counter); } [TestMethod] public void CircuitBreakerTests_Brake_Then_Close() { var state = State.Closed; var successResult = 5; var policy = this.CreatePolicy(this.CreateConfiguration<int>(TimeSpan.FromMilliseconds(200)) .BrakeWhenResultIs(r => r != successResult) .OnClosed(() => state = State.Closed) .OnHalfOpen(() => state = State.HalfOpen) .OnOpen(ts => { state = State.Open; Assert.AreEqual(TimeSpan.FromMilliseconds(200), ts); }), this.CreateStrategyConfiguration(2, 2)); var counter = 0; // brake the circuit policy.Execute((ctx, t) => successResult + 1, CancellationToken.None); Assert.ThrowsException<Exception>(() => policy.Execute((ctx, t) => throw new Exception(), CancellationToken.None)); Assert.AreEqual(State.Open, state); var openException = Assert.ThrowsException<CircuitOpenException>(() => policy.Execute((ctx, t) => 0, CancellationToken.None)); Assert.IsTrue(openException.RemainingOpenTime <= TimeSpan.FromMilliseconds(200) && openException.RemainingOpenTime > TimeSpan.FromMilliseconds(100)); // wait until the open duration is being expired Thread.Sleep(openException.RemainingOpenTime.Add(TimeSpan.FromMilliseconds(10))); // two calls will close the circuit policy.Execute((ctx, t) => { counter++; Assert.AreEqual(State.HalfOpen, state); return successResult; }, CancellationToken.None); policy.Execute((ctx, t) => { counter++; Assert.AreEqual(State.HalfOpen, state); return successResult; }, CancellationToken.None); Assert.AreEqual(State.Closed, state); Assert.AreEqual(2, counter); } [TestMethod] public async Task CircuitBreakerTests_Brake_Then_Close_Async() { var state = State.Closed; var successResult = 5; var policy = this.CreatePolicy(this.CreateConfiguration<int>(TimeSpan.FromMilliseconds(200)) .BrakeWhenResultIs(r => r != successResult) .OnClosed(() => state = State.Closed) .OnHalfOpen(() => state = State.HalfOpen) .OnOpen(ts => { state = State.Open; Assert.AreEqual(TimeSpan.FromMilliseconds(200), ts); }), this.CreateStrategyConfiguration(2, 2)); var counter = 0; // brake the circuit await policy.ExecuteAsync((ctx, t) => Task.FromResult(successResult + 1), CancellationToken.None); await Assert.ThrowsExceptionAsync<NullReferenceException>(async () => await policy.ExecuteAsync((ctx, t) => { object o = null; o.GetHashCode(); return Task.FromResult(0); }, CancellationToken.None)); Assert.AreEqual(State.Open, state); var openException = await Assert.ThrowsExceptionAsync<CircuitOpenException>(() => policy.ExecuteAsync((ctx, t) => 0, CancellationToken.None)); Assert.IsTrue(openException.RemainingOpenTime <= TimeSpan.FromMilliseconds(200) && openException.RemainingOpenTime > TimeSpan.FromMilliseconds(100)); // wait until the open duration is being expired Thread.Sleep(openException.RemainingOpenTime.Add(TimeSpan.FromMilliseconds(10))); // two calls will close the circuit await policy.ExecuteAsync((ctx, t) => { counter++; Assert.AreEqual(State.HalfOpen, state); return Task.FromResult(successResult); }, CancellationToken.None); await policy.ExecuteAsync((ctx, t) => { counter++; Assert.AreEqual(State.HalfOpen, state); return successResult; }, CancellationToken.None); Assert.AreEqual(State.Closed, state); Assert.AreEqual(2, counter); } [TestMethod] [Ignore] // This test is very undeterministic, used only for local testing public void CircuitBreakerTests_Brake_Then_Only_Allow_One_Execution_On_HalfOpen() { var state = State.Closed; var policy = this.CreatePolicy(this.CreateConfiguration<int>(TimeSpan.FromMilliseconds(200)) .OnClosed(() => state = State.Closed) .OnHalfOpen(() => state = State.HalfOpen) .OnOpen(ts => { state = State.Open; Assert.AreEqual(TimeSpan.FromMilliseconds(200), ts); }), this.CreateStrategyConfiguration(2, 2)); var counter = 0; // brake the circuit for (var i = 0; i < 2; i++) Assert.ThrowsException<InvalidOperationException>(() => policy.Execute((ctx, t) => throw new InvalidOperationException(), CancellationToken.None)); Assert.AreEqual(State.Open, state); var openException = Assert.ThrowsException<CircuitOpenException>(() => policy.Execute((ctx, t) => 0, CancellationToken.None)); // wait until the open duration is being expired Thread.Sleep(openException.RemainingOpenTime.Add(TimeSpan.FromMilliseconds(10))); // simulate fast parallel calls, the faster one will win and attempts to close the circuit, the other one will be rejected Parallel.For(0, 2, i => { try { policy.Execute((ctx, t) => { counter++; Assert.AreEqual(State.HalfOpen, state); Task.Delay(TimeSpan.FromMilliseconds(300), t).Wait(t); return 0; }, CancellationToken.None); } catch (Exception e) { Assert.IsInstanceOfType(e, typeof(HalfOpenExecutionLimitExceededException)); } }); Assert.AreEqual(State.HalfOpen, state); Assert.AreEqual(1, counter); // next call will close the circuit policy.Execute((ctx, t) => { counter++; Assert.AreEqual(State.HalfOpen, state); return 0; }, CancellationToken.None); Assert.AreEqual(State.Closed, state); Assert.AreEqual(2, counter); } [TestMethod] [Ignore] // This test is very undeterministic, used only for local testing public async Task CircuitBreakerTests_Brake_Then_Only_Allow_One_Execution_On_HalfOpen_Async() { var state = State.Closed; var policy = this.CreatePolicy(this.CreateConfiguration<int>(TimeSpan.FromMilliseconds(200)) .OnClosed(() => state = State.Closed) .OnHalfOpen(() => state = State.HalfOpen) .OnOpen(ts => { state = State.Open; Assert.AreEqual(TimeSpan.FromMilliseconds(200), ts); }), this.CreateStrategyConfiguration(2, 2)); var counter = 0; // brake the circuit for (var i = 0; i < 2; i++) await Assert.ThrowsExceptionAsync<NullReferenceException>(() => policy.ExecuteAsync((ctx, t) => { object o = null; o.GetHashCode(); return Task.FromResult(0); }, CancellationToken.None)); Assert.AreEqual(State.Open, state); var openException = await Assert.ThrowsExceptionAsync<CircuitOpenException>(() => policy.ExecuteAsync((ctx, t) => 0, CancellationToken.None)); // wait until the open duration is being expired Thread.Sleep(openException.RemainingOpenTime.Add(TimeSpan.FromMilliseconds(10))); // simulate fast parallel calls, the faster one will win and attempts to close the circuit, the other one will be rejected var tasks = new List<Task>(); for (var i = 0; i < 2; i++) { tasks.Add(Task.Run(async () => { try { await policy.ExecuteAsync(async (ctx, t) => { counter++; Assert.AreEqual(State.HalfOpen, state); await Task.Delay(TimeSpan.FromMilliseconds(300), t); return 0; }, CancellationToken.None); } catch (Exception e) { Assert.IsInstanceOfType(e, typeof(HalfOpenExecutionLimitExceededException)); } })); } await Task.WhenAll(tasks); Assert.AreEqual(State.HalfOpen, state); Assert.AreEqual(1, counter); // next call will close the circuit await policy.ExecuteAsync((ctx, t) => { counter++; Assert.AreEqual(State.HalfOpen, state); return 0; }, CancellationToken.None); Assert.AreEqual(State.Closed, state); Assert.AreEqual(2, counter); } } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // WriteOnceBlock.cs // // // A propagator block capable of receiving and storing only one message, ever. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Security; using System.Threading.Tasks.Dataflow.Internal; namespace System.Threading.Tasks.Dataflow { /// <summary>Provides a buffer for receiving and storing at most one element in a network of dataflow blocks.</summary> /// <typeparam name="T">Specifies the type of the data buffered by this dataflow block.</typeparam> [DebuggerDisplay("{DebuggerDisplayContent,nq}")] [DebuggerTypeProxy(typeof(WriteOnceBlock<>.DebugView))] public sealed class WriteOnceBlock<T> : IPropagatorBlock<T, T>, IReceivableSourceBlock<T>, IDebuggerDisplay { /// <summary>A registry used to store all linked targets and information about them.</summary> private readonly TargetRegistry<T> _targetRegistry; /// <summary>The cloning function.</summary> private readonly Func<T, T> _cloningFunction; /// <summary>The options used to configure this block's execution.</summary> private readonly DataflowBlockOptions _dataflowBlockOptions; /// <summary>Lazily initialized task completion source that produces the actual completion task when needed.</summary> private TaskCompletionSource<VoidResult> _lazyCompletionTaskSource; /// <summary>Whether all future messages should be declined.</summary> private bool _decliningPermanently; /// <summary>Whether block completion is disallowed.</summary> private bool _completionReserved; /// <summary>The header of the singly-assigned value.</summary> private DataflowMessageHeader _header; /// <summary>The singly-assigned value.</summary> private T _value; /// <summary>Gets the object used as the value lock.</summary> private object ValueLock { get { return _targetRegistry; } } /// <summary>Initializes the <see cref="WriteOnceBlock{T}"/>.</summary> /// <param name="cloningFunction"> /// The function to use to clone the data when offered to other blocks. /// This may be null to indicate that no cloning need be performed. /// </param> public WriteOnceBlock(Func<T, T> cloningFunction) : this(cloningFunction, DataflowBlockOptions.Default) { } /// <summary>Initializes the <see cref="WriteOnceBlock{T}"/> with the specified <see cref="DataflowBlockOptions"/>.</summary> /// <param name="cloningFunction"> /// The function to use to clone the data when offered to other blocks. /// This may be null to indicate that no cloning need be performed. /// </param> /// <param name="dataflowBlockOptions">The options with which to configure this <see cref="WriteOnceBlock{T}"/>.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="dataflowBlockOptions"/> is null (Nothing in Visual Basic).</exception> public WriteOnceBlock(Func<T, T> cloningFunction, DataflowBlockOptions dataflowBlockOptions) { // Validate arguments if (dataflowBlockOptions == null) throw new ArgumentNullException(nameof(dataflowBlockOptions)); Contract.EndContractBlock(); // Store the option _cloningFunction = cloningFunction; _dataflowBlockOptions = dataflowBlockOptions.DefaultOrClone(); // The target registry also serves as our ValueLock, // and thus must always be initialized, even if the block is pre-canceled, as // subsequent usage of the block may run through code paths that try to take this lock. _targetRegistry = new TargetRegistry<T>(this); // If a cancelable CancellationToken has been passed in, // we need to initialize the completion task's TCS now. if (dataflowBlockOptions.CancellationToken.CanBeCanceled) { _lazyCompletionTaskSource = new TaskCompletionSource<VoidResult>(); // If we've already had cancellation requested, do as little work as we have to // in order to be done. if (dataflowBlockOptions.CancellationToken.IsCancellationRequested) { _completionReserved = _decliningPermanently = true; // Cancel the completion task's TCS _lazyCompletionTaskSource.SetCanceled(); } else { // Handle async cancellation requests by declining on the target Common.WireCancellationToComplete( dataflowBlockOptions.CancellationToken, _lazyCompletionTaskSource.Task, state => ((WriteOnceBlock<T>)state).Complete(), this); } } #if FEATURE_TRACING DataflowEtwProvider etwLog = DataflowEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.DataflowBlockCreated(this, dataflowBlockOptions); } #endif } /// <summary>Asynchronously completes the block on another task.</summary> /// <remarks> /// This must only be called once all of the completion conditions are met. /// </remarks> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] private void CompleteBlockAsync(IList<Exception> exceptions) { Debug.Assert(_decliningPermanently, "We may get here only after we have started to decline permanently."); Debug.Assert(_completionReserved, "We may get here only after we have reserved completion."); Common.ContractAssertMonitorStatus(ValueLock, held: false); // If there is no exceptions list, we offer the message around, and then complete. // If there is an exception list, we complete without offering the message. if (exceptions == null) { // Offer the message to any linked targets and complete the block asynchronously to avoid blocking the caller var taskForOutputProcessing = new Task(state => ((WriteOnceBlock<T>)state).OfferToTargetsAndCompleteBlock(), this, Common.GetCreationOptionsForTask()); #if FEATURE_TRACING DataflowEtwProvider etwLog = DataflowEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.TaskLaunchedForMessageHandling( this, taskForOutputProcessing, DataflowEtwProvider.TaskLaunchedReason.OfferingOutputMessages, _header.IsValid ? 1 : 0); } #endif // Start the task handling scheduling exceptions Exception exception = Common.StartTaskSafe(taskForOutputProcessing, _dataflowBlockOptions.TaskScheduler); if (exception != null) CompleteCore(exception, storeExceptionEvenIfAlreadyCompleting: true); } else { // Complete the block asynchronously to avoid blocking the caller Task.Factory.StartNew(state => { Tuple<WriteOnceBlock<T>, IList<Exception>> blockAndList = (Tuple<WriteOnceBlock<T>, IList<Exception>>)state; blockAndList.Item1.CompleteBlock(blockAndList.Item2); }, Tuple.Create(this, exceptions), CancellationToken.None, Common.GetCreationOptionsForTask(), TaskScheduler.Default); } } /// <summary>Offers the message and completes the block.</summary> /// <remarks> /// This is called only once. /// </remarks> private void OfferToTargetsAndCompleteBlock() { // OfferToTargets calls to potentially multiple targets, each of which // could be faulty and throw an exception. OfferToTargets creates a // list of all such exceptions and returns it. // If _value is null, OfferToTargets does nothing. List<Exception> exceptions = OfferToTargets(); CompleteBlock(exceptions); } /// <summary>Completes the block.</summary> /// <remarks> /// This is called only once. /// </remarks> private void CompleteBlock(IList<Exception> exceptions) { // Do not invoke the CompletionTaskSource property if there is a chance that _lazyCompletionTaskSource // has not been initialized yet and we may have to complete normally, because that would defeat the // sole purpose of the TCS being lazily initialized. Debug.Assert(_lazyCompletionTaskSource == null || !_lazyCompletionTaskSource.Task.IsCompleted, "The task completion source must not be completed. This must be the only thread that ever completes the block."); // Save the linked list of targets so that it could be traversed later to propagate completion TargetRegistry<T>.LinkedTargetInfo linkedTargets = _targetRegistry.ClearEntryPoints(); // Complete the block's completion task if (exceptions != null && exceptions.Count > 0) { CompletionTaskSource.TrySetException(exceptions); } else if (_dataflowBlockOptions.CancellationToken.IsCancellationRequested) { CompletionTaskSource.TrySetCanceled(); } else { // Safely try to initialize the completion task's TCS with a cached completed TCS. // If our attempt succeeds (CompareExchange returns null), we have nothing more to do. // If the completion task's TCS was already initialized (CompareExchange returns non-null), // we have to complete that TCS instance. if (Interlocked.CompareExchange(ref _lazyCompletionTaskSource, Common.CompletedVoidResultTaskCompletionSource, null) != null) { _lazyCompletionTaskSource.TrySetResult(default(VoidResult)); } } // Now that the completion task is completed, we may propagate completion to the linked targets _targetRegistry.PropagateCompletion(linkedTargets); #if FEATURE_TRACING DataflowEtwProvider etwLog = DataflowEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.DataflowBlockCompleted(this); } #endif } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Fault"]/*' /> void IDataflowBlock.Fault(Exception exception) { if (exception == null) throw new ArgumentNullException(nameof(exception)); Contract.EndContractBlock(); CompleteCore(exception, storeExceptionEvenIfAlreadyCompleting: false); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Complete"]/*' /> public void Complete() { CompleteCore(exception: null, storeExceptionEvenIfAlreadyCompleting: false); } private void CompleteCore(Exception exception, bool storeExceptionEvenIfAlreadyCompleting) { Debug.Assert(exception != null || !storeExceptionEvenIfAlreadyCompleting, "When storeExceptionEvenIfAlreadyCompleting is set to true, an exception must be provided."); Contract.EndContractBlock(); bool thisThreadReservedCompletion = false; lock (ValueLock) { // Faulting from outside is allowed until we start declining permanently if (_decliningPermanently && !storeExceptionEvenIfAlreadyCompleting) return; // Decline further messages _decliningPermanently = true; // Reserve Completion. // If storeExceptionEvenIfAlreadyCompleting is true, we are here to fault the block, // because we couldn't launch the offer-and-complete task. // We have to retry to just complete. We do that by pretending completion wasn't reserved. if (!_completionReserved || storeExceptionEvenIfAlreadyCompleting) thisThreadReservedCompletion = _completionReserved = true; } // This call caused us to start declining further messages, // there's nothing more this block needs to do... complete it if we just reserved completion. if (thisThreadReservedCompletion) { List<Exception> exceptions = null; if (exception != null) { exceptions = new List<Exception>(); exceptions.Add(exception); } CompleteBlockAsync(exceptions); } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="TryReceive"]/*' /> public Boolean TryReceive(Predicate<T> filter, out T item) { // No need to take the outgoing lock, as we don't need to synchronize with other // targets, and _value only ever goes from null to non-null, not the other way around. // If we have a value, give it up. All receives on a successfully // completed WriteOnceBlock will return true, as long as the message // passes the filter (all messages pass a null filter). if (_header.IsValid && (filter == null || filter(_value))) { item = CloneItem(_value); return true; } // Otherwise, nothing to receive else { item = default(T); return false; } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="TryReceiveAll"]/*' /> Boolean IReceivableSourceBlock<T>.TryReceiveAll(out IList<T> items) { // Try to receive the one item this block may have. // If we can, give back an array of one item. Otherwise, // give back null. T item; if (TryReceive(null, out item)) { items = new T[] { item }; return true; } else { items = null; return false; } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="LinkTo"]/*' /> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] public IDisposable LinkTo(ITargetBlock<T> target, DataflowLinkOptions linkOptions) { // Validate arguments if (target == null) throw new ArgumentNullException(nameof(target)); if (linkOptions == null) throw new ArgumentNullException(nameof(linkOptions)); Contract.EndContractBlock(); bool hasValue; bool isCompleted; lock (ValueLock) { hasValue = HasValue; isCompleted = _completionReserved; // If we haven't gotten a value yet and the block is not complete, add the target and bail if (!hasValue && !isCompleted) { _targetRegistry.Add(ref target, linkOptions); return Common.CreateUnlinker(ValueLock, _targetRegistry, target); } } // If we already have a value, send it along to the linking target if (hasValue) { bool useCloning = _cloningFunction != null; target.OfferMessage(_header, _value, this, consumeToAccept: useCloning); } // If completion propagation has been requested, do it safely. // The Completion property will ensure the lazy TCS is initialized. if (linkOptions.PropagateCompletion) Common.PropagateCompletionOnceCompleted(Completion, target); return Disposables.Nop; } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Completion"]/*' /> public Task Completion { get { return CompletionTaskSource.Task; } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Targets/Member[@name="OfferMessage"]/*' /> DataflowMessageStatus ITargetBlock<T>.OfferMessage(DataflowMessageHeader messageHeader, T messageValue, ISourceBlock<T> source, Boolean consumeToAccept) { // Validate arguments if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, nameof(messageHeader)); if (source == null && consumeToAccept) throw new ArgumentException(SR.Argument_CantConsumeFromANullSource, nameof(consumeToAccept)); Contract.EndContractBlock(); bool thisThreadReservedCompletion = false; lock (ValueLock) { // If we are declining messages, bail if (_decliningPermanently) return DataflowMessageStatus.DecliningPermanently; // Consume the message from the source if necessary. We do this while holding ValueLock to prevent multiple concurrent // offers from all succeeding. if (consumeToAccept) { bool consumed; messageValue = source.ConsumeMessage(messageHeader, this, out consumed); if (!consumed) return DataflowMessageStatus.NotAvailable; } // Update the header and the value _header = Common.SingleMessageHeader; _value = messageValue; // We got what we needed. Start declining permanently. _decliningPermanently = true; // Reserve Completion if (!_completionReserved) thisThreadReservedCompletion = _completionReserved = true; } // Since this call to OfferMessage succeeded (and only one can ever), complete the block // (but asynchronously so as not to block the Post call while offering to // targets, running synchronous continuations off of the completion task, etc.) if (thisThreadReservedCompletion) CompleteBlockAsync(exceptions: null); return DataflowMessageStatus.Accepted; } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ConsumeMessage"]/*' /> T ISourceBlock<T>.ConsumeMessage(DataflowMessageHeader messageHeader, ITargetBlock<T> target, out Boolean messageConsumed) { // Validate arguments if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, nameof(messageHeader)); if (target == null) throw new ArgumentNullException(nameof(target)); Contract.EndContractBlock(); // As long as the message being requested is the one we have, allow it to be consumed, // but make a copy using the provided cloning function. if (_header.Id == messageHeader.Id) { messageConsumed = true; return CloneItem(_value); } else { messageConsumed = false; return default(T); } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ReserveMessage"]/*' /> Boolean ISourceBlock<T>.ReserveMessage(DataflowMessageHeader messageHeader, ITargetBlock<T> target) { // Validate arguments if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, nameof(messageHeader)); if (target == null) throw new ArgumentNullException(nameof(target)); Contract.EndContractBlock(); // As long as the message is the one we have, it can be "reserved." // Reservations on a WriteOnceBlock are not exclusive, because // everyone who wants a copy can get one. return _header.Id == messageHeader.Id; } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ReleaseReservation"]/*' /> void ISourceBlock<T>.ReleaseReservation(DataflowMessageHeader messageHeader, ITargetBlock<T> target) { // Validate arguments if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, nameof(messageHeader)); if (target == null) throw new ArgumentNullException(nameof(target)); Contract.EndContractBlock(); // As long as the message is the one we have, everything's fine. if (_header.Id != messageHeader.Id) throw new InvalidOperationException(SR.InvalidOperation_MessageNotReservedByTarget); // In other blocks, upon release we typically re-offer the message to all linked targets. // We need to do the same thing for WriteOnceBlock, in order to account for cases where the block // may be linked to a join or similar block, such that the join could never again be satisfied // if it didn't receive another offer from this source. However, since the message is broadcast // and all targets can get a copy, we don't need to broadcast to all targets, only to // the target that released the message. Note that we don't care whether it's accepted // or not, nor do we care about any exceptions which may emerge (they should just propagate). Debug.Assert(_header.IsValid, "A valid header is required."); bool useCloning = _cloningFunction != null; target.OfferMessage(_header, _value, this, consumeToAccept: useCloning); } /// <summary>Clones the item.</summary> /// <param name="item">The item to clone.</param> /// <returns>The cloned item.</returns> private T CloneItem(T item) { return _cloningFunction != null ? _cloningFunction(item) : item; } /// <summary>Offers the WriteOnceBlock's message to all targets.</summary> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private List<Exception> OfferToTargets() { Common.ContractAssertMonitorStatus(ValueLock, held: false); // If there is a message, offer it to everyone. Return values // don't matter, because we only get one message and then complete, // and everyone who wants a copy can get a copy. List<Exception> exceptions = null; if (HasValue) { TargetRegistry<T>.LinkedTargetInfo cur = _targetRegistry.FirstTargetNode; while (cur != null) { TargetRegistry<T>.LinkedTargetInfo next = cur.Next; ITargetBlock<T> target = cur.Target; try { // Offer the message. If there's a cloning function, we force the target to // come back to us to consume the message, allowing us the opportunity to run // the cloning function once we know they want the data. If there is no cloning // function, there's no reason for them to call back here. bool useCloning = _cloningFunction != null; target.OfferMessage(_header, _value, this, consumeToAccept: useCloning); } catch (Exception exc) { // Track any erroneous exceptions that may occur // and return them to the caller so that they may // be logged in the completion task. Common.StoreDataflowMessageValueIntoExceptionData(exc, _value); Common.AddException(ref exceptions, exc); } cur = next; } } return exceptions; } /// <summary>Ensures the completion task's TCS is initialized.</summary> /// <returns>The completion task's TCS.</returns> private TaskCompletionSource<VoidResult> CompletionTaskSource { get { // If the completion task's TCS has not been initialized by now, safely try to initialize it. // It is very important that once a completion task/source instance has been handed out, // it remains the block's completion task. if (_lazyCompletionTaskSource == null) { Interlocked.CompareExchange(ref _lazyCompletionTaskSource, new TaskCompletionSource<VoidResult>(), null); } return _lazyCompletionTaskSource; } } /// <summary>Gets whether the block is storing a value.</summary> private bool HasValue { get { return _header.IsValid; } } /// <summary>Gets the value being stored by the block.</summary> private T Value { get { return _header.IsValid ? _value : default(T); } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="ToString"]/*' /> public override string ToString() { return Common.GetNameForDebugger(this, _dataflowBlockOptions); } /// <summary>The data to display in the debugger display attribute.</summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider")] private object DebuggerDisplayContent { get { return string.Format("{0}, HasValue={1}, Value={2}", Common.GetNameForDebugger(this, _dataflowBlockOptions), HasValue, Value); } } /// <summary>Gets the data to display in the debugger display attribute for this instance.</summary> object IDebuggerDisplay.Content { get { return DebuggerDisplayContent; } } /// <summary>Provides a debugger type proxy for WriteOnceBlock.</summary> private sealed class DebugView { /// <summary>The WriteOnceBlock being viewed.</summary> private readonly WriteOnceBlock<T> _writeOnceBlock; /// <summary>Initializes the debug view.</summary> /// <param name="writeOnceBlock">The WriteOnceBlock to view.</param> public DebugView(WriteOnceBlock<T> writeOnceBlock) { Debug.Assert(writeOnceBlock != null, "Need a block with which to construct the debug view."); _writeOnceBlock = writeOnceBlock; } /// <summary>Gets whether the WriteOnceBlock has completed.</summary> public bool IsCompleted { get { return _writeOnceBlock.Completion.IsCompleted; } } /// <summary>Gets the block's Id.</summary> public int Id { get { return Common.GetBlockId(_writeOnceBlock); } } /// <summary>Gets whether the WriteOnceBlock has a value.</summary> public bool HasValue { get { return _writeOnceBlock.HasValue; } } /// <summary>Gets the WriteOnceBlock's value if it has one, or default(T) if it doesn't.</summary> public T Value { get { return _writeOnceBlock.Value; } } /// <summary>Gets the DataflowBlockOptions used to configure this block.</summary> public DataflowBlockOptions DataflowBlockOptions { get { return _writeOnceBlock._dataflowBlockOptions; } } /// <summary>Gets the set of all targets linked from this block.</summary> public TargetRegistry<T> LinkedTargets { get { return _writeOnceBlock._targetRegistry; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** Purpose: A representation of an IEEE double precision ** floating point number. ** ** ===========================================================*/ using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Diagnostics.Contracts; namespace System { [StructLayout(LayoutKind.Sequential)] [System.Runtime.InteropServices.ComVisible(true)] public struct Double : IComparable, IFormattable, IComparable<Double>, IEquatable<Double>, IConvertible { internal double m_value; // // Public Constants // public const double MinValue = -1.7976931348623157E+308; public const double MaxValue = 1.7976931348623157E+308; // Note Epsilon should be a double whose hex representation is 0x1 // on little endian machines. public const double Epsilon = 4.9406564584124654E-324; public const double NegativeInfinity = (double)-1.0 / (double)(0.0); public const double PositiveInfinity = (double)1.0 / (double)(0.0); public const double NaN = (double)0.0 / (double)0.0; // 0x8000000000000000 is exactly same as -0.0. We use this explicit definition to avoid the confusion between 0.0 and -0.0. internal static double NegativeZero = Int64BitsToDouble(unchecked((long)0x8000000000000000)); private static unsafe double Int64BitsToDouble(long value) { return *((double*)&value); } [Pure] [System.Security.SecuritySafeCritical] // auto-generated public unsafe static bool IsInfinity(double d) { return (*(long*)(&d) & 0x7FFFFFFFFFFFFFFF) == 0x7FF0000000000000; } [Pure] public static bool IsPositiveInfinity(double d) { //Jit will generate inlineable code with this if (d == double.PositiveInfinity) { return true; } else { return false; } } [Pure] public static bool IsNegativeInfinity(double d) { //Jit will generate inlineable code with this if (d == double.NegativeInfinity) { return true; } else { return false; } } [Pure] [System.Security.SecuritySafeCritical] // auto-generated internal unsafe static bool IsNegative(double d) { return (*(UInt64*)(&d) & 0x8000000000000000) == 0x8000000000000000; } [Pure] [System.Security.SecuritySafeCritical] public unsafe static bool IsNaN(double d) { return (*(UInt64*)(&d) & 0x7FFFFFFFFFFFFFFFL) > 0x7FF0000000000000L; } // Compares this object to another object, returning an instance of System.Relation. // Null is considered less than any instance. // // If object is not of type Double, this method throws an ArgumentException. // // Returns a value less than zero if this object // int IComparable.CompareTo(Object value) { if (value == null) { return 1; } if (value is Double) { double d = (double)value; if (m_value < d) return -1; if (m_value > d) return 1; if (m_value == d) return 0; // At least one of the values is NaN. if (IsNaN(m_value)) return (IsNaN(d) ? 0 : -1); else return 1; } throw new ArgumentException(SR.Arg_MustBeDouble); } public int CompareTo(Double value) { if (m_value < value) return -1; if (m_value > value) return 1; if (m_value == value) return 0; // At least one of the values is NaN. if (IsNaN(m_value)) return (IsNaN(value) ? 0 : -1); else return 1; } // True if obj is another Double with the same value as the current instance. This is // a method of object equality, that only returns true if obj is also a double. public override bool Equals(Object obj) { if (!(obj is Double)) { return false; } double temp = ((Double)obj).m_value; // This code below is written this way for performance reasons i.e the != and == check is intentional. if (temp == m_value) { return true; } return IsNaN(temp) && IsNaN(m_value); } [NonVersionable] public static bool operator ==(Double left, Double right) { return left == right; } [NonVersionable] public static bool operator !=(Double left, Double right) { return left != right; } [NonVersionable] public static bool operator <(Double left, Double right) { return left < right; } [NonVersionable] public static bool operator >(Double left, Double right) { return left > right; } [NonVersionable] public static bool operator <=(Double left, Double right) { return left <= right; } [NonVersionable] public static bool operator >=(Double left, Double right) { return left >= right; } public bool Equals(Double obj) { if (obj == m_value) { return true; } return IsNaN(obj) && IsNaN(m_value); } //The hashcode for a double is the absolute value of the integer representation //of that double. // [System.Security.SecuritySafeCritical] public unsafe override int GetHashCode() { double d = m_value; if (d == 0) { // Ensure that 0 and -0 have the same hash code return 0; } long value = *(long*)(&d); return unchecked((int)value) ^ ((int)(value >> 32)); } [System.Security.SecuritySafeCritical] // auto-generated public override String ToString() { Contract.Ensures(Contract.Result<String>() != null); return FormatProvider.FormatDouble(m_value, null, null); } [System.Security.SecuritySafeCritical] // auto-generated public String ToString(String format) { Contract.Ensures(Contract.Result<String>() != null); return FormatProvider.FormatDouble(m_value, format, null); } [System.Security.SecuritySafeCritical] // auto-generated public String ToString(IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return FormatProvider.FormatDouble(m_value, null, provider); } [System.Security.SecuritySafeCritical] // auto-generated public String ToString(String format, IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return FormatProvider.FormatDouble(m_value, format, provider); } public static double Parse(String s) { return Parse(s, NumberStyles.Float | NumberStyles.AllowThousands, null); } public static double Parse(String s, NumberStyles style) { Decimal.ValidateParseStyleFloatingPoint(style); return Parse(s, style, null); } public static double Parse(String s, IFormatProvider provider) { return Parse(s, NumberStyles.Float | NumberStyles.AllowThousands, provider); } public static double Parse(String s, NumberStyles style, IFormatProvider provider) { Decimal.ValidateParseStyleFloatingPoint(style); return FormatProvider.ParseDouble(s, style, provider); } // Parses a double from a String in the given style. If // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. // // This method will not throw an OverflowException, but will return // PositiveInfinity or NegativeInfinity for a number that is too // large or too small. // public static bool TryParse(String s, out double result) { return TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, null, out result); } public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out double result) { Decimal.ValidateParseStyleFloatingPoint(style); if (s == null) { result = 0; return false; } bool success = FormatProvider.TryParseDouble(s, style, provider, out result); if (!success) { String sTrim = s.Trim(); if (FormatProvider.IsPositiveInfinity(sTrim, provider)) { result = PositiveInfinity; } else if (FormatProvider.IsNegativeInfinity(sTrim, provider)) { result = NegativeInfinity; } else if (FormatProvider.IsNaNSymbol(sTrim, provider)) { result = NaN; } else return false; // We really failed } return true; } // // IConvertible implementation // TypeCode IConvertible.GetTypeCode() { return TypeCode.Double; } /// <internalonly/> bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(m_value); } /// <internalonly/> char IConvertible.ToChar(IFormatProvider provider) { throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "Double", "Char")); } /// <internalonly/> sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(m_value); } /// <internalonly/> byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(m_value); } /// <internalonly/> short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(m_value); } /// <internalonly/> ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(m_value); } /// <internalonly/> int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(m_value); } /// <internalonly/> uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(m_value); } /// <internalonly/> long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(m_value); } /// <internalonly/> ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(m_value); } /// <internalonly/> float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(m_value); } /// <internalonly/> double IConvertible.ToDouble(IFormatProvider provider) { return m_value; } /// <internalonly/> Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } /// <internalonly/> DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "Double", "DateTime")); } /// <internalonly/> Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } } }
using System; using Jsonics; using NUnit.Framework; namespace JsonicsTests.ToJsonTests { [TestFixture] public class ArrayTests { [Test] public void ToJson_StringArray_CorrectJson() { //arrange var converter = JsonFactory.Compile<string[]>(); //act string json = converter.ToJson(new string[]{"1","2","3","4","5"}); //assert Assert.That(json, Is.EqualTo("[\"1\",\"2\",\"3\",\"4\",\"5\"]")); } [Test] public void ToJson_IntArray_CorrectJson() { //arrange var converter = JsonFactory.Compile<int[]>(); //act string json = converter.ToJson(new int[]{1,2,3,4,5}); //assert Assert.That(json, Is.EqualTo("[1,2,3,4,5]")); } public class IntArrayObject { public int[] IntArrayProperty { get; set; } } [Test] public void ToJson_IntArrayObjectNullProperty_PropertyNotIncludedInJson() { //arrange var jsonConverter = JsonFactory.Compile<IntArrayObject>(); var testObject = new IntArrayObject(); //act var json = jsonConverter.ToJson(testObject); //assert Assert.That(json, Is.EqualTo("{\"IntArrayProperty\":null}")); } [Test] public void ToJson_IntArrayProperty_CorrectJson() { //arrange var jsonConverter = JsonFactory.Compile<IntArrayObject>(); var testObject = new IntArrayObject() { IntArrayProperty = new int[]{1,2,3,4,5} }; //act var json = jsonConverter.ToJson(testObject); //assert Assert.That(json, Is.EqualTo("{\"IntArrayProperty\":[1,2,3,4,5]}")); } public class StringArrayObject { public string[] StringArrayProperty { get; set; } } [Test] public void ToJson_StringArrayObjectNullProperty_PropertyNotIncludedInJson() { //arrange var jsonConverter = JsonFactory.Compile<StringArrayObject>(); var testObject = new StringArrayObject(); //act var json = jsonConverter.ToJson(testObject); //assert Assert.That(json, Is.EqualTo("{\"StringArrayProperty\":null}")); } [Test] public void ToJson_StringArrayProperty_CorrectJson() { //arrange var jsonConverter = JsonFactory.Compile<StringArrayObject>(); var testObject = new StringArrayObject() { StringArrayProperty = new string[]{"1","2","3","4","5"} }; //act var json = jsonConverter.ToJson(testObject); //assert Assert.That(json, Is.EqualTo("{\"StringArrayProperty\":[\"1\",\"2\",\"3\",\"4\",\"5\"]}")); } [Test] public void ToJson_StringArrayPropertyNeedsEscaping_CorrectJson() { //arrange var jsonConverter = JsonFactory.Compile<StringArrayObject>(); var testObject = new StringArrayObject() { StringArrayProperty = new string[]{"1","2","3\"","4","5"} }; //act var json = jsonConverter.ToJson(testObject); //assert Assert.That(json, Is.EqualTo("{\"StringArrayProperty\":[\"1\",\"2\",\"3\\\"\",\"4\",\"5\"]}")); } [Test] public void ToJson_StringArrayPropertyEmpty_CorrectJson() { //arrange var jsonConverter = JsonFactory.Compile<StringArrayObject>(); var testObject = new StringArrayObject() { StringArrayProperty = new string[0] }; //act var json = jsonConverter.ToJson(testObject); //assert Assert.That(json, Is.EqualTo("{\"StringArrayProperty\":[]}")); } [Test] public void ToJson_NullableIntArray_CorrectJson() { //arrange var converter = JsonFactory.Compile<int?[]>(); //act string json = converter.ToJson(new int?[]{1,-2,3,null,4,5}); //assert Assert.That(json, Is.EqualTo("[1,-2,3,null,4,5]")); } [Test] public void ToJson_NullableUIntArray_CorrectJson() { //arrange var converter = JsonFactory.Compile<uint?[]>(); //act string json = converter.ToJson(new uint?[]{1,2,3,null,4,5}); //assert Assert.That(json, Is.EqualTo("[1,2,3,null,4,5]")); } [Test] public void ToJson_UIntArray_CorrectJson() { //arrange var converter = JsonFactory.Compile<uint[]>(); //act string json = converter.ToJson(new uint[]{1,2,3,4,5}); //assert Assert.That(json, Is.EqualTo("[1,2,3,4,5]")); } [Test] public void ToJson_NullableShortArray_CorrectJson() { //arrange var converter = JsonFactory.Compile<short?[]>(); //act string json = converter.ToJson(new short?[]{-11,2,3,null,4,5}); //assert Assert.That(json, Is.EqualTo("[-11,2,3,null,4,5]")); } [Test] public void ToJson_ShortArray_CorrectJson() { //arrange var converter = JsonFactory.Compile<short[]>(); //act string json = converter.ToJson(new short[]{-11,2,3,4,5}); //assert Assert.That(json, Is.EqualTo("[-11,2,3,4,5]")); } [Test] public void ToJson_NullableUShortArray_CorrectJson() { //arrange var converter = JsonFactory.Compile<ushort?[]>(); //act string json = converter.ToJson(new ushort?[]{1,2,3,null,4,5}); //assert Assert.That(json, Is.EqualTo("[1,2,3,null,4,5]")); } [Test] public void ToJson_UShortArray_CorrectJson() { //arrange var converter = JsonFactory.Compile<ushort[]>(); //act string json = converter.ToJson(new ushort[]{1,2,3,4,5}); //assert Assert.That(json, Is.EqualTo("[1,2,3,4,5]")); } [Test] public void ToJson_NullableFloatArray_CorrectJson() { //arrange var converter = JsonFactory.Compile<float?[]>(); //act string json = converter.ToJson(new float?[]{-11,2.2f,3,null,4,5}); //assert Assert.That(json, Is.EqualTo("[-11,2.2,3,null,4,5]")); } [Test] public void ToJson_FloatArray_CorrectJson() { //arrange var converter = JsonFactory.Compile<float[]>(); //act string json = converter.ToJson(new float[]{-11.12f,2.2f,3,4,5.5f}); //assert Assert.That(json, Is.EqualTo("[-11.12,2.2,3,4,5.5]")); } [Test] public void ToJson_NullableDoubleArray_CorrectJson() { //arrange var converter = JsonFactory.Compile<double?[]>(); //act string json = converter.ToJson(new double?[]{-11,2.3d,3,null,4,5}); //assert Assert.That(json, Is.EqualTo("[-11,2.3,3,null,4,5]")); } [Test] public void ToJson_DoubleArray_CorrectJson() { //arrange var converter = JsonFactory.Compile<double[]>(); //act string json = converter.ToJson(new double[]{-11.12d,2.4d,3,4,5.5f}); //assert Assert.That(json, Is.EqualTo("[-11.12,2.4,3,4,5.5]")); } [Test] public void ToJson_NullableByteArray_CorrectJson() { //arrange var converter = JsonFactory.Compile<byte?[]>(); //act string json = converter.ToJson(new byte?[]{255,0,1,null,3,4}); //assert Assert.That(json, Is.EqualTo("[255,0,1,null,3,4]")); } [Test] public void ToJson_ByteArray_CorrectJson() { //arrange var converter = JsonFactory.Compile<byte[]>(); //act string json = converter.ToJson(new byte[]{255,0,1,3,4}); //assert Assert.That(json, Is.EqualTo("[255,0,1,3,4]")); } [Test] public void ToJson_NullableSByteArray_CorrectJson() { //arrange var converter = JsonFactory.Compile<sbyte?[]>(); //act string json = converter.ToJson(new sbyte?[]{127,-128,1,null,3,4}); //assert Assert.That(json, Is.EqualTo("[127,-128,1,null,3,4]")); } [Test] public void ToJson_SByteArray_CorrectJson() { //arrange var converter = JsonFactory.Compile<sbyte[]>(); //act string json = converter.ToJson(new sbyte[]{127,-128,1,3,4}); //assert Assert.That(json, Is.EqualTo("[127,-128,1,3,4]")); } [Test] public void ToJson_NullableCharArray_CorrectJson() { //arrange var converter = JsonFactory.Compile<char?[]>(); //act string json = converter.ToJson(new char?[]{'a','b','c',null,'d','e'}); //assert Assert.That(json, Is.EqualTo("[\"a\",\"b\",\"c\",null,\"d\",\"e\"]")); } [Test] public void ToJson_CharArray_CorrectJson() { //arrange var converter = JsonFactory.Compile<char[]>(); //act string json = converter.ToJson(new char[]{'a','b','c','d','e'}); //assert Assert.That(json, Is.EqualTo("[\"a\",\"b\",\"c\",\"d\",\"e\"]")); } [Test] public void ToJson_NullableBoolArray_CorrectJson() { //arrange var converter = JsonFactory.Compile<bool?[]>(); //act string json = converter.ToJson(new bool?[]{true, null, false}); //assert Assert.That(json, Is.EqualTo("[true,null,false]")); } [Test] public void ToJson_BoolArray_CorrectJson() { //arrange var converter = JsonFactory.Compile<bool[]>(); //act string json = converter.ToJson(new bool[]{true, false}); //assert Assert.That(json, Is.EqualTo("[true,false]")); } [Test] public void ToJson_NullableGuidArray_CorrectJson() { //arrange var converter = JsonFactory.Compile<Guid?[]>(); //act string json = converter.ToJson(new Guid?[]{new Guid(1,2,3,4,5,6,7,8,9,10,11), null, new Guid(2,3,4,5,6,7,8,9,10,11,12)}); //assert Assert.That(json, Is.EqualTo("[\"00000001-0002-0003-0405-060708090a0b\",null,\"00000002-0003-0004-0506-0708090a0b0c\"]")); } [Test] public void ToJson_GuidArray_CorrectJson() { //arrange var converter = JsonFactory.Compile<Guid[]>(); //act string json = converter.ToJson(new Guid[]{new Guid(1,2,3,4,5,6,7,8,9,10,11), new Guid(2,3,4,5,6,7,8,9,10,11,12)}); //assert Assert.That(json, Is.EqualTo("[\"00000001-0002-0003-0405-060708090a0b\",\"00000002-0003-0004-0506-0708090a0b0c\"]")); } [Test] public void ToJson_NullableDateTimeArray_CorrectJson() { //arrange var converter = JsonFactory.Compile<DateTime?[]>(); //act string json = converter.ToJson(new DateTime?[]{new DateTime(2018,04,08, 1,2,3, DateTimeKind.Utc), null, new DateTime(2017,03,07, 23,59,42, DateTimeKind.Utc)}); //assert Assert.That(json, Is.EqualTo("[\"2018-04-08T01:02:03Z\",null,\"2017-03-07T23:59:42Z\"]")); } [Test] public void ToJson_DateTimeArray_CorrectJson() { //arrange var converter = JsonFactory.Compile<DateTime[]>(); //act string json = converter.ToJson(new DateTime[]{new DateTime(2018,04,08, 1,2,3, DateTimeKind.Utc), new DateTime(2017,03,07, 23,59,42, DateTimeKind.Utc)}); //assert Assert.That(json, Is.EqualTo("[\"2018-04-08T01:02:03Z\",\"2017-03-07T23:59:42Z\"]")); } [Test] public void ToJson_DecimalArray_CorrectJson() { //arrange var converter = JsonFactory.Compile<decimal[]>(); //act string json = converter.ToJson(new decimal[]{-11.12M,2.4M,3M,4M,5.5M}); //assert Assert.That(json, Is.EqualTo("[-11.12,2.4,3,4,5.5]")); } [Test] public void ToJson_NullableDecimalArray_CorrectJson() { //arrange var converter = JsonFactory.Compile<decimal?[]>(); //act string json = converter.ToJson(new decimal?[]{-11.12M,2.4M,null,3M,4M,5.5M}); //assert Assert.That(json, Is.EqualTo("[-11.12,2.4,null,3,4,5.5]")); } } }
//----------------------------------------------------------------------- // <copyright file="Cube.cs" company="RVS Game Company"> // Copyright (c) RVS Game Company. All rights reserved. // </copyright> // <author>Ricardo da Verdade Silva</author> // <create_date> 2014-04-05 </create_date> // <project> 2D Basic Physics Engine </project> //----------------------------------------------------------------------- namespace Basic_Physics_XNA_Engine { using System; using System.Collections; using System.Collections.Generic; using Interfaces; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; /// <summary> /// This is a cube used to tests and to /// serve as base class. This is a <see cref="DrawableGameComponent"/> /// and implements <see cref="IApplyPhysics"/> and /// <see cref="ICollidable"/>. /// </summary> public class Cube : DrawableGameComponent, IApplyPhysics, ICollidable, IControllable { private const float MovementForce = 200f; private const float JumpForce = 900f; private const float PixelsPerMetre = 10f; /// <summary> /// Initializes a new instance of the <see cref="Cube"/> class. /// </summary> /// <param name="game">Reference to game.</param> public Cube(Game game) : base(game) { IsActive = true; IsPhysicsOn = true; this.Velocity = new Vector2(0,0); this.UsesGamepad = true; this.UsesKeyboard = true; this.GamepadIndex = 0; game.Components.Add(this); } /// <summary> /// Gets or sets a value to draw device. /// </summary> public SpriteBatch SpriteBatch { get; set; } /// <summary> /// Gets or sets a value that indicating /// bounds of object. /// </summary> public Rectangle Bounds { get { return new Rectangle( (int) this.Position.X, (int) this.Position.Y, (int) (this.Size.X), (int) (this.Size.Y)); } } /// <summary> /// Gets or sets a value indicating position of object /// in game world. /// </summary> public Vector2 Position { get { return this.position; } set { this.Delta = value - this.position; this.position = value; } } Vector2 position; /// <summary> /// Gets or sets a value indicating the change from previous /// position. /// </summary> public Vector2 Delta { get; set; } /// <summary> /// Gets or sets a value indicating whether object /// is active in game world.Sometimes you may want /// temporarily remove object from game, for this /// just deactivate. While deactivated, object /// should do nothing and cannot impact in game world. /// </summary> public bool IsActive { get; set; } /// <summary> /// Gets or sets a value indicating whether /// object will be affected by physics. /// </summary> public bool IsPhysicsOn { get; set; } public Vector2 Force { get { Vector2 thisForce = new Vector2 { X = this.Mass * this.Velocity.X, Y = this.Mass * this.Velocity.Y }; return thisForce; } } /// <summary> /// Gets or sets the velocity of /// object. /// </summary> public Vector2 Velocity { get; set; } /// <summary> /// Gets or sets object acceleration. /// </summary> public Vector2 Acceleration { get; set; } /// <summary> /// Gets or sets representation /// of object mass in kilograms. /// </summary> public float Mass { get; set; } /// <summary> /// Gets or sets reference to world gravity. /// </summary> public Gravity WorldGravity { get; set; } /// <summary> /// Gets or sets object size. /// </summary> public Vector2 Size { get; set; } /// <summary> /// Gets or sets a queue of forces. /// </summary> private Queue<Vector2> Forces { get; set; } /// <summary> /// Apply force to this object. /// </summary> /// <param name="forceToApply">Force to apply.</param> /// <param name="gameTime">Reference to game time.</param> public void ApplyForce(Vector2 forceToApply, GameTime gameTime) { Forces.Enqueue(forceToApply); } private void CalculateForces() { Vector2 resultForce = Vector2.Zero; while (Forces.Count > 0) { resultForce += Forces.Dequeue(); } this.Acceleration = resultForce/this.Mass; } private Texture2D CubeTexture2D { get { return this.Game.Content.Load<Texture2D>("GameThumbnail"); } } /// <summary> /// Method to be trigger when this object /// get involved in collision. /// </summary> /// <param name="collider">Other object participating /// in collision.</param> public void OnCollisionHappens(ICollidable collider, GameTime gameTime) { } /// <summary> /// Allows the game component to perform any initialization it needs to before starting /// to run. This is where it can query for any required services and load content. /// </summary> public override void Initialize() { this.Forces = new Queue<Vector2>(); base.Initialize(); } /// <summary> /// Called when graphics resources need to be loaded. Override this method to load any component-specific graphics resources. /// </summary> protected override void LoadContent() { this.SpriteBatch = (SpriteBatch)this.Game.Services.GetService(typeof(SpriteBatch)); base.LoadContent(); } /// <summary> /// Allows the game component to update itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> public override void Update(GameTime gameTime) { if (this.IsPhysicsOn) { ApplyPhysics(gameTime); } if (this.UsesGamepad) { GetGamepadState(gameTime); } if (this.UsesKeyboard) { GetKeyboardState(gameTime); } base.Update(gameTime); } /// <summary> /// Allows the game component to draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> public override void Draw(GameTime gameTime) { this.SpriteBatch.Draw(this.CubeTexture2D, this.Bounds, Color.White); base.Draw(gameTime); } /// <summary> /// Apply gravity to object. /// </summary> /// <param name="gameTime">Reference to game time.</param> private void ApplyGravity(GameTime gameTime) { Vector2 gravityForce = new Vector2() { X = 0, Y = this.WorldGravity.Force * Mass }; //gravityForce = gravityForce*elapsedTime; this.ApplyForce(gravityForce, gameTime); } private void GetGamepadState(GameTime gameTime) { GamePadState gamePadState = GamePad.GetState((PlayerIndex) this.GamepadIndex); if (gamePadState.ThumbSticks.Left.X != 0) { this.ApplyForce(new Vector2 { X = gamePadState.ThumbSticks.Left.X*MovementForce, Y = 0 }, gameTime); } if (gamePadState.Buttons.A.Equals(ButtonState.Pressed)) { this.ApplyForce(new Vector2 { X = 0, Y = -(Convert.ToInt32(gamePadState.Buttons.A == ButtonState.Pressed) * JumpForce) }, gameTime); } } private void GetKeyboardState(GameTime gameTime) { KeyboardState keyboardState = Keyboard.GetState(); if (keyboardState.IsKeyDown(Keys.Left)) { this.ApplyForce(new Vector2(-MovementForce, 0), gameTime); } if (keyboardState.IsKeyDown(Keys.Right)) { this.ApplyForce(new Vector2(MovementForce, 0), gameTime); } if (keyboardState.IsKeyDown(Keys.Space)) { this.ApplyForce(new Vector2(0, -JumpForce), gameTime); } } /// <summary> /// Apply physics to object. /// </summary> /// <param name="gameTime">Reference to game time.</param> private void ApplyPhysics(GameTime gameTime) { ApplyGravity(gameTime); CalculateForces(); this.Velocity += Acceleration * gameTime.ElapsedGameTime.Milliseconds * 0.001f; this.Position += PixelsPerMetre * Velocity * gameTime.ElapsedGameTime.Milliseconds * 0.001f; } public bool UsesKeyboard { get; set; } public bool UsesGamepad { get; set; } public int GamepadIndex { get; set; } public ControllableState CurrentState { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } } }
// 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.IO; using System.Reflection; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Scripting { /// <summary> /// Represents a runtime execution context for C# scripts. /// </summary> internal abstract class ScriptEngine { public static readonly ImmutableArray<string> DefaultReferenceSearchPaths; // state captured by session at creation time: private ScriptOptions _options = ScriptOptions.Default; private ScriptBuilder _builder; static ScriptEngine() { DefaultReferenceSearchPaths = ImmutableArray.Create<string>(RuntimeEnvironment.GetRuntimeDirectory()); } internal ScriptEngine(MetadataFileReferenceProvider metadataReferenceProvider, AssemblyLoader assemblyLoader) { if (metadataReferenceProvider == null) { metadataReferenceProvider = _options.AssemblyResolver.Provider; } if (assemblyLoader == null) { assemblyLoader = new InteractiveAssemblyLoader(); } _builder = new ScriptBuilder(assemblyLoader); _options = _options.WithReferenceProvider(metadataReferenceProvider); string initialBaseDirectory; try { initialBaseDirectory = Directory.GetCurrentDirectory(); } catch { initialBaseDirectory = null; } _options = _options.WithBaseDirectory(initialBaseDirectory); } public MetadataFileReferenceProvider MetadataReferenceProvider { get { return _options.AssemblyResolver.Provider; } } public AssemblyLoader AssemblyLoader { get { return _builder.AssemblyLoader; } } internal ScriptBuilder Builder { get { return _builder; } } // TODO (tomat): Consider exposing FileResolver and removing BaseDirectory. // We would need WithAssemblySearchPaths on FileResolver to implement SetReferenceSearchPaths internal MetadataFileReferenceResolver MetadataReferenceResolver { get { return _options.AssemblyResolver.PathResolver; } // for testing set { Debug.Assert(value != null); _options = _options.WithReferenceResolver(value); } } internal string AssemblyNamePrefix { get { return _builder.AssemblyNamePrefix; } } #region Script internal abstract Script Create(string code, ScriptOptions options, Type globalsType, Type returnType); #endregion #region Session // for testing only: // TODO (tomat): Sessions generate uncollectible code since we don't know whether they would execute just one submissions or multiple. // We need to address code collectibility of multi-submission sessions at some point (the CLR needs to be fixed). Meanwhile use this helper // to force collectible code generation in order to keep test coverage. internal Session CreateCollectibleSession() { return new Session(this, _options.WithIsCollectible(true), null); } internal Session CreateCollectibleSession<THostObject>(THostObject hostObject) { return new Session(this, _options.WithIsCollectible(true), hostObject, typeof(THostObject)); } public Session CreateSession() // TODO (tomat): bool isCancellable = false { return new Session(this, _options, null); } public Session CreateSession(object hostObject) // TODO (tomat): bool isCancellable = false { if (hostObject == null) { throw new ArgumentNullException("hostObject"); } return new Session(this, _options, hostObject, hostObject.GetType()); } public Session CreateSession(object hostObject, Type hostObjectType) // TODO (tomat): bool isCancellable = false { if (hostObject == null) { throw new ArgumentNullException("hostObject"); } if (hostObjectType == null) { throw new ArgumentNullException("hostObjectType"); } Type actualType = hostObject.GetType(); if (!hostObjectType.IsAssignableFrom(actualType)) { throw new ArgumentException(String.Format(ScriptingResources.CantAssignTo, actualType, hostObjectType), "hostObjectType"); } return new Session(this, _options, hostObject, hostObjectType); } public Session CreateSession<THostObject>(THostObject hostObject) // TODO (tomat): bool isCancellable = false where THostObject : class { if (hostObject == null) { throw new ArgumentNullException("hostObject"); } return new Session(this, _options, hostObject, typeof(THostObject)); } #endregion #region State /// <summary> /// The base directory used to resolve relative paths to assembly references and /// relative paths that appear in source code compiled by this script engine. /// </summary> /// <remarks> /// If null relative paths won't be resolved and an error will be reported when the compiler encountrs such paths. /// The value can be changed at any point in time. However the new value doesn't affect already compiled submissions. /// The initial value is the current working directory if the current process, or null if not available. /// Changing the base directory doesn't affect the process current working directory used by <see cref="System.IO"/> APIs. /// </remarks> public string BaseDirectory { get { return _options.BaseDirectory; } set { _options = _options.WithBaseDirectory(value); } } public ImmutableArray<string> ReferenceSearchPaths { get { return _options.SearchPaths; } } public void SetReferenceSearchPaths(params string[] paths) { SetReferenceSearchPaths(ImmutableArray.CreateRange<string>(paths)); } public void SetReferenceSearchPaths(IEnumerable<string> paths) { SetReferenceSearchPaths(ImmutableArray.CreateRange<string>(paths)); } public void SetReferenceSearchPaths(ImmutableArray<string> paths) { MetadataFileReferenceResolver.ValidateSearchPaths(paths, "paths"); _options = _options.WithSearchPaths(paths); } /// <summary> /// Returns a list of assemblies that are currently referenced by the engine. /// </summary> public ImmutableArray<MetadataReference> GetReferences() { return _options.References; } /// <summary> /// Adds a reference to specified assembly. /// </summary> /// <param name="assemblyDisplayNameOrPath">Assembly display name or path.</param> /// <exception cref="ArgumentNullException"><paramref name="assemblyDisplayNameOrPath"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="assemblyDisplayNameOrPath"/> is empty.</exception> /// <exception cref="FileNotFoundException">Assembly file can't be found.</exception> public void AddReference(string assemblyDisplayNameOrPath) { if (assemblyDisplayNameOrPath == null) { throw new ArgumentNullException(nameof(assemblyDisplayNameOrPath)); } _options = _options.AddReferences(assemblyDisplayNameOrPath); } /// <summary> /// Adds a reference to specified assembly. /// </summary> /// <param name="assembly">Runtime assembly. The assembly must be loaded from a file on disk. In-memory assemblies are not supported.</param> /// <exception cref="ArgumentNullException"><paramref name="assembly"/> is null.</exception> public void AddReference(Assembly assembly) { if (assembly == null) { throw new ArgumentNullException(nameof(assembly)); } _options = _options.AddReferences(assembly); } /// <summary> /// Adds a reference to specified assembly. /// </summary> /// <param name="reference">Assembly reference.</param> /// <exception cref="ArgumentException"><paramref name="reference"/> is not an assembly reference (it's a module).</exception> /// <exception cref="ArgumentNullException"><paramref name="reference"/> is null.</exception> public void AddReference(MetadataReference reference) { if (reference == null) { throw new ArgumentNullException(nameof(reference)); } if (reference.Properties.Kind != MetadataImageKind.Assembly) { throw new ArgumentException(ScriptingResources.ExpectedAnAssemblyReference, nameof(reference)); } _options = _options.AddReferences(reference); } /// <summary> /// Returns a list of imported namespaces. /// </summary> public ImmutableArray<string> GetImportedNamespaces() { return _options.Namespaces; } /// <summary> /// Imports a namespace, an equivalent of executing "using <paramref name="namespace"/>;" (C#) or "Imports <paramref name="namespace"/>" (VB). /// </summary> /// <exception cref="ArgumentNullException"><paramref name="namespace"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="namespace"/> is not a valid namespace name.</exception> public void ImportNamespace(string @namespace) { ValidateNamespace(@namespace); // we don't report duplicates to get the same behavior as evaluating "using NS;" twice. _options = _options.AddNamespaces(@namespace); } internal static void ValidateNamespace(string @namespace) { if (@namespace == null) { throw new ArgumentNullException(nameof(@namespace)); } // Only check that the namespace is a CLR namespace name. // If the namespace doesn't exist an error will be reported when compiling the next submission. if (!@namespace.IsValidClrNamespaceName()) { throw new ArgumentException("Invalid namespace name", "namespace"); } } #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.Xml.Xsl.XsltOld { using System; using System.Diagnostics; using System.Collections; using System.Xml; using System.Xml.XPath; using MS.Internal.Xml.XPath; using System.Globalization; internal class TemplateAction : TemplateBaseAction { private int _matchKey = Compiler.InvalidQueryKey; private XmlQualifiedName _name; private double _priority = double.NaN; private XmlQualifiedName _mode; private int _templateId; private bool _replaceNSAliasesDone; internal int MatchKey { get { return _matchKey; } } internal XmlQualifiedName Name { get { return _name; } } internal double Priority { get { return _priority; } } internal XmlQualifiedName Mode { get { return _mode; } } internal int TemplateId { get { return _templateId; } set { Debug.Assert(_templateId == 0); _templateId = value; } } internal override void Compile(Compiler compiler) { CompileAttributes(compiler); if (_matchKey == Compiler.InvalidQueryKey) { if (_name == null) { throw XsltException.Create(SR.Xslt_TemplateNoAttrib); } if (_mode != null) { throw XsltException.Create(SR.Xslt_InvalidModeAttribute); } } compiler.BeginTemplate(this); if (compiler.Recurse()) { CompileParameters(compiler); CompileTemplate(compiler); compiler.ToParent(); } compiler.EndTemplate(); AnalyzePriority(compiler); } internal virtual void CompileSingle(Compiler compiler) { _matchKey = compiler.AddQuery("/", /*allowVars:*/false, /*allowKey:*/true, /*pattern*/true); _priority = Compiler.RootPriority; CompileOnceTemplate(compiler); } internal override bool CompileAttribute(Compiler compiler) { string name = compiler.Input.LocalName; string value = compiler.Input.Value; if (Ref.Equal(name, compiler.Atoms.Match)) { Debug.Assert(_matchKey == Compiler.InvalidQueryKey); _matchKey = compiler.AddQuery(value, /*allowVars:*/false, /*allowKey:*/true, /*pattern*/true); } else if (Ref.Equal(name, compiler.Atoms.Name)) { Debug.Assert(_name == null); _name = compiler.CreateXPathQName(value); } else if (Ref.Equal(name, compiler.Atoms.Priority)) { Debug.Assert(double.IsNaN(_priority)); _priority = XmlConvert.ToXPathDouble(value); if (double.IsNaN(_priority) && !compiler.ForwardCompatibility) { throw XsltException.Create(SR.Xslt_InvalidAttrValue, "priority", value); } } else if (Ref.Equal(name, compiler.Atoms.Mode)) { Debug.Assert(_mode == null); if (compiler.AllowBuiltInMode && value == "*") { _mode = Compiler.BuiltInMode; } else { _mode = compiler.CreateXPathQName(value); } } else { return false; } return true; } private void AnalyzePriority(Compiler compiler) { NavigatorInput input = compiler.Input; if (!double.IsNaN(_priority) || _matchKey == Compiler.InvalidQueryKey) { return; } // Split Unions: TheQuery theQuery = (TheQuery)compiler.QueryStore[this.MatchKey]; CompiledXpathExpr expr = (CompiledXpathExpr)theQuery.CompiledQuery; Query query = expr.QueryTree; UnionExpr union; while ((union = query as UnionExpr) != null) { Debug.Assert(!(union.qy2 is UnionExpr), "only qy1 can be union"); TemplateAction copy = this.CloneWithoutName(); compiler.QueryStore.Add(new TheQuery( new CompiledXpathExpr(union.qy2, expr.Expression, false), theQuery._ScopeManager )); copy._matchKey = compiler.QueryStore.Count - 1; copy._priority = union.qy2.XsltDefaultPriority; compiler.AddTemplate(copy); query = union.qy1; } if (expr.QueryTree != query) { // query was splitted and we need create new TheQuery for this template compiler.QueryStore[this.MatchKey] = new TheQuery( new CompiledXpathExpr(query, expr.Expression, false), theQuery._ScopeManager ); } _priority = query.XsltDefaultPriority; } protected void CompileParameters(Compiler compiler) { NavigatorInput input = compiler.Input; do { switch (input.NodeType) { case XPathNodeType.Element: if (Ref.Equal(input.NamespaceURI, input.Atoms.UriXsl) && Ref.Equal(input.LocalName, input.Atoms.Param)) { compiler.PushNamespaceScope(); AddAction(compiler.CreateVariableAction(VariableType.LocalParameter)); compiler.PopScope(); continue; } else { return; } case XPathNodeType.Text: return; case XPathNodeType.SignificantWhitespace: this.AddEvent(compiler.CreateTextEvent()); continue; default: continue; } } while (input.Advance()); } // // Priority calculation plus template splitting // private TemplateAction CloneWithoutName() { TemplateAction clone = new TemplateAction(); { clone.containedActions = this.containedActions; clone._mode = _mode; clone.variableCount = this.variableCount; clone._replaceNSAliasesDone = true; // We shouldn't replace NS in clones. } return clone; } internal override void ReplaceNamespaceAlias(Compiler compiler) { // if template has both name and match it will be twice caled by stylesheet to replace NS aliases. if (!_replaceNSAliasesDone) { base.ReplaceNamespaceAlias(compiler); _replaceNSAliasesDone = true; } } // // Execution // internal override void Execute(Processor processor, ActionFrame frame) { Debug.Assert(processor != null && frame != null); switch (frame.State) { case Initialized: if (this.variableCount > 0) { frame.AllocateVariables(this.variableCount); } if (this.containedActions != null && this.containedActions.Count > 0) { processor.PushActionFrame(frame); frame.State = ProcessingChildren; } else { frame.Finished(); } break; // Allow children to run case ProcessingChildren: frame.Finished(); break; default: Debug.Fail("Invalid Container action execution state"); break; } } } }
using UnityEngine; [System.Serializable] public struct HSBColor { public float h; public float s; public float b; public float a; public HSBColor(float h, float s, float b, float a) { this.h = h; this.s = s; this.b = b; this.a = a; } public HSBColor(float h, float s, float b) { this.h = h; this.s = s; this.b = b; this.a = 1f; } public HSBColor(Color col) { HSBColor temp = FromColor(col); h = temp.h; s = temp.s; b = temp.b; a = temp.a; } public static HSBColor FromColor(Color color) { HSBColor ret = new HSBColor(0f, 0f, 0f, color.a); float r = color.r; float g = color.g; float b = color.b; float max = Mathf.Max(r, Mathf.Max(g, b)); if (max <= 0) { return ret; } float min = Mathf.Min(r, Mathf.Min(g, b)); float dif = max - min; if (max > min) { if (g == max) { ret.h = (b - r) / dif * 60f + 120f; } else if (b == max) { ret.h = (r - g) / dif * 60f + 240f; } else if (b > g) { ret.h = (g - b) / dif * 60f + 360f; } else { ret.h = (g - b) / dif * 60f; } if (ret.h < 0) { ret.h = ret.h + 360f; } } else { ret.h = 0; } ret.h *= 1f / 360f; ret.s = (dif / max) * 1f; ret.b = max; return ret; } public static Color ToColor(HSBColor hsbColor) { float r = hsbColor.b; float g = hsbColor.b; float b = hsbColor.b; if (hsbColor.s != 0) { float max = hsbColor.b; float dif = hsbColor.b * hsbColor.s; float min = hsbColor.b - dif; float h = hsbColor.h * 360f; if (h < 60f) { r = max; g = h * dif / 60f + min; b = min; } else if (h < 120f) { r = -(h - 120f) * dif / 60f + min; g = max; b = min; } else if (h < 180f) { r = min; g = max; b = (h - 120f) * dif / 60f + min; } else if (h < 240f) { r = min; g = -(h - 240f) * dif / 60f + min; b = max; } else if (h < 300f) { r = (h - 240f) * dif / 60f + min; g = min; b = max; } else if (h <= 360f) { r = max; g = min; b = -(h - 360f) * dif / 60 + min; } else { r = 0; g = 0; b = 0; } } return new Color(Mathf.Clamp01(r),Mathf.Clamp01(g),Mathf.Clamp01(b),hsbColor.a); } public Color ToColor() { return ToColor(this); } public override string ToString() { return "H:" + h + " S:" + s + " B:" + b; } public static HSBColor Lerp(HSBColor a, HSBColor b, float t) { float h,s; //check special case black (color.b==0): interpolate neither hue nor saturation! //check special case grey (color.s==0): don't interpolate hue! if(a.b==0){ h=b.h; s=b.s; }else if(b.b==0){ h=a.h; s=a.s; }else{ if(a.s==0){ h=b.h; }else if(b.s==0){ h=a.h; }else{ // works around bug with LerpAngle float angle = Mathf.LerpAngle(a.h * 360f, b.h * 360f, t); while (angle < 0f) angle += 360f; while (angle > 360f) angle -= 360f; h=angle/360f; } s=Mathf.Lerp(a.s,b.s,t); } return new HSBColor(h, s, Mathf.Lerp(a.b, b.b, t), Mathf.Lerp(a.a, b.a, t)); } public static void Test() { HSBColor color; color = new HSBColor(Color.red); Debug.Log("red: " + color); color = new HSBColor(Color.green); Debug.Log("green: " + color); color = new HSBColor(Color.blue); Debug.Log("blue: " + color); color = new HSBColor(Color.grey); Debug.Log("grey: " + color); color = new HSBColor(Color.white); Debug.Log("white: " + color); color = new HSBColor(new Color(0.4f, 1f, 0.84f, 1f)); Debug.Log("0.4, 1f, 0.84: " + color); Debug.Log("164,82,84 .... 0.643137f, 0.321568f, 0.329411f :" + ToColor(new HSBColor(new Color(0.643137f, 0.321568f, 0.329411f)))); } }
// // Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Internal { using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using NLog.Common; /// <summary> /// Reflection helpers. /// </summary> internal static class ReflectionHelpers { /// <summary> /// Gets all usable exported types from the given assembly. /// </summary> /// <param name="assembly">Assembly to scan.</param> /// <returns>Usable types from the given assembly.</returns> /// <remarks>Types which cannot be loaded are skipped.</remarks> public static Type[] SafeGetTypes(this Assembly assembly) { try { return assembly.GetTypes(); } #if !SILVERLIGHT || WINDOWS_PHONE catch (ReflectionTypeLoadException typeLoadException) { foreach (var ex in typeLoadException.LoaderExceptions) { InternalLogger.Warn(ex, "Type load exception."); } var loadedTypes = new List<Type>(); foreach (var t in typeLoadException.Types) { if (t != null) { loadedTypes.Add(t); } } return loadedTypes.ToArray(); } #endif catch (Exception ex) { InternalLogger.Warn(ex, "Type load exception."); return ArrayHelper.Empty<Type>(); } } /// <summary> /// Is this a static class? /// </summary> /// <param name="type"></param> /// <returns></returns> /// <remarks>This is a work around, as Type doesn't have this property. /// From: https://stackoverflow.com/questions/1175888/determine-if-a-type-is-static /// </remarks> public static bool IsStaticClass(this Type type) { return type.IsClass() && type.IsAbstract() && type.IsSealed(); } /// <summary> /// Optimized delegate for calling MethodInfo /// </summary> /// <param name="target">Object instance, use null for static methods.</param> /// <param name="arguments">Complete list of parameters that matches the method, including optional/default parameters.</param> /// <returns></returns> public delegate object LateBoundMethod(object target, object[] arguments); public delegate object LateBoundMethodSingle(object target, object argument); /// <summary> /// Creates an optimized delegate for calling the MethodInfo using Expression-Trees /// </summary> /// <param name="methodInfo">Method to optimize</param> /// <returns>Optimized delegate for invoking the MethodInfo</returns> public static LateBoundMethod CreateLateBoundMethod(MethodInfo methodInfo) { // parameters to execute var instanceParameter = Expression.Parameter(typeof(object), "instance"); var parametersParameter = Expression.Parameter(typeof(object[]), "parameters"); // build parameter list var methodCall = BuildParameterList(methodInfo, instanceParameter, parametersParameter); // ((TInstance)instance).Method((T0)parameters[0], (T1)parameters[1], ...) if (methodCall.Type == typeof(void)) { var lambda = Expression.Lambda<Action<object, object[]>>( methodCall, instanceParameter, parametersParameter); Action<object, object[]> execute = lambda.Compile(); return (instance, parameters) => { execute(instance, parameters); return null; // There is no return-type, so we return null-object }; } else { var castMethodCall = Expression.Convert(methodCall, typeof(object)); var lambda = Expression.Lambda<LateBoundMethod>( castMethodCall, instanceParameter, parametersParameter); return lambda.Compile(); } } /// <summary> /// Creates an optimized delegate for calling the MethodInfo using Expression-Trees /// </summary> /// <param name="methodInfo">Method to optimize</param> /// <returns>Optimized delegate for invoking the MethodInfo</returns> public static LateBoundMethodSingle CreateLateBoundMethodSingle(MethodInfo methodInfo) { // parameters to execute var instanceParameter = Expression.Parameter(typeof(object), "instance"); var parametersParameter = Expression.Parameter(typeof(object), "parameters"); // build parameter list var methodCall = BuildParameterListSingle(methodInfo, instanceParameter, parametersParameter); // ((TInstance)instance).Method((T0)parameters[0], (T1)parameters[1], ...) if (methodCall.Type == typeof(void)) { var lambda = Expression.Lambda<Action<object, object>>( methodCall, instanceParameter, parametersParameter); Action<object, object> execute = lambda.Compile(); return (instance, parameters) => { execute(instance, parameters); return null; // There is no return-type, so we return null-object }; } else { var castMethodCall = Expression.Convert(methodCall, typeof(object)); var lambda = Expression.Lambda<LateBoundMethodSingle>( castMethodCall, instanceParameter, parametersParameter); return lambda.Compile(); } } private static MethodCallExpression BuildParameterList(MethodInfo methodInfo, ParameterExpression instanceParameter, ParameterExpression parametersParameter) { var parameterExpressions = new List<Expression>(); var paramInfos = methodInfo.GetParameters(); for (int i = 0; i < paramInfos.Length; i++) { // (Ti)parameters[i] var valueObj = Expression.ArrayIndex(parametersParameter, Expression.Constant(i)); var valueCast = CreateParameterExpression(paramInfos[i], valueObj); parameterExpressions.Add(valueCast); } return CreateMethodCallExpression(methodInfo, instanceParameter, parameterExpressions); } private static MethodCallExpression BuildParameterListSingle(MethodInfo methodInfo, ParameterExpression instanceParameter, ParameterExpression parameterParameter) { var parameterExpressions = new List<Expression>(); var paramInfos = methodInfo.GetParameters().Single(); { // (Ti)parameters[i] var parameterExpression = CreateParameterExpression(paramInfos, parameterParameter); parameterExpressions.Add(parameterExpression); } return CreateMethodCallExpression(methodInfo, instanceParameter, parameterExpressions); } private static MethodCallExpression CreateMethodCallExpression(MethodInfo methodInfo, ParameterExpression instanceParameter, IEnumerable<Expression> parameterExpressions) { // non-instance for static method, or ((TInstance)instance) var instanceCast = methodInfo.IsStatic ? null : Expression.Convert(instanceParameter, methodInfo.DeclaringType); // static invoke or ((TInstance)instance).Method var methodCall = Expression.Call(instanceCast, methodInfo, parameterExpressions); return methodCall; } private static UnaryExpression CreateParameterExpression(ParameterInfo parameterInfo, Expression expression) { Type parameterType = parameterInfo.ParameterType; if (parameterType.IsByRef) parameterType = parameterType.GetElementType(); var valueCast = Expression.Convert(expression, parameterType); return valueCast; } public static bool IsEnum(this Type type) { #if NETSTANDARD1_0 return type.GetTypeInfo().IsEnum; #else return type.IsEnum; #endif } public static bool IsPrimitive(this Type type) { #if NETSTANDARD1_0 return type.GetTypeInfo().IsPrimitive; #else return type.IsPrimitive; #endif } public static bool IsValueType(this Type type) { #if NETSTANDARD1_0 return type.GetTypeInfo().IsValueType; #else return type.IsValueType; #endif } public static bool IsSealed(this Type type) { #if NETSTANDARD1_0 return type.GetTypeInfo().IsSealed; #else return type.IsSealed; #endif } public static bool IsAbstract(this Type type) { #if NETSTANDARD1_0 return type.GetTypeInfo().IsAbstract; #else return type.IsAbstract; #endif } public static bool IsClass(this Type type) { #if NETSTANDARD1_0 return type.GetTypeInfo().IsClass; #else return type.IsClass; #endif } public static bool IsGenericType(this Type type) { #if NETSTANDARD1_0 return type.GetTypeInfo().IsGenericType; #else return type.IsGenericType; #endif } public static TAttr GetCustomAttribute<TAttr>(this Type type) where TAttr : Attribute { #if NETSTANDARD1_0 var typeInfo = type.GetTypeInfo(); return typeInfo.GetCustomAttribute<TAttr>(); #else return (TAttr)Attribute.GetCustomAttribute(type, typeof(TAttr)); #endif } public static TAttr GetCustomAttribute<TAttr>(this PropertyInfo info) where TAttr : Attribute { #if NETSTANDARD1_0 return info.GetCustomAttributes(typeof(TAttr), false).FirstOrDefault() as TAttr; #else return (TAttr)Attribute.GetCustomAttribute(info, typeof(TAttr)); #endif } public static TAttr GetCustomAttribute<TAttr>(this Assembly assembly) where TAttr : Attribute { #if NETSTANDARD1_0 return assembly.GetCustomAttributes(typeof(TAttr)).FirstOrDefault() as TAttr; #else return (TAttr)Attribute.GetCustomAttribute(assembly, typeof(TAttr)); #endif } public static IEnumerable<TAttr> GetCustomAttributes<TAttr>(this Type type, bool inherit) where TAttr : Attribute { #if NETSTANDARD1_0 return type.GetTypeInfo().GetCustomAttributes<TAttr>(inherit); #else return (TAttr[])type.GetCustomAttributes(typeof(TAttr), inherit); #endif } public static Assembly GetAssembly(this Type type) { #if NETSTANDARD1_0 var typeInfo = type.GetTypeInfo(); return typeInfo.Assembly; #else return type.Assembly; #endif } public static bool IsValidPublicProperty(this PropertyInfo p) { return p.CanRead && p.GetIndexParameters().Length == 0 && p.GetGetMethod() != null; } public static object GetPropertyValue(this PropertyInfo p, object instance) { #if NET45 return p.GetValue(instance); #else return p.GetGetMethod().Invoke(instance, null); #endif } } }
// 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 gagvr = Google.Ads.GoogleAds.V10.Resources; using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V10.Resources { /// <summary>Resource name for the <c>CustomizerAttribute</c> resource.</summary> public sealed partial class CustomizerAttributeName : gax::IResourceName, sys::IEquatable<CustomizerAttributeName> { /// <summary>The possible contents of <see cref="CustomizerAttributeName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>customers/{customer_id}/customizerAttributes/{customizer_attribute_id}</c> /// . /// </summary> CustomerCustomizerAttribute = 1, } private static gax::PathTemplate s_customerCustomizerAttribute = new gax::PathTemplate("customers/{customer_id}/customizerAttributes/{customizer_attribute_id}"); /// <summary>Creates a <see cref="CustomizerAttributeName"/> 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="CustomizerAttributeName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static CustomizerAttributeName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new CustomizerAttributeName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="CustomizerAttributeName"/> with the pattern /// <c>customers/{customer_id}/customizerAttributes/{customizer_attribute_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="customizerAttributeId"> /// The <c>CustomizerAttribute</c> ID. Must not be <c>null</c> or empty. /// </param> /// <returns> /// A new instance of <see cref="CustomizerAttributeName"/> constructed from the provided ids. /// </returns> public static CustomizerAttributeName FromCustomerCustomizerAttribute(string customerId, string customizerAttributeId) => new CustomizerAttributeName(ResourceNameType.CustomerCustomizerAttribute, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), customizerAttributeId: gax::GaxPreconditions.CheckNotNullOrEmpty(customizerAttributeId, nameof(customizerAttributeId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="CustomizerAttributeName"/> with pattern /// <c>customers/{customer_id}/customizerAttributes/{customizer_attribute_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="customizerAttributeId"> /// The <c>CustomizerAttribute</c> ID. Must not be <c>null</c> or empty. /// </param> /// <returns> /// The string representation of this <see cref="CustomizerAttributeName"/> with pattern /// <c>customers/{customer_id}/customizerAttributes/{customizer_attribute_id}</c>. /// </returns> public static string Format(string customerId, string customizerAttributeId) => FormatCustomerCustomizerAttribute(customerId, customizerAttributeId); /// <summary> /// Formats the IDs into the string representation of this <see cref="CustomizerAttributeName"/> with pattern /// <c>customers/{customer_id}/customizerAttributes/{customizer_attribute_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="customizerAttributeId"> /// The <c>CustomizerAttribute</c> ID. Must not be <c>null</c> or empty. /// </param> /// <returns> /// The string representation of this <see cref="CustomizerAttributeName"/> with pattern /// <c>customers/{customer_id}/customizerAttributes/{customizer_attribute_id}</c>. /// </returns> public static string FormatCustomerCustomizerAttribute(string customerId, string customizerAttributeId) => s_customerCustomizerAttribute.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(customizerAttributeId, nameof(customizerAttributeId))); /// <summary> /// Parses the given resource name string into a new <see cref="CustomizerAttributeName"/> 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}/customizerAttributes/{customizer_attribute_id}</c></description> /// </item> /// </list> /// </remarks> /// <param name="customizerAttributeName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="CustomizerAttributeName"/> if successful.</returns> public static CustomizerAttributeName Parse(string customizerAttributeName) => Parse(customizerAttributeName, false); /// <summary> /// Parses the given resource name string into a new <see cref="CustomizerAttributeName"/> 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}/customizerAttributes/{customizer_attribute_id}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="customizerAttributeName">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="CustomizerAttributeName"/> if successful.</returns> public static CustomizerAttributeName Parse(string customizerAttributeName, bool allowUnparsed) => TryParse(customizerAttributeName, allowUnparsed, out CustomizerAttributeName 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="CustomizerAttributeName"/> 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}/customizerAttributes/{customizer_attribute_id}</c></description> /// </item> /// </list> /// </remarks> /// <param name="customizerAttributeName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="CustomizerAttributeName"/>, 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 customizerAttributeName, out CustomizerAttributeName result) => TryParse(customizerAttributeName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="CustomizerAttributeName"/> 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}/customizerAttributes/{customizer_attribute_id}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="customizerAttributeName">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="CustomizerAttributeName"/>, 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 customizerAttributeName, bool allowUnparsed, out CustomizerAttributeName result) { gax::GaxPreconditions.CheckNotNull(customizerAttributeName, nameof(customizerAttributeName)); gax::TemplatedResourceName resourceName; if (s_customerCustomizerAttribute.TryParseName(customizerAttributeName, out resourceName)) { result = FromCustomerCustomizerAttribute(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(customizerAttributeName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private CustomizerAttributeName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string customizerAttributeId = null) { Type = type; UnparsedResource = unparsedResourceName; CustomerId = customerId; CustomizerAttributeId = customizerAttributeId; } /// <summary> /// Constructs a new instance of a <see cref="CustomizerAttributeName"/> class from the component parts of /// pattern <c>customers/{customer_id}/customizerAttributes/{customizer_attribute_id}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="customizerAttributeId"> /// The <c>CustomizerAttribute</c> ID. Must not be <c>null</c> or empty. /// </param> public CustomizerAttributeName(string customerId, string customizerAttributeId) : this(ResourceNameType.CustomerCustomizerAttribute, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), customizerAttributeId: gax::GaxPreconditions.CheckNotNullOrEmpty(customizerAttributeId, nameof(customizerAttributeId))) { } /// <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>CustomizerAttribute</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed /// resource name. /// </summary> public string CustomizerAttributeId { 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.CustomerCustomizerAttribute: return s_customerCustomizerAttribute.Expand(CustomerId, CustomizerAttributeId); 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 CustomizerAttributeName); /// <inheritdoc/> public bool Equals(CustomizerAttributeName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(CustomizerAttributeName a, CustomizerAttributeName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(CustomizerAttributeName a, CustomizerAttributeName b) => !(a == b); } public partial class CustomizerAttribute { /// <summary> /// <see cref="gagvr::CustomizerAttributeName"/>-typed view over the <see cref="ResourceName"/> resource name /// property. /// </summary> internal CustomizerAttributeName ResourceNameAsCustomizerAttributeName { get => string.IsNullOrEmpty(ResourceName) ? null : gagvr::CustomizerAttributeName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } /// <summary> /// <see cref="gagvr::CustomizerAttributeName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> internal CustomizerAttributeName CustomizerAttributeName { get => string.IsNullOrEmpty(Name) ? null : gagvr::CustomizerAttributeName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
//------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ namespace Microsoft.Tools.ServiceModel.WsatConfig { using System; using System.IO; using System.Text; using System.Diagnostics; using System.Runtime.InteropServices; static class Utilities { static Nullable<bool> isHttpApiLibAvailable; static string localizedMyComputerString; internal static void Log(string s) { /*using (StreamWriter sw = new StreamWriter("c:\\wsat.log", true)) { sw.WriteLine(s); sw.Flush(); sw.Close(); }*/ } internal static bool SafeCompare(string s1, string s2) { return string.Compare(s1, s2, StringComparison.OrdinalIgnoreCase) == 0; } internal static int OSMajor { get { return System.Environment.OSVersion.Version.Major; } } internal static int GetOSMajor(string machineName) { if (IsLocalMachineName(machineName)) { return OSMajor; } int result = 0; try { IntPtr workstationPtr; const int WorkstationInformationLevel = 100; int hr = SafeNativeMethods.NetWkstaGetInfo( @"\\" + machineName, WorkstationInformationLevel, out workstationPtr); if (hr == SafeNativeMethods.NERR_Success && workstationPtr != IntPtr.Zero) { try { SafeNativeMethods.WKSTA_INFO_100 workstationInfo = (SafeNativeMethods.WKSTA_INFO_100)Marshal.PtrToStructure(workstationPtr, typeof(SafeNativeMethods.WKSTA_INFO_100)); result = workstationInfo.ver_major; } finally { #pragma warning suppress 56523 hr = SafeNativeMethods.NetApiBufferFree(workstationPtr); } workstationPtr = IntPtr.Zero; } } #pragma warning suppress 56500 catch (Exception ex) { if (Utilities.IsCriticalException(ex)) { throw; } } return result; } #if WSAT_CMDLINE internal static string GetEnabledStatusString(bool enabled) { return enabled ? SR.GetString(SR.ConfigStatusEnabled) : SR.GetString(SR.ConfigStatusDiabled); } #endif // We do not parse ActivityTracing in this function internal static bool ParseSourceLevel(string levelString, out SourceLevels level) { level = SourceLevels.Off; if (Utilities.SafeCompare(levelString, CommandLineOption.TracingOff)) { level = SourceLevels.Off; } else if (Utilities.SafeCompare(levelString, CommandLineOption.TracingError)) { level = SourceLevels.Error; } else if (Utilities.SafeCompare(levelString, CommandLineOption.TracingCritical)) { level = SourceLevels.Critical; } else if (Utilities.SafeCompare(levelString, CommandLineOption.TracingWarning)) { level = SourceLevels.Warning; } else if (Utilities.SafeCompare(levelString, CommandLineOption.TracingInformation)) { level = SourceLevels.Information; } else if (Utilities.SafeCompare(levelString, CommandLineOption.TracingVerbose)) { level = SourceLevels.Verbose; } else if (Utilities.SafeCompare(levelString, CommandLineOption.TracingAll)) { level = SourceLevels.All; } else { return false; } return true; } internal static string LocalHostName { get { string hostName; try { hostName = System.Net.Dns.GetHostName(); } catch (System.Net.Sockets.SocketException) { hostName = null; } return hostName; } } internal static bool IsLocalMachineName(string machineName) { const string comResDllName = "ComRes.dll"; const string englishMyComputer = "My Computer"; const int IDS_MYCOMPUTER = 1824; // resource id for My Computer in ComRes.dll if (localizedMyComputerString == null) { // default value localizedMyComputerString = englishMyComputer; #pragma warning suppress 56523 IntPtr comResDll = SafeNativeMethods.LoadLibrary(comResDllName); if (comResDll != IntPtr.Zero) { StringBuilder sb; int len, size = 16; do { sb = new StringBuilder(size); #pragma warning suppress 56523 len = SafeNativeMethods.LoadString(comResDll, IDS_MYCOMPUTER, sb, size); if (len > 0 && len < size) { localizedMyComputerString = sb.ToString(); break; } size *= 2; } while (len > 0); #pragma warning suppress 56523 SafeNativeMethods.FreeLibrary(comResDll); } } return (string.IsNullOrEmpty(machineName) || SafeCompare(machineName, "localhost") || SafeCompare(machineName, localizedMyComputerString) || SafeCompare(machineName, LocalHostName)); } // code from System\ServiceModel\Install\InstallUtil.cs internal static bool IsHttpApiLibAvailable { get { if (!isHttpApiLibAvailable.HasValue) { isHttpApiLibAvailable = IsHttpApiLibAvailableHelper(); } return (bool)isHttpApiLibAvailable.Value; } } static bool IsHttpApiLibAvailableHelper() { bool retVal = false; int retCode = SafeNativeMethods.NoError; try { retCode = SafeNativeMethods.HttpInitialize(new HttpApiVersion(1, 0), SafeNativeMethods.HTTP_INITIALIZE_CONFIG, IntPtr.Zero); SafeNativeMethods.HttpTerminate(SafeNativeMethods.HTTP_INITIALIZE_CONFIG, IntPtr.Zero); if (retCode != SafeNativeMethods.NoError) { retVal = false; } else { retVal = true; } } catch (System.IO.FileNotFoundException) { retVal = false; } return retVal; } internal static bool IsCriticalException(Exception e) { return (e is System.AccessViolationException) || (e is System.StackOverflowException) || (e is System.OutOfMemoryException) || (e is System.InvalidOperationException) || (e is System.Threading.ThreadAbortException); } } }
//----------------------------------------------------------------------- // <copyright file="InstantPreviewManager.cs" company="Google"> // // Copyright 2017 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> //----------------------------------------------------------------------- namespace GoogleARCoreInternal { using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text; using System.Threading; using GoogleARCore; using UnityEngine; using UnityEngine.Rendering; using UnityEngine.SpatialTracking; #if UNITY_EDITOR using UnityEditor; #endif #if UNITY_IOS && !UNITY_EDITOR using AndroidImport = GoogleARCoreInternal.DllImportNoop; using IOSImport = System.Runtime.InteropServices.DllImportAttribute; #else using AndroidImport = System.Runtime.InteropServices.DllImportAttribute; using IOSImport = GoogleARCoreInternal.DllImportNoop; #endif /// <summary> /// Contains methods for managing communication to the Instant Preview /// plugin. /// </summary> public static class InstantPreviewManager { /// <summary> /// Name of the Instant Preview plugin library. /// </summary> public const string InstantPreviewNativeApi = "arcore_instant_preview_unity_plugin"; // Guid is taken from meta file and should never change. private const string k_ApkGuid = "cf7b10762fe921e40a18151a6c92a8a6"; private const string k_NoDevicesFoundAdbResult = "error: no devices/emulators found"; private const float k_MaxTolerableAspectRatioDifference = 0.1f; private const string k_MismatchedAspectRatioWarningFormatString = "Instant Preview camera texture aspect ratio ({0}) is different than Game view " + "aspect ratio ({1}).\n" + " To avoid distorted preview while using Instant Preview, set the Game view Aspect " + "to match the camera texture resolution ({2}x{3})."; private const string k_InstantPreviewInputWarning = "Touch ignored. Make sure your script contains `using Input = InstantPreviewInput;` " + "when using editor Play mode.\nTo learn more, see " + "https://developers.google.com/ar/develop/unity/instant-preview"; private const string k_WarningToastFormat = "Instant Preview is not able to {0}. See " + "Unity console."; private const int k_WarningThrottleTimeSeconds = 5; private const float k_UnknownGameViewScale = (float)Single.MinValue; private static readonly WaitForEndOfFrame k_WaitForEndOfFrame = new WaitForEndOfFrame(); private static Dictionary<string, DateTime> s_SentWarnings = new Dictionary<string, DateTime>(); /// <summary> /// Gets a value indicating whether Instant Preview is providing the ARCore platform for the /// current environment. /// </summary> /// <value>Whether Instant Preview is providing the ARCore platform for the current /// environment.</value> public static bool IsProvidingPlatform { get { return Application.isEditor; } } /// <summary> /// Logs a limited support message to the console for an instant preview feature. /// </summary> /// <param name="featureName">The name of the feature that has limited support.</param> public static void LogLimitedSupportMessage(string featureName) { Debug.LogErrorFormat( "Attempted to {0} which is not yet supported by Instant Preview.\n" + "Please build and run on device to use this feature.", featureName); if (!s_SentWarnings.ContainsKey(featureName) || (DateTime.UtcNow - s_SentWarnings[featureName]).TotalSeconds >= k_WarningThrottleTimeSeconds) { string warning = string.Format(k_WarningToastFormat, featureName); NativeApi.SendToast(warning); s_SentWarnings[featureName] = DateTime.UtcNow; } } /// <summary> /// Coroutine method that communicates to the Instant Preview plugin /// every frame. /// /// If not running in the editor, this does nothing. /// </summary> /// <returns>Enumerator for a coroutine that updates Instant Preview /// every frame.</returns> public static IEnumerator InitializeIfNeeded() { // Terminates if not running in editor. if (!Application.isEditor) { yield break; } // User may have explicitly disabled Instant Preview. if (ARCoreProjectSettings.Instance != null && !ARCoreProjectSettings.Instance.IsInstantPreviewEnabled) { yield break; } #if UNITY_EDITOR // When build platform is not Android, verify min game view scale is 1.0x to prevent // confusing 2x scaling when Unity editor is running on a high density display. if (EditorUserBuildSettings.activeBuildTarget != BuildTarget.Android) { float minGameViewScale = GetMinGameViewScaleOrUnknown(); if (minGameViewScale != 1.0) { String viewScaleText = minGameViewScale == k_UnknownGameViewScale ? "<unknown>" : string.Format("{0}x", minGameViewScale); Debug.LogWarningFormat( "Instant Preview disabled, {0} minimum Game view scale unsupported for " + "target build platform '{1}'.\n" + "To use Instant Preview, switch build platform to '{2}' from the 'Build " + "settings' window.", viewScaleText, EditorUserBuildSettings.activeBuildTarget, BuildTarget.Android); yield break; } } // Determine if any augmented image databases need a rebuild. List<AugmentedImageDatabase> databases = new List<AugmentedImageDatabase>(); bool shouldRebuild = false; var augmentedImageDatabaseGuids = AssetDatabase.FindAssets("t:AugmentedImageDatabase"); foreach (var databaseGuid in augmentedImageDatabaseGuids) { var database = AssetDatabase.LoadAssetAtPath<AugmentedImageDatabase>( AssetDatabase.GUIDToAssetPath(databaseGuid)); databases.Add(database); shouldRebuild = shouldRebuild || database.IsBuildNeeded(); } // If the preference is to ask the user to rebuild, ask now. if (shouldRebuild && PromptToRebuildAugmentedImagesDatabase()) { foreach (var database in databases) { string error; database.BuildIfNeeded(out error); if (!string.IsNullOrEmpty(error)) { Debug.LogWarning("Failed to rebuild augmented image database: " + error); } } } #endif var adbPath = ShellHelper.GetAdbPath(); if (adbPath == null) { Debug.LogError("Instant Preview requires your Unity Android SDK path to be set. " + "Please set it under 'Preferences > External Tools > Android'. " + "You may need to install the Android SDK first."); yield break; } else if (!File.Exists(adbPath)) { Debug.LogErrorFormat( "adb not found at \"{0}\". Please verify that 'Preferences > External Tools " + "> Android' has the correct Android SDK path that the Android Platform Tools " + "are installed, and that \"{0}\" exists. You may need to install the Android " + "SDK first.", adbPath); yield break; } string localVersion; if (!StartServer(adbPath, out localVersion)) { yield break; } yield return InstallApkAndRunIfConnected(adbPath, localVersion); yield return UpdateLoop(adbPath); } /// <summary> /// Uploads the latest camera video frame received from Instant Preview /// to the specified texture. The texture might be recreated if it is /// not the right size or null. /// </summary> /// <param name="backgroundTexture">Texture variable to store the latest /// Instant Preview video frame.</param> /// <returns>True if InstantPreview updated the background texture, /// false if it did not and the texture still needs updating.</returns> public static bool UpdateBackgroundTextureIfNeeded(ref Texture2D backgroundTexture) { if (!Application.isEditor) { return false; } IntPtr pixelBytes; int width; int height; if (NativeApi.LockCameraTexture(out pixelBytes, out width, out height)) { if (backgroundTexture == null || width != backgroundTexture.width || height != backgroundTexture.height) { backgroundTexture = new Texture2D(width, height, TextureFormat.BGRA32, false); } backgroundTexture.LoadRawTextureData(pixelBytes, width * height * 4); backgroundTexture.Apply(); NativeApi.UnlockCameraTexture(); } return true; } private static IEnumerator UpdateLoop(string adbPath) { var renderEventFunc = NativeApi.GetRenderEventFunc(); var shouldConvertToBgra = SystemInfo.graphicsDeviceType == GraphicsDeviceType.Direct3D11; var loggedAspectRatioWarning = false; // Waits until the end of the first frame until capturing the screen size, // because it might be incorrect when first querying it. yield return k_WaitForEndOfFrame; var currentWidth = 0; var currentHeight = 0; var needToStartActivity = true; var prevFrameLandscape = false; RenderTexture screenTexture = null; RenderTexture targetTexture = null; RenderTexture bgrTexture = null; // Begins update loop. The coroutine will cease when the // ARCoreSession component it's called from is destroyed. for (;;) { yield return k_WaitForEndOfFrame; var curFrameLandscape = Screen.width > Screen.height; if (prevFrameLandscape != curFrameLandscape) { needToStartActivity = true; } prevFrameLandscape = curFrameLandscape; if (needToStartActivity) { string activityName = curFrameLandscape ? "InstantPreviewLandscapeActivity" : "InstantPreviewActivity"; string output; string errors; ShellHelper.RunCommand(adbPath, "shell am start -S -n com.google.ar.core.instantpreview/." + activityName, out output, out errors); needToStartActivity = false; } // Creates a target texture to capture the preview window onto. // Some video encoders prefer the dimensions to be a multiple of 16. var targetWidth = RoundUpToNearestMultipleOf16(Screen.width); var targetHeight = RoundUpToNearestMultipleOf16(Screen.height); if (targetWidth != currentWidth || targetHeight != currentHeight) { screenTexture = new RenderTexture(targetWidth, targetHeight, 0); targetTexture = screenTexture; if (shouldConvertToBgra) { bgrTexture = new RenderTexture( screenTexture.width, screenTexture.height, 0, RenderTextureFormat.BGRA32); targetTexture = bgrTexture; } currentWidth = targetWidth; currentHeight = targetHeight; } NativeApi.Update(); InstantPreviewInput.Update(); if (NativeApi.AppShowedTouchWarning()) { Debug.LogWarning(k_InstantPreviewInputWarning); NativeApi.UnityLoggedTouchWarning(); } AddInstantPreviewTrackedPoseDriverWhenNeeded(); Graphics.Blit(null, screenTexture); if (shouldConvertToBgra) { Graphics.Blit(screenTexture, bgrTexture); } var cameraTexture = Frame.CameraImage.Texture; if (!loggedAspectRatioWarning && cameraTexture != null) { var sourceWidth = cameraTexture.width; var sourceHeight = cameraTexture.height; var sourceAspectRatio = (float)sourceWidth / sourceHeight; var destinationWidth = Screen.width; var destinationHeight = Screen.height; var destinationAspectRatio = (float)destinationWidth / destinationHeight; if (Mathf.Abs(sourceAspectRatio - destinationAspectRatio) > k_MaxTolerableAspectRatioDifference) { Debug.LogWarningFormat( k_MismatchedAspectRatioWarningFormatString, sourceAspectRatio, destinationAspectRatio, sourceWidth, sourceHeight); loggedAspectRatioWarning = true; } } NativeApi.SendFrame(targetTexture.GetNativeTexturePtr()); GL.IssuePluginEvent(renderEventFunc, 1); } } private static void AddInstantPreviewTrackedPoseDriverWhenNeeded() { foreach (var poseDriver in Component.FindObjectsOfType<TrackedPoseDriver>()) { poseDriver.enabled = false; var gameObject = poseDriver.gameObject; var hasInstantPreviewTrackedPoseDriver = gameObject.GetComponent<InstantPreviewTrackedPoseDriver>() != null; if (!hasInstantPreviewTrackedPoseDriver) { gameObject.AddComponent<InstantPreviewTrackedPoseDriver>(); } } } /// <summary> /// Tries to install and run the Instant Preview android app. /// </summary> /// <param name="adbPath">Path to adb to use for installing.</param> /// <param name="localVersion">Local version of Instant Preview plugin to compare installed /// APK against.</param> /// <returns>Enumerator for coroutine that handles installation if necessary.</returns> private static IEnumerator InstallApkAndRunIfConnected(string adbPath, string localVersion) { string apkPath = null; #if UNITY_EDITOR apkPath = UnityEditor.AssetDatabase.GUIDToAssetPath(k_ApkGuid); #endif // !UNITY_EDITOR // Early outs if set to install but the apk can't be found. if (!File.Exists(apkPath)) { Debug.LogErrorFormat( "Trying to install Instant Preview APK but reference to InstantPreview.apk " + "is broken. Couldn't find an asset with .meta file guid={0}.", k_ApkGuid); yield break; } Result result = new Result(); Thread checkAdbThread = new Thread((object obj) => { Result res = (Result)obj; string output; string errors; // Gets version of installed apk. ShellHelper.RunCommand(adbPath, "shell dumpsys package com.google.ar.core.instantpreview | grep versionName", out output, out errors); string installedVersion = null; if (!string.IsNullOrEmpty(output) && string.IsNullOrEmpty(errors)) { installedVersion = output.Substring(output.IndexOf('=') + 1); } // Early outs if no device is connected. if (string.Compare(errors, k_NoDevicesFoundAdbResult) == 0) { return; } // Prints errors and exits on failure. if (!string.IsNullOrEmpty(errors)) { Debug.LogError(errors); return; } if (installedVersion == null) { Debug.LogFormat( "Instant Preview app not installed on device.", apkPath); } else if (installedVersion != localVersion) { Debug.LogFormat( "Instant Preview installed version \"{0}\" does not match local version " + "\"{1}\".", installedVersion, localVersion); } res.ShouldPromptForInstall = installedVersion != localVersion; }); checkAdbThread.Start(result); while (!checkAdbThread.Join(0)) { yield return 0; } if (result.ShouldPromptForInstall) { if (PromptToInstall()) { Thread installThread = new Thread(() => { string output; string errors; Debug.LogFormat( "Installing Instant Preview app version {0}.", localVersion); ShellHelper.RunCommand(adbPath, "uninstall com.google.ar.core.instantpreview", out output, out errors); ShellHelper.RunCommand(adbPath, string.Format("install \"{0}\"", apkPath), out output, out errors); // Prints any output from trying to install. if (!string.IsNullOrEmpty(output)) { Debug.LogFormat("Instant Preview installation:\n{0}", output); } if (!string.IsNullOrEmpty(errors) && errors != "Success") { Debug.LogErrorFormat( "Failed to install Instant Preview app:\n{0}", errors); } }); installThread.Start(); while (!installThread.Join(0)) { yield return 0; } } else { yield break; } } } private static bool PromptToInstall() { #if UNITY_EDITOR return UnityEditor.EditorUtility.DisplayDialog( "Instant Preview", "To instantly reflect your changes on device, the Instant Preview app will be " + "installed on your connected device.\n\nTo disable Instant Preview in this " + "project, uncheck 'Instant Preview Enabled' under 'Edit > Project Settings > " + "ARCore'.", "Okay", "Don't Install This Time"); #else return false; #endif } private static bool PromptToRebuildAugmentedImagesDatabase() { #if UNITY_EDITOR return UnityEditor.EditorUtility.DisplayDialog( "Augmented Images", "The Augmented Images database is out of date, rebuild it now?", "Build", "Don't Build This Time"); #else return false; #endif } private static bool StartServer(string adbPath, out string version) { // Tries to start server. const int k_InstantPreviewVersionStringMaxLength = 64; var versionStringBuilder = new StringBuilder(k_InstantPreviewVersionStringMaxLength); var started = NativeApi.InitializeInstantPreview( adbPath, versionStringBuilder, versionStringBuilder.Capacity); if (!started) { Debug.LogErrorFormat( "Couldn't start Instant Preview server with adb path \"{0}\".", adbPath); version = null; return false; } version = versionStringBuilder.ToString(); Debug.LogFormat( "Instant Preview version {0}\n" + "To disable Instant Preview in this project, uncheck 'Instant Preview Enabled' " + "under 'Edit > Project Settings > ARCore'.", version); return true; } private static int RoundUpToNearestMultipleOf16(int value) { return (value + 15) & ~15; } private static float GetMinGameViewScaleOrUnknown() { try { var gameViewType = Type.GetType("UnityEditor.GameView,UnityEditor"); if (gameViewType == null) { return k_UnknownGameViewScale; } UnityEngine.Object[] gameViewObjects = UnityEngine.Resources.FindObjectsOfTypeAll(gameViewType); if (gameViewObjects == null || gameViewObjects.Length == 0) { return k_UnknownGameViewScale; } PropertyInfo minScaleProperty = gameViewType.GetProperty( "minScale", BindingFlags.Instance | BindingFlags.NonPublic); if (minScaleProperty == null) { return k_UnknownGameViewScale; } return (float)minScaleProperty.GetValue(gameViewObjects[0], null); } catch { return k_UnknownGameViewScale; } } private struct NativeApi { #pragma warning disable 626 [AndroidImport(InstantPreviewNativeApi)] public static extern bool InitializeInstantPreview( string adbPath, StringBuilder version, int versionStringLength); [AndroidImport(InstantPreviewNativeApi)] public static extern void Update(); [AndroidImport(InstantPreviewNativeApi)] public static extern IntPtr GetRenderEventFunc(); [AndroidImport(InstantPreviewNativeApi)] public static extern void SendFrame(IntPtr renderTexture); [AndroidImport(InstantPreviewNativeApi)] public static extern bool LockCameraTexture(out IntPtr pixelBytes, out int width, out int height); [AndroidImport(InstantPreviewNativeApi)] public static extern void UnlockCameraTexture(); [AndroidImport(InstantPreviewNativeApi)] public static extern bool IsConnected(); [AndroidImport(InstantPreviewNativeApi)] public static extern bool AppShowedTouchWarning(); [AndroidImport(InstantPreviewNativeApi)] public static extern bool UnityLoggedTouchWarning(); [AndroidImport(InstantPreviewNativeApi)] public static extern void SendToast(string toastMessage); #pragma warning restore 626 } private class Result { public bool ShouldPromptForInstall = false; } } }
// 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 System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.ReferenceHighlighting { internal abstract class AbstractDocumentHighlightsService : IDocumentHighlightsService { public async Task<ImmutableArray<DocumentHighlights>> GetDocumentHighlightsAsync( Document document, int position, IImmutableSet<Document> documentsToSearch, CancellationToken cancellationToken) { // use speculative semantic model to see whether we are on a symbol we can do HR var span = new TextSpan(position, 0); var solution = document.Project.Solution; var semanticModel = await document.GetSemanticModelForSpanAsync(span, cancellationToken).ConfigureAwait(false); var symbol = await SymbolFinder.FindSymbolAtPositionAsync( semanticModel, position, solution.Workspace, cancellationToken).ConfigureAwait(false); if (symbol == null) { return ImmutableArray<DocumentHighlights>.Empty; } symbol = await GetSymbolToSearchAsync(document, position, semanticModel, symbol, cancellationToken).ConfigureAwait(false); if (symbol == null) { return ImmutableArray<DocumentHighlights>.Empty; } // Get unique tags for referenced symbols return await GetTagsForReferencedSymbolAsync( new SymbolAndProjectId(symbol, document.Project.Id), documentsToSearch, solution, cancellationToken).ConfigureAwait(false); } private async Task<ISymbol> GetSymbolToSearchAsync(Document document, int position, SemanticModel semanticModel, ISymbol symbol, CancellationToken cancellationToken) { // see whether we can use the symbol as it is var currentSemanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); if (currentSemanticModel == semanticModel) { return symbol; } // get symbols from current document again return await SymbolFinder.FindSymbolAtPositionAsync(currentSemanticModel, position, document.Project.Solution.Workspace, cancellationToken).ConfigureAwait(false); } private async Task<ImmutableArray<DocumentHighlights>> GetTagsForReferencedSymbolAsync( SymbolAndProjectId symbolAndProjectId, IImmutableSet<Document> documentsToSearch, Solution solution, CancellationToken cancellationToken) { var symbol = symbolAndProjectId.Symbol; Contract.ThrowIfNull(symbol); if (ShouldConsiderSymbol(symbol)) { var progress = new StreamingProgressCollector( StreamingFindReferencesProgress.Instance); await SymbolFinder.FindReferencesAsync( symbolAndProjectId, solution, progress, documentsToSearch, cancellationToken).ConfigureAwait(false); return await FilterAndCreateSpansAsync( progress.GetReferencedSymbols(), solution, documentsToSearch, symbol, cancellationToken).ConfigureAwait(false); } return ImmutableArray<DocumentHighlights>.Empty; } private bool ShouldConsiderSymbol(ISymbol symbol) { switch (symbol.Kind) { case SymbolKind.Method: switch (((IMethodSymbol)symbol).MethodKind) { case MethodKind.AnonymousFunction: case MethodKind.PropertyGet: case MethodKind.PropertySet: case MethodKind.EventAdd: case MethodKind.EventRaise: case MethodKind.EventRemove: return false; default: return true; } default: return true; } } private async Task<ImmutableArray<DocumentHighlights>> FilterAndCreateSpansAsync( IEnumerable<ReferencedSymbol> references, Solution solution, IImmutableSet<Document> documentsToSearch, ISymbol symbol, CancellationToken cancellationToken) { references = references.FilterToItemsToShow(); references = references.FilterNonMatchingMethodNames(solution, symbol); references = references.FilterToAliasMatches(symbol as IAliasSymbol); if (symbol.IsConstructor()) { references = references.Where(r => r.Definition.OriginalDefinition.Equals(symbol.OriginalDefinition)); } var additionalReferences = new List<Location>(); foreach (var document in documentsToSearch) { additionalReferences.AddRange(await GetAdditionalReferencesAsync(document, symbol, cancellationToken).ConfigureAwait(false)); } return await CreateSpansAsync( solution, symbol, references, additionalReferences, documentsToSearch, cancellationToken).ConfigureAwait(false); } private Task<IEnumerable<Location>> GetAdditionalReferencesAsync( Document document, ISymbol symbol, CancellationToken cancellationToken) { var additionalReferenceProvider = document.Project.LanguageServices.GetService<IReferenceHighlightingAdditionalReferenceProvider>(); if (additionalReferenceProvider != null) { return additionalReferenceProvider.GetAdditionalReferencesAsync(document, symbol, cancellationToken); } return Task.FromResult(SpecializedCollections.EmptyEnumerable<Location>()); } private async Task<ImmutableArray<DocumentHighlights>> CreateSpansAsync( Solution solution, ISymbol symbol, IEnumerable<ReferencedSymbol> references, IEnumerable<Location> additionalReferences, IImmutableSet<Document> documentToSearch, CancellationToken cancellationToken) { var spanSet = new HashSet<ValueTuple<Document, TextSpan>>(); var tagMap = new MultiDictionary<Document, HighlightSpan>(); bool addAllDefinitions = true; // Add definitions // Filter out definitions that cannot be highlighted. e.g: alias symbols defined via project property pages. if (symbol.Kind == SymbolKind.Alias && symbol.Locations.Length > 0) { addAllDefinitions = false; if (symbol.Locations.First().IsInSource) { // For alias symbol we want to get the tag only for the alias definition, not the target symbol's definition. await AddLocationSpan(symbol.Locations.First(), solution, spanSet, tagMap, HighlightSpanKind.Definition, cancellationToken).ConfigureAwait(false); } } // Add references and definitions foreach (var reference in references) { if (addAllDefinitions && ShouldIncludeDefinition(reference.Definition)) { foreach (var location in reference.Definition.Locations) { if (location.IsInSource) { var document = solution.GetDocument(location.SourceTree); // GetDocument will return null for locations in #load'ed trees. // TODO: Remove this check and add logic to fetch the #load'ed tree's // Document once https://github.com/dotnet/roslyn/issues/5260 is fixed. if (document == null) { Debug.Assert(solution.Workspace.Kind == "Interactive"); continue; } if (documentToSearch.Contains(document)) { await AddLocationSpan(location, solution, spanSet, tagMap, HighlightSpanKind.Definition, cancellationToken).ConfigureAwait(false); } } } } foreach (var referenceLocation in reference.Locations) { var referenceKind = referenceLocation.IsWrittenTo ? HighlightSpanKind.WrittenReference : HighlightSpanKind.Reference; await AddLocationSpan(referenceLocation.Location, solution, spanSet, tagMap, referenceKind, cancellationToken).ConfigureAwait(false); } } // Add additional references foreach (var location in additionalReferences) { await AddLocationSpan(location, solution, spanSet, tagMap, HighlightSpanKind.Reference, cancellationToken).ConfigureAwait(false); } var list = ArrayBuilder<DocumentHighlights>.GetInstance(tagMap.Count); foreach (var kvp in tagMap) { var spans = ArrayBuilder<HighlightSpan>.GetInstance(kvp.Value.Count); foreach (var span in kvp.Value) { spans.Add(span); } list.Add(new DocumentHighlights(kvp.Key, spans.ToImmutableAndFree())); } return list.ToImmutableAndFree(); } private static bool ShouldIncludeDefinition(ISymbol symbol) { switch (symbol.Kind) { case SymbolKind.Namespace: return false; case SymbolKind.NamedType: return !((INamedTypeSymbol)symbol).IsScriptClass; case SymbolKind.Parameter: // If it's an indexer parameter, we will have also cascaded to the accessor // one that actually receives the references var containingProperty = symbol.ContainingSymbol as IPropertySymbol; if (containingProperty != null && containingProperty.IsIndexer) { return false; } break; } return true; } private async Task AddLocationSpan(Location location, Solution solution, HashSet<ValueTuple<Document, TextSpan>> spanSet, MultiDictionary<Document, HighlightSpan> tagList, HighlightSpanKind kind, CancellationToken cancellationToken) { var span = await GetLocationSpanAsync(solution, location, cancellationToken).ConfigureAwait(false); if (span != null && !spanSet.Contains(span.Value)) { spanSet.Add(span.Value); tagList.Add(span.Value.Item1, new HighlightSpan(span.Value.Item2, kind)); } } private async Task<ValueTuple<Document, TextSpan>?> GetLocationSpanAsync( Solution solution, Location location, CancellationToken cancellationToken) { try { if (location != null && location.IsInSource) { var tree = location.SourceTree; var document = solution.GetDocument(tree); var syntaxFacts = document.Project.LanguageServices.GetService<ISyntaxFactsService>(); if (syntaxFacts != null) { // Specify findInsideTrivia: true to ensure that we search within XML doc comments. var root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindToken(location.SourceSpan.Start, findInsideTrivia: true); return syntaxFacts.IsGenericName(token.Parent) || syntaxFacts.IsIndexerMemberCRef(token.Parent) ? ValueTuple.Create(document, token.Span) : ValueTuple.Create(document, location.SourceSpan); } } } catch (NullReferenceException e) when (FatalError.ReportWithoutCrash(e)) { // We currently are seeing a strange null references crash in this code. We have // a strong belief that this is recoverable, but we'd like to know why it is // happening. This exception filter allows us to report the issue and continue // without damaging the user experience. Once we get more crash reports, we // can figure out the root cause and address appropriately. This is preferable // to just using conditionl access operators to be resilient (as we won't actually // know why this is happening). } return null; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.Docs.Build { using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Threading.Tasks.Dataflow; using Microsoft.Docs.Glob; using Microsoft.Docs.Markdown; using static Util; /// <summary> /// A build step is an action, when completed, yields all child build steps to spawn. /// A parent build step should NEVER depend on the result of a child build step. /// /// By yielding child build steps: /// - we create a dynamic build scope based on the root build scope /// - we can choose not to execute child build scopes in *watch* mode /// </summary> public delegate IEnumerable<BuildStep> BuildStep(); public static partial class DocsBuild { public static Task Build(string projectPath, BuildOutput output = null) => Build(BuildInput.Create(projectPath), output ?? new BuildOutput()); public static Task Build(BuildInput input, BuildOutput output) => Execute(BuildProject(new BuildContext { In = input, Out = output }), output); public static Task Restore(string projectPath, BuildOutput output = null) => Execute(Restore(BuildInput.Create(projectPath).Config), output ?? new BuildOutput()); public static Task Watch(string projectPath, BuildOutput output = null, CancellationToken ct = default) => Build(BuildInput.Create(projectPath), output ?? new BuildOutput()); public static BuildStep BuildProject(BuildContext context) => () => GlobInput(context.In).Select(file => BuildDocument(context, file)); public static BuildStep Restore(Config config) => () => { return config.Dependencies.Select(dep => FetchOrCloneRepo(dep.Value)); BuildStep FetchOrCloneRepo(string href) => () => { var (dir, url) = DependencyLocation(href); var psi = Directory.Exists(Path.Combine(dir, ".git")) ? new ProcessStartInfo { FileName = "git", Arguments = $"pull", WorkingDirectory = dir } : new ProcessStartInfo { FileName = "git", Arguments = $"clone \"{url}\" \"{dir}\"" }; psi.UseShellExecute = false; psi.RedirectStandardError = true; psi.RedirectStandardInput = true; psi.RedirectStandardOutput = true; var p = Process.Start(psi); p.WaitForExit(); if (p.ExitCode != 0) { throw new InvalidOperationException(p.StandardError.ReadToEnd()); } return null; }; }; private static readonly string RestoreDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".ops", "git"); public static (string dir, string url) DependencyLocation(string href) { var uri = new Uri(href); var rev = string.IsNullOrEmpty(uri.Fragment) ? "master" : uri.Fragment; var url = uri.GetLeftPart(UriPartial.Path); var repo = Path.Combine(uri.Host, uri.AbsolutePath.Substring(1)); var dir = Path.Combine(RestoreDir, repo, rev); return (dir, url); } public static IEnumerable<BuildFile> GlobInput(BuildInput input) => from file in input.Config.Files let sitePath = Path.Combine(input.ProjectPath, file.Key) from fullPath in FileGlob.GetFiles(sitePath, file.Value.Include, file.Value.Exclude) select BuildFile.Create(fullPath, input.ProjectPath, input.ProjectRepoPath, sitePath); public static BuildFile Resolve(BuildContext context, string href, BuildFile relativeTo) { if (!IsRelative(href)) return null; Debug.Assert(!Path.IsPathRooted(href)); var hrefPath = NormalizeFile(GetPath(href)); var pathToProject = NormalizeFile(Path.Combine(Path.GetDirectoryName(relativeTo.PathToProject), hrefPath)); if (context.In.Redirections.TryGetValue(pathToProject, out var redirectedPath)) return null; var fullPath = Path.Combine(Path.GetDirectoryName(relativeTo.FullPath), hrefPath); if (!File.Exists(fullPath)) { var depFile = ResolveDependency(); if (depFile != null) return depFile; throw new InvalidOperationException($"Cannot resolve '{href}' relative to '{relativeTo.PathToProject ?? relativeTo.FullPath}'"); } var sitePath = context.In.Config.Files.Keys.Select(dir => InsideDir(pathToProject, dir)).FirstOrDefault(p => p != null); return BuildFile.Create(fullPath, context.In.ProjectPath, context.In.ProjectRepoPath, sitePath ?? context.In.ProjectPath); bool IsRelative(string str) { return !str.StartsWith('#') && !str.StartsWith('/') && !str.StartsWith('\\') && !string.IsNullOrWhiteSpace(str) && Uri.TryCreate(str, UriKind.Relative, out _); } string GetPath(string uri) { var i = uri.IndexOfAny(new[] { '#', '?' }); return i >= 0 ? uri.Substring(0, i) : uri; } string InsideDir(string path, string dir) { return NormalizeFile(path).StartsWith(NormalizeFolder(dir), StringComparison.OrdinalIgnoreCase) ? Path.Combine(context.In.ProjectPath, dir) : null; } BuildFile ResolveDependency() { foreach (var (dep, url) in context.In.Config.Dependencies) { if (!pathToProject.StartsWith(dep, StringComparison.OrdinalIgnoreCase)) continue; var (dir, _) = DependencyLocation(url); var depFullPath = Path.Combine(dir, Path.GetRelativePath(dep, pathToProject)); if (!File.Exists(depFullPath)) continue; return BuildFile.Create(depFullPath, null, dir, dir); } return null; } } public static BuildStep BuildDocument(BuildContext context, BuildFile file) { if (file.PathToSite == null) return null; if (!context.SiteMap.TryAdd(file.PathToSite, file.FullPath)) return null; switch (Path.GetExtension(file.FullPath).ToLowerInvariant()) { case ".md": return BuildMarkdown(context, file); default: return CopyToOutput(context, file); } } public static BuildStep CopyToOutput(BuildContext context, BuildFile file) => () => { var outputPath = Path.Combine(context.In.OutDir, file.PathToSite); if (File.Exists(outputPath)) return null; Directory.CreateDirectory(Path.GetDirectoryName(outputPath)); File.Copy(file.FullPath, outputPath, true); return null; }; public async static Task Execute(BuildStep root, BuildOutput output) { if (root == null) return; ActionBlock<BuildStep> queue = null; var total = 1; var done = 0; var queueOptions = new ExecutionDataflowBlockOptions { // The queue has to be unbounded to avoid deadlock // https://blogs.msdn.microsoft.com/seteplia/2016/12/20/dissecting-the-actionblock-a-short-story-about-a-nasty-deadlock/ MaxDegreeOfParallelism = DataflowBlockOptions.Unbounded, BoundedCapacity = DataflowBlockOptions.Unbounded, }; queue = new ActionBlock<BuildStep>(step => { try { var deps = step(); if (deps == null) return; foreach (var dep in deps) { if (dep == null) continue; output.Progress(done, Interlocked.Increment(ref total)); var posted = queue.Post(dep); Debug.Assert(posted); } } catch (Exception ex) { output.Error(ex); } finally { var completed = (Interlocked.Increment(ref done) == Volatile.Read(ref total)); output.Progress(done, total); if (completed) queue.Complete(); } }, queueOptions); await queue.SendAsync(root); await queue.Completion; } } }
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 TodoApp.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; } } }
// 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.IO; using System.Text; using System.Diagnostics; using System.Globalization; 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 { internal sealed partial class CertificatePal : IDisposable, ICertificatePal { public static ICertificatePal FromBlob(byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags) { return FromBlobOrFile(rawData, null, password, keyStorageFlags); } public static ICertificatePal FromFile(string fileName, string password, X509KeyStorageFlags keyStorageFlags) { return FromBlobOrFile(null, fileName, password, keyStorageFlags); } private static ICertificatePal FromBlobOrFile(byte[] rawData, string fileName, string password, X509KeyStorageFlags keyStorageFlags) { Debug.Assert(rawData != null || fileName != null); bool loadFromFile = (fileName != null); PfxCertStoreFlags pfxCertStoreFlags = MapKeyStorageFlags(keyStorageFlags); bool persistKeySet = (0 != (keyStorageFlags & X509KeyStorageFlags.PersistKeySet)); CertEncodingType msgAndCertEncodingType; ContentType contentType; FormatType formatType; SafeCertStoreHandle hCertStore = null; SafeCryptMsgHandle hCryptMsg = null; SafeCertContextHandle pCertContext = null; try { unsafe { fixed (byte* pRawData = rawData) { fixed (char* pFileName = fileName) { CRYPTOAPI_BLOB certBlob = new CRYPTOAPI_BLOB(loadFromFile ? 0 : rawData.Length, pRawData); CertQueryObjectType objectType = loadFromFile ? CertQueryObjectType.CERT_QUERY_OBJECT_FILE : CertQueryObjectType.CERT_QUERY_OBJECT_BLOB; void* pvObject = loadFromFile ? (void*)pFileName : (void*)&certBlob; bool success = Interop.crypt32.CryptQueryObject( objectType, pvObject, X509ExpectedContentTypeFlags, X509ExpectedFormatTypeFlags, 0, out msgAndCertEncodingType, out contentType, out formatType, out hCertStore, out hCryptMsg, out pCertContext ); if (!success) { int hr = Marshal.GetHRForLastWin32Error(); throw hr.ToCryptographicException(); } } } if (contentType == ContentType.CERT_QUERY_CONTENT_PKCS7_SIGNED || contentType == ContentType.CERT_QUERY_CONTENT_PKCS7_SIGNED_EMBED) { pCertContext = GetSignerInPKCS7Store(hCertStore, hCryptMsg); } else if (contentType == ContentType.CERT_QUERY_CONTENT_PFX) { if (loadFromFile) rawData = File.ReadAllBytes(fileName); pCertContext = FilterPFXStore(rawData, password, pfxCertStoreFlags); } CertificatePal pal = new CertificatePal(pCertContext, deleteKeyContainer: !persistKeySet); pCertContext = null; return pal; } } finally { if (hCertStore != null) hCertStore.Dispose(); if (hCryptMsg != null) hCryptMsg.Dispose(); if (pCertContext != null) pCertContext.Dispose(); } } private static SafeCertContextHandle GetSignerInPKCS7Store(SafeCertStoreHandle hCertStore, SafeCryptMsgHandle hCryptMsg) { // make sure that there is at least one signer of the certificate store int dwSigners; int cbSigners = sizeof(int); if (!Interop.crypt32.CryptMsgGetParam(hCryptMsg, CryptMessageParameterType.CMSG_SIGNER_COUNT_PARAM, 0, out dwSigners, ref cbSigners)) throw Marshal.GetHRForLastWin32Error().ToCryptographicException();; if (dwSigners == 0) throw ErrorCode.CRYPT_E_SIGNER_NOT_FOUND.ToCryptographicException(); // get the first signer from the store, and use that as the loaded certificate int cbData = 0; if (!Interop.crypt32.CryptMsgGetParam(hCryptMsg, CryptMessageParameterType.CMSG_SIGNER_INFO_PARAM, 0, null, ref cbData)) throw Marshal.GetHRForLastWin32Error().ToCryptographicException();; byte[] cmsgSignerBytes = new byte[cbData]; if (!Interop.crypt32.CryptMsgGetParam(hCryptMsg, CryptMessageParameterType.CMSG_SIGNER_INFO_PARAM, 0, cmsgSignerBytes, ref cbData)) throw Marshal.GetHRForLastWin32Error().ToCryptographicException();; CERT_INFO certInfo = default(CERT_INFO); unsafe { fixed (byte* pCmsgSignerBytes = cmsgSignerBytes) { CMSG_SIGNER_INFO_Partial* pCmsgSignerInfo = (CMSG_SIGNER_INFO_Partial*)pCmsgSignerBytes; certInfo.Issuer.cbData = pCmsgSignerInfo->Issuer.cbData; certInfo.Issuer.pbData = pCmsgSignerInfo->Issuer.pbData; certInfo.SerialNumber.cbData = pCmsgSignerInfo->SerialNumber.cbData; certInfo.SerialNumber.pbData = pCmsgSignerInfo->SerialNumber.pbData; } SafeCertContextHandle pCertContext = null; if (!Interop.crypt32.CertFindCertificateInStore(hCertStore, CertFindType.CERT_FIND_SUBJECT_CERT, &certInfo, ref pCertContext)) throw Marshal.GetHRForLastWin32Error().ToCryptographicException();; return pCertContext; } } private static SafeCertContextHandle FilterPFXStore(byte[] rawData, string password, PfxCertStoreFlags pfxCertStoreFlags) { SafeCertStoreHandle hStore; unsafe { fixed (byte* pbRawData = rawData) { CRYPTOAPI_BLOB certBlob = new CRYPTOAPI_BLOB(rawData.Length, pbRawData); hStore = Interop.crypt32.PFXImportCertStore(ref certBlob, password, pfxCertStoreFlags); if (hStore.IsInvalid) throw Marshal.GetHRForLastWin32Error().ToCryptographicException();; } } try { // Find the first cert with private key. If none, then simply take the very first cert. Along the way, delete the keycontainers // of any cert we don't accept. SafeCertContextHandle pCertContext = SafeCertContextHandle.InvalidHandle; SafeCertContextHandle pEnumContext = null; while (Interop.crypt32.CertEnumCertificatesInStore(hStore, ref pEnumContext)) { if (pEnumContext.ContainsPrivateKey) { if ((!pCertContext.IsInvalid) && pCertContext.ContainsPrivateKey) { // We already found our chosen one. Free up this one's key and move on. SafeCertContextHandleWithKeyContainerDeletion.DeleteKeyContainer(pEnumContext); } else { // Found our first cert that has a private key. Set him up as our chosen one but keep iterating // as we need to free up the keys of any remaining certs. pCertContext.Dispose(); pCertContext = pEnumContext.Duplicate(); } } else { if (pCertContext.IsInvalid) pCertContext = pEnumContext.Duplicate(); // Doesn't have a private key but hang on to it anyway in case we don't find any certs with a private key. } } if (pCertContext.IsInvalid) { // For compat, setting "hr" to ERROR_INVALID_PARAMETER even though ERROR_INVALID_PARAMETER is not actually an HRESULT. throw ErrorCode.ERROR_INVALID_PARAMETER.ToCryptographicException(); } return pCertContext; } finally { hStore.Dispose(); } } private static PfxCertStoreFlags MapKeyStorageFlags(X509KeyStorageFlags keyStorageFlags) { if ((keyStorageFlags & (X509KeyStorageFlags)~0x1F) != 0) throw new ArgumentException(SR.Argument_InvalidFlag, "keyStorageFlags"); PfxCertStoreFlags pfxCertStoreFlags = 0; if ((keyStorageFlags & X509KeyStorageFlags.UserKeySet) == X509KeyStorageFlags.UserKeySet) pfxCertStoreFlags |= PfxCertStoreFlags.CRYPT_USER_KEYSET; else if ((keyStorageFlags & X509KeyStorageFlags.MachineKeySet) == X509KeyStorageFlags.MachineKeySet) pfxCertStoreFlags |= PfxCertStoreFlags.CRYPT_MACHINE_KEYSET; if ((keyStorageFlags & X509KeyStorageFlags.Exportable) == X509KeyStorageFlags.Exportable) pfxCertStoreFlags |= PfxCertStoreFlags.CRYPT_EXPORTABLE; if ((keyStorageFlags & X509KeyStorageFlags.UserProtected) == X509KeyStorageFlags.UserProtected) pfxCertStoreFlags |= PfxCertStoreFlags.CRYPT_USER_PROTECTED; // In the full .NET Framework loading a PFX then adding the key to the Windows Certificate Store would // enable a native application compiled against CAPI to find that private key and interoperate with it. // // For CoreFX this behavior is being retained. // // For .NET Native (UWP) the API used to delete the private key (if it wasn't added to a store) is not // allowed to be called if the key is stored in CAPI. So for UWP force the key to be stored in the // CNG Key Storage Provider, then deleting the key with CngKey.Delete will clean up the file on disk, too. #if NETNATIVE pfxCertStoreFlags |= PfxCertStoreFlags.PKCS12_ALWAYS_CNG_KSP; #endif return pfxCertStoreFlags; } private const ExpectedContentTypeFlags X509ExpectedContentTypeFlags = ExpectedContentTypeFlags.CERT_QUERY_CONTENT_FLAG_CERT | ExpectedContentTypeFlags.CERT_QUERY_CONTENT_FLAG_SERIALIZED_CERT | ExpectedContentTypeFlags.CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED | ExpectedContentTypeFlags.CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED | ExpectedContentTypeFlags.CERT_QUERY_CONTENT_FLAG_PFX; private const ExpectedFormatTypeFlags X509ExpectedFormatTypeFlags = ExpectedFormatTypeFlags.CERT_QUERY_FORMAT_FLAG_ALL; } }
using System; using System.Dynamic; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Web; using Newtonsoft.Json.Linq; namespace RedditSharp { public sealed class WebAgent : IWebAgent { /// <summary> /// Additional values to append to the default RedditSharp user agent. /// </summary> public static string UserAgent { get; set; } /// <summary> /// It is strongly advised that you leave this enabled. Reddit bans excessive /// requests with extreme predjudice. /// </summary> public static bool EnableRateLimit { get; set; } public static string Protocol { get; set; } /// <summary> /// It is strongly advised that you leave this set to Burst or Pace. Reddit bans excessive /// requests with extreme predjudice. /// </summary> public static RateLimitMode RateLimit { get; set; } /// <summary> /// The method by which the WebAgent will limit request rate /// </summary> public enum RateLimitMode { /// <summary> /// Limits requests to one every two seconds /// </summary> Pace, /// <summary> /// Restricts requests to five per ten seconds /// </summary> SmallBurst, /// <summary> /// Restricts requests to thirty per minute /// </summary> Burst, /// <summary> /// Does not restrict request rate. ***NOT RECOMMENDED*** /// </summary> None } /// <summary> /// The root domain RedditSharp uses to address Reddit. /// www.reddit.com by default /// </summary> public static string RootDomain { get; set; } /// <summary> /// Used to make calls against Reddit's API using OAuth23 /// </summary> public string AccessToken { get; set; } public CookieContainer Cookies { get; set; } public string AuthCookie { get; set; } private static DateTime _lastRequest; private static DateTime _burstStart; private static int _requestsThisBurst; /// <summary> /// UTC DateTime of last request made to Reddit API /// </summary> public DateTime LastRequest { get { return _lastRequest; } } /// <summary> /// UTC DateTime of when the last burst started /// </summary> public DateTime BurstStart { get { return _burstStart; } } /// <summary> /// Number of requests made during the current burst /// </summary> public int RequestsThisBurst { get { return _requestsThisBurst; } } public JToken CreateAndExecuteRequest(string url) { Uri uri; if (!Uri.TryCreate(url, UriKind.Absolute, out uri)) { if (!Uri.TryCreate(String.Format("{0}://{1}{2}", Protocol, RootDomain, url), UriKind.Absolute, out uri)) throw new Exception("Could not parse Uri"); } var request = CreateGet(uri); try { return ExecuteRequest(request); } catch (Exception) { var tempProtocol = Protocol; var tempRootDomain = RootDomain; Protocol = "http"; RootDomain = "www.reddit.com"; var retval = CreateAndExecuteRequest(url); Protocol = tempProtocol; RootDomain = tempRootDomain; return retval; } } /// <summary> /// Executes the web request and handles errors in the response /// </summary> /// <param name="request"></param> /// <returns></returns> public JToken ExecuteRequest(HttpWebRequest request) { EnforceRateLimit(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); var result = GetResponseString(response.GetResponseStream()); JToken json; if (!string.IsNullOrEmpty(result)) { json = JToken.Parse(result); try { if (json["json"] != null) { json = json["json"]; //get json object if there is a root node } if (json["error"] != null) { switch (json["error"].ToString()) { case "404": throw new Exception("File Not Found"); case "403": throw new Exception("Restricted"); case "invalid_grant": //Refresh authtoken //AccessToken = authProvider.GetRefreshToken(); //ExecuteRequest(request); break; } } } catch { } } else { json = JToken.Parse("{'method':'" + response.Method + "','uri':'" + response.ResponseUri.AbsoluteUri + "','status':'" + response.StatusCode.ToString() + "'}"); } return json; } [MethodImpl(MethodImplOptions.Synchronized)] private static void EnforceRateLimit() { switch (RateLimit) { case RateLimitMode.Pace: while ((DateTime.UtcNow - _lastRequest).TotalSeconds < 2)// Rate limiting Thread.Sleep(250); _lastRequest = DateTime.UtcNow; break; case RateLimitMode.SmallBurst: if (_requestsThisBurst == 0 || (DateTime.UtcNow - _burstStart).TotalSeconds >= 10) //this is first request OR the burst expired { _burstStart = DateTime.UtcNow; _requestsThisBurst = 0; } if (_requestsThisBurst >= 5) //limit has been reached { while ((DateTime.UtcNow - _burstStart).TotalSeconds < 10) Thread.Sleep(250); _burstStart = DateTime.UtcNow; _requestsThisBurst = 0; } _lastRequest = DateTime.UtcNow; _requestsThisBurst++; break; case RateLimitMode.Burst: if (_requestsThisBurst == 0 || (DateTime.UtcNow - _burstStart).TotalSeconds >= 60) //this is first request OR the burst expired { _burstStart = DateTime.UtcNow; _requestsThisBurst = 0; } if (_requestsThisBurst >= 30) //limit has been reached { while ((DateTime.UtcNow - _burstStart).TotalSeconds < 60) Thread.Sleep(250); _burstStart = DateTime.UtcNow; _requestsThisBurst = 0; } _lastRequest = DateTime.UtcNow; _requestsThisBurst++; break; } } public HttpWebRequest CreateRequest(string url, string method) { EnforceRateLimit(); bool prependDomain; // IsWellFormedUriString returns true on Mono for some reason when using a string like "/api/me" if (Type.GetType("Mono.Runtime") != null) prependDomain = !url.StartsWith("http://") && !url.StartsWith("https://"); else prependDomain = !Uri.IsWellFormedUriString(url, UriKind.Absolute); HttpWebRequest request; if (prependDomain) request = (HttpWebRequest)WebRequest.Create(String.Format("{0}://{1}{2}", Protocol, RootDomain, url)); else request = (HttpWebRequest)WebRequest.Create(url); request.CookieContainer = Cookies; if (Type.GetType("Mono.Runtime") != null) { var cookieHeader = Cookies.GetCookieHeader(new Uri("http://reddit.com")); request.Headers.Set("Cookie", cookieHeader); } if (RootDomain == "oauth.reddit.com")// use OAuth { request.Headers.Set("Authorization", "bearer " + AccessToken);//Must be included in OAuth calls } request.Method = method; request.UserAgent = UserAgent + " - with RedditSharp by /u/sircmpwn"; return request; } private HttpWebRequest CreateRequest(Uri uri, string method) { EnforceRateLimit(); var request = (HttpWebRequest)WebRequest.Create(uri); request.CookieContainer = Cookies; if (Type.GetType("Mono.Runtime") != null) { var cookieHeader = Cookies.GetCookieHeader(new Uri("http://reddit.com")); request.Headers.Set("Cookie", cookieHeader); } if (RootDomain == "oauth.reddit.com")// use OAuth { request.Headers.Set("Authorization", "bearer " + AccessToken);//Must be included in OAuth calls } request.Method = method; request.UserAgent = UserAgent + " - with RedditSharp by /u/sircmpwn"; return request; } public HttpWebRequest CreateGet(string url) { return CreateRequest(url, "GET"); } private HttpWebRequest CreateGet(Uri url) { return CreateRequest(url, "GET"); } public HttpWebRequest CreatePost(string url) { var request = CreateRequest(url, "POST"); request.ContentType = "application/x-www-form-urlencoded"; return request; } public string GetResponseString(Stream stream) { var data = new StreamReader(stream).ReadToEnd(); stream.Close(); return data; } public void WritePostBody(Stream stream, object data, params string[] additionalFields) { var type = data.GetType(); var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); string value = ""; foreach (var property in properties) { var attr = property.GetCustomAttributes(typeof(RedditAPINameAttribute), false).FirstOrDefault() as RedditAPINameAttribute; string name = attr == null ? property.Name : attr.Name; var entry = Convert.ToString(property.GetValue(data, null)); value += name + "=" + HttpUtility.UrlEncode(entry).Replace(";", "%3B").Replace("&", "%26") + "&"; } for (int i = 0; i < additionalFields.Length; i += 2) { var entry = Convert.ToString(additionalFields[i + 1]) ?? string.Empty; value += additionalFields[i] + "=" + HttpUtility.UrlEncode(entry).Replace(";", "%3B").Replace("&", "%26") + "&"; } value = value.Remove(value.Length - 1); // Remove trailing & var raw = Encoding.UTF8.GetBytes(value); stream.Write(raw, 0, raw.Length); stream.Close(); } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using lro = Google.LongRunning; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using sc = System.Collections; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Cloud.Compute.V1 { /// <summary>Settings for <see cref="RegionCommitmentsClient"/> instances.</summary> public sealed partial class RegionCommitmentsSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="RegionCommitmentsSettings"/>.</summary> /// <returns>A new instance of the default <see cref="RegionCommitmentsSettings"/>.</returns> public static RegionCommitmentsSettings GetDefault() => new RegionCommitmentsSettings(); /// <summary>Constructs a new <see cref="RegionCommitmentsSettings"/> object with default settings.</summary> public RegionCommitmentsSettings() { } private RegionCommitmentsSettings(RegionCommitmentsSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); AggregatedListSettings = existing.AggregatedListSettings; GetSettings = existing.GetSettings; InsertSettings = existing.InsertSettings; InsertOperationsSettings = existing.InsertOperationsSettings.Clone(); ListSettings = existing.ListSettings; OnCopy(existing); } partial void OnCopy(RegionCommitmentsSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>RegionCommitmentsClient.AggregatedList</c> and <c>RegionCommitmentsClient.AggregatedListAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>No timeout is applied.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings AggregatedListSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to <c>RegionCommitmentsClient.Get</c> /// and <c>RegionCommitmentsClient.GetAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>No timeout is applied.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>RegionCommitmentsClient.Insert</c> and <c>RegionCommitmentsClient.InsertAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>No timeout is applied.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings InsertSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None); /// <summary> /// Long Running Operation settings for calls to <c>RegionCommitmentsClient.Insert</c> and /// <c>RegionCommitmentsClient.InsertAsync</c>. /// </summary> /// <remarks> /// Uses default <see cref="gax::PollSettings"/> of: /// <list type="bullet"> /// <item><description>Initial delay: 20 seconds.</description></item> /// <item><description>Delay multiplier: 1.5</description></item> /// <item><description>Maximum delay: 45 seconds.</description></item> /// <item><description>Total timeout: 24 hours.</description></item> /// </list> /// </remarks> public lro::OperationsSettings InsertOperationsSettings { get; set; } = new lro::OperationsSettings { DefaultPollSettings = new gax::PollSettings(gax::Expiration.FromTimeout(sys::TimeSpan.FromHours(24)), sys::TimeSpan.FromSeconds(20), 1.5, sys::TimeSpan.FromSeconds(45)), }; /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>RegionCommitmentsClient.List</c> and <c>RegionCommitmentsClient.ListAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>No timeout is applied.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings ListSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="RegionCommitmentsSettings"/> object.</returns> public RegionCommitmentsSettings Clone() => new RegionCommitmentsSettings(this); } /// <summary> /// Builder class for <see cref="RegionCommitmentsClient"/> to provide simple configuration of credentials, endpoint /// etc. /// </summary> public sealed partial class RegionCommitmentsClientBuilder : gaxgrpc::ClientBuilderBase<RegionCommitmentsClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public RegionCommitmentsSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public RegionCommitmentsClientBuilder() { UseJwtAccessWithScopes = RegionCommitmentsClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref RegionCommitmentsClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<RegionCommitmentsClient> task); /// <summary>Builds the resulting client.</summary> public override RegionCommitmentsClient Build() { RegionCommitmentsClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<RegionCommitmentsClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<RegionCommitmentsClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private RegionCommitmentsClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return RegionCommitmentsClient.Create(callInvoker, Settings); } private async stt::Task<RegionCommitmentsClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return RegionCommitmentsClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => RegionCommitmentsClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => RegionCommitmentsClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => RegionCommitmentsClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => ComputeRestAdapter.ComputeAdapter; } /// <summary>RegionCommitments client wrapper, for convenient use.</summary> /// <remarks> /// The RegionCommitments API. /// </remarks> public abstract partial class RegionCommitmentsClient { /// <summary> /// The default endpoint for the RegionCommitments service, which is a host of "compute.googleapis.com" and a /// port of 443. /// </summary> public static string DefaultEndpoint { get; } = "compute.googleapis.com:443"; /// <summary>The default RegionCommitments scopes.</summary> /// <remarks> /// The default RegionCommitments scopes are: /// <list type="bullet"> /// <item><description>https://www.googleapis.com/auth/compute</description></item> /// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item> /// </list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/cloud-platform", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="RegionCommitmentsClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="RegionCommitmentsClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="RegionCommitmentsClient"/>.</returns> public static stt::Task<RegionCommitmentsClient> CreateAsync(st::CancellationToken cancellationToken = default) => new RegionCommitmentsClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="RegionCommitmentsClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="RegionCommitmentsClientBuilder"/>. /// </summary> /// <returns>The created <see cref="RegionCommitmentsClient"/>.</returns> public static RegionCommitmentsClient Create() => new RegionCommitmentsClientBuilder().Build(); /// <summary> /// Creates a <see cref="RegionCommitmentsClient"/> which uses the specified call invoker for remote operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="RegionCommitmentsSettings"/>.</param> /// <returns>The created <see cref="RegionCommitmentsClient"/>.</returns> internal static RegionCommitmentsClient Create(grpccore::CallInvoker callInvoker, RegionCommitmentsSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } RegionCommitments.RegionCommitmentsClient grpcClient = new RegionCommitments.RegionCommitmentsClient(callInvoker); return new RegionCommitmentsClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC RegionCommitments client</summary> public virtual RegionCommitments.RegionCommitmentsClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Retrieves an aggregated list of commitments by region. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="scg::KeyValuePair{TKey,TValue}"/> resources.</returns> public virtual gax::PagedEnumerable<CommitmentAggregatedList, scg::KeyValuePair<string, CommitmentsScopedList>> AggregatedList(AggregatedListRegionCommitmentsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Retrieves an aggregated list of commitments by region. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns> /// A pageable asynchronous sequence of <see cref="scg::KeyValuePair{TKey,TValue}"/> resources. /// </returns> public virtual gax::PagedAsyncEnumerable<CommitmentAggregatedList, scg::KeyValuePair<string, CommitmentsScopedList>> AggregatedListAsync(AggregatedListRegionCommitmentsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Retrieves an aggregated list of commitments by region. /// </summary> /// <param name="project"> /// Project ID for this request. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first /// page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. A value of /// <c>null</c> or <c>0</c> uses a server-defined page size. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="scg::KeyValuePair{TKey,TValue}"/> resources.</returns> public virtual gax::PagedEnumerable<CommitmentAggregatedList, scg::KeyValuePair<string, CommitmentsScopedList>> AggregatedList(string project, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => AggregatedList(new AggregatedListRegionCommitmentsRequest { Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Retrieves an aggregated list of commitments by region. /// </summary> /// <param name="project"> /// Project ID for this request. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first /// page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. A value of /// <c>null</c> or <c>0</c> uses a server-defined page size. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns> /// A pageable asynchronous sequence of <see cref="scg::KeyValuePair{TKey,TValue}"/> resources. /// </returns> public virtual gax::PagedAsyncEnumerable<CommitmentAggregatedList, scg::KeyValuePair<string, CommitmentsScopedList>> AggregatedListAsync(string project, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => AggregatedListAsync(new AggregatedListRegionCommitmentsRequest { Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Returns the specified commitment resource. Gets a list of available commitments by making a list() request. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual Commitment Get(GetRegionCommitmentRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the specified commitment resource. Gets a list of available commitments by making a list() request. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<Commitment> GetAsync(GetRegionCommitmentRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the specified commitment resource. Gets a list of available commitments by making a list() request. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<Commitment> GetAsync(GetRegionCommitmentRequest request, st::CancellationToken cancellationToken) => GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the specified commitment resource. Gets a list of available commitments by making a list() request. /// </summary> /// <param name="project"> /// Project ID for this request. /// </param> /// <param name="region"> /// Name of the region for this request. /// </param> /// <param name="commitment"> /// Name of the commitment to return. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual Commitment Get(string project, string region, string commitment, gaxgrpc::CallSettings callSettings = null) => Get(new GetRegionCommitmentRequest { Commitment = gax::GaxPreconditions.CheckNotNullOrEmpty(commitment, nameof(commitment)), Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)), Region = gax::GaxPreconditions.CheckNotNullOrEmpty(region, nameof(region)), }, callSettings); /// <summary> /// Returns the specified commitment resource. Gets a list of available commitments by making a list() request. /// </summary> /// <param name="project"> /// Project ID for this request. /// </param> /// <param name="region"> /// Name of the region for this request. /// </param> /// <param name="commitment"> /// Name of the commitment to return. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<Commitment> GetAsync(string project, string region, string commitment, gaxgrpc::CallSettings callSettings = null) => GetAsync(new GetRegionCommitmentRequest { Commitment = gax::GaxPreconditions.CheckNotNullOrEmpty(commitment, nameof(commitment)), Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)), Region = gax::GaxPreconditions.CheckNotNullOrEmpty(region, nameof(region)), }, callSettings); /// <summary> /// Returns the specified commitment resource. Gets a list of available commitments by making a list() request. /// </summary> /// <param name="project"> /// Project ID for this request. /// </param> /// <param name="region"> /// Name of the region for this request. /// </param> /// <param name="commitment"> /// Name of the commitment to return. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<Commitment> GetAsync(string project, string region, string commitment, st::CancellationToken cancellationToken) => GetAsync(project, region, commitment, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates a commitment in the specified project using the data included in the request. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual lro::Operation<Operation, Operation> Insert(InsertRegionCommitmentRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates a commitment in the specified project using the data included in the request. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<Operation, Operation>> InsertAsync(InsertRegionCommitmentRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates a commitment in the specified project using the data included in the request. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<Operation, Operation>> InsertAsync(InsertRegionCommitmentRequest request, st::CancellationToken cancellationToken) => InsertAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary>The long-running operations client for <c>Insert</c>.</summary> public virtual lro::OperationsClient InsertOperationsClient => throw new sys::NotImplementedException(); /// <summary> /// Poll an operation once, using an <c>operationName</c> from a previous invocation of <c>Insert</c>. /// </summary> /// <param name="operationName"> /// The name of a previously invoked operation. Must not be <c>null</c> or empty. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The result of polling the operation.</returns> public virtual lro::Operation<Operation, Operation> PollOnceInsert(string operationName, gaxgrpc::CallSettings callSettings = null) => lro::Operation<Operation, Operation>.PollOnceFromName(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), InsertOperationsClient, callSettings); /// <summary> /// Asynchronously poll an operation once, using an <c>operationName</c> from a previous invocation of <c>Insert</c> /// . /// </summary> /// <param name="operationName"> /// The name of a previously invoked operation. Must not be <c>null</c> or empty. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A task representing the result of polling the operation.</returns> public virtual stt::Task<lro::Operation<Operation, Operation>> PollOnceInsertAsync(string operationName, gaxgrpc::CallSettings callSettings = null) => lro::Operation<Operation, Operation>.PollOnceFromNameAsync(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), InsertOperationsClient, callSettings); /// <summary> /// Creates a commitment in the specified project using the data included in the request. /// </summary> /// <param name="project"> /// Project ID for this request. /// </param> /// <param name="region"> /// Name of the region for this request. /// </param> /// <param name="commitmentResource"> /// The body resource for this request /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual lro::Operation<Operation, Operation> Insert(string project, string region, Commitment commitmentResource, gaxgrpc::CallSettings callSettings = null) => Insert(new InsertRegionCommitmentRequest { CommitmentResource = gax::GaxPreconditions.CheckNotNull(commitmentResource, nameof(commitmentResource)), Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)), Region = gax::GaxPreconditions.CheckNotNullOrEmpty(region, nameof(region)), }, callSettings); /// <summary> /// Creates a commitment in the specified project using the data included in the request. /// </summary> /// <param name="project"> /// Project ID for this request. /// </param> /// <param name="region"> /// Name of the region for this request. /// </param> /// <param name="commitmentResource"> /// The body resource for this request /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<Operation, Operation>> InsertAsync(string project, string region, Commitment commitmentResource, gaxgrpc::CallSettings callSettings = null) => InsertAsync(new InsertRegionCommitmentRequest { CommitmentResource = gax::GaxPreconditions.CheckNotNull(commitmentResource, nameof(commitmentResource)), Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)), Region = gax::GaxPreconditions.CheckNotNullOrEmpty(region, nameof(region)), }, callSettings); /// <summary> /// Creates a commitment in the specified project using the data included in the request. /// </summary> /// <param name="project"> /// Project ID for this request. /// </param> /// <param name="region"> /// Name of the region for this request. /// </param> /// <param name="commitmentResource"> /// The body resource for this request /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<Operation, Operation>> InsertAsync(string project, string region, Commitment commitmentResource, st::CancellationToken cancellationToken) => InsertAsync(project, region, commitmentResource, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Retrieves a list of commitments contained within the specified region. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="Commitment"/> resources.</returns> public virtual gax::PagedEnumerable<CommitmentList, Commitment> List(ListRegionCommitmentsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Retrieves a list of commitments contained within the specified region. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="Commitment"/> resources.</returns> public virtual gax::PagedAsyncEnumerable<CommitmentList, Commitment> ListAsync(ListRegionCommitmentsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Retrieves a list of commitments contained within the specified region. /// </summary> /// <param name="project"> /// Project ID for this request. /// </param> /// <param name="region"> /// Name of the region for this request. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first /// page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. A value of /// <c>null</c> or <c>0</c> uses a server-defined page size. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="Commitment"/> resources.</returns> public virtual gax::PagedEnumerable<CommitmentList, Commitment> List(string project, string region, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => List(new ListRegionCommitmentsRequest { Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)), Region = gax::GaxPreconditions.CheckNotNullOrEmpty(region, nameof(region)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Retrieves a list of commitments contained within the specified region. /// </summary> /// <param name="project"> /// Project ID for this request. /// </param> /// <param name="region"> /// Name of the region for this request. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first /// page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. A value of /// <c>null</c> or <c>0</c> uses a server-defined page size. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="Commitment"/> resources.</returns> public virtual gax::PagedAsyncEnumerable<CommitmentList, Commitment> ListAsync(string project, string region, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => ListAsync(new ListRegionCommitmentsRequest { Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)), Region = gax::GaxPreconditions.CheckNotNullOrEmpty(region, nameof(region)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); } /// <summary>RegionCommitments client wrapper implementation, for convenient use.</summary> /// <remarks> /// The RegionCommitments API. /// </remarks> public sealed partial class RegionCommitmentsClientImpl : RegionCommitmentsClient { private readonly gaxgrpc::ApiCall<AggregatedListRegionCommitmentsRequest, CommitmentAggregatedList> _callAggregatedList; private readonly gaxgrpc::ApiCall<GetRegionCommitmentRequest, Commitment> _callGet; private readonly gaxgrpc::ApiCall<InsertRegionCommitmentRequest, Operation> _callInsert; private readonly gaxgrpc::ApiCall<ListRegionCommitmentsRequest, CommitmentList> _callList; /// <summary> /// Constructs a client wrapper for the RegionCommitments service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="RegionCommitmentsSettings"/> used within this client.</param> public RegionCommitmentsClientImpl(RegionCommitments.RegionCommitmentsClient grpcClient, RegionCommitmentsSettings settings) { GrpcClient = grpcClient; RegionCommitmentsSettings effectiveSettings = settings ?? RegionCommitmentsSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); InsertOperationsClient = new lro::OperationsClientImpl(grpcClient.CreateOperationsClientForRegionOperations(), effectiveSettings.InsertOperationsSettings); _callAggregatedList = clientHelper.BuildApiCall<AggregatedListRegionCommitmentsRequest, CommitmentAggregatedList>(grpcClient.AggregatedListAsync, grpcClient.AggregatedList, effectiveSettings.AggregatedListSettings).WithGoogleRequestParam("project", request => request.Project); Modify_ApiCall(ref _callAggregatedList); Modify_AggregatedListApiCall(ref _callAggregatedList); _callGet = clientHelper.BuildApiCall<GetRegionCommitmentRequest, Commitment>(grpcClient.GetAsync, grpcClient.Get, effectiveSettings.GetSettings).WithGoogleRequestParam("project", request => request.Project).WithGoogleRequestParam("region", request => request.Region).WithGoogleRequestParam("commitment", request => request.Commitment); Modify_ApiCall(ref _callGet); Modify_GetApiCall(ref _callGet); _callInsert = clientHelper.BuildApiCall<InsertRegionCommitmentRequest, Operation>(grpcClient.InsertAsync, grpcClient.Insert, effectiveSettings.InsertSettings).WithGoogleRequestParam("project", request => request.Project).WithGoogleRequestParam("region", request => request.Region); Modify_ApiCall(ref _callInsert); Modify_InsertApiCall(ref _callInsert); _callList = clientHelper.BuildApiCall<ListRegionCommitmentsRequest, CommitmentList>(grpcClient.ListAsync, grpcClient.List, effectiveSettings.ListSettings).WithGoogleRequestParam("project", request => request.Project).WithGoogleRequestParam("region", request => request.Region); Modify_ApiCall(ref _callList); Modify_ListApiCall(ref _callList); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_AggregatedListApiCall(ref gaxgrpc::ApiCall<AggregatedListRegionCommitmentsRequest, CommitmentAggregatedList> call); partial void Modify_GetApiCall(ref gaxgrpc::ApiCall<GetRegionCommitmentRequest, Commitment> call); partial void Modify_InsertApiCall(ref gaxgrpc::ApiCall<InsertRegionCommitmentRequest, Operation> call); partial void Modify_ListApiCall(ref gaxgrpc::ApiCall<ListRegionCommitmentsRequest, CommitmentList> call); partial void OnConstruction(RegionCommitments.RegionCommitmentsClient grpcClient, RegionCommitmentsSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC RegionCommitments client</summary> public override RegionCommitments.RegionCommitmentsClient GrpcClient { get; } partial void Modify_AggregatedListRegionCommitmentsRequest(ref AggregatedListRegionCommitmentsRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_GetRegionCommitmentRequest(ref GetRegionCommitmentRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_InsertRegionCommitmentRequest(ref InsertRegionCommitmentRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_ListRegionCommitmentsRequest(ref ListRegionCommitmentsRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Retrieves an aggregated list of commitments by region. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="scg::KeyValuePair{TKey,TValue}"/> resources.</returns> public override gax::PagedEnumerable<CommitmentAggregatedList, scg::KeyValuePair<string, CommitmentsScopedList>> AggregatedList(AggregatedListRegionCommitmentsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_AggregatedListRegionCommitmentsRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedEnumerable<AggregatedListRegionCommitmentsRequest, CommitmentAggregatedList, scg::KeyValuePair<string, CommitmentsScopedList>>(_callAggregatedList, request, callSettings); } /// <summary> /// Retrieves an aggregated list of commitments by region. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns> /// A pageable asynchronous sequence of <see cref="scg::KeyValuePair{TKey,TValue}"/> resources. /// </returns> public override gax::PagedAsyncEnumerable<CommitmentAggregatedList, scg::KeyValuePair<string, CommitmentsScopedList>> AggregatedListAsync(AggregatedListRegionCommitmentsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_AggregatedListRegionCommitmentsRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedAsyncEnumerable<AggregatedListRegionCommitmentsRequest, CommitmentAggregatedList, scg::KeyValuePair<string, CommitmentsScopedList>>(_callAggregatedList, request, callSettings); } /// <summary> /// Returns the specified commitment resource. Gets a list of available commitments by making a list() request. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override Commitment Get(GetRegionCommitmentRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetRegionCommitmentRequest(ref request, ref callSettings); return _callGet.Sync(request, callSettings); } /// <summary> /// Returns the specified commitment resource. Gets a list of available commitments by making a list() request. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<Commitment> GetAsync(GetRegionCommitmentRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetRegionCommitmentRequest(ref request, ref callSettings); return _callGet.Async(request, callSettings); } /// <summary>The long-running operations client for <c>Insert</c>.</summary> public override lro::OperationsClient InsertOperationsClient { get; } /// <summary> /// Creates a commitment in the specified project using the data included in the request. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override lro::Operation<Operation, Operation> Insert(InsertRegionCommitmentRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_InsertRegionCommitmentRequest(ref request, ref callSettings); Operation response = _callInsert.Sync(request, callSettings); GetRegionOperationRequest pollRequest = GetRegionOperationRequest.FromInitialResponse(response); request.PopulatePollRequestFields(pollRequest); return new lro::Operation<Operation, Operation>(response.ToLroResponse(pollRequest.ToLroOperationName()), InsertOperationsClient); } /// <summary> /// Creates a commitment in the specified project using the data included in the request. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override async stt::Task<lro::Operation<Operation, Operation>> InsertAsync(InsertRegionCommitmentRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_InsertRegionCommitmentRequest(ref request, ref callSettings); Operation response = await _callInsert.Async(request, callSettings).ConfigureAwait(false); GetRegionOperationRequest pollRequest = GetRegionOperationRequest.FromInitialResponse(response); request.PopulatePollRequestFields(pollRequest); return new lro::Operation<Operation, Operation>(response.ToLroResponse(pollRequest.ToLroOperationName()), InsertOperationsClient); } /// <summary> /// Retrieves a list of commitments contained within the specified region. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="Commitment"/> resources.</returns> public override gax::PagedEnumerable<CommitmentList, Commitment> List(ListRegionCommitmentsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListRegionCommitmentsRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedEnumerable<ListRegionCommitmentsRequest, CommitmentList, Commitment>(_callList, request, callSettings); } /// <summary> /// Retrieves a list of commitments contained within the specified region. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="Commitment"/> resources.</returns> public override gax::PagedAsyncEnumerable<CommitmentList, Commitment> ListAsync(ListRegionCommitmentsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListRegionCommitmentsRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedAsyncEnumerable<ListRegionCommitmentsRequest, CommitmentList, Commitment>(_callList, request, callSettings); } } public partial class AggregatedListRegionCommitmentsRequest : gaxgrpc::IPageRequest { /// <inheritdoc/> public int PageSize { get => checked((int)MaxResults); set => MaxResults = checked((uint)value); } } public partial class ListRegionCommitmentsRequest : gaxgrpc::IPageRequest { /// <inheritdoc/> public int PageSize { get => checked((int)MaxResults); set => MaxResults = checked((uint)value); } } public partial class CommitmentAggregatedList : gaxgrpc::IPageResponse<scg::KeyValuePair<string, CommitmentsScopedList>> { /// <summary>Returns an enumerator that iterates through the resources in this response.</summary> public scg::IEnumerator<scg::KeyValuePair<string, CommitmentsScopedList>> GetEnumerator() => Items.GetEnumerator(); sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator(); } public partial class CommitmentList : gaxgrpc::IPageResponse<Commitment> { /// <summary>Returns an enumerator that iterates through the resources in this response.</summary> public scg::IEnumerator<Commitment> GetEnumerator() => Items.GetEnumerator(); sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator(); } public static partial class RegionCommitments { public partial class RegionCommitmentsClient { /// <summary> /// Creates a new instance of <see cref="lro::Operations.OperationsClient"/> using the same call invoker as /// this client, delegating to RegionOperations. /// </summary> /// <returns>A new Operations client for the same target as this client.</returns> public virtual lro::Operations.OperationsClient CreateOperationsClientForRegionOperations() => RegionOperations.RegionOperationsClient.CreateOperationsClient(CallInvoker); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using ServiceStack.Common; using ServiceStack.Text; using ServiceStack.WebHost.Endpoints; using ServiceStack.WebHost.Endpoints.Extensions; namespace ServiceStack.ServiceHost { public class ServiceMetadata { public ServiceMetadata() { this.RequestTypes = new HashSet<Type>(); this.ServiceTypes = new HashSet<Type>(); this.ResponseTypes = new HashSet<Type>(); this.OperationsMap = new Dictionary<Type, Operation>(); this.OperationsResponseMap = new Dictionary<Type, Operation>(); this.OperationNamesMap = new Dictionary<string, Operation>(); this.Routes = new ServiceRoutes(); } public Dictionary<Type, Operation> OperationsMap { get; protected set; } public Dictionary<Type, Operation> OperationsResponseMap { get; protected set; } public Dictionary<string, Operation> OperationNamesMap { get; protected set; } public HashSet<Type> RequestTypes { get; protected set; } public HashSet<Type> ServiceTypes { get; protected set; } public HashSet<Type> ResponseTypes { get; protected set; } public ServiceRoutes Routes { get; set; } public IEnumerable<Operation> Operations { get { return OperationsMap.Values; } } public void Add(Type serviceType, Type requestType, Type responseType) { this.ServiceTypes.Add(serviceType); this.RequestTypes.Add(requestType); var restrictTo = requestType.GetCustomAttributes(true) .OfType<RestrictAttribute>().FirstOrDefault() ?? serviceType.GetCustomAttributes(true) .OfType<RestrictAttribute>().FirstOrDefault(); var operation = new Operation { ServiceType = serviceType, RequestType = requestType, ResponseType = responseType, RestrictTo = restrictTo, Actions = GetImplementedActions(serviceType, requestType), Routes = new List<RestPath>(), }; this.OperationsMap[requestType] = operation; this.OperationNamesMap[requestType.Name.ToLower()] = operation; if (responseType != null) { this.ResponseTypes.Add(responseType); this.OperationsResponseMap[responseType] = operation; } } public void AfterInit() { foreach (var restPath in Routes.RestPaths) { Operation operation; if (!OperationsMap.TryGetValue(restPath.RequestType, out operation)) continue; operation.Routes.Add(restPath); } } public List<OperationDto> GetOperationDtos() { return OperationsMap.Values .SafeConvertAll(x => x.ToOperationDto()) .OrderBy(x => x.Name) .ToList(); } public Operation GetOperation(Type operationType) { Operation op; OperationsMap.TryGetValue(operationType, out op); return op; } public List<string> GetImplementedActions(Type serviceType, Type requestType) { if (typeof(IService).IsAssignableFrom(serviceType)) { return serviceType.GetActions() .Where(x => x.GetParameters()[0].ParameterType == requestType) .Select(x => x.Name.ToUpper()) .ToList(); } var oldApiActions = serviceType .GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly) .Select(x => ToNewApiAction(x.Name)) .Where(x => x != null) .ToList(); return oldApiActions; } public static string ToNewApiAction(string oldApiAction) { switch (oldApiAction) { case "Get": case "OnGet": return "GET"; case "Put": case "OnPut": return "PUT"; case "Post": case "OnPost": return "POST"; case "Delete": case "OnDelete": return "DELETE"; case "Patch": case "OnPatch": return "PATCH"; case "Execute": case "Run": return "ANY"; } return null; } public Type GetOperationType(string operationTypeName) { Operation operation; OperationNamesMap.TryGetValue(operationTypeName.ToLower(), out operation); return operation != null ? operation.RequestType : null; } public Type GetServiceTypeByRequest(Type requestType) { Operation operation; OperationsMap.TryGetValue(requestType, out operation); return operation != null ? operation.ServiceType : null; } public Type GetServiceTypeByResponse(Type responseType) { Operation operation; OperationsResponseMap.TryGetValue(responseType, out operation); return operation != null ? operation.ServiceType : null; } public Type GetResponseTypeByRequest(Type requestType) { Operation operation; OperationsMap.TryGetValue(requestType, out operation); return operation != null ? operation.ResponseType : null; } public List<Type> GetAllTypes() { var allTypes = new List<Type>(RequestTypes); foreach (var responseType in ResponseTypes) { allTypes.AddIfNotExists(responseType); } return allTypes; } public List<string> GetAllOperationNames() { return Operations.Select(x => x.RequestType.Name).OrderBy(operation => operation).ToList(); } public List<string> GetOperationNamesForMetadata(IHttpRequest httpReq) { return GetAllOperationNames(); } public List<string> GetOperationNamesForMetadata(IHttpRequest httpReq, Format format) { return GetAllOperationNames(); } public bool IsVisible(IHttpRequest httpReq, Operation operation) { if (EndpointHost.Config != null && !EndpointHost.Config.EnableAccessRestrictions) return true; if (operation.RestrictTo == null) return true; //Less fine-grained on /metadata pages. Only check Network and Format var reqAttrs = httpReq.GetAttributes(); var showToNetwork = CanShowToNetwork(operation, reqAttrs); return showToNetwork; } public bool IsVisible(IHttpRequest httpReq, Format format, string operationName) { if (EndpointHost.Config != null && !EndpointHost.Config.EnableAccessRestrictions) return true; Operation operation; OperationNamesMap.TryGetValue(operationName.ToLower(), out operation); if (operation == null) return false; var canCall = HasImplementation(operation, format); if (!canCall) return false; var isVisible = IsVisible(httpReq, operation); if (!isVisible) return false; if (operation.RestrictTo == null) return true; var allowsFormat = operation.RestrictTo.CanShowTo((EndpointAttributes)(long)format); return allowsFormat; } public bool CanAccess(IHttpRequest httpReq, Format format, string operationName) { var reqAttrs = httpReq.GetAttributes(); return CanAccess(reqAttrs, format, operationName); } public bool CanAccess(EndpointAttributes reqAttrs, Format format, string operationName) { if (EndpointHost.Config != null && !EndpointHost.Config.EnableAccessRestrictions) return true; Operation operation; OperationNamesMap.TryGetValue(operationName.ToLower(), out operation); if (operation == null) return false; var canCall = HasImplementation(operation, format); if (!canCall) return false; if (operation.RestrictTo == null) return true; var allow = operation.RestrictTo.HasAccessTo(reqAttrs); if (!allow) return false; var allowsFormat = operation.RestrictTo.HasAccessTo((EndpointAttributes)(long)format); return allowsFormat; } public bool CanAccess(Format format, string operationName) { if (EndpointHost.Config != null && !EndpointHost.Config.EnableAccessRestrictions) return true; Operation operation; OperationNamesMap.TryGetValue(operationName.ToLower(), out operation); if (operation == null) return false; var canCall = HasImplementation(operation, format); if (!canCall) return false; if (operation.RestrictTo == null) return true; var allowsFormat = operation.RestrictTo.HasAccessTo((EndpointAttributes)(long)format); return allowsFormat; } public bool HasImplementation(Operation operation, Format format) { if (format == Format.Soap11 || format == Format.Soap12) { if (operation.Actions == null) return false; return operation.Actions.Contains("POST") || operation.Actions.Contains(ActionContext.AnyAction); } return true; } private static bool CanShowToNetwork(Operation operation, EndpointAttributes reqAttrs) { if (reqAttrs.IsLocalhost()) return operation.RestrictTo.CanShowTo(EndpointAttributes.Localhost) || operation.RestrictTo.CanShowTo(EndpointAttributes.LocalSubnet); return operation.RestrictTo.CanShowTo( reqAttrs.IsLocalSubnet() ? EndpointAttributes.LocalSubnet : EndpointAttributes.External); } } public class Operation { public string Name { get { return RequestType.Name; } } public Type RequestType { get; set; } public Type ServiceType { get; set; } public Type ResponseType { get; set; } public RestrictAttribute RestrictTo { get; set; } public List<string> Actions { get; set; } public List<RestPath> Routes { get; set; } public bool IsOneWay { get { return ResponseType == null; } } } public class OperationDto { public string Name { get; set; } public string ResponseName { get; set; } public string ServiceName { get; set; } public List<string> RestrictTo { get; set; } public List<string> VisibleTo { get; set; } public List<string> Actions { get; set; } public Dictionary<string, string> Routes { get; set; } } public class XsdMetadata { public ServiceMetadata Metadata { get; set; } public bool Flash { get; set; } public XsdMetadata(ServiceMetadata metadata, bool flash = false) { Metadata = metadata; Flash = flash; } public List<Type> GetAllTypes() { var allTypes = new List<Type>(Metadata.RequestTypes); allTypes.AddRange(Metadata.ResponseTypes); return allTypes; } public List<string> GetReplyOperationNames(Format format) { return Metadata.OperationsMap.Values .Where(x => EndpointHost.Config != null && EndpointHost.Config.MetadataPagesConfig.CanAccess(format, x.Name)) .Where(x => !x.IsOneWay) .Select(x => x.RequestType.Name) .ToList(); } public List<string> GetOneWayOperationNames(Format format) { return Metadata.OperationsMap.Values .Where(x => EndpointHost.Config != null && EndpointHost.Config.MetadataPagesConfig.CanAccess(format, x.Name)) .Where(x => x.IsOneWay) .Select(x => x.RequestType.Name) .ToList(); } /// <summary> /// Gets the name of the base most type in the heirachy tree with the same. /// /// We get an exception when trying to create a schema with multiple types of the same name /// like when inheriting from a DataContract with the same name. /// </summary> /// <param name="type">The type.</param> /// <returns></returns> public static Type GetBaseTypeWithTheSameName(Type type) { var typesWithSameName = new Stack<Type>(); var baseType = type; do { if (baseType.Name == type.Name) typesWithSameName.Push(baseType); } while ((baseType = baseType.BaseType) != null); return typesWithSameName.Pop(); } } public static class ServiceMetadataExtensions { public static OperationDto ToOperationDto(this Operation operation) { var to = new OperationDto { Name = operation.Name, ResponseName = operation.IsOneWay ? null : operation.ResponseType.Name, ServiceName = operation.ServiceType.Name, Actions = operation.Actions, Routes = operation.Routes.ToDictionary(x => x.Path.PairWith(x.AllowedVerbs)), }; if (operation.RestrictTo != null) { to.RestrictTo = operation.RestrictTo.AccessibleToAny.ToList().ConvertAll(x => x.ToString()); to.VisibleTo = operation.RestrictTo.VisibleToAny.ToList().ConvertAll(x => x.ToString()); } return to; } public static string GetDescription(this Type operationType) { var apiAttr = operationType.GetCustomAttributes(typeof(ApiAttribute), true).OfType<ApiAttribute>().FirstOrDefault(); return apiAttr != null ? apiAttr.Description : ""; } public static List<ApiMemberAttribute> GetApiMembers(this Type operationType) { var members = operationType.GetMembers(BindingFlags.Instance | BindingFlags.Public); List<ApiMemberAttribute> attrs = new List<ApiMemberAttribute>(); foreach (var member in members) { var memattr = member.GetCustomAttributes(typeof(ApiMemberAttribute), true) .OfType<ApiMemberAttribute>() .Select(x => { x.Name = x.Name ?? member.Name; return x; }); attrs.AddRange(memattr); } return attrs; } } }
// MIT License // // Copyright(c) 2022 ICARUS Consulting GmbH // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Yaapii.Atoms.Scalar; #pragma warning disable MaxClassLength // Class length max namespace Yaapii.Atoms.Bytes { /// <summary> /// Bytes out of other objects. /// </summary> public sealed class BytesOf : IBytes { /// <summary> /// original /// </summary> private readonly IScalar<byte[]> origin; /// <summary> /// Bytes out of a input. /// </summary> /// <param name="input">the input</param> public BytesOf(IInput input) : this(new InputAsBytes(input)) { } /// <summary> /// Bytes out of a input. /// </summary> /// <param name="input">the input</param> /// <param name="max">max buffer size</param> public BytesOf(IInput input, int max) : this(new InputAsBytes(input, max)) { } /// <summary> /// Bytes out of a StringBuilder. /// </summary> /// <param name="builder">stringbuilder</param> public BytesOf(StringBuilder builder) : this(builder, Encoding.UTF8) { } /// <summary> /// Bytes out of a StringBuilder. /// </summary> /// <param name="builder">stringbuilder</param> /// <param name="enc">encoding of stringbuilder</param> public BytesOf(StringBuilder builder, Encoding enc) : this( () => enc.GetBytes(builder.ToString())) { } /// <summary> /// Bytes out of a StringReader. /// </summary> /// <param name="rdr">stringreader</param> public BytesOf(StringReader rdr) : this(new ReaderAsBytes(rdr)) { } /// <summary> /// Bytes out of a StreamReader. /// </summary> /// <param name="rdr">streamreader</param> public BytesOf(StreamReader rdr) : this(new ReaderAsBytes(rdr)) { } /// <summary> /// Bytes out of a StreamReader. /// </summary> /// <param name="rdr">the reader</param> /// <param name="enc">encoding of the reader</param> /// <param name="max">max buffer size of the reader</param> public BytesOf(StreamReader rdr, Encoding enc, int max = 16 << 10) : this(new ReaderAsBytes(rdr, enc, max)) { } /// <summary> /// Bytes out of a list of chars. /// </summary> /// <param name="chars">enumerable of bytes</param> public BytesOf(IEnumerable<char> chars) : this(chars, Encoding.UTF8) { } /// <summary> /// Bytes out of a list of chars. /// </summary> /// <param name="chars">enumerable of chars</param> /// <param name="enc">encoding of chars</param> public BytesOf(IEnumerable<char> chars, Encoding enc) : this( () => chars.Select(c => (Byte)c).ToArray()) { } /// <summary> /// Bytes out of a char array. /// </summary> /// <param name="chars">array of chars</param> public BytesOf(params char[] chars) : this(chars, Encoding.UTF8) { } /// <summary> /// Bytes out of a char array. /// </summary> /// <param name="chars">an array of chars</param> /// <param name="encoding">encoding of chars</param> public BytesOf(char[] chars, Encoding encoding) : this(new String(chars), encoding) { } /// <summary> /// Bytes out of a string. /// </summary> /// <param name="source">a string</param> public BytesOf(String source) : this(source, Encoding.UTF8) { } /// <summary> /// Bytes out of a string. /// </summary> /// <param name="source">a string</param> /// <param name="encoding">encoding of the string</param> public BytesOf(String source, Encoding encoding) : this( () => encoding.GetBytes(source)) { } /// <summary> /// Bytes out of Text. /// </summary> /// <param name="text">a text</param> public BytesOf(IText text) : this(text, Encoding.UTF8) { } /// <summary> /// Bytes out of Text. /// </summary> /// <param name="text">a text</param> /// <param name="encoding">encoding of the string</param> public BytesOf(IText text, Encoding encoding) : this( () => encoding.GetBytes(text.AsString())) { } /// <summary> /// Bytes out of Exception object. /// </summary> /// <param name="error">exception to serialize</param> public BytesOf(Exception error) : this( () => Encoding.UTF8.GetBytes(error.ToString())) { } /// <summary> /// Bytes out of IBytes object. /// </summary> /// <param name="bytes">bytes</param> public BytesOf(IBytes bytes) : this( () => bytes.AsBytes()) { } /// <summary> /// Bytes out of function which returns a byte array. /// </summary> /// <param name="bytes">byte aray</param> public BytesOf(Func<Byte[]> bytes) : this(new ScalarOf<Byte[]>(bytes)) { } /// <summary> /// Bytes out of byte array. /// </summary> /// <param name="bytes">byte aray</param> public BytesOf(params Byte[] bytes) : this(new ScalarOf<Byte[]>(bytes)) { } /// <summary> /// Bytes out of an int. /// </summary> /// <param name="number">an int</param> public BytesOf(int number) : this( new ScalarOf<Byte[]>(() => BitConverter.GetBytes(number) ) ) { } /// <summary> /// Bytes out of a long. /// </summary> /// <param name="number">a long</param> public BytesOf(long number) : this( new ScalarOf<Byte[]>(() => BitConverter.GetBytes(number) ) ) { } /// <summary> /// Bytes out of a float. /// </summary> /// <param name="number">a float</param> public BytesOf(float number) : this( new ScalarOf<Byte[]>(() => BitConverter.GetBytes(number) ) ) { } /// <summary> /// Bytes out of a double. /// </summary> /// <param name="number">a double</param> public BytesOf(double number) : this( new ScalarOf<Byte[]>(() => BitConverter.GetBytes(number) ) ) { } /// <summary> /// Bytes out of other objects. /// </summary> /// <param name="bytes">scalar of bytes</param> private BytesOf(IScalar<Byte[]> bytes) { this.origin = bytes; } /// <summary> /// Get the content as byte array. /// </summary> /// <returns>content as byte array</returns> public byte[] AsBytes() { return this.origin.Value(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; using System.Numerics; using Internal.Runtime.CompilerServices; #if BIT64 using nint = System.Int64; using nuint = System.UInt64; #else // BIT64 using nint = System.Int32; using nuint = System.UInt32; #endif // BIT64 namespace System.Text.Unicode { internal static unsafe partial class Utf16Utility { #if DEBUG static Utf16Utility() { Debug.Assert(sizeof(nint) == IntPtr.Size && nint.MinValue < 0, "nint is defined incorrectly."); Debug.Assert(sizeof(nuint) == IntPtr.Size && nuint.MinValue == 0, "nuint is defined incorrectly."); } #endif // DEBUG // Returns &inputBuffer[inputLength] if the input buffer is valid. /// <summary> /// Given an input buffer <paramref name="pInputBuffer"/> of char length <paramref name="inputLength"/>, /// returns a pointer to where the first invalid data appears in <paramref name="pInputBuffer"/>. /// </summary> /// <remarks> /// Returns a pointer to the end of <paramref name="pInputBuffer"/> if the buffer is well-formed. /// </remarks> public static char* GetPointerToFirstInvalidChar(char* pInputBuffer, int inputLength, out long utf8CodeUnitCountAdjustment, out int scalarCountAdjustment) { Debug.Assert(inputLength >= 0, "Input length must not be negative."); Debug.Assert(pInputBuffer != null || inputLength == 0, "Input length must be zero if input buffer pointer is null."); // First, we'll handle the common case of all-ASCII. If this is able to // consume the entire buffer, we'll skip the remainder of this method's logic. int numAsciiCharsConsumedJustNow = (int)ASCIIUtility.GetIndexOfFirstNonAsciiChar(pInputBuffer, (uint)inputLength); Debug.Assert(0 <= numAsciiCharsConsumedJustNow && numAsciiCharsConsumedJustNow <= inputLength); pInputBuffer += (uint)numAsciiCharsConsumedJustNow; inputLength -= numAsciiCharsConsumedJustNow; if (inputLength == 0) { utf8CodeUnitCountAdjustment = 0; scalarCountAdjustment = 0; return pInputBuffer; } // If we got here, it means we saw some non-ASCII data, so within our // vectorized code paths below we'll handle all non-surrogate UTF-16 // code points branchlessly. We'll only branch if we see surrogates. // // We still optimistically assume the data is mostly ASCII. This means that the // number of UTF-8 code units and the number of scalars almost matches the number // of UTF-16 code units. As we go through the input and find non-ASCII // characters, we'll keep track of these "adjustment" fixups. To get the // total number of UTF-8 code units required to encode the input data, add // the UTF-8 code unit count adjustment to the number of UTF-16 code units // seen. To get the total number of scalars present in the input data, // add the scalar count adjustment to the number of UTF-16 code units seen. long tempUtf8CodeUnitCountAdjustment = 0; int tempScalarCountAdjustment = 0; if (Sse2.IsSupported) { if (inputLength >= Vector128<ushort>.Count) { Vector128<ushort> vector0080 = Vector128.Create((ushort)0x80); Vector128<ushort> vectorA800 = Vector128.Create((ushort)0xA800); Vector128<short> vector8800 = Vector128.Create(unchecked((short)0x8800)); Vector128<ushort> vectorZero = Vector128<ushort>.Zero; do { Vector128<ushort> utf16Data = Sse2.LoadVector128((ushort*)pInputBuffer); // unaligned uint mask; // The 'charIsNonAscii' vector we're about to build will have the 0x8000 or the 0x0080 // bit set (but not both!) only if the corresponding input char is non-ASCII. Which of // the two bits is set doesn't matter, as will be explained in the diagram a few lines // below. Vector128<ushort> charIsNonAscii; if (Sse41.IsSupported) { // sets 0x0080 bit if corresponding char element is >= 0x0080 charIsNonAscii = Sse41.Min(utf16Data, vector0080); } else { // sets 0x8000 bit if corresponding char element is >= 0x0080 charIsNonAscii = Sse2.AndNot(vector0080, Sse2.Subtract(vectorZero, Sse2.ShiftRightLogical(utf16Data, 7))); } #if DEBUG // Quick check to ensure we didn't accidentally set both 0x8080 bits in any element. uint debugMask = (uint)Sse2.MoveMask(charIsNonAscii.AsByte()); Debug.Assert((debugMask & (debugMask << 1)) == 0, "Two set bits shouldn't occur adjacent to each other in this mask."); #endif // DEBUG // sets 0x8080 bits if corresponding char element is >= 0x0800 Vector128<ushort> charIsThreeByteUtf8Encoded = Sse2.Subtract(vectorZero, Sse2.ShiftRightLogical(utf16Data, 11)); mask = (uint)Sse2.MoveMask(Sse2.Or(charIsNonAscii, charIsThreeByteUtf8Encoded).AsByte()); // Each odd bit of mask will be 1 only if the char was >= 0x0080, // and each even bit of mask will be 1 only if the char was >= 0x0800. // // Example for UTF-16 input "[ 0123 ] [ 1234 ] ...": // // ,-- set if char[1] is non-ASCII // | ,-- set if char[0] is non-ASCII // v v // mask = ... 1 1 1 0 // ^ ^-- set if char[0] is >= 0x0800 // `-- set if char[1] is >= 0x0800 // // (If the SSE4.1 code path is taken above, the meaning of the odd and even // bits are swapped, but the logic below otherwise holds.) // // This means we can popcnt the number of set bits, and the result is the // number of *additional* UTF-8 bytes that each UTF-16 code unit requires as // it expands. This results in the wrong count for UTF-16 surrogate code // units (we just counted that each individual code unit expands to 3 bytes, // but in reality a well-formed UTF-16 surrogate pair expands to 4 bytes). // We'll handle this in just a moment. // // For now, compute the popcnt but squirrel it away. We'll fold it in to the // cumulative UTF-8 adjustment factor once we determine that there are no // unpaired surrogates in our data. (Unpaired surrogates would invalidate // our computed result and we'd have to throw it away.) uint popcnt = (uint)BitOperations.PopCount(mask); // Surrogates need to be special-cased for two reasons: (a) we need // to account for the fact that we over-counted in the addition above; // and (b) they require separate validation. utf16Data = Sse2.Add(utf16Data, vectorA800); mask = (uint)Sse2.MoveMask(Sse2.CompareLessThan(utf16Data.AsInt16(), vector8800).AsByte()); if (mask != 0) { // There's at least one UTF-16 surrogate code unit present. // Since we performed a pmovmskb operation on the result of a 16-bit pcmpgtw, // the resulting bits of 'mask' will occur in pairs: // - 00 if the corresponding UTF-16 char was not a surrogate code unit; // - 11 if the corresponding UTF-16 char was a surrogate code unit. // // A UTF-16 high/low surrogate code unit has the bit pattern [ 11011q## ######## ], // where # is any bit; q = 0 represents a high surrogate, and q = 1 represents // a low surrogate. Since we added 0xA800 in the vectorized operation above, // our surrogate pairs will now have the bit pattern [ 10000q## ######## ]. // If we logical right-shift each word by 3, we'll end up with the bit pattern // [ 00010000 q####### ], which means that we can immediately use pmovmskb to // determine whether a given char was a high or a low surrogate. // // Therefore the resulting bits of 'mask2' will occur in pairs: // - 00 if the corresponding UTF-16 char was a high surrogate code unit; // - 01 if the corresponding UTF-16 char was a low surrogate code unit; // - ## (garbage) if the corresponding UTF-16 char was not a surrogate code unit. // Since 'mask' already has 00 in these positions (since the corresponding char // wasn't a surrogate), "mask AND mask2 == 00" holds for these positions. uint mask2 = (uint)Sse2.MoveMask(Sse2.ShiftRightLogical(utf16Data, 3).AsByte()); // 'lowSurrogatesMask' has its bits occur in pairs: // - 01 if the corresponding char was a low surrogate char, // - 00 if the corresponding char was a high surrogate char or not a surrogate at all. uint lowSurrogatesMask = mask2 & mask; // 'highSurrogatesMask' has its bits occur in pairs: // - 01 if the corresponding char was a high surrogate char, // - 00 if the corresponding char was a low surrogate char or not a surrogate at all. uint highSurrogatesMask = (mask2 ^ 0b_0101_0101_0101_0101u /* flip all even-numbered bits 00 <-> 01 */) & mask; Debug.Assert((highSurrogatesMask & lowSurrogatesMask) == 0, "A char cannot simultaneously be both a high and a low surrogate char."); Debug.Assert(((highSurrogatesMask | lowSurrogatesMask) & 0b_1010_1010_1010_1010u) == 0, "Only even bits (no odd bits) of the masks should be set."); // Now check that each high surrogate is followed by a low surrogate and that each // low surrogate follows a high surrogate. We make an exception for the case where // the final char of the vector is a high surrogate, since we can't perform validation // on it until the next iteration of the loop when we hope to consume the matching // low surrogate. highSurrogatesMask <<= 2; if ((ushort)highSurrogatesMask != lowSurrogatesMask) { goto NonVectorizedLoop; // error: mismatched surrogate pair; break out of vectorized logic } if (highSurrogatesMask > ushort.MaxValue) { // There was a standalone high surrogate at the end of the vector. // We'll adjust our counters so that we don't consider this char consumed. highSurrogatesMask = (ushort)highSurrogatesMask; // don't allow stray high surrogate to be consumed by popcnt popcnt -= 2; // the '0xC000_0000' bits in the original mask are shifted out and discarded, so account for that here pInputBuffer--; inputLength++; } // If we're 64-bit, we can perform the zero-extension of the surrogate pairs count for // free right now, saving the extension step a few lines below. If we're 32-bit, the // convertion to nuint immediately below is a no-op, and we'll pay the cost of the real // 64 -bit extension a few lines below. nuint surrogatePairsCountNuint = (uint)BitOperations.PopCount(highSurrogatesMask); // 2 UTF-16 chars become 1 Unicode scalar tempScalarCountAdjustment -= (int)surrogatePairsCountNuint; // Since each surrogate code unit was >= 0x0800, we eagerly assumed // it'd be encoded as 3 UTF-8 code units, so our earlier popcnt computation // assumes that the pair is encoded as 6 UTF-8 code units. Since each // pair is in reality only encoded as 4 UTF-8 code units, we need to // perform this adjustment now. if (IntPtr.Size == 8) { // Since we've already zero-extended surrogatePairsCountNuint, we can directly // sub + sub. It's more efficient than shl + sub. tempUtf8CodeUnitCountAdjustment -= (long)surrogatePairsCountNuint; tempUtf8CodeUnitCountAdjustment -= (long)surrogatePairsCountNuint; } else { // Take the hit of the 64-bit extension now. tempUtf8CodeUnitCountAdjustment -= 2 * (uint)surrogatePairsCountNuint; } } tempUtf8CodeUnitCountAdjustment += popcnt; pInputBuffer += Vector128<ushort>.Count; inputLength -= Vector128<ushort>.Count; } while (inputLength >= Vector128<ushort>.Count); } } else if (Vector.IsHardwareAccelerated) { if (inputLength >= Vector<ushort>.Count) { Vector<ushort> vector0080 = new Vector<ushort>(0x0080); Vector<ushort> vector0400 = new Vector<ushort>(0x0400); Vector<ushort> vector0800 = new Vector<ushort>(0x0800); Vector<ushort> vectorD800 = new Vector<ushort>(0xD800); do { // The 'twoOrMoreUtf8Bytes' and 'threeOrMoreUtf8Bytes' vectors will contain // elements whose values are 0xFFFF (-1 as signed word) iff the corresponding // UTF-16 code unit was >= 0x0080 and >= 0x0800, respectively. By summing these // vectors, each element of the sum will contain one of three values: // // 0x0000 ( 0) = original char was 0000..007F // 0xFFFF (-1) = original char was 0080..07FF // 0xFFFE (-2) = original char was 0800..FFFF // // We'll negate them to produce a value 0..2 for each element, then sum all the // elements together to produce the number of *additional* UTF-8 code units // required to represent this UTF-16 data. This is similar to the popcnt step // performed by the SSE2 code path. This will overcount surrogates, but we'll // handle that shortly. Vector<ushort> utf16Data = Unsafe.ReadUnaligned<Vector<ushort>>(pInputBuffer); Vector<ushort> twoOrMoreUtf8Bytes = Vector.GreaterThanOrEqual(utf16Data, vector0080); Vector<ushort> threeOrMoreUtf8Bytes = Vector.GreaterThanOrEqual(utf16Data, vector0800); Vector<nuint> sumVector = (Vector<nuint>)(Vector<ushort>.Zero - twoOrMoreUtf8Bytes - threeOrMoreUtf8Bytes); // We'll try summing by a natural word (rather than a 16-bit word) at a time, // which should halve the number of operations we must perform. nuint popcnt = 0; for (int i = 0; i < Vector<nuint>.Count; i++) { popcnt += sumVector[i]; } uint popcnt32 = (uint)popcnt; if (IntPtr.Size == 8) { popcnt32 += (uint)(popcnt >> 32); } // As in the SSE4.1 paths, compute popcnt but don't fold it in until we // know there aren't any unpaired surrogates in the input data. popcnt32 = (ushort)popcnt32 + (popcnt32 >> 16); // Now check for surrogates. utf16Data -= vectorD800; Vector<ushort> surrogateChars = Vector.LessThan(utf16Data, vector0800); if (surrogateChars != Vector<ushort>.Zero) { // There's at least one surrogate (high or low) UTF-16 code unit in // the vector. We'll build up additional vectors: 'highSurrogateChars' // and 'lowSurrogateChars', where the elements are 0xFFFF iff the original // UTF-16 code unit was a high or low surrogate, respectively. Vector<ushort> highSurrogateChars = Vector.LessThan(utf16Data, vector0400); Vector<ushort> lowSurrogateChars = Vector.AndNot(surrogateChars, highSurrogateChars); // We want to make sure that each high surrogate code unit is followed by // a low surrogate code unit and each low surrogate code unit follows a // high surrogate code unit. Since we don't have an equivalent of pmovmskb // or palignr available to us, we'll do this as a loop. We won't look at // the very last high surrogate char element since we don't yet know if // the next vector read will have a low surrogate char element. if (lowSurrogateChars[0] != 0) { goto Error; // error: start of buffer contains standalone low surrogate char } ushort surrogatePairsCount = 0; for (int i = 0; i < Vector<ushort>.Count - 1; i++) { surrogatePairsCount -= highSurrogateChars[i]; // turns into +1 or +0 if (highSurrogateChars[i] != lowSurrogateChars[i + 1]) { goto NonVectorizedLoop; // error: mismatched surrogate pair; break out of vectorized logic } } if (highSurrogateChars[Vector<ushort>.Count - 1] != 0) { // There was a standalone high surrogate at the end of the vector. // We'll adjust our counters so that we don't consider this char consumed. pInputBuffer--; inputLength++; popcnt32 -= 2; } nint surrogatePairsCountNint = (nint)surrogatePairsCount; // zero-extend to native int size // 2 UTF-16 chars become 1 Unicode scalar tempScalarCountAdjustment -= (int)surrogatePairsCountNint; // Since each surrogate code unit was >= 0x0800, we eagerly assumed // it'd be encoded as 3 UTF-8 code units. Each surrogate half is only // encoded as 2 UTF-8 code units (for 4 UTF-8 code units total), // so we'll adjust this now. tempUtf8CodeUnitCountAdjustment -= surrogatePairsCountNint; tempUtf8CodeUnitCountAdjustment -= surrogatePairsCountNint; } tempUtf8CodeUnitCountAdjustment += popcnt32; pInputBuffer += Vector<ushort>.Count; inputLength -= Vector<ushort>.Count; } while (inputLength >= Vector<ushort>.Count); } } NonVectorizedLoop: // Vectorization isn't supported on our current platform, or the input was too small to benefit // from vectorization, or we saw invalid UTF-16 data in the vectorized code paths and need to // drain remaining valid chars before we report failure. for (; inputLength > 0; pInputBuffer++, inputLength--) { uint thisChar = pInputBuffer[0]; if (thisChar <= 0x7F) { continue; } // Bump adjustment by +1 for U+0080..U+07FF; by +2 for U+0800..U+FFFF. // This optimistically assumes no surrogates, which we'll handle shortly. tempUtf8CodeUnitCountAdjustment += (thisChar + 0x0001_F800u) >> 16; if (!UnicodeUtility.IsSurrogateCodePoint(thisChar)) { continue; } // Found a surrogate char. Back out the adjustment we made above, then // try to consume the entire surrogate pair all at once. We won't bother // trying to interpret the surrogate pair as a scalar value; we'll only // validate that its bit pattern matches what's expected for a surrogate pair. tempUtf8CodeUnitCountAdjustment -= 2; if (inputLength == 1) { goto Error; // input buffer too small to read a surrogate pair } thisChar = Unsafe.ReadUnaligned<uint>(pInputBuffer); if (((thisChar - (BitConverter.IsLittleEndian ? 0xDC00_D800u : 0xD800_DC00u)) & 0xFC00_FC00u) != 0) { goto Error; // not a well-formed surrogate pair } tempScalarCountAdjustment--; // 2 UTF-16 code units -> 1 scalar tempUtf8CodeUnitCountAdjustment += 2; // 2 UTF-16 code units -> 4 UTF-8 code units pInputBuffer++; // consumed one extra char inputLength--; } Error: // Also used for normal return. utf8CodeUnitCountAdjustment = tempUtf8CodeUnitCountAdjustment; scalarCountAdjustment = tempScalarCountAdjustment; return pInputBuffer; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using SPA.Areas.HelpPage.ModelDescriptions; using SPA.Areas.HelpPage.Models; namespace SPA.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// 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 Microsoft.Xunit.Performance; namespace System.Text.RegularExpressions.Tests { /// <summary> /// Performance tests for Regular Expressions /// </summary> public class Perf_Regex { private const int InnerIterations = 100; [Benchmark] [MeasureGCAllocations] public void Match() { var cacheSizeOld = Regex.CacheSize; try { Regex.CacheSize = 0; // disable cache to get clearer results foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < InnerIterations; i++) { foreach (var test in Match_TestData()) Regex.Match((string)test[1], (string)test[0], (RegexOptions)test[2]); } } } } finally { Regex.CacheSize = cacheSizeOld; } } // A series of patterns (all valid and non pathological) and inputs (which they may or may not match) public static IEnumerable<object[]> Match_TestData() { yield return new object[] { "[abcd-[d]]+", "dddaabbccddd", RegexOptions.None }; yield return new object[] { @"[\d-[357]]+", "33312468955", RegexOptions.None }; yield return new object[] { @"[\d-[357]]+", "51246897", RegexOptions.None }; yield return new object[] { @"[\d-[357]]+", "3312468977", RegexOptions.None }; yield return new object[] { @"[\w-[b-y]]+", "bbbaaaABCD09zzzyyy", RegexOptions.None }; yield return new object[] { @"[\w-[\d]]+", "0AZaz9", RegexOptions.None }; yield return new object[] { @"[\w-[\p{Ll}]]+", "a09AZz", RegexOptions.None }; yield return new object[] { @"[\d-[13579]]+", "1024689", RegexOptions.ECMAScript }; yield return new object[] { @"[\d-[13579]]+", "\x066102468\x0660", RegexOptions.ECMAScript }; yield return new object[] { @"[\d-[13579]]+", "\x066102468\x0660", RegexOptions.None }; yield return new object[] { @"[\w-[b-y]]+", "bbbaaaABCD09zzzyyy", RegexOptions.None }; yield return new object[] { @"[\w-[b-y]]+", "bbbaaaABCD09zzzyyy", RegexOptions.None }; yield return new object[] { @"[\w-[b-y]]+", "bbbaaaABCD09zzzyyy", RegexOptions.None }; yield return new object[] { @"[\p{Ll}-[ae-z]]+", "aaabbbcccdddeee", RegexOptions.None }; yield return new object[] { @"[\p{Nd}-[2468]]+", "20135798", RegexOptions.None }; yield return new object[] { @"[\P{Lu}-[ae-z]]+", "aaabbbcccdddeee", RegexOptions.None }; yield return new object[] { @"[\P{Nd}-[\p{Ll}]]+", "az09AZ'[]", RegexOptions.None }; yield return new object[] { "[abcd-[def]]+", "fedddaabbccddd", RegexOptions.None }; yield return new object[] { @"[\d-[357a-z]]+", "az33312468955", RegexOptions.None }; yield return new object[] { @"[\d-[de357fgA-Z]]+", "AZ51246897", RegexOptions.None }; yield return new object[] { @"[\d-[357\p{Ll}]]+", "az3312468977", RegexOptions.None }; yield return new object[] { @"[\w-[b-y\s]]+", " \tbbbaaaABCD09zzzyyy", RegexOptions.None }; yield return new object[] { @"[\w-[\d\p{Po}]]+", "!#0AZaz9", RegexOptions.None }; yield return new object[] { @"[\w-[\p{Ll}\s]]+", "a09AZz", RegexOptions.None }; yield return new object[] { @"[\d-[13579a-zA-Z]]+", "AZ1024689", RegexOptions.ECMAScript }; yield return new object[] { @"[\d-[13579abcd]]+", "abcd\x066102468\x0660", RegexOptions.ECMAScript }; yield return new object[] { @"[\d-[13579\s]]+", " \t\x066102468\x0660", RegexOptions.None }; yield return new object[] { @"[\w-[b-y\p{Po}]]+", "!#bbbaaaABCD09zzzyyy", RegexOptions.None }; yield return new object[] { @"[\w-[b-y!.,]]+", "!.,bbbaaaABCD09zzzyyy", RegexOptions.None }; yield return new object[] { "[\\w-[b-y\x00-\x0F]]+", "\0bbbaaaABCD09zzzyyy", RegexOptions.None }; yield return new object[] { @"[\p{Ll}-[ae-z0-9]]+", "09aaabbbcccdddeee", RegexOptions.None }; yield return new object[] { @"[\p{Nd}-[2468az]]+", "az20135798", RegexOptions.None }; yield return new object[] { @"[\P{Lu}-[ae-zA-Z]]+", "AZaaabbbcccdddeee", RegexOptions.None }; yield return new object[] { @"[\P{Nd}-[\p{Ll}0123456789]]+", "09az09AZ'[]", RegexOptions.None }; yield return new object[] { "[abc-[defg]]+", "dddaabbccddd", RegexOptions.None }; yield return new object[] { @"[\d-[abc]]+", "abc09abc", RegexOptions.None }; yield return new object[] { @"[\d-[a-zA-Z]]+", "az09AZ", RegexOptions.None }; yield return new object[] { @"[\d-[\p{Ll}]]+", "az09az", RegexOptions.None }; yield return new object[] { @"[\w-[\x00-\x0F]]+", "bbbaaaABYZ09zzzyyy", RegexOptions.None }; yield return new object[] { @"[\w-[\s]]+", "0AZaz9", RegexOptions.None }; yield return new object[] { @"[\w-[\W]]+", "0AZaz9", RegexOptions.None }; yield return new object[] { @"[\w-[\p{Po}]]+", "#a09AZz!", RegexOptions.None }; yield return new object[] { @"[\d-[\D]]+", "azAZ1024689", RegexOptions.ECMAScript }; yield return new object[] { @"[\d-[a-zA-Z]]+", "azAZ\x066102468\x0660", RegexOptions.ECMAScript }; yield return new object[] { @"[\d-[\p{Ll}]]+", "\x066102468\x0660", RegexOptions.None }; yield return new object[] { @"[a-zA-Z0-9-[\s]]+", " \tazAZ09", RegexOptions.None }; yield return new object[] { @"[a-zA-Z0-9-[\W]]+", "bbbaaaABCD09zzzyyy", RegexOptions.None }; yield return new object[] { @"[a-zA-Z0-9-[^a-zA-Z0-9]]+", "bbbaaaABCD09zzzyyy", RegexOptions.None }; yield return new object[] { @"[\p{Ll}-[A-Z]]+", "AZaz09", RegexOptions.None }; yield return new object[] { @"[\p{Nd}-[a-z]]+", "az09", RegexOptions.None }; yield return new object[] { @"[\P{Lu}-[\p{Lu}]]+", "AZazAZ", RegexOptions.None }; yield return new object[] { @"[\P{Lu}-[A-Z]]+", "AZazAZ", RegexOptions.None }; yield return new object[] { @"[\P{Nd}-[\p{Nd}]]+", "azAZ09", RegexOptions.None }; yield return new object[] { @"[\P{Nd}-[2-8]]+", "1234567890azAZ1234567890", RegexOptions.None }; yield return new object[] { @"([ ]|[\w-[0-9]])+", "09az AZ90", RegexOptions.None }; yield return new object[] { @"([0-9-[02468]]|[0-9-[13579]])+", "az1234567890za", RegexOptions.None }; yield return new object[] { @"([^0-9-[a-zAE-Z]]|[\w-[a-zAF-Z]])+", "azBCDE1234567890BCDEFza", RegexOptions.None }; yield return new object[] { @"([\p{Ll}-[aeiou]]|[^\w-[\s]])+", "aeiobcdxyz!@#aeio", RegexOptions.None }; yield return new object[] { @"98[\d-[9]][\d-[8]][\d-[0]]", "98911 98881 98870 98871", RegexOptions.None }; yield return new object[] { @"m[\w-[^aeiou]][\w-[^aeiou]]t", "mbbt mect meet", RegexOptions.None }; yield return new object[] { "[abcdef-[^bce]]+", "adfbcefda", RegexOptions.None }; yield return new object[] { "[^cde-[ag]]+", "agbfxyzga", RegexOptions.None }; yield return new object[] { @"[\p{L}-[^\p{Lu}]]+", "09',.abcxyzABCXYZ", RegexOptions.None }; yield return new object[] { @"[\p{IsGreek}-[\P{Lu}]]+", "\u0390\u03FE\u0386\u0388\u03EC\u03EE\u0400", RegexOptions.None }; yield return new object[] { @"[\p{IsBasicLatin}-[G-L]]+", "GAFMZL", RegexOptions.None }; yield return new object[] { "[a-zA-Z-[aeiouAEIOU]]+", "aeiouAEIOUbcdfghjklmnpqrstvwxyz", RegexOptions.None }; yield return new object[] { @"^ (?<octet>^ ( ( (?<Octet2xx>[\d-[013-9]]) | [\d-[2-9]] ) (?(Octet2xx) ( (?<Octet25x>[\d-[01-46-9]]) | [\d-[5-9]] ) ( (?(Octet25x) [\d-[6-9]] | [\d] ) ) | [\d]{2} ) ) | ([\d][\d]) | [\d] )$" , "255", RegexOptions.IgnorePatternWhitespace }; yield return new object[] { @"[abcd\-d-[bc]]+", "bbbaaa---dddccc", RegexOptions.None }; yield return new object[] { @"[abcd\-d-[bc]]+", "bbbaaa---dddccc", RegexOptions.None }; yield return new object[] { @"[^a-f-[\x00-\x60\u007B-\uFFFF]]+", "aaafffgggzzz{{{", RegexOptions.None }; yield return new object[] { @"[\[\]a-f-[[]]+", "gggaaafff]]][[[", RegexOptions.None }; yield return new object[] { @"[\[\]a-f-[]]]+", "gggaaafff[[[]]]", RegexOptions.None }; yield return new object[] { @"[ab\-\[cd-[-[]]]]", "a]]", RegexOptions.None }; yield return new object[] { @"[ab\-\[cd-[-[]]]]", "b]]", RegexOptions.None }; yield return new object[] { @"[ab\-\[cd-[-[]]]]", "c]]", RegexOptions.None }; yield return new object[] { @"[ab\-\[cd-[-[]]]]", "d]]", RegexOptions.None }; yield return new object[] { @"[ab\-\[cd-[[]]]]", "a]]", RegexOptions.None }; yield return new object[] { @"[ab\-\[cd-[[]]]]", "b]]", RegexOptions.None }; yield return new object[] { @"[ab\-\[cd-[[]]]]", "c]]", RegexOptions.None }; yield return new object[] { @"[ab\-\[cd-[[]]]]", "d]]", RegexOptions.None }; yield return new object[] { @"[ab\-\[cd-[[]]]]", "-]]", RegexOptions.None }; yield return new object[] { @"[a-[c-e]]+", "bbbaaaccc", RegexOptions.None }; yield return new object[] { @"[a-[c-e]]+", "```aaaccc", RegexOptions.None }; yield return new object[] { @"[a-d\--[bc]]+", "cccaaa--dddbbb", RegexOptions.None }; yield return new object[] { @"[\0- [bc]+", "!!!\0\0\t\t [[[[bbbcccaaa", RegexOptions.None }; yield return new object[] { "[[abcd]-[bc]]+", "a-b]", RegexOptions.None }; yield return new object[] { "[-[e-g]+", "ddd[[[---eeefffggghhh", RegexOptions.None }; yield return new object[] { "[-e-g]+", "ddd---eeefffggghhh", RegexOptions.None }; yield return new object[] { "[-e-g]+", "ddd---eeefffggghhh", RegexOptions.None }; yield return new object[] { "[a-e - m-p]+", "---a b c d e m n o p---", RegexOptions.None }; yield return new object[] { "[^-[bc]]", "b] c] -] aaaddd]", RegexOptions.None }; yield return new object[] { "[^-[bc]]", "b] c] -] aaa]ddd]", RegexOptions.None }; yield return new object[] { @"[a\-[bc]+", "```bbbaaa---[[[cccddd", RegexOptions.None }; yield return new object[] { @"[a\-[\-\-bc]+", "```bbbaaa---[[[cccddd", RegexOptions.None }; yield return new object[] { @"[a\-\[\-\[\-bc]+", "```bbbaaa---[[[cccddd", RegexOptions.None }; yield return new object[] { @"[abc\--[b]]+", "[[[```bbbaaa---cccddd", RegexOptions.None }; yield return new object[] { @"[abc\-z-[b]]+", "```aaaccc---zzzbbb", RegexOptions.None }; yield return new object[] { @"[a-d\-[b]+", "```aaabbbcccddd----[[[[]]]", RegexOptions.None }; yield return new object[] { @"[abcd\-d\-[bc]+", "bbbaaa---[[[dddccc", RegexOptions.None }; yield return new object[] { "[a - c - [ b ] ]+", "dddaaa ccc [[[[ bbb ]]]", RegexOptions.IgnorePatternWhitespace }; yield return new object[] { "[a - c - [ b ] +", "dddaaa ccc [[[[ bbb ]]]", RegexOptions.IgnorePatternWhitespace }; yield return new object[] { @"(\p{Lu}\w*)\s(\p{Lu}\w*)", "Hello World", RegexOptions.None }; yield return new object[] { @"(\p{Lu}\p{Ll}*)\s(\p{Lu}\p{Ll}*)", "Hello World", RegexOptions.None }; yield return new object[] { @"(\P{Ll}\p{Ll}*)\s(\P{Ll}\p{Ll}*)", "Hello World", RegexOptions.None }; yield return new object[] { @"(\P{Lu}+\p{Lu})\s(\P{Lu}+\p{Lu})", "hellO worlD", RegexOptions.None }; yield return new object[] { @"(\p{Lt}\w*)\s(\p{Lt}*\w*)", "\u01C5ello \u01C5orld", RegexOptions.None }; yield return new object[] { @"(\P{Lt}\w*)\s(\P{Lt}*\w*)", "Hello World", RegexOptions.None }; yield return new object[] { @"[@-D]+", "eE?@ABCDabcdeE", RegexOptions.IgnoreCase }; yield return new object[] { @"[>-D]+", "eE=>?@ABCDabcdeE", RegexOptions.IgnoreCase }; yield return new object[] { @"[\u0554-\u0557]+", "\u0583\u0553\u0554\u0555\u0556\u0584\u0585\u0586\u0557\u0558", RegexOptions.IgnoreCase }; yield return new object[] { @"[X-\]]+", "wWXYZxyz[\\]^", RegexOptions.IgnoreCase }; yield return new object[] { @"[X-\u0533]+", "\u0551\u0554\u0560AXYZaxyz\u0531\u0532\u0533\u0561\u0562\u0563\u0564", RegexOptions.IgnoreCase }; yield return new object[] { @"[X-a]+", "wWAXYZaxyz", RegexOptions.IgnoreCase }; yield return new object[] { @"[X-c]+", "wWABCXYZabcxyz", RegexOptions.IgnoreCase }; yield return new object[] { @"[X-\u00C0]+", "\u00C1\u00E1\u00C0\u00E0wWABCXYZabcxyz", RegexOptions.IgnoreCase }; yield return new object[] { @"[\u0100\u0102\u0104]+", "\u00FF \u0100\u0102\u0104\u0101\u0103\u0105\u0106", RegexOptions.IgnoreCase }; yield return new object[] { @"[B-D\u0130]+", "aAeE\u0129\u0131\u0068 BCDbcD\u0130\u0069\u0070", RegexOptions.IgnoreCase }; yield return new object[] { @"[\u013B\u013D\u013F]+", "\u013A\u013B\u013D\u013F\u013C\u013E\u0140\u0141", RegexOptions.IgnoreCase }; yield return new object[] { "(Cat)\r(Dog)", "Cat\rDog", RegexOptions.None }; yield return new object[] { "(Cat)\t(Dog)", "Cat\tDog", RegexOptions.None }; yield return new object[] { "(Cat)\f(Dog)", "Cat\fDog", RegexOptions.None }; yield return new object[] { @"{5", "hello {5 world", RegexOptions.None }; yield return new object[] { @"{5,", "hello {5, world", RegexOptions.None }; yield return new object[] { @"{5,6", "hello {5,6 world", RegexOptions.None }; yield return new object[] { @"(?n:(?<cat>cat)(\s+)(?<dog>dog))", "cat dog", RegexOptions.None }; yield return new object[] { @"(?n:(cat)(\s+)(dog))", "cat dog", RegexOptions.None }; yield return new object[] { @"(?n:(cat)(?<SpaceChars>\s+)(dog))", "cat dog", RegexOptions.None }; yield return new object[] { @"(?x: (?<cat>cat) # Cat statement (\s+) # Whitespace chars (?<dog>dog # Dog statement ))", "cat dog", RegexOptions.None }; yield return new object[] { @"(?+i:cat)", "CAT", RegexOptions.None }; yield return new object[] { @"cat([\d]*)dog", "hello123cat230927dog1412d", RegexOptions.None }; yield return new object[] { @"([\D]*)dog", "65498catdog58719", RegexOptions.None }; yield return new object[] { @"cat([\s]*)dog", "wiocat dog3270", RegexOptions.None }; yield return new object[] { @"cat([\S]*)", "sfdcatdog 3270", RegexOptions.None }; yield return new object[] { @"cat([\w]*)", "sfdcatdog 3270", RegexOptions.None }; yield return new object[] { @"cat([\W]*)dog", "wiocat dog3270", RegexOptions.None }; yield return new object[] { @"([\p{Lu}]\w*)\s([\p{Lu}]\w*)", "Hello World", RegexOptions.None }; yield return new object[] { @"([\P{Ll}][\p{Ll}]*)\s([\P{Ll}][\p{Ll}]*)", "Hello World", RegexOptions.None }; yield return new object[] { @"(cat)([\x41]*)(dog)", "catAAAdog", RegexOptions.None }; yield return new object[] { @"(cat)([\u0041]*)(dog)", "catAAAdog", RegexOptions.None }; yield return new object[] { @"(cat)([\a]*)(dog)", "cat\a\a\adog", RegexOptions.None }; yield return new object[] { @"(cat)([\b]*)(dog)", "cat\b\b\bdog", RegexOptions.None }; yield return new object[] { @"(cat)([\e]*)(dog)", "cat\u001B\u001B\u001Bdog", RegexOptions.None }; yield return new object[] { @"(cat)([\f]*)(dog)", "cat\f\f\fdog", RegexOptions.None }; yield return new object[] { @"(cat)([\r]*)(dog)", "cat\r\r\rdog", RegexOptions.None }; yield return new object[] { @"(cat)([\v]*)(dog)", "cat\v\v\vdog", RegexOptions.None }; yield return new object[] { @"cat([\d]*)dog", "hello123cat230927dog1412d", RegexOptions.ECMAScript }; yield return new object[] { @"([\D]*)dog", "65498catdog58719", RegexOptions.ECMAScript }; yield return new object[] { @"cat([\s]*)dog", "wiocat dog3270", RegexOptions.ECMAScript }; yield return new object[] { @"cat([\S]*)", "sfdcatdog 3270", RegexOptions.ECMAScript }; yield return new object[] { @"cat([\w]*)", "sfdcatdog 3270", RegexOptions.ECMAScript }; yield return new object[] { @"cat([\W]*)dog", "wiocat dog3270", RegexOptions.ECMAScript }; yield return new object[] { @"([\p{Lu}]\w*)\s([\p{Lu}]\w*)", "Hello World", RegexOptions.ECMAScript }; yield return new object[] { @"([\P{Ll}][\p{Ll}]*)\s([\P{Ll}][\p{Ll}]*)", "Hello World", RegexOptions.ECMAScript }; yield return new object[] { @"(cat)\d*dog", "hello123cat230927dog1412d", RegexOptions.ECMAScript }; yield return new object[] { @"\D*(dog)", "65498catdog58719", RegexOptions.ECMAScript }; yield return new object[] { @"(cat)\s*(dog)", "wiocat dog3270", RegexOptions.ECMAScript }; yield return new object[] { @"(cat)\S*", "sfdcatdog 3270", RegexOptions.ECMAScript }; yield return new object[] { @"(cat)\w*", "sfdcatdog 3270", RegexOptions.ECMAScript }; yield return new object[] { @"(cat)\W*(dog)", "wiocat dog3270", RegexOptions.ECMAScript }; yield return new object[] { @"\p{Lu}(\w*)\s\p{Lu}(\w*)", "Hello World", RegexOptions.ECMAScript }; yield return new object[] { @"\P{Ll}\p{Ll}*\s\P{Ll}\p{Ll}*", "Hello World", RegexOptions.ECMAScript }; yield return new object[] { @"cat(?<dog121>dog)", "catcatdogdogcat", RegexOptions.None }; yield return new object[] { @"(?<cat>cat)\s*(?<cat>dog)", "catcat dogdogcat", RegexOptions.None }; yield return new object[] { @"(?<1>cat)\s*(?<1>dog)", "catcat dogdogcat", RegexOptions.None }; yield return new object[] { @"(?<2048>cat)\s*(?<2048>dog)", "catcat dogdogcat", RegexOptions.None }; yield return new object[] { @"(?<cat>cat)\w+(?<dog-cat>dog)", "cat_Hello_World_dog", RegexOptions.None }; yield return new object[] { @"(?<cat>cat)\w+(?<-cat>dog)", "cat_Hello_World_dog", RegexOptions.None }; yield return new object[] { @"(?<cat>cat)\w+(?<cat-cat>dog)", "cat_Hello_World_dog", RegexOptions.None }; yield return new object[] { @"(?<1>cat)\w+(?<dog-1>dog)", "cat_Hello_World_dog", RegexOptions.None }; yield return new object[] { @"(?<cat>cat)\w+(?<2-cat>dog)", "cat_Hello_World_dog", RegexOptions.None }; yield return new object[] { @"(?<1>cat)\w+(?<2-1>dog)", "cat_Hello_World_dog", RegexOptions.None }; yield return new object[] { @"(?<cat>cat){", "STARTcat{", RegexOptions.None }; yield return new object[] { @"(?<cat>cat){fdsa", "STARTcat{fdsa", RegexOptions.None }; yield return new object[] { @"(?<cat>cat){1", "STARTcat{1", RegexOptions.None }; yield return new object[] { @"(?<cat>cat){1END", "STARTcat{1END", RegexOptions.None }; yield return new object[] { @"(?<cat>cat){1,", "STARTcat{1,", RegexOptions.None }; yield return new object[] { @"(?<cat>cat){1,END", "STARTcat{1,END", RegexOptions.None }; yield return new object[] { @"(?<cat>cat){1,2", "STARTcat{1,2", RegexOptions.None }; yield return new object[] { @"(?<cat>cat){1,2END", "STARTcat{1,2END", RegexOptions.None }; yield return new object[] { @"(cat) #cat \s+ #followed by 1 or more whitespace (dog) #followed by dog ", "cat dog", RegexOptions.IgnorePatternWhitespace }; yield return new object[] { @"(cat) #cat \s+ #followed by 1 or more whitespace (dog) #followed by dog", "cat dog", RegexOptions.IgnorePatternWhitespace }; yield return new object[] { @"(cat) (?#cat) \s+ (?#followed by 1 or more whitespace) (dog) (?#followed by dog)", "cat dog", RegexOptions.IgnorePatternWhitespace }; yield return new object[] { @"(?<cat>cat)(?<dog>dog)\k<cat>", "asdfcatdogcatdog", RegexOptions.None }; yield return new object[] { @"(?<cat>cat)\s+(?<dog>dog)\k<cat>", "asdfcat dogcat dog", RegexOptions.None }; yield return new object[] { @"(?<cat>cat)\s+(?<dog>dog)\k'cat'", "asdfcat dogcat dog", RegexOptions.None }; yield return new object[] { @"(?<cat>cat)\s+(?<dog>dog)\<cat>", "asdfcat dogcat dog", RegexOptions.None }; yield return new object[] { @"(?<cat>cat)\s+(?<dog>dog)\'cat'", "asdfcat dogcat dog", RegexOptions.None }; yield return new object[] { @"(?<cat>cat)\s+(?<dog>dog)\k<1>", "asdfcat dogcat dog", RegexOptions.None }; yield return new object[] { @"(?<cat>cat)\s+(?<dog>dog)\k'1'", "asdfcat dogcat dog", RegexOptions.None }; yield return new object[] { @"(?<cat>cat)\s+(?<dog>dog)\<1>", "asdfcat dogcat dog", RegexOptions.None }; yield return new object[] { @"(?<cat>cat)\s+(?<dog>dog)\'1'", "asdfcat dogcat dog", RegexOptions.None }; yield return new object[] { @"(?<cat>cat)\s+(?<dog>dog)\1", "asdfcat dogcat dog", RegexOptions.None }; yield return new object[] { @"(?<cat>cat)\s+(?<dog>dog)\1", "asdfcat dogcat dog", RegexOptions.ECMAScript }; yield return new object[] { @"(?<cat>cat)\s+(?<dog>dog)\k<dog>", "asdfcat dogdog dog", RegexOptions.None }; yield return new object[] { @"(?<cat>cat)\s+(?<dog>dog)\2", "asdfcat dogdog dog", RegexOptions.None }; yield return new object[] { @"(?<cat>cat)\s+(?<dog>dog)\2", "asdfcat dogdog dog", RegexOptions.ECMAScript }; yield return new object[] { @"(cat)(\077)", "hellocat?dogworld", RegexOptions.None }; yield return new object[] { @"(cat)(\77)", "hellocat?dogworld", RegexOptions.None }; yield return new object[] { @"(cat)(\176)", "hellocat~dogworld", RegexOptions.None }; yield return new object[] { @"(cat)(\400)", "hellocat\0dogworld", RegexOptions.None }; yield return new object[] { @"(cat)(\300)", "hellocat\u00C0dogworld", RegexOptions.None }; yield return new object[] { @"(cat)(\300)", "hellocat\u00C0dogworld", RegexOptions.None }; yield return new object[] { @"(cat)(\477)", "hellocat\u003Fdogworld", RegexOptions.None }; yield return new object[] { @"(cat)(\777)", "hellocat\u00FFdogworld", RegexOptions.None }; yield return new object[] { @"(cat)(\7770)", "hellocat\u00FF0dogworld", RegexOptions.None }; yield return new object[] { @"(cat)(\077)", "hellocat?dogworld", RegexOptions.ECMAScript }; yield return new object[] { @"(cat)(\77)", "hellocat?dogworld", RegexOptions.ECMAScript }; yield return new object[] { @"(cat)(\7)", "hellocat\adogworld", RegexOptions.ECMAScript }; yield return new object[] { @"(cat)(\40)", "hellocat dogworld", RegexOptions.ECMAScript }; yield return new object[] { @"(cat)(\040)", "hellocat dogworld", RegexOptions.ECMAScript }; yield return new object[] { @"(cat)(\176)", "hellocatcat76dogworld", RegexOptions.ECMAScript }; yield return new object[] { @"(cat)(\377)", "hellocat\u00FFdogworld", RegexOptions.ECMAScript }; yield return new object[] { @"(cat)(\400)", "hellocat 0Fdogworld", RegexOptions.ECMAScript }; yield return new object[] { @"(cat)\s+(?<2147483646>dog)", "asdlkcat dogiwod", RegexOptions.None }; yield return new object[] { @"(cat)\s+(?<2147483647>dog)", "asdlkcat dogiwod", RegexOptions.None }; yield return new object[] { @"(cat)(\x2a*)(dog)", "asdlkcat***dogiwod", RegexOptions.None }; yield return new object[] { @"(cat)(\x2b*)(dog)", "asdlkcat+++dogiwod", RegexOptions.None }; yield return new object[] { @"(cat)(\x2c*)(dog)", "asdlkcat,,,dogiwod", RegexOptions.None }; yield return new object[] { @"(cat)(\x2d*)(dog)", "asdlkcat---dogiwod", RegexOptions.None }; yield return new object[] { @"(cat)(\x2e*)(dog)", "asdlkcat...dogiwod", RegexOptions.None }; yield return new object[] { @"(cat)(\x2A*)(dog)", "asdlkcat***dogiwod", RegexOptions.None }; yield return new object[] { @"(cat)(\x2B*)(dog)", "asdlkcat+++dogiwod", RegexOptions.None }; yield return new object[] { @"(cat)(\x2C*)(dog)", "asdlkcat,,,dogiwod", RegexOptions.None }; yield return new object[] { @"(cat)(\x2D*)(dog)", "asdlkcat---dogiwod", RegexOptions.None }; yield return new object[] { @"(cat)(\x2E*)(dog)", "asdlkcat...dogiwod", RegexOptions.None }; yield return new object[] { @"(cat)(\c@*)(dog)", "asdlkcat\0\0dogiwod", RegexOptions.None }; yield return new object[] { @"(cat)(\cA*)(dog)", "asdlkcat\u0001dogiwod", RegexOptions.None }; yield return new object[] { @"(cat)(\ca*)(dog)", "asdlkcat\u0001dogiwod", RegexOptions.None }; yield return new object[] { @"(cat)(\cC*)(dog)", "asdlkcat\u0003dogiwod", RegexOptions.None }; yield return new object[] { @"(cat)(\cc*)(dog)", "asdlkcat\u0003dogiwod", RegexOptions.None }; yield return new object[] { @"(cat)(\cD*)(dog)", "asdlkcat\u0004dogiwod", RegexOptions.None }; yield return new object[] { @"(cat)(\cd*)(dog)", "asdlkcat\u0004dogiwod", RegexOptions.None }; yield return new object[] { @"(cat)(\cX*)(dog)", "asdlkcat\u0018dogiwod", RegexOptions.None }; yield return new object[] { @"(cat)(\cx*)(dog)", "asdlkcat\u0018dogiwod", RegexOptions.None }; yield return new object[] { @"(cat)(\cZ*)(dog)", "asdlkcat\u001adogiwod", RegexOptions.None }; yield return new object[] { @"(cat)(\cz*)(dog)", "asdlkcat\u001adogiwod", RegexOptions.None }; yield return new object[] { @"\A(cat)\s+(dog)", "cat \n\n\n dog", RegexOptions.None }; yield return new object[] { @"\A(cat)\s+(dog)", "cat \n\n\n dog", RegexOptions.Multiline }; yield return new object[] { @"\A(cat)\s+(dog)", "cat \n\n\n dog", RegexOptions.ECMAScript }; yield return new object[] { @"(cat)\s+(dog)\Z", "cat \n\n\n dog", RegexOptions.None }; yield return new object[] { @"(cat)\s+(dog)\Z", "cat \n\n\n dog", RegexOptions.Multiline }; yield return new object[] { @"(cat)\s+(dog)\Z", "cat \n\n\n dog", RegexOptions.ECMAScript }; yield return new object[] { @"(cat)\s+(dog)\Z", "cat \n\n\n dog\n", RegexOptions.None }; yield return new object[] { @"(cat)\s+(dog)\Z", "cat \n\n\n dog\n", RegexOptions.Multiline }; yield return new object[] { @"(cat)\s+(dog)\Z", "cat \n\n\n dog\n", RegexOptions.ECMAScript }; yield return new object[] { @"(cat)\s+(dog)\z", "cat \n\n\n dog", RegexOptions.None }; yield return new object[] { @"(cat)\s+(dog)\z", "cat \n\n\n dog", RegexOptions.Multiline }; yield return new object[] { @"(cat)\s+(dog)\z", "cat \n\n\n dog", RegexOptions.ECMAScript }; yield return new object[] { @"\b@cat", "123START123@catEND", RegexOptions.None }; yield return new object[] { @"\b\<cat", "123START123<catEND", RegexOptions.None }; yield return new object[] { @"\b,cat", "satwe,,,START,catEND", RegexOptions.None }; yield return new object[] { @"\b\[cat", "`12START123[catEND", RegexOptions.None }; yield return new object[] { @"\B@cat", "123START123;@catEND", RegexOptions.None }; yield return new object[] { @"\B\<cat", "123START123'<catEND", RegexOptions.None }; yield return new object[] { @"\B,cat", "satwe,,,START',catEND", RegexOptions.None }; yield return new object[] { @"\B\[cat", "`12START123'[catEND", RegexOptions.None }; yield return new object[] { @"(\w+)\s+(\w+)", "cat\u02b0 dog\u02b1", RegexOptions.None }; yield return new object[] { @"(cat\w+)\s+(dog\w+)", "STARTcat\u30FC dog\u3005END", RegexOptions.None }; yield return new object[] { @"(cat\w+)\s+(dog\w+)", "STARTcat\uff9e dog\uff9fEND", RegexOptions.None }; yield return new object[] { @"[^a]|d", "d", RegexOptions.None }; yield return new object[] { @"([^a]|[d])*", "Hello Worlddf", RegexOptions.None }; yield return new object[] { @"([^{}]|\n)+", "{{{{Hello\n World \n}END", RegexOptions.None }; yield return new object[] { @"([a-d]|[^abcd])+", "\tonce\n upon\0 a- ()*&^%#time?", RegexOptions.None }; yield return new object[] { @"([^a]|[a])*", "once upon a time", RegexOptions.None }; yield return new object[] { @"([a-d]|[^abcd]|[x-z]|^wxyz])+", "\tonce\n upon\0 a- ()*&^%#time?", RegexOptions.None }; yield return new object[] { @"([a-d]|[e-i]|[^e]|wxyz])+", "\tonce\n upon\0 a- ()*&^%#time?", RegexOptions.None }; yield return new object[] { @"^(([^b]+ )|(.* ))$", "aaa ", RegexOptions.None }; yield return new object[] { @"^(([^b]+ )|(.*))$", "aaa", RegexOptions.None }; yield return new object[] { @"^(([^b]+ )|(.* ))$", "bbb ", RegexOptions.None }; yield return new object[] { @"^(([^b]+ )|(.*))$", "bbb", RegexOptions.None }; yield return new object[] { @"^((a*)|(.*))$", "aaa", RegexOptions.None }; yield return new object[] { @"^((a*)|(.*))$", "aaabbb", RegexOptions.None }; yield return new object[] { @"(([0-9])|([a-z])|([A-Z]))*", "{hello 1234567890 world}", RegexOptions.None }; yield return new object[] { @"(([0-9])|([a-z])|([A-Z]))+", "{hello 1234567890 world}", RegexOptions.None }; yield return new object[] { @"(([0-9])|([a-z])|([A-Z]))*", "{HELLO 1234567890 world}", RegexOptions.None }; yield return new object[] { @"(([0-9])|([a-z])|([A-Z]))+", "{HELLO 1234567890 world}", RegexOptions.None }; yield return new object[] { @"(([0-9])|([a-z])|([A-Z]))*", "{1234567890 hello world}", RegexOptions.None }; yield return new object[] { @"(([0-9])|([a-z])|([A-Z]))+", "{1234567890 hello world}", RegexOptions.None }; yield return new object[] { @"^(([a-d]*)|([a-z]*))$", "aaabbbcccdddeeefff", RegexOptions.None }; yield return new object[] { @"^(([d-f]*)|([c-e]*))$", "dddeeeccceee", RegexOptions.None }; yield return new object[] { @"^(([c-e]*)|([d-f]*))$", "dddeeeccceee", RegexOptions.None }; yield return new object[] { @"(([a-d]*)|([a-z]*))", "aaabbbcccdddeeefff", RegexOptions.None }; yield return new object[] { @"(([d-f]*)|([c-e]*))", "dddeeeccceee", RegexOptions.None }; yield return new object[] { @"(([c-e]*)|([d-f]*))", "dddeeeccceee", RegexOptions.None }; yield return new object[] { @"(([a-d]*)|(.*))", "aaabbbcccdddeeefff", RegexOptions.None }; yield return new object[] { @"(([d-f]*)|(.*))", "dddeeeccceee", RegexOptions.None }; yield return new object[] { @"(([c-e]*)|(.*))", "dddeeeccceee", RegexOptions.None }; yield return new object[] { @"\p{Pi}(\w*)\p{Pf}", "\u00ABCat\u00BB \u00BBDog\u00AB'", RegexOptions.None }; yield return new object[] { @"\p{Pi}(\w*)\p{Pf}", "\u2018Cat\u2019 \u2019Dog\u2018'", RegexOptions.None }; yield return new object[] { @"(?<cat>cat)\s+(?<dog>dog)\s+\123\s+\234", "asdfcat dog cat23 dog34eia", RegexOptions.ECMAScript }; yield return new object[] { @"<div> (?> <div>(?<DEPTH>) | </div> (?<-DEPTH>) | .? )*? (?(DEPTH)(?!)) </div>", "<div>this is some <div>red</div> text</div></div></div>", RegexOptions.IgnorePatternWhitespace }; yield return new object[] { @"( ((?'open'<+)[^<>]*)+ ((?'close-open'>+)[^<>]*)+ )+", "<01deep_01<02deep_01<03deep_01>><02deep_02><02deep_03<03deep_03>>>", RegexOptions.IgnorePatternWhitespace }; yield return new object[] { @"( (?<start><)? [^<>]? (?<end-start>>)? )*", "<01deep_01<02deep_01<03deep_01>><02deep_02><02deep_03<03deep_03>>>", RegexOptions.IgnorePatternWhitespace }; yield return new object[] { @"( (?<start><[^/<>]*>)? [^<>]? (?<end-start></[^/<>]*>)? )*", "<b><a>Cat</a></b>", RegexOptions.IgnorePatternWhitespace }; yield return new object[] { @"( (?<start><(?<TagName>[^/<>]*)>)? [^<>]? (?<end-start></\k<TagName>>)? )*", "<b>cat</b><a>dog</a>", RegexOptions.IgnorePatternWhitespace }; yield return new object[] { @"([0-9]+?)([\w]+?)", "55488aheiaheiad", RegexOptions.ECMAScript }; yield return new object[] { @"([0-9]+?)([a-z]+?)", "55488aheiaheiad", RegexOptions.ECMAScript }; yield return new object[] { @"\G<%#(?<code>.*?)?%>", @"<%# DataBinder.Eval(this, ""MyNumber"") %>", RegexOptions.Singleline }; yield return new object[] { @"^[abcd]{0,0x10}*$", "a{0,0x10}}}", RegexOptions.None }; yield return new object[] { @"([a-z]*?)([\w])", "cat", RegexOptions.IgnoreCase }; yield return new object[] { @"^([a-z]*?)([\w])$", "cat", RegexOptions.IgnoreCase }; yield return new object[] { @"([a-z]*)([\w])", "cat", RegexOptions.IgnoreCase }; yield return new object[] { @"^([a-z]*)([\w])$", "cat", RegexOptions.IgnoreCase }; yield return new object[] { @"(cat){", "cat{", RegexOptions.None }; yield return new object[] { @"(cat){}", "cat{}", RegexOptions.None }; yield return new object[] { @"(cat){,", "cat{,", RegexOptions.None }; yield return new object[] { @"(cat){,}", "cat{,}", RegexOptions.None }; yield return new object[] { @"(cat){cat}", "cat{cat}", RegexOptions.None }; yield return new object[] { @"(cat){cat,5}", "cat{cat,5}", RegexOptions.None }; yield return new object[] { @"(cat){5,dog}", "cat{5,dog}", RegexOptions.None }; yield return new object[] { @"(cat){cat,dog}", "cat{cat,dog}", RegexOptions.None }; yield return new object[] { @"(cat){,}?", "cat{,}?", RegexOptions.None }; yield return new object[] { @"(cat){cat}?", "cat{cat}?", RegexOptions.None }; yield return new object[] { @"(cat){cat,5}?", "cat{cat,5}?", RegexOptions.None }; yield return new object[] { @"(cat){5,dog}?", "cat{5,dog}?", RegexOptions.None }; yield return new object[] { @"(cat){cat,dog}?", "cat{cat,dog}?", RegexOptions.None }; yield return new object[] { @"()", "cat", RegexOptions.None }; yield return new object[] { @"(?<cat>)", "cat", RegexOptions.None }; yield return new object[] { @"(?'cat')", "cat", RegexOptions.None }; yield return new object[] { @"(?:)", "cat", RegexOptions.None }; yield return new object[] { @"(?imn)", "cat", RegexOptions.None }; yield return new object[] { @"(?imn)cat", "(?imn)cat", RegexOptions.None }; yield return new object[] { @"(?=)", "cat", RegexOptions.None }; yield return new object[] { @"(?<=)", "cat", RegexOptions.None }; yield return new object[] { @"(?>)", "cat", RegexOptions.None }; yield return new object[] { @"(?()|)", "(?()|)", RegexOptions.None }; yield return new object[] { @"(?(cat)|)", "cat", RegexOptions.None }; yield return new object[] { @"(?(cat)|)", "dog", RegexOptions.None }; yield return new object[] { @"(?(cat)catdog|)", "catdog", RegexOptions.None }; yield return new object[] { @"(?(cat)catdog|)", "dog", RegexOptions.None }; yield return new object[] { @"(?(cat)dog|)", "dog", RegexOptions.None }; yield return new object[] { @"(?(cat)dog|)", "cat", RegexOptions.None }; yield return new object[] { @"(?(cat)|catdog)", "cat", RegexOptions.None }; yield return new object[] { @"(?(cat)|catdog)", "catdog", RegexOptions.None }; yield return new object[] { @"(?(cat)|dog)", "dog", RegexOptions.None }; yield return new object[] { "([\u0000-\uFFFF-[azAZ09]]|[\u0000-\uFFFF-[^azAZ09]])+", "azAZBCDE1234567890BCDEFAZza", RegexOptions.None }; yield return new object[] { "[\u0000-\uFFFF-[\u0000-\uFFFF-[\u0000-\uFFFF-[\u0000-\uFFFF-[\u0000-\uFFFF-[a]]]]]]+", "abcxyzABCXYZ123890", RegexOptions.None }; yield return new object[] { "[\u0000-\uFFFF-[\u0000-\uFFFF-[\u0000-\uFFFF-[\u0000-\uFFFF-[\u0000-\uFFFF-[\u0000-\uFFFF-[a]]]]]]]+", "bcxyzABCXYZ123890a", RegexOptions.None }; yield return new object[] { "[\u0000-\uFFFF-[\\p{P}\\p{S}\\p{C}]]+", "!@`';.,$+<>=\x0001\x001FazAZ09", RegexOptions.None }; yield return new object[] { @"[\uFFFD-\uFFFF]+", "\uFFFC\uFFFD\uFFFE\uFFFF", RegexOptions.IgnoreCase }; yield return new object[] { @"[\uFFFC-\uFFFE]+", "\uFFFB\uFFFC\uFFFD\uFFFE\uFFFF", RegexOptions.IgnoreCase }; yield return new object[] { @"([a*]*)+?$", "ab", RegexOptions.None }; yield return new object[] { @"(a*)+?$", "b", RegexOptions.None }; } } }
// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD. // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. using System; using Xunit; namespace Moq.Tests { public class CallbacksFixture { [Fact] public void ExecutesCallbackWhenVoidMethodIsCalled() { var mock = new Mock<IFoo>(); bool called = false; mock.Setup(x => x.Submit()).Callback(() => called = true); mock.Object.Submit(); Assert.True(called); } [Fact] public void ExecutesCallbackWhenNonVoidMethodIsCalled() { var mock = new Mock<IFoo>(); bool called = false; mock.Setup(x => x.Execute("ping")).Callback(() => called = true).Returns("ack"); Assert.Equal("ack", mock.Object.Execute("ping")); Assert.True(called); } [Fact] public void CallbackCalledWithoutArgumentsForMethodCallWithArguments() { var mock = new Mock<IFoo>(); bool called = false; mock.Setup(x => x.Submit(It.IsAny<string>())).Callback(() => called = true); mock.Object.Submit("blah"); Assert.True(called); } [Fact] public void FriendlyErrorWhenCallbackArgumentCountNotMatch() { var mock = new Mock<IFoo>(); Assert.Throws<ArgumentException>(() => mock.Setup(x => x.Submit(It.IsAny<string>())) .Callback((string s1, string s2) => System.Console.WriteLine(s1 + s2))); } [Fact] public void CallbackCalledWithOneArgument() { var mock = new Mock<IFoo>(); string callbackArg = null; mock.Setup(x => x.Submit(It.IsAny<string>())).Callback((string s) => callbackArg = s); mock.Object.Submit("blah"); Assert.Equal("blah", callbackArg); } [Fact] public void CallbackCalledWithTwoArguments() { var mock = new Mock<IFoo>(); string callbackArg1 = null; string callbackArg2 = null; mock.Setup(x => x.Submit(It.IsAny<string>(), It.IsAny<string>())) .Callback((string s1, string s2) => { callbackArg1 = s1; callbackArg2 = s2; }); mock.Object.Submit("blah1", "blah2"); Assert.Equal("blah1", callbackArg1); Assert.Equal("blah2", callbackArg2); } [Fact] public void CallbackCalledWithThreeArguments() { var mock = new Mock<IFoo>(); string callbackArg1 = null; string callbackArg2 = null; string callbackArg3 = null; mock.Setup(x => x.Submit(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())) .Callback((string s1, string s2, string s3) => { callbackArg1 = s1; callbackArg2 = s2; callbackArg3 = s3; }); mock.Object.Submit("blah1", "blah2", "blah3"); Assert.Equal("blah1", callbackArg1); Assert.Equal("blah2", callbackArg2); Assert.Equal("blah3", callbackArg3); } [Fact] public void CallbackCalledWithFourArguments() { var mock = new Mock<IFoo>(); string callbackArg1 = null; string callbackArg2 = null; string callbackArg3 = null; string callbackArg4 = null; mock.Setup(x => x.Submit(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())) .Callback((string s1, string s2, string s3, string s4) => { callbackArg1 = s1; callbackArg2 = s2; callbackArg3 = s3; callbackArg4 = s4; }); mock.Object.Submit("blah1", "blah2", "blah3", "blah4"); Assert.Equal("blah1", callbackArg1); Assert.Equal("blah2", callbackArg2); Assert.Equal("blah3", callbackArg3); Assert.Equal("blah4", callbackArg4); } [Fact] public void CallbackCalledWithFiveArguments() { var mock = new Mock<IFoo>(); string callbackArg1 = null; string callbackArg2 = null; string callbackArg3 = null; string callbackArg4 = null; string callbackArg5 = null; mock.Setup(x => x.Submit(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())) .Callback((string s1, string s2, string s3, string s4, string s5) => { callbackArg1 = s1; callbackArg2 = s2; callbackArg3 = s3; callbackArg4 = s4; callbackArg5 = s5; }); mock.Object.Submit("blah1", "blah2", "blah3", "blah4", "blah5"); Assert.Equal("blah1", callbackArg1); Assert.Equal("blah2", callbackArg2); Assert.Equal("blah3", callbackArg3); Assert.Equal("blah4", callbackArg4); Assert.Equal("blah5", callbackArg5); } [Fact] public void CallbackCalledWithSixArguments() { var mock = new Mock<IFoo>(); string callbackArg1 = null; string callbackArg2 = null; string callbackArg3 = null; string callbackArg4 = null; string callbackArg5 = null; string callbackArg6 = null; mock.Setup(x => x.Submit(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())) .Callback((string s1, string s2, string s3, string s4, string s5, string s6) => { callbackArg1 = s1; callbackArg2 = s2; callbackArg3 = s3; callbackArg4 = s4; callbackArg5 = s5; callbackArg6 = s6; }); mock.Object.Submit("blah1", "blah2", "blah3", "blah4", "blah5", "blah6"); Assert.Equal("blah1", callbackArg1); Assert.Equal("blah2", callbackArg2); Assert.Equal("blah3", callbackArg3); Assert.Equal("blah4", callbackArg4); Assert.Equal("blah5", callbackArg5); Assert.Equal("blah6", callbackArg6); } [Fact] public void CallbackCalledWithSevenArguments() { var mock = new Mock<IFoo>(); string callbackArg1 = null; string callbackArg2 = null; string callbackArg3 = null; string callbackArg4 = null; string callbackArg5 = null; string callbackArg6 = null; string callbackArg7 = null; mock.Setup(x => x.Submit(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())) .Callback((string s1, string s2, string s3, string s4, string s5, string s6, string s7) => { callbackArg1 = s1; callbackArg2 = s2; callbackArg3 = s3; callbackArg4 = s4; callbackArg5 = s5; callbackArg6 = s6; callbackArg7 = s7; }); mock.Object.Submit("blah1", "blah2", "blah3", "blah4", "blah5", "blah6", "blah7"); Assert.Equal("blah1", callbackArg1); Assert.Equal("blah2", callbackArg2); Assert.Equal("blah3", callbackArg3); Assert.Equal("blah4", callbackArg4); Assert.Equal("blah5", callbackArg5); Assert.Equal("blah6", callbackArg6); Assert.Equal("blah7", callbackArg7); } [Fact] public void CallbackCalledWithEightArguments() { var mock = new Mock<IFoo>(); string callbackArg1 = null; string callbackArg2 = null; string callbackArg3 = null; string callbackArg4 = null; string callbackArg5 = null; string callbackArg6 = null; string callbackArg7 = null; string callbackArg8 = null; mock.Setup(x => x.Submit(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())) .Callback((string s1, string s2, string s3, string s4, string s5, string s6, string s7, string s8) => { callbackArg1 = s1; callbackArg2 = s2; callbackArg3 = s3; callbackArg4 = s4; callbackArg5 = s5; callbackArg6 = s6; callbackArg7 = s7; callbackArg8 = s8; }); mock.Object.Submit("blah1", "blah2", "blah3", "blah4", "blah5", "blah6", "blah7", "blah8"); Assert.Equal("blah1", callbackArg1); Assert.Equal("blah2", callbackArg2); Assert.Equal("blah3", callbackArg3); Assert.Equal("blah4", callbackArg4); Assert.Equal("blah5", callbackArg5); Assert.Equal("blah6", callbackArg6); Assert.Equal("blah7", callbackArg7); Assert.Equal("blah8", callbackArg8); } [Fact] public void CallbackCalledWithOneArgumentForNonVoidMethod() { var mock = new Mock<IFoo>(); string callbackArg1 = null; mock.Setup(x => x.Execute(It.IsAny<string>())) .Callback((string s1) => callbackArg1 = s1) .Returns("foo"); mock.Object.Execute("blah1"); Assert.Equal("blah1", callbackArg1); } [Fact] public void CallbackCalledWithTwoArgumentsForNonVoidMethod() { var mock = new Mock<IFoo>(); string callbackArg1 = null; string callbackArg2 = null; mock.Setup(x => x.Execute(It.IsAny<string>(), It.IsAny<string>())) .Callback((string s1, string s2) => { callbackArg1 = s1; callbackArg2 = s2; }) .Returns("foo"); mock.Object.Execute("blah1", "blah2"); Assert.Equal("blah1", callbackArg1); Assert.Equal("blah2", callbackArg2); } [Fact] public void CallbackCalledWithThreeArgumentsForNonVoidMethod() { var mock = new Mock<IFoo>(); string callbackArg1 = null; string callbackArg2 = null; string callbackArg3 = null; mock.Setup(x => x.Execute(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())) .Callback((string s1, string s2, string s3) => { callbackArg1 = s1; callbackArg2 = s2; callbackArg3 = s3; }) .Returns("foo"); mock.Object.Execute("blah1", "blah2", "blah3"); Assert.Equal("blah1", callbackArg1); Assert.Equal("blah2", callbackArg2); Assert.Equal("blah3", callbackArg3); } [Fact] public void CallbackCalledWithFourArgumentsForNonVoidMethod() { var mock = new Mock<IFoo>(); string callbackArg1 = null; string callbackArg2 = null; string callbackArg3 = null; string callbackArg4 = null; mock.Setup(x => x.Execute(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())) .Callback((string s1, string s2, string s3, string s4) => { callbackArg1 = s1; callbackArg2 = s2; callbackArg3 = s3; callbackArg4 = s4; }) .Returns("foo"); mock.Object.Execute("blah1", "blah2", "blah3", "blah4"); Assert.Equal("blah1", callbackArg1); Assert.Equal("blah2", callbackArg2); Assert.Equal("blah3", callbackArg3); Assert.Equal("blah4", callbackArg4); } [Fact] public void CallbackCalledWithFiveArgumentsForNonVoidMethod() { var mock = new Mock<IFoo>(); string callbackArg1 = null; string callbackArg2 = null; string callbackArg3 = null; string callbackArg4 = null; string callbackArg5 = null; mock.Setup(x => x.Execute(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())) .Callback((string s1, string s2, string s3, string s4, string s5) => { callbackArg1 = s1; callbackArg2 = s2; callbackArg3 = s3; callbackArg4 = s4; callbackArg5 = s5; }) .Returns("foo"); mock.Object.Execute("blah1", "blah2", "blah3", "blah4", "blah5"); Assert.Equal("blah1", callbackArg1); Assert.Equal("blah2", callbackArg2); Assert.Equal("blah3", callbackArg3); Assert.Equal("blah4", callbackArg4); Assert.Equal("blah5", callbackArg5); } [Fact] public void CallbackCalledWithSixArgumentsForNonVoidMethod() { var mock = new Mock<IFoo>(); string callbackArg1 = null; string callbackArg2 = null; string callbackArg3 = null; string callbackArg4 = null; string callbackArg5 = null; string callbackArg6 = null; mock.Setup(x => x.Execute(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())) .Callback((string s1, string s2, string s3, string s4, string s5, string s6) => { callbackArg1 = s1; callbackArg2 = s2; callbackArg3 = s3; callbackArg4 = s4; callbackArg5 = s5; callbackArg6 = s6; }) .Returns("foo"); mock.Object.Execute("blah1", "blah2", "blah3", "blah4", "blah5", "blah6"); Assert.Equal("blah1", callbackArg1); Assert.Equal("blah2", callbackArg2); Assert.Equal("blah3", callbackArg3); Assert.Equal("blah4", callbackArg4); Assert.Equal("blah5", callbackArg5); Assert.Equal("blah6", callbackArg6); } [Fact] public void CallbackCalledWithSevenArgumentsForNonVoidMethod() { var mock = new Mock<IFoo>(); string callbackArg1 = null; string callbackArg2 = null; string callbackArg3 = null; string callbackArg4 = null; string callbackArg5 = null; string callbackArg6 = null; string callbackArg7 = null; mock.Setup(x => x.Execute(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())) .Callback((string s1, string s2, string s3, string s4, string s5, string s6, string s7) => { callbackArg1 = s1; callbackArg2 = s2; callbackArg3 = s3; callbackArg4 = s4; callbackArg5 = s5; callbackArg6 = s6; callbackArg7 = s7; }) .Returns("foo"); mock.Object.Execute("blah1", "blah2", "blah3", "blah4", "blah5", "blah6", "blah7"); Assert.Equal("blah1", callbackArg1); Assert.Equal("blah2", callbackArg2); Assert.Equal("blah3", callbackArg3); Assert.Equal("blah4", callbackArg4); Assert.Equal("blah5", callbackArg5); Assert.Equal("blah6", callbackArg6); Assert.Equal("blah7", callbackArg7); } [Fact] public void CallbackCalledWithEightArgumentsForNonVoidMethod() { var mock = new Mock<IFoo>(); string callbackArg1 = null; string callbackArg2 = null; string callbackArg3 = null; string callbackArg4 = null; string callbackArg5 = null; string callbackArg6 = null; string callbackArg7 = null; string callbackArg8 = null; mock.Setup(x => x.Execute(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())) .Callback((string s1, string s2, string s3, string s4, string s5, string s6, string s7, string s8) => { callbackArg1 = s1; callbackArg2 = s2; callbackArg3 = s3; callbackArg4 = s4; callbackArg5 = s5; callbackArg6 = s6; callbackArg7 = s7; callbackArg8 = s8; }) .Returns("foo"); mock.Object.Execute("blah1", "blah2", "blah3", "blah4", "blah5", "blah6", "blah7", "blah8"); Assert.Equal("blah1", callbackArg1); Assert.Equal("blah2", callbackArg2); Assert.Equal("blah3", callbackArg3); Assert.Equal("blah4", callbackArg4); Assert.Equal("blah5", callbackArg5); Assert.Equal("blah6", callbackArg6); Assert.Equal("blah7", callbackArg7); Assert.Equal("blah8", callbackArg8); } [Fact] public void CallbackCalledAfterReturnsCall() { var mock = new Mock<IFoo>(); bool returnsCalled = false; bool beforeCalled = false; bool afterCalled = false; mock.Setup(foo => foo.Execute("ping")) .Callback(() => { Assert.False(returnsCalled); beforeCalled = true; }) .Returns(() => { returnsCalled = true; return "ack"; }) .Callback(() => { Assert.True(returnsCalled); afterCalled = true; }); Assert.Equal("ack", mock.Object.Execute("ping")); Assert.True(beforeCalled); Assert.True(afterCalled); } [Fact] public void CallbackCalledAfterReturnsCallWithArg() { var mock = new Mock<IFoo>(); bool returnsCalled = false; mock.Setup(foo => foo.Execute(It.IsAny<string>())) .Callback<string>(s => Assert.False(returnsCalled)) .Returns(() => { returnsCalled = true; return "ack"; }) .Callback<string>(s => Assert.True(returnsCalled)); mock.Object.Execute("ping"); Assert.True(returnsCalled); } [Fact] public void CallbackCanReceiveABaseClass() { var mock = new Mock<IInterface>(MockBehavior.Strict); mock.Setup(foo => foo.Method(It.IsAny<Derived>())).Callback<Derived>(TraceMe); mock.Object.Method(new Derived()); } [Fact] public void CallbackCanBeImplementedByExtensionMethod() { var mock = new Mock<IFoo>(); string receivedArgument = null; Action<string> innerCallback = param => { receivedArgument = param; }; // Delegate parameter currying can confuse Moq (used by extension delegates) Action<string> callback = innerCallback.ExtensionCallbackHelper; mock.Setup(x => x.Submit(It.IsAny<string>())).Callback(callback); mock.Object.Submit("blah"); Assert.Equal("blah extended", receivedArgument); } [Fact] public void CallbackWithRefParameterReceivesArguments() { var input = "input"; var received = default(string); var mock = new Mock<IFoo>(); mock.Setup(f => f.Execute(ref input)) .Callback(new ExecuteRHandler((ref string arg1) => { received = arg1; })); mock.Object.Execute(ref input); Assert.Equal("input", input); Assert.Equal(input, received); } [Fact] public void CallbackWithRefParameterCanModifyRefParameter() { var value = "input"; var mock = new Mock<IFoo>(); mock.Setup(f => f.Execute(ref value)) .Callback(new ExecuteRHandler((ref string arg1) => { arg1 = "output"; })); Assert.Equal("input", value); mock.Object.Execute(ref value); Assert.Equal("output", value); } [Fact] public void CallbackWithRefParameterCannotModifyNonRefParameter() { var _ = default(string); var value = "input"; var mock = new Mock<IFoo>(); mock.Setup(f => f.Execute(ref _, value)) .Callback(new ExecuteRVHandler((ref string arg1, string arg2) => { arg2 = "output"; })); Assert.Equal("input", value); mock.Object.Execute(ref _, value); Assert.Equal("input", value); } [Fact] public void CallbackWithIndexerSetter() { int x = default(int); int result = default(int); var mock = new Mock<IFoo>(); mock.SetupSet(f => f[10] = It.IsAny<int>()) .Callback(new Action<int, int>((x_, result_) => { x = x_; result = result_; })); mock.Object[10] = 5; Assert.Equal(10, x); Assert.Equal(5, result); } [Fact] public void CallbackWithMultipleArgumentIndexerSetterWithoutAny() { int x = default(int); int y = default(int); int result = default(int); var mock = new Mock<IFoo>(); mock.SetupSet(f => f[3, 13] = It.IsAny<int>()) .Callback(new Action<int, int, int>((x_, y_, result_) => { x = x_; y = y_; result = result_; })); mock.Object[3, 13] = 2; Assert.Equal(3, x); Assert.Equal(13, y); Assert.Equal(2, result); } public interface IInterface { void Method(Derived b); } public class Base { } public class Derived : Base { } private void TraceMe(Base b) { } public interface IFoo { void Submit(); void Submit(string command); string Submit(string arg1, string arg2); string Submit(string arg1, string arg2, string arg3); string Submit(string arg1, string arg2, string arg3, string arg4); void Submit(string arg1, string arg2, string arg3, string arg4, string arg5); void Submit(string arg1, string arg2, string arg3, string arg4, string arg5, string arg6); void Submit(string arg1, string arg2, string arg3, string arg4, string arg5, string arg6, string arg7); void Submit(string arg1, string arg2, string arg3, string arg4, string arg5, string arg6, string arg7, string arg8); string Execute(string command); string Execute(string arg1, string arg2); string Execute(string arg1, string arg2, string arg3); string Execute(string arg1, string arg2, string arg3, string arg4); string Execute(string arg1, string arg2, string arg3, string arg4, string arg5); string Execute(string arg1, string arg2, string arg3, string arg4, string arg5, string arg6); string Execute(string arg1, string arg2, string arg3, string arg4, string arg5, string arg6, string arg7); string Execute(string arg1, string arg2, string arg3, string arg4, string arg5, string arg6, string arg7, string arg8); string Execute(ref string arg1); string Execute(ref string arg1, string arg2); int Value { get; set; } int this[int x] { get; set; } int this[int x, int y] { get; set; } } public delegate void ExecuteRHandler(ref string arg1); public delegate void ExecuteRVHandler(ref string arg1, string arg2); } static class Extensions { public static void ExtensionCallbackHelper(this Action<string> inner, string param) { inner.Invoke(param + " extended"); } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using Avalonia.Controls; using Avalonia.Controls.Templates; using Avalonia.Diagnostics; using Avalonia.Layout; using Avalonia.Platform; using Avalonia.Rendering; using Avalonia.UnitTests; using Avalonia.VisualTree; using JetBrains.dotMemoryUnit; using Moq; using Xunit; using Xunit.Abstractions; namespace Avalonia.LeakTests { [DotMemoryUnit(FailIfRunWithoutSupport = false)] public class ControlTests { public ControlTests(ITestOutputHelper atr) { DotMemoryUnitTestOutput.SetOutputMethod(atr.WriteLine); } [Fact] public void Canvas_Is_Freed() { using (Start()) { Func<Window> run = () => { var window = new Window { Content = new Canvas() }; window.Show(); // Do a layout and make sure that Canvas gets added to visual tree. window.LayoutManager.ExecuteInitialLayoutPass(window); Assert.IsType<Canvas>(window.Presenter.Child); // Clear the content and ensure the Canvas is removed. window.Content = null; window.LayoutManager.ExecuteLayoutPass(); Assert.Null(window.Presenter.Child); return window; }; var result = run(); dotMemory.Check(memory => Assert.Equal(0, memory.GetObjects(where => where.Type.Is<Canvas>()).ObjectsCount)); } } [Fact] public void Named_Canvas_Is_Freed() { using (Start()) { Func<Window> run = () => { var window = new Window { Content = new Canvas { Name = "foo" } }; window.Show(); // Do a layout and make sure that Canvas gets added to visual tree. window.LayoutManager.ExecuteInitialLayoutPass(window); Assert.IsType<Canvas>(window.Find<Canvas>("foo")); Assert.IsType<Canvas>(window.Presenter.Child); // Clear the content and ensure the Canvas is removed. window.Content = null; window.LayoutManager.ExecuteLayoutPass(); Assert.Null(window.Presenter.Child); return window; }; var result = run(); dotMemory.Check(memory => Assert.Equal(0, memory.GetObjects(where => where.Type.Is<Canvas>()).ObjectsCount)); } } [Fact] public void ScrollViewer_With_Content_Is_Freed() { using (Start()) { Func<Window> run = () => { var window = new Window { Content = new ScrollViewer { Content = new Canvas() } }; window.Show(); // Do a layout and make sure that ScrollViewer gets added to visual tree and its // template applied. window.LayoutManager.ExecuteInitialLayoutPass(window); Assert.IsType<ScrollViewer>(window.Presenter.Child); Assert.IsType<Canvas>(((ScrollViewer)window.Presenter.Child).Presenter.Child); // Clear the content and ensure the ScrollViewer is removed. window.Content = null; window.LayoutManager.ExecuteLayoutPass(); Assert.Null(window.Presenter.Child); return window; }; var result = run(); dotMemory.Check(memory => Assert.Equal(0, memory.GetObjects(where => where.Type.Is<TextBox>()).ObjectsCount)); dotMemory.Check(memory => Assert.Equal(0, memory.GetObjects(where => where.Type.Is<Canvas>()).ObjectsCount)); } } [Fact] public void TextBox_Is_Freed() { using (Start()) { Func<Window> run = () => { var window = new Window { Content = new TextBox() }; window.Show(); // Do a layout and make sure that TextBox gets added to visual tree and its // template applied. window.LayoutManager.ExecuteInitialLayoutPass(window); Assert.IsType<TextBox>(window.Presenter.Child); Assert.NotEmpty(window.Presenter.Child.GetVisualChildren()); // Clear the content and ensure the TextBox is removed. window.Content = null; window.LayoutManager.ExecuteLayoutPass(); Assert.Null(window.Presenter.Child); return window; }; var result = run(); dotMemory.Check(memory => Assert.Equal(0, memory.GetObjects(where => where.Type.Is<TextBox>()).ObjectsCount)); } } [Fact] public void TextBox_With_Xaml_Binding_Is_Freed() { using (Start()) { Func<Window> run = () => { var window = new Window { DataContext = new Node { Name = "foo" }, Content = new TextBox() }; var binding = new Avalonia.Data.Binding { Path = "Name" }; var textBox = (TextBox)window.Content; textBox.Bind(TextBox.TextProperty, binding); window.Show(); // Do a layout and make sure that TextBox gets added to visual tree and its // Text property set. window.LayoutManager.ExecuteInitialLayoutPass(window); Assert.IsType<TextBox>(window.Presenter.Child); Assert.Equal("foo", ((TextBox)window.Presenter.Child).Text); // Clear the content and DataContext and ensure the TextBox is removed. window.Content = null; window.DataContext = null; window.LayoutManager.ExecuteLayoutPass(); Assert.Null(window.Presenter.Child); return window; }; var result = run(); dotMemory.Check(memory => Assert.Equal(0, memory.GetObjects(where => where.Type.Is<TextBox>()).ObjectsCount)); dotMemory.Check(memory => Assert.Equal(0, memory.GetObjects(where => where.Type.Is<Node>()).ObjectsCount)); } } [Fact] public void TextBox_Class_Listeners_Are_Freed() { using (Start()) { TextBox textBox; var window = new Window { Content = textBox = new TextBox() }; window.Show(); // Do a layout and make sure that TextBox gets added to visual tree and its // template applied. window.LayoutManager.ExecuteInitialLayoutPass(window); Assert.Same(textBox, window.Presenter.Child); // Get the border from the TextBox template. var border = textBox.GetTemplateChildren().FirstOrDefault(x => x.Name == "border"); // The TextBox should have subscriptions to its Classes collection from the // default theme. Assert.NotEmpty(((INotifyCollectionChangedDebug)textBox.Classes).GetCollectionChangedSubscribers()); // Clear the content and ensure the TextBox is removed. window.Content = null; window.LayoutManager.ExecuteLayoutPass(); Assert.Null(window.Presenter.Child); // Check that the TextBox has no subscriptions to its Classes collection. Assert.Null(((INotifyCollectionChangedDebug)textBox.Classes).GetCollectionChangedSubscribers()); } } [Fact] public void TreeView_Is_Freed() { using (Start()) { Func<Window> run = () => { var nodes = new[] { new Node { Children = new[] { new Node() }, } }; TreeView target; var window = new Window { Content = target = new TreeView { DataTemplates = { new FuncTreeDataTemplate<Node>( x => new TextBlock { Text = x.Name }, x => x.Children) }, Items = nodes } }; window.Show(); // Do a layout and make sure that TreeViewItems get realized. window.LayoutManager.ExecuteInitialLayoutPass(window); Assert.Single(target.ItemContainerGenerator.Containers); // Clear the content and ensure the TreeView is removed. window.Content = null; window.LayoutManager.ExecuteLayoutPass(); Assert.Null(window.Presenter.Child); return window; }; var result = run(); dotMemory.Check(memory => Assert.Equal(0, memory.GetObjects(where => where.Type.Is<TreeView>()).ObjectsCount)); } } [Fact] public void RendererIsDisposed() { using (Start()) { var renderer = new Mock<IRenderer>(); renderer.Setup(x => x.Dispose()); var impl = new Mock<IWindowImpl>(); impl.SetupGet(x => x.Scaling).Returns(1); impl.SetupProperty(x => x.Closed); impl.Setup(x => x.CreateRenderer(It.IsAny<IRenderRoot>())).Returns(renderer.Object); impl.Setup(x => x.Dispose()).Callback(() => impl.Object.Closed()); AvaloniaLocator.CurrentMutable.Bind<IWindowingPlatform>() .ToConstant(new MockWindowingPlatform(() => impl.Object)); var window = new Window() { Content = new Button() }; window.Show(); window.Close(); renderer.Verify(r => r.Dispose()); } } private IDisposable Start() { return UnitTestApplication.Start(TestServices.StyledWindow); } private class Node { public string Name { get; set; } public IEnumerable<Node> Children { get; set; } } private class NullRenderer : IRenderer { public bool DrawFps { get; set; } public bool DrawDirtyRects { get; set; } public void AddDirty(IVisual visual) { } public void Dispose() { } public IEnumerable<IVisual> HitTest(Point p, IVisual root, Func<IVisual, bool> filter) => null; public void Paint(Rect rect) { } public void Resized(Size size) { } public void Start() { } public void Stop() { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.Xml.Serialization { using System; using System.Collections; using System.Diagnostics; using System.Reflection; using System.Reflection.Emit; using System.Text.RegularExpressions; internal class SourceInfo { //a[ia] //((global::Microsoft.Xml.Serialization.XmlSerializerNamespaces)p[0]) private static Regex s_regex = new Regex("([(][(](?<t>[^)]+)[)])?(?<a>[^[]+)[[](?<ia>.+)[]][)]?"); //((global::Microsoft.CFx.Test.Common.TypeLibrary.IXSType_9)o), @"IXSType_9", @"", true, true); private static Regex s_regex2 = new Regex("[(][(](?<cast>[^)]+)[)](?<arg>[^)]+)[)]"); private static readonly Lazy<MethodInfo> s_iListGetItemMethod = new Lazy<MethodInfo>( () => { return typeof(IList).GetMethod( "get_Item", CodeGenerator.InstanceBindingFlags, null, new Type[] { typeof(Int32) }, null ); }); public string Source; public readonly string Arg; public readonly MemberInfo MemberInfo; public readonly Type Type; public readonly CodeGenerator ILG; public SourceInfo(string source, string arg, MemberInfo memberInfo, Type type, CodeGenerator ilg) { this.Source = source; this.Arg = arg ?? source; this.MemberInfo = memberInfo; this.Type = type; this.ILG = ilg; } public SourceInfo CastTo(TypeDesc td) { return new SourceInfo("((" + td.CSharpName + ")" + Source + ")", Arg, MemberInfo, td.Type, ILG); } public void LoadAddress(Type elementType) { InternalLoad(elementType, asAddress: true); } public void Load(Type elementType) { InternalLoad(elementType); } private void InternalLoad(Type elementType, bool asAddress = false) { Match match = s_regex.Match(Arg); if (match.Success) { object varA = ILG.GetVariable(match.Groups["a"].Value); Type varType = ILG.GetVariableType(varA); object varIA = ILG.GetVariable(match.Groups["ia"].Value); if (varType.IsArray) { ILG.Load(varA); ILG.Load(varIA); Type eType = varType.GetElementType(); if (CodeGenerator.IsNullableGenericType(eType)) { ILG.Ldelema(eType); ConvertNullableValue(eType, elementType); } else { if (eType.GetTypeInfo().IsValueType) { ILG.Ldelema(eType); if (!asAddress) { ILG.Ldobj(eType); } } else ILG.Ldelem(eType); if (elementType != null) ILG.ConvertValue(eType, elementType); } } else { ILG.Load(varA); ILG.Load(varIA); MethodInfo get_Item = varType.GetMethod( "get_Item", CodeGenerator.InstanceBindingFlags, null, new Type[] { typeof(Int32) }, null ); if (get_Item == null && typeof(IList).IsAssignableFrom(varType)) { get_Item = s_iListGetItemMethod.Value; } Debug.Assert(get_Item != null); ILG.Call(get_Item); Type eType = get_Item.ReturnType; if (CodeGenerator.IsNullableGenericType(eType)) { LocalBuilder localTmp = ILG.GetTempLocal(eType); ILG.Stloc(localTmp); ILG.Ldloca(localTmp); ConvertNullableValue(eType, elementType); } else if ((elementType != null) && !(eType.IsAssignableFrom(elementType) || elementType.IsAssignableFrom(eType))) { throw new CodeGeneratorConversionException(eType, elementType, asAddress, "IsNotAssignableFrom"); } else { Convert(eType, elementType, asAddress); } } } else if (Source == "null") { ILG.Load(null); } else { object var; Type varType; if (Arg.StartsWith("o.@", StringComparison.Ordinal) || MemberInfo != null) { var = ILG.GetVariable(Arg.StartsWith("o.@", StringComparison.Ordinal) ? "o" : Arg); varType = ILG.GetVariableType(var); if (varType.GetTypeInfo().IsValueType) ILG.LoadAddress(var); else ILG.Load(var); } else { var = ILG.GetVariable(Arg); varType = ILG.GetVariableType(var); if (CodeGenerator.IsNullableGenericType(varType) && varType.GetGenericArguments()[0] == elementType) { ILG.LoadAddress(var); ConvertNullableValue(varType, elementType); } else { if (asAddress) ILG.LoadAddress(var); else ILG.Load(var); } } if (MemberInfo != null) { Type memberType = (MemberInfo is FieldInfo) ? ((FieldInfo)MemberInfo).FieldType : ((PropertyInfo)MemberInfo).PropertyType; if (CodeGenerator.IsNullableGenericType(memberType)) { ILG.LoadMemberAddress(MemberInfo); ConvertNullableValue(memberType, elementType); } else { ILG.LoadMember(MemberInfo); Convert(memberType, elementType, asAddress); } } else { match = s_regex2.Match(Source); if (match.Success) { Debug.Assert(match.Groups["arg"].Value == Arg); Debug.Assert(match.Groups["cast"].Value == CodeIdentifier.GetCSharpName(Type)); if (asAddress) ILG.ConvertAddress(varType, Type); else ILG.ConvertValue(varType, Type); varType = Type; } Convert(varType, elementType, asAddress); } } } private void Convert(Type sourceType, Type targetType, bool asAddress) { if (targetType != null) { if (asAddress) ILG.ConvertAddress(sourceType, targetType); else ILG.ConvertValue(sourceType, targetType); } } private void ConvertNullableValue(Type nullableType, Type targetType) { System.Diagnostics.Debug.Assert(targetType == nullableType || targetType.IsAssignableFrom(nullableType.GetGenericArguments()[0])); if (targetType != nullableType) { MethodInfo Nullable_get_Value = nullableType.GetMethod( "get_Value", CodeGenerator.InstanceBindingFlags, null, CodeGenerator.EmptyTypeArray, null ); ILG.Call(Nullable_get_Value); if (targetType != null) { ILG.ConvertValue(Nullable_get_Value.ReturnType, targetType); } } } public static implicit operator string(SourceInfo source) { return source.Source; } public static bool operator !=(SourceInfo a, SourceInfo b) { if ((object)a != null) return !a.Equals(b); return (object)b != null; } public static bool operator ==(SourceInfo a, SourceInfo b) { if ((object)a != null) return a.Equals(b); return (object)b == null; } public override bool Equals(object obj) { if (obj == null) return Source == null; SourceInfo info = obj as SourceInfo; if (info != null) return Source == info.Source; return false; } public override int GetHashCode() { return (Source == null) ? 0 : Source.GetHashCode(); } } }
#region License //----------------------------------------------------------------------- // <copyright> // The MIT License (MIT) // // Copyright (c) 2014 Kirk S Woll // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // </copyright> //----------------------------------------------------------------------- #endregion using System.Collections.Generic; using System.Runtime.WootzJs; using System.Text; namespace System { /// <summary> /// Equivalent to the Number type in Javascript. /// </summary> [Js(Name = "Number", BuiltIn = true, BaseType = typeof(Object))] public abstract class Number : IComparable { public const int MAX_VALUE = 0; public const int MIN_VALUE = 0; public const int NaN = 0; public const int NEGATIVE_INFINITY = 0; public const int POSITIVE_INFINITY = 0; [Js(Name = "GetType")] public new Type GetType() { return base.GetType(); } public string Format(string format) { return null; } public static bool IsFinite(Number n) { return false; } public static bool IsNaN(Number n) { return false; } public string LocaleFormat(string format) { return null; } public static Number Parse(string s) { return null; } public static double ParseDouble(string s) { return 0.0; } public static float ParseFloat(string s) { return 0f; } public static int ParseInt(float f) { return 0; } public static int ParseInt(double d) { return 0; } public static int ParseInt(string s) { return 0; } public static int ParseInt(string s, int radix) { return 0; } /// <summary> /// Returns a string containing the number represented in exponential notation. /// </summary> /// <returns>The exponential representation</returns> public string ToExponential() { return null; } /// <summary> /// Returns a string containing the number represented in exponential notation. /// </summary> /// <param name="fractionDigits">The number of digits after the decimal point (0 - 20)</param> /// <returns>The exponential representation</returns> public string ToExponential(int fractionDigits) { return null; } /// <summary> /// Returns a string representing the number in fixed-point notation. /// </summary> /// <returns>The fixed-point notation</returns> public string ToFixed() { return null; } /// <summary> /// Returns a string representing the number in fixed-point notation. /// </summary> /// <param name="fractionDigits">The number of digits after the decimal point from 0 - 20</param> /// <returns>The fixed-point notation</returns> public string ToFixed(int fractionDigits) { return null; } /// <summary> /// Returns a string containing the number represented either in exponential or /// fixed-point notation with a specified number of digits. /// </summary> /// <returns>The string representation of the value.</returns> public string ToPrecision() { return null; } /// <summary> /// Returns a string containing the number represented either in exponential or /// fixed-point notation with a specified number of digits. /// </summary> /// <param name="precision">The number of significant digits (in the range 1 to 21)</param> /// <returns>The string representation of the value.</returns> public string ToPrecision(int precision) { return null; } /// <summary> /// Converts the value to its string representation. /// </summary> /// <param name="radix">The radix used in the conversion (eg. 10 for decimal, 16 for hexadecimal)</param> /// <returns>The string representation of the value.</returns> public string ToString(int radix) { return null; } enum DecimalState { Before, On, After } public string ToString(string format) { if (string.IsNullOrEmpty(format)) return ToString(); Number value = this; if (format == "P" || format == "p") { value = value.As<double>() * 100; format = "0.00%"; } else if (format[0] == 'X') { var radix = 16; var remainingFormat = format.Substring(1); var s = this.As<JsNumber>().toString(radix); if (remainingFormat.Length > 0) { var minimumDigits = int.Parse(remainingFormat); while (s.length < minimumDigits.As<JsNumber>()) s = "0" + s; } return s; } var parts = value.ToString().Split('.'); var leftOfDecimal = parts[0]; var rightOfDecimal = parts.Length > 1 ? parts[1] : ""; var leftDigits = new Queue<char>(leftOfDecimal); var rightDigits = new Queue<char>(rightOfDecimal); var result = new StringBuilder(); if (value.As<JsNumber>() < 0) result.Append("-"); var state = DecimalState.Before; foreach (var token in format) { switch (token) { case '0': case '#': switch (state) { case DecimalState.Before: if (leftDigits.Count > 0) result.Append(leftDigits.Dequeue()); else if (token == '0') result.Append('0'); break; case DecimalState.On: state = DecimalState.After; if ((rightDigits.Count == 0 && token == '0') || rightDigits.Count > 0) result.Append('.'); if (rightDigits.Count == 0 && token == '0') result.Append('0'); else if (rightDigits.Count > 0) result.Append(rightDigits.Dequeue()); break; case DecimalState.After: if (rightDigits.Count == 0 && token == '0') result.Append('0'); else if (rightDigits.Count > 0) result.Append(rightDigits.Dequeue()); break; } break; case '.': state = DecimalState.On; while (leftDigits.Count > 0) result.Append(leftDigits.Dequeue()); break; } } return result.ToString(); } public int CompareTo(object obj) { return (this.As<JsNumber>() - obj.As<JsNumber>()).As<int>(); } // ReSharper disable once RedundantOverridenMember /* public override string GetStringHashCode() { // We need to override it to make sure this method gets added to the String prototype. return base.GetStringHashCode(); } */ // ReSharper disable once RedundantOverridenMember public override bool Equals(object obj) { return base.Equals(obj); } public override int GetHashCode() { return this.As<int>(); } public override string ToString() { return this.As<JsObject>().toString(); } } }
// // 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.Iscsi { using System; using System.Collections.Generic; using System.IO; using System.Net.Sockets; using System.Reflection; internal enum Digest { [ProtocolKeyValue("None")] None, [ProtocolKeyValue("CRC32C")] Crc32c } internal sealed class Connection : IDisposable { #region Parameters private const string InitiatorNameParameter = "InitiatorName"; private const string SessionTypeParameter = "SessionType"; private const string AuthMethodParameter = "AuthMethod"; private const string HeaderDigestParameter = "HeaderDigest"; private const string DataDigestParameter = "DataDigest"; private const string MaxRecvDataSegmentLengthParameter = "MaxRecvDataSegmentLength"; private const string DefaultTime2WaitParameter = "DefaultTime2Wait"; private const string DefaultTime2RetainParameter = "DefaultTime2Retain"; private const string SendTargetsParameter = "SendTargets"; private const string TargetNameParameter = "TargetName"; private const string TargetAddressParameter = "TargetAddress"; private const string NoneValue = "None"; private const string ChapValue = "CHAP"; #endregion private Session _session; private Stream _stream; private Authenticator[] _authenticators; private ushort _id; private uint _expectedStatusSequenceNumber = 1; private LoginStages _loginStage = LoginStages.SecurityNegotiation; /// <summary> /// The set of all 'parameters' we've negotiated. /// </summary> private Dictionary<string, string> _negotiatedParameters; public Connection(Session session, TargetAddress address, Authenticator[] authenticators) { _session = session; _authenticators = authenticators; TcpClient client = new TcpClient(address.NetworkAddress, address.NetworkPort); client.NoDelay = true; _stream = client.GetStream(); _id = session.NextConnectionId(); // Default negotiated values HeaderDigest = Digest.None; DataDigest = Digest.None; MaxInitiatorTransmitDataSegmentLength = 131072; MaxTargetReceiveDataSegmentLength = 8192; _negotiatedParameters = new Dictionary<string, string>(); NegotiateSecurity(); NegotiateFeatures(); } #region Protocol Features [ProtocolKey("HeaderDigest", "None", KeyUsagePhase.OperationalNegotiation, KeySender.Both, KeyType.Negotiated, UsedForDiscovery = true)] public Digest HeaderDigest { get; set; } [ProtocolKey("DataDigest", "None", KeyUsagePhase.OperationalNegotiation, KeySender.Both, KeyType.Negotiated, UsedForDiscovery = true)] public Digest DataDigest { get; set; } [ProtocolKey("MaxRecvDataSegmentLength", "8192", KeyUsagePhase.OperationalNegotiation, KeySender.Initiator, KeyType.Declarative)] internal int MaxInitiatorTransmitDataSegmentLength { get; set; } [ProtocolKey("MaxRecvDataSegmentLength", "8192", KeyUsagePhase.OperationalNegotiation, KeySender.Target, KeyType.Declarative)] internal int MaxTargetReceiveDataSegmentLength { get; set; } #endregion internal ushort Id { get { return _id; } } internal Session Session { get { return _session; } } internal LoginStages CurrentLoginStage { get { return _loginStage; } } internal LoginStages NextLoginStage { get { switch (_loginStage) { case LoginStages.SecurityNegotiation: return LoginStages.LoginOperationalNegotiation; case LoginStages.LoginOperationalNegotiation: return LoginStages.FullFeaturePhase; default: return LoginStages.FullFeaturePhase; } } } internal uint ExpectedStatusSequenceNumber { get { return _expectedStatusSequenceNumber; } } public void Dispose() { Close(LogoutReason.CloseConnection); } public void Close(LogoutReason reason) { LogoutRequest req = new LogoutRequest(this); byte[] packet = req.GetBytes(reason); _stream.Write(packet, 0, packet.Length); _stream.Flush(); ProtocolDataUnit pdu = ReadPdu(); LogoutResponse resp = ParseResponse<LogoutResponse>(pdu); if (resp.Response != LogoutResponseCode.ClosedSuccessfully) { throw new InvalidProtocolException("Target indicated failure during logout: " + resp.Response); } _stream.Close(); } /// <summary> /// Sends an SCSI command (aka task) to a LUN via the connected target. /// </summary> /// <param name="cmd">The command to send</param> /// <param name="outBuffer">The data to send with the command</param> /// <param name="outBufferOffset">The offset of the first byte to send</param> /// <param name="outBufferCount">The number of bytes to send, if any</param> /// <param name="inBuffer">The buffer to fill with returned data</param> /// <param name="inBufferOffset">The first byte to fill with returned data</param> /// <param name="inBufferMax">The maximum amount of data to receive</param> /// <returns>The number of bytes received</returns> public int Send(ScsiCommand cmd, byte[] outBuffer, int outBufferOffset, int outBufferCount, byte[] inBuffer, int inBufferOffset, int inBufferMax) { CommandRequest req = new CommandRequest(this, cmd.TargetLun); int toSend = Math.Min(Math.Min(outBufferCount, _session.ImmediateData ? _session.FirstBurstLength : 0), MaxTargetReceiveDataSegmentLength); byte[] packet = req.GetBytes(cmd, outBuffer, outBufferOffset, toSend, true, inBufferMax != 0, outBufferCount != 0, (uint)(outBufferCount != 0 ? outBufferCount : inBufferMax)); _stream.Write(packet, 0, packet.Length); _stream.Flush(); int numApproved = 0; int numSent = toSend; int pktsSent = 0; while (numSent < outBufferCount) { ProtocolDataUnit pdu = ReadPdu(); ReadyToTransferPacket resp = ParseResponse<ReadyToTransferPacket>(pdu); numApproved = (int)resp.DesiredTransferLength; uint targetTransferTag = resp.TargetTransferTag; while (numApproved > 0) { toSend = Math.Min(Math.Min(outBufferCount - numSent, numApproved), MaxTargetReceiveDataSegmentLength); DataOutPacket pkt = new DataOutPacket(this, cmd.TargetLun); packet = pkt.GetBytes(outBuffer, outBufferOffset + numSent, toSend, toSend == numApproved, pktsSent++, (uint)numSent, targetTransferTag); _stream.Write(packet, 0, packet.Length); _stream.Flush(); numApproved -= toSend; numSent += toSend; } } bool isFinal = false; int numRead = 0; while (!isFinal) { ProtocolDataUnit pdu = ReadPdu(); if (pdu.OpCode == OpCode.ScsiResponse) { Response resp = ParseResponse<Response>(pdu); if (resp.StatusPresent && resp.Status == ScsiStatus.CheckCondition) { ushort senseLength = Utilities.ToUInt16BigEndian(pdu.ContentData, 0); byte[] senseData = new byte[senseLength]; Array.Copy(pdu.ContentData, 2, senseData, 0, senseLength); throw new ScsiCommandException(resp.Status, "Target indicated SCSI failure", senseData); } else if (resp.StatusPresent && resp.Status != ScsiStatus.Good) { throw new ScsiCommandException(resp.Status, "Target indicated SCSI failure"); } isFinal = resp.Header.FinalPdu; } else if (pdu.OpCode == OpCode.ScsiDataIn) { DataInPacket resp = ParseResponse<DataInPacket>(pdu); if (resp.StatusPresent && resp.Status != ScsiStatus.Good) { throw new ScsiCommandException(resp.Status, "Target indicated SCSI failure"); } if (resp.ReadData != null) { Array.Copy(resp.ReadData, 0, inBuffer, inBufferOffset + resp.BufferOffset, resp.ReadData.Length); numRead += resp.ReadData.Length; } isFinal = resp.Header.FinalPdu; } } _session.NextTaskTag(); _session.NextCommandSequenceNumber(); return numRead; } public T Send<T>(ScsiCommand cmd, byte[] buffer, int offset, int count, int expected) where T : ScsiResponse, new() { byte[] tempBuffer = new byte[expected]; int numRead = Send(cmd, buffer, offset, count, tempBuffer, 0, expected); T result = new T(); result.ReadFrom(tempBuffer, 0, numRead); return result; } public TargetInfo[] EnumerateTargets() { TextBuffer parameters = new TextBuffer(); parameters.Add(SendTargetsParameter, "All"); byte[] paramBuffer = new byte[parameters.Size]; parameters.WriteTo(paramBuffer, 0); TextRequest req = new TextRequest(this); byte[] packet = req.GetBytes(0, paramBuffer, 0, paramBuffer.Length, true); _stream.Write(packet, 0, packet.Length); _stream.Flush(); ProtocolDataUnit pdu = ReadPdu(); TextResponse resp = ParseResponse<TextResponse>(pdu); TextBuffer buffer = new TextBuffer(); if (resp.TextData != null) { buffer.ReadFrom(resp.TextData, 0, resp.TextData.Length); } List<TargetInfo> targets = new List<TargetInfo>(); string currentTarget = null; List<TargetAddress> currentAddresses = null; foreach (var line in buffer.Lines) { if (currentTarget == null) { if (line.Key != TargetNameParameter) { throw new InvalidProtocolException("Unexpected response parameter " + line.Key + " expected " + TargetNameParameter); } currentTarget = line.Value; currentAddresses = new List<TargetAddress>(); } else if (line.Key == TargetNameParameter) { targets.Add(new TargetInfo(currentTarget, currentAddresses.ToArray())); currentTarget = line.Value; currentAddresses.Clear(); } else if (line.Key == TargetAddressParameter) { currentAddresses.Add(TargetAddress.Parse(line.Value)); } } if (currentTarget != null) { targets.Add(new TargetInfo(currentTarget, currentAddresses.ToArray())); } return targets.ToArray(); } internal void SeenStatusSequenceNumber(uint number) { if (number != 0 && number != _expectedStatusSequenceNumber) { throw new InvalidProtocolException("Unexpected status sequence number " + number + ", expected " + _expectedStatusSequenceNumber); } _expectedStatusSequenceNumber = number + 1; } private void NegotiateSecurity() { _loginStage = LoginStages.SecurityNegotiation; // // Establish the contents of the request // TextBuffer parameters = new TextBuffer(); GetParametersToNegotiate(parameters, KeyUsagePhase.SecurityNegotiation, _session.SessionType); _session.GetParametersToNegotiate(parameters, KeyUsagePhase.SecurityNegotiation); string authParam = _authenticators[0].Identifier; for (int i = 1; i < _authenticators.Length; ++i) { authParam += "," + _authenticators[i].Identifier; } parameters.Add(AuthMethodParameter, authParam); // // Send the request... // byte[] paramBuffer = new byte[parameters.Size]; parameters.WriteTo(paramBuffer, 0); LoginRequest req = new LoginRequest(this); byte[] packet = req.GetBytes(paramBuffer, 0, paramBuffer.Length, true); _stream.Write(packet, 0, packet.Length); _stream.Flush(); // // Read the response... // TextBuffer settings = new TextBuffer(); ProtocolDataUnit pdu = ReadPdu(); LoginResponse resp = ParseResponse<LoginResponse>(pdu); if (resp.StatusCode != LoginStatusCode.Success) { throw new LoginException("iSCSI Target indicated login failure: " + resp.StatusCode); } if (resp.Continue) { MemoryStream ms = new MemoryStream(); ms.Write(resp.TextData, 0, resp.TextData.Length); while (resp.Continue) { pdu = ReadPdu(); resp = ParseResponse<LoginResponse>(pdu); ms.Write(resp.TextData, 0, resp.TextData.Length); } settings.ReadFrom(ms.GetBuffer(), 0, (int)ms.Length); } else if (resp.TextData != null) { settings.ReadFrom(resp.TextData, 0, resp.TextData.Length); } Authenticator authenticator = null; for (int i = 0; i < _authenticators.Length; ++i) { if (settings[AuthMethodParameter] == _authenticators[i].Identifier) { authenticator = _authenticators[i]; break; } } settings.Remove(AuthMethodParameter); settings.Remove("TargetPortalGroupTag"); if (authenticator == null) { throw new LoginException("iSCSI Target specified an unsupported authentication method: " + settings[AuthMethodParameter]); } parameters = new TextBuffer(); ConsumeParameters(settings, parameters); while (!resp.Transit) { // // Send the request... // parameters = new TextBuffer(); authenticator.GetParameters(parameters); paramBuffer = new byte[parameters.Size]; parameters.WriteTo(paramBuffer, 0); req = new LoginRequest(this); packet = req.GetBytes(paramBuffer, 0, paramBuffer.Length, true); _stream.Write(packet, 0, packet.Length); _stream.Flush(); // // Read the response... // settings = new TextBuffer(); pdu = ReadPdu(); resp = ParseResponse<LoginResponse>(pdu); if (resp.StatusCode != LoginStatusCode.Success) { throw new LoginException("iSCSI Target indicated login failure: " + resp.StatusCode); } if (resp.TextData != null && resp.TextData.Length != 0) { if (resp.Continue) { MemoryStream ms = new MemoryStream(); ms.Write(resp.TextData, 0, resp.TextData.Length); while (resp.Continue) { pdu = ReadPdu(); resp = ParseResponse<LoginResponse>(pdu); ms.Write(resp.TextData, 0, resp.TextData.Length); } settings.ReadFrom(ms.GetBuffer(), 0, (int)ms.Length); } else { settings.ReadFrom(resp.TextData, 0, resp.TextData.Length); } authenticator.SetParameters(settings); } } if (resp.NextStage != NextLoginStage) { throw new LoginException("iSCSI Target wants to transition to a different login stage: " + resp.NextStage + " (expected: " + NextLoginStage + ")"); } _loginStage = resp.NextStage; } private void NegotiateFeatures() { // // Send the request... // TextBuffer parameters = new TextBuffer(); GetParametersToNegotiate(parameters, KeyUsagePhase.OperationalNegotiation, _session.SessionType); _session.GetParametersToNegotiate(parameters, KeyUsagePhase.OperationalNegotiation); byte[] paramBuffer = new byte[parameters.Size]; parameters.WriteTo(paramBuffer, 0); LoginRequest req = new LoginRequest(this); byte[] packet = req.GetBytes(paramBuffer, 0, paramBuffer.Length, true); _stream.Write(packet, 0, packet.Length); _stream.Flush(); // // Read the response... // TextBuffer settings = new TextBuffer(); ProtocolDataUnit pdu = ReadPdu(); LoginResponse resp = ParseResponse<LoginResponse>(pdu); if (resp.StatusCode != LoginStatusCode.Success) { throw new LoginException("iSCSI Target indicated login failure: " + resp.StatusCode); } if (resp.Continue) { MemoryStream ms = new MemoryStream(); ms.Write(resp.TextData, 0, resp.TextData.Length); while (resp.Continue) { pdu = ReadPdu(); resp = ParseResponse<LoginResponse>(pdu); ms.Write(resp.TextData, 0, resp.TextData.Length); } settings.ReadFrom(ms.GetBuffer(), 0, (int)ms.Length); } else if (resp.TextData != null) { settings.ReadFrom(resp.TextData, 0, resp.TextData.Length); } parameters = new TextBuffer(); ConsumeParameters(settings, parameters); while (!resp.Transit || parameters.Count != 0) { paramBuffer = new byte[parameters.Size]; parameters.WriteTo(paramBuffer, 0); req = new LoginRequest(this); packet = req.GetBytes(paramBuffer, 0, paramBuffer.Length, true); _stream.Write(packet, 0, packet.Length); _stream.Flush(); // // Read the response... // settings = new TextBuffer(); pdu = ReadPdu(); resp = ParseResponse<LoginResponse>(pdu); if (resp.StatusCode != LoginStatusCode.Success) { throw new LoginException("iSCSI Target indicated login failure: " + resp.StatusCode); } parameters = new TextBuffer(); if (resp.TextData != null) { if (resp.Continue) { MemoryStream ms = new MemoryStream(); ms.Write(resp.TextData, 0, resp.TextData.Length); while (resp.Continue) { pdu = ReadPdu(); resp = ParseResponse<LoginResponse>(pdu); ms.Write(resp.TextData, 0, resp.TextData.Length); } settings.ReadFrom(ms.GetBuffer(), 0, (int)ms.Length); } else { settings.ReadFrom(resp.TextData, 0, resp.TextData.Length); } ConsumeParameters(settings, parameters); } } if (resp.NextStage != NextLoginStage) { throw new LoginException("iSCSI Target wants to transition to a different login stage: " + resp.NextStage + " (expected: " + NextLoginStage + ")"); } _loginStage = resp.NextStage; } private ProtocolDataUnit ReadPdu() { ProtocolDataUnit pdu = ProtocolDataUnit.ReadFrom(_stream, HeaderDigest != Digest.None, DataDigest != Digest.None); if (pdu.OpCode == OpCode.Reject) { RejectPacket pkt = new RejectPacket(); pkt.Parse(pdu); throw new IscsiException("Target sent reject packet, reason " + pkt.Reason); } return pdu; } private void GetParametersToNegotiate(TextBuffer parameters, KeyUsagePhase phase, SessionType sessionType) { PropertyInfo[] properties = GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach (var propInfo in properties) { ProtocolKeyAttribute attr = (ProtocolKeyAttribute)Attribute.GetCustomAttribute(propInfo, typeof(ProtocolKeyAttribute)); if (attr != null) { object value = propInfo.GetGetMethod(true).Invoke(this, null); if (attr.ShouldTransmit(value, propInfo.PropertyType, phase, sessionType == SessionType.Discovery)) { parameters.Add(attr.Name, ProtocolKeyAttribute.GetValueAsString(value, propInfo.PropertyType)); _negotiatedParameters.Add(attr.Name, string.Empty); } } } } private void ConsumeParameters(TextBuffer inParameters, TextBuffer outParameters) { PropertyInfo[] properties = GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach (var propInfo in properties) { ProtocolKeyAttribute attr = (ProtocolKeyAttribute)Attribute.GetCustomAttribute(propInfo, typeof(ProtocolKeyAttribute)); if (attr != null && (attr.Sender & KeySender.Target) != 0) { if (inParameters[attr.Name] != null) { object value = ProtocolKeyAttribute.GetValueAsObject(inParameters[attr.Name], propInfo.PropertyType); propInfo.GetSetMethod(true).Invoke(this, new object[] { value }); inParameters.Remove(attr.Name); if (attr.Type == KeyType.Negotiated && !_negotiatedParameters.ContainsKey(attr.Name)) { value = propInfo.GetGetMethod(true).Invoke(this, null); outParameters.Add(attr.Name, ProtocolKeyAttribute.GetValueAsString(value, propInfo.PropertyType)); _negotiatedParameters.Add(attr.Name, string.Empty); } } } } _session.ConsumeParameters(inParameters, outParameters); foreach (var param in inParameters.Lines) { outParameters.Add(param.Key, "NotUnderstood"); } } private T ParseResponse<T>(ProtocolDataUnit pdu) where T : BaseResponse, new() { BaseResponse resp; switch (pdu.OpCode) { case OpCode.LoginResponse: resp = new LoginResponse(); break; case OpCode.LogoutResponse: resp = new LogoutResponse(); break; case OpCode.ReadyToTransfer: resp = new ReadyToTransferPacket(); break; case OpCode.Reject: resp = new RejectPacket(); break; case OpCode.ScsiDataIn: resp = new DataInPacket(); break; case OpCode.ScsiResponse: resp = new Response(); break; case OpCode.TextResponse: resp = new TextResponse(); break; default: throw new InvalidProtocolException("Unrecognized response opcode: " + pdu.OpCode); } resp.Parse(pdu); if (resp.StatusPresent) { SeenStatusSequenceNumber(resp.StatusSequenceNumber); } T result = resp as T; if (result == null) { throw new InvalidProtocolException("Unexpected response, expected " + typeof(T) + ", got " + result.GetType()); } return result; } } }
/* * Copyright 2008 ZXing 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. */ using System; using System.Collections.Generic; using System.Text; using ZXing.Common; namespace ZXing.OneD { /// <summary> /// <p>Decodes Codabar barcodes.</p> /// /// <author>Bas Vijfwinkel</author> /// </summary> public sealed class CodaBarReader : OneDReader { // These values are critical for determining how permissive the decoding // will be. All stripe sizes must be within the window these define, as // compared to the average stripe size. private static readonly int MAX_ACCEPTABLE = (int)(PATTERN_MATCH_RESULT_SCALE_FACTOR * 2.0f); private static readonly int PADDING = (int)(PATTERN_MATCH_RESULT_SCALE_FACTOR * 1.5f); private const String ALPHABET_STRING = "0123456789-$:/.+ABCD"; internal static readonly char[] ALPHABET = ALPHABET_STRING.ToCharArray(); /** * These represent the encodings of characters, as patterns of wide and narrow bars. The 7 least-significant bits of * each int correspond to the pattern of wide and narrow, with 1s representing "wide" and 0s representing narrow. */ internal static int[] CHARACTER_ENCODINGS = { 0x003, 0x006, 0x009, 0x060, 0x012, 0x042, 0x021, 0x024, 0x030, 0x048, // 0-9 0x00c, 0x018, 0x045, 0x051, 0x054, 0x015, 0x01A, 0x029, 0x00B, 0x00E, // -$:/.+ABCD }; // minimal number of characters that should be present (including start and stop characters) // under normal circumstances this should be set to 3, but can be set higher // as a last-ditch attempt to reduce false positives. private const int MIN_CHARACTER_LENGTH = 3; // official start and end patterns private static readonly char[] STARTEND_ENCODING = { 'A', 'B', 'C', 'D' }; // some Codabar generator allow the Codabar string to be closed by every // character. This will cause lots of false positives! // some industries use a checksum standard but this is not part of the original Codabar standard // for more information see : http://www.mecsw.com/specs/codabar.html // Keep some instance variables to avoid reallocations private readonly StringBuilder decodeRowResult; private int[] counters; private int counterLength; public CodaBarReader() { decodeRowResult = new StringBuilder(20); counters = new int[80]; counterLength = 0; } public override Result decodeRow(int rowNumber, BitArray row, IDictionary<DecodeHintType, object> hints) { for (var index = 0; index < counters.Length; index++) counters[index] = 0; if (!setCounters(row)) return null; int startOffset = findStartPattern(); if (startOffset < 0) return null; int nextStart = startOffset; decodeRowResult.Length = 0; do { int charOffset = toNarrowWidePattern(nextStart); if (charOffset == -1) { return null; } // Hack: We store the position in the alphabet table into a // StringBuilder, so that we can access the decoded patterns in // validatePattern. We'll translate to the actual characters later. decodeRowResult.Append((char) charOffset); nextStart += 8; // Stop as soon as we see the end character. if (decodeRowResult.Length > 1 && arrayContains(STARTEND_ENCODING, ALPHABET[charOffset])) { break; } } while (nextStart < counterLength); // no fixed end pattern so keep on reading while data is available // Look for whitespace after pattern: int trailingWhitespace = counters[nextStart - 1]; int lastPatternSize = 0; for (int i = -8; i < -1; i++) { lastPatternSize += counters[nextStart + i]; } // We need to see whitespace equal to 50% of the last pattern size, // otherwise this is probably a false positive. The exception is if we are // at the end of the row. (I.e. the barcode barely fits.) if (nextStart < counterLength && trailingWhitespace < lastPatternSize/2) { return null; } if (!validatePattern(startOffset)) return null; // Translate character table offsets to actual characters. for (int i = 0; i < decodeRowResult.Length; i++) { decodeRowResult[i] = ALPHABET[decodeRowResult[i]]; } // Ensure a valid start and end character char startchar = decodeRowResult[0]; if (!arrayContains(STARTEND_ENCODING, startchar)) { return null; } char endchar = decodeRowResult[decodeRowResult.Length - 1]; if (!arrayContains(STARTEND_ENCODING, endchar)) { return null; } // remove stop/start characters character and check if a long enough string is contained if (decodeRowResult.Length <= MIN_CHARACTER_LENGTH) { // Almost surely a false positive ( start + stop + at least 1 character) return null; } if (!SupportClass.GetValue(hints, DecodeHintType.RETURN_CODABAR_START_END, false)) { decodeRowResult.Remove(decodeRowResult.Length - 1, 1); decodeRowResult.Remove(0, 1); } int runningCount = 0; for (int i = 0; i < startOffset; i++) { runningCount += counters[i]; } float left = runningCount; for (int i = startOffset; i < nextStart - 1; i++) { runningCount += counters[i]; } float right = runningCount; var resultPointCallback = SupportClass.GetValue(hints, DecodeHintType.NEED_RESULT_POINT_CALLBACK, (ResultPointCallback) null); if (resultPointCallback != null) { resultPointCallback(new ResultPoint(left, rowNumber)); resultPointCallback(new ResultPoint(right, rowNumber)); } return new Result( decodeRowResult.ToString(), null, new[] { new ResultPoint(left, rowNumber), new ResultPoint(right, rowNumber) }, BarcodeFormat.CODABAR); } private bool validatePattern(int start) { // First, sum up the total size of our four categories of stripe sizes; int[] sizes = { 0, 0, 0, 0 }; int[] counts = { 0, 0, 0, 0 }; int end = decodeRowResult.Length - 1; // We break out of this loop in the middle, in order to handle // inter-character spaces properly. int pos = start; for (int i = 0; true; i++) { int pattern = CHARACTER_ENCODINGS[decodeRowResult[i]]; for (int j = 6; j >= 0; j--) { // Even j = bars, while odd j = spaces. Categories 2 and 3 are for // long stripes, while 0 and 1 are for short stripes. int category = (j & 1) + (pattern & 1) * 2; sizes[category] += counters[pos + j]; counts[category]++; pattern >>= 1; } if (i >= end) { break; } // We ignore the inter-character space - it could be of any size. pos += 8; } // Calculate our allowable size thresholds using fixed-point math. int[] maxes = new int[4]; int[] mins = new int[4]; // Define the threshold of acceptability to be the midpoint between the // average small stripe and the average large stripe. No stripe lengths // should be on the "wrong" side of that line. for (int i = 0; i < 2; i++) { mins[i] = 0; // Accept arbitrarily small "short" stripes. mins[i + 2] = ((sizes[i] << INTEGER_MATH_SHIFT) / counts[i] + (sizes[i + 2] << INTEGER_MATH_SHIFT) / counts[i + 2]) >> 1; maxes[i] = mins[i + 2]; maxes[i + 2] = (sizes[i + 2] * MAX_ACCEPTABLE + PADDING) / counts[i + 2]; } // Now verify that all of the stripes are within the thresholds. pos = start; for (int i = 0; true; i++) { int pattern = CHARACTER_ENCODINGS[decodeRowResult[i]]; for (int j = 6; j >= 0; j--) { // Even j = bars, while odd j = spaces. Categories 2 and 3 are for // long stripes, while 0 and 1 are for short stripes. int category = (j & 1) + (pattern & 1) * 2; int size = counters[pos + j] << INTEGER_MATH_SHIFT; if (size < mins[category] || size > maxes[category]) { return false; } pattern >>= 1; } if (i >= end) { break; } pos += 8; } return true; } /// <summary> /// Records the size of all runs of white and black pixels, starting with white. /// This is just like recordPattern, except it records all the counters, and /// uses our builtin "counters" member for storage. /// </summary> /// <param name="row">row to count from</param> private bool setCounters(BitArray row) { counterLength = 0; // Start from the first white bit. int i = row.getNextUnset(0); int end = row.Size; if (i >= end) { return false; } bool isWhite = true; int count = 0; while (i < end) { if (row[i] != isWhite) { count++; } else { counterAppend(count); count = 1; isWhite = !isWhite; } i++; } counterAppend(count); return true; } private void counterAppend(int e) { counters[counterLength] = e; counterLength++; if (counterLength >= counters.Length) { int[] temp = new int[counterLength * 2]; Array.Copy(counters, 0, temp, 0, counterLength); counters = temp; } } private int findStartPattern() { for (int i = 1; i < counterLength; i += 2) { int charOffset = toNarrowWidePattern(i); if (charOffset != -1 && arrayContains(STARTEND_ENCODING, ALPHABET[charOffset])) { // Look for whitespace before start pattern, >= 50% of width of start pattern // We make an exception if the whitespace is the first element. int patternSize = 0; for (int j = i; j < i + 7; j++) { patternSize += counters[j]; } if (i == 1 || counters[i - 1] >= patternSize / 2) { return i; } } } return -1; } internal static bool arrayContains(char[] array, char key) { if (array != null) { foreach (char c in array) { if (c == key) { return true; } } } return false; } // Assumes that counters[position] is a bar. private int toNarrowWidePattern(int position) { int end = position + 7; if (end >= counterLength) { return -1; } int[] theCounters = counters; int maxBar = 0; int minBar = Int32.MaxValue; for (int j = position; j < end; j += 2) { int currentCounter = theCounters[j]; if (currentCounter < minBar) { minBar = currentCounter; } if (currentCounter > maxBar) { maxBar = currentCounter; } } int thresholdBar = (minBar + maxBar) / 2; int maxSpace = 0; int minSpace = Int32.MaxValue; for (int j = position + 1; j < end; j += 2) { int currentCounter = theCounters[j]; if (currentCounter < minSpace) { minSpace = currentCounter; } if (currentCounter > maxSpace) { maxSpace = currentCounter; } } int thresholdSpace = (minSpace + maxSpace) / 2; int bitmask = 1 << 7; int pattern = 0; for (int i = 0; i < 7; i++) { int threshold = (i & 1) == 0 ? thresholdBar : thresholdSpace; bitmask >>= 1; if (theCounters[position + i] > threshold) { pattern |= bitmask; } } for (int i = 0; i < CHARACTER_ENCODINGS.Length; i++) { if (CHARACTER_ENCODINGS[i] == pattern) { return i; } } return -1; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; using System.Globalization; namespace System.Xml { /// <summary> /// Contains various static functions and methods for parsing and validating: /// NCName (not namespace-aware, no colons allowed) /// QName (prefix:local-name) /// </summary> internal static class ValidateNames { internal enum Flags { NCNames = 0x1, // Validate that each non-empty prefix and localName is a valid NCName CheckLocalName = 0x2, // Validate the local-name CheckPrefixMapping = 0x4, // Validate the prefix --> namespace mapping All = 0x7, AllExceptNCNames = 0x6, AllExceptPrefixMapping = 0x3, }; private static XmlCharType s_xmlCharType = XmlCharType.Instance; //----------------------------------------------- // Nmtoken parsing //----------------------------------------------- /// <summary> /// Attempts to parse the input string as an Nmtoken (see the XML spec production [7] && XML Namespaces spec). /// Quits parsing when an invalid Nmtoken char is reached or the end of string is reached. /// Returns the number of valid Nmtoken chars that were parsed. /// </summary> internal static unsafe int ParseNmtoken(string s, int offset) { Debug.Assert(s != null && offset <= s.Length); // Keep parsing until the end of string or an invalid NCName character is reached int i = offset; while (i < s.Length) { if ((s_xmlCharType.charProperties[s[i]] & XmlCharType.fNCNameSC) != 0) { i++; } #if XML10_FIFTH_EDITION else if (xmlCharType.IsNCNameSurrogateChar(s, i)) { i += 2; } #endif else { break; } } return i - offset; } //----------------------------------------------- // Nmtoken parsing (no XML namespaces support) //----------------------------------------------- /// <summary> /// Attempts to parse the input string as an Nmtoken (see the XML spec production [7]) without taking /// into account the XML Namespaces spec. What it means is that the ':' character is allowed at any /// position and any number of times in the token. /// Quits parsing when an invalid Nmtoken char is reached or the end of string is reached. /// Returns the number of valid Nmtoken chars that were parsed. /// </summary> internal static unsafe int ParseNmtokenNoNamespaces(string s, int offset) { Debug.Assert(s != null && offset <= s.Length); // Keep parsing until the end of string or an invalid Name character is reached int i = offset; while (i < s.Length) { if ((s_xmlCharType.charProperties[s[i]] & XmlCharType.fNCNameSC) != 0 || s[i] == ':') { // if (xmlCharType.IsNameSingleChar(s[i])) { i++; } #if XML10_FIFTH_EDITION else if (xmlCharType.IsNCNameSurrogateChar(s, i)) { i += 2; } #endif else { break; } } return i - offset; } // helper methods internal static bool IsNmtokenNoNamespaces(string s) { int endPos = ParseNmtokenNoNamespaces(s, 0); return endPos > 0 && endPos == s.Length; } //----------------------------------------------- // Name parsing (no XML namespaces support) //----------------------------------------------- /// <summary> /// Attempts to parse the input string as a Name without taking into account the XML Namespaces spec. /// What it means is that the ':' character does not delimiter prefix and local name, but it is a regular /// name character, which is allowed to appear at any position and any number of times in the name. /// Quits parsing when an invalid Name char is reached or the end of string is reached. /// Returns the number of valid Name chars that were parsed. /// </summary> internal static unsafe int ParseNameNoNamespaces(string s, int offset) { Debug.Assert(s != null && offset <= s.Length); // Quit if the first character is not a valid NCName starting character int i = offset; if (i < s.Length) { if ((s_xmlCharType.charProperties[s[i]] & XmlCharType.fNCStartNameSC) != 0 || s[i] == ':') { i++; } #if XML10_FIFTH_EDITION else if (xmlCharType.IsNCNameSurrogateChar(s, i)) { i += 2; } #endif else { return 0; // no valid StartNCName char } // Keep parsing until the end of string or an invalid NCName character is reached while (i < s.Length) { if ((s_xmlCharType.charProperties[s[i]] & XmlCharType.fNCNameSC) != 0 || s[i] == ':') { i++; } #if XML10_FIFTH_EDITION else if (xmlCharType.IsNCNameSurrogateChar(s, i)) { i += 2; } #endif else { break; } } } return i - offset; } // helper methods internal static bool IsNameNoNamespaces(string s) { int endPos = ParseNameNoNamespaces(s, 0); return endPos > 0 && endPos == s.Length; } //----------------------------------------------- // NCName parsing //----------------------------------------------- /// <summary> /// Attempts to parse the input string as an NCName (see the XML Namespace spec). /// Quits parsing when an invalid NCName char is reached or the end of string is reached. /// Returns the number of valid NCName chars that were parsed. /// </summary> internal static unsafe int ParseNCName(string s, int offset) { Debug.Assert(s != null && offset <= s.Length); // Quit if the first character is not a valid NCName starting character int i = offset; if (i < s.Length) { if ((s_xmlCharType.charProperties[s[i]] & XmlCharType.fNCStartNameSC) != 0) { i++; } #if XML10_FIFTH_EDITION else if (xmlCharType.IsNCNameSurrogateChar(s, i)) { i += 2; } #endif else { return 0; // no valid StartNCName char } // Keep parsing until the end of string or an invalid NCName character is reached while (i < s.Length) { if ((s_xmlCharType.charProperties[s[i]] & XmlCharType.fNCNameSC) != 0) { i++; } #if XML10_FIFTH_EDITION else if (xmlCharType.IsNCNameSurrogateChar(s, i)) { i += 2; } #endif else { break; } } } return i - offset; } internal static int ParseNCName(string s) { return ParseNCName(s, 0); } //----------------------------------------------- // QName parsing //----------------------------------------------- /// <summary> /// Attempts to parse the input string as a QName (see the XML Namespace spec). /// Quits parsing when an invalid QName char is reached or the end of string is reached. /// Returns the number of valid QName chars that were parsed. /// Sets colonOffset to the offset of a colon character if it exists, or 0 otherwise. /// </summary> internal static int ParseQName(string s, int offset, out int colonOffset) { // Assume no colon colonOffset = 0; // Parse NCName (may be prefix, may be local name) int len = ParseNCName(s, offset); if (len != 0) { // Non-empty NCName, so look for colon if there are any characters left offset += len; if (offset < s.Length && s[offset] == ':') { // First NCName was prefix, so look for local name part int lenLocal = ParseNCName(s, offset + 1); if (lenLocal != 0) { // Local name part found, so increase total QName length (add 1 for colon) colonOffset = offset; len += lenLocal + 1; } } } return len; } /// <summary> /// Calls parseQName and throws exception if the resulting name is not a valid QName. /// Returns the prefix and local name parts. /// </summary> internal static void ParseQNameThrow(string s, out string prefix, out string localName) { int colonOffset; int len = ParseQName(s, 0, out colonOffset); if (len == 0 || len != s.Length) { // If the string is not a valid QName, then throw ThrowInvalidName(s, 0, len); } if (colonOffset != 0) { prefix = s.Substring(0, colonOffset); localName = s.Substring(colonOffset + 1); } else { prefix = ""; localName = s; } } /// <summary> /// Throws an invalid name exception. /// </summary> /// <param name="s">String that was parsed.</param> /// <param name="offsetStartChar">Offset in string where parsing began.</param> /// <param name="offsetBadChar">Offset in string where parsing failed.</param> internal static void ThrowInvalidName(string s, int offsetStartChar, int offsetBadChar) { // If the name is empty, throw an exception if (offsetStartChar >= s.Length) throw new XmlException(SR.Xml_EmptyName); Debug.Assert(offsetBadChar < s.Length); if (s_xmlCharType.IsNCNameSingleChar(s[offsetBadChar]) && !XmlCharType.Instance.IsStartNCNameSingleChar(s[offsetBadChar])) { // The error character is a valid name character, but is not a valid start name character throw new XmlException(SR.Format(SR.Xml_BadStartNameChar, XmlExceptionHelper.BuildCharExceptionArgs(s, offsetBadChar))); } else { // The error character is an invalid name character throw new XmlException(SR.Format(SR.Xml_BadNameChar, XmlExceptionHelper.BuildCharExceptionArgs(s, offsetBadChar))); } } /// <summary> /// Split a QualifiedName into prefix and localname, w/o any checking. /// (Used for XmlReader/XPathNavigator MoveTo(name) methods) /// </summary> internal static void SplitQName(string name, out string prefix, out string lname) { int colonPos = name.IndexOf(':'); if (-1 == colonPos) { prefix = string.Empty; lname = name; } else if (0 == colonPos || (name.Length - 1) == colonPos) { throw new ArgumentException(SR.Format(SR.Xml_BadNameChar, XmlExceptionHelper.BuildCharExceptionArgs(':', '\0')), "name"); } else { prefix = name.Substring(0, colonPos); colonPos++; // move after colon lname = name.Substring(colonPos, name.Length - colonPos); } } } internal class XmlExceptionHelper { internal static string[] BuildCharExceptionArgs(string data, int invCharIndex) { return BuildCharExceptionArgs(data[invCharIndex], invCharIndex + 1 < data.Length ? data[invCharIndex + 1] : '\0'); } internal static string[] BuildCharExceptionArgs(char[] data, int invCharIndex) { return BuildCharExceptionArgs(data, data.Length, invCharIndex); } internal static string[] BuildCharExceptionArgs(char[] data, int length, int invCharIndex) { Debug.Assert(invCharIndex < data.Length); Debug.Assert(invCharIndex < length); Debug.Assert(length <= data.Length); return BuildCharExceptionArgs(data[invCharIndex], invCharIndex + 1 < length ? data[invCharIndex + 1] : '\0'); } internal static string[] BuildCharExceptionArgs(char invChar, char nextChar) { string[] aStringList = new string[2]; // for surrogate characters include both high and low char in the message so that a full character is displayed if (XmlCharType.IsHighSurrogate(invChar) && nextChar != 0) { int combinedChar = XmlCharType.CombineSurrogateChar(nextChar, invChar); aStringList[0] = new string(new char[] { invChar, nextChar }); aStringList[1] = string.Format(CultureInfo.InvariantCulture, "0x{0:X2}", combinedChar); } else { // don't include 0 character in the string - in means eof-of-string in native code, where this may bubble up to if ((int)invChar == 0) { aStringList[0] = "."; } else { aStringList[0] = Convert.ToString(invChar, CultureInfo.InvariantCulture); } aStringList[1] = string.Format(CultureInfo.InvariantCulture, "0x{0:X2}", (int)invChar); } return aStringList; } } }
#region License /* The MIT License Copyright (c) 2008 Sky Morey Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion namespace System.Collections.Generic { /// <summary> /// DictionaryExtensions class /// A string/string type implementation extending the generic <see cref="Instinct.Collections.Hash{TKey, TValue}"/> type. Provide /// standardization of common functions such as <see cref="Instinct.Collections.Hash.Append(string[])"/> and /// <see cref="Instinct.Collections.Hash.ToStringArray"/>. /// </summary> /// <seealso cref="System.Collections.Generic.IDictionary{Key, TValue}"/> /// <seealso cref="Instinct.Collections.Hash{TKey, TValue}"/> /// <seealso cref="Instinct.Collections.IndexBase{TKey, TValue}"/> public static class DictionaryExtensions { //public static TValue GetValue<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, int index, TValue defaultValue) //{ // return defaultValue; //} /// <summary> /// Appends the specified value array to the underlying instance of /// <see cref="System.Collections.Generic.Dictionary{TKey, TValue}"/> provided by the /// <see cref="Instinct.Collections.Hash{TKey, TValue}"/> base class. /// </summary> /// <param name="dictionary">The dictionary.</param> /// <param name="values">String array of default values to use in initializing the collection.</param> /// <returns></returns> public static Dictionary<string, string> Insert(this Dictionary<string, string> dictionary, string[] values) { if (dictionary == null) throw new ArgumentNullException("dictionary"); if ((values == null) || (values.Length == 0)) return dictionary; foreach (string value in values) { if (value == null) throw new NullReferenceException(Local.InvalidArrayNullItem); if (value.Length > 0) { int valueEqualIndex = value.IndexOf('='); if (valueEqualIndex >= 0) dictionary[value.Substring(0, valueEqualIndex)] = value.Substring(valueEqualIndex + 1); else dictionary[value] = value; } } return dictionary; } /// <summary> /// Appends the specified value array to the underlying instance of /// <see cref="System.Collections.Generic.Dictionary{TKey, TValue}"/> provided by the /// <see cref="Instinct.Collections.Hash{TKey, TValue}"/> base class. /// </summary> /// <param name="dictionary">The dictionary.</param> /// <param name="values">String array of default values to use in initializing the collection.</param> /// <param name="startIndex">The initial index value to use as a starting point when processing the specified <c>values</c></param> /// <returns></returns> public static Dictionary<string, string> Insert(this Dictionary<string, string> dictionary, string[] values, int startIndex) { if (dictionary == null) throw new ArgumentNullException("dictionary"); if (startIndex < 0) throw new ArgumentOutOfRangeException("startIndex"); if ((values == null) || (startIndex >= values.Length)) return dictionary; for (int valueIndex = startIndex; valueIndex < values.Length; valueIndex++) { string value = values[valueIndex]; if (value == null) throw new NullReferenceException(Local.InvalidArrayNullItem); if (value.Length > 0) { int valueEqualIndex = value.IndexOf('='); if (valueEqualIndex >= 0) dictionary[value.Substring(0, valueEqualIndex)] = value.Substring(valueEqualIndex + 1); else dictionary[value] = value; } } return dictionary; } /// <summary> /// Appends the specified value array to the underlying instance of /// <see cref="System.Collections.Generic.Dictionary{TKey, TValue}"/> provided by the /// <see cref="Instinct.Collections.Hash{TKey, TValue}"/> base class. /// </summary> /// <param name="dictionary">The dictionary.</param> /// <param name="values">String array of default values to use in initializing the collection.</param> /// <param name="startIndex">The initial index value to use as a starting point when processing the specified <c>values</c></param> /// <param name="count">The number of value from <c>values</c> to process, starting at the position indicated by <c>startIndex</c>.</param> /// <returns></returns> public static Dictionary<string, string> Insert(this Dictionary<string, string> dictionary, string[] values, int startIndex, int count) { if (dictionary == null) throw new ArgumentNullException("dictionary"); if (startIndex < 0) throw new ArgumentOutOfRangeException("startIndex"); if (count < 0) throw new ArgumentOutOfRangeException("count"); if ((values == null) || (startIndex >= count)) return dictionary; if (count > values.Length) count = values.Length; for (int valueIndex = startIndex; valueIndex < count; valueIndex++) { string value = values[valueIndex]; if (value == null) throw new InvalidOperationException(Local.InvalidArrayNullItem); if (value.Length > 0) { int valueEqualIndex = value.IndexOf('='); if (valueEqualIndex >= 0) dictionary[value.Substring(0, valueEqualIndex)] = value.Substring(valueEqualIndex + 1); else dictionary[value] = value; } } return dictionary; } /// <summary> /// Appends the specified value array to the underlying instance of /// <see cref="System.Collections.Generic.Dictionary{TKey, TValue}"/> provided by the /// <see cref="Instinct.Collections.Hash{TKey, TValue}"/> base class. /// </summary> /// <param name="dictionary">The dictionary.</param> /// <param name="values">String array of default values to use in initializing the collection.</param> /// <param name="namespaceKey">A namespace prefix to search when setting initial values.</param> /// <returns></returns> /// <remarks>When processing <c>values</c>, the underlying /// instance of <see cref="System.Collections.Generic.Dictionary{TKey, TValue}"/> provided by the /// <see cref="Instinct.Collections.Hash{TKey, TValue}"/> base class</remarks> /// is search for values. The /// <c>namespaceKey</c> /// + ":" is used as a prefix to the keys found in the internal dictionary to /// determine a match for initializing to the value provided by /// <c>values.</c> public static Dictionary<string, string> Insert(this Dictionary<string, string> dictionary, string[] values, string namespaceKey) { if (string.IsNullOrEmpty(namespaceKey)) { Insert(dictionary, values); return dictionary; } if (values == null) return dictionary; namespaceKey += ":"; int namespaceKeyLength = namespaceKey.Length; int valueDataIndex; foreach (string value in values) { if (value == null) throw new InvalidOperationException(Local.InvalidArrayNullItem); if ((value.Length > -1) && ((valueDataIndex = value.IndexOf(namespaceKey, StringComparison.OrdinalIgnoreCase)) > -1)) { valueDataIndex += namespaceKeyLength; int valueEqualIndex = value.IndexOf('=', valueDataIndex); if (valueEqualIndex >= 0) dictionary[value.Substring(valueDataIndex, valueEqualIndex - valueDataIndex)] = value.Substring(valueDataIndex + valueEqualIndex + 1); else { string value2 = value.Substring(valueDataIndex); dictionary[value2] = value2; } } } return dictionary; } /// <summary> /// Appends the specified value array to the underlying instance of /// <see cref="System.Collections.Generic.Dictionary{TKey, TValue}"/> provided by the /// <see cref="Instinct.Collections.Hash{TKey, TValue}"/> base class. /// </summary> /// <param name="dictionary">The dictionary.</param> /// <param name="values">String array of default values to use in initializing the collection.</param> /// <param name="namespaceKey">A namespace prefix to search when setting initial values.</param> /// <param name="startIndex">The initial index value to use as a starting point when processing the specified <c>values</c></param> /// <param name="count">The number of value from <c>values</c> to process, starting at the position indicated by <c>startIndex</c>.</param> /// <returns></returns> /// <remarks>When processing <c>values</c>, the underlying /// instance of <see cref="System.Collections.Generic.Dictionary{TKey, TValue}"/> provided by the /// <see cref="Instinct.Collections.Hash{TKey, TValue}"/> base class</remarks> /// is search for values. The /// <c>namespaceKey</c> /// + ":" is used as a prefix to the keys found in the internal dictionary to /// determine a match for initializing to the value provided by /// <c>values.</c> public static Dictionary<string, string> Insert(this Dictionary<string, string> dictionary, string[] values, string namespaceKey, int startIndex, int count) { if (string.IsNullOrEmpty(namespaceKey)) { Insert(dictionary, values, startIndex, count); return dictionary; } if ((values == null) || (startIndex >= count)) return dictionary; if (count > values.Length) count = values.Length; namespaceKey += ":"; int namespaceKeyLength = namespaceKey.Length; int valueDataIndex; for (int valueIndex = startIndex; valueIndex < count; valueIndex++) { string value = values[valueIndex]; if (value == null) throw new InvalidOperationException(Local.InvalidArrayNullItem); if ((value.Length > -1) && ((valueDataIndex = value.IndexOf(namespaceKey, StringComparison.OrdinalIgnoreCase)) > -1)) { valueDataIndex += namespaceKeyLength; int valueEqualIndex = value.IndexOf('=', valueDataIndex); if (valueEqualIndex >= 0) dictionary[value.Substring(valueDataIndex, valueEqualIndex - valueDataIndex)] = value.Substring(valueDataIndex + valueEqualIndex + 1); else { value = value.Substring(valueDataIndex); dictionary[value] = value; } } } return dictionary; } /// <summary> /// Appends the specified hash to the underlying instance of /// <see cref="System.Collections.Generic.Dictionary{TKey, TValue}"/> provided by the /// <see cref="Instinct.Collections.Hash{TKey, TValue}"/> base class. /// </summary> /// <param name="dictionary">The dictionary.</param> /// <param name="sourceDictionary">The source dictionary.</param> /// <returns></returns> public static Dictionary<string, string> Insert(this Dictionary<string, string> dictionary, IDictionary<string, string> sourceDictionary) { if (sourceDictionary == null) return dictionary; foreach (string key in sourceDictionary.Keys) dictionary[key] = sourceDictionary[key]; return dictionary; } /// <summary> /// Gets the bit. /// </summary> /// <param name="dictionary">The dictionary.</param> /// <param name="key">The key.</param> /// <returns></returns> public static bool GetBit(this Dictionary<string, string> dictionary, string key) { string value; return ((dictionary.TryGetValue(key, out value)) && (string.Compare(value, key, StringComparison.OrdinalIgnoreCase) == 0)); } /// <summary> /// Sets the bit. /// </summary> /// <param name="dictionary">The dictionary.</param> /// <param name="key">The key.</param> /// <param name="value">The value.</param> public static void SetBit(this Dictionary<string, string> dictionary, string key, bool value) { if (value) dictionary[key] = key; else if (dictionary.ContainsKey(key)) dictionary.Remove(key); } /// <summary> /// Slices or removes all keys prefixed with the provided <c>namespaceKey</c> value from the underlying /// <see cref="System.Collections.Generic.Dictionary{TKey, TValue}"/> instance that contains /// the values stored within the collection object. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="dictionary">The dictionary.</param> /// <param name="namespaceKey">The namespace to target.</param> /// <returns> /// Returns a new <see cref="Instinct.Collections.Hash"/> instance containing all the values removed /// from the stored values. /// </returns> public static T Slice<T>(this Dictionary<string, string> dictionary, string namespaceKey) where T : Dictionary<string, string>, new() { return Slice<T>(dictionary, namespaceKey, false); } /// <summary> /// Slices or removes all keys prefixed with the provided <c>namespaceKey</c> value from the underlying /// <see cref="System.Collections.Generic.Dictionary{TKey, TValue}"/> instance that contains /// the values stored within the collection object. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="dictionary">The dictionary.</param> /// <param name="namespaceKey">The namespace to target.</param> /// <param name="returnNullIfNoMatch">if set to <c>true</c> [return null if no match].</param> /// <returns> /// Returns a new <see cref="Instinct.Collections.Hash"/> instance containing all the values removed /// from the stored values. /// </returns> public static T Slice<T>(this Dictionary<string, string> dictionary, string namespaceKey, bool returnNullIfNoMatch) where T : Dictionary<string, string>, new() { T sliceHash = null; if (namespaceKey.Length > 0) { namespaceKey += ":"; int namespaceKeyLength = namespaceKey.Length; //+ return namespace set foreach (string key in new System.Collections.Generic.List<string>(dictionary.Keys)) if (key.StartsWith(namespaceKey)) { if (sliceHash == null) sliceHash = new T(); // add & remove string value = dictionary[key]; if (key != value) sliceHash[key.Substring(namespaceKeyLength)] = value; else { // isbit value = key.Substring(namespaceKeyLength); sliceHash[value] = value; } dictionary.Remove(key); } } // return root-namespace set else foreach (string key in new List<string>(dictionary.Keys)) if (key.IndexOf(":") == -1) { sliceHash[key] = dictionary[key]; dictionary.Remove(key); } return ((sliceHash != null) || (returnNullIfNoMatch) ? sliceHash : new T()); } /// <summary> /// Slices or removes all keys prefixed with the provided <c>namespaceKey</c> value from the underlying /// <see cref="System.Collections.Generic.Dictionary{TKey, TValue}"/> instance that contains /// the values stored within the collection object. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="dictionary">The dictionary.</param> /// <param name="namespaceKey">The namespace to target.</param> /// <param name="isReturnNullIfNoMatch">TODO.</param> /// <param name="valueReplacerIfStartsWith">The value replacer if starts with.</param> /// <param name="valueReplacer">The value replacer.</param> /// <returns> /// Returns a new <see cref="Instinct.Collections.Hash"/> instance containing all the values removed /// from the stored values. /// </returns> public static T Slice<T>(this Dictionary<string, string> dictionary, string namespaceKey, bool isReturnNullIfNoMatch, string valueReplacerIfStartsWith, Func<string, string> valueReplacer) where T : Dictionary<string, string>, new() { T sliceHash = null; if (namespaceKey.Length > 0) { namespaceKey += ":"; int namespaceKeyLength = namespaceKey.Length; string compositeKey = valueReplacerIfStartsWith + namespaceKey; int compositeKeyLength = compositeKey.Length; // return namespace set foreach (string key in new List<string>(dictionary.Keys)) if (key.StartsWith(compositeKey)) { if (sliceHash == null) sliceHash = new T(); // add & remove string value = valueReplacer(dictionary[key]); if (key != value) sliceHash[key.Substring(compositeKeyLength)] = value; else { // isbit value = key.Substring(compositeKeyLength); sliceHash[value] = value; } dictionary.Remove(key); } else if (key.StartsWith(namespaceKey)) { if (sliceHash == null) sliceHash = new T(); // add and remove string value = dictionary[key]; if (key != value) sliceHash[key.Substring(namespaceKeyLength)] = value; else { // isbit value = key.Substring(namespaceKeyLength); sliceHash[value] = value; } dictionary.Remove(key); } } // return root-namespace set else foreach (string key in new List<string>(dictionary.Keys)) if (key.IndexOf(":") == -1) { sliceHash[key] = (!key.StartsWith(valueReplacerIfStartsWith) ? dictionary[key] : valueReplacer(dictionary[key])); dictionary.Remove(key); } return ((sliceHash != null) || (isReturnNullIfNoMatch) ? sliceHash : new T()); } /// <summary> /// Looks for the item in the underlying hash and if exists, removes it and returns it. /// </summary> /// <param name="dictionary">The dictionary.</param> /// <param name="key">The key.</param> /// <returns></returns> public static bool SliceBit(this Dictionary<string, string> dictionary, string key) { string value; if (dictionary.TryGetValue(key, out value)) { bool isSlice = (string.Compare(value, key, StringComparison.OrdinalIgnoreCase) == 0); dictionary.Remove(key); return isSlice; } return false; } /// <summary> /// Looks for the item in the underlying hash and if exists, removes it and returns it, or returns default value if not found. /// </summary> /// <param name="dictionary">The dictionary.</param> /// <param name="key">The key.</param> /// <param name="defaultValue">The default value.</param> /// <returns></returns> public static bool SliceBit(this Dictionary<string, string> dictionary, string key, bool defaultValue) { string value; if (dictionary.TryGetValue(key, out value)) { bool isSlice = (string.Compare(value, key, StringComparison.OrdinalIgnoreCase) == 0); dictionary.Remove(key); return isSlice; } return defaultValue; } /// <summary> /// Converts the underlying collection of string representations. /// </summary> /// <param name="this">The @this.</param> /// <returns> /// Returns a string array of values following the format "<c>key</c>=<c>value</c>" /// </returns> public static string[] ToStringArray(this Dictionary<string, string> dictionary) { var keys = dictionary.Keys; int keyIndex = 0; string[] array = new string[keys.Count]; foreach (var entry in dictionary) array[keyIndex++] = entry.Key + "=" + entry.Value; return array; } } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; using Csla; using Invoices.DataAccess; namespace Invoices.Business { /// <summary> /// ProductTypeCachedList (read only list).<br/> /// This is a generated base class of <see cref="ProductTypeCachedList"/> business object. /// This class is a root collection. /// </summary> /// <remarks> /// The items of the collection are <see cref="ProductTypeCachedInfo"/> objects. /// Cached. Updated by ProductTypeItem /// </remarks> [Serializable] #if WINFORMS public partial class ProductTypeCachedList : ReadOnlyBindingListBase<ProductTypeCachedList, ProductTypeCachedInfo> #else public partial class ProductTypeCachedList : ReadOnlyListBase<ProductTypeCachedList, ProductTypeCachedInfo> #endif { #region Event handler properties [NotUndoable] private static bool _singleInstanceSavedHandler = true; /// <summary> /// Gets or sets a value indicating whether only a single instance should handle the Saved event. /// </summary> /// <value> /// <c>true</c> if only a single instance should handle the Saved event; otherwise, <c>false</c>. /// </value> public static bool SingleInstanceSavedHandler { get { return _singleInstanceSavedHandler; } set { _singleInstanceSavedHandler = value; } } #endregion #region Collection Business Methods /// <summary> /// Determines whether a <see cref="ProductTypeCachedInfo"/> item is in the collection. /// </summary> /// <param name="productTypeId">The ProductTypeId of the item to search for.</param> /// <returns><c>true</c> if the ProductTypeCachedInfo is a collection item; otherwise, <c>false</c>.</returns> public bool Contains(int productTypeId) { foreach (var productTypeCachedInfo in this) { if (productTypeCachedInfo.ProductTypeId == productTypeId) { return true; } } return false; } #endregion #region Private Fields private static ProductTypeCachedList _list; #endregion #region Cache Management Methods /// <summary> /// Clears the in-memory ProductTypeCachedList cache so it is reloaded on the next request. /// </summary> public static void InvalidateCache() { _list = null; } /// <summary> /// Used by async loaders to load the cache. /// </summary> /// <param name="list">The list to cache.</param> internal static void SetCache(ProductTypeCachedList list) { _list = list; } internal static bool IsCached { get { return _list != null; } } #endregion #region Factory Methods /// <summary> /// Factory method. Loads a <see cref="ProductTypeCachedList"/> collection. /// </summary> /// <returns>A reference to the fetched <see cref="ProductTypeCachedList"/> collection.</returns> public static ProductTypeCachedList GetProductTypeCachedList() { if (_list == null) _list = DataPortal.Fetch<ProductTypeCachedList>(); return _list; } /// <summary> /// Factory method. Asynchronously loads a <see cref="ProductTypeCachedList"/> collection. /// </summary> /// <param name="callback">The completion callback method.</param> public static void GetProductTypeCachedList(EventHandler<DataPortalResult<ProductTypeCachedList>> callback) { if (_list == null) DataPortal.BeginFetch<ProductTypeCachedList>((o, e) => { _list = e.Object; callback(o, e); }); else callback(null, new DataPortalResult<ProductTypeCachedList>(_list, null, null)); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="ProductTypeCachedList"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public ProductTypeCachedList() { // Use factory methods and do not use direct creation. ProductTypeItemSaved.Register(this); var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; AllowNew = false; AllowEdit = false; AllowRemove = false; RaiseListChangedEvents = rlce; } #endregion #region Saved Event Handler /// <summary> /// Handle Saved events of <see cref="ProductTypeItem"/> to update the list of <see cref="ProductTypeCachedInfo"/> objects. /// </summary> /// <param name="sender">The sender of the event.</param> /// <param name="e">The <see cref="Csla.Core.SavedEventArgs"/> instance containing the event data.</param> internal void ProductTypeItemSavedHandler(object sender, Csla.Core.SavedEventArgs e) { var obj = (ProductTypeItem)e.NewObject; if (((ProductTypeItem)sender).IsNew) { IsReadOnly = false; var rlce = RaiseListChangedEvents; RaiseListChangedEvents = true; Add(ProductTypeCachedInfo.LoadInfo(obj)); RaiseListChangedEvents = rlce; IsReadOnly = true; } else if (((ProductTypeItem)sender).IsDeleted) { for (int index = 0; index < this.Count; index++) { var child = this[index]; if (child.ProductTypeId == obj.ProductTypeId) { IsReadOnly = false; var rlce = RaiseListChangedEvents; RaiseListChangedEvents = true; this.RemoveItem(index); RaiseListChangedEvents = rlce; IsReadOnly = true; break; } } } else { for (int index = 0; index < this.Count; index++) { var child = this[index]; if (child.ProductTypeId == obj.ProductTypeId) { child.UpdatePropertiesOnSaved(obj); #if !WINFORMS var notifyCollectionChangedEventArgs = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, child, child, index); OnCollectionChanged(notifyCollectionChangedEventArgs); #else var listChangedEventArgs = new ListChangedEventArgs(ListChangedType.ItemChanged, index); OnListChanged(listChangedEventArgs); #endif break; } } } } #endregion #region Data Access /// <summary> /// Loads a <see cref="ProductTypeCachedList"/> collection from the database. /// </summary> protected void DataPortal_Fetch() { var args = new DataPortalHookArgs(); OnFetchPre(args); using (var dalManager = DalFactoryInvoices.GetManager()) { var dal = dalManager.GetProvider<IProductTypeCachedListDal>(); var data = dal.Fetch(); Fetch(data); } OnFetchPost(args); } /// <summary> /// Loads all <see cref="ProductTypeCachedList"/> collection items from the given list of ProductTypeCachedInfoDto. /// </summary> /// <param name="data">The list of <see cref="ProductTypeCachedInfoDto"/>.</param> private void Fetch(List<ProductTypeCachedInfoDto> data) { IsReadOnly = false; var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; foreach (var dto in data) { Add(DataPortal.FetchChild<ProductTypeCachedInfo>(dto)); } RaiseListChangedEvents = rlce; IsReadOnly = true; } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); #endregion #region ProductTypeItemSaved nested class // TODO: edit "ProductTypeCachedList.cs", uncomment the "OnDeserialized" method and add the following line: // TODO: ProductTypeItemSaved.Register(this); /// <summary> /// Nested class to manage the Saved events of <see cref="ProductTypeItem"/> /// to update the list of <see cref="ProductTypeCachedInfo"/> objects. /// </summary> private static class ProductTypeItemSaved { private static List<WeakReference> _references; private static bool Found(object obj) { return _references.Any(reference => Equals(reference.Target, obj)); } /// <summary> /// Registers a ProductTypeCachedList instance to handle Saved events. /// to update the list of <see cref="ProductTypeCachedInfo"/> objects. /// </summary> /// <param name="obj">The ProductTypeCachedList instance.</param> public static void Register(ProductTypeCachedList obj) { var mustRegister = _references == null; if (mustRegister) _references = new List<WeakReference>(); if (ProductTypeCachedList.SingleInstanceSavedHandler) _references.Clear(); if (!Found(obj)) _references.Add(new WeakReference(obj)); if (mustRegister) ProductTypeItem.ProductTypeItemSaved += ProductTypeItemSavedHandler; } /// <summary> /// Handles Saved events of <see cref="ProductTypeItem"/>. /// </summary> /// <param name="sender">The sender of the event.</param> /// <param name="e">The <see cref="Csla.Core.SavedEventArgs"/> instance containing the event data.</param> public static void ProductTypeItemSavedHandler(object sender, Csla.Core.SavedEventArgs e) { foreach (var reference in _references) { if (reference.IsAlive) ((ProductTypeCachedList) reference.Target).ProductTypeItemSavedHandler(sender, e); } } /// <summary> /// Removes event handling and clears all registered ProductTypeCachedList instances. /// </summary> public static void Unregister() { ProductTypeItem.ProductTypeItemSaved -= ProductTypeItemSavedHandler; _references = null; } } #endregion } }
using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; namespace NuKeeper.AzureDevOps { #pragma warning disable CA1056 // Uri properties should not be strings #pragma warning disable CA1707 // Identifiers should not contain underscores #pragma warning disable CA2227 // Collection properties should be read only public class Resource<T> { public int count { get; set; } public IEnumerable<T> value { get; set; } } public class Account { public string accountId { get; set; } public string accountName { get; set; } public string accountOwner { get; set; } public Dictionary<string, object> properties { get; set; } public string Mail { get { if (properties.ContainsKey("Mail")) { switch (properties["Mail"]) { case JObject mailObject: return mailObject.Property("$value").Value.ToString(); case JProperty mailProp: return mailProp.Value.ToString(); case string mailString: return mailString; } } return string.Empty; } } } public class Avatar { public string href { get; set; } } public class Links { public Avatar avatar { get; set; } } public class Creator { public string displayName { get; set; } public string url { get; set; } public Links _links { get; set; } public string id { get; set; } public string uniqueName { get; set; } public string imageUrl { get; set; } public string descriptor { get; set; } } public class GitRefs { public string name { get; set; } public string objectId { get; set; } public Creator creator { get; set; } public string url { get; set; } } public class GitRefsResource { public List<GitRefs> value { get; set; } public int count { get; set; } } public class PullRequestErrorResource { public string id { get; set; } public object innerException { get; set; } public string message { get; set; } public string typeName { get; set; } public string typeKey { get; set; } public int errorCode { get; set; } public int eventId { get; set; } } public class PullRequestResource { public int Count { get; set; } public IEnumerable<PullRequest> value { get; set; } } public class PullRequest { public AzureRepository AzureRepository { get; set; } public int PullRequestId { get; set; } public int CodeReviewId { get; set; } public string Status { get; set; } public DateTime CreationDate { get; set; } public string Title { get; set; } public string Description { get; set; } public string SourceRefName { get; set; } public string TargetRefName { get; set; } public string MergeStatus { get; set; } public string MergeId { get; set; } public string Url { get; set; } public bool SupportsIterations { get; set; } public Creator CreatedBy { get; set; } public IEnumerable<WebApiTagDefinition> labels { get; set; } // public CreatedBy CreatedBy { get; set; } // public Lastmergesourcecommit LastMergeSourceCommit { get; set; } // public Lastmergetargetcommit LastMergeTargetCommit { get; set; } // public Lastmergecommit LastMergeCommit { get; set; } // public IEnumerable<Reviewer> Reviewers { get; set; } } public class WebApiTagDefinition { public bool active { get; set; } public string id { get; set; } public string name { get; set; } public string url { get; set; } } public class ProjectResource { public int Count { get; set; } public IEnumerable<Project> value { get; set; } } public class Project { public string description { get; set; } public string id { get; set; } public string name { get; set; } public string url { get; set; } public string state { get; set; } public int revision { get; set; } public string visibility { get; set; } } public class PRRequest { public string sourceRefName { get; set; } public string targetRefName { get; set; } public string title { get; set; } public string description { get; set; } public GitPullRequestCompletionOptions completionOptions { get; set; } public Creator autoCompleteSetBy { get; set; } } public class GitPullRequestCompletionOptions { public bool deleteSourceBranch { get; set; } } public class AzureRepository { public string id { get; set; } public string name { get; set; } public string url { get; set; } public Project project { get; set; } public string defaultBranch { get; set; } public long size { get; set; } public string remoteUrl { get; set; } public string sshUrl { get; set; } } public class GitRepositories { public IEnumerable<AzureRepository> value { get; set; } public int count { get; set; } } public class LabelRequest { public string name { get; set; } } public class Label { public string id { get; set; } public string name { get; set; } public bool active { get; set; } public string url { get; set; } } public class LabelResource { public int count { get; set; } public IEnumerable<Label> value { get; set; } } public class GitItemResource { public int count { get; set; } public IEnumerable<GitItem> value { get; set; } } public class GitItem { public string path { get; set; } } }
//============================================================================== // TorqueLab -> // Copyright (c) 2015 All Right Reserved, http://nordiklab.com/ //------------------------------------------------------------------------------ //============================================================================== //============================================================================== function LabParamsDlg::onWake( %this ) { if (!$LabParamsTreeBuilt) Lab.buildSettingTree(true); foreach(%gui in LP_SettingsContainer) hide(%gui); hide(%this-->ParamStyles); LabParamsTree.expandAllGroups(true); //Get the predefined config files and add to menu LabCfg.getAllConfigs(); } //------------------------------------------------------------------------------ //============================================================================== function Lab::buildSettingTree( %this,%keepExisting ) { foreach(%paramArray in LabParamsGroup) { %name = %paramArray.internalName; %group = %paramArray.group; %containerName = "lpPage_"@%group@"_"@%name; if (!%keepExisting) delObj(%containerName); //%paramArray.groupLink = %group@"_"@%name; //TMP if (!isObject(%containerName)) { %newContainer = cloneObject(LP_SampleContainer,%containerName,%group@"_"@%name,LP_SettingsContainer); } %paramArray.optContainer = %containerName; LabParamsTree.addParam(%paramArray); %paramArray.container = %containerName-->Params_Stack; %paramArray.style = $LabParamsStyle; buildParamsArray(%paramArray); if (isObject(%paramArray.extraStack)) %this.buildParamsExtra(%paramArray,%containerName); LabParams.syncArray(%paramArray,true); } $LabParamsTreeBuilt = true; } //------------------------------------------------------------------------------ //============================================================================== function Lab::buildAllParamsExtra( %this ) { foreach(%paramArray in LabParamsGroup) { if (isObject(%paramArray.extraStack)) %this.buildParamsExtra(%paramArray,%paramArray.optContainer); } } //------------------------------------------------------------------------------ //============================================================================== function Lab::buildParamsExtra( %this,%paramArray,%container ) { %stackSrc = %paramArray.extraStack; %stackTgt = %container-->Params_Stack; devLog("buildParams Extra:",%stackSrc,"Add to",%container,"Stack",%stackTgt); foreach(%ctrl in %stackSrc) { %clone = cloneObject(%ctrl,"","",%stackTgt); } } //------------------------------------------------------------------------------ //============================================================================== function LabParamsDlg::regenerate( %this ) { LabParamsTree.clear(); %this.clearSettingsContainer(); Lab.buildSettingTree(); LabParamsTree.buildVisibleTree(); } //------------------------------------------------------------------------------ //============================================================================== function LabParamsDlg::onPreEditorSave( %this ) { //%this.clearSettingsContainer(); } //------------------------------------------------------------------------------ //============================================================================== function LabParamsDlg::onPostEditorSave( %this ) { } //------------------------------------------------------------------------------ //============================================================================== // Add default setting (Must set beginGroup and endGroup from caller) function LPD_ConfigNameMenu::onSelect( %this,%id,%text ) { %fileText = %text; %filename = fileBase(%fileText)@".cfg.cs"; %cfg = "tlab/core/settings/cfgs/"@%filename; if (!isFile(%cfg)) return; LPD_ConfigNameEdit.setText(%text); LabCfg.file = %cfg; } //------------------------------------------------------------------------------ //============================================================================== // Unreviewed //============================================================================== //============================================================================== function LabParamsDlg::toggleSettings( %this,%text) { %id = LabParamsTree.findItemByName(%text); if (%id <= 0) return; %selected = false; if (%id $= LabParamsTree.getSelectedItem()) %selected = true; if (!%this.isAwake()) { toggleDlg(LabParamsDlg); LabParamsTree.clearSelection(); LabParamsTree.selectItem(%id); } else if (%id $= LabParamsTree.getSelectedItem()) { toggleDlg(LabParamsDlg); } else { LabParamsTree.clearSelection(); LabParamsTree.selectItem(%id); } } //------------------------------------------------------------------------------ //============================================================================== function LabParamsDlg::setSelectedSettings( %this,%treeItemObj ) { if (!isObject(%treeItemObj)) { warnLog("Invalid settings item objects selected:",%treeItemObj); return; } foreach(%gui in LP_SettingsContainer) hide(%gui); show(%treeItemObj.itemContainer); } //------------------------------------------------------------------------------ //============================================================================== function LabParamsDlg::createSettingContainer( %this,%group,%subgroup ) { %containerName = "lpPage_"@%group@"_"@%subgroup; if (isObject(%containerName)) { warnLog("There's already an object using that name:",%containerName.getName(),"ObjId=",%containerName.getId()); return; } %newContainer = cloneObject(LP_SampleContainer); %newContainer.setName(%containerName); %newContainer.internalName = %group@"_"@%subgroup; LP_SettingsContainer.add(%newContainer); return %newContainer; } //============================================================================== //LabParamsDlg.clearSettingsContainer(); function LabParamsDlg::clearSettingsContainer( %this ) { foreach(%gui in LP_SettingsContainer) { if (%gui.internalName $= "core") continue; %delList = strAddWord(%delList,%gui.getId()); } foreach$(%id in %delList) delObj(%id); LabParamsDlg.cleared = true; } //------------------------------------------------------------------------------ //============================================================================== // Tree Builder functions //============================================================================== //============================================================================== // LabParamsTree Callbacks //============================================================================== //============================================================================== function LabParamsTree::expandAllGroups( %this,%buildTree ) { foreach$(%id in LabParamsTree.groupList) LabParamsTree.expandItem(%id); if (%buildTree) %this.buildVisibleTree(); } //------------------------------------------------------------------------------ //============================================================================== function LabParamsTree::onSelect( %this,%itemId ) { %text = %this.getItemText(%itemId); %value = %this.getItemValue(%itemId); %itemObj = $LabParamsItemObj[%itemId]; if (isObject(%itemObj)) { LabParamsDlg.setSelectedSettings(%itemObj); } } //------------------------------------------------------------------------------ //============================================================================== function LabParamsTree::onMouseUp( %this,%itemId,%clicks ) { %itemObj = $LabParamsItemObj[%itemId]; %text = %this.getItemText(%itemId); %value = %this.getItemValue(%itemId); return; } //------------------------------------------------------------------------------ //============================================================================== function LabParamsTree::addParam( %this,%paramArray) { %group = %paramArray.group; %link = %paramArray.groupLink; %name = %paramArray.displayName; %parentId = LabParamsTree.addSettingGroup(%group); %itemId = %this.findChildItemByName( %parentID,%name); if( !%itemId ) { %itemId = %this.insertItem( %parentID, %name,%link ); } %itemName = "soSettingItem_"@%link; %itemObj = newScriptObject(%itemName); %itemObj.groupParent = %group; %itemObj.groupItem = %name; $LabParamsItemObj[%itemId] = %itemObj; %itemObj.itemContainer = %paramArray.optContainer; } //------------------------------------------------------------------------------ //============================================================================== function LabParamsTree::addSettingGroup( %this,%group) { %tree = LabParamsTree; %groupTitle = $LabParamsGroupName[%group]; if (%groupTitle $="") %groupTitle = %group; %parentName = %tree.findItemByName( %group ); %groupId = %tree.findItemByValue( %group ); if( %groupId == 0 ) { %groupId = %tree.insertItem( 0, %groupTitle,%group ); LabParamsTree.groupList = strAddWord(LabParamsTree.groupList,%groupId,true); } return %groupId; } //------------------------------------------------------------------------------
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\EntityRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type ContentTypeRequest. /// </summary> public partial class ContentTypeRequest : BaseRequest, IContentTypeRequest { /// <summary> /// Constructs a new ContentTypeRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public ContentTypeRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified ContentType using POST. /// </summary> /// <param name="contentTypeToCreate">The ContentType to create.</param> /// <returns>The created ContentType.</returns> public System.Threading.Tasks.Task<ContentType> CreateAsync(ContentType contentTypeToCreate) { return this.CreateAsync(contentTypeToCreate, CancellationToken.None); } /// <summary> /// Creates the specified ContentType using POST. /// </summary> /// <param name="contentTypeToCreate">The ContentType to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created ContentType.</returns> public async System.Threading.Tasks.Task<ContentType> CreateAsync(ContentType contentTypeToCreate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; var newEntity = await this.SendAsync<ContentType>(contentTypeToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Deletes the specified ContentType. /// </summary> /// <returns>The task to await.</returns> public System.Threading.Tasks.Task DeleteAsync() { return this.DeleteAsync(CancellationToken.None); } /// <summary> /// Deletes the specified ContentType. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken) { this.Method = "DELETE"; await this.SendAsync<ContentType>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified ContentType. /// </summary> /// <returns>The ContentType.</returns> public System.Threading.Tasks.Task<ContentType> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the specified ContentType. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The ContentType.</returns> public async System.Threading.Tasks.Task<ContentType> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var retrievedEntity = await this.SendAsync<ContentType>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Updates the specified ContentType using PATCH. /// </summary> /// <param name="contentTypeToUpdate">The ContentType to update.</param> /// <returns>The updated ContentType.</returns> public System.Threading.Tasks.Task<ContentType> UpdateAsync(ContentType contentTypeToUpdate) { return this.UpdateAsync(contentTypeToUpdate, CancellationToken.None); } /// <summary> /// Updates the specified ContentType using PATCH. /// </summary> /// <param name="contentTypeToUpdate">The ContentType to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The updated ContentType.</returns> public async System.Threading.Tasks.Task<ContentType> UpdateAsync(ContentType contentTypeToUpdate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "PATCH"; var updatedEntity = await this.SendAsync<ContentType>(contentTypeToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IContentTypeRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IContentTypeRequest Expand(Expression<Func<ContentType, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IContentTypeRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IContentTypeRequest Select(Expression<Func<ContentType, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Initializes any collection properties after deserialization, like next requests for paging. /// </summary> /// <param name="contentTypeToInitialize">The <see cref="ContentType"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(ContentType contentTypeToInitialize) { if (contentTypeToInitialize != null && contentTypeToInitialize.AdditionalData != null) { if (contentTypeToInitialize.ColumnLinks != null && contentTypeToInitialize.ColumnLinks.CurrentPage != null) { contentTypeToInitialize.ColumnLinks.AdditionalData = contentTypeToInitialize.AdditionalData; object nextPageLink; contentTypeToInitialize.AdditionalData.TryGetValue("columnLinks@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { contentTypeToInitialize.ColumnLinks.InitializeNextPageRequest( this.Client, nextPageLinkString); } } } } } }
namespace Xbehave.Test { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using Xbehave.Test.Infrastructure; using Xunit; using Xunit.Abstractions; using Xunit.Sdk; // In order to save time // As a developer // I want to write a single scenario using many examples public class ExampleFeature : Feature { [Scenario] public void Examples(Type feature, ITestResultMessage[] results) { "Given a feature with a scenario with examples" .x(() => feature = typeof(SingleStepAndThreeExamples)); "When I run the scenarios" .x(() => results = this.Run<ITestResultMessage>(feature)); "Then each result should be a pass" .x(() => Assert.All(results, result => Assert.IsAssignableFrom<ITestPassed>(result))); "And there should be three results" .x(() => Assert.Equal(3, results.Length)); "And the display name of one result should contain '(x: 1, y: 2, sum: 3)'" .x(() => Assert.Single(results, result => result.Test.DisplayName.Contains("(x: 1, y: 2, sum: 3)"))); "And the display name of one result should contain '(x: 10, y: 20, sum: 30)'" .x(() => Assert.Single(results, result => result.Test.DisplayName.Contains("(x: 10, y: 20, sum: 30)"))); "And the display name of one result should contain '(x: 100, y: 200, sum: 300)'" .x(() => Assert.Single(results, result => result.Test.DisplayName.Contains("(x: 100, y: 200, sum: 300)"))); } [Scenario] public void SkippedExamples(Type feature, ITestResultMessage[] results) { "Given two examples with a problematic one skipped" .x(() => feature = typeof(TwoExamplesWithAProblematicOneSkipped)); "When I run the scenarios" .x(() => results = this.Run<ITestResultMessage>(feature)); "Then there should be two results" .x(() => Assert.Equal(2, results.Length)); "And one result should be a pass" .x(() => Assert.Single(results.OfType<ITestPassed>())); "And there should be no failures" .x(() => Assert.Empty(results.OfType<ITestFailed>())); "And one result should be a skip" .x(() => Assert.Single(results.OfType<ITestSkipped>())); } [Scenario] public void ExamplesWithArrays(Type feature, ITestResultMessage[] results) { "Given a feature with a scenario with array examples" .x(() => feature = typeof(ArrayExamples)); "When I run the scenarios" .x(() => results = this.Run<ITestResultMessage>(feature)); "Then there should be one result" .x(() => Assert.Single(results)); "And the display name of the result should contain '(words: [\"one\", \"two\"], numbers: [1, 2])'" .x(() => Assert.Contains("(words: [\"one\", \"two\"], numbers: [1, 2])", results.Single().Test.DisplayName)); } [Scenario] public void ExamplesWithMissingValues(Type feature, ITestResultMessage[] results) { "Given a scenario with three parameters, a single step and three examples each with one value" .x(() => feature = typeof(ScenarioWithThreeParametersASingleStepAndThreeExamplesEachWithOneValue)); "When I run the scenarios" .x(() => results = this.Run<ITestResultMessage>(feature)); "Then there should be three results" .x(() => Assert.Equal(3, results.Length)); "And each result should be a pass" .x(() => Assert.All(results, result => Assert.IsAssignableFrom<ITestPassed>(result))); "And each result should contain the example value" .x(() => Assert.All(results, result => Assert.Contains("example:", result.Test.DisplayName))); "And each result should not contain the missing values" .x(() => Assert.All(results, result => { Assert.DoesNotContain("missing1:", result.Test.DisplayName); Assert.DoesNotContain("missing2:", result.Test.DisplayName); })); } [Scenario] public void ExamplesWithTwoMissingResolvableGenericArguments(Type feature, ITestResultMessage[] results) { "Given a feature with a scenario with a single step and examples with one argument missing" .x(() => feature = typeof(SingleStepAndThreeExamplesWithMissingResolvableGenericArguments)); "When I run the scenarios" .x(() => results = this.Run<ITestResultMessage>(feature)); "Then there should be three results" .x(() => Assert.Equal(3, results.Length)); "And each result should be a pass" .x(() => Assert.All(results, result => Assert.IsAssignableFrom<ITestPassed>(result))); } [Scenario] public void GenericScenario(Type feature, ITestResultMessage[] results) { @"Given a feature with a scenario with one step, five type parameters and three examples each containing an Int32 value for an argument defined using the first type parameter, an Int64 value for an argument defined using the second type parameter, an String value for an argument defined using the third type parameter, an Int32 value for an argument defined using the fourth type parameter, an Int64 value for another argument defined using the fourth type parameter and an null value for an argument defined using the fifth type parameter" .x(() => feature = typeof(GenericScenarioFeature)); "When I run the scenarios" .x(() => results = this.Run<ITestResultMessage>(feature)); "Then there should be three results" .x(() => Assert.Equal(3, results.Length)); "And the display name of each result should contain \"<Int32, Int64, String, Object, Object>\"" .x(() => Assert.All(results, result => Assert.Contains("<Int32, Int64, String, Object, Object>", result.Test.DisplayName))); } [Scenario] public void BadlyFormattedSteps(Type feature, ITestResultMessage[] results) { "Given a feature with a scenario with example values one two and three and a step with the format \"Given {{3}}, {{4}} and {{5}}\"" .x(() => feature = typeof(FeatureWithAScenarioWithExampleValuesAndABadlyFormattedStep)); "When I run the scenarios" .x(() => results = this.Run<ITestResultMessage>(feature)); "Then there should be one result" .x(() => Assert.Single(results)); "And the result should not be a pass" .x(() => Assert.All(results, result => Assert.IsAssignableFrom<ITestPassed>(result))); "And the display name of the result should end with \"Given {{3}}, {{4}} and {{5}}\"" .x(() => Assert.EndsWith("Given {3}, {4} and {5}", results.Single().Test.DisplayName)); } [Scenario] public void InvalidExamples(Type feature, Exception exception, ITestResultMessage[] results) { "Given a feature with scenarios with invalid examples" .x(() => feature = typeof(FeatureWithTwoScenariosWithInvalidExamples)); "When I run the scenarios" .x(() => exception = Record.Exception(() => results = this.Run<ITestResultMessage>(feature))); "Then no exception should be thrown" .x(() => Assert.Null(exception)); "And there should be 2 results" .x(() => Assert.Equal(2, results.Length)); "And each result should be a failure" .x(() => Assert.All(results, result => Assert.IsAssignableFrom<ITestFailed>(result))); } [Scenario] public void DiscoveryFailure(Type feature, Exception exception, ITestResultMessage[] results) { "Given a feature with two scenarios with examples which throw errors" .x(() => feature = typeof(FeatureWithTwoScenariosWithExamplesWhichThrowErrors)); "When I run the scenarios" .x(() => exception = Record.Exception(() => results = this.Run<ITestResultMessage>(feature))); "Then no exception should be thrown" .x(() => Assert.Null(exception)); "And there should be 2 results" .x(() => Assert.Equal(2, results.Length)); "And each result should be a failure" .x(() => Assert.All(results, result => Assert.IsAssignableFrom<ITestFailed>(result))); } [Scenario] public void ExampleValueDisposalFailure(Type feature, Exception exception, ITestCaseCleanupFailure[] failures) { "Given a feature with two scenarios with examples with values which throw exceptions when disposed" .x(() => feature = typeof(FeatureWithTwoScenariosWithExamplesWithValuesWhichThrowErrorsWhenDisposed)); "When I run the scenarios" .x(() => exception = Record.Exception(() => failures = this.Run<ITestCaseCleanupFailure>(feature))); "Then no exception should be thrown" .x(() => Assert.Null(exception)); "And there should be 2 test case clean up failures" .x(() => Assert.Equal(2, failures.Length)); } [Scenario] public void DateTimeExampleValues(Type feature, ITestResultMessage[] results) { "Given scenarios expecting DateTime example values" .x(() => feature = typeof(ScenariosExpectingDateTimeValues)); "When I run the scenarios" .x(() => results = this.Run<ITestResultMessage>(feature)); "Then each result should be a pass" .x(() => Assert.All(results, result => Assert.IsAssignableFrom<ITestPassed>(result))); } [Scenario] public void DateTimeOffsetExampleValues(Type feature, ITestResultMessage[] results) { "Given scenarios expecting DateTimeOffset example values" .x(() => feature = typeof(ScenariosExpectingDateTimeOffsetValues)); "When I run the scenarios" .x(() => results = this.Run<ITestResultMessage>(feature)); "Then each result should be a pass" .x(() => Assert.All(results, result => Assert.IsAssignableFrom<ITestPassed>(result))); } [Scenario] public void GuidExampleValues(Type feature, ITestResultMessage[] results) { "Given scenarios expecting Guid example values" .x(() => feature = typeof(ScenariosExpectingGuidValues)); "When I run the scenarios" .x(() => results = this.Run<ITestResultMessage>(feature)); "Then each result should be a pass" .x(() => Assert.All(results, result => Assert.IsAssignableFrom<ITestPassed>(result))); } public sealed class BadExampleAttribute : MemberDataAttributeBase { public BadExampleAttribute() : base("Dummy", new object[0]) { } protected override object[] ConvertDataItem(MethodInfo testMethod, object item) => throw new NotImplementedException(); } public sealed class BadValuesExampleAttribute : DataAttribute { public override IEnumerable<object[]> GetData(MethodInfo testMethod) { yield return new object[] { new BadDisposable() }; } } public sealed class BadDisposable : IDisposable { [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations", Justification = "Test")] public void Dispose() => throw new InvalidOperationException(); } private static class SingleStepAndThreeExamples { private static int previousSum; [Scenario] [Example(1, 2, 3)] [Example(10, 20, 30)] [Example(100, 200, 300)] public static void Scenario(int x, int y, int sum) => $"Then as a distinct example the sum of {x} and {y} is {sum}" .x(() => { Assert.NotEqual(previousSum, sum); Assert.Equal(sum, x + y); previousSum = sum; }); } private static class TwoExamplesWithAProblematicOneSkipped { [Scenario] [Example(1)] [Example(2, Skip = "Because I can.")] public static void Scenario(int x) => $"Given {x}" .x(() => { if (x == 2) { throw new Exception(); } }); } private static class ArrayExamples { [Scenario] [Example(new[] { "one", "two" }, new[] { 1, 2 })] #pragma warning disable IDE0060 // Remove unused parameter public static void Scenario(string[] words, int[] numbers) => #pragma warning restore IDE0060 // Remove unused parameter "Given something" .x(() => { }); } private static class ScenarioWithThreeParametersASingleStepAndThreeExamplesEachWithOneValue { private static int previousExample; [Scenario] [Example(1)] [Example(2)] [Example(3)] public static void Scenario(int example, int missing1, object missing2) => "Then distinct examples are passed with the default values for missing arguments" .x(() => { Assert.NotEqual(previousExample, example); Assert.Equal(default, missing1); Assert.Equal(default, missing2); previousExample = example; }); } private static class SingleStepAndThreeExamplesWithMissingResolvableGenericArguments { private static object previousExample1; private static object previousExample2; [Scenario] [Example(1, "a")] [Example(3, "b")] [Example(5, "c")] public static void Scenario<T1, T2>(T1 example1, T2 example2, T1 missing1, T2 missing2) => "Then distinct examples are passed with the default values for missing arguments" .x(() => { Assert.NotEqual(previousExample1, example1); Assert.NotEqual(previousExample2, example2); Assert.Equal(default, missing1); Assert.Equal(default, missing2); previousExample1 = example1; previousExample2 = example2; }); } private static class GenericScenarioFeature { [Scenario] [Example(1, 2L, "a", 7, 7L, null)] [Example(3, 4L, "a", 8, 8L, null)] [Example(5, 6L, "a", 9, 8L, null)] #pragma warning disable IDE0060 // Remove unused parameter public static void Scenario<T1, T2, T3, T4, T5>(T1 a, T2 b, T3 c, T4 d, T4 e, T5 f) => #pragma warning restore IDE0060 // Remove unused parameter "Given" .x(() => { }); } private static class FeatureWithAScenarioWithExampleValuesAndAFormattedStep { [Scenario] [Example(1, 2, 3)] public static void Scenario(int x, int y, int z) => $"Given {x}, {y} and {z}" .x(() => { }); } private static class FeatureWithAScenarioWithNullExampleValuesAndAFormattedStep { [Scenario] [Example(null, null, null)] public static void Scenario(object x, object y, object z) => $"Given {x}, {y} and {z}" .x(() => { }); } private static class FeatureWithAScenarioWithExampleValuesAndABadlyFormattedStep { [Scenario] [Example(1, 2, 3)] #pragma warning disable IDE0060 // Remove unused parameter public static void Scenario(int x, int y, int z) => #pragma warning restore IDE0060 // Remove unused parameter "Given {3}, {4} and {5}" .x(() => { }); } private static class FeatureWithTwoScenariosWithInvalidExamples { [Scenario] [Example("a")] #pragma warning disable IDE0060 // Remove unused parameter public static void Scenario2(int i) #pragma warning restore IDE0060 // Remove unused parameter { } [Scenario] [Example(1, 2)] #pragma warning disable IDE0060 // Remove unused parameter public static void Scenario3(int i) #pragma warning restore IDE0060 // Remove unused parameter { } } private static class FeatureWithTwoScenariosWithExamplesWhichThrowErrors { [Scenario] [BadExample] #pragma warning disable IDE0060 // Remove unused parameter public static void Scenario1(int i) #pragma warning restore IDE0060 // Remove unused parameter { } [Scenario] [BadExample] #pragma warning disable IDE0060 // Remove unused parameter public static void Scenario2(int i) #pragma warning restore IDE0060 // Remove unused parameter { } } private static class FeatureWithTwoScenariosWithExamplesWithValuesWhichThrowErrorsWhenDisposed { [Scenario] [BadValuesExample] #pragma warning disable IDE0060 // Remove unused parameter public static void Scenario1(BadDisposable obj) #pragma warning restore IDE0060 // Remove unused parameter { } [Scenario] [BadValuesExample] #pragma warning disable IDE0060 // Remove unused parameter public static void Scenario2(BadDisposable obj) #pragma warning restore IDE0060 // Remove unused parameter { } } private static class ScenariosExpectingDateTimeValues { private static readonly DateTime expected = new DateTime(2014, 6, 26, 10, 48, 30); [Scenario] [Example("2014-06-26")] public static void Scenario1(DateTime actual) => "Then the actual is expected" .x(() => Assert.Equal(expected.Date, actual)); [Scenario] [Example("Thu, 26 Jun 2014 10:48:30")] [Example("2014-06-26T10:48:30.0000000")] public static void Scenario2(DateTime actual) => "Then the actual is expected" .x(() => Assert.Equal(expected, actual)); } private static class ScenariosExpectingDateTimeOffsetValues { private static readonly DateTimeOffset expected = new DateTimeOffset(new DateTime(2014, 6, 26, 10, 48, 30)); [Scenario] [Example("2014-06-26")] public static void Scenario1(DateTimeOffset actual) => "Then the actual is expected" .x(() => Assert.Equal(expected.Date, actual)); [Scenario] [Example("Thu, 26 Jun 2014 10:48:30")] [Example("2014-06-26T10:48:30.0000000")] public static void Scenario2(DateTimeOffset actual) => "Then the actual is expected" .x(() => Assert.Equal(expected, actual)); } private static class ScenariosExpectingGuidValues { private static readonly Guid expected = new Guid("0b228327-585d-47f9-a5ee-292f96ca085c"); [Scenario] [Example("0b228327-585d-47f9-a5ee-292f96ca085c")] [Example("0B228327-585D-47F9-A5EE-292F96CA085C")] [Example("0B228327585D47F9A5EE292F96CA085C")] public static void Scenario(Guid actual) => "Then the actual is expected" .x(() => Assert.Equal(expected, actual)); } } }
// Copyright (C) 2014 dot42 // // Original filename: Junit.Runner.cs // // 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. #pragma warning disable 1717 namespace Junit.Runner { /// <summary> /// <para>An interface to define how a test suite should be loaded. </para> /// </summary> /// <java-name> /// junit/runner/TestSuiteLoader /// </java-name> [Dot42.DexImport("junit/runner/TestSuiteLoader", AccessFlags = 1537)] public partial interface ITestSuiteLoader /* scope: __dot42__ */ { /// <java-name> /// load /// </java-name> [Dot42.DexImport("load", "(Ljava/lang/String;)Ljava/lang/Class;", AccessFlags = 1025)] global::System.Type Load(string suiteClassName) /* MethodBuilder.Create */ ; /// <java-name> /// reload /// </java-name> [Dot42.DexImport("reload", "(Ljava/lang/Class;)Ljava/lang/Class;", AccessFlags = 1025)] global::System.Type Reload(global::System.Type aClass) /* MethodBuilder.Create */ ; } /// <summary> /// <para>This class defines the current version of JUnit </para> /// </summary> /// <java-name> /// junit/runner/Version /// </java-name> [Dot42.DexImport("junit/runner/Version", AccessFlags = 33)] public partial class Version /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 0)] internal Version() /* MethodBuilder.Create */ { } /// <java-name> /// id /// </java-name> [Dot42.DexImport("id", "()Ljava/lang/String;", AccessFlags = 9)] public static string Id() /* MethodBuilder.Create */ { return default(string); } } /// <summary> /// <para>Base class for all test runners. This class was born live on stage in Sardinia during XP2000. </para> /// </summary> /// <java-name> /// junit/runner/BaseTestRunner /// </java-name> [Dot42.DexImport("junit/runner/BaseTestRunner", AccessFlags = 1057)] public abstract partial class BaseTestRunner : global::Junit.Framework.ITestListener /* scope: __dot42__ */ { /// <java-name> /// SUITE_METHODNAME /// </java-name> [Dot42.DexImport("SUITE_METHODNAME", "Ljava/lang/String;", AccessFlags = 25)] public const string SUITE_METHODNAME = "suite"; [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public BaseTestRunner() /* MethodBuilder.Create */ { } /// <summary> /// <para>A test started. </para> /// </summary> /// <java-name> /// startTest /// </java-name> [Dot42.DexImport("startTest", "(Ljunit/framework/Test;)V", AccessFlags = 33)] public virtual void StartTest(global::Junit.Framework.ITest test) /* MethodBuilder.Create */ { } /// <java-name> /// setPreferences /// </java-name> [Dot42.DexImport("setPreferences", "(Ljava/util/Properties;)V", AccessFlags = 12)] protected internal static void SetPreferences(global::Java.Util.Properties preferences) /* MethodBuilder.Create */ { } /// <java-name> /// getPreferences /// </java-name> [Dot42.DexImport("getPreferences", "()Ljava/util/Properties;", AccessFlags = 12)] protected internal static global::Java.Util.Properties GetPreferences() /* MethodBuilder.Create */ { return default(global::Java.Util.Properties); } /// <java-name> /// savePreferences /// </java-name> [Dot42.DexImport("savePreferences", "()V", AccessFlags = 9)] public static void SavePreferences() /* MethodBuilder.Create */ { } /// <java-name> /// setPreference /// </java-name> [Dot42.DexImport("setPreference", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1)] public virtual void SetPreference(string key, string value) /* MethodBuilder.Create */ { } /// <summary> /// <para>A test ended. </para> /// </summary> /// <java-name> /// endTest /// </java-name> [Dot42.DexImport("endTest", "(Ljunit/framework/Test;)V", AccessFlags = 33)] public virtual void EndTest(global::Junit.Framework.ITest test) /* MethodBuilder.Create */ { } /// <java-name> /// addError /// </java-name> [Dot42.DexImport("addError", "(Ljunit/framework/Test;Ljava/lang/Throwable;)V", AccessFlags = 33)] public virtual void AddError(global::Junit.Framework.ITest test, global::System.Exception t) /* MethodBuilder.Create */ { } /// <java-name> /// addFailure /// </java-name> [Dot42.DexImport("addFailure", "(Ljunit/framework/Test;Ljunit/framework/AssertionFailedError;)V", AccessFlags = 33)] public virtual void AddFailure(global::Junit.Framework.ITest test, global::Junit.Framework.AssertionFailedError t) /* MethodBuilder.Create */ { } /// <java-name> /// testStarted /// </java-name> [Dot42.DexImport("testStarted", "(Ljava/lang/String;)V", AccessFlags = 1025)] public abstract void TestStarted(string testName) /* MethodBuilder.Create */ ; /// <java-name> /// testEnded /// </java-name> [Dot42.DexImport("testEnded", "(Ljava/lang/String;)V", AccessFlags = 1025)] public abstract void TestEnded(string testName) /* MethodBuilder.Create */ ; /// <java-name> /// testFailed /// </java-name> [Dot42.DexImport("testFailed", "(ILjunit/framework/Test;Ljava/lang/Throwable;)V", AccessFlags = 1025)] public abstract void TestFailed(int status, global::Junit.Framework.ITest test, global::System.Exception t) /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the Test corresponding to the given suite. This is a template method, subclasses override runFailed(), clearStatus(). </para> /// </summary> /// <java-name> /// getTest /// </java-name> [Dot42.DexImport("getTest", "(Ljava/lang/String;)Ljunit/framework/Test;", AccessFlags = 1)] public virtual global::Junit.Framework.ITest GetTest(string suiteClassName) /* MethodBuilder.Create */ { return default(global::Junit.Framework.ITest); } /// <summary> /// <para>Returns the formatted string of the elapsed time. </para> /// </summary> /// <java-name> /// elapsedTimeAsString /// </java-name> [Dot42.DexImport("elapsedTimeAsString", "(J)Ljava/lang/String;", AccessFlags = 1)] public virtual string ElapsedTimeAsString(long runTime) /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Processes the command line arguments and returns the name of the suite class to run or null </para> /// </summary> /// <java-name> /// processArguments /// </java-name> [Dot42.DexImport("processArguments", "([Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 4)] protected internal virtual string ProcessArguments(string[] args) /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Sets the loading behaviour of the test runner </para> /// </summary> /// <java-name> /// setLoading /// </java-name> [Dot42.DexImport("setLoading", "(Z)V", AccessFlags = 1)] public virtual void SetLoading(bool enable) /* MethodBuilder.Create */ { } /// <summary> /// <para>Extract the class name from a String in VA/Java style </para> /// </summary> /// <java-name> /// extractClassName /// </java-name> [Dot42.DexImport("extractClassName", "(Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 1)] public virtual string ExtractClassName(string className) /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Truncates a String to the maximum length. </para> /// </summary> /// <java-name> /// truncate /// </java-name> [Dot42.DexImport("truncate", "(Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 9)] public static string Truncate(string s) /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Override to define how to handle a failed loading of a test suite. </para> /// </summary> /// <java-name> /// runFailed /// </java-name> [Dot42.DexImport("runFailed", "(Ljava/lang/String;)V", AccessFlags = 1028)] protected internal abstract void RunFailed(string message) /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the loaded Class for a suite name. </para> /// </summary> /// <java-name> /// loadSuiteClass /// </java-name> [Dot42.DexImport("loadSuiteClass", "(Ljava/lang/String;)Ljava/lang/Class;", AccessFlags = 4)] protected internal virtual global::System.Type LoadSuiteClass(string suiteClassName) /* MethodBuilder.Create */ { return default(global::System.Type); } /// <summary> /// <para>Clears the status message. </para> /// </summary> /// <java-name> /// clearStatus /// </java-name> [Dot42.DexImport("clearStatus", "()V", AccessFlags = 4)] protected internal virtual void ClearStatus() /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the loader to be used.</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>not present in JUnit4.10 </para></xrefdescription></xrefsect></para> /// </summary> /// <java-name> /// getLoader /// </java-name> [Dot42.DexImport("getLoader", "()Ljunit/runner/TestSuiteLoader;", AccessFlags = 1)] public virtual global::Junit.Runner.ITestSuiteLoader GetLoader() /* MethodBuilder.Create */ { return default(global::Junit.Runner.ITestSuiteLoader); } /// <java-name> /// useReloadingTestSuiteLoader /// </java-name> [Dot42.DexImport("useReloadingTestSuiteLoader", "()Z", AccessFlags = 4)] protected internal virtual bool UseReloadingTestSuiteLoader() /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// getPreference /// </java-name> [Dot42.DexImport("getPreference", "(Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 9)] public static string GetPreference(string key) /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// getPreference /// </java-name> [Dot42.DexImport("getPreference", "(Ljava/lang/String;I)I", AccessFlags = 9)] public static int GetPreference(string key, int dflt) /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>not present in JUnit4.10 </para></xrefdescription></xrefsect></para> /// </summary> /// <java-name> /// inVAJava /// </java-name> [Dot42.DexImport("inVAJava", "()Z", AccessFlags = 9)] public static bool InVAJava() /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// getFilteredTrace /// </java-name> [Dot42.DexImport("getFilteredTrace", "(Ljava/lang/Throwable;)Ljava/lang/String;", AccessFlags = 9)] public static string GetFilteredTrace(global::System.Exception exception) /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// getFilteredTrace /// </java-name> [Dot42.DexImport("getFilteredTrace", "(Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 9)] public static string GetFilteredTrace(string @string) /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// showStackRaw /// </java-name> [Dot42.DexImport("showStackRaw", "()Z", AccessFlags = 12)] protected internal static bool ShowStackRaw() /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// getPreferences /// </java-name> protected internal static global::Java.Util.Properties Preferences { [Dot42.DexImport("getPreferences", "()Ljava/util/Properties;", AccessFlags = 12)] get{ return GetPreferences(); } [Dot42.DexImport("setPreferences", "(Ljava/util/Properties;)V", AccessFlags = 12)] set{ SetPreferences(value); } } /// <summary> /// <para>Returns the loader to be used.</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>not present in JUnit4.10 </para></xrefdescription></xrefsect></para> /// </summary> /// <java-name> /// getLoader /// </java-name> public global::Junit.Runner.ITestSuiteLoader Loader { [Dot42.DexImport("getLoader", "()Ljunit/runner/TestSuiteLoader;", AccessFlags = 1)] get{ return GetLoader(); } } } }
using System; using Windows.UI.Xaml; using System.Threading.Tasks; using PlayStation_Gui.Services.SettingsServices; using Windows.ApplicationModel.Activation; using Windows.ApplicationModel.Background; using Windows.Foundation.Metadata; using Windows.UI.Notifications; using Windows.UI.Xaml.Controls; using Microsoft.ApplicationInsights; using PlayStation_App.Database; using PlayStation_Gui.Tools.Background; using PlayStation_Gui.Tools.Database; using PlayStation_Gui.Tools.Debug; using PlayStation_Gui.Views; using SQLite.Net.Platform.WinRT; namespace PlayStation_Gui { /// Documentation on APIs used in this page: /// https://github.com/Windows-XAML/Template10/wiki sealed partial class App : Template10.Common.BootStrapper { public static ISettingsService Settings; public static Frame Frame; public App() { Microsoft.ApplicationInsights.WindowsAppInitializer.InitializeAsync(); InitializeComponent(); #region App settings Settings = SettingsService.Instance; //RequestedTheme = _settings.AppTheme; #endregion #region Database var db = new UserAccountDataSource(new SQLitePlatformWinRT(), DatabaseWinRTHelpers.GetWinRTDatabasePath(StringConstants.UserDatabase)); db.CreateDatabase(); var dbs = new StickersDataSource(new SQLitePlatformWinRT(), DatabaseWinRTHelpers.GetWinRTDatabasePath(StringConstants.StampDatabase)); dbs.CreateDatabase(); #endregion } // runs even if restored from state public override async Task OnInitializeAsync(IActivatedEventArgs args) { // Setup Background var isIoT = ApiInformation.IsTypePresent("Windows.Devices.Gpio.GpioController"); if (!isIoT) { TileUpdateManager.CreateTileUpdaterForApplication().EnableNotificationQueue(true); //BackgroundTaskUtils.UnregisterBackgroundTasks(BackgroundTaskUtils.ToastBackgroundTaskName); //var task2 = await // BackgroundTaskUtils.RegisterBackgroundTask(BackgroundTaskUtils.ToastBackgroundTaskEntryPoint, // BackgroundTaskUtils.ToastBackgroundTaskName, new ToastNotificationActionTrigger(), // null); if (Settings.BackgroundEnable) { BackgroundTaskUtils.UnregisterBackgroundTasks(BackgroundTaskUtils.BackgroundTaskName); var task = await BackgroundTaskUtils.RegisterBackgroundTask(BackgroundTaskUtils.BackgroundTaskEntryPoint, BackgroundTaskUtils.BackgroundTaskName, new TimeTrigger(15, false), null); } } var launch = args as LaunchActivatedEventArgs; if (launch?.PreviousExecutionState == ApplicationExecutionState.NotRunning || launch?.PreviousExecutionState == ApplicationExecutionState.Terminated || launch?.PreviousExecutionState == ApplicationExecutionState.ClosedByUser) { // setup hamburger shell Frame = new Frame(); var nav = NavigationServiceFactory(BackButton.Attach, ExistingContent.Include, Frame); var shell = new Shell(nav); if (Shell.Instance.ViewModel.CurrentUser == null) { var userAccountDatabase = new UserAccountDatabase(new SQLitePlatformWinRT(), DatabaseWinRTHelpers.GetWinRTDatabasePath(StringConstants.UserDatabase)); if (await userAccountDatabase.HasDefaultAccounts()) { try { var result = await Shell.Instance.ViewModel.LoginDefaultUser(); } catch (Exception) { // error happened, send them to account page so we can check on it. } } } Window.Current.Content = shell; } await Task.CompletedTask; } public override async void OnResuming(object s, object e, AppExecutionState previousExecutionState) { base.OnResuming(s, e, previousExecutionState); // On Restore, if we have a frame, remake navigation so we can go back to previous pages. if (Frame != null) { var nav = NavigationServiceFactory(BackButton.Attach, ExistingContent.Include, Frame); var shell = (Shell)Window.Current.Content; shell.SetNav(nav); if (Shell.Instance.ViewModel.CurrentUser == null) { var userAccountDatabase = new UserAccountDatabase(new SQLitePlatformWinRT(), DatabaseWinRTHelpers.GetWinRTDatabasePath(StringConstants.UserDatabase)); if (await userAccountDatabase.HasDefaultAccounts()) { try { var result = await Shell.Instance.ViewModel.LoginDefaultUser(); } catch (Exception) { // error happened, send them to account page so we can check on it. } } } else { await Shell.Instance.ViewModel.UpdateTokens(); } var page = Frame.Content as MessagesPage; if (page != null) { Current.NavigationService.FrameFacade.BackRequested += page.ViewModel.MasterDetailViewControl.NavigationManager_BackRequested; } else { var threadpage = Frame.Content as FriendsPage; if (threadpage != null) { Current.NavigationService.FrameFacade.BackRequested += threadpage.ViewModel.MasterDetailViewControl.NavigationManager_BackRequested; } } } await Task.CompletedTask; } // runs only when not restored from state public override async Task OnStartAsync(StartKind startKind, IActivatedEventArgs args) { var launch = args as LaunchActivatedEventArgs; if (launch?.PreviousExecutionState == ApplicationExecutionState.NotRunning || launch?.PreviousExecutionState == ApplicationExecutionState.Terminated || launch?.PreviousExecutionState == ApplicationExecutionState.ClosedByUser) { if (Shell.Instance.ViewModel.CurrentUser == null) { var userAccountDatabase = new UserAccountDatabase(new SQLitePlatformWinRT(), DatabaseWinRTHelpers.GetWinRTDatabasePath(StringConstants.UserDatabase)); if (await userAccountDatabase.HasAccounts()) { if (await userAccountDatabase.HasDefaultAccounts()) { try { var result = await Shell.Instance.ViewModel.LoginDefaultUser(); NavigationService.Navigate(result ? typeof(Views.MainPage) : typeof(Views.AccountPage)); } catch (Exception) { // error happened, send them to account page so we can check on it. NavigationService.Navigate(typeof(Views.AccountPage)); } } else { NavigationService.Navigate(typeof(Views.AccountPage)); } } else { NavigationService.Navigate(typeof(Views.LoginPage)); } } else { NavigationService.Navigate(typeof(Views.MainPage)); } } await Task.CompletedTask; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using NUnit.Framework; namespace StructureMap.Testing { public static class Exception<T> where T : Exception { public static T ShouldBeThrownBy(Action action) { T exception = null; try { action(); } catch (Exception e) { exception = e.ShouldBeOfType<T>(); } if (exception == null) Assert.Fail("An exception was expected, but not thrown by the given action."); return exception; } } public delegate void MethodThatThrows(); public static class SpecificationExtensions { public static void ShouldContain<T>(this IEnumerable<T> actual, Func<T, bool> expected) { actual.Count().ShouldBeGreaterThan(0); T result = actual.FirstOrDefault(expected); Assert.That(result, Is.Not.EqualTo(default(T)), "Expected item was not found in the actual sequence"); } public static void ShouldHaveTheSameElementsAs<T>(this IEnumerable<T> actual, IEnumerable<T> expected) { var actualList = (actual is IList) ? (IList) actual : actual.ToList(); var expectedList = (expected is IList) ? (IList) expected : expected.ToList(); ShouldHaveTheSameElementsAs(actualList, expectedList); } public static void ShouldHaveTheSameElementsAs<T>(this IEnumerable<T> actual, params T[] expected) { var actualList = (actual is IList) ? (IList) actual : actual.ToList(); var expectedList = (expected is IList) ? (IList) expected : expected.ToList(); ShouldHaveTheSameElementsAs(actualList, expectedList); } public static void ShouldHaveTheSameElementsAs(this IList actual, IList expected) { actual.ShouldNotBeNull(); expected.ShouldNotBeNull(); try { actual.Count.ShouldEqual(expected.Count); for (var i = 0; i < actual.Count; i++) { actual[i].ShouldEqual(expected[i]); } } catch (Exception) { Debug.WriteLine("ACTUAL:"); foreach (var o in actual) { Debug.WriteLine(o); } throw; } } public static void ShouldBeFalse(this bool condition) { Assert.IsFalse(condition); } public static void ShouldBeTrue(this bool condition) { Assert.IsTrue(condition); } public static object ShouldEqual(this object actual, object expected) { Assert.AreEqual(expected, actual); return expected; } public static object ShouldNotEqual(this object actual, object expected) { Assert.AreNotEqual(expected, actual); return expected; } public static void ShouldBeNull(this object anObject) { Assert.IsNull(anObject); } public static void ShouldNotBeNull(this object anObject) { Assert.IsNotNull(anObject); } public static object ShouldBeTheSameAs(this object actual, object expected) { Assert.AreSame(expected, actual); return expected; } public static T IsType<T>(this object actual) { actual.ShouldBeOfType(typeof (T)); return (T) actual; } public static object ShouldNotBeTheSameAs(this object actual, object expected) { Assert.AreNotSame(expected, actual); return expected; } public static void ShouldBeOfType(this object actual, Type expected) { Assert.IsInstanceOf(expected, actual); } public static T ShouldBeOfType<T>(this object actual) { Assert.IsInstanceOf(typeof (T), actual); return (T) actual; } public static void ShouldNotBeOfType<T>(this object actual) { actual.ShouldNotBeOfType(typeof(T)); } public static void ShouldNotBeOfType(this object actual, Type expected) { Assert.IsNotInstanceOf(expected, actual); } public static void ShouldContain(this IList actual, object expected) { Assert.Contains(expected, actual); } public static IComparable ShouldBeGreaterThan(this IComparable arg1, IComparable arg2) { Assert.Greater(arg1, arg2); return arg2; } public static IComparable ShouldBeLessThan(this IComparable arg1, IComparable arg2) { Assert.Less(arg1, arg2); return arg2; } public static void ShouldBeEmpty(this ICollection collection) { Assert.IsEmpty(collection); } public static void ShouldBeEmpty(this string aString) { Assert.IsEmpty(aString); } public static void ShouldNotBeEmpty(this ICollection collection) { Assert.IsNotEmpty(collection); } public static string ShouldNotBeEmpty(this string aString) { Assert.IsNotEmpty(aString); return aString; } public static void ShouldContain(this string actual, string expected) { StringAssert.Contains(expected, actual); } public static string ShouldNotContain(this string actual, string expected) { Assert.IsTrue(!actual.Contains(expected)); return actual; } public static string ShouldBeEqualIgnoringCase(this string actual, string expected) { StringAssert.AreEqualIgnoringCase(expected, actual); return expected; } public static void ShouldEndWith(this string actual, string expected) { StringAssert.EndsWith(expected, actual); } public static void ShouldStartWith(this string actual, string expected) { StringAssert.StartsWith(expected, actual); } public static void ShouldContainErrorMessage(this Exception exception, string expected) { StringAssert.Contains(expected, exception.Message); } public static Exception ShouldBeThrownBy(this Type exceptionType, MethodThatThrows method) { Exception exception = null; try { method(); } catch (Exception e) { Assert.AreEqual(exceptionType, e.GetType()); exception = e; } if (exception == null) { Assert.Fail(String.Format("Expected {0} to be thrown.", exceptionType.FullName)); } return exception; } public static void ShouldEqualSqlDate(this DateTime actual, DateTime expected) { var timeSpan = actual - expected; Assert.Less(Math.Abs(timeSpan.TotalMilliseconds), 3); } } }
// 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! namespace Google.Cloud.Compute.V1.Snippets { using Google.Api.Gax; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class AllGeneratedInterconnectLocationsClientSnippets { /// <summary>Snippet for Get</summary> public void GetRequestObject() { // Snippet: Get(GetInterconnectLocationRequest, CallSettings) // Create client InterconnectLocationsClient interconnectLocationsClient = InterconnectLocationsClient.Create(); // Initialize request argument(s) GetInterconnectLocationRequest request = new GetInterconnectLocationRequest { Project = "", InterconnectLocation = "", }; // Make the request InterconnectLocation response = interconnectLocationsClient.Get(request); // End snippet } /// <summary>Snippet for GetAsync</summary> public async Task GetRequestObjectAsync() { // Snippet: GetAsync(GetInterconnectLocationRequest, CallSettings) // Additional: GetAsync(GetInterconnectLocationRequest, CancellationToken) // Create client InterconnectLocationsClient interconnectLocationsClient = await InterconnectLocationsClient.CreateAsync(); // Initialize request argument(s) GetInterconnectLocationRequest request = new GetInterconnectLocationRequest { Project = "", InterconnectLocation = "", }; // Make the request InterconnectLocation response = await interconnectLocationsClient.GetAsync(request); // End snippet } /// <summary>Snippet for Get</summary> public void Get() { // Snippet: Get(string, string, CallSettings) // Create client InterconnectLocationsClient interconnectLocationsClient = InterconnectLocationsClient.Create(); // Initialize request argument(s) string project = ""; string interconnectLocation = ""; // Make the request InterconnectLocation response = interconnectLocationsClient.Get(project, interconnectLocation); // End snippet } /// <summary>Snippet for GetAsync</summary> public async Task GetAsync() { // Snippet: GetAsync(string, string, CallSettings) // Additional: GetAsync(string, string, CancellationToken) // Create client InterconnectLocationsClient interconnectLocationsClient = await InterconnectLocationsClient.CreateAsync(); // Initialize request argument(s) string project = ""; string interconnectLocation = ""; // Make the request InterconnectLocation response = await interconnectLocationsClient.GetAsync(project, interconnectLocation); // End snippet } /// <summary>Snippet for List</summary> public void ListRequestObject() { // Snippet: List(ListInterconnectLocationsRequest, CallSettings) // Create client InterconnectLocationsClient interconnectLocationsClient = InterconnectLocationsClient.Create(); // Initialize request argument(s) ListInterconnectLocationsRequest request = new ListInterconnectLocationsRequest { OrderBy = "", Project = "", Filter = "", ReturnPartialSuccess = false, }; // Make the request PagedEnumerable<InterconnectLocationList, InterconnectLocation> response = interconnectLocationsClient.List(request); // Iterate over all response items, lazily performing RPCs as required foreach (InterconnectLocation item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (InterconnectLocationList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (InterconnectLocation item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<InterconnectLocation> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (InterconnectLocation item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListAsync</summary> public async Task ListRequestObjectAsync() { // Snippet: ListAsync(ListInterconnectLocationsRequest, CallSettings) // Create client InterconnectLocationsClient interconnectLocationsClient = await InterconnectLocationsClient.CreateAsync(); // Initialize request argument(s) ListInterconnectLocationsRequest request = new ListInterconnectLocationsRequest { OrderBy = "", Project = "", Filter = "", ReturnPartialSuccess = false, }; // Make the request PagedAsyncEnumerable<InterconnectLocationList, InterconnectLocation> response = interconnectLocationsClient.ListAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((InterconnectLocation item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((InterconnectLocationList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (InterconnectLocation item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<InterconnectLocation> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (InterconnectLocation item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for List</summary> public void List() { // Snippet: List(string, string, int?, CallSettings) // Create client InterconnectLocationsClient interconnectLocationsClient = InterconnectLocationsClient.Create(); // Initialize request argument(s) string project = ""; // Make the request PagedEnumerable<InterconnectLocationList, InterconnectLocation> response = interconnectLocationsClient.List(project); // Iterate over all response items, lazily performing RPCs as required foreach (InterconnectLocation item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (InterconnectLocationList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (InterconnectLocation item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<InterconnectLocation> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (InterconnectLocation item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListAsync</summary> public async Task ListAsync() { // Snippet: ListAsync(string, string, int?, CallSettings) // Create client InterconnectLocationsClient interconnectLocationsClient = await InterconnectLocationsClient.CreateAsync(); // Initialize request argument(s) string project = ""; // Make the request PagedAsyncEnumerable<InterconnectLocationList, InterconnectLocation> response = interconnectLocationsClient.ListAsync(project); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((InterconnectLocation item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((InterconnectLocationList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (InterconnectLocation item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<InterconnectLocation> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (InterconnectLocation item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } } }
using System; using System.IO; using System.Collections.Generic; using System.Text; using LumiSoft.Net.SIP.Message; namespace LumiSoft.Net.SIP.Stack { /// <summary> /// SIP server response. Related RFC 3261. /// </summary> public class SIP_Response : SIP_Message { private SIP_Request m_pRequest = null; private double m_SipVersion = 2.0d; private int m_StatusCode = 100; private string m_ReasonPhrase = ""; /// <summary> /// Default constructor. /// </summary> public SIP_Response() { } /// <summary> /// SIP_Request.CreateResponse constructor. /// </summary> /// <param name="request">Owner request.</param> internal SIP_Response(SIP_Request request) { m_pRequest = request; } #region method Copy /// <summary> /// Clones this request. /// </summary> /// <returns>Returns new cloned request.</returns> public SIP_Response Copy() { SIP_Response retVal = SIP_Response.Parse(this.ToByteData()); return retVal; } #endregion #region method Validate /// <summary> /// Checks if SIP response has all required values as response line,header fields and their values. /// Throws Exception if not valid SIP response. /// </summary> public void Validate() { // Via: + branch prameter // To: // From: // CallID: // CSeq if(this.Via.GetTopMostValue() == null){ throw new SIP_ParseException("Via: header field is missing !"); } if(this.Via.GetTopMostValue().Branch == null){ throw new SIP_ParseException("Via: header fields branch parameter is missing !"); } if(this.To == null){ throw new SIP_ParseException("To: header field is missing !"); } if(this.From == null){ throw new SIP_ParseException("From: header field is missing !"); } if(this.CallID == null){ throw new SIP_ParseException("CallID: header field is missing !"); } if(this.CSeq == null){ throw new SIP_ParseException("CSeq: header field is missing !"); } // TODO: INVITE 2xx must have only 1 contact header with SIP or SIPS. } #endregion #region method Parse /// <summary> /// Parses SIP_Response from byte array. /// </summary> /// <param name="data">Valid SIP response data.</param> /// <returns>Returns parsed SIP_Response obeject.</returns> /// <exception cref="ArgumentNullException">Raised when <b>data</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public static SIP_Response Parse(byte[] data) { if(data == null){ throw new ArgumentNullException("data"); } return Parse(new MemoryStream(data)); } /// <summary> /// Parses SIP_Response from stream. /// </summary> /// <param name="stream">Stream what contains valid SIP response.</param> /// <returns>Returns parsed SIP_Response obeject.</returns> /// <exception cref="ArgumentNullException">Raised when <b>stream</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public static SIP_Response Parse(Stream stream) { /* Syntax: SIP-Version SP Status-Code SP Reason-Phrase SIP-Message */ if(stream == null){ throw new ArgumentNullException("stream"); } SIP_Response retVal = new SIP_Response(); // Parse Response-line StreamLineReader r = new StreamLineReader(stream); r.Encoding = "utf-8"; string[] version_code_text = r.ReadLineString().Split(new char[]{' '},3); if(version_code_text.Length != 3){ throw new SIP_ParseException("Invalid SIP Status-Line syntax ! Syntax: {SIP-Version SP Status-Code SP Reason-Phrase}."); } // SIP-Version try{ retVal.SipVersion = Convert.ToDouble(version_code_text[0].Split('/')[1],System.Globalization.NumberFormatInfo.InvariantInfo); } catch{ throw new SIP_ParseException("Invalid Status-Line SIP-Version value !"); } // Status-Code try{ retVal.StatusCode = Convert.ToInt32(version_code_text[1]); } catch{ throw new SIP_ParseException("Invalid Status-Line Status-Code value !"); } // Reason-Phrase retVal.ReasonPhrase = version_code_text[2]; // Parse SIP-Message retVal.InternalParse(stream); return retVal; } #endregion #region method ToStream /// <summary> /// Stores SIP_Response to specified stream. /// </summary> /// <param name="stream">Stream where to store.</param> public void ToStream(Stream stream) { // Status-Line = SIP-Version SP Status-Code SP Reason-Phrase CRLF // Add response-line byte[] responseLine = Encoding.UTF8.GetBytes("SIP/" + this.SipVersion.ToString("f1").Replace(',','.') + " " + this.StatusCode + " " + this.ReasonPhrase + "\r\n"); stream.Write(responseLine,0,responseLine.Length); // Add SIP-message this.InternalToStream(stream); } #endregion #region method ToByteData /// <summary> /// Converts this response to raw srver response data. /// </summary> /// <returns></returns> public byte[] ToByteData() { MemoryStream retVal = new MemoryStream(); ToStream(retVal); return retVal.ToArray(); } #endregion #region method ToString /// <summary> /// Returns response as string. /// </summary> /// <returns>Returns response as string.</returns> public override string ToString() { return Encoding.UTF8.GetString(ToByteData()); } #endregion #region Properties Implementation /// <summary> /// Gets SIP request which response it is. This value is null if this is stateless response. /// </summary> public SIP_Request Request { get{ return m_pRequest; } } /// <summary> /// Gets or sets SIP version. /// </summary> /// <exception cref="ArgumentException">Is raised when invalid SIP version value passed.</exception> public double SipVersion { get{ return m_SipVersion; } set{ if(value < 1){ throw new ArgumentException("Property SIP version must be >= 1.0 !"); } m_SipVersion = value; } } /// <summary> /// Gets SIP status code type. /// </summary> public SIP_StatusCodeType StatusCodeType { get{ if(m_StatusCode >= 100 && m_StatusCode < 200){ return SIP_StatusCodeType.Provisional; } else if(m_StatusCode >= 200 && m_StatusCode < 300){ return SIP_StatusCodeType.Success; } else if(m_StatusCode >= 300 && m_StatusCode < 400){ return SIP_StatusCodeType.Redirection; } else if(m_StatusCode >= 400 && m_StatusCode < 500){ return SIP_StatusCodeType.RequestFailure; } else if(m_StatusCode >= 500 && m_StatusCode < 600){ return SIP_StatusCodeType.ServerFailure; } else if(m_StatusCode >= 600 && m_StatusCode < 700){ return SIP_StatusCodeType.GlobalFailure; } else{ throw new Exception("Unknown SIP StatusCodeType !"); } } } /// <summary> /// Gets or sets response status code. This value must be between 100 and 999. /// </summary> /// <exception cref="ArgumentException">Is raised when value is out of allowed range.</exception> public int StatusCode { get{ return m_StatusCode; } set{ if(value < 1 || value > 999){ throw new ArgumentException("Property 'StatusCode' value must be >= 100 && <= 999 !"); } m_StatusCode = value; } } /// <summary> /// Gets or sets reponse reasong phrase. This just StatusCode describeing text. /// </summary> public string ReasonPhrase { get{ return m_ReasonPhrase; } set{ if(value == null){ throw new ArgumentNullException("ReasonPhrase"); } m_ReasonPhrase = value; } } /// <summary> /// Gets or sets SIP Status-Code with Reason-Phrase (Status-Code SP Reason-Phrase). /// </summary> public string StatusCode_ReasonPhrase { get{ return m_StatusCode + " " + m_ReasonPhrase; } set{ // Status-Code SP Reason-Phrase if(value == null){ throw new ArgumentNullException("StatusCode_ReasonPhrase"); } string[] code_reason = value.Split(new char[]{' '},2); if(code_reason.Length != 2){ throw new ArgumentException("Invalid property 'StatusCode_ReasonPhrase' Reason-Phrase value !"); } try{ this.StatusCode = Convert.ToInt32(code_reason[0]); } catch{ throw new ArgumentException("Invalid property 'StatusCode_ReasonPhrase' Status-Code value !"); } this.ReasonPhrase = code_reason[1]; } } #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.Collections.Generic; using System.Linq; using Xunit; namespace System.MemoryTests { public static partial class ReadOnlyMemoryTests { [Fact] public static void EqualityTrue() { int[] a = { 91, 92, 93, 94, 95 }; var left = new ReadOnlyMemory<int>(a, 2, 3); var right = new ReadOnlyMemory<int>(a, 2, 3); Assert.True(left.Equals(right)); Assert.True(right.Equals(left)); } [Fact] public static void EqualityReflexivity() { int[] a = { 91, 92, 93, 94, 95 }; var left = new ReadOnlyMemory<int>(a, 2, 3); Assert.True(left.Equals(left)); } [Fact] public static void EqualityIncludesLength() { int[] a = { 91, 92, 93, 94, 95 }; var left = new ReadOnlyMemory<int>(a, 2, 1); var right = new ReadOnlyMemory<int>(a, 2, 3); Assert.False(left.Equals(right)); Assert.False(right.Equals(left)); } [Fact] public static void EqualityIncludesBase() { int[] a = { 91, 92, 93, 94, 95 }; var left = new ReadOnlyMemory<int>(a, 1, 3); var right = new ReadOnlyMemory<int>(a, 2, 3); Assert.False(left.Equals(right)); Assert.False(right.Equals(left)); } [Fact] public static void EqualityComparesRangeNotContent() { var left = new ReadOnlyMemory<int>(new int[] { 0, 1, 2 }, 1, 1); var right = new ReadOnlyMemory<int>(new int[] { 0, 1, 2 }, 1, 1); Assert.False(left.Equals(right)); Assert.False(right.Equals(left)); } [Fact] public static void EmptyMemoryNotUnified() { var left = new ReadOnlyMemory<int>(new int[0]); var right = new ReadOnlyMemory<int>(new int[0]); ReadOnlyMemory<int> memoryFromNonEmptyArrayButWithZeroLength = new ReadOnlyMemory<int>(new int[1] { 123 }).Slice(0, 0); Assert.False(left.Equals(right)); Assert.False(right.Equals(left)); Assert.False(memoryFromNonEmptyArrayButWithZeroLength.Equals(left)); Assert.False(left.Equals(memoryFromNonEmptyArrayButWithZeroLength)); // Empty property is equal left = ReadOnlyMemory<int>.Empty; right = ReadOnlyMemory<int>.Empty; Assert.True(left.Equals(right)); Assert.True(right.Equals(left)); } [Fact] public static void EqualityThroughInterface_True() { int[] array = { 10, 11, 12, 13, 14 }; ReadOnlyMemory<int> left = new ReadOnlyMemory<int>(array, 2, 3); ReadOnlyMemory<int> right = new ReadOnlyMemory<int>(array, 2, 3); IEquatable<ReadOnlyMemory<int>> leftAsEquatable = left; IEquatable<ReadOnlyMemory<int>> rightAsEquatable = right; Assert.True(leftAsEquatable.Equals(right)); Assert.True(rightAsEquatable.Equals(left)); } [Fact] public static void EqualityThroughInterface_Reflexivity() { int[] array = { 42, 43, 44, 45, 46 }; ReadOnlyMemory<int> left = new ReadOnlyMemory<int>(array, 2, 3); IEquatable<ReadOnlyMemory<int>> leftAsEquatable = left; Assert.True(leftAsEquatable.Equals(left)); } [Fact] public static void EqualityThroughInterface_IncludesLength() { int[] array = { 42, 43, 44, 45, 46 }; ReadOnlyMemory<int> baseline = new ReadOnlyMemory<int>(array, 2, 3); ReadOnlyMemory<int> equalRangeButLength = new ReadOnlyMemory<int>(array, 2, 2); IEquatable<ReadOnlyMemory<int>> baselineAsEquatable = baseline; IEquatable<ReadOnlyMemory<int>> anotherOneAsEquatable = equalRangeButLength; Assert.False(baselineAsEquatable.Equals(equalRangeButLength)); Assert.False(anotherOneAsEquatable.Equals(baseline)); } [Fact] public static void EqualityThroughInterface_IncludesBase() { int[] array = { 42, 43, 44, 45, 46 }; ReadOnlyMemory<int> baseline = new ReadOnlyMemory<int>(array, 2, 3); ReadOnlyMemory<int> equalLengthButRange = new ReadOnlyMemory<int>(array, 1, 3); IEquatable<ReadOnlyMemory<int>> baselineAsEquatable = baseline; IEquatable<ReadOnlyMemory<int>> anotherOneAsEquatable = equalLengthButRange; Assert.False(baselineAsEquatable.Equals(equalLengthButRange)); Assert.False(anotherOneAsEquatable.Equals(baseline)); } [Fact] public static void EqualityThroughInterface_ComparesRangeNotContent() { ReadOnlyMemory<int> baseline = new ReadOnlyMemory<int>(new[] { 1, 2, 3, 4, 5, 6 }, 2, 3); ReadOnlyMemory<int> duplicate = new ReadOnlyMemory<int>(new[] { 1, 2, 3, 4, 5, 6 }, 2, 3); IEquatable<ReadOnlyMemory<int>> baselineAsEquatable = baseline; IEquatable<ReadOnlyMemory<int>> duplicateAsEquatable = duplicate; Assert.False(baselineAsEquatable.Equals(duplicate)); Assert.False(duplicateAsEquatable.Equals(baseline)); } [Fact] public static void EqualityThroughInterface_Strings() { string[] array = { "A", "B", "C", "D", "E", "F" }; string[] anotherArray = { "A", "B", "C", "D", "E", "F" }; ReadOnlyMemory<string> baseline = new ReadOnlyMemory<string>(array, 2, 3); IEquatable<ReadOnlyMemory<string>> baselineAsEquatable = baseline; ReadOnlyMemory<string> equalRangeAndLength = new ReadOnlyMemory<string>(array, 2, 3); ReadOnlyMemory<string> equalRangeButLength = new ReadOnlyMemory<string>(array, 2, 2); ReadOnlyMemory<string> equalLengthButReference = new ReadOnlyMemory<string>(array, 3, 3); ReadOnlyMemory<string> differentArraySegmentAsMemory = new ReadOnlyMemory<string>(anotherArray, 2, 3); Assert.True(baselineAsEquatable.Equals(baseline)); // Reflexivity Assert.True(baselineAsEquatable.Equals(equalRangeAndLength)); // Range check & length check Assert.False(baselineAsEquatable.Equals(equalRangeButLength)); // Length check Assert.False(baselineAsEquatable.Equals(equalLengthButReference)); // Range check Assert.True(baseline.Span.SequenceEqual(differentArraySegmentAsMemory.Span)); Assert.False(baselineAsEquatable.Equals(differentArraySegmentAsMemory)); // Doesn't check for content equality } [Fact] public static void EqualityThroughInterface_Chars() { char[] array = { 'H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!' }; string str = new string(array); // To prevent both string literals being interned therefore having same reference string anotherStr = new string(array); ReadOnlyMemory<char> baseline = str.AsMemory(2, 3); IEquatable<ReadOnlyMemory<char>> baselineAsEquatable = baseline; ReadOnlyMemory<char> equalRangeAndLength = str.AsMemory(2, 3); ReadOnlyMemory<char> equalRangeButLength = str.AsMemory(2, 2); ReadOnlyMemory<char> equalLengthButReference = str.AsMemory(3, 3); ReadOnlyMemory<char> differentArraySegmentAsMemory = anotherStr.AsMemory(2, 3); Assert.True(baselineAsEquatable.Equals(baseline)); // Reflexivity Assert.True(baselineAsEquatable.Equals(equalRangeAndLength)); // Range check & length check Assert.False(baselineAsEquatable.Equals(equalRangeButLength)); // Length check Assert.False(baselineAsEquatable.Equals(equalLengthButReference)); // Range check Assert.True(baseline.Span.SequenceEqual(differentArraySegmentAsMemory.Span)); Assert.False(baselineAsEquatable.Equals(differentArraySegmentAsMemory)); // Doesn't check for content equality } [Theory] [MemberData(nameof(ValidArraySegments))] public static void MemoryReferencingSameMemoryAreEqualInEveryAspect(byte[] bytes, int start, int length) { var memory = new ReadOnlyMemory<byte>(bytes, start, length); var pointingToSameMemory = new ReadOnlyMemory<byte>(bytes, start, length); ReadOnlyMemory<byte> structCopy = memory; Assert.True(memory.Equals(pointingToSameMemory)); Assert.True(pointingToSameMemory.Equals(memory)); Assert.True(memory.Equals(structCopy)); Assert.True(structCopy.Equals(memory)); } [Theory] [MemberData(nameof(ValidArraySegments))] public static void MemoryOfEqualValuesAreNotEqual(byte[] bytes, int start, int length) { byte[] bytesCopy = bytes.ToArray(); var memory = new ReadOnlyMemory<byte>(bytes, start, length); var ofSameValues = new ReadOnlyMemory<byte>(bytesCopy, start, length); Assert.False(memory.Equals(ofSameValues)); Assert.False(ofSameValues.Equals(memory)); } [Theory] [MemberData(nameof(ValidArraySegments))] public static void MemoryOfDifferentValuesAreNotEqual(byte[] bytes, int start, int length) { byte[] differentBytes = bytes.Select(value => ++value).ToArray(); var memory = new ReadOnlyMemory<byte>(bytes, start, length); var ofDifferentValues = new ReadOnlyMemory<byte>(differentBytes, start, length); Assert.False(memory.Equals(ofDifferentValues)); Assert.False(ofDifferentValues.Equals(memory)); } public static IEnumerable<object[]> ValidArraySegments { get { return new List<object[]> { new object[] { new byte[1] { 0 }, 0, 1}, new object[] { new byte[2] { 0, 0 }, 0, 2}, new object[] { new byte[2] { 0, 0 }, 0, 1}, new object[] { new byte[2] { 0, 0 }, 1, 1}, new object[] { new byte[3] { 0, 0, 0 }, 0, 3}, new object[] { new byte[3] { 0, 0, 0 }, 0, 2}, new object[] { new byte[3] { 0, 0, 0 }, 1, 2}, new object[] { new byte[3] { 0, 0, 0 }, 1, 1}, new object[] { Enumerable.Range(0, 100000).Select(i => (byte)i).ToArray(), 0, 100000 } }; } } public static IEnumerable<object[]> FullArraySegments { get { return new List<object[]> { new object[] { new byte[1] { 0 } }, new object[] { new byte[2] { 0, 0 } }, new object[] { new byte[3] { 0, 0, 0 } }, new object[] { Enumerable.Range(0, 100000).Select(i => (byte)i).ToArray() } }; } } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Globalization; using NUnit.Framework; using QuantConnect.Data; using QuantConnect.Data.Market; using QuantConnect.Indicators; namespace QuantConnect.Tests.Indicators { /// <summary> /// Provides helper methods for testing indicatora /// </summary> public static class TestHelper { /// <summary> /// Gets a stream of IndicatorDataPoints that can be fed to an indicator. The data stream starts at {DateTime.Today, 1m} and /// increasing at {1 second, 1m} /// </summary> /// <param name="count">The number of data points to stream</param> /// <param name="valueProducer">Function to produce the value of the data, null to use the index</param> /// <returns>A stream of IndicatorDataPoints</returns> public static IEnumerable<IndicatorDataPoint> GetDataStream(int count, Func<int, decimal> valueProducer = null) { var reference = DateTime.Today; valueProducer = valueProducer ?? (x => x); for (int i = 0; i < count; i++) { yield return new IndicatorDataPoint(reference.AddSeconds(i), valueProducer.Invoke(i)); } } /// <summary> /// Compare the specified indicator against external data using the spy_with_indicators.txt file. /// The 'Close' column will be fed to the indicator as input /// </summary> /// <param name="indicator">The indicator under test</param> /// <param name="targetColumn">The column with the correct answers</param> /// <param name="epsilon">The maximum delta between expected and actual</param> public static void TestIndicator(IndicatorBase<IndicatorDataPoint> indicator, string targetColumn, double epsilon = 1e-3) { TestIndicator(indicator, "spy_with_indicators.txt", targetColumn, (i, expected) => Assert.AreEqual(expected, (double) i.Current.Value, epsilon)); } /// <summary> /// Compare the specified indicator against external data using the specificied comma delimited text file. /// The 'Close' column will be fed to the indicator as input /// </summary> /// <param name="indicator">The indicator under test</param> /// <param name="externalDataFilename"></param> /// <param name="targetColumn">The column with the correct answers</param> /// <param name="customAssertion">Sets custom assertion logic, parameter is the indicator, expected value from the file</param> public static void TestIndicator(IndicatorBase<IndicatorDataPoint> indicator, string externalDataFilename, string targetColumn, Action<IndicatorBase<IndicatorDataPoint>, double> customAssertion) { // assumes the Date is in the first index bool first = true; int closeIndex = -1; int targetIndex = -1; foreach (var line in File.ReadLines(Path.Combine("TestData", externalDataFilename))) { string[] parts = line.Split(new[] {','}, StringSplitOptions.None); if (first) { first = false; for (int i = 0; i < parts.Length; i++) { if (parts[i].Trim() == "Close") { closeIndex = i; } if (parts[i].Trim() == targetColumn) { targetIndex = i; } } if (closeIndex*targetIndex < 0) { Assert.Fail("Didn't find one of 'Close' or '{0}' in the header: " + line, targetColumn); } continue; } decimal close = decimal.Parse(parts[closeIndex], CultureInfo.InvariantCulture); DateTime date = Time.ParseDate(parts[0]); var data = new IndicatorDataPoint(date, close); indicator.Update(data); if (!indicator.IsReady || parts[targetIndex].Trim() == string.Empty) { continue; } double expected = double.Parse(parts[targetIndex], CultureInfo.InvariantCulture); customAssertion.Invoke(indicator, expected); } } /// <summary> /// Compare the specified indicator against external data using the specificied comma delimited text file. /// The 'Close' column will be fed to the indicator as input /// </summary> /// <param name="indicator">The indicator under test</param> /// <param name="externalDataFilename"></param> /// <param name="targetColumn">The column with the correct answers</param> /// <param name="epsilon">The maximum delta between expected and actual</param> public static void TestIndicator(IndicatorBase<TradeBar> indicator, string externalDataFilename, string targetColumn, double epsilon = 1e-3) { TestIndicator(indicator, externalDataFilename, targetColumn, (i, expected) => Assert.AreEqual(expected, (double)i.Current.Value, epsilon, "Failed at " + i.Current.Time.ToString("o"))); } /// <summary> /// Compare the specified indicator against external data using the specificied comma delimited text file. /// The 'Close' column will be fed to the indicator as input /// </summary> /// <param name="indicator">The indicator under test</param> /// <param name="externalDataFilename"></param> /// <param name="targetColumn">The column with the correct answers</param> /// <param name="selector">A function that receives the indicator as input and outputs a value to match the target column</param> /// <param name="epsilon">The maximum delta between expected and actual</param> public static void TestIndicator<T>(T indicator, string externalDataFilename, string targetColumn, Func<T, double> selector, double epsilon = 1e-3) where T : Indicator { TestIndicator(indicator, externalDataFilename, targetColumn, (i, expected) => Assert.AreEqual(expected, selector(indicator), epsilon, "Failed at " + i.Current.Time.ToString("o"))); } /// <summary> /// Compare the specified indicator against external data using the specificied comma delimited text file. /// The 'Close' column will be fed to the indicator as input /// </summary> /// <param name="indicator">The indicator under test</param> /// <param name="externalDataFilename"></param> /// <param name="targetColumn">The column with the correct answers</param> /// <param name="customAssertion">Sets custom assertion logic, parameter is the indicator, expected value from the file</param> public static void TestIndicator(IndicatorBase<TradeBar> indicator, string externalDataFilename, string targetColumn, Action<IndicatorBase<TradeBar>, double> customAssertion) { bool first = true; int targetIndex = -1; bool fileHasVolume = false; foreach (var line in File.ReadLines(Path.Combine("TestData", externalDataFilename))) { var parts = line.Split(','); if (first) { fileHasVolume = parts[5].Trim() == "Volume"; first = false; for (int i = 0; i < parts.Length; i++) { if (parts[i].Trim() == targetColumn) { targetIndex = i; break; } } continue; } var tradebar = new TradeBar { Time = Time.ParseDate(parts[0]), Open = parts[1].ToDecimal(), High = parts[2].ToDecimal(), Low = parts[3].ToDecimal(), Close = parts[4].ToDecimal(), Volume = fileHasVolume ? long.Parse(parts[5], NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture) : 0 }; indicator.Update(tradebar); if (!indicator.IsReady || parts[targetIndex].Trim() == string.Empty) { continue; } double expected = double.Parse(parts[targetIndex], CultureInfo.InvariantCulture); customAssertion.Invoke(indicator, expected); } } public static IEnumerable<IReadOnlyDictionary<string, string>> GetCsvFileStream(string externalDataFilename) { var enumerator = File.ReadLines(Path.Combine("TestData", externalDataFilename)).GetEnumerator(); if (!enumerator.MoveNext()) { yield break; } string[] header = enumerator.Current.Split(','); while (enumerator.MoveNext()) { var values = enumerator.Current.Split(','); var headerAndValues = header.Zip(values, (h, v) => new {h, v}); var dictionary = headerAndValues.ToDictionary(x => x.h.Trim(), x => x.v.Trim(), StringComparer.OrdinalIgnoreCase); yield return new ReadOnlyDictionary<string, string>(dictionary); } } /// <summary> /// Gets a stream of trade bars from the specified file /// </summary> public static IEnumerable<TradeBar> GetTradeBarStream(string externalDataFilename, bool fileHasVolume = true) { return GetCsvFileStream(externalDataFilename).Select(values => new TradeBar { Time = Time.ParseDate(values.GetCsvValue("date", "time")), Open = values.GetCsvValue("open").ToDecimal(), High = values.GetCsvValue("high").ToDecimal(), Low = values.GetCsvValue("low").ToDecimal(), Close = values.GetCsvValue("close").ToDecimal(), Volume = fileHasVolume ? long.Parse(values.GetCsvValue("volume"), NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture) : 0 }); } /// <summary> /// Asserts that the indicator has zero samples, is not ready, and has the default value /// </summary> /// <param name="indicator">The indicator to assert</param> public static void AssertIndicatorIsInDefaultState<T>(IndicatorBase<T> indicator) where T : BaseData { Assert.AreEqual(0m, indicator.Current.Value); Assert.AreEqual(DateTime.MinValue, indicator.Current.Time); Assert.AreEqual(0, indicator.Samples); Assert.IsFalse(indicator.IsReady); } /// <summary> /// Gets a customAssertion action which will gaurantee that the delta between the expected and the /// actual continues to decrease with a lower bound as specified by the epsilon parameter. This is useful /// for testing indicators which retain theoretically infinite information via methods such as exponential smoothing /// </summary> /// <param name="epsilon">The largest increase in the delta permitted</param> /// <returns></returns> public static Action<IndicatorBase<IndicatorDataPoint>, double> AssertDeltaDecreases(double epsilon) { double delta = double.MaxValue; return (indicator, expected) => { // the delta should be forever decreasing var currentDelta = Math.Abs((double) indicator.Current.Value - expected); if (currentDelta - delta > epsilon) { Assert.Fail("The delta increased!"); //Console.WriteLine(indicator.Value.Time.Date.ToShortDateString() + " - " + indicator.Value.Data.ToString("000.000") + " \t " + expected.ToString("000.000") + " \t " + currentDelta.ToString("0.000")); } delta = currentDelta; }; } /// <summary> /// Grabs the first value from the set of keys /// </summary> private static string GetCsvValue(this IReadOnlyDictionary<string, string> dictionary, params string[] keys) { string value = null; if (keys.Any(key => dictionary.TryGetValue(key, out value))) { return value; } throw new ArgumentException("Unable to find column: " + string.Join(", ", keys)); } } }
// User32.cs // ------------------------------------------------------------------ // // Wrapper for User32.dll methods, etc. // // Time-stamp: <2010-April-19 18:21:29> // ------------------------------------------------------------------ // // Copyright (c) 2010 by Dino Chiesa // All rights reserved! // // ------------------------------------------------------------------ using System; using System.Reflection; using System.Runtime.InteropServices; namespace Ionic { public static class User32 { public enum Styles : uint { WS_OVERLAPPED = 0x00000000, WS_POPUP = 0x80000000, WS_CHILD = 0x40000000, WS_MINIMIZE = 0x20000000, WS_VISIBLE = 0x10000000, WS_DISABLED = 0x08000000, WS_CLIPSIBLINGS = 0x04000000, WS_CLIPCHILDREN = 0x02000000, WS_MAXIMIZE = 0x01000000, WS_CAPTION = 0x00C00000, WS_BORDER = 0x00800000, WS_DLGFRAME = 0x00400000, WS_VSCROLL = 0x00200000, WS_HSCROLL = 0x00100000, WS_SYSMENU = 0x00080000, WS_THICKFRAME = 0x00040000, WS_GROUP = 0x00020000, WS_TABSTOP = 0x00010000, GWL_STYLE = 0xFFFFFFF0, } public enum Msgs { // GetWindow GW_HWNDFIRST = 0, GW_HWNDLAST = 1, GW_HWNDNEXT = 2, GW_HWNDPREV = 3, GW_OWNER = 4, GW_CHILD = 5, // Window messages - WinUser.h WM_NULL = 0x0000, WM_CREATE = 0x0001, WM_DESTROY = 0x0002, WM_MOVE = 0x0003, WM_SIZE = 0x0005, WM_KILLFOCUS = 0x0008, WM_SETREDRAW = 0x000B, WM_GETTEXT = 0x000D, WM_GETTEXTLENGTH = 0x000E, WM_PAINT = 0x000F, WM_ERASEBKGND = 0x0014, WM_SHOWWINDOW = 0x0018, WM_FONTCHANGE = 0x001d, WM_SETCURSOR = 0x0020, WM_MOUSEACTIVATE = 0x0021, WM_CHILDACTIVATE = 0x0022, WM_DRAWITEM = 0x002B, WM_MEASUREITEM = 0x002C, WM_DELETEITEM = 0x002D, WM_VKEYTOITEM = 0x002E, WM_CHARTOITEM = 0x002F, WM_SETFONT = 0x0030, WM_COMPAREITEM = 0x0039, WM_WINDOWPOSCHANGING = 0x0046, WM_WINDOWPOSCHANGED = 0x0047, WM_NOTIFY = 0x004E, WM_NOTIFYFORMAT = 0x0055, WM_STYLECHANGING = 0x007C, WM_STYLECHANGED = 0x007D, WM_NCMOUSEMOVE = 0x00A0, WM_NCLBUTTONDOWN = 0x00A1, WM_NCCREATE = 0x0081, WM_NCDESTROY = 0x0082, WM_NCCALCSIZE = 0x0083, WM_NCHITTEST = 0x0084, WM_NCPAINT = 0x0085, WM_GETDLGCODE = 0x0087, // from WinUser.h and RichEdit.h EM_GETSEL = 0x00B0, EM_SETSEL = 0x00B1, EM_GETRECT = 0x00B2, EM_SETRECT = 0x00B3, EM_SETRECTNP = 0x00B4, EM_SCROLL = 0x00B5, EM_LINESCROLL = 0x00B6, //EM_SCROLLCARET = 0x00B7, EM_GETMODIFY = 0x00B8, EM_SETMODIFY = 0x00B9, EM_GETLINECOUNT = 0x00BA, EM_LINEINDEX = 0x00BB, EM_SETHANDLE = 0x00BC, EM_GETHANDLE = 0x00BD, EM_GETTHUMB = 0x00BE, EM_LINELENGTH = 0x00C1, EM_LINEFROMCHAR = 0x00C9, EM_GETFIRSTVISIBLELINE = 0x00CE, EM_SETMARGINS = 0x00D3, EM_GETMARGINS = 0x00D4, EM_POSFROMCHAR = 0x00D6, EM_CHARFROMPOS = 0x00D7, WM_KEYFIRST = 0x0100, WM_KEYDOWN = 0x0100, WM_KEYUP = 0x0101, WM_CHAR = 0x0102, WM_DEADCHAR = 0x0103, WM_SYSKEYDOWN = 0x0104, WM_SYSKEYUP = 0x0105, WM_SYSCHAR = 0x0106, WM_SYSDEADCHAR = 0x0107, WM_COMMAND = 0x0111, WM_SYSCOMMAND = 0x0112, WM_TIMER = 0x0113, WM_HSCROLL = 0x0114, WM_VSCROLL = 0x0115, WM_UPDATEUISTATE = 0x0128, WM_QUERYUISTATE = 0x0129, WM_MOUSEFIRST = 0x0200, WM_MOUSEMOVE = 0x0200, WM_LBUTTONDOWN = 0x0201, WM_LBUTTONUP = 0x0202, WM_PARENTNOTIFY = 0x0210, WM_NEXTMENU = 0x0213, WM_SIZING = 0x0214, WM_CAPTURECHANGED = 0x0215, WM_MOVING = 0x0216, WM_IME_SETCONTEXT = 0x0281, WM_IME_NOTIFY = 0x0282, WM_IME_CONTROL = 0x0283, WM_IME_COMPOSITIONFULL = 0x0284, WM_IME_SELECT = 0x0285, WM_IME_CHAR = 0x0286, WM_IME_REQUEST = 0x0288, WM_IME_KEYDOWN = 0x0290, WM_IME_KEYUP = 0x0291, WM_NCMOUSEHOVER = 0x02A0, WM_NCMOUSELEAVE = 0x02A2, WM_MOUSEHOVER = 0x02A1, WM_MOUSELEAVE = 0x02A3, WM_CUT = 0x0300, WM_COPY = 0x0301, WM_PASTE = 0x0302, WM_CLEAR = 0x0303, WM_UNDO = 0x0304, WM_RENDERFORMAT = 0x0305, WM_RENDERALLFORMATS = 0x0306, WM_DESTROYCLIPBOARD = 0x0307, WM_DRAWCLIPBOARD = 0x0308, WM_PAINTCLIPBOARD = 0x0309, WM_VSCROLLCLIPBOARD = 0x030A, WM_SIZECLIPBOARD = 0x030B, WM_ASKCBFORMATNAME = 0x030C, WM_CHANGECBCHAIN = 0x030D, WM_HSCROLLCLIPBOARD = 0x030E, WM_QUERYNEWPALETTE = 0x030F, WM_PALETTEISCHANGING = 0x0310, WM_PALETTECHANGED = 0x0311, WM_HOTKEY = 0x0312, WM_USER = 0x0400, EM_SCROLLCARET = (WM_USER + 49), EM_CANPASTE = (WM_USER + 50), EM_DISPLAYBAND = (WM_USER + 51), EM_EXGETSEL = (WM_USER + 52), EM_EXLIMITTEXT = (WM_USER + 53), EM_EXLINEFROMCHAR = (WM_USER + 54), EM_EXSETSEL = (WM_USER + 55), EM_FINDTEXT = (WM_USER + 56), EM_FORMATRANGE = (WM_USER + 57), EM_GETCHARFORMAT = (WM_USER + 58), EM_GETEVENTMASK = (WM_USER + 59), EM_GETOLEINTERFACE = (WM_USER + 60), EM_GETPARAFORMAT = (WM_USER + 61), EM_GETSELTEXT = (WM_USER + 62), EM_HIDESELECTION = (WM_USER + 63), EM_PASTESPECIAL = (WM_USER + 64), EM_REQUESTRESIZE = (WM_USER + 65), EM_SELECTIONTYPE = (WM_USER + 66), EM_SETBKGNDCOLOR = (WM_USER + 67), EM_SETCHARFORMAT = (WM_USER + 68), EM_SETEVENTMASK = (WM_USER + 69), EM_SETOLECALLBACK = (WM_USER + 70), EM_SETPARAFORMAT = (WM_USER + 71), EM_SETTARGETDEVICE = (WM_USER + 72), EM_STREAMIN = (WM_USER + 73), EM_STREAMOUT = (WM_USER + 74), EM_GETTEXTRANGE = (WM_USER + 75), EM_FINDWORDBREAK = (WM_USER + 76), EM_SETOPTIONS = (WM_USER + 77), EM_GETOPTIONS = (WM_USER + 78), EM_FINDTEXTEX = (WM_USER + 79), // Tab Control Messages - CommCtrl.h TCM_DELETEITEM = 0x1308, TCM_INSERTITEM = 0x133E, TCM_GETITEMRECT = 0x130A, TCM_GETCURSEL = 0x130B, TCM_SETCURSEL = 0x130C, TCM_ADJUSTRECT = 0x1328, TCM_SETITEMSIZE = 0x1329, TCM_SETPADDING = 0x132B, // olectl.h OCM__BASE = (WM_USER+0x1c00), OCM_COMMAND = (OCM__BASE + WM_COMMAND), OCM_DRAWITEM = (OCM__BASE + WM_DRAWITEM), OCM_MEASUREITEM = (OCM__BASE + WM_MEASUREITEM), OCM_DELETEITEM = (OCM__BASE + WM_DELETEITEM), OCM_VKEYTOITEM = (OCM__BASE + WM_VKEYTOITEM), OCM_CHARTOITEM = (OCM__BASE + WM_CHARTOITEM), OCM_COMPAREITEM = (OCM__BASE + WM_COMPAREITEM), OCM_HSCROLL = (OCM__BASE + WM_HSCROLL), OCM_VSCROLL = (OCM__BASE + WM_VSCROLL), OCM_PARENTNOTIFY = (OCM__BASE + WM_PARENTNOTIFY), OCM_NOTIFY = (OCM__BASE + WM_NOTIFY), } public const int SCF_SELECTION = 0x0001; /* Edit control EM_SETMARGIN parameters */ public const int EC_LEFTMARGIN = 0x0001; public const int EC_RIGHTMARGIN = 0x0002; [Flags] public enum Flags { // SetWindowPos Flags - WinUser.h SWP_NOSIZE = 0x0001, SWP_NOMOVE = 0x0002, SWP_NOZORDER = 0x0004, SWP_NOREDRAW = 0x0008, SWP_NOACTIVATE = 0x0010, SWP_FRAMECHANGED = 0x0020 , SWP_SHOWWINDOW = 0x0040, SWP_HIDEWINDOW = 0x0080, SWP_NOCOPYBITS = 0x0100, SWP_NOOWNERZORDER = 0x0200 , SWP_NOSENDCHANGING = 0x0400, }; private static Type tmsgs = typeof (Msgs); public static string Mnemonic(int z) { foreach (int ix in Enum.GetValues(tmsgs)) { if (z == ix) return Enum.GetName(tmsgs, ix); } return z.ToString("X4"); } [StructLayout(LayoutKind.Sequential)] public struct WINDOWPOS { public IntPtr hwnd, hwndInsertAfter; public int x ,y ,cx ,cy ,flags; } [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] public struct STYLESTRUCT { public int styleOld; public int styleNew; } [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] public struct CREATESTRUCT { public IntPtr lpCreateParams; public IntPtr hInstance; public IntPtr hMenu; public IntPtr hwndParent; public int cy; public int cx; public int y; public int x; public int style; public string lpszName; public string lpszClass; public int dwExStyle; } [StructLayout(LayoutKind.Sequential)] public struct CHARFORMAT { public int cbSize; public UInt32 dwMask; public UInt32 dwEffects; public Int32 yHeight; public Int32 yOffset; public Int32 crTextColor; public byte bCharSet; public byte bPitchAndFamily; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)] public char[] szFaceName; } [StructLayout(LayoutKind.Sequential)] public struct POINTL { public Int32 X; public Int32 Y; } public static void BeginUpdate(IntPtr hWnd) { SendMessage(hWnd, (int)Msgs.WM_SETREDRAW, 0, IntPtr.Zero); } public static void EndUpdate(IntPtr hWnd) { SendMessage(hWnd, (int)Msgs.WM_SETREDRAW, 1, IntPtr.Zero); } [DllImport("User32.dll", EntryPoint="SendMessage", CharSet=CharSet.Auto)] public static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam); [DllImport("User32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)] public static extern IntPtr SendMessage(IntPtr hWnd, [MarshalAs(UnmanagedType.I4)] Msgs msg, int wParam, IntPtr lParam); [DllImport("User32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)] public static extern IntPtr SendMessage(IntPtr hWnd, [MarshalAs(UnmanagedType.I4)] Msgs msg, int wParam, int lParam); [DllImport("User32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)] public static extern int SendMessage(IntPtr hWnd, int msg, int wparam, IntPtr lparam); [DllImport("User32.dll", EntryPoint="SendMessage", CharSet=CharSet.Auto)] public static extern int SendMessage(IntPtr hWnd, int msg, int wparam, int lparam); [DllImport("User32.dll", EntryPoint="SendMessage", CharSet=CharSet.Auto)] public static extern int SendMessageRef(IntPtr hWnd, int msg, out int wparam, out int lparam); [DllImport("User32.dll",CharSet = CharSet.Auto)] public static extern IntPtr GetWindow(IntPtr hWnd, int uCmd); [DllImport("User32.dll",CharSet = CharSet.Auto)] public static extern int GetClassName(IntPtr hWnd, char[] className, int maxCount); [DllImport("user32.dll")] //[return: MarshalAs(UnmanagedType.Bool)] public static extern int SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags); [DllImport("user32.dll", SetLastError=true)] public static extern uint GetWindowLong(IntPtr hWnd, uint nIndex); [DllImport("user32.dll")] public static extern int SetWindowLong(IntPtr hWnd, uint nIndex, uint dwNewLong); } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Linq; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.DiaSymReader; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class MissingAssemblyTests : ExpressionCompilerTestBase { [Fact] public void ErrorsWithAssemblyIdentityArguments() { var identity = new AssemblyIdentity(GetUniqueName()); Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_NoTypeDef, identity)); } [Fact] public void ErrorsWithAssemblySymbolArguments() { var assembly = CreateCompilation("").Assembly; var identity = assembly.Identity; Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_GlobalSingleTypeNameNotFoundFwd, assembly)); Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_DottedTypeNameNotFoundInNSFwd, assembly)); Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_SingleTypeNameNotFoundFwd, assembly)); Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_NameNotInContextPossibleMissingReference, assembly)); } [Fact] public void ErrorsRequiringSystemCore() { var identity = EvaluationContextBase.SystemCoreIdentity; Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_NoSuchMemberOrExtension)); Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_DynamicAttributeMissing)); Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_DynamicRequiredTypesMissing)); Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_QueryNoProviderStandard)); Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_ExtensionAttrNotFound)); } [Fact] public void MultipleAssemblyArguments() { var identity1 = new AssemblyIdentity(GetUniqueName()); var identity2 = new AssemblyIdentity(GetUniqueName()); Assert.Equal(identity1, GetMissingAssemblyIdentity(ErrorCode.ERR_NoTypeDef, identity1, identity2)); Assert.Equal(identity2, GetMissingAssemblyIdentity(ErrorCode.ERR_NoTypeDef, identity2, identity1)); } [Fact] public void NoAssemblyArguments() { Assert.Null(GetMissingAssemblyIdentity(ErrorCode.ERR_NoTypeDef)); Assert.Null(GetMissingAssemblyIdentity(ErrorCode.ERR_NoTypeDef, "Not an assembly")); } [Fact] public void ERR_NoTypeDef() { var libSource = @" public class Missing { } "; var source = @" public class C { public void M(Missing parameter) { } } "; var libRef = CreateStandardCompilation(libSource, assemblyName: "Lib").EmitToImageReference(); var comp = CreateStandardCompilation(source, new[] { libRef }, TestOptions.DebugDll); WithRuntimeInstance(comp, new[] { MscorlibRef }, runtime => { var context = CreateMethodContext(runtime, "C.M"); var expectedError = "error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'."; var expectedMissingAssemblyIdentity = new AssemblyIdentity("Lib"); ResultProperties resultProperties; string actualError; ImmutableArray<AssemblyIdentity> actualMissingAssemblyIdentities; context.CompileExpression( "parameter", DkmEvaluationFlags.TreatAsExpression, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out actualError, out actualMissingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal(expectedError, actualError); Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single()); }); } [Fact] public void ERR_QueryNoProviderStandard() { var source = @" public class C { public void M(int[] array) { } } "; var comp = CreateStandardCompilation(source, new[] { SystemCoreRef }, TestOptions.DebugDll); WithRuntimeInstance(comp, new[] { MscorlibRef }, runtime => { var context = CreateMethodContext(runtime, "C.M"); var expectedError = "error CS1935: Could not find an implementation of the query pattern for source type 'int[]'. 'Select' not found. Are you missing a reference to 'System.Core.dll' or a using directive for 'System.Linq'?"; var expectedMissingAssemblyIdentity = EvaluationContextBase.SystemCoreIdentity; ResultProperties resultProperties; string actualError; ImmutableArray<AssemblyIdentity> actualMissingAssemblyIdentities; context.CompileExpression( "from i in array select i", DkmEvaluationFlags.TreatAsExpression, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out actualError, out actualMissingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal(expectedError, actualError); Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single()); }); } [WorkItem(1151888, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1151888")] [Fact] public void ERR_NoSuchMemberOrExtension_CompilationReferencesSystemCore() { var source = @" using System.Linq; public class C { public void M(int[] array) { } } "; var comp = CreateStandardCompilation(source, new[] { SystemCoreRef }, TestOptions.DebugDll); WithRuntimeInstance(comp, new[] { MscorlibRef }, runtime => { var context = CreateMethodContext(runtime, "C.M"); var expectedErrorTemplate = "error CS1061: 'int[]' does not contain a definition for '{0}' and no extension method '{0}' accepting a first argument of type 'int[]' could be found (are you missing a using directive or an assembly reference?)"; var expectedMissingAssemblyIdentity = EvaluationContextBase.SystemCoreIdentity; ResultProperties resultProperties; string actualError; ImmutableArray<AssemblyIdentity> actualMissingAssemblyIdentities; context.CompileExpression( "array.Count()", DkmEvaluationFlags.TreatAsExpression, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out actualError, out actualMissingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal(string.Format(expectedErrorTemplate, "Count"), actualError); Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single()); context.CompileExpression( "array.NoSuchMethod()", DkmEvaluationFlags.TreatAsExpression, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out actualError, out actualMissingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal(string.Format(expectedErrorTemplate, "NoSuchMethod"), actualError); Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single()); }); } /// <remarks> /// The fact that the compilation does not reference System.Core has no effect since /// this test only covers our ability to identify an assembly to attempt to load, not /// our ability to actually load or consume it. /// </remarks> [WorkItem(1151888, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1151888")] [Fact] public void ERR_NoSuchMemberOrExtension_CompilationDoesNotReferenceSystemCore() { var source = @" using System.Linq; public class C { public void M(int[] array) { } } namespace System.Linq { public class Dummy { } } "; var comp = CreateStandardCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, new[] { MscorlibRef }, runtime => { var context = CreateMethodContext(runtime, "C.M"); var expectedErrorTemplate = "error CS1061: 'int[]' does not contain a definition for '{0}' and no extension method '{0}' accepting a first argument of type 'int[]' could be found (are you missing a using directive or an assembly reference?)"; var expectedMissingAssemblyIdentity = EvaluationContextBase.SystemCoreIdentity; ResultProperties resultProperties; string actualError; ImmutableArray<AssemblyIdentity> actualMissingAssemblyIdentities; context.CompileExpression( "array.Count()", DkmEvaluationFlags.TreatAsExpression, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out actualError, out actualMissingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal(string.Format(expectedErrorTemplate, "Count"), actualError); Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single()); context.CompileExpression( "array.NoSuchMethod()", DkmEvaluationFlags.TreatAsExpression, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out actualError, out actualMissingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal(string.Format(expectedErrorTemplate, "NoSuchMethod"), actualError); Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single()); }); } [Fact] public void ForwardingErrors() { var il = @" .assembly extern mscorlib { } .assembly extern pe2 { } .assembly pe1 { } .class extern forwarder Forwarded { .assembly extern pe2 } .class extern forwarder NS.Forwarded { .assembly extern pe2 } .class public auto ansi beforefieldinit Dummy extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } "; var csharp = @" class C { static void M(Dummy d) { } } "; var ilRef = CompileIL(il, prependDefaultHeader: false); var comp = CreateStandardCompilation(csharp, new[] { ilRef }); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var expectedMissingAssemblyIdentity = new AssemblyIdentity("pe2"); ResultProperties resultProperties; string actualError; ImmutableArray<AssemblyIdentity> actualMissingAssemblyIdentities; context.CompileExpression( "new global::Forwarded()", DkmEvaluationFlags.TreatAsExpression, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out actualError, out actualMissingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal( "error CS1068: The type name 'Forwarded' could not be found in the global namespace. This type has been forwarded to assembly 'pe2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' Consider adding a reference to that assembly.", actualError); Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single()); context.CompileExpression( "new Forwarded()", DkmEvaluationFlags.TreatAsExpression, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out actualError, out actualMissingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal( "error CS1070: The type name 'Forwarded' could not be found. This type has been forwarded to assembly 'pe2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Consider adding a reference to that assembly.", actualError); Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single()); context.CompileExpression( "new NS.Forwarded()", DkmEvaluationFlags.TreatAsExpression, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out actualError, out actualMissingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal( "error CS1069: The type name 'Forwarded' could not be found in the namespace 'NS'. This type has been forwarded to assembly 'pe2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' Consider adding a reference to that assembly.", actualError); Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single()); }); } [Fact] public unsafe void ShouldTryAgain_Success() { var comp = CreateStandardCompilation("public class C { }"); using (var pinned = new PinnedMetadata(GetMetadataBytes(comp))) { DkmUtilities.GetMetadataBytesPtrFunction gmdbpf = (AssemblyIdentity assemblyIdentity, out uint uSize) => { uSize = (uint)pinned.Size; return pinned.Pointer; }; var references = ImmutableArray<MetadataBlock>.Empty; var missingAssemblyIdentity = new AssemblyIdentity("A"); var missingAssemblyIdentities = ImmutableArray.Create(missingAssemblyIdentity); Assert.True(ExpressionCompiler.ShouldTryAgainWithMoreMetadataBlocks(gmdbpf, missingAssemblyIdentities, ref references)); var newReference = references.Single(); Assert.Equal(pinned.Pointer, newReference.Pointer); Assert.Equal(pinned.Size, newReference.Size); } } [Fact] public unsafe void ShouldTryAgain_Mixed() { var comp1 = CreateStandardCompilation("public class C { }", assemblyName: GetUniqueName()); var comp2 = CreateStandardCompilation("public class D { }", assemblyName: GetUniqueName()); using (PinnedMetadata pinned1 = new PinnedMetadata(GetMetadataBytes(comp1)), pinned2 = new PinnedMetadata(GetMetadataBytes(comp2))) { var assemblyIdentity1 = comp1.Assembly.Identity; var assemblyIdentity2 = comp2.Assembly.Identity; Assert.NotEqual(assemblyIdentity1, assemblyIdentity2); DkmUtilities.GetMetadataBytesPtrFunction gmdbpf = (AssemblyIdentity assemblyIdentity, out uint uSize) => { if (assemblyIdentity == assemblyIdentity1) { uSize = (uint)pinned1.Size; return pinned1.Pointer; } else if (assemblyIdentity == assemblyIdentity2) { uSize = (uint)pinned2.Size; return pinned2.Pointer; } else { Marshal.ThrowExceptionForHR(unchecked((int)MetadataUtilities.CORDBG_E_MISSING_METADATA)); throw ExceptionUtilities.Unreachable; } }; var references = ImmutableArray.Create(default(MetadataBlock)); var unknownAssemblyIdentity = new AssemblyIdentity(GetUniqueName()); var missingAssemblyIdentities = ImmutableArray.Create(assemblyIdentity1, unknownAssemblyIdentity, assemblyIdentity2); Assert.True(ExpressionCompiler.ShouldTryAgainWithMoreMetadataBlocks(gmdbpf, missingAssemblyIdentities, ref references)); Assert.Equal(3, references.Length); Assert.Equal(default(MetadataBlock), references[0]); Assert.Equal(pinned1.Pointer, references[1].Pointer); Assert.Equal(pinned1.Size, references[1].Size); Assert.Equal(pinned2.Pointer, references[2].Pointer); Assert.Equal(pinned2.Size, references[2].Size); } } [Fact] public void ShouldTryAgain_CORDBG_E_MISSING_METADATA() { ShouldTryAgain_False( (AssemblyIdentity assemblyIdentity, out uint uSize) => { Marshal.ThrowExceptionForHR(unchecked((int)MetadataUtilities.CORDBG_E_MISSING_METADATA)); throw ExceptionUtilities.Unreachable; }); } [Fact] public void ShouldTryAgain_COR_E_BADIMAGEFORMAT() { ShouldTryAgain_False( (AssemblyIdentity assemblyIdentity, out uint uSize) => { Marshal.ThrowExceptionForHR(unchecked((int)MetadataUtilities.COR_E_BADIMAGEFORMAT)); throw ExceptionUtilities.Unreachable; }); } [Fact] public void ShouldTryAgain_ObjectDisposedException() { ShouldTryAgain_False( (AssemblyIdentity assemblyIdentity, out uint uSize) => { throw new ObjectDisposedException("obj"); }); } [Fact] public void ShouldTryAgain_RPC_E_DISCONNECTED() { DkmUtilities.GetMetadataBytesPtrFunction gmdbpf = (AssemblyIdentity assemblyIdentity, out uint uSize) => { Marshal.ThrowExceptionForHR(unchecked((int)0x80010108)); throw ExceptionUtilities.Unreachable; }; var references = ImmutableArray<MetadataBlock>.Empty; var missingAssemblyIdentities = ImmutableArray.Create(new AssemblyIdentity("A")); Assert.Throws<COMException>(() => ExpressionCompiler.ShouldTryAgainWithMoreMetadataBlocks(gmdbpf, missingAssemblyIdentities, ref references)); } [Fact] public void ShouldTryAgain_Exception() { DkmUtilities.GetMetadataBytesPtrFunction gmdbpf = (AssemblyIdentity assemblyIdentity, out uint uSize) => { throw new Exception(); }; var references = ImmutableArray<MetadataBlock>.Empty; var missingAssemblyIdentities = ImmutableArray.Create(new AssemblyIdentity("A")); Assert.Throws<Exception>(() => ExpressionCompiler.ShouldTryAgainWithMoreMetadataBlocks(gmdbpf, missingAssemblyIdentities, ref references)); } private static void ShouldTryAgain_False(DkmUtilities.GetMetadataBytesPtrFunction gmdbpf) { var references = ImmutableArray<MetadataBlock>.Empty; var missingAssemblyIdentities = ImmutableArray.Create(new AssemblyIdentity("A")); Assert.False(ExpressionCompiler.ShouldTryAgainWithMoreMetadataBlocks(gmdbpf, missingAssemblyIdentities, ref references)); Assert.Empty(references); } [WorkItem(1124725, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1124725")] [Fact] public void PseudoVariableType() { var source = @"class C { static void M() { } } "; var comp = CreateStandardCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, new[] { CSharpRef }, runtime => { var context = CreateMethodContext(runtime, "C.M"); const string expectedError = "error CS0012: The type 'Exception' is defined in an assembly that is not referenced. You must add a reference to assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'."; var expectedMissingAssemblyIdentity = comp.Assembly.CorLibrary.Identity; ResultProperties resultProperties; string actualError; ImmutableArray<AssemblyIdentity> actualMissingAssemblyIdentities; context.CompileExpression( "$stowedexception", DkmEvaluationFlags.TreatAsExpression, ImmutableArray.Create(ExceptionAlias("Microsoft.CSharp.RuntimeBinder.RuntimeBinderException, Microsoft.CSharp, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", stowed: true)), DebuggerDiagnosticFormatter.Instance, out resultProperties, out actualError, out actualMissingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal(expectedError, actualError); Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single()); }); } [WorkItem(1114866, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1114866")] [ConditionalFact(typeof(OSVersionWin8))] public void NotYetLoadedWinMds() { var source = @"class C { static void M(Windows.Storage.StorageFolder f) { } }"; var comp = CreateStandardCompilation(source, WinRtRefs, TestOptions.DebugDll); var runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage"); Assert.True(runtimeAssemblies.Any()); WithRuntimeInstance(comp, new[] { MscorlibRef }.Concat(runtimeAssemblies), runtime => { var context = CreateMethodContext(runtime, "C.M"); const string expectedError = "error CS0234: The type or namespace name 'UI' does not exist in the namespace 'Windows' (are you missing an assembly reference?)"; var expectedMissingAssemblyIdentity = new AssemblyIdentity("Windows.UI", contentType: System.Reflection.AssemblyContentType.WindowsRuntime); ResultProperties resultProperties; string actualError; ImmutableArray<AssemblyIdentity> actualMissingAssemblyIdentities; context.CompileExpression( "typeof(@Windows.UI.Colors)", DkmEvaluationFlags.None, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out actualError, out actualMissingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal(expectedError, actualError); Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single()); }); } /// <remarks> /// Windows.UI.Xaml is the only (win8) winmd with more than two parts. /// </remarks> [WorkItem(1114866, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1114866")] [ConditionalFact(typeof(OSVersionWin8))] public void NotYetLoadedWinMds_MultipleParts() { var source = @"class C { static void M(Windows.UI.Colors c) { } }"; var comp = CreateStandardCompilation(source, WinRtRefs, TestOptions.DebugDll); var runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.UI"); Assert.True(runtimeAssemblies.Any()); WithRuntimeInstance(comp, new[] { MscorlibRef }.Concat(runtimeAssemblies), runtime => { var context = CreateMethodContext(runtime, "C.M"); const string expectedError = "error CS0234: The type or namespace name 'Xaml' does not exist in the namespace 'Windows.UI' (are you missing an assembly reference?)"; var expectedMissingAssemblyIdentity = new AssemblyIdentity("Windows.UI.Xaml", contentType: System.Reflection.AssemblyContentType.WindowsRuntime); ResultProperties resultProperties; string actualError; ImmutableArray<AssemblyIdentity> actualMissingAssemblyIdentities; context.CompileExpression( "typeof(Windows.@UI.Xaml.Application)", DkmEvaluationFlags.None, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out actualError, out actualMissingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal(expectedError, actualError); Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single()); }); } [WorkItem(1154988, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1154988")] [Fact] public void CompileWithRetrySameErrorReported() { var source = @" class C { void M() { } }"; var comp = CreateStandardCompilation(source); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var missingModule = runtime.Modules.First(); var missingIdentity = missingModule.GetMetadataReader().ReadAssemblyIdentityOrThrow(); var numRetries = 0; string errorMessage; ExpressionCompilerTestHelpers.CompileExpressionWithRetry( runtime.Modules.Select(m => m.MetadataBlock).ToImmutableArray(), context, (_, diagnostics) => { numRetries++; Assert.InRange(numRetries, 0, 2); // We don't want to loop forever... diagnostics.Add(new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.ERR_NoTypeDef, "MissingType", missingIdentity), Location.None)); return null; }, (AssemblyIdentity assemblyIdentity, out uint uSize) => { uSize = (uint)missingModule.MetadataLength; return missingModule.MetadataAddress; }, out errorMessage); Assert.Equal(2, numRetries); // Ensure that we actually retried and that we bailed out on the second retry if the same identity was seen in the diagnostics. Assert.Equal($"error CS0012: The type 'MissingType' is defined in an assembly that is not referenced. You must add a reference to assembly '{missingIdentity}'.", errorMessage); }); } [WorkItem(1151888, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1151888")] [Fact] public void SucceedOnRetry() { var source = @" class C { void M() { } }"; var comp = CreateStandardCompilation(source); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var missingModule = runtime.Modules.First(); var missingIdentity = missingModule.GetMetadataReader().ReadAssemblyIdentityOrThrow(); var shouldSucceed = false; string errorMessage; var compileResult = ExpressionCompilerTestHelpers.CompileExpressionWithRetry( runtime.Modules.Select(m => m.MetadataBlock).ToImmutableArray(), context, (_, diagnostics) => { if (shouldSucceed) { return TestCompileResult.Instance; } else { shouldSucceed = true; diagnostics.Add(new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.ERR_NoTypeDef, "MissingType", missingIdentity), Location.None)); return null; } }, (AssemblyIdentity assemblyIdentity, out uint uSize) => { uSize = (uint)missingModule.MetadataLength; return missingModule.MetadataAddress; }, out errorMessage); Assert.Same(TestCompileResult.Instance, compileResult); Assert.Null(errorMessage); }); } [WorkItem(2547, "https://github.com/dotnet/roslyn/issues/2547")] [Fact] public void TryDifferentLinqLibraryOnRetry() { var source = @" using System.Linq; class C { void M(string[] args) { } } class UseLinq { bool b = Enumerable.Any<int>(null); }"; var compilation = CreateCompilation(source, new[] { MscorlibRef, SystemCoreRef }); WithRuntimeInstance(compilation, new[] { MscorlibRef }, runtime => { var context = CreateMethodContext(runtime, "C.M"); var systemCore = SystemCoreRef.ToModuleInstance(); var fakeSystemLinq = CreateCompilationWithMscorlib45("", assemblyName: "System.Linq"). EmitToImageReference().ToModuleInstance(); string errorMessage; CompilationTestData testData; int retryCount = 0; var compileResult = ExpressionCompilerTestHelpers.CompileExpressionWithRetry( runtime.Modules.Select(m => m.MetadataBlock).ToImmutableArray(), "args.Where(a => a.Length > 0)", ImmutableArray<Alias>.Empty, (_1, _2) => context, // ignore new blocks and just keep using the same failed context... (AssemblyIdentity assemblyIdentity, out uint uSize) => { retryCount++; MetadataBlock block; switch (retryCount) { case 1: Assert.Equal(EvaluationContextBase.SystemLinqIdentity, assemblyIdentity); block = fakeSystemLinq.MetadataBlock; break; case 2: Assert.Equal(EvaluationContextBase.SystemCoreIdentity, assemblyIdentity); block = systemCore.MetadataBlock; break; default: throw ExceptionUtilities.Unreachable; } uSize = (uint)block.Size; return block.Pointer; }, errorMessage: out errorMessage, testData: out testData); Assert.Equal(2, retryCount); }); } [Fact] public void TupleNoSystemRuntime() { var source = @"class C { static void M() { var x = 1; var y = (x, 2); var z = (3, 4, (5, 6)); } }"; TupleContextNoSystemRuntime( source, "C.M", "y", @"{ // Code size 2 (0x2) .maxstack 1 .locals init (int V_0, //x (int, int) V_1, //y (int, int, (int, int)) V_2) //z IL_0000: ldloc.1 IL_0001: ret }"); } [WorkItem(16879, "https://github.com/dotnet/roslyn/issues/16879")] [Fact] public void NonTupleNoSystemRuntime() { var source = @"class C { static void M() { var x = 1; var y = (x, 2); var z = (3, 4, (5, 6)); } }"; TupleContextNoSystemRuntime( source, "C.M", "x", @"{ // Code size 2 (0x2) .maxstack 1 .locals init (int V_0, //x (int, int) V_1, //y (int, int, (int, int)) V_2) //z IL_0000: ldloc.0 IL_0001: ret }"); } private static void TupleContextNoSystemRuntime(string source, string methodName, string expression, string expectedIL) { var comp = CreateStandardCompilation(source, new[] { SystemRuntimeFacadeRef, ValueTupleRef }, options: TestOptions.DebugDll); using (var systemRuntime = SystemRuntimeFacadeRef.ToModuleInstance()) { WithRuntimeInstance(comp, new[] { MscorlibRef, ValueTupleRef }, runtime => { ImmutableArray<MetadataBlock> blocks; Guid moduleVersionId; ISymUnmanagedReader symReader; int methodToken; int localSignatureToken; GetContextState(runtime, methodName, out blocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken); string errorMessage; CompilationTestData testData; int retryCount = 0; var compileResult = ExpressionCompilerTestHelpers.CompileExpressionWithRetry( runtime.Modules.Select(m => m.MetadataBlock).ToImmutableArray(), expression, ImmutableArray<Alias>.Empty, (b, u) => EvaluationContext.CreateMethodContext(b.ToCompilation(), symReader, moduleVersionId, methodToken, methodVersion: 1, ilOffset: 0, localSignatureToken: localSignatureToken), (AssemblyIdentity assemblyIdentity, out uint uSize) => { retryCount++; Assert.Equal("System.Runtime", assemblyIdentity.Name); var block = systemRuntime.MetadataBlock; uSize = (uint)block.Size; return block.Pointer; }, errorMessage: out errorMessage, testData: out testData); Assert.Equal(1, retryCount); testData.GetMethodData("<>x.<>m0").VerifyIL(expectedIL); }); } } private sealed class TestCompileResult : CompileResult { public static readonly CompileResult Instance = new TestCompileResult(); private TestCompileResult() : base(null, null, null, null) { } public override Guid GetCustomTypeInfo(out ReadOnlyCollection<byte> payload) { throw new NotImplementedException(); } } private static AssemblyIdentity GetMissingAssemblyIdentity(ErrorCode code, params object[] arguments) { var missingAssemblyIdentities = EvaluationContext.GetMissingAssemblyIdentitiesHelper(code, arguments, EvaluationContextBase.SystemCoreIdentity); return missingAssemblyIdentities.IsDefault ? null : missingAssemblyIdentities.Single(); } private static ImmutableArray<byte> GetMetadataBytes(Compilation comp) { var imageReference = (MetadataImageReference)comp.EmitToImageReference(); var assemblyMetadata = (AssemblyMetadata)imageReference.GetMetadataNoCopy(); var moduleMetadata = assemblyMetadata.GetModules()[0]; return moduleMetadata.Module.PEReaderOpt.GetMetadata().GetContent(); } } }
#region License /* * HttpListener.cs * * This code is derived from HttpListener.cs (System.Net) of Mono * (http://www.mono-project.com). * * The MIT License * * Copyright (c) 2005 Novell, Inc. (http://www.novell.com) * Copyright (c) 2012-2016 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 #region Authors /* * Authors: * - Gonzalo Paniagua Javier <gonzalo@novell.com> */ #endregion #region Contributors /* * Contributors: * - Liryna <liryna.stark@gmail.com> */ #endregion using System; using System.Collections; using System.Collections.Generic; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.Threading; // TODO: Logging. namespace CustomWebSocketSharp.Net { /// <summary> /// Provides a simple, programmatically controlled HTTP listener. /// </summary> public sealed class HttpListener : IDisposable { #region Private Fields private AuthenticationSchemes _authSchemes; private Func<HttpListenerRequest, AuthenticationSchemes> _authSchemeSelector; private string _certFolderPath; private Dictionary<HttpConnection, HttpConnection> _connections; private object _connectionsSync; private List<HttpListenerContext> _ctxQueue; private object _ctxQueueSync; private Dictionary<HttpListenerContext, HttpListenerContext> _ctxRegistry; private object _ctxRegistrySync; private static readonly string _defaultRealm; private bool _disposed; private bool _ignoreWriteExceptions; private volatile bool _listening; private Logger _logger; private HttpListenerPrefixCollection _prefixes; private string _realm; private bool _reuseAddress; private ServerSslConfiguration _sslConfig; private Func<IIdentity, NetworkCredential> _userCredFinder; private List<HttpListenerAsyncResult> _waitQueue; private object _waitQueueSync; #endregion #region Static Constructor static HttpListener () { _defaultRealm = "SECRET AREA"; } #endregion #region Public Constructors /// <summary> /// Initializes a new instance of the <see cref="HttpListener"/> class. /// </summary> public HttpListener () { _authSchemes = AuthenticationSchemes.Anonymous; _connections = new Dictionary<HttpConnection, HttpConnection> (); _connectionsSync = ((ICollection) _connections).SyncRoot; _ctxQueue = new List<HttpListenerContext> (); _ctxQueueSync = ((ICollection) _ctxQueue).SyncRoot; _ctxRegistry = new Dictionary<HttpListenerContext, HttpListenerContext> (); _ctxRegistrySync = ((ICollection) _ctxRegistry).SyncRoot; _logger = new Logger (); _prefixes = new HttpListenerPrefixCollection (this); _waitQueue = new List<HttpListenerAsyncResult> (); _waitQueueSync = ((ICollection) _waitQueue).SyncRoot; } #endregion #region Internal Properties internal bool IsDisposed { get { return _disposed; } } internal bool ReuseAddress { get { return _reuseAddress; } set { _reuseAddress = value; } } #endregion #region Public Properties /// <summary> /// Gets or sets the scheme used to authenticate the clients. /// </summary> /// <value> /// One of the <see cref="CustomWebSocketSharp.Net.AuthenticationSchemes"/> enum values, /// represents the scheme used to authenticate the clients. The default value is /// <see cref="CustomWebSocketSharp.Net.AuthenticationSchemes.Anonymous"/>. /// </value> /// <exception cref="ObjectDisposedException"> /// This listener has been closed. /// </exception> public AuthenticationSchemes AuthenticationSchemes { get { CheckDisposed (); return _authSchemes; } set { CheckDisposed (); _authSchemes = value; } } /// <summary> /// Gets or sets the delegate called to select the scheme used to authenticate the clients. /// </summary> /// <remarks> /// If you set this property, the listener uses the authentication scheme selected by /// the delegate for each request. Or if you don't set, the listener uses the value of /// the <see cref="HttpListener.AuthenticationSchemes"/> property as the authentication /// scheme for all requests. /// </remarks> /// <value> /// A <c>Func&lt;<see cref="HttpListenerRequest"/>, <see cref="AuthenticationSchemes"/>&gt;</c> /// delegate that references the method used to select an authentication scheme. The default /// value is <see langword="null"/>. /// </value> /// <exception cref="ObjectDisposedException"> /// This listener has been closed. /// </exception> public Func<HttpListenerRequest, AuthenticationSchemes> AuthenticationSchemeSelector { get { CheckDisposed (); return _authSchemeSelector; } set { CheckDisposed (); _authSchemeSelector = value; } } /// <summary> /// Gets or sets the path to the folder in which stores the certificate files used to /// authenticate the server on the secure connection. /// </summary> /// <remarks> /// <para> /// This property represents the path to the folder in which stores the certificate files /// associated with each port number of added URI prefixes. A set of the certificate files /// is a pair of the <c>'port number'.cer</c> (DER) and <c>'port number'.key</c> /// (DER, RSA Private Key). /// </para> /// <para> /// If this property is <see langword="null"/> or empty, the result of /// <c>System.Environment.GetFolderPath /// (<see cref="Environment.SpecialFolder.ApplicationData"/>)</c> is used as the default path. /// </para> /// </remarks> /// <value> /// A <see cref="string"/> that represents the path to the folder in which stores /// the certificate files. The default value is <see langword="null"/>. /// </value> /// <exception cref="ObjectDisposedException"> /// This listener has been closed. /// </exception> public string CertificateFolderPath { get { CheckDisposed (); return _certFolderPath; } set { CheckDisposed (); _certFolderPath = value; } } /// <summary> /// Gets or sets a value indicating whether the listener returns exceptions that occur when /// sending the response to the client. /// </summary> /// <value> /// <c>true</c> if the listener shouldn't return those exceptions; otherwise, <c>false</c>. /// The default value is <c>false</c>. /// </value> /// <exception cref="ObjectDisposedException"> /// This listener has been closed. /// </exception> public bool IgnoreWriteExceptions { get { CheckDisposed (); return _ignoreWriteExceptions; } set { CheckDisposed (); _ignoreWriteExceptions = value; } } /// <summary> /// Gets a value indicating whether the listener has been started. /// </summary> /// <value> /// <c>true</c> if the listener has been started; otherwise, <c>false</c>. /// </value> public bool IsListening { get { return _listening; } } /// <summary> /// Gets a value indicating whether the listener can be used with the current operating system. /// </summary> /// <value> /// <c>true</c>. /// </value> public static bool IsSupported { get { return true; } } /// <summary> /// Gets the logging functions. /// </summary> /// <remarks> /// The default logging level is <see cref="LogLevel.Error"/>. If you would like to change it, /// you should set the <c>Log.Level</c> property to any of the <see cref="LogLevel"/> enum /// values. /// </remarks> /// <value> /// A <see cref="Logger"/> that provides the logging functions. /// </value> public Logger Log { get { return _logger; } } /// <summary> /// Gets the URI prefixes handled by the listener. /// </summary> /// <value> /// A <see cref="HttpListenerPrefixCollection"/> that contains the URI prefixes. /// </value> /// <exception cref="ObjectDisposedException"> /// This listener has been closed. /// </exception> public HttpListenerPrefixCollection Prefixes { get { CheckDisposed (); return _prefixes; } } /// <summary> /// Gets or sets the name of the realm associated with the listener. /// </summary> /// <remarks> /// If this property is <see langword="null"/> or empty, <c>"SECRET AREA"</c> will be used as /// the name of the realm. /// </remarks> /// <value> /// A <see cref="string"/> that represents the name of the realm. The default value is /// <see langword="null"/>. /// </value> /// <exception cref="ObjectDisposedException"> /// This listener has been closed. /// </exception> public string Realm { get { CheckDisposed (); return _realm; } set { CheckDisposed (); _realm = value; } } /// <summary> /// Gets or sets the SSL configuration used to authenticate the server and /// optionally the client for secure connection. /// </summary> /// <value> /// A <see cref="ServerSslConfiguration"/> that represents the configuration used to /// authenticate the server and optionally the client for secure connection. /// </value> /// <exception cref="ObjectDisposedException"> /// This listener has been closed. /// </exception> public ServerSslConfiguration SslConfiguration { get { CheckDisposed (); return _sslConfig ?? (_sslConfig = new ServerSslConfiguration (null)); } set { CheckDisposed (); _sslConfig = value; } } /// <summary> /// Gets or sets a value indicating whether, when NTLM authentication is used, /// the authentication information of first request is used to authenticate /// additional requests on the same connection. /// </summary> /// <remarks> /// This property isn't currently supported and always throws /// a <see cref="NotSupportedException"/>. /// </remarks> /// <value> /// <c>true</c> if the authentication information of first request is used; /// otherwise, <c>false</c>. /// </value> /// <exception cref="NotSupportedException"> /// Any use of this property. /// </exception> public bool UnsafeConnectionNtlmAuthentication { get { throw new NotSupportedException (); } set { throw new NotSupportedException (); } } /// <summary> /// Gets or sets the delegate called to find the credentials for an identity used to /// authenticate a client. /// </summary> /// <value> /// A <c>Func&lt;<see cref="IIdentity"/>, <see cref="NetworkCredential"/>&gt;</c> delegate /// that references the method used to find the credentials. The default value is /// <see langword="null"/>. /// </value> /// <exception cref="ObjectDisposedException"> /// This listener has been closed. /// </exception> public Func<IIdentity, NetworkCredential> UserCredentialsFinder { get { CheckDisposed (); return _userCredFinder; } set { CheckDisposed (); _userCredFinder = value; } } #endregion #region Private Methods private void cleanupConnections () { HttpConnection[] conns = null; lock (_connectionsSync) { if (_connections.Count == 0) return; // Need to copy this since closing will call the RemoveConnection method. var keys = _connections.Keys; conns = new HttpConnection[keys.Count]; keys.CopyTo (conns, 0); _connections.Clear (); } for (var i = conns.Length - 1; i >= 0; i--) conns[i].Close (true); } private void cleanupContextQueue (bool sendServiceUnavailable) { HttpListenerContext[] ctxs = null; lock (_ctxQueueSync) { if (_ctxQueue.Count == 0) return; ctxs = _ctxQueue.ToArray (); _ctxQueue.Clear (); } if (!sendServiceUnavailable) return; foreach (var ctx in ctxs) { var res = ctx.Response; res.StatusCode = (int) HttpStatusCode.ServiceUnavailable; res.Close (); } } private void cleanupContextRegistry () { HttpListenerContext[] ctxs = null; lock (_ctxRegistrySync) { if (_ctxRegistry.Count == 0) return; // Need to copy this since closing will call the UnregisterContext method. var keys = _ctxRegistry.Keys; ctxs = new HttpListenerContext[keys.Count]; keys.CopyTo (ctxs, 0); _ctxRegistry.Clear (); } for (var i = ctxs.Length - 1; i >= 0; i--) ctxs[i].Connection.Close (true); } private void cleanupWaitQueue (Exception exception) { HttpListenerAsyncResult[] aress = null; lock (_waitQueueSync) { if (_waitQueue.Count == 0) return; aress = _waitQueue.ToArray (); _waitQueue.Clear (); } foreach (var ares in aress) ares.Complete (exception); } private void close (bool force) { if (_listening) { _listening = false; EndPointManager.RemoveListener (this); } lock (_ctxRegistrySync) cleanupContextQueue (!force); cleanupContextRegistry (); cleanupConnections (); cleanupWaitQueue (new ObjectDisposedException (GetType ().ToString ())); _disposed = true; } private HttpListenerAsyncResult getAsyncResultFromQueue () { if (_waitQueue.Count == 0) return null; var ares = _waitQueue[0]; _waitQueue.RemoveAt (0); return ares; } private HttpListenerContext getContextFromQueue () { if (_ctxQueue.Count == 0) return null; var ctx = _ctxQueue[0]; _ctxQueue.RemoveAt (0); return ctx; } #endregion #region Internal Methods internal bool AddConnection (HttpConnection connection) { if (!_listening) return false; lock (_connectionsSync) { if (!_listening) return false; _connections[connection] = connection; return true; } } internal HttpListenerAsyncResult BeginGetContext (HttpListenerAsyncResult asyncResult) { lock (_ctxRegistrySync) { if (!_listening) throw new HttpListenerException (995); var ctx = getContextFromQueue (); if (ctx == null) _waitQueue.Add (asyncResult); else asyncResult.Complete (ctx, true); return asyncResult; } } internal void CheckDisposed () { if (_disposed) throw new ObjectDisposedException (GetType ().ToString ()); } internal string GetRealm () { var realm = _realm; return realm != null && realm.Length > 0 ? realm : _defaultRealm; } internal Func<IIdentity, NetworkCredential> GetUserCredentialsFinder () { return _userCredFinder; } internal bool RegisterContext (HttpListenerContext context) { if (!_listening) return false; lock (_ctxRegistrySync) { if (!_listening) return false; _ctxRegistry[context] = context; var ares = getAsyncResultFromQueue (); if (ares == null) _ctxQueue.Add (context); else ares.Complete (context); return true; } } internal void RemoveConnection (HttpConnection connection) { lock (_connectionsSync) _connections.Remove (connection); } internal AuthenticationSchemes SelectAuthenticationScheme (HttpListenerRequest request) { var selector = _authSchemeSelector; if (selector == null) return _authSchemes; try { return selector (request); } catch { return AuthenticationSchemes.None; } } internal void UnregisterContext (HttpListenerContext context) { lock (_ctxRegistrySync) _ctxRegistry.Remove (context); } #endregion #region Public Methods /// <summary> /// Shuts down the listener immediately. /// </summary> public void Abort () { if (_disposed) return; close (true); } /// <summary> /// Begins getting an incoming request asynchronously. /// </summary> /// <remarks> /// This asynchronous operation must be completed by calling the <c>EndGetContext</c> method. /// Typically, the method is invoked by the <paramref name="callback"/> delegate. /// </remarks> /// <returns> /// An <see cref="IAsyncResult"/> that represents the status of the asynchronous operation. /// </returns> /// <param name="callback"> /// An <see cref="AsyncCallback"/> delegate that references the method to invoke when /// the asynchronous operation completes. /// </param> /// <param name="state"> /// An <see cref="object"/> that represents a user defined object to pass to /// the <paramref name="callback"/> delegate. /// </param> /// <exception cref="InvalidOperationException"> /// <para> /// This listener has no URI prefix on which listens. /// </para> /// <para> /// -or- /// </para> /// <para> /// This listener hasn't been started, or is currently stopped. /// </para> /// </exception> /// <exception cref="ObjectDisposedException"> /// This listener has been closed. /// </exception> public IAsyncResult BeginGetContext (AsyncCallback callback, Object state) { CheckDisposed (); if (_prefixes.Count == 0) throw new InvalidOperationException ("The listener has no URI prefix on which listens."); if (!_listening) throw new InvalidOperationException ("The listener hasn't been started."); return BeginGetContext (new HttpListenerAsyncResult (callback, state)); } /// <summary> /// Shuts down the listener. /// </summary> public void Close () { if (_disposed) return; close (false); } /// <summary> /// Ends an asynchronous operation to get an incoming request. /// </summary> /// <remarks> /// This method completes an asynchronous operation started by calling /// the <c>BeginGetContext</c> method. /// </remarks> /// <returns> /// A <see cref="HttpListenerContext"/> that represents a request. /// </returns> /// <param name="asyncResult"> /// An <see cref="IAsyncResult"/> obtained by calling the <c>BeginGetContext</c> method. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="asyncResult"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="asyncResult"/> wasn't obtained by calling the <c>BeginGetContext</c> method. /// </exception> /// <exception cref="InvalidOperationException"> /// This method was already called for the specified <paramref name="asyncResult"/>. /// </exception> /// <exception cref="ObjectDisposedException"> /// This listener has been closed. /// </exception> public HttpListenerContext EndGetContext (IAsyncResult asyncResult) { CheckDisposed (); if (asyncResult == null) throw new ArgumentNullException ("asyncResult"); var ares = asyncResult as HttpListenerAsyncResult; if (ares == null) throw new ArgumentException ("A wrong IAsyncResult.", "asyncResult"); if (ares.EndCalled) throw new InvalidOperationException ("This IAsyncResult cannot be reused."); ares.EndCalled = true; if (!ares.IsCompleted) ares.AsyncWaitHandle.WaitOne (); return ares.GetContext (); // This may throw an exception. } /// <summary> /// Gets an incoming request. /// </summary> /// <remarks> /// This method waits for an incoming request, and returns when a request is received. /// </remarks> /// <returns> /// A <see cref="HttpListenerContext"/> that represents a request. /// </returns> /// <exception cref="InvalidOperationException"> /// <para> /// This listener has no URI prefix on which listens. /// </para> /// <para> /// -or- /// </para> /// <para> /// This listener hasn't been started, or is currently stopped. /// </para> /// </exception> /// <exception cref="ObjectDisposedException"> /// This listener has been closed. /// </exception> public HttpListenerContext GetContext () { CheckDisposed (); if (_prefixes.Count == 0) throw new InvalidOperationException ("The listener has no URI prefix on which listens."); if (!_listening) throw new InvalidOperationException ("The listener hasn't been started."); var ares = BeginGetContext (new HttpListenerAsyncResult (null, null)); ares.InGet = true; return EndGetContext (ares); } /// <summary> /// Starts receiving incoming requests. /// </summary> /// <exception cref="ObjectDisposedException"> /// This listener has been closed. /// </exception> public void Start () { CheckDisposed (); if (_listening) return; EndPointManager.AddListener (this); _listening = true; } /// <summary> /// Stops receiving incoming requests. /// </summary> /// <exception cref="ObjectDisposedException"> /// This listener has been closed. /// </exception> public void Stop () { CheckDisposed (); if (!_listening) return; _listening = false; EndPointManager.RemoveListener (this); lock (_ctxRegistrySync) cleanupContextQueue (true); cleanupContextRegistry (); cleanupConnections (); cleanupWaitQueue (new HttpListenerException (995, "The listener is stopped.")); } #endregion #region Explicit Interface Implementations /// <summary> /// Releases all resources used by the listener. /// </summary> void IDisposable.Dispose () { if (_disposed) return; close (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. using System.IO; using System.Diagnostics; using System.Data.Common; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; using System.Runtime.Serialization; using System.Runtime.CompilerServices; namespace System.Data.SqlTypes { [XmlSchemaProvider("GetXsdType")] public sealed class SqlChars : INullable, IXmlSerializable, ISerializable { // -------------------------------------------------------------- // Data members // -------------------------------------------------------------- // SqlChars has five possible states // 1) SqlChars is Null // - m_stream must be null, m_lCuLen must be x_lNull // 2) SqlChars contains a valid buffer, // - m_rgchBuf must not be null, and m_stream must be null // 3) SqlChars contains a valid pointer // - m_rgchBuf could be null or not, // if not null, content is garbage, should never look into it. // - m_stream must be null. // 4) SqlChars contains a SqlStreamChars // - m_stream must not be null // - m_rgchBuf could be null or not. if not null, content is garbage, should never look into it. // - m_lCurLen must be x_lNull. // 5) SqlChars contains a Lazy Materialized Blob (ie, StorageState.Delayed) // internal char[] _rgchBuf; // Data buffer private long _lCurLen; // Current data length internal SqlStreamChars _stream; private SqlBytesCharsState _state; private char[] _rgchWorkBuf; // A 1-char work buffer. // The max data length that we support at this time. private const long x_lMaxLen = System.Int32.MaxValue; private const long x_lNull = -1L; // -------------------------------------------------------------- // Constructor(s) // -------------------------------------------------------------- // Public default constructor used for XML serialization public SqlChars() { SetNull(); } // Create a SqlChars with an in-memory buffer public SqlChars(char[] buffer) { _rgchBuf = buffer; _stream = null; if (_rgchBuf == null) { _state = SqlBytesCharsState.Null; _lCurLen = x_lNull; } else { _state = SqlBytesCharsState.Buffer; _lCurLen = _rgchBuf.Length; } _rgchWorkBuf = null; AssertValid(); } // Create a SqlChars from a SqlString public SqlChars(SqlString value) : this(value.IsNull ? null : value.Value.ToCharArray()) { } // Create a SqlChars from a SqlStreamChars internal SqlChars(SqlStreamChars s) { _rgchBuf = null; _lCurLen = x_lNull; _stream = s; _state = (s == null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Stream; _rgchWorkBuf = null; AssertValid(); } // Constructor required for serialization. Deserializes as a Buffer. If the bits have been tampered with // then this will throw a SerializationException or a InvalidCastException. private SqlChars(SerializationInfo info, StreamingContext context) { _stream = null; _rgchWorkBuf = null; if (info.GetBoolean("IsNull")) { _state = SqlBytesCharsState.Null; _rgchBuf = null; } else { _state = SqlBytesCharsState.Buffer; _rgchBuf = (char[])info.GetValue("data", typeof(char[])); _lCurLen = _rgchBuf.Length; } AssertValid(); } // -------------------------------------------------------------- // Public properties // -------------------------------------------------------------- // INullable public bool IsNull { get { return _state == SqlBytesCharsState.Null; } } // Property: the in-memory buffer of SqlChars // Return Buffer even if SqlChars is Null. public char[] Buffer { get { if (FStream()) { CopyStreamToBuffer(); } return _rgchBuf; } } // Property: the actual length of the data public long Length { get { switch (_state) { case SqlBytesCharsState.Null: throw new SqlNullValueException(); case SqlBytesCharsState.Stream: return _stream.Length; default: return _lCurLen; } } } // Property: the max length of the data // Return MaxLength even if SqlChars is Null. // When the buffer is also null, return -1. // If containing a Stream, return -1. public long MaxLength { get { switch (_state) { case SqlBytesCharsState.Stream: return -1L; default: return (_rgchBuf == null) ? -1L : _rgchBuf.Length; } } } // Property: get a copy of the data in a new char[] array. public char[] Value { get { char[] buffer; switch (_state) { case SqlBytesCharsState.Null: throw new SqlNullValueException(); case SqlBytesCharsState.Stream: if (_stream.Length > x_lMaxLen) throw new SqlTypeException(SR.SqlMisc_BufferInsufficientMessage); buffer = new char[_stream.Length]; if (_stream.Position != 0) _stream.Seek(0, SeekOrigin.Begin); _stream.Read(buffer, 0, checked((int)_stream.Length)); break; default: buffer = new char[_lCurLen]; Array.Copy(_rgchBuf, 0, buffer, 0, (int)_lCurLen); break; } return buffer; } } // class indexer public char this[long offset] { get { if (offset < 0 || offset >= Length) throw new ArgumentOutOfRangeException(nameof(offset)); if (_rgchWorkBuf == null) _rgchWorkBuf = new char[1]; Read(offset, _rgchWorkBuf, 0, 1); return _rgchWorkBuf[0]; } set { if (_rgchWorkBuf == null) _rgchWorkBuf = new char[1]; _rgchWorkBuf[0] = value; Write(offset, _rgchWorkBuf, 0, 1); } } internal SqlStreamChars Stream { get { return FStream() ? _stream : new StreamOnSqlChars(this); } set { _lCurLen = x_lNull; _stream = value; _state = (value == null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Stream; AssertValid(); } } public StorageState Storage { get { switch (_state) { case SqlBytesCharsState.Null: throw new SqlNullValueException(); case SqlBytesCharsState.Stream: return StorageState.Stream; case SqlBytesCharsState.Buffer: return StorageState.Buffer; default: return StorageState.UnmanagedBuffer; } } } // -------------------------------------------------------------- // Public methods // -------------------------------------------------------------- public void SetNull() { _lCurLen = x_lNull; _stream = null; _state = SqlBytesCharsState.Null; AssertValid(); } // Set the current length of the data // If the SqlChars is Null, setLength will make it non-Null. public void SetLength(long value) { if (value < 0) throw new ArgumentOutOfRangeException(nameof(value)); if (FStream()) { _stream.SetLength(value); } else { // If there is a buffer, even the value of SqlChars is Null, // still allow setting length to zero, which will make it not Null. // If the buffer is null, raise exception // if (null == _rgchBuf) throw new SqlTypeException(SR.SqlMisc_NoBufferMessage); if (value > _rgchBuf.Length) throw new ArgumentOutOfRangeException(nameof(value)); else if (IsNull) // At this point we know that value is small enough // Go back in buffer mode _state = SqlBytesCharsState.Buffer; _lCurLen = value; } AssertValid(); } // Read data of specified length from specified offset into a buffer public long Read(long offset, char[] buffer, int offsetInBuffer, int count) { if (IsNull) throw new SqlNullValueException(); // Validate the arguments if (buffer == null) throw new ArgumentNullException(nameof(buffer)); if (offset > Length || offset < 0) throw new ArgumentOutOfRangeException(nameof(offset)); if (offsetInBuffer > buffer.Length || offsetInBuffer < 0) throw new ArgumentOutOfRangeException(nameof(offsetInBuffer)); if (count < 0 || count > buffer.Length - offsetInBuffer) throw new ArgumentOutOfRangeException(nameof(count)); // Adjust count based on data length if (count > Length - offset) count = (int)(Length - offset); if (count != 0) { switch (_state) { case SqlBytesCharsState.Stream: if (_stream.Position != offset) _stream.Seek(offset, SeekOrigin.Begin); _stream.Read(buffer, offsetInBuffer, count); break; default: Array.Copy(_rgchBuf, offset, buffer, offsetInBuffer, count); break; } } return count; } // Write data of specified length into the SqlChars from specified offset public void Write(long offset, char[] buffer, int offsetInBuffer, int count) { if (FStream()) { if (_stream.Position != offset) _stream.Seek(offset, SeekOrigin.Begin); _stream.Write(buffer, offsetInBuffer, count); } else { // Validate the arguments if (buffer == null) throw new ArgumentNullException(nameof(buffer)); if (_rgchBuf == null) throw new SqlTypeException(SR.SqlMisc_NoBufferMessage); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset)); if (offset > _rgchBuf.Length) throw new SqlTypeException(SR.SqlMisc_BufferInsufficientMessage); if (offsetInBuffer < 0 || offsetInBuffer > buffer.Length) throw new ArgumentOutOfRangeException(nameof(offsetInBuffer)); if (count < 0 || count > buffer.Length - offsetInBuffer) throw new ArgumentOutOfRangeException(nameof(count)); if (count > _rgchBuf.Length - offset) throw new SqlTypeException(SR.SqlMisc_BufferInsufficientMessage); if (IsNull) { // If NULL and there is buffer inside, we only allow writing from // offset zero. // if (offset != 0) throw new SqlTypeException(SR.SqlMisc_WriteNonZeroOffsetOnNullMessage); // treat as if our current length is zero. // Note this has to be done after all inputs are validated, so that // we won't throw exception after this point. // _lCurLen = 0; _state = SqlBytesCharsState.Buffer; } else if (offset > _lCurLen) { // Don't allow writing from an offset that this larger than current length. // It would leave uninitialized data in the buffer. // throw new SqlTypeException(SR.SqlMisc_WriteOffsetLargerThanLenMessage); } if (count != 0) { Array.Copy(buffer, offsetInBuffer, _rgchBuf, offset, count); // If the last position that has been written is after // the current data length, reset the length if (_lCurLen < offset + count) _lCurLen = offset + count; } } AssertValid(); } public SqlString ToSqlString() { return IsNull ? SqlString.Null : new string(Value); } // -------------------------------------------------------------- // Conversion operators // -------------------------------------------------------------- // Alternative method: ToSqlString() public static explicit operator SqlString(SqlChars value) { return value.ToSqlString(); } // Alternative method: constructor SqlChars(SqlString) public static explicit operator SqlChars(SqlString value) { return new SqlChars(value); } // -------------------------------------------------------------- // Private utility functions // -------------------------------------------------------------- [Conditional("DEBUG")] private void AssertValid() { Debug.Assert(_state >= SqlBytesCharsState.Null && _state <= SqlBytesCharsState.Stream); if (IsNull) { } else { Debug.Assert((_lCurLen >= 0 && _lCurLen <= x_lMaxLen) || FStream()); Debug.Assert(FStream() || (_rgchBuf != null && _lCurLen <= _rgchBuf.Length)); Debug.Assert(!FStream() || (_lCurLen == x_lNull)); } Debug.Assert(_rgchWorkBuf == null || _rgchWorkBuf.Length == 1); } // whether the SqlChars contains a Stream internal bool FStream() { return _state == SqlBytesCharsState.Stream; } // Copy the data from the Stream to the array buffer. // If the SqlChars doesn't hold a buffer or the buffer // is not big enough, allocate new char array. private void CopyStreamToBuffer() { Debug.Assert(FStream()); long lStreamLen = _stream.Length; if (lStreamLen >= x_lMaxLen) throw new SqlTypeException(SR.SqlMisc_BufferInsufficientMessage); if (_rgchBuf == null || _rgchBuf.Length < lStreamLen) _rgchBuf = new char[lStreamLen]; if (_stream.Position != 0) _stream.Seek(0, SeekOrigin.Begin); _stream.Read(_rgchBuf, 0, (int)lStreamLen); _stream = null; _lCurLen = lStreamLen; _state = SqlBytesCharsState.Buffer; AssertValid(); } private void SetBuffer(char[] buffer) { _rgchBuf = buffer; _lCurLen = (_rgchBuf == null) ? x_lNull : _rgchBuf.Length; _stream = null; _state = (_rgchBuf == null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Buffer; AssertValid(); } // -------------------------------------------------------------- // XML Serialization // -------------------------------------------------------------- XmlSchema IXmlSerializable.GetSchema() { return null; } void IXmlSerializable.ReadXml(XmlReader r) { char[] value = null; string isNull = r.GetAttribute("nil", XmlSchema.InstanceNamespace); if (isNull != null && XmlConvert.ToBoolean(isNull)) { // Read the next value. r.ReadElementString(); SetNull(); } else { value = r.ReadElementString().ToCharArray(); SetBuffer(value); } } void IXmlSerializable.WriteXml(XmlWriter writer) { if (IsNull) { writer.WriteAttributeString("xsi", "nil", XmlSchema.InstanceNamespace, "true"); } else { char[] value = Buffer; writer.WriteString(new string(value, 0, (int)(Length))); } } public static XmlQualifiedName GetXsdType(XmlSchemaSet schemaSet) { return new XmlQualifiedName("string", XmlSchema.Namespace); } // -------------------------------------------------------------- // Serialization using ISerializable // -------------------------------------------------------------- // State information is not saved. The current state is converted to Buffer and only the underlying // array is serialized, except for Null, in which case this state is kept. void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { switch (_state) { case SqlBytesCharsState.Null: info.AddValue("IsNull", true); break; case SqlBytesCharsState.Buffer: info.AddValue("IsNull", false); info.AddValue("data", _rgchBuf); break; case SqlBytesCharsState.Stream: CopyStreamToBuffer(); goto case SqlBytesCharsState.Buffer; default: Debug.Assert(false); goto case SqlBytesCharsState.Null; } } // -------------------------------------------------------------- // Static fields, properties // -------------------------------------------------------------- // Get a Null instance. // Since SqlChars is mutable, have to be property and create a new one each time. public static SqlChars Null { get { return new SqlChars((char[])null); } } } // class SqlChars // StreamOnSqlChars is a stream build on top of SqlChars, and // provides the Stream interface. The purpose is to help users // to read/write SqlChars object. internal sealed class StreamOnSqlChars : SqlStreamChars { // -------------------------------------------------------------- // Data members // -------------------------------------------------------------- private SqlChars _sqlchars; // the SqlChars object private long _lPosition; // -------------------------------------------------------------- // Constructor(s) // -------------------------------------------------------------- internal StreamOnSqlChars(SqlChars s) { _sqlchars = s; _lPosition = 0; } // -------------------------------------------------------------- // Public properties // -------------------------------------------------------------- public override bool IsNull { get { return _sqlchars == null || _sqlchars.IsNull; } } public override long Length { get { CheckIfStreamClosed("get_Length"); return _sqlchars.Length; } } public override long Position { get { CheckIfStreamClosed("get_Position"); return _lPosition; } set { CheckIfStreamClosed("set_Position"); if (value < 0 || value > _sqlchars.Length) throw new ArgumentOutOfRangeException(nameof(value)); else _lPosition = value; } } // -------------------------------------------------------------- // Public methods // -------------------------------------------------------------- public override long Seek(long offset, SeekOrigin origin) { CheckIfStreamClosed(); long lPosition = 0; switch (origin) { case SeekOrigin.Begin: if (offset < 0 || offset > _sqlchars.Length) throw ADP.ArgumentOutOfRange(nameof(offset)); _lPosition = offset; break; case SeekOrigin.Current: lPosition = _lPosition + offset; if (lPosition < 0 || lPosition > _sqlchars.Length) throw ADP.ArgumentOutOfRange(nameof(offset)); _lPosition = lPosition; break; case SeekOrigin.End: lPosition = _sqlchars.Length + offset; if (lPosition < 0 || lPosition > _sqlchars.Length) throw ADP.ArgumentOutOfRange(nameof(offset)); _lPosition = lPosition; break; default: throw ADP.ArgumentOutOfRange(nameof(offset)); } return _lPosition; } // The Read/Write/Readchar/Writechar simply delegates to SqlChars public override int Read(char[] buffer, int offset, int count) { CheckIfStreamClosed(); if (buffer == null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0 || offset > buffer.Length) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0 || count > buffer.Length - offset) throw new ArgumentOutOfRangeException(nameof(count)); int icharsRead = (int)_sqlchars.Read(_lPosition, buffer, offset, count); _lPosition += icharsRead; return icharsRead; } public override void Write(char[] buffer, int offset, int count) { CheckIfStreamClosed(); if (buffer == null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0 || offset > buffer.Length) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0 || count > buffer.Length - offset) throw new ArgumentOutOfRangeException(nameof(count)); _sqlchars.Write(_lPosition, buffer, offset, count); _lPosition += count; } public override void SetLength(long value) { CheckIfStreamClosed(); _sqlchars.SetLength(value); if (_lPosition > value) _lPosition = value; } protected override void Dispose(bool disposing) { // When m_sqlchars is null, it means the stream has been closed, and // any opearation in the future should fail. // This is the only case that m_sqlchars is null. _sqlchars = null; } // -------------------------------------------------------------- // Private utility functions // -------------------------------------------------------------- private bool FClosed() { return _sqlchars == null; } private void CheckIfStreamClosed([CallerMemberName] string methodname = "") { if (FClosed()) throw ADP.StreamClosed(methodname); } } // class StreamOnSqlChars } // namespace System.Data.SqlTypes
using System; using Microsoft.Data.Entity; using Microsoft.Data.Entity.Infrastructure; using Microsoft.Data.Entity.Metadata; using Microsoft.Data.Entity.Migrations; using AllReady.Models; namespace AllReady.Migrations { [DbContext(typeof(AllReadyContext))] [Migration("20160607115449_AddingItinerary")] partial class AddingItinerary { protected override void BuildTargetModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "7.0.0-rc1-16348") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("AllReady.Models.AllReadyTask", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Description"); b.Property<DateTimeOffset?>("EndDateTime"); b.Property<int?>("EventId"); b.Property<bool>("IsAllowWaitList"); b.Property<bool>("IsLimitVolunteers"); b.Property<string>("Name") .IsRequired(); b.Property<int>("NumberOfVolunteersRequired"); b.Property<int?>("OrganizationId"); b.Property<DateTimeOffset?>("StartDateTime"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.ApplicationUser", b => { b.Property<string>("Id"); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasAnnotation("MaxLength", 256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("Name"); b.Property<string>("NormalizedEmail") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedUserName") .HasAnnotation("MaxLength", 256); b.Property<int?>("OrganizationId"); b.Property<string>("PasswordHash"); b.Property<string>("PendingNewEmail"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<string>("TimeZoneId") .IsRequired(); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasAnnotation("Relational:Name", "EmailIndex"); b.HasIndex("NormalizedUserName") .HasAnnotation("Relational:Name", "UserNameIndex"); b.HasAnnotation("Relational:TableName", "AspNetUsers"); }); modelBuilder.Entity("AllReady.Models.Campaign", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int?>("CampaignImpactId"); b.Property<string>("Description"); b.Property<DateTimeOffset>("EndDateTime"); b.Property<string>("ExternalUrl"); b.Property<string>("ExternalUrlText"); b.Property<bool>("Featured"); b.Property<string>("FullDescription"); b.Property<string>("ImageUrl"); b.Property<int?>("LocationId"); b.Property<bool>("Locked"); b.Property<int>("ManagingOrganizationId"); b.Property<string>("Name") .IsRequired(); b.Property<string>("OrganizerId"); b.Property<DateTimeOffset>("StartDateTime"); b.Property<string>("TimeZoneId") .IsRequired(); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.CampaignContact", b => { b.Property<int>("CampaignId"); b.Property<int>("ContactId"); b.Property<int>("ContactType"); b.HasKey("CampaignId", "ContactId", "ContactType"); }); modelBuilder.Entity("AllReady.Models.CampaignImpact", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("CurrentImpactLevel"); b.Property<bool>("Display"); b.Property<int>("ImpactType"); b.Property<int>("NumericImpactGoal"); b.Property<string>("TextualImpactGoal"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.CampaignSponsors", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int?>("CampaignId"); b.Property<int?>("OrganizationId"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.ClosestLocation", b => { b.Property<string>("PostalCode"); b.Property<string>("City"); b.Property<double>("Distance"); b.Property<string>("State"); b.HasKey("PostalCode"); }); modelBuilder.Entity("AllReady.Models.Contact", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Email"); b.Property<string>("FirstName"); b.Property<string>("LastName"); b.Property<string>("PhoneNumber"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.Event", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("CampaignId"); b.Property<string>("Description"); b.Property<DateTimeOffset>("EndDateTime"); b.Property<int>("EventType"); b.Property<string>("ImageUrl"); b.Property<bool>("IsAllowWaitList"); b.Property<bool>("IsLimitVolunteers"); b.Property<int?>("LocationId"); b.Property<string>("Name") .IsRequired(); b.Property<int>("NumberOfVolunteersRequired"); b.Property<string>("OrganizerId"); b.Property<DateTimeOffset>("StartDateTime"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.EventSignup", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("AdditionalInfo"); b.Property<DateTime?>("CheckinDateTime"); b.Property<int?>("EventId"); b.Property<string>("PreferredEmail"); b.Property<string>("PreferredPhoneNumber"); b.Property<DateTime>("SignupDateTime"); b.Property<string>("UserId"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.EventSkill", b => { b.Property<int>("EventId"); b.Property<int>("SkillId"); b.HasKey("EventId", "SkillId"); }); modelBuilder.Entity("AllReady.Models.Itinerary", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("Date"); b.Property<int>("EventId"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.ItineraryRequest", b => { b.Property<int>("ItineraryId"); b.Property<Guid>("RequestId"); b.HasKey("ItineraryId", "RequestId"); }); modelBuilder.Entity("AllReady.Models.Location", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Address1"); b.Property<string>("Address2"); b.Property<string>("City"); b.Property<string>("Country"); b.Property<string>("Name"); b.Property<string>("PhoneNumber"); b.Property<string>("PostalCode"); b.Property<string>("State"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.Organization", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int?>("LocationId"); b.Property<string>("LogoUrl"); b.Property<string>("Name") .IsRequired(); b.Property<string>("PrivacyPolicy"); b.Property<string>("WebUrl"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.OrganizationContact", b => { b.Property<int>("OrganizationId"); b.Property<int>("ContactId"); b.Property<int>("ContactType"); b.HasKey("OrganizationId", "ContactId", "ContactType"); }); modelBuilder.Entity("AllReady.Models.PostalCodeGeo", b => { b.Property<string>("PostalCode"); b.Property<string>("City"); b.Property<string>("State"); b.HasKey("PostalCode"); }); modelBuilder.Entity("AllReady.Models.PostalCodeGeoCoordinate", b => { b.Property<double>("Latitude"); b.Property<double>("Longitude"); b.HasKey("Latitude", "Longitude"); }); modelBuilder.Entity("AllReady.Models.Request", b => { b.Property<Guid>("RequestId") .ValueGeneratedOnAdd(); b.Property<string>("Address"); b.Property<string>("City"); b.Property<string>("Email"); b.Property<double>("Lattitude"); b.Property<double>("Longitude"); b.Property<string>("Name"); b.Property<string>("Phone"); b.Property<string>("ProviderData"); b.Property<string>("ProviderId"); b.Property<string>("State"); b.Property<int>("Status"); b.Property<string>("Zip"); b.HasKey("RequestId"); }); modelBuilder.Entity("AllReady.Models.Resource", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("CategoryTag"); b.Property<string>("Description"); b.Property<string>("MediaUrl"); b.Property<string>("Name"); b.Property<DateTime>("PublishDateBegin"); b.Property<DateTime>("PublishDateEnd"); b.Property<string>("ResourceUrl"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.Skill", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Description"); b.Property<string>("Name") .IsRequired(); b.Property<int?>("OwningOrganizationId"); b.Property<int?>("ParentSkillId"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.TaskSignup", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("AdditionalInfo"); b.Property<int?>("ItineraryId"); b.Property<string>("PreferredEmail"); b.Property<string>("PreferredPhoneNumber"); b.Property<string>("Status"); b.Property<DateTime>("StatusDateTimeUtc"); b.Property<string>("StatusDescription"); b.Property<int?>("TaskId"); b.Property<string>("UserId"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.TaskSkill", b => { b.Property<int>("TaskId"); b.Property<int>("SkillId"); b.HasKey("TaskId", "SkillId"); }); modelBuilder.Entity("AllReady.Models.UserSkill", b => { b.Property<string>("UserId"); b.Property<int>("SkillId"); b.HasKey("UserId", "SkillId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b => { b.Property<string>("Id"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedName") .HasAnnotation("Relational:Name", "RoleNameIndex"); b.HasAnnotation("Relational:TableName", "AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasAnnotation("Relational:TableName", "AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasAnnotation("Relational:TableName", "AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasAnnotation("Relational:TableName", "AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasAnnotation("Relational:TableName", "AspNetUserRoles"); }); modelBuilder.Entity("AllReady.Models.AllReadyTask", b => { b.HasOne("AllReady.Models.Event") .WithMany() .HasForeignKey("EventId"); b.HasOne("AllReady.Models.Organization") .WithMany() .HasForeignKey("OrganizationId"); }); modelBuilder.Entity("AllReady.Models.ApplicationUser", b => { b.HasOne("AllReady.Models.Organization") .WithMany() .HasForeignKey("OrganizationId"); }); modelBuilder.Entity("AllReady.Models.Campaign", b => { b.HasOne("AllReady.Models.CampaignImpact") .WithMany() .HasForeignKey("CampaignImpactId"); b.HasOne("AllReady.Models.Location") .WithMany() .HasForeignKey("LocationId"); b.HasOne("AllReady.Models.Organization") .WithMany() .HasForeignKey("ManagingOrganizationId"); b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("OrganizerId"); }); modelBuilder.Entity("AllReady.Models.CampaignContact", b => { b.HasOne("AllReady.Models.Campaign") .WithMany() .HasForeignKey("CampaignId"); b.HasOne("AllReady.Models.Contact") .WithMany() .HasForeignKey("ContactId"); }); modelBuilder.Entity("AllReady.Models.CampaignSponsors", b => { b.HasOne("AllReady.Models.Campaign") .WithMany() .HasForeignKey("CampaignId"); b.HasOne("AllReady.Models.Organization") .WithMany() .HasForeignKey("OrganizationId"); }); modelBuilder.Entity("AllReady.Models.Event", b => { b.HasOne("AllReady.Models.Campaign") .WithMany() .HasForeignKey("CampaignId"); b.HasOne("AllReady.Models.Location") .WithMany() .HasForeignKey("LocationId"); b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("OrganizerId"); }); modelBuilder.Entity("AllReady.Models.EventSignup", b => { b.HasOne("AllReady.Models.Event") .WithMany() .HasForeignKey("EventId"); b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("AllReady.Models.EventSkill", b => { b.HasOne("AllReady.Models.Event") .WithMany() .HasForeignKey("EventId"); b.HasOne("AllReady.Models.Skill") .WithMany() .HasForeignKey("SkillId"); }); modelBuilder.Entity("AllReady.Models.Itinerary", b => { b.HasOne("AllReady.Models.Event") .WithMany() .HasForeignKey("EventId"); }); modelBuilder.Entity("AllReady.Models.ItineraryRequest", b => { b.HasOne("AllReady.Models.Itinerary") .WithMany() .HasForeignKey("ItineraryId"); b.HasOne("AllReady.Models.Request") .WithMany() .HasForeignKey("RequestId"); }); modelBuilder.Entity("AllReady.Models.Organization", b => { b.HasOne("AllReady.Models.Location") .WithMany() .HasForeignKey("LocationId"); }); modelBuilder.Entity("AllReady.Models.OrganizationContact", b => { b.HasOne("AllReady.Models.Contact") .WithMany() .HasForeignKey("ContactId"); b.HasOne("AllReady.Models.Organization") .WithMany() .HasForeignKey("OrganizationId"); }); modelBuilder.Entity("AllReady.Models.Skill", b => { b.HasOne("AllReady.Models.Organization") .WithMany() .HasForeignKey("OwningOrganizationId"); b.HasOne("AllReady.Models.Skill") .WithMany() .HasForeignKey("ParentSkillId"); }); modelBuilder.Entity("AllReady.Models.TaskSignup", b => { b.HasOne("AllReady.Models.Itinerary") .WithMany() .HasForeignKey("ItineraryId"); b.HasOne("AllReady.Models.AllReadyTask") .WithMany() .HasForeignKey("TaskId"); b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("AllReady.Models.TaskSkill", b => { b.HasOne("AllReady.Models.Skill") .WithMany() .HasForeignKey("SkillId"); b.HasOne("AllReady.Models.AllReadyTask") .WithMany() .HasForeignKey("TaskId"); }); modelBuilder.Entity("AllReady.Models.UserSkill", b => { b.HasOne("AllReady.Models.Skill") .WithMany() .HasForeignKey("SkillId"); b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .WithMany() .HasForeignKey("RoleId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .WithMany() .HasForeignKey("RoleId"); b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); } } }
using System; using Server; using Server.Engines.MLQuests; using Server.Mobiles; using Server.Gumps; using System.Collections.Generic; using Server.Misc; using Server.Items; namespace Server.Engines.MLQuests.Objectives { public class EscortObjective : BaseObjective { private QuestArea m_Destination; public QuestArea Destination { get { return m_Destination; } set { m_Destination = value; } } public EscortObjective() : this( null ) { } public EscortObjective( QuestArea destination ) { m_Destination = destination; } public override bool CanOffer( IQuestGiver quester, PlayerMobile pm, bool message ) { if ( ( quester is BaseCreature && ( (BaseCreature)quester ).Controlled ) || ( quester is BaseEscortable && ( (BaseEscortable)quester ).IsBeingDeleted ) ) return false; MLQuestContext context = MLQuestSystem.GetContext( pm ); if ( context != null ) { foreach ( MLQuestInstance instance in context.QuestInstances ) { if ( instance.Quest.IsEscort ) { if ( message ) MLQuestSystem.Tell( quester, pm, 500896 ); // I see you already have an escort. return false; } } } DateTime nextEscort = pm.LastEscortTime + BaseEscortable.EscortDelay; if ( nextEscort > DateTime.Now ) { if ( message ) { int minutes = (int)Math.Ceiling( ( nextEscort - DateTime.Now ).TotalMinutes ); if ( minutes == 1 ) MLQuestSystem.Tell( quester, pm, "You must rest 1 minute before we set out on this journey." ); else MLQuestSystem.Tell( quester, pm, 1071195, minutes.ToString() ); // You must rest ~1_minsleft~ minutes before we set out on this journey. } return false; } return true; } public override void WriteToGump( Gump g, ref int y ) { g.AddHtmlLocalized( 98, y, 312, 16, 1072206, 0x15F90, false, false ); // Escort to if ( m_Destination.Name.Number > 0 ) g.AddHtmlLocalized( 173, y, 312, 20, m_Destination.Name.Number, 0xFFFFFF, false, false ); else if ( m_Destination.Name.String != null ) g.AddLabel( 173, y, 0x481, m_Destination.Name.String ); y += 16; } public override BaseObjectiveInstance CreateInstance( MLQuestInstance instance ) { if ( instance == null || m_Destination == null ) return null; return new EscortObjectiveInstance( this, instance ); } } public class EscortObjectiveInstance : BaseObjectiveInstance { private EscortObjective m_Objective; private bool m_HasCompleted; private Timer m_Timer; private DateTime m_LastSeenEscorter; private BaseCreature m_Escort; public bool HasCompleted { get { return m_HasCompleted; } set { m_HasCompleted = value; } } public EscortObjectiveInstance( EscortObjective objective, MLQuestInstance instance ) : base( instance, objective ) { m_Objective = objective; m_HasCompleted = false; m_Timer = Timer.DelayCall( TimeSpan.FromSeconds( 5 ), TimeSpan.FromSeconds( 5 ), new TimerCallback( CheckDestination ) ); m_LastSeenEscorter = DateTime.Now; m_Escort = instance.Quester as BaseCreature; if ( MLQuestSystem.Debug && m_Escort == null && instance.Quester != null ) Console.WriteLine( "Warning: EscortObjective is not supported for type '{0}'", instance.Quester.GetType().Name ); } public override bool IsCompleted() { return m_HasCompleted; } private void CheckDestination() { if ( m_Escort == null || m_HasCompleted ) // Completed by deserialization { StopTimer(); return; } MLQuestInstance instance = Instance; PlayerMobile pm = instance.Player; if ( instance.Removed ) { Abandon(); } else if ( m_Objective.Destination.Contains( m_Escort ) ) { m_Escort.Say( 1042809, pm.Name ); // We have arrived! I thank thee, ~1_PLAYER_NAME~! I have no further need of thy services. Here is thy pay. if ( pm.Young || m_Escort.Region.IsPartOf( "Haven Island" ) ) Titles.AwardFame( pm, 10, true ); else VirtueHelper.AwardVirtue( pm, VirtueName.Compassion, ( m_Escort is BaseEscortable && ( (BaseEscortable)m_Escort ).IsPrisoner ) ? 400 : 200 ); EndFollow( m_Escort ); StopTimer(); m_HasCompleted = true; CheckComplete(); // Auto claim reward MLQuestSystem.OnDoubleClick( m_Escort, pm ); } else if ( pm.Map != m_Escort.Map || !pm.InRange( m_Escort, 30 ) ) // TODO: verify range { if ( m_LastSeenEscorter + BaseEscortable.AbandonDelay <= DateTime.Now ) Abandon(); } else { m_LastSeenEscorter = DateTime.Now; } } private void StopTimer() { if ( m_Timer != null ) { m_Timer.Stop(); m_Timer = null; } } public static void BeginFollow( BaseCreature quester, PlayerMobile pm ) { quester.ControlSlots = 0; quester.SetControlMaster( pm ); quester.ActiveSpeed = 0.1; quester.PassiveSpeed = 0.2; quester.ControlOrder = OrderType.Follow; quester.ControlTarget = pm; quester.CantWalk = false; quester.CurrentSpeed = 0.1; } public static void EndFollow( BaseCreature quester ) { quester.ActiveSpeed = 0.2; quester.PassiveSpeed = 1.0; quester.ControlOrder = OrderType.None; quester.ControlTarget = null; quester.CurrentSpeed = 1.0; quester.SetControlMaster( null ); if ( quester is BaseEscortable ) ( (BaseEscortable)quester ).BeginDelete(); } public override void OnQuestAccepted() { MLQuestInstance instance = Instance; PlayerMobile pm = instance.Player; pm.LastEscortTime = DateTime.Now; if ( m_Escort != null ) BeginFollow( m_Escort, pm ); } public void Abandon() { StopTimer(); MLQuestInstance instance = Instance; PlayerMobile pm = instance.Player; if ( m_Escort != null && !m_Escort.Deleted ) { if ( !pm.Alive ) m_Escort.Say( 500901 ); // Ack! My escort has come to haunt me! else m_Escort.Say( 500902 ); // My escort seems to have abandoned me! EndFollow( m_Escort ); } // Note: this sound is sent twice on OSI (once here and once in Cancel()) //m_Player.SendSound( 0x5B3 ); // private sound pm.SendLocalizedMessage( 1071194 ); // You have failed your escort quest... if ( !instance.Removed ) instance.Cancel(); } public override void OnQuesterDeleted() { if ( IsCompleted() || Instance.Removed ) return; Abandon(); } public override void OnPlayerDeath() { // Note: OSI also cancels it when the quest is already complete if ( /*IsCompleted() ||*/ Instance.Removed ) return; Instance.Cancel(); } public override void OnExpire() { Abandon(); } public override void WriteToGump( Gump g, ref int y ) { m_Objective.WriteToGump( g, ref y ); base.WriteToGump( g, ref y ); // No extra instance stuff printed for this objective } public override DataType ExtraDataType { get { return DataType.EscortObjective; } } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( m_HasCompleted ); } } }
// Copyright 2008-2011. This work is licensed under the BSD license, available at // http://www.movesinstitute.org/licenses // // Orignal authors: DMcG, Jason Nelson // Modified for use with C#: // - Peter Smith (Naval Air Warfare Center - Training Systems Division) // - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si) using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Reflection; namespace OpenDis.Enumerations.DistributedEmission { /// <summary> /// Enumeration values for EmissionFunction (der.emission.function, Function, /// section 8.1.2) /// The enumeration values are generated from the SISO DIS XML EBV document (R35), which was /// obtained from http://discussions.sisostds.org/default.asp?action=10&amp;fd=31 /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Serializable] public enum EmissionFunction : byte { /// <summary> /// Other. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Other.")] Other = 0, /// <summary> /// Multi-function. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Multi-function.")] MultiFunction = 1, /// <summary> /// Early Warning/Surveillance. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Early Warning/Surveillance.")] EarlyWarningSurveillance = 2, /// <summary> /// Height Finding. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Height Finding.")] HeightFinding = 3, /// <summary> /// Fire Control. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Fire Control.")] FireControl = 4, /// <summary> /// Acquisition/Detection. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Acquisition/Detection.")] AcquisitionDetection = 5, /// <summary> /// Tracking. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Tracking.")] Tracking = 6, /// <summary> /// Guidance/Illumination. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Guidance/Illumination.")] GuidanceIllumination = 7, /// <summary> /// Firing point/launch point location. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Firing point/launch point location.")] FiringPointLaunchPointLocation = 8, /// <summary> /// Ranging. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Ranging.")] Ranging = 9, /// <summary> /// Radar Altimeter. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Radar Altimeter.")] RadarAltimeter = 10, /// <summary> /// Imaging. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Imaging.")] Imaging = 11, /// <summary> /// Motion Detection. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Motion Detection.")] MotionDetection = 12, /// <summary> /// Navigation. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Navigation.")] Navigation = 13, /// <summary> /// Weather / Meterological. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Weather / Meterological.")] WeatherMeterological = 14, /// <summary> /// Instrumentation. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Instrumentation.")] Instrumentation = 15, /// <summary> /// Identification/Classification (including IFF). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Identification/Classification (including IFF).")] IdentificationClassificationIncludingIFF = 16, /// <summary> /// AAA (Anti-Aircraft Artillery) Fire Control. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("AAA (Anti-Aircraft Artillery) Fire Control.")] AAAAntiAircraftArtilleryFireControl = 17, /// <summary> /// Air Search/Bomb. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Air Search/Bomb.")] AirSearchBomb = 18, /// <summary> /// Air Intercept. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Air Intercept.")] AirIntercept = 19, /// <summary> /// Altimeter. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Altimeter.")] Altimeter = 20, /// <summary> /// Air Mapping. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Air Mapping.")] AirMapping = 21, /// <summary> /// Air Traffic Control. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Air Traffic Control.")] AirTrafficControl = 22, /// <summary> /// Beacon. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Beacon.")] Beacon = 23, /// <summary> /// Battlefield Surveillance. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Battlefield Surveillance.")] BattlefieldSurveillance = 24, /// <summary> /// Ground Control Approach. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Ground Control Approach.")] GroundControlApproach = 25, /// <summary> /// Ground Control Intercept. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Ground Control Intercept.")] GroundControlIntercept = 26, /// <summary> /// Coastal Surveillance. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Coastal Surveillance.")] CoastalSurveillance = 27, /// <summary> /// Decoy/Mimic. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Decoy/Mimic.")] DecoyMimic = 28, /// <summary> /// Data Transmission. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Data Transmission.")] DataTransmission = 29, /// <summary> /// Earth Surveillance. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Earth Surveillance.")] EarthSurveillance = 30, /// <summary> /// Gun Lay Beacon. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Gun Lay Beacon.")] GunLayBeacon = 31, /// <summary> /// Ground Mapping. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Ground Mapping.")] GroundMapping = 32, /// <summary> /// Harbor Surveillance. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Harbor Surveillance.")] HarborSurveillance = 33, /// <summary> /// ILS (Instrument Landing System). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("ILS (Instrument Landing System).")] ILSInstrumentLandingSystem = 35, /// <summary> /// Ionospheric Sound. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Ionospheric Sound.")] IonosphericSound = 36, /// <summary> /// Interrogator. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Interrogator.")] Interrogator = 37, /// <summary> /// Barrage Jamming. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Barrage Jamming.")] BarrageJamming = 38, /// <summary> /// Click Jamming. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Click Jamming.")] ClickJamming = 39, /// <summary> /// Frequency Swept Jamming. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Frequency Swept Jamming.")] FrequencySweptJamming = 41, /// <summary> /// Jamming. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Jamming.")] Jamming = 42, /// <summary> /// Pulsed Jamming. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Pulsed Jamming.")] PulsedJamming = 44, /// <summary> /// Repeater Jamming. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Repeater Jamming.")] RepeaterJamming = 45, /// <summary> /// Spot Noise Jamming. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Spot Noise Jamming.")] SpotNoiseJamming = 46, /// <summary> /// Missile Acquisition. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Missile Acquisition.")] MissileAcquisition = 47, /// <summary> /// Missile Downlink. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Missile Downlink.")] MissileDownlink = 48, /// <summary> /// Space. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Space.")] Space = 50, /// <summary> /// Surface Search. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Surface Search.")] SurfaceSearch = 51, /// <summary> /// Shell Tracking. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Shell Tracking.")] ShellTracking = 52, /// <summary> /// Television. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Television.")] Television = 56, /// <summary> /// Unknown. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Unknown.")] Unknown = 57, /// <summary> /// Video Remoting. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Video Remoting.")] VideoRemoting = 58, /// <summary> /// Experimental or Training. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Experimental or Training.")] ExperimentalOrTraining = 59, /// <summary> /// Missile Guidance. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Missile Guidance.")] MissileGuidance = 60, /// <summary> /// Missile Homing. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Missile Homing.")] MissileHoming = 61, /// <summary> /// Missile Tracking. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Missile Tracking.")] MissileTracking = 62, /// <summary> /// Jamming, noise. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Jamming, noise.")] JammingNoise = 64, /// <summary> /// Jamming, deception. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Jamming, deception.")] JammingDeception = 65, /// <summary> /// Navigation/Distance Measuring Equipment. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Navigation/Distance Measuring Equipment.")] NavigationDistanceMeasuringEquipment = 71, /// <summary> /// Terrain Following. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Terrain Following.")] TerrainFollowing = 72, /// <summary> /// Weather Avoidance. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Weather Avoidance.")] WeatherAvoidance = 73, /// <summary> /// Proximity Fuse. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Proximity Fuse.")] ProximityFuse = 74, /// <summary> /// Radiosonde. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Radiosonde.")] Radiosonde = 76, /// <summary> /// Sonobuoy. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Sonobuoy.")] Sonobuoy = 77, /// <summary> /// Bathythermal Sensor. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Bathythermal Sensor.")] BathythermalSensor = 78, /// <summary> /// Towed Counter Measure. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Towed Counter Measure.")] TowedCounterMeasure = 79, /// <summary> /// Weapon, non-lethal. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Weapon, non-lethal.")] WeaponNonLethal = 96, /// <summary> /// Weapon, lethal. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Weapon, lethal.")] WeaponLethal = 97 } }
// 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.IO; using System.Net.Http; using System.Net.Test.Common; using System.Text; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Tests { public class FileWebRequestTest { private readonly ITestOutputHelper _output; public FileWebRequestTest(ITestOutputHelper output) { _output = output; } [Fact] public void Ctor_VerifyDefaults_Success() { Uri uri = new Uri("file://somefilepath"); FileWebRequest request = (FileWebRequest)WebRequest.Create(uri); Assert.Null(request.ContentType); Assert.Null(request.Credentials); Assert.NotNull(request.Headers); Assert.Equal(0, request.Headers.Count); Assert.Equal("GET", request.Method); Assert.Null(request.Proxy); Assert.Equal(uri, request.RequestUri); } [Fact] public void FileWebRequest_Properties_Roundtrips() { WebRequest request = WebRequest.Create("file://anything"); request.ContentLength = 42; Assert.Equal(42, request.ContentLength); request.ContentType = "anything"; Assert.Equal("anything", request.ContentType); request.Timeout = 42000; Assert.Equal(42000, request.Timeout); } [Fact] public void InvalidArguments_Throws() { WebRequest request = WebRequest.Create("file://anything"); AssertExtensions.Throws<ArgumentException>("value", () => request.ContentLength = -1); AssertExtensions.Throws<ArgumentException>("value", () => request.Method = null); AssertExtensions.Throws<ArgumentException>("value", () => request.Method = ""); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => request.Timeout = -2); } [Fact] public void GetRequestStream_MethodGet_ThrowsProtocolViolation() { WebRequest request = WebRequest.Create("file://anything"); Assert.Throws<ProtocolViolationException>(() => request.BeginGetRequestStream(null, null)); } [Fact] public void GetRequestResponseAfterAbort_Throws() { WebRequest request = WebRequest.Create("file://anything"); request.Abort(); Assert.Throws<WebException>(() => request.BeginGetRequestStream(null, null)); Assert.Throws<WebException>(() => request.BeginGetResponse(null, null)); } [Fact] public void UseDefaultCredentials_GetOrSet_Throws() { WebRequest request = WebRequest.Create("file://anything"); Assert.Throws<NotSupportedException>(() => request.UseDefaultCredentials); Assert.Throws<NotSupportedException>(() => request.UseDefaultCredentials = true); } } public abstract class FileWebRequestTestBase { public abstract Task<WebResponse> GetResponseAsync(WebRequest request); public abstract Task<Stream> GetRequestStreamAsync(WebRequest request); [Fact] public async Task ReadFile_ContainsExpectedContent() { string path = Path.GetTempFileName(); try { var data = new byte[1024 * 10]; var random = new Random(42); random.NextBytes(data); File.WriteAllBytes(path, data); WebRequest request = WebRequest.Create("file://" + path); using (WebResponse response = await GetResponseAsync(request)) { Assert.Equal(data.Length, response.ContentLength); Assert.Equal("application/octet-stream", response.ContentType); Assert.True(response.SupportsHeaders); Assert.NotNull(response.Headers); Assert.Equal(new Uri("file://" + path), response.ResponseUri); using (Stream s = response.GetResponseStream()) { var target = new MemoryStream(); await s.CopyToAsync(target); Assert.Equal(data, target.ToArray()); } } } finally { File.Delete(path); } } [Fact] public async Task WriteFile_ContainsExpectedContent() { string path = Path.GetTempFileName(); try { var data = new byte[1024 * 10]; var random = new Random(42); random.NextBytes(data); var request = WebRequest.Create("file://" + path); request.Method = WebRequestMethods.File.UploadFile; using (Stream s = await GetRequestStreamAsync(request)) { await s.WriteAsync(data, 0, data.Length); } Assert.Equal(data, File.ReadAllBytes(path)); } finally { File.Delete(path); } } [Fact] public async Task WriteThenReadFile_WriteAccessResultsInNullResponseStream() { string path = Path.GetTempFileName(); try { var data = new byte[1024 * 10]; var random = new Random(42); random.NextBytes(data); var request = WebRequest.Create("file://" + path); request.Method = WebRequestMethods.File.UploadFile; using (Stream s = await GetRequestStreamAsync(request)) { await s.WriteAsync(data, 0, data.Length); } using (WebResponse response = await GetResponseAsync(request)) using (Stream s = response.GetResponseStream()) // will hand back a null stream { Assert.Equal(0, s.Length); } } finally { File.Delete(path); } } protected virtual bool EnableConcurrentReadWriteTests => true; [Fact] public async Task RequestAfterResponse_throws() { string path = Path.GetTempFileName(); try { var data = new byte[1024]; WebRequest request = WebRequest.Create("file://" + path); request.Method = WebRequestMethods.File.UploadFile; using (WebResponse response = await GetResponseAsync(request)) { await Assert.ThrowsAsync<InvalidOperationException>(() => GetRequestStreamAsync(request)); } } finally { File.Delete(path); } } [Theory] [InlineData(null)] [InlineData(false)] [InlineData(true)] public async Task BeginGetResponse_OnNonexistentFile_ShouldNotCrashApplication(bool? abortWithDelay) { FileWebRequest request = (FileWebRequest)WebRequest.Create("file://" + Path.GetRandomFileName()); Task<WebResponse> responseTask = GetResponseAsync(request); if (abortWithDelay.HasValue) { if (abortWithDelay.Value) { await Task.Delay(1); } request.Abort(); } await Assert.ThrowsAsync<WebException>(() => responseTask); } } public abstract class AsyncFileWebRequestTestBase : FileWebRequestTestBase { [Fact] public async Task ConcurrentReadWrite_ResponseBlocksThenGetsNullStream() { string path = Path.GetTempFileName(); try { var data = new byte[1024 * 10]; var random = new Random(42); random.NextBytes(data); var request = WebRequest.Create("file://" + path); request.Method = WebRequestMethods.File.UploadFile; Task<Stream> requestStreamTask = GetRequestStreamAsync(request); Task<WebResponse> responseTask = GetResponseAsync(request); using (Stream s = await requestStreamTask) { await s.WriteAsync(data, 0, data.Length); } using (WebResponse response = await responseTask) using (Stream s = response.GetResponseStream()) // will hand back a null stream { Assert.Equal(0, s.Length); } } finally { File.Delete(path); } } } public sealed class SyncFileWebRequestTestBase : FileWebRequestTestBase { public override Task<WebResponse> GetResponseAsync(WebRequest request) => Task.Run(() => request.GetResponse()); public override Task<Stream> GetRequestStreamAsync(WebRequest request) => Task.Run(() => request.GetRequestStream()); } public sealed class BeginEndFileWebRequestTestBase : AsyncFileWebRequestTestBase { public override Task<WebResponse> GetResponseAsync(WebRequest request) => Task.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null); public override Task<Stream> GetRequestStreamAsync(WebRequest request) => Task.Factory.FromAsync(request.BeginGetRequestStream, request.EndGetRequestStream, null); } public sealed class TaskFileWebRequestTestBase : AsyncFileWebRequestTestBase { public override Task<WebResponse> GetResponseAsync(WebRequest request) => request.GetResponseAsync(); public override Task<Stream> GetRequestStreamAsync(WebRequest request) => request.GetRequestStreamAsync(); } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using OpenMetaverse; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using System.Collections; using System.Collections.Generic; // using OpenSim.Region.Framework.Interfaces; namespace OpenSim.Framework.Capabilities { /// <summary> /// XXX Probably not a particularly nice way of allow us to get the scene presence from the scene (chiefly so that /// we can popup a message on the user's client if the inventory service has permanently failed). But I didn't want /// to just pass the whole Scene into CAPS. /// </summary> public delegate IClientAPI GetClientDelegate(UUID agentID); public class Caps { private UUID m_agentID; private CapsHandlers m_capsHandlers; /// <summary> /// This is the uuid portion of every CAPS path. It is used to make capability urls private to the requester. /// </summary> private string m_capsObjectPath; private Dictionary<string, string> m_externalCapsHandlers = new Dictionary<string, string>(); private IHttpServer m_httpListener; private string m_httpListenerHostName; private uint m_httpListenPort; private Dictionary<string, PollServiceEventArgs> m_pollServiceHandlers = new Dictionary<string, PollServiceEventArgs>(); private string m_regionName; public Caps(IHttpServer httpServer, string httpListen, uint httpPort, string capsPath, UUID agent, string regionName) { m_capsObjectPath = capsPath; m_httpListener = httpServer; m_httpListenerHostName = httpListen; m_httpListenPort = httpPort; if (httpServer != null && httpServer.UseSSL) { m_httpListenPort = httpServer.SSLPort; httpListen = httpServer.SSLCommonName; httpPort = httpServer.SSLPort; } m_agentID = agent; m_capsHandlers = new CapsHandlers(httpServer, httpListen, httpPort, (httpServer == null) ? false : httpServer.UseSSL); m_regionName = regionName; } public UUID AgentID { get { return m_agentID; } } public CapsHandlers CapsHandlers { get { return m_capsHandlers; } } public string CapsObjectPath { get { return m_capsObjectPath; } } public Dictionary<string, string> ExternalCapsHandlers { get { return m_externalCapsHandlers; } } public string HostName { get { return m_httpListenerHostName; } } public IHttpServer HttpListener { get { return m_httpListener; } } public uint Port { get { return m_httpListenPort; } } public string RegionName { get { return m_regionName; } } public bool SSLCaps { get { return m_httpListener.UseSSL; } } public string SSLCommonName { get { return m_httpListener.SSLCommonName; } } /// <summary> /// Remove all CAPS service handlers. /// </summary> public void DeregisterHandlers() { foreach (string capsName in m_capsHandlers.Caps) { m_capsHandlers.Remove(capsName); } foreach (PollServiceEventArgs handler in m_pollServiceHandlers.Values) { m_httpListener.RemovePollServiceHTTPHandler("", handler.Url); } } /// <summary> /// Return an LLSD-serializable Hashtable describing the /// capabilities and their handler details. /// </summary> /// <param name="excludeSeed">If true, then exclude the seed cap.</param> public Hashtable GetCapsDetails(bool excludeSeed, List<string> requestedCaps) { Hashtable caps = CapsHandlers.GetCapsDetails(excludeSeed, requestedCaps); lock (m_pollServiceHandlers) { foreach (KeyValuePair<string, PollServiceEventArgs> kvp in m_pollServiceHandlers) { if (!requestedCaps.Contains(kvp.Key)) continue; string hostName = m_httpListenerHostName; uint port = (MainServer.Instance == null) ? 0 : MainServer.Instance.Port; string protocol = "http"; if (MainServer.Instance.UseSSL) { hostName = MainServer.Instance.SSLCommonName; port = MainServer.Instance.SSLPort; protocol = "https"; } // // caps.RegisterHandler("FetchInventoryDescendents2", String.Format("{0}://{1}:{2}{3}", protocol, hostName, port, capUrl)); caps[kvp.Key] = string.Format("{0}://{1}:{2}{3}", protocol, hostName, port, kvp.Value.Url); } } // Add the external too foreach (KeyValuePair<string, string> kvp in ExternalCapsHandlers) { if (!requestedCaps.Contains(kvp.Key)) continue; caps[kvp.Key] = kvp.Value; } return caps; } public Dictionary<string, PollServiceEventArgs> GetPollHandlers() { return new Dictionary<string, PollServiceEventArgs>(m_pollServiceHandlers); } /// <summary> /// Register a handler. This allows modules to register handlers. /// </summary> /// <param name="capName"></param> /// <param name="handler"></param> public void RegisterHandler(string capName, IRequestHandler handler) { //m_log.DebugFormat("[CAPS]: Registering handler for \"{0}\": path {1}", capName, handler.Path); m_capsHandlers[capName] = handler; } /// <summary> /// Register an external handler. The service for this capability is somewhere else /// given by the URL. /// </summary> /// <param name="capsName"></param> /// <param name="url"></param> public void RegisterHandler(string capsName, string url) { m_externalCapsHandlers.Add(capsName, url); } public void RegisterPollHandler(string capName, PollServiceEventArgs pollServiceHandler) { // m_log.DebugFormat( // "[CAPS]: Registering handler with name {0}, url {1} for {2}", // capName, pollServiceHandler.Url, m_agentID, m_regionName); m_pollServiceHandlers.Add(capName, pollServiceHandler); m_httpListener.AddPollServiceHTTPHandler(pollServiceHandler.Url, pollServiceHandler); // uint port = (MainServer.Instance == null) ? 0 : MainServer.Instance.Port; // string protocol = "http"; // string hostName = m_httpListenerHostName; // // if (MainServer.Instance.UseSSL) // { // hostName = MainServer.Instance.SSLCommonName; // port = MainServer.Instance.SSLPort; // protocol = "https"; // } // RegisterHandler( // capName, String.Format("{0}://{1}:{2}{3}", protocol, hostName, port, pollServiceHandler.Url)); } public bool TryGetPollHandler(string name, out PollServiceEventArgs pollHandler) { return m_pollServiceHandlers.TryGetValue(name, out pollHandler); } } }
using System; using System.Collections; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Runtime.InteropServices; namespace Kooboo.Drawing { /// <summary> /// /// </summary> internal abstract class Quantizer { #region .ctor /// <summary> /// Construct the quantizer /// </summary> /// <param name="singlePass">If true, the quantization only needs to loop through the source pixels once</param> /// <remarks> /// If you construct this class with a true value for singlePass, then the code will, when quantizing your image, /// only call the 'QuantizeImage' function. If two passes are required, the code will call 'InitialQuantizeImage' /// and then 'QuantizeImage'. /// </remarks> public Quantizer(bool singlePass) { _singlePass = singlePass; _pixelSize = Marshal.SizeOf(typeof(Color32)); } #endregion #region Methods /// <summary> /// Quantize an image and return the resulting output bitmap /// </summary> /// <param name="source">The image to quantize</param> /// <returns>A quantized version of the image</returns> public Bitmap Quantize(Image source) { // Get the size of the source image int height = source.Height; int width = source.Width; // And construct a rectangle from these dimensions Rectangle bounds = new Rectangle(0, 0, width, height); // First off take a 32bpp copy of the image Bitmap copy = new Bitmap(width, height, PixelFormat.Format32bppArgb); // And construct an 8bpp version Bitmap output = new Bitmap(width, height, PixelFormat.Format8bppIndexed); // Now lock the bitmap into memory using (Graphics g = Graphics.FromImage(copy)) { g.PageUnit = GraphicsUnit.Pixel; // Draw the source image onto the copy bitmap, // which will effect a widening as appropriate. g.DrawImage(source, bounds); } // Define a pointer to the bitmap data BitmapData sourceData = null; try { // Get the source image bits and lock into memory sourceData = copy.LockBits(bounds, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); // Call the FirstPass function if not a single pass algorithm. // For something like an octree quantizer, this will run through // all image pixels, build a data structure, and create a palette. if (!_singlePass) FirstPass(sourceData, width, height); // Then set the color palette on the output bitmap. I'm passing in the current palette // as there's no way to construct a new, empty palette. output.Palette = this.GetPalette(output.Palette); // Then call the second pass which actually does the conversion SecondPass(sourceData, output, width, height, bounds); } finally { // Ensure that the bits are unlocked copy.UnlockBits(sourceData); } // Last but not least, return the output bitmap return output; } /// <summary> /// Execute the first pass through the pixels in the image /// </summary> /// <param name="sourceData">The source data</param> /// <param name="width">The width in pixels of the image</param> /// <param name="height">The height in pixels of the image</param> protected virtual void FirstPass(BitmapData sourceData, int width, int height) { // Define the source data pointers. The source row is a byte to // keep addition of the stride value easier (as this is in bytes) IntPtr pSourceRow = sourceData.Scan0; // Loop through each row for (int row = 0; row < height; row++) { // Set the source pixel to the first pixel in this row IntPtr pSourcePixel = pSourceRow; // And loop through each column for (int col = 0; col < width; col++) { // Now I have the pixel, call the FirstPassQuantize function... InitialQuantizePixel(new Color32(pSourcePixel)); pSourcePixel = (IntPtr)(pSourcePixel.ToInt64() + _pixelSize); } // Add the stride to the source row pSourceRow = (IntPtr)(pSourceRow.ToInt64() + sourceData.Stride); } } /// <summary> /// Execute a second pass through the bitmap /// </summary> /// <param name="sourceData">The source bitmap, locked into memory</param> /// <param name="output">The output bitmap</param> /// <param name="width">The width in pixels of the image</param> /// <param name="height">The height in pixels of the image</param> /// <param name="bounds">The bounding rectangle</param> protected virtual void SecondPass(BitmapData sourceData, Bitmap output, int width, int height, Rectangle bounds) { BitmapData outputData = null; try { // Lock the output bitmap into memory outputData = output.LockBits(bounds, ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed); // Define the source data pointers. The source row is a byte to // keep addition of the stride value easier (as this is in bytes) IntPtr pSourceRow = sourceData.Scan0; IntPtr pSourcePixel = pSourceRow; IntPtr pPreviousPixel = pSourcePixel; // Now define the destination data pointers IntPtr pDestinationRow = outputData.Scan0; IntPtr pDestinationPixel = pDestinationRow; // And convert the first pixel, so that I have values going into the loop byte pixelValue = QuantizePixel(new Color32(pSourcePixel)); // Assign the value of the first pixel Marshal.WriteByte(pDestinationPixel, pixelValue); // Loop through each row for (int row = 0; row < height; row++) { // Set the source pixel to the first pixel in this row pSourcePixel = pSourceRow; // And set the destination pixel pointer to the first pixel in the row pDestinationPixel = pDestinationRow; // Loop through each pixel on this scan line for (int col = 0; col < width; col++) { // Check if this is the same as the last pixel. If so use that value // rather than calculating it again. This is an inexpensive optimisation. if (Marshal.ReadInt32(pPreviousPixel) != Marshal.ReadInt32(pSourcePixel)) { // Quantize the pixel pixelValue = QuantizePixel(new Color32(pSourcePixel)); // And setup the previous pointer pPreviousPixel = pSourcePixel; } // And set the pixel in the output Marshal.WriteByte(pDestinationPixel, pixelValue); pSourcePixel = (IntPtr)(pSourcePixel.ToInt64() + _pixelSize); pDestinationPixel = (IntPtr)(pDestinationPixel.ToInt64() + 1); } // Add the stride to the source row pSourceRow = (IntPtr)(pSourceRow.ToInt64() + sourceData.Stride); // And to the destination row pDestinationRow = (IntPtr)(pDestinationRow.ToInt64() + outputData.Stride); } } finally { // Ensure that I unlock the output bits output.UnlockBits(outputData); } } /// <summary> /// Override this to process the pixel in the first pass of the algorithm /// </summary> /// <param name="pixel">The pixel to quantize</param> /// <remarks> /// This function need only be overridden if your quantize algorithm needs two passes, /// such as an Octree quantizer. /// </remarks> protected virtual void InitialQuantizePixel(Color32 pixel) { } /// <summary> /// Override this to process the pixel in the second pass of the algorithm /// </summary> /// <param name="pixel">The pixel to quantize</param> /// <returns>The quantized value</returns> protected abstract byte QuantizePixel(Color32 pixel); /// <summary> /// Retrieve the palette for the quantized image /// </summary> /// <param name="original">Any old palette, this is overrwritten</param> /// <returns>The new color palette</returns> protected abstract ColorPalette GetPalette(ColorPalette original); #endregion #region Properties /// <summary> /// Flag used to indicate whether a single pass or two passes are needed for quantization. /// </summary> private bool _singlePass; private int _pixelSize; /// <summary> /// Struct that defines a 32 bpp colour /// </summary> /// <remarks> /// This struct is used to read data from a 32 bits per pixel image /// in memory, and is ordered in this manner as this is the way that /// the data is layed out in memory /// </remarks> [StructLayout(LayoutKind.Explicit)] public struct Color32 { public Color32(IntPtr pSourcePixel) { this = (Color32)Marshal.PtrToStructure(pSourcePixel, typeof(Color32)); } /// <summary> /// Holds the blue component of the colour /// </summary> [FieldOffset(0)] public byte Blue; /// <summary> /// Holds the green component of the colour /// </summary> [FieldOffset(1)] public byte Green; /// <summary> /// Holds the red component of the colour /// </summary> [FieldOffset(2)] public byte Red; /// <summary> /// Holds the alpha component of the colour /// </summary> [FieldOffset(3)] public byte Alpha; /// <summary> /// Permits the color32 to be treated as an int32 /// </summary> [FieldOffset(0)] public int ARGB; /// <summary> /// Return the color for this Color32 object /// </summary> public Color Color { get { return Color.FromArgb(Alpha, Red, Green, Blue); } } } #endregion } /// <summary> /// Quantize using an Octree /// </summary> internal class OctreeQuantizer : Quantizer { #region .ctor /// <summary> /// Construct the octree quantizer /// </summary> /// <remarks> /// The Octree quantizer is a two pass algorithm. The initial pass sets up the octree, /// the second pass quantizes a color based on the nodes in the tree /// </remarks> /// <param name="maxColors">The maximum number of colors to return</param> /// <param name="maxColorBits">The number of significant bits</param> public OctreeQuantizer(int maxColors, int maxColorBits) : base(false) { if (maxColors > 255) throw new ArgumentOutOfRangeException("maxColors", maxColors, "The number of colors should be less than 256"); if ((maxColorBits < 1) | (maxColorBits > 8)) throw new ArgumentOutOfRangeException("maxColorBits", maxColorBits, "This should be between 1 and 8"); // Construct the octree _octree = new Octree(maxColorBits); _maxColors = maxColors; } #endregion #region Methods /// <summary> /// Process the pixel in the first pass of the algorithm /// </summary> /// <param name="pixel">The pixel to quantize</param> /// <remarks> /// This function need only be overridden if your quantize algorithm needs two passes, /// such as an Octree quantizer. /// </remarks> protected override void InitialQuantizePixel(Color32 pixel) { // Add the color to the octree _octree.AddColor(pixel); } /// <summary> /// Override this to process the pixel in the second pass of the algorithm /// </summary> /// <param name="pixel">The pixel to quantize</param> /// <returns>The quantized value</returns> protected override byte QuantizePixel(Color32 pixel) { byte paletteIndex = (byte)_maxColors; // The color at [_maxColors] is set to transparent // Get the palette index if this non-transparent if (pixel.Alpha > 0) paletteIndex = (byte)_octree.GetPaletteIndex(pixel); return paletteIndex; } /// <summary> /// Retrieve the palette for the quantized image /// </summary> /// <param name="original">Any old palette, this is overrwritten</param> /// <returns>The new color palette</returns> protected override ColorPalette GetPalette(ColorPalette original) { // First off convert the octree to _maxColors colors ArrayList palette = _octree.Palletize(_maxColors - 1); // Then convert the palette based on those colors for (int index = 0; index < palette.Count; index++) original.Entries[index] = (Color)palette[index]; // Add the transparent color original.Entries[_maxColors] = Color.FromArgb(0, 0, 0, 0); return original; } #endregion #region Fields /// <summary> /// Stores the tree /// </summary> private Octree _octree; /// <summary> /// Maximum allowed color depth /// </summary> private int _maxColors; /// <summary> /// Class which does the actual quantization /// </summary> private class Octree { /// <summary> /// Construct the octree /// </summary> /// <param name="maxColorBits">The maximum number of significant bits in the image</param> public Octree(int maxColorBits) { _maxColorBits = maxColorBits; _leafCount = 0; _reducibleNodes = new OctreeNode[9]; _root = new OctreeNode(0, _maxColorBits, this); _previousColor = 0; _previousNode = null; } /// <summary> /// Add a given color value to the octree /// </summary> /// <param name="pixel"></param> public void AddColor(Color32 pixel) { // Check if this request is for the same color as the last if (_previousColor == pixel.ARGB) { // If so, check if I have a previous node setup. This will only ocurr if the first color in the image // happens to be black, with an alpha component of zero. if (null == _previousNode) { _previousColor = pixel.ARGB; _root.AddColor(pixel, _maxColorBits, 0, this); } else // Just update the previous node _previousNode.Increment(pixel); } else { _previousColor = pixel.ARGB; _root.AddColor(pixel, _maxColorBits, 0, this); } } /// <summary> /// Reduce the depth of the tree /// </summary> public void Reduce() { int index; // Find the deepest level containing at least one reducible node for (index = _maxColorBits - 1; (index > 0) && (null == _reducibleNodes[index]); index--) ; // Reduce the node most recently added to the list at level 'index' OctreeNode node = _reducibleNodes[index]; _reducibleNodes[index] = node.NextReducible; // Decrement the leaf count after reducing the node _leafCount -= node.Reduce(); // And just in case I've reduced the last color to be added, and the next color to // be added is the same, invalidate the previousNode... _previousNode = null; } /// <summary> /// Get/Set the number of leaves in the tree /// </summary> public int Leaves { get { return _leafCount; } set { _leafCount = value; } } /// <summary> /// Return the array of reducible nodes /// </summary> protected OctreeNode[] ReducibleNodes { get { return _reducibleNodes; } } /// <summary> /// Keep track of the previous node that was quantized /// </summary> /// <param name="node">The node last quantized</param> protected void TrackPrevious(OctreeNode node) { _previousNode = node; } /// <summary> /// Convert the nodes in the octree to a palette with a maximum of colorCount colors /// </summary> /// <param name="colorCount">The maximum number of colors</param> /// <returns>An arraylist with the palettized colors</returns> public ArrayList Palletize(int colorCount) { while (Leaves > colorCount) Reduce(); // Now palettize the nodes ArrayList palette = new ArrayList(Leaves); int paletteIndex = 0; _root.ConstructPalette(palette, ref paletteIndex); // And return the palette return palette; } /// <summary> /// Get the palette index for the passed color /// </summary> /// <param name="pixel"></param> /// <returns></returns> public int GetPaletteIndex(Color32 pixel) { return _root.GetPaletteIndex(pixel, 0); } /// <summary> /// Mask used when getting the appropriate pixels for a given node /// </summary> private static int[] mask = new int[8] { 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01 }; /// <summary> /// The root of the octree /// </summary> private OctreeNode _root; /// <summary> /// Number of leaves in the tree /// </summary> private int _leafCount; /// <summary> /// Array of reducible nodes /// </summary> private OctreeNode[] _reducibleNodes; /// <summary> /// Maximum number of significant bits in the image /// </summary> private int _maxColorBits; /// <summary> /// Store the last node quantized /// </summary> private OctreeNode _previousNode; /// <summary> /// Cache the previous color quantized /// </summary> private int _previousColor; /// <summary> /// Class which encapsulates each node in the tree /// </summary> protected class OctreeNode { /// <summary> /// Construct the node /// </summary> /// <param name="level">The level in the tree = 0 - 7</param> /// <param name="colorBits">The number of significant color bits in the image</param> /// <param name="octree">The tree to which this node belongs</param> public OctreeNode(int level, int colorBits, Octree octree) { // Construct the new node _leaf = (level == colorBits); _red = _green = _blue = 0; _pixelCount = 0; // If a leaf, increment the leaf count if (_leaf) { octree.Leaves++; _nextReducible = null; _children = null; } else { // Otherwise add this to the reducible nodes _nextReducible = octree.ReducibleNodes[level]; octree.ReducibleNodes[level] = this; _children = new OctreeNode[8]; } } /// <summary> /// Add a color into the tree /// </summary> /// <param name="pixel">The color</param> /// <param name="colorBits">The number of significant color bits</param> /// <param name="level">The level in the tree</param> /// <param name="octree">The tree to which this node belongs</param> public void AddColor(Color32 pixel, int colorBits, int level, Octree octree) { // Update the color information if this is a leaf if (_leaf) { Increment(pixel); // Setup the previous node octree.TrackPrevious(this); } else { // Go to the next level down in the tree int shift = 7 - level; int index = ((pixel.Red & mask[level]) >> (shift - 2)) | ((pixel.Green & mask[level]) >> (shift - 1)) | ((pixel.Blue & mask[level]) >> (shift)); OctreeNode child = _children[index]; if (null == child) { // Create a new child node & store in the array child = new OctreeNode(level + 1, colorBits, octree); _children[index] = child; } // Add the color to the child node child.AddColor(pixel, colorBits, level + 1, octree); } } /// <summary> /// Get/Set the next reducible node /// </summary> public OctreeNode NextReducible { get { return _nextReducible; } set { _nextReducible = value; } } /// <summary> /// Return the child nodes /// </summary> public OctreeNode[] Children { get { return _children; } } /// <summary> /// Reduce this node by removing all of its children /// </summary> /// <returns>The number of leaves removed</returns> public int Reduce() { _red = _green = _blue = 0; int children = 0; // Loop through all children and add their information to this node for (int index = 0; index < 8; index++) { if (null != _children[index]) { _red += _children[index]._red; _green += _children[index]._green; _blue += _children[index]._blue; _pixelCount += _children[index]._pixelCount; ++children; _children[index] = null; } } // Now change this to a leaf node _leaf = true; // Return the number of nodes to decrement the leaf count by return (children - 1); } /// <summary> /// Traverse the tree, building up the color palette /// </summary> /// <param name="palette">The palette</param> /// <param name="paletteIndex">The current palette index</param> public void ConstructPalette(ArrayList palette, ref int paletteIndex) { if (_leaf) { // Consume the next palette index _paletteIndex = paletteIndex++; // And set the color of the palette entry palette.Add(Color.FromArgb(_red / _pixelCount, _green / _pixelCount, _blue / _pixelCount)); } else { // Loop through children looking for leaves for (int index = 0; index < 8; index++) { if (null != _children[index]) _children[index].ConstructPalette(palette, ref paletteIndex); } } } /// <summary> /// Return the palette index for the passed color /// </summary> public int GetPaletteIndex(Color32 pixel, int level) { int paletteIndex = _paletteIndex; if (!_leaf) { int shift = 7 - level; int index = ((pixel.Red & mask[level]) >> (shift - 2)) | ((pixel.Green & mask[level]) >> (shift - 1)) | ((pixel.Blue & mask[level]) >> (shift)); if (null != _children[index]) paletteIndex = _children[index].GetPaletteIndex(pixel, level + 1); else throw new Exception("Didn't expect this!"); } return paletteIndex; } /// <summary> /// Increment the pixel count and add to the color information /// </summary> public void Increment(Color32 pixel) { _pixelCount++; _red += pixel.Red; _green += pixel.Green; _blue += pixel.Blue; } /// <summary> /// Flag indicating that this is a leaf node /// </summary> private bool _leaf; /// <summary> /// Number of pixels in this node /// </summary> private int _pixelCount; /// <summary> /// Red component /// </summary> private int _red; /// <summary> /// Green Component /// </summary> private int _green; /// <summary> /// Blue component /// </summary> private int _blue; /// <summary> /// Pointers to any child nodes /// </summary> private OctreeNode[] _children; /// <summary> /// Pointer to next reducible node /// </summary> private OctreeNode _nextReducible; /// <summary> /// The index of this node in the palette /// </summary> private int _paletteIndex; } } #endregion } /// <summary> /// /// </summary> public static class ImageTools { #region Methods /// <summary> /// Determines whether [is image extension] [the specified extension]. /// </summary> /// <param name="extension">The extension.</param> /// <returns> /// <c>true</c> if [is image extension] [the specified extension]; otherwise, <c>false</c>. /// </returns> public static bool IsImageExtension(string extension) { switch (extension.ToLower()) { case ".jpg": case ".jpeg": case ".gif": case ".png": case ".bmp": return true; } return false; } /// <summary> /// Converts to image format. /// </summary> /// <param name="extension">The extension.</param> /// <returns></returns> public static ImageFormat ConvertToImageFormat(string extension) { switch (extension.ToLower()) { case ".jpg": case ".jpeg": return ImageFormat.Jpeg; case ".gif": return ImageFormat.Gif; case ".png": return ImageFormat.Png; case ".bmp": default: return ImageFormat.Bmp; } } /// <summary> /// Validates the image. /// </summary> /// <param name="filePath">The file path.</param> /// <returns></returns> public static bool ValidateImage(string filePath) { System.Drawing.Image sourceImage; try { sourceImage = System.Drawing.Image.FromFile(filePath); sourceImage.Dispose(); return true; } catch { // This is not a valid image. Do nothing. return false; } } /// <summary> /// Resizes the image. /// </summary> /// <param name="sourceFile">The source file.</param> /// <param name="targetFile">The target file.</param> /// <param name="maxWidth">Width of the max.</param> /// <param name="maxHeight">Height of the max.</param> /// <param name="preserverAspectRatio">if set to <c>true</c> [preserver aspect ratio].</param> /// <param name="quality">The quality.</param> /// <returns></returns> public static bool ResizeImage(string sourceFile, string targetFile, int maxWidth, int maxHeight, bool preserverAspectRatio, int quality) { System.Drawing.Image sourceImage; try { sourceImage = System.Drawing.Image.FromFile(sourceFile); } catch (OutOfMemoryException) { // This is not a valid image. Do nothing. return false; } // If 0 is passed in any of the max sizes it means that that size must be ignored, // so the original image size is used. maxWidth = maxWidth == 0 ? sourceImage.Width : maxWidth; maxHeight = maxHeight == 0 ? sourceImage.Height : maxHeight; if (sourceImage.Width <= maxWidth && sourceImage.Height <= maxHeight) { sourceImage.Dispose(); if (sourceFile != targetFile) System.IO.File.Copy(sourceFile, targetFile); return true; } Size oSize; if (preserverAspectRatio) { // Gets the best size for aspect ratio resampling oSize = GetAspectRatioSize(maxWidth, maxHeight, sourceImage.Width, sourceImage.Height); } else oSize = new Size(maxWidth, maxHeight); System.Drawing.Image oResampled = null; Graphics oGraphics = null; try { oResampled = new Bitmap(oSize.Width, oSize.Height, PixelFormat.Format24bppRgb); // Creates a Graphics for the oResampled image oGraphics = Graphics.FromImage(oResampled); // The Rectangle that holds the Resampled image size Rectangle oRectangle; // High quality resizing if (quality > 80) { oGraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; // If HighQualityBicubic is used, bigger Rectangle is required to remove the white border oRectangle = new Rectangle(-1, -1, oSize.Width + 1, oSize.Height + 1); } else oRectangle = new Rectangle(0, 0, oSize.Width, oSize.Height); // Place a white background (for transparent images). oGraphics.FillRectangle(new SolidBrush(Color.White), oRectangle); // Draws over the oResampled image the resampled Image oGraphics.DrawImage(sourceImage, oRectangle); sourceImage.Dispose(); String extension = System.IO.Path.GetExtension(targetFile).ToLower(); if (extension == ".jpg" || extension == ".jpeg") { ImageCodecInfo oCodec = GetJpgCodec(); if (oCodec != null) { EncoderParameters aCodecParams = new EncoderParameters(1); aCodecParams.Param[0] = new EncoderParameter(Encoder.Quality, quality); oResampled.Save(targetFile, oCodec, aCodecParams); } else oResampled.Save(targetFile); } else { switch (extension) { case ".gif": try { // Use a proper palette OctreeQuantizer quantizer = new OctreeQuantizer(255, 8); using (Bitmap quantized = quantizer.Quantize(oResampled)) { quantized.Save(targetFile, System.Drawing.Imaging.ImageFormat.Gif); } } catch (System.Security.SecurityException) { // The calls to Marshal might fail in Medium trust, save the image using the default palette oResampled.Save(targetFile, System.Drawing.Imaging.ImageFormat.Png); } break; case ".png": oResampled.Save(targetFile, System.Drawing.Imaging.ImageFormat.Png); break; case ".bmp": oResampled.Save(targetFile, System.Drawing.Imaging.ImageFormat.Bmp); break; } } } finally { if (oGraphics != null) oGraphics.Dispose(); if (oResampled != null) oResampled.Dispose(); } return true; } public static bool ResizeImage(Stream sourceStream, Stream targetStream, ImageFormat imageFormat, int maxWidth, int maxHeight, bool preserverAspectRatio, int quality) { System.Drawing.Image sourceImage; try { sourceImage = System.Drawing.Image.FromStream(sourceStream); sourceStream.Position = 0; } catch (OutOfMemoryException) { // This is not a valid image. Do nothing. return false; } // If 0 is passed in any of the max sizes it means that that size must be ignored, // so the original image size is used. maxWidth = maxWidth == 0 ? sourceImage.Width : maxWidth; maxHeight = maxHeight == 0 ? sourceImage.Height : maxHeight; if (sourceImage.Width <= maxWidth && sourceImage.Height <= maxHeight) { sourceImage.Dispose(); sourceStream.CopyTo(targetStream); return true; } Size oSize; if (preserverAspectRatio) { // Gets the best size for aspect ratio resampling oSize = GetAspectRatioSize(maxWidth, maxHeight, sourceImage.Width, sourceImage.Height); } else oSize = new Size(maxWidth, maxHeight); System.Drawing.Image oResampled = null; Graphics oGraphics = null; try { oResampled = new Bitmap(oSize.Width, oSize.Height, PixelFormat.Format24bppRgb); // Creates a Graphics for the oResampled image oGraphics = Graphics.FromImage(oResampled); // The Rectangle that holds the Resampled image size Rectangle oRectangle; // High quality resizing if (quality > 80) { oGraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; // If HighQualityBicubic is used, bigger Rectangle is required to remove the white border oRectangle = new Rectangle(-1, -1, oSize.Width + 1, oSize.Height + 1); } else oRectangle = new Rectangle(0, 0, oSize.Width, oSize.Height); // Place a white background (for transparent images). oGraphics.FillRectangle(new SolidBrush(Color.White), oRectangle); // Draws over the oResampled image the resampled Image oGraphics.DrawImage(sourceImage, oRectangle); sourceImage.Dispose(); if (imageFormat == ImageFormat.Jpeg) { ImageCodecInfo oCodec = GetJpgCodec(); if (oCodec != null) { EncoderParameters aCodecParams = new EncoderParameters(1); aCodecParams.Param[0] = new EncoderParameter(Encoder.Quality, quality); oResampled.Save(targetStream, oCodec, aCodecParams); } else oResampled.Save(targetStream, imageFormat); } else if (imageFormat == ImageFormat.Gif) { try { // Use a proper palette OctreeQuantizer quantizer = new OctreeQuantizer(255, 8); using (Bitmap quantized = quantizer.Quantize(oResampled)) { quantized.Save(targetStream, System.Drawing.Imaging.ImageFormat.Gif); } } catch (System.Security.SecurityException) { // The calls to Marshal might fail in Medium trust, save the image using the default palette oResampled.Save(targetStream, System.Drawing.Imaging.ImageFormat.Png); } } else { oResampled.Save(targetStream, System.Drawing.Imaging.ImageFormat.Png); } } finally { if (oGraphics != null) oGraphics.Dispose(); if (oResampled != null) oResampled.Dispose(); } return true; } /// <summary> /// Crops the image. /// </summary> /// <param name="sourceFilePath">The source file path.</param> /// <param name="targetFilePath">The target file path.</param> /// <param name="x">The x.</param> /// <param name="y">The y.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <returns></returns> public static bool CropImage(string sourceFilePath, string targetFilePath, int x, int y, int width, int height) { var extension = Path.GetExtension(sourceFilePath); var imageFormat = ConvertToImageFormat(extension); using (FileStream fs = new FileStream(sourceFilePath, FileMode.Open, FileAccess.Read, FileShare.Read)) { using (FileStream target = new FileStream(targetFilePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None)) { CropImage(fs, target, imageFormat, x, y, width, height); } } return true; } public static bool CropImage(Stream sourceStream, Stream targetStream, ImageFormat imageFormat, int x, int y, int width, int height) { Rectangle r = new Rectangle(x, y, width, height); using (Bitmap src = Image.FromStream(sourceStream) as Bitmap) { Bitmap target = new Bitmap(width, height); using (Graphics g = Graphics.FromImage(target)) { g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; g.DrawImage(src, new Rectangle(0, 0, target.Width, target.Height), r, GraphicsUnit.Pixel); } target.Save(targetStream, imageFormat); } return true; } /// <summary> /// Gets the JPG codec. /// </summary> /// <returns></returns> private static ImageCodecInfo GetJpgCodec() { ImageCodecInfo[] aCodecs = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo oCodec = null; for (int i = 0; i < aCodecs.Length; i++) { if (aCodecs[i].MimeType.Equals("image/jpeg")) { oCodec = aCodecs[i]; break; } } return oCodec; } /// <summary> /// Gets the size of the aspect ratio. /// </summary> /// <param name="maxWidth">Width of the max.</param> /// <param name="maxHeight">Height of the max.</param> /// <param name="actualWidth">The actual width.</param> /// <param name="actualHeight">The actual height.</param> /// <returns></returns> public static Size GetAspectRatioSize(int maxWidth, int maxHeight, int actualWidth, int actualHeight) { // Creates the Size object to be returned Size oSize = new System.Drawing.Size(maxWidth, maxHeight); // Calculates the X and Y resize factors float iFactorX = (float)maxWidth / (float)actualWidth; float iFactorY = (float)maxHeight / (float)actualHeight; // If some dimension have to be scaled if (iFactorX != 1 || iFactorY != 1) { // Uses the lower Factor to scale the opposite size if (iFactorX < iFactorY) { oSize.Height = (int)Math.Round((float)actualHeight * iFactorX); } else if (iFactorX > iFactorY) { oSize.Width = (int)Math.Round((float)actualWidth * iFactorY); } } if (oSize.Height <= 0) oSize.Height = 1; if (oSize.Width <= 0) oSize.Width = 1; // Returns the Size return oSize; } #endregion } }
// MbUnit Test Framework // // Copyright (c) 2004 Jonathan de Halleux // // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from // the use of this software. // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; // you must not claim that you wrote the original software. // If you use this software in a product, an acknowledgment in the product // documentation would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must // not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source // distribution. // // MbUnit HomePage: http://www.mbunit.com // Author: Jonathan de Halleux using System; using System.Reflection; using System.Threading; namespace MbUnit.Core { using MbUnit.Core.Runs; using MbUnit.Framework; using MbUnit.Core.Exceptions; using MbUnit.Core.Collections; using MbUnit.Core.Reports.Serialization; using MbUnit.Core.Invokers; using MbUnit.Core.Filters; public class Fixture { private Type type; private IRun run; private MethodInfo setUp = null; private MethodInfo tearDown = null; private bool ignored; private RunPipeStarterCollection starters; private TimeSpan timeOut = new TimeSpan(0, 5, 0); private ApartmentState apartmentState = ApartmentState.Unknown; public Fixture(Type type, IRun run, MethodInfo setUp, MethodInfo tearDown, bool ignored) { if (type==null) throw new ArgumentNullException("type"); if (run==null) throw new ArgumentNullException("run"); this.type=type; ReflectionAssert.HasDefaultConstructor(this.type); this.run = run; this.setUp = setUp; this.tearDown = tearDown; this.ignored = ignored; this.starters = new RunPipeStarterCollection(this); } public string Name { get { if (this.Type.DeclaringType != null) { string name = this.Type.FullName; return name.Substring( this.Type.Namespace.Length+1, name.Length - this.Type.Namespace.Length-1 ); } else return this.Type.Name; } } public Type Type { get { return this.type; } } public IRun Run { get { return this.run; } } public RunPipeStarterCollection Starters { get { return this.starters; } } public MethodInfo SetUpMethod { get { return this.setUp; } } public MethodInfo TearDownMethod { get { return this.tearDown; } } /// <summary> /// Returns true if the entire test fixture is ignored. /// </summary> public bool IsIgnored { get { return this.ignored; } } public TimeSpan TimeOut { get { return this.timeOut; } set { this.timeOut = value; } } public ApartmentState ApartmentState { get { return this.apartmentState; } set { this.apartmentState = value; } } public bool HasSetUp { get { return this.setUp != null; } } public bool HasTearDown { get { return this.tearDown!=null; } } public void Load(IRunPipeFilter filter) { if (filter == null) throw new ArgumentNullException("filter"); this.starters.Clear(); try { RunInvokerTree tree = new RunInvokerTree(this); foreach (RunPipe pipe in tree.AllTestPipes()) { if (!filter.Filter(pipe)) continue; RunPipeStarter starter = new RunPipeStarter(pipe); this.Starters.Add(starter); } } catch (Exception ex) { throw new ApplicationException("Error while create the invoker tree", ex); } } public ReportCounter GetCounter() { ReportCounter counter = new ReportCounter(); counter.RunCount = this.Starters.Count; foreach (RunPipeStarter starter in this.Starters) { if (starter.HasResult) { switch (starter.Result.Result) { case ReportRunResult.Success: ++counter.SuccessCount; break; case ReportRunResult.Failure: ++counter.FailureCount; break; case ReportRunResult.Ignore: ++counter.IgnoreCount; break; } } } return counter; } #region SetUp and TearDown public Object CreateInstance() { Object fixture = TypeHelper.CreateInstance(this.type); ; return fixture; } public void SetUp(object fixture) { if (fixture == null) throw new ArgumentNullException("fixture"); if (this.setUp!=null && ! ignored) this.setUp.Invoke(fixture,null); } public void TearDown(object fixture) { if (fixture==null) throw new ArgumentNullException("fixture"); if (this.tearDown!=null && ! ignored) this.tearDown.Invoke(fixture,null); IDisposable disposable = fixture as IDisposable; if (disposable != null) disposable.Dispose(); } #endregion public override string ToString() { return this.Name; } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.Contracts; namespace System.Reflection.Emit { public class TypeBuilder { public string FullName { get; } public Type ReflectedType { get; } public System.Reflection.Assembly Assembly { get; } public PackingSize PackingSize { get; } public Type UnderlyingSystemType { get; } public int Size { get; } public Type DeclaringType { get; } public RuntimeTypeHandle TypeHandle { get; } public TypeToken TypeToken { get; } public Type BaseType { get; } public string Name { get; } public Guid GUID { get; } public string Namespace { get; } public string AssemblyQualifiedName { get; } public System.Reflection.Module Module { get; } public void SetCustomAttribute (CustomAttributeBuilder! customBuilder) { CodeContract.Requires(customBuilder != null); } public void SetCustomAttribute (System.Reflection.ConstructorInfo! con, Byte[]! binaryAttribute) { CodeContract.Requires(con != null); CodeContract.Requires(binaryAttribute != null); } public bool IsDefined (Type attributeType, bool inherit) { return default(bool); } public Object[] GetCustomAttributes (Type! attributeType, bool inherit) { CodeContract.Requires(attributeType != null); return default(Object[]); } public Object[] GetCustomAttributes (bool inherit) { return default(Object[]); } public bool IsSubclassOf (Type c) { return default(bool); } public Type GetElementType () { return default(Type); } public bool IsAssignableFrom (Type c) { return default(bool); } public System.Reflection.MemberInfo[] GetMembers (System.Reflection.BindingFlags bindingAttr) { return default(System.Reflection.MemberInfo[]); } public System.Reflection.EventInfo[] GetEvents (System.Reflection.BindingFlags bindingAttr) { return default(System.Reflection.EventInfo[]); } public System.Reflection.InterfaceMapping GetInterfaceMap (Type interfaceType) { return default(System.Reflection.InterfaceMapping); } public System.Reflection.MemberInfo[] GetMember (string name, System.Reflection.MemberTypes type, System.Reflection.BindingFlags bindingAttr) { return default(System.Reflection.MemberInfo[]); } public Type GetNestedType (string name, System.Reflection.BindingFlags bindingAttr) { return default(Type); } public Type[] GetNestedTypes (System.Reflection.BindingFlags bindingAttr) { return default(Type[]); } public System.Reflection.PropertyInfo[] GetProperties (System.Reflection.BindingFlags bindingAttr) { return default(System.Reflection.PropertyInfo[]); } public System.Reflection.EventInfo[] GetEvents () { return default(System.Reflection.EventInfo[]); } public System.Reflection.EventInfo GetEvent (string name, System.Reflection.BindingFlags bindingAttr) { return default(System.Reflection.EventInfo); } public Type[] GetInterfaces () { return default(Type[]); } public Type GetInterface (string name, bool ignoreCase) { return default(Type); } public System.Reflection.FieldInfo[] GetFields (System.Reflection.BindingFlags bindingAttr) { return default(System.Reflection.FieldInfo[]); } public System.Reflection.FieldInfo GetField (string name, System.Reflection.BindingFlags bindingAttr) { return default(System.Reflection.FieldInfo); } public System.Reflection.MethodInfo[] GetMethods (System.Reflection.BindingFlags bindingAttr) { return default(System.Reflection.MethodInfo[]); } public System.Reflection.ConstructorInfo[] GetConstructors (System.Reflection.BindingFlags bindingAttr) { return default(System.Reflection.ConstructorInfo[]); } [Pure][Reads(ReadsAttribute.Reads.Owned)] public string ToString () { return default(string); } public object InvokeMember (string name, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object target, Object[] args, System.Reflection.ParameterModifier[] modifiers, System.Globalization.CultureInfo culture, String[] namedParameters) { return default(object); } public void AddDeclarativeSecurity (System.Security.Permissions.SecurityAction action, System.Security.PermissionSet pset) { } public TypeBuilder DefineNestedType (string name, System.Reflection.TypeAttributes attr, Type parent, PackingSize packSize) { return default(TypeBuilder); } public TypeBuilder DefineNestedType (string name, System.Reflection.TypeAttributes attr, Type parent, int typeSize) { return default(TypeBuilder); } public TypeBuilder DefineNestedType (string name, System.Reflection.TypeAttributes attr) { return default(TypeBuilder); } public TypeBuilder DefineNestedType (string name, System.Reflection.TypeAttributes attr, Type parent) { return default(TypeBuilder); } public TypeBuilder DefineNestedType (string name, System.Reflection.TypeAttributes attr, Type parent, Type[] interfaces) { return default(TypeBuilder); } public TypeBuilder DefineNestedType (string name) { return default(TypeBuilder); } public FieldBuilder DefineUninitializedData (string name, int size, System.Reflection.FieldAttributes attributes) { return default(FieldBuilder); } public FieldBuilder DefineInitializedData (string name, Byte[] data, System.Reflection.FieldAttributes attributes) { return default(FieldBuilder); } public FieldBuilder DefineField (string fieldName, Type type, System.Reflection.FieldAttributes attributes) { return default(FieldBuilder); } public void DefineMethodOverride (System.Reflection.MethodInfo methodInfoBody, System.Reflection.MethodInfo methodInfoDeclaration) { } public Type CreateType () { return default(Type); } public ConstructorBuilder DefineDefaultConstructor (System.Reflection.MethodAttributes attributes) { return default(ConstructorBuilder); } public ConstructorBuilder DefineConstructor (System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type[] parameterTypes) { return default(ConstructorBuilder); } public ConstructorBuilder DefineTypeInitializer () { return default(ConstructorBuilder); } public MethodBuilder DefinePInvokeMethod (string name, string dllName, string entryName, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type returnType, Type[] parameterTypes, System.Runtime.InteropServices.CallingConvention nativeCallConv, System.Runtime.InteropServices.CharSet nativeCharSet) { return default(MethodBuilder); } public MethodBuilder DefinePInvokeMethod (string name, string dllName, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type returnType, Type[] parameterTypes, System.Runtime.InteropServices.CallingConvention nativeCallConv, System.Runtime.InteropServices.CharSet nativeCharSet) { return default(MethodBuilder); } public EventBuilder DefineEvent (string name, System.Reflection.EventAttributes attributes, Type eventtype) { return default(EventBuilder); } public PropertyBuilder DefineProperty (string name, System.Reflection.PropertyAttributes attributes, Type returnType, Type[] parameterTypes) { return default(PropertyBuilder); } public MethodBuilder DefineMethod (string name, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type returnType, Type[] parameterTypes) { return default(MethodBuilder); } public MethodBuilder DefineMethod (string name, System.Reflection.MethodAttributes attributes, Type returnType, Type[] parameterTypes) { return default(MethodBuilder); } public void AddInterfaceImplementation (Type! interfaceType) { CodeContract.Requires(interfaceType != null); } public void SetParent (Type! parent) { CodeContract.Requires(parent != null); } } }
using System; using System.Collections.Generic; using System.Linq; using DevExpress.CodeRush.Core; namespace CR_XkeysEngine { public class KeyLayout : IKeyGetter { List<KeyBase> keys = new List<KeyBase>(); public KeyLayout() { } public List<KeyBase> GetPressedKeys(string customData) { return Hardware.Keyboard.GetPressedKeys(customData, this as IKeyGetter); } public string GetBindingName(bool anyShiftModifier, bool ctrlKeyDown, bool shiftKeyDown, bool altKeyDown, string customData) { return XkeysUtils.GetKeyName(anyShiftModifier, ctrlKeyDown, shiftKeyDown, altKeyDown, GetPressedKeys(customData)); } public string GetCodeStr() { return Hardware.Keyboard.GetCodeStr(this as IKeyGetter); } public void Remove(KeyBase key) { keys.Remove(key); } public void UngroupSelection() { XkeySelection selection = GetSelection(); foreach (KeyBase selectedKey in selection.SelectedKeys) { KeyGroup keyGroup = selectedKey as KeyGroup; if (keyGroup != null) keyGroup.Ungroup(this); } OnSelectionChanged(); } void RemoveSelectedKeys() { XkeySelection selection = GetSelection(); foreach (KeyBase selectedKey in selection.SelectedKeys) keys.Remove(selectedKey); } public void GroupSelection(KeyGroupType keysGroupType) { XkeySelection selection = GetSelection(); RemoveSelectedKeys(); KeyGroup keyGroup = new KeyGroup() { Type = keysGroupType, Name = selection.GetName() }; int topmostRow = -1; int leftmostColumn = -1; foreach (KeyBase selectedKey in selection.SelectedKeys) { selectedKey.ClearSelection(); keyGroup.Keys.Add(selectedKey); if (topmostRow == -1 || selectedKey.Row < topmostRow) topmostRow = selectedKey.Row; if (leftmostColumn == -1 || selectedKey.Column < leftmostColumn) leftmostColumn = selectedKey.Column; } keyGroup.Selected = true; keyGroup.SetPosition(leftmostColumn, topmostRow); keys.Add(keyGroup); OnSelectionChanged(); } protected virtual void OnSelectionChanged() { EventHandler handler = SelectionChanged; if (handler != null) handler(this, EventArgs.Empty); } public event EventHandler SelectionChanged; public XkeySelection GetSelection() { XkeySelection selection = new XkeySelection(); for (int i = 0; i < Keys.Count; i++) if (Keys[i].Selected) selection.AddKey(Keys[i]); return selection; } public void MoveSelection(int deltaX, int deltaY, bool addToSelection) { int selectionColumn = -1; int keyWidth = 1; int keyHeight = 1; int selectionRow = -1; for (int i = 0; i < Keys.Count; i++) if (Keys[i].Selected) { KeyGroup keyGroup = Keys[i] as KeyGroup; if (keyGroup != null) { if (deltaX > 0) if (keyGroup.Type == KeyGroupType.Wide || keyGroup.Type == KeyGroupType.Square) keyWidth = 2; if (deltaY > 0) if (keyGroup.Type == KeyGroupType.Tall || keyGroup.Type == KeyGroupType.Square) keyHeight = 2; } selectionColumn = Keys[i].Column; selectionRow = Keys[i].Row; break; } if (selectionColumn == -1) return; int newColumn = selectionColumn + deltaX * keyWidth; int newRow = selectionRow + deltaY * keyHeight; if (Hardware.Keyboard.IsValidKey(newColumn, newRow)) Select(newColumn, newRow, addToSelection, false); } public void SetRepeat(bool shouldRepeat) { for (int i = 0; i < Keys.Count; i++) if (Keys[i].Selected) Keys[i].SetRepeat(shouldRepeat); } public void SetName(string newName) { for (int i = 0; i < Keys.Count; i++) if (Keys[i].Selected) Keys[i].SetName(newName); } public void ClearSelection() { bool selectionChanged = false; for (int i = 0; i < Keys.Count; i++) if (Keys[i].ClearSelection()) selectionChanged = true; if (selectionChanged) OnSelectionChanged(); } public bool Select(int column, int row, bool addToSelection, bool toggleSelection) { if (IsSelected(column, row) && !toggleSelection) { XkeySelection selection = GetSelection(); if (selection.SelectedKeys.Count == 1) // Already selected. No changes. return false; } if (!addToSelection && !toggleSelection) ClearSelection(); for (int i = 0; i < Keys.Count; i++) if (toggleSelection) Keys[i].ToggleSelection(column, row); else Keys[i].Select(column, row); return true; } public KeyBase GetKey(int column, int row) { for (int i = 0; i < Keys.Count; i++) if (Keys[i].IsAt(column, row)) return Keys[i]; return null; } /// <summary> /// Gets the single key at the specified column and row. If a group key /// (tall, wide, or square) is at the specified location, then that group /// is drilled into to find and return the actual subkey at the column and /// row. /// </summary> public KeyBase GetSingleKey(int column, int row) { KeyBase key = GetKey(column, row); KeyGroup keyGroup = key as KeyGroup; if (keyGroup == null) return key; foreach (KeyBase subkey in keyGroup.Keys) if (subkey.IsAt(column, row)) return subkey; return null; } public string GetKeyName(int column, int row) { KeyBase key = GetKey(column, row); if (key != null) return key.Name; else return null; } public bool IsSelected(int column, int row) { foreach (KeyBase key in Keys) if (key.IsSelected(column, row)) return true; return false; } public List<KeyBase> Keys { get { return keys; } } public void Save() { DecoupledStorage storage = OptXkeysLayout.Storage; storage.ClearAll(); storage.WriteInt32("Layout", "Count", keys.Count); for (int i = 0; i < Keys.Count; i++) Keys[i].Save(storage, "Layout", i); } public void BlockSettingsChanged() { Hardware.Keyboard.BlockSettingsChanged(Keys); } public void Load() { Keys.Clear(); DecoupledStorage storage = OptXkeysLayout.Storage; int numKeys = storage.ReadInt32("Layout", "Count"); for (int i = 0; i < numKeys; i++) Keys.Add(KeyBase.CreateAndLoad(storage, "Layout", i)); BlockSettingsChanged(); } } }
// 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.Reflection; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Diagnostics.Contracts; namespace System.Reflection.Emit { public sealed class GenericTypeParameterBuilder : TypeInfo { public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo) { if (typeInfo == null) return false; return IsAssignableFrom(typeInfo.AsType()); } #region Private Data Mebers internal TypeBuilder m_type; #endregion #region Constructor internal GenericTypeParameterBuilder(TypeBuilder type) { m_type = type; } #endregion #region Object Overrides public override String ToString() { return m_type.Name; } public override bool Equals(object o) { GenericTypeParameterBuilder g = o as GenericTypeParameterBuilder; if (g == null) return false; return object.ReferenceEquals(g.m_type, m_type); } public override int GetHashCode() { return m_type.GetHashCode(); } #endregion #region MemberInfo Overrides public override Type DeclaringType { get { return m_type.DeclaringType; } } public override Type ReflectedType { get { return m_type.ReflectedType; } } public override String Name { get { return m_type.Name; } } public override Module Module { get { return m_type.Module; } } internal int MetadataTokenInternal { get { return m_type.MetadataTokenInternal; } } #endregion #region Type Overrides public override Type MakePointerType() { return SymbolType.FormCompoundType("*", this, 0); } public override Type MakeByRefType() { return SymbolType.FormCompoundType("&", this, 0); } public override Type MakeArrayType() { return SymbolType.FormCompoundType("[]", this, 0); } public override Type MakeArrayType(int rank) { if (rank <= 0) throw new IndexOutOfRangeException(); Contract.EndContractBlock(); string szrank = ""; if (rank == 1) { szrank = "*"; } else { for (int i = 1; i < rank; i++) szrank += ","; } string s = String.Format(CultureInfo.InvariantCulture, "[{0}]", szrank); // [,,] SymbolType st = SymbolType.FormCompoundType(s, this, 0) as SymbolType; return st; } public override Guid GUID { get { throw new NotSupportedException(); } } public override Object InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParameters) { throw new NotSupportedException(); } public override Assembly Assembly { get { return m_type.Assembly; } } public override RuntimeTypeHandle TypeHandle { get { throw new NotSupportedException(); } } public override String FullName { get { return null; } } public override String Namespace { get { return null; } } public override String AssemblyQualifiedName { get { return null; } } public override Type BaseType { get { return m_type.BaseType; } } protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); } public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) { throw new NotSupportedException(); } protected override MethodInfo GetMethodImpl(String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); } public override MethodInfo[] GetMethods(BindingFlags bindingAttr) { throw new NotSupportedException(); } public override FieldInfo GetField(String name, BindingFlags bindingAttr) { throw new NotSupportedException(); } public override FieldInfo[] GetFields(BindingFlags bindingAttr) { throw new NotSupportedException(); } public override Type GetInterface(String name, bool ignoreCase) { throw new NotSupportedException(); } public override Type[] GetInterfaces() { throw new NotSupportedException(); } public override EventInfo GetEvent(String name, BindingFlags bindingAttr) { throw new NotSupportedException(); } public override EventInfo[] GetEvents() { throw new NotSupportedException(); } protected override PropertyInfo GetPropertyImpl(String name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); } public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) { throw new NotSupportedException(); } public override Type[] GetNestedTypes(BindingFlags bindingAttr) { throw new NotSupportedException(); } public override Type GetNestedType(String name, BindingFlags bindingAttr) { throw new NotSupportedException(); } public override MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr) { throw new NotSupportedException(); } public override InterfaceMapping GetInterfaceMap(Type interfaceType) { throw new NotSupportedException(); } public override EventInfo[] GetEvents(BindingFlags bindingAttr) { throw new NotSupportedException(); } public override MemberInfo[] GetMembers(BindingFlags bindingAttr) { throw new NotSupportedException(); } protected override TypeAttributes GetAttributeFlagsImpl() { return TypeAttributes.Public; } public override bool IsTypeDefinition => false; public override bool IsSZArray => false; protected override bool IsArrayImpl() { return false; } protected override bool IsByRefImpl() { return false; } protected override bool IsPointerImpl() { return false; } protected override bool IsPrimitiveImpl() { return false; } protected override bool IsCOMObjectImpl() { return false; } public override Type GetElementType() { throw new NotSupportedException(); } protected override bool HasElementTypeImpl() { return false; } public override Type UnderlyingSystemType { get { return this; } } public override Type[] GetGenericArguments() { throw new InvalidOperationException(); } public override bool IsGenericTypeDefinition { get { return false; } } public override bool IsGenericType { get { return false; } } public override bool IsGenericParameter { get { return true; } } public override bool IsConstructedGenericType { get { return false; } } public override int GenericParameterPosition { get { return m_type.GenericParameterPosition; } } public override bool ContainsGenericParameters { get { return m_type.ContainsGenericParameters; } } public override GenericParameterAttributes GenericParameterAttributes { get { return m_type.GenericParameterAttributes; } } public override MethodBase DeclaringMethod { get { return m_type.DeclaringMethod; } } public override Type GetGenericTypeDefinition() { throw new InvalidOperationException(); } public override Type MakeGenericType(params Type[] typeArguments) { throw new InvalidOperationException(SR.Arg_NotGenericTypeDefinition); } protected override bool IsValueTypeImpl() { return false; } public override bool IsAssignableFrom(Type c) { throw new NotSupportedException(); } [Pure] public override bool IsSubclassOf(Type c) { throw new NotSupportedException(); } #endregion #region ICustomAttributeProvider Implementation public override Object[] GetCustomAttributes(bool inherit) { throw new NotSupportedException(); } public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { throw new NotSupportedException(); } public override bool IsDefined(Type attributeType, bool inherit) { throw new NotSupportedException(); } #endregion #region Public Members public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { m_type.SetGenParamCustomAttribute(con, binaryAttribute); } public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { m_type.SetGenParamCustomAttribute(customBuilder); } public void SetBaseTypeConstraint(Type baseTypeConstraint) { m_type.CheckContext(baseTypeConstraint); m_type.SetParent(baseTypeConstraint); } public void SetInterfaceConstraints(params Type[] interfaceConstraints) { m_type.CheckContext(interfaceConstraints); m_type.SetInterfaces(interfaceConstraints); } public void SetGenericParameterAttributes(GenericParameterAttributes genericParameterAttributes) { m_type.SetGenParamAttributes(genericParameterAttributes); } #endregion } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using SerialNET; using Franson.BlueTools; namespace SerialService { /// <summary> /// Summary description for Form1. /// </summary> public class MainForm : System.Windows.Forms.Form { private System.Windows.Forms.Button startService; private System.Windows.Forms.Button stopService; private System.Windows.Forms.Label label1; private System.Windows.Forms.ComboBox serialPortList; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; Manager manager; Network[] networks; LocalService service; public MainForm() { // // Required for Windows Form Designer support // InitializeComponent(); Closing += new CancelEventHandler(MainForm_Closing); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { manager.Dispose(); 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() { this.startService = new System.Windows.Forms.Button(); this.stopService = new System.Windows.Forms.Button(); this.serialPortList = new System.Windows.Forms.ComboBox(); this.label1 = new System.Windows.Forms.Label(); this.SuspendLayout(); // // startService // this.startService.Location = new System.Drawing.Point(8, 56); this.startService.Name = "startService"; this.startService.TabIndex = 0; this.startService.Text = "Start"; this.startService.Click += new System.EventHandler(this.startService_Click); // // stopService // this.stopService.Location = new System.Drawing.Point(88, 56); this.stopService.Name = "stopService"; this.stopService.TabIndex = 1; this.stopService.Text = "Stop"; this.stopService.Click += new System.EventHandler(this.stopService_Click); // // serialPortList // this.serialPortList.Location = new System.Drawing.Point(8, 24); this.serialPortList.Name = "serialPortList"; this.serialPortList.Size = new System.Drawing.Size(160, 21); this.serialPortList.TabIndex = 2; // // label1 // this.label1.Location = new System.Drawing.Point(8, 8); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(100, 16); this.label1.TabIndex = 3; this.label1.Text = "Serial Port"; // // MainForm // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(184, 102); this.Controls.Add(this.label1); this.Controls.Add(this.serialPortList); this.Controls.Add(this.stopService); this.Controls.Add(this.startService); this.Name = "MainForm"; this.Text = "Serial Service"; this.Load += new System.EventHandler(this.MainForm_Load); this.ResumeLayout(false); } #endregion /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.Run(new MainForm()); } private void MainForm_Load(object sender, System.EventArgs e) { startService.Enabled = true; stopService.Enabled = false; byte[] ports = Port.List; for(int i = 0; i < ports.Length; i++) { serialPortList.Items.Add("COM" + ports[i]); } // You can get a valid evaluation key for BlueTools at // http://franson.com/bluetools/ // That key will be valid for 14 days. Just cut and paste that key into the statement below. // To get a key that do not expire you need to purchase a license Franson.BlueTools.License bluetoolsLicense = new Franson.BlueTools.License(); bluetoolsLicense.LicenseKey = "WoK6HM24B9ECLOPQSXVZPixRDRfuIYHYWrT9"; // You can get a valid evaluation key for SerialTools at // http://franson.com/serialtools/ // That key will be valid for 14 days. Just cut and paste that key into the statement below. // To get a key that do not expire you need to purchase a license SerialNET.License serialNetLicense = new SerialNET.License(); serialNetLicense.LicenseKey = "SfHBmVyklQfUSYkv63PXn4jZo4ndCTxZSjHB"; try { manager = Manager.GetManager(); manager.Parent = this; networks = manager.Networks; } catch (BlueToolsException exc) { MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } private void startService_Click(object sender, System.EventArgs e) { if(service != null) { MessageBox.Show("The service has already been started"); } else { Port port = new Port(); port.BaudRate = 4800; port.ComPort = Int32.Parse(serialPortList.SelectedItem.ToString().Substring(3)); service = new SerialService(port); startService.Enabled = false; stopService.Enabled = true; try { foreach(Network network in networks) { network.Server.Advertise(service); } } catch (Exception exc) { MessageBox.Show(exc.Message); } } } private void MainForm_Closing(object sender, CancelEventArgs e) { Dispose(); } private void stopService_Click(object sender, System.EventArgs e) { if(service == null) { MessageBox.Show("The service has not been started"); } else { foreach(Network network in networks) { network.Server.Deadvertise(service); } service = null; startService.Enabled = true; stopService.Enabled = false; } } } }
// Copyright 2018 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! namespace Google.Cloud.Debugger.V2.Tests { using Google.Api.Gax; using Google.Api.Gax.Grpc; using apis = Google.Cloud.Debugger.V2; using Google.Protobuf.WellKnownTypes; using Grpc.Core; using Moq; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading; using System.Threading.Tasks; using Xunit; /// <summary>Generated unit tests</summary> public class GeneratedDebugger2ClientTest { [Fact] public void SetBreakpoint() { Mock<Debugger2.Debugger2Client> mockGrpcClient = new Mock<Debugger2.Debugger2Client>(MockBehavior.Strict); SetBreakpointRequest expectedRequest = new SetBreakpointRequest { DebuggeeId = "debuggeeId-997255898", Breakpoint = new Breakpoint(), ClientVersion = "clientVersion-1506231196", }; SetBreakpointResponse expectedResponse = new SetBreakpointResponse(); mockGrpcClient.Setup(x => x.SetBreakpoint(expectedRequest, It.IsAny<CallOptions>())) .Returns(expectedResponse); Debugger2Client client = new Debugger2ClientImpl(mockGrpcClient.Object, null); string debuggeeId = "debuggeeId-997255898"; Breakpoint breakpoint = new Breakpoint(); string clientVersion = "clientVersion-1506231196"; SetBreakpointResponse response = client.SetBreakpoint(debuggeeId, breakpoint, clientVersion); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public async Task SetBreakpointAsync() { Mock<Debugger2.Debugger2Client> mockGrpcClient = new Mock<Debugger2.Debugger2Client>(MockBehavior.Strict); SetBreakpointRequest expectedRequest = new SetBreakpointRequest { DebuggeeId = "debuggeeId-997255898", Breakpoint = new Breakpoint(), ClientVersion = "clientVersion-1506231196", }; SetBreakpointResponse expectedResponse = new SetBreakpointResponse(); mockGrpcClient.Setup(x => x.SetBreakpointAsync(expectedRequest, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<SetBreakpointResponse>(Task.FromResult(expectedResponse), null, null, null, null)); Debugger2Client client = new Debugger2ClientImpl(mockGrpcClient.Object, null); string debuggeeId = "debuggeeId-997255898"; Breakpoint breakpoint = new Breakpoint(); string clientVersion = "clientVersion-1506231196"; SetBreakpointResponse response = await client.SetBreakpointAsync(debuggeeId, breakpoint, clientVersion); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public void SetBreakpoint2() { Mock<Debugger2.Debugger2Client> mockGrpcClient = new Mock<Debugger2.Debugger2Client>(MockBehavior.Strict); SetBreakpointRequest request = new SetBreakpointRequest { DebuggeeId = "debuggeeId-997255898", Breakpoint = new Breakpoint(), ClientVersion = "clientVersion-1506231196", }; SetBreakpointResponse expectedResponse = new SetBreakpointResponse(); mockGrpcClient.Setup(x => x.SetBreakpoint(request, It.IsAny<CallOptions>())) .Returns(expectedResponse); Debugger2Client client = new Debugger2ClientImpl(mockGrpcClient.Object, null); SetBreakpointResponse response = client.SetBreakpoint(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public async Task SetBreakpointAsync2() { Mock<Debugger2.Debugger2Client> mockGrpcClient = new Mock<Debugger2.Debugger2Client>(MockBehavior.Strict); SetBreakpointRequest request = new SetBreakpointRequest { DebuggeeId = "debuggeeId-997255898", Breakpoint = new Breakpoint(), ClientVersion = "clientVersion-1506231196", }; SetBreakpointResponse expectedResponse = new SetBreakpointResponse(); mockGrpcClient.Setup(x => x.SetBreakpointAsync(request, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<SetBreakpointResponse>(Task.FromResult(expectedResponse), null, null, null, null)); Debugger2Client client = new Debugger2ClientImpl(mockGrpcClient.Object, null); SetBreakpointResponse response = await client.SetBreakpointAsync(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public void GetBreakpoint() { Mock<Debugger2.Debugger2Client> mockGrpcClient = new Mock<Debugger2.Debugger2Client>(MockBehavior.Strict); GetBreakpointRequest expectedRequest = new GetBreakpointRequest { DebuggeeId = "debuggeeId-997255898", BreakpointId = "breakpointId498424873", ClientVersion = "clientVersion-1506231196", }; GetBreakpointResponse expectedResponse = new GetBreakpointResponse(); mockGrpcClient.Setup(x => x.GetBreakpoint(expectedRequest, It.IsAny<CallOptions>())) .Returns(expectedResponse); Debugger2Client client = new Debugger2ClientImpl(mockGrpcClient.Object, null); string debuggeeId = "debuggeeId-997255898"; string breakpointId = "breakpointId498424873"; string clientVersion = "clientVersion-1506231196"; GetBreakpointResponse response = client.GetBreakpoint(debuggeeId, breakpointId, clientVersion); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public async Task GetBreakpointAsync() { Mock<Debugger2.Debugger2Client> mockGrpcClient = new Mock<Debugger2.Debugger2Client>(MockBehavior.Strict); GetBreakpointRequest expectedRequest = new GetBreakpointRequest { DebuggeeId = "debuggeeId-997255898", BreakpointId = "breakpointId498424873", ClientVersion = "clientVersion-1506231196", }; GetBreakpointResponse expectedResponse = new GetBreakpointResponse(); mockGrpcClient.Setup(x => x.GetBreakpointAsync(expectedRequest, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<GetBreakpointResponse>(Task.FromResult(expectedResponse), null, null, null, null)); Debugger2Client client = new Debugger2ClientImpl(mockGrpcClient.Object, null); string debuggeeId = "debuggeeId-997255898"; string breakpointId = "breakpointId498424873"; string clientVersion = "clientVersion-1506231196"; GetBreakpointResponse response = await client.GetBreakpointAsync(debuggeeId, breakpointId, clientVersion); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public void GetBreakpoint2() { Mock<Debugger2.Debugger2Client> mockGrpcClient = new Mock<Debugger2.Debugger2Client>(MockBehavior.Strict); GetBreakpointRequest request = new GetBreakpointRequest { DebuggeeId = "debuggeeId-997255898", BreakpointId = "breakpointId498424873", ClientVersion = "clientVersion-1506231196", }; GetBreakpointResponse expectedResponse = new GetBreakpointResponse(); mockGrpcClient.Setup(x => x.GetBreakpoint(request, It.IsAny<CallOptions>())) .Returns(expectedResponse); Debugger2Client client = new Debugger2ClientImpl(mockGrpcClient.Object, null); GetBreakpointResponse response = client.GetBreakpoint(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public async Task GetBreakpointAsync2() { Mock<Debugger2.Debugger2Client> mockGrpcClient = new Mock<Debugger2.Debugger2Client>(MockBehavior.Strict); GetBreakpointRequest request = new GetBreakpointRequest { DebuggeeId = "debuggeeId-997255898", BreakpointId = "breakpointId498424873", ClientVersion = "clientVersion-1506231196", }; GetBreakpointResponse expectedResponse = new GetBreakpointResponse(); mockGrpcClient.Setup(x => x.GetBreakpointAsync(request, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<GetBreakpointResponse>(Task.FromResult(expectedResponse), null, null, null, null)); Debugger2Client client = new Debugger2ClientImpl(mockGrpcClient.Object, null); GetBreakpointResponse response = await client.GetBreakpointAsync(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public void DeleteBreakpoint() { Mock<Debugger2.Debugger2Client> mockGrpcClient = new Mock<Debugger2.Debugger2Client>(MockBehavior.Strict); DeleteBreakpointRequest expectedRequest = new DeleteBreakpointRequest { DebuggeeId = "debuggeeId-997255898", BreakpointId = "breakpointId498424873", ClientVersion = "clientVersion-1506231196", }; Empty expectedResponse = new Empty(); mockGrpcClient.Setup(x => x.DeleteBreakpoint(expectedRequest, It.IsAny<CallOptions>())) .Returns(expectedResponse); Debugger2Client client = new Debugger2ClientImpl(mockGrpcClient.Object, null); string debuggeeId = "debuggeeId-997255898"; string breakpointId = "breakpointId498424873"; string clientVersion = "clientVersion-1506231196"; client.DeleteBreakpoint(debuggeeId, breakpointId, clientVersion); mockGrpcClient.VerifyAll(); } [Fact] public async Task DeleteBreakpointAsync() { Mock<Debugger2.Debugger2Client> mockGrpcClient = new Mock<Debugger2.Debugger2Client>(MockBehavior.Strict); DeleteBreakpointRequest expectedRequest = new DeleteBreakpointRequest { DebuggeeId = "debuggeeId-997255898", BreakpointId = "breakpointId498424873", ClientVersion = "clientVersion-1506231196", }; Empty expectedResponse = new Empty(); mockGrpcClient.Setup(x => x.DeleteBreakpointAsync(expectedRequest, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<Empty>(Task.FromResult(expectedResponse), null, null, null, null)); Debugger2Client client = new Debugger2ClientImpl(mockGrpcClient.Object, null); string debuggeeId = "debuggeeId-997255898"; string breakpointId = "breakpointId498424873"; string clientVersion = "clientVersion-1506231196"; await client.DeleteBreakpointAsync(debuggeeId, breakpointId, clientVersion); mockGrpcClient.VerifyAll(); } [Fact] public void DeleteBreakpoint2() { Mock<Debugger2.Debugger2Client> mockGrpcClient = new Mock<Debugger2.Debugger2Client>(MockBehavior.Strict); DeleteBreakpointRequest request = new DeleteBreakpointRequest { DebuggeeId = "debuggeeId-997255898", BreakpointId = "breakpointId498424873", ClientVersion = "clientVersion-1506231196", }; Empty expectedResponse = new Empty(); mockGrpcClient.Setup(x => x.DeleteBreakpoint(request, It.IsAny<CallOptions>())) .Returns(expectedResponse); Debugger2Client client = new Debugger2ClientImpl(mockGrpcClient.Object, null); client.DeleteBreakpoint(request); mockGrpcClient.VerifyAll(); } [Fact] public async Task DeleteBreakpointAsync2() { Mock<Debugger2.Debugger2Client> mockGrpcClient = new Mock<Debugger2.Debugger2Client>(MockBehavior.Strict); DeleteBreakpointRequest request = new DeleteBreakpointRequest { DebuggeeId = "debuggeeId-997255898", BreakpointId = "breakpointId498424873", ClientVersion = "clientVersion-1506231196", }; Empty expectedResponse = new Empty(); mockGrpcClient.Setup(x => x.DeleteBreakpointAsync(request, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<Empty>(Task.FromResult(expectedResponse), null, null, null, null)); Debugger2Client client = new Debugger2ClientImpl(mockGrpcClient.Object, null); await client.DeleteBreakpointAsync(request); mockGrpcClient.VerifyAll(); } [Fact] public void ListBreakpoints() { Mock<Debugger2.Debugger2Client> mockGrpcClient = new Mock<Debugger2.Debugger2Client>(MockBehavior.Strict); ListBreakpointsRequest expectedRequest = new ListBreakpointsRequest { DebuggeeId = "debuggeeId-997255898", ClientVersion = "clientVersion-1506231196", }; ListBreakpointsResponse expectedResponse = new ListBreakpointsResponse { NextWaitToken = "nextWaitToken1006864251", }; mockGrpcClient.Setup(x => x.ListBreakpoints(expectedRequest, It.IsAny<CallOptions>())) .Returns(expectedResponse); Debugger2Client client = new Debugger2ClientImpl(mockGrpcClient.Object, null); string debuggeeId = "debuggeeId-997255898"; string clientVersion = "clientVersion-1506231196"; ListBreakpointsResponse response = client.ListBreakpoints(debuggeeId, clientVersion); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public async Task ListBreakpointsAsync() { Mock<Debugger2.Debugger2Client> mockGrpcClient = new Mock<Debugger2.Debugger2Client>(MockBehavior.Strict); ListBreakpointsRequest expectedRequest = new ListBreakpointsRequest { DebuggeeId = "debuggeeId-997255898", ClientVersion = "clientVersion-1506231196", }; ListBreakpointsResponse expectedResponse = new ListBreakpointsResponse { NextWaitToken = "nextWaitToken1006864251", }; mockGrpcClient.Setup(x => x.ListBreakpointsAsync(expectedRequest, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<ListBreakpointsResponse>(Task.FromResult(expectedResponse), null, null, null, null)); Debugger2Client client = new Debugger2ClientImpl(mockGrpcClient.Object, null); string debuggeeId = "debuggeeId-997255898"; string clientVersion = "clientVersion-1506231196"; ListBreakpointsResponse response = await client.ListBreakpointsAsync(debuggeeId, clientVersion); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public void ListBreakpoints2() { Mock<Debugger2.Debugger2Client> mockGrpcClient = new Mock<Debugger2.Debugger2Client>(MockBehavior.Strict); ListBreakpointsRequest request = new ListBreakpointsRequest { DebuggeeId = "debuggeeId-997255898", ClientVersion = "clientVersion-1506231196", }; ListBreakpointsResponse expectedResponse = new ListBreakpointsResponse { NextWaitToken = "nextWaitToken1006864251", }; mockGrpcClient.Setup(x => x.ListBreakpoints(request, It.IsAny<CallOptions>())) .Returns(expectedResponse); Debugger2Client client = new Debugger2ClientImpl(mockGrpcClient.Object, null); ListBreakpointsResponse response = client.ListBreakpoints(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public async Task ListBreakpointsAsync2() { Mock<Debugger2.Debugger2Client> mockGrpcClient = new Mock<Debugger2.Debugger2Client>(MockBehavior.Strict); ListBreakpointsRequest request = new ListBreakpointsRequest { DebuggeeId = "debuggeeId-997255898", ClientVersion = "clientVersion-1506231196", }; ListBreakpointsResponse expectedResponse = new ListBreakpointsResponse { NextWaitToken = "nextWaitToken1006864251", }; mockGrpcClient.Setup(x => x.ListBreakpointsAsync(request, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<ListBreakpointsResponse>(Task.FromResult(expectedResponse), null, null, null, null)); Debugger2Client client = new Debugger2ClientImpl(mockGrpcClient.Object, null); ListBreakpointsResponse response = await client.ListBreakpointsAsync(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public void ListDebuggees() { Mock<Debugger2.Debugger2Client> mockGrpcClient = new Mock<Debugger2.Debugger2Client>(MockBehavior.Strict); ListDebuggeesRequest expectedRequest = new ListDebuggeesRequest { Project = "project-309310695", ClientVersion = "clientVersion-1506231196", }; ListDebuggeesResponse expectedResponse = new ListDebuggeesResponse(); mockGrpcClient.Setup(x => x.ListDebuggees(expectedRequest, It.IsAny<CallOptions>())) .Returns(expectedResponse); Debugger2Client client = new Debugger2ClientImpl(mockGrpcClient.Object, null); string project = "project-309310695"; string clientVersion = "clientVersion-1506231196"; ListDebuggeesResponse response = client.ListDebuggees(project, clientVersion); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public async Task ListDebuggeesAsync() { Mock<Debugger2.Debugger2Client> mockGrpcClient = new Mock<Debugger2.Debugger2Client>(MockBehavior.Strict); ListDebuggeesRequest expectedRequest = new ListDebuggeesRequest { Project = "project-309310695", ClientVersion = "clientVersion-1506231196", }; ListDebuggeesResponse expectedResponse = new ListDebuggeesResponse(); mockGrpcClient.Setup(x => x.ListDebuggeesAsync(expectedRequest, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<ListDebuggeesResponse>(Task.FromResult(expectedResponse), null, null, null, null)); Debugger2Client client = new Debugger2ClientImpl(mockGrpcClient.Object, null); string project = "project-309310695"; string clientVersion = "clientVersion-1506231196"; ListDebuggeesResponse response = await client.ListDebuggeesAsync(project, clientVersion); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public void ListDebuggees2() { Mock<Debugger2.Debugger2Client> mockGrpcClient = new Mock<Debugger2.Debugger2Client>(MockBehavior.Strict); ListDebuggeesRequest request = new ListDebuggeesRequest { Project = "project-309310695", ClientVersion = "clientVersion-1506231196", }; ListDebuggeesResponse expectedResponse = new ListDebuggeesResponse(); mockGrpcClient.Setup(x => x.ListDebuggees(request, It.IsAny<CallOptions>())) .Returns(expectedResponse); Debugger2Client client = new Debugger2ClientImpl(mockGrpcClient.Object, null); ListDebuggeesResponse response = client.ListDebuggees(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public async Task ListDebuggeesAsync2() { Mock<Debugger2.Debugger2Client> mockGrpcClient = new Mock<Debugger2.Debugger2Client>(MockBehavior.Strict); ListDebuggeesRequest request = new ListDebuggeesRequest { Project = "project-309310695", ClientVersion = "clientVersion-1506231196", }; ListDebuggeesResponse expectedResponse = new ListDebuggeesResponse(); mockGrpcClient.Setup(x => x.ListDebuggeesAsync(request, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<ListDebuggeesResponse>(Task.FromResult(expectedResponse), null, null, null, null)); Debugger2Client client = new Debugger2ClientImpl(mockGrpcClient.Object, null); ListDebuggeesResponse response = await client.ListDebuggeesAsync(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using WebApiAngularJsUploader.Areas.HelpPage.ModelDescriptions; using WebApiAngularJsUploader.Areas.HelpPage.Models; namespace WebApiAngularJsUploader.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
#region Copyright notice and license // Copyright 2015 gRPC authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.IO; using System.Reflection; using Grpc.Core.Logging; namespace Grpc.Core.Internal { /// <summary> /// Takes care of loading C# native extension and provides access to PInvoke calls the library exports. /// </summary> internal sealed class NativeExtension { static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<NativeExtension>(); static readonly object staticLock = new object(); static volatile NativeExtension instance; readonly NativeMethods nativeMethods; private NativeExtension() { this.nativeMethods = LoadNativeMethods(); // Redirect the native logs as the very first thing after loading the native extension // to make sure we don't lose any logs. NativeLogRedirector.Redirect(this.nativeMethods); DefaultSslRootsOverride.Override(this.nativeMethods); Logger.Debug("gRPC native library loaded successfully."); } /// <summary> /// Gets singleton instance of this class. /// The native extension is loaded when called for the first time. /// </summary> public static NativeExtension Get() { if (instance == null) { lock (staticLock) { if (instance == null) { instance = new NativeExtension(); } } } return instance; } /// <summary> /// Provides access to the exported native methods. /// </summary> public NativeMethods NativeMethods { get { return this.nativeMethods; } } /// <summary> /// Detects which configuration of native extension to load and load it. /// </summary> private static UnmanagedLibrary LoadUnmanagedLibrary() { // TODO: allow customizing path to native extension (possibly through exposing a GrpcEnvironment property). // See https://github.com/grpc/grpc/pull/7303 for one option. var assemblyDirectory = Path.GetDirectoryName(GetAssemblyPath()); // With "classic" VS projects, the native libraries get copied using a .targets rule to the build output folder // alongside the compiled assembly. // With dotnet cli projects targeting net45 framework, the native libraries (just the required ones) // are similarly copied to the built output folder, through the magic of Microsoft.NETCore.Platforms. var classicPath = Path.Combine(assemblyDirectory, GetNativeLibraryFilename()); // With dotnet cli project targeting netcoreappX.Y, projects will use Grpc.Core assembly directly in the location where it got restored // by nuget. We locate the native libraries based on known structure of Grpc.Core nuget package. // When "dotnet publish" is used, the runtimes directory is copied next to the published assemblies. string runtimesDirectory = string.Format("runtimes/{0}/native", GetPlatformString()); var netCorePublishedAppStylePath = Path.Combine(assemblyDirectory, runtimesDirectory, GetNativeLibraryFilename()); var netCoreAppStylePath = Path.Combine(assemblyDirectory, "../..", runtimesDirectory, GetNativeLibraryFilename()); // Look for the native library in all possible locations in given order. string[] paths = new[] { classicPath, netCorePublishedAppStylePath, netCoreAppStylePath}; return new UnmanagedLibrary(paths); } /// <summary> /// Loads native extension and return native methods delegates. /// </summary> private static NativeMethods LoadNativeMethods() { if (PlatformApis.IsUnity) { return LoadNativeMethodsUnity(); } if (PlatformApis.IsXamarin) { return LoadNativeMethodsXamarin(); } return new NativeMethods(LoadUnmanagedLibrary()); } /// <summary> /// Return native method delegates when running on Unity platform. /// Unity does not use standard NuGet packages and the native library is treated /// there as a "native plugin" which is (provided it has the right metadata) /// automatically made available to <c>[DllImport]</c> loading logic. /// WARNING: Unity support is experimental and work-in-progress. Don't expect it to work. /// </summary> private static NativeMethods LoadNativeMethodsUnity() { switch (PlatformApis.GetUnityRuntimePlatform()) { case "IPhonePlayer": return new NativeMethods(new NativeMethods.DllImportsFromStaticLib()); default: // most other platforms load unity plugins as a shared library return new NativeMethods(new NativeMethods.DllImportsFromSharedLib()); } } /// <summary> /// Return native method delegates when running on the Xamarin platform. /// WARNING: Xamarin support is experimental and work-in-progress. Don't expect it to work. /// </summary> private static NativeMethods LoadNativeMethodsXamarin() { if (PlatformApis.IsXamarinAndroid) { return new NativeMethods(new NativeMethods.DllImportsFromSharedLib()); } // not tested yet return new NativeMethods(new NativeMethods.DllImportsFromStaticLib()); } private static string GetAssemblyPath() { var assembly = typeof(NativeExtension).GetTypeInfo().Assembly; #if NETSTANDARD1_5 // Assembly.EscapedCodeBase does not exist under CoreCLR, but assemblies imported from a nuget package // don't seem to be shadowed by DNX-based projects at all. return assembly.Location; #else // If assembly is shadowed (e.g. in a webapp), EscapedCodeBase is pointing // to the original location of the assembly, and Location is pointing // to the shadow copy. We care about the original location because // the native dlls don't get shadowed. var escapedCodeBase = assembly.EscapedCodeBase; if (IsFileUri(escapedCodeBase)) { return new Uri(escapedCodeBase).LocalPath; } return assembly.Location; #endif } #if !NETSTANDARD1_5 private static bool IsFileUri(string uri) { return uri.ToLowerInvariant().StartsWith(Uri.UriSchemeFile); } #endif private static string GetPlatformString() { if (PlatformApis.IsWindows) { return "win"; } if (PlatformApis.IsLinux) { return "linux"; } if (PlatformApis.IsMacOSX) { return "osx"; } throw new InvalidOperationException("Unsupported platform."); } // Currently, only Intel platform is supported. private static string GetArchitectureString() { if (PlatformApis.Is64Bit) { return "x64"; } else { return "x86"; } } // platform specific file name of the extension library private static string GetNativeLibraryFilename() { string architecture = GetArchitectureString(); if (PlatformApis.IsWindows) { return string.Format("grpc_csharp_ext.{0}.dll", architecture); } if (PlatformApis.IsLinux) { return string.Format("libgrpc_csharp_ext.{0}.so", architecture); } if (PlatformApis.IsMacOSX) { return string.Format("libgrpc_csharp_ext.{0}.dylib", architecture); } throw new InvalidOperationException("Unsupported platform."); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace NuGet { public class LocalPackageRepository : PackageRepositoryBase, IPackageLookup { private Dictionary<string, PackageCacheEntry> _packageCache = new Dictionary<string, PackageCacheEntry>(StringComparer.OrdinalIgnoreCase); private Dictionary<PackageName, string> _packagePathLookup = new Dictionary<PackageName, string>(); private readonly bool _enableCaching; public LocalPackageRepository(string physicalPath) : this(physicalPath, enableCaching: true) { } public LocalPackageRepository(string physicalPath, bool enableCaching) : this(new DefaultPackagePathResolver(physicalPath), new PhysicalFileSystem(physicalPath), enableCaching) { } public LocalPackageRepository(IPackagePathResolver pathResolver, IFileSystem fileSystem) : this(pathResolver, fileSystem, enableCaching: true) { } public LocalPackageRepository(IPackagePathResolver pathResolver, IFileSystem fileSystem, bool enableCaching) { if (pathResolver == null) { throw new ArgumentNullException("pathResolver"); } if (fileSystem == null) { throw new ArgumentNullException("fileSystem"); } FileSystem = fileSystem; PathResolver = pathResolver; _enableCaching = enableCaching; } public override string Source { get { return FileSystem.Root; } } protected IFileSystem FileSystem { get; private set; } private IPackagePathResolver PathResolver { get; set; } public override IQueryable<IPackage> GetPackages() { return GetPackages(OpenPackage).AsSafeQueryable(); } public override void AddPackage(IPackage package) { string packageFilePath = GetPackageFilePath(package); FileSystem.AddFileWithCheck(packageFilePath, package.GetStream); } public override void RemovePackage(IPackage package) { // Delete the package file string packageFilePath = GetPackageFilePath(package); FileSystem.DeleteFileSafe(packageFilePath); // Delete the package directory if any FileSystem.DeleteDirectorySafe(PathResolver.GetPackageDirectory(package), recursive: false); // If this is the last package delete the package directory if (!FileSystem.GetFilesSafe(String.Empty).Any() && !FileSystem.GetDirectoriesSafe(String.Empty).Any()) { FileSystem.DeleteDirectorySafe(String.Empty, recursive: false); } } public IPackage FindPackage(string packageId, Version version) { var packageName = new PackageName(packageId, version); string path; if (!_packagePathLookup.TryGetValue(packageName, out path)) { // Try to find the path based on id and version path = GetPackageFilePath(packageName.PackageId, packageName.Version); // If this path doesn't exist try the other one if (!FileSystem.FileExists(path)) { path = PathResolver.GetPackageFileName(packageId, version); } } if (!FileSystem.FileExists(path)) { return null; } // Get the package at this path return GetPackage(path); } internal IEnumerable<IPackage> GetPackages(Func<string, IPackage> openPackage) { foreach (var path in GetPackageFiles()) { IPackage package = GetPackage(openPackage, path); yield return package; } } private IPackage GetPackage(string path) { return GetPackage(OpenPackage, path); } private IPackage GetPackage(Func<string, IPackage> openPackage, string path) { PackageCacheEntry cacheEntry; DateTimeOffset lastModified = FileSystem.GetLastModified(path); // If we never cached this file or we did and it's current last modified time is newer // create a new entry if (!_packageCache.TryGetValue(path, out cacheEntry) || (cacheEntry != null && lastModified > cacheEntry.LastModifiedTime)) { // We need to do this so we capture the correct loop variable string packagePath = path; // Create the package IPackage package = openPackage(packagePath); // create a cache entry with the last modified time cacheEntry = new PackageCacheEntry(package, lastModified); if (_enableCaching) { // Store the entry _packageCache[packagePath] = cacheEntry; _packagePathLookup[new PackageName(package.Id, package.Version)] = path; } } return cacheEntry.Package; } internal IEnumerable<string> GetPackageFiles() { // Check for package files one level deep. We use this at package install time // to determine the set of installed packages. Installed packages are copied to // {id}.{version}\{packagefile}.{extension}. foreach (var dir in FileSystem.GetDirectories(String.Empty)) { foreach (var path in FileSystem.GetFiles(dir, "*" + Constants.PackageExtension)) { yield return path; } } // Check top level directory foreach (var path in FileSystem.GetFiles(String.Empty, "*" + Constants.PackageExtension)) { yield return path; } } protected virtual IPackage OpenPackage(string path) { return new ZipPackage(() => FileSystem.OpenFile(path)); } protected virtual string GetPackageFilePath(IPackage package) { return Path.Combine(PathResolver.GetPackageDirectory(package), PathResolver.GetPackageFileName(package)); } protected virtual string GetPackageFilePath(string id, Version version) { return Path.Combine(PathResolver.GetPackageDirectory(id, version), PathResolver.GetPackageFileName(id, version)); } private class PackageCacheEntry { public PackageCacheEntry(IPackage package, DateTimeOffset lastModifiedTime) { Package = package; LastModifiedTime = lastModifiedTime; } public IPackage Package { get; private set; } public DateTimeOffset LastModifiedTime { get; private set; } } private class PackageName : IEquatable<PackageName> { public PackageName(string packageId, Version version) { PackageId = packageId; Version = version; } public string PackageId { get; private set; } public Version Version { get; private set; } public bool Equals(PackageName other) { return PackageId.Equals(other.PackageId, StringComparison.OrdinalIgnoreCase) && Version.Equals(other.Version); } public override int GetHashCode() { var combiner = new HashCodeCombiner(); combiner.AddObject(PackageId); combiner.AddObject(Version); return combiner.CombinedHash; } public override string ToString() { return PackageId + " " + Version; } } } }
// // Template.cs // // Author: // Michael Hutchinson <mhutchinson@novell.com> // // Copyright (c) 2009 Novell, Inc. (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.IO; using Microsoft.VisualStudio.TextTemplating; namespace Mono.TextTemplating { public class ParsedTemplate { List<ISegment> segments = new List<ISegment> (); CompilerErrorCollection errors = new CompilerErrorCollection (); string rootFileName; public ParsedTemplate (string rootFileName) { this.rootFileName = rootFileName; } public List<ISegment> RawSegments { get { return segments; } } public IEnumerable<Directive> Directives { get { foreach (ISegment seg in segments) { Directive dir = seg as Directive; if (dir != null) yield return dir; } } } public IEnumerable<TemplateSegment> Content { get { foreach (ISegment seg in segments) { TemplateSegment ts = seg as TemplateSegment; if (ts != null) yield return ts; } } } public CompilerErrorCollection Errors { get { return errors; } } public static ParsedTemplate FromText (string content, ITextTemplatingEngineHost host) { ParsedTemplate template = new ParsedTemplate (host.TemplateFile); try { template.Parse (host, new Tokeniser (host.TemplateFile, content)); } catch (ParserException ex) { template.LogError (ex.Message, ex.Location); } return template; } public void Parse (ITextTemplatingEngineHost host, Tokeniser tokeniser) { Parse (host, tokeniser, true); } public void ParseWithoutIncludes (Tokeniser tokeniser) { Parse (null, tokeniser, false); } void Parse (ITextTemplatingEngineHost host, Tokeniser tokeniser, bool parseIncludes) { bool skip = false; while ((skip || tokeniser.Advance ()) && tokeniser.State != State.EOF) { skip = false; ISegment seg = null; switch (tokeniser.State) { case State.Block: if (!String.IsNullOrEmpty (tokeniser.Value)) seg = new TemplateSegment (SegmentType.Block, tokeniser.Value, tokeniser.Location); break; case State.Content: if (!String.IsNullOrEmpty (tokeniser.Value)) seg = new TemplateSegment (SegmentType.Content, tokeniser.Value, tokeniser.Location); break; case State.Expression: if (!String.IsNullOrEmpty (tokeniser.Value)) seg = new TemplateSegment (SegmentType.Expression, tokeniser.Value, tokeniser.Location); break; case State.Helper: if (!String.IsNullOrEmpty (tokeniser.Value)) seg = new TemplateSegment (SegmentType.Helper, tokeniser.Value, tokeniser.Location); break; case State.Directive: Directive directive = null; string attName = null; while (!skip && tokeniser.Advance ()) { switch (tokeniser.State) { case State.DirectiveName: if (directive == null) { directive = new Directive (tokeniser.Value.ToLower (), tokeniser.Location); directive.TagStartLocation = tokeniser.TagStartLocation; if (!parseIncludes || directive.Name != "include") segments.Add (directive); } else attName = tokeniser.Value; break; case State.DirectiveValue: if (attName != null && directive != null) directive.Attributes[attName.ToLower ()] = tokeniser.Value; else LogError ("Directive value without name", tokeniser.Location); attName = null; break; case State.Directive: if (directive != null) directive.EndLocation = tokeniser.TagEndLocation; break; default: skip = true; break; } } if (parseIncludes && directive.Name == "include") Import (host, directive); break; default: throw new InvalidOperationException (); } if (seg != null) { seg.TagStartLocation = tokeniser.TagStartLocation; seg.EndLocation = tokeniser.TagEndLocation; segments.Add (seg); } } } void Import (ITextTemplatingEngineHost host, Directive includeDirective) { string fileName; if (includeDirective.Attributes.Count > 1 || !includeDirective.Attributes.TryGetValue ("file", out fileName)) { LogError ("Unexpected attributes in include directive", includeDirective.StartLocation); return; } string content, resolvedName; if (host.LoadIncludeText (fileName, out content, out resolvedName)) Parse (host, new Tokeniser (resolvedName, content), true); else LogError ("Could not resolve include file '" + fileName + "'.", includeDirective.StartLocation); } void LogError (string message, Location location, bool isWarning) { CompilerError err = new CompilerError (); err.ErrorText = message; if (location.FileName != null) { err.Line = location.Line; err.Column = location.Column; err.FileName = location.FileName ?? string.Empty; } else { err.FileName = rootFileName ?? string.Empty; } err.IsWarning = isWarning; errors.Add (err); } public void LogError (string message) { LogError (message, Location.Empty, false); } public void LogWarning (string message) { LogError (message, Location.Empty, true); } public void LogError (string message, Location location) { LogError (message, location, false); } public void LogWarning (string message, Location location) { LogError (message, location, true); } } public interface ISegment { Location StartLocation { get; } Location EndLocation { get; set; } Location TagStartLocation {get; set; } } public class TemplateSegment : ISegment { public TemplateSegment (SegmentType type, string text, Location start) { this.Type = type; this.StartLocation = start; this.Text = text; } public SegmentType Type { get; private set; } public string Text { get; private set; } public Location TagStartLocation { get; set; } public Location StartLocation { get; private set; } public Location EndLocation { get; set; } } public class Directive : ISegment { public Directive (string name, Location start) { this.Name = name; this.Attributes = new Dictionary<string, string> (); this.StartLocation = start; } public string Name { get; private set; } public Dictionary<string,string> Attributes { get; private set; } public Location TagStartLocation { get; set; } public Location StartLocation { get; private set; } public Location EndLocation { get; set; } public string Extract (string key) { string value; if (!Attributes.TryGetValue (key, out value)) return null; Attributes.Remove (key); return value; } } public enum SegmentType { Block, Expression, Content, Helper } public struct Location : IEquatable<Location> { public Location (string fileName, int line, int column) : this() { FileName = fileName; Column = column; Line = line; } public int Line { get; private set; } public int Column { get; private set; } public string FileName { get; private set; } public static Location Empty { get { return new Location (null, -1, -1); } } public Location AddLine () { return new Location (this.FileName, this.Line + 1, 1); } public Location AddCol () { return AddCols (1); } public Location AddCols (int number) { return new Location (this.FileName, this.Line, this.Column + number); } public override string ToString () { return string.Format("[{0} ({1},{2})]", FileName, Line, Column); } public bool Equals (Location other) { return other.Line == Line && other.Column == Column && other.FileName == FileName; } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Net; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Connections; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.ClientObservers; using Orleans.Configuration; namespace Orleans.Runtime.Messaging { internal class Gateway : IConnectedClientCollection { private readonly GatewayClientCleanupAgent clientCleanupAgent; // clients is the main authorative collection of all connected clients. // Any client currently in the system appears in this collection. // In addition, we use clientConnections collection for fast retrival of ClientState. // Anything that appears in those 2 collections should also appear in the main clients collection. private readonly ConcurrentDictionary<ClientGrainId, ClientState> clients = new(); private readonly Dictionary<GatewayInboundConnection, ClientState> clientConnections = new(); private readonly SiloAddress gatewayAddress; private readonly GatewaySender sender; private readonly ClientsReplyRoutingCache clientsReplyRoutingCache; private readonly ILogger logger; private readonly ILoggerFactory loggerFactory; private readonly SiloMessagingOptions messagingOptions; private long clientsCollectionVersion = 0; public Gateway( MessageCenter msgCtr, ILocalSiloDetails siloDetails, MessageFactory messageFactory, ILoggerFactory loggerFactory, IOptions<SiloMessagingOptions> options) { this.messagingOptions = options.Value; this.loggerFactory = loggerFactory; this.logger = this.loggerFactory.CreateLogger<Gateway>(); clientCleanupAgent = new GatewayClientCleanupAgent(this, loggerFactory, messagingOptions.ClientDropTimeout); clientsReplyRoutingCache = new ClientsReplyRoutingCache(messagingOptions.ResponseTimeout); this.gatewayAddress = siloDetails.GatewayAddress; this.sender = new GatewaySender(this, msgCtr, messageFactory, loggerFactory.CreateLogger<GatewaySender>()); } public static ActivationAddress GetClientActivationAddress(GrainId clientId, SiloAddress siloAddress) { // Need to pick a unique deterministic ActivationId for this client. // We store it in the grain directory and there for every GrainId we use ActivationId as a key // so every GW needs to behave as a different "activation" with a different ActivationId (its not enough that they have different SiloAddress) string stringToHash = clientId.ToString() + siloAddress.Endpoint + siloAddress.Generation.ToString(System.Globalization.CultureInfo.InvariantCulture); Guid hash = Utils.CalculateGuidHash(stringToHash); var activationId = ActivationId.GetActivationId(hash); return ActivationAddress.GetAddress(siloAddress, clientId, activationId); } internal void Start() { clientCleanupAgent.Start(); } internal async Task SendStopSendMessages(IInternalGrainFactory grainFactory) { lock (clients) { foreach (var client in clients) { if (client.Value.IsConnected) { var observer = ClientGatewayObserver.GetObserver(grainFactory, client.Key); observer.StopSendingToGateway(this.gatewayAddress); } } } await Task.Delay(this.messagingOptions.ClientGatewayShutdownNotificationTimeout); } internal void Stop() { clientCleanupAgent.Stop(); } long IConnectedClientCollection.Version => Interlocked.Read(ref clientsCollectionVersion); List<GrainId> IConnectedClientCollection.GetConnectedClientIds() { var result = new List<GrainId>(); foreach (var pair in clients) { result.Add(pair.Key.GrainId); } return result; } internal void RecordOpenedConnection(GatewayInboundConnection connection, ClientGrainId clientId) { logger.LogInformation((int)ErrorCode.GatewayClientOpenedSocket, "Recorded opened connection from endpoint {EndPoint}, client ID {ClientId}.", connection.RemoteEndPoint, clientId); lock (clients) { if (clients.TryGetValue(clientId, out var clientState)) { var oldSocket = clientState.Connection; if (oldSocket != null) { // The old socket will be closed by itself later. clientConnections.Remove(oldSocket); } } else { clientState = new ClientState(clientId, messagingOptions.ClientDropTimeout); clients[clientId] = clientState; MessagingStatisticsGroup.ConnectedClientCount.Increment(); } clientState.RecordConnection(connection); clientConnections[connection] = clientState; clientsCollectionVersion++; } } internal void RecordClosedConnection(GatewayInboundConnection connection) { if (connection == null) return; ClientState clientState; lock (clients) { if (!clientConnections.Remove(connection, out clientState)) return; clientState.RecordDisconnection(); clientsCollectionVersion++; } logger.LogInformation( (int)ErrorCode.GatewayClientClosedSocket, "Recorded closed socket from endpoint {Endpoint}, client ID {clientId}.", connection.RemoteEndPoint?.ToString() ?? "null", clientState.Id); } internal SiloAddress TryToReroute(Message msg) { // ** Special routing rule for system target here ** // When a client make a request/response to/from a SystemTarget, the TargetSilo can be set to either // - the GatewayAddress of the target silo (for example, when the client want get the cluster typemap) // - the "internal" Silo-to-Silo address, if the client want to send a message to a specific SystemTarget // activation that is on a silo on which there is no gateway available (or if the client is not // connected to that gateway) // So, if the TargetGrain is a SystemTarget we always trust the value from Message.TargetSilo and forward // it to this address... // EXCEPT if the value is equal to the current GatewayAdress: in this case we will return // null and the local dispatcher will forward the Message to a local SystemTarget activation if (msg.TargetGrain.IsSystemTarget() && !IsTargetingLocalGateway(msg.TargetSilo)) return msg.TargetSilo; // for responses from ClientAddressableObject to ClientGrain try to use clientsReplyRoutingCache for sending replies directly back. if (!msg.SendingGrain.IsClient() || !msg.TargetGrain.IsClient()) return null; if (msg.Direction != Message.Directions.Response) return null; SiloAddress gateway; return clientsReplyRoutingCache.TryFindClientRoute(msg.TargetGrain, out gateway) ? gateway : null; } internal void DropExpiredRoutingCachedEntries() { lock (clients) { clientsReplyRoutingCache.DropExpiredEntries(); } } private bool IsTargetingLocalGateway(SiloAddress siloAddress) { // Special case if the address used by the client was loopback return this.gatewayAddress.Matches(siloAddress) || (IPAddress.IsLoopback(siloAddress.Endpoint.Address) && siloAddress.Endpoint.Port == this.gatewayAddress.Endpoint.Port && siloAddress.Generation == this.gatewayAddress.Generation); } // There is NO need to acquire individual ClientState lock, since we only close an older socket. internal void DropDisconnectedClients() { foreach (var kv in clients) { if (kv.Value.ReadyToDrop()) { lock (clients) { if (clients.TryGetValue(kv.Key, out var client) && client.ReadyToDrop()) { if (logger.IsEnabled(LogLevel.Information)) { logger.LogInformation( (int)ErrorCode.GatewayDroppingClient, "Dropping client {ClientId}, {IdleDuration} after disconnect with no reconnect", kv.Key, DateTime.UtcNow.Subtract(client.DisconnectedSince)); } clients.TryRemove(kv.Key, out _); clientsCollectionVersion++; MessagingStatisticsGroup.ConnectedClientCount.DecrementBy(1); } } } } } /// <summary> /// See if this message is intended for a grain we're proxying, and queue it for delivery if so. /// </summary> /// <param name="msg"></param> /// <returns>true if the message should be delivered to a proxied grain, false if not.</returns> internal bool TryDeliverToProxy(Message msg) { // See if it's a grain we're proxying. var targetGrain = msg.TargetGrain; if (!ClientGrainId.TryParse(targetGrain, out var clientId)) { return false; } if (!clients.TryGetValue(clientId, out var client)) { return false; } // when this Gateway receives a message from client X to client addressale object Y // it needs to record the original Gateway address through which this message came from (the address of the Gateway that X is connected to) // it will use this Gateway to re-route the REPLY from Y back to X. if (msg.SendingGrain.IsClient()) { clientsReplyRoutingCache.RecordClientRoute(msg.SendingGrain, msg.SendingSilo); } msg.TargetSilo = null; // Override the SendingSilo only if the sending grain is not // a system target if (!msg.SendingGrain.IsSystemTarget()) { msg.SendingSilo = gatewayAddress; } QueueRequest(client, msg); return true; } private void QueueRequest(ClientState clientState, Message msg) => this.sender.Send(clientState, msg); private class ClientState { private readonly TimeSpan clientDropTimeout; internal Queue<Message> PendingToSend { get; } = new(); internal GatewayInboundConnection Connection { get; private set; } internal DateTime DisconnectedSince { get; private set; } internal ClientGrainId Id { get; } public bool IsConnected => this.Connection != null; internal ClientState(ClientGrainId id, TimeSpan clientDropTimeout) { Id = id; this.clientDropTimeout = clientDropTimeout; } internal void RecordDisconnection() { if (Connection == null) return; DisconnectedSince = DateTime.UtcNow; Connection = null; } internal void RecordConnection(GatewayInboundConnection connection) { Connection = connection; DisconnectedSince = DateTime.MaxValue; } internal bool ReadyToDrop() { return !IsConnected && (DateTime.UtcNow.Subtract(DisconnectedSince) >= clientDropTimeout); } } private class GatewayClientCleanupAgent : TaskSchedulerAgent { private readonly Gateway gateway; private readonly TimeSpan clientDropTimeout; internal GatewayClientCleanupAgent(Gateway gateway, ILoggerFactory loggerFactory, TimeSpan clientDropTimeout) : base(loggerFactory) { this.gateway = gateway; this.clientDropTimeout = clientDropTimeout; } protected override async Task Run() { while (!Cts.IsCancellationRequested) { gateway.DropDisconnectedClients(); gateway.DropExpiredRoutingCachedEntries(); await Task.Delay(clientDropTimeout); } } } // this cache is used to record the addresses of Gateways from which clients connected to. // it is used to route replies to clients from client addressable objects // without this cache this Gateway will not know how to route the reply back to the client // (since clients are not registered in the directory and this Gateway may not be proxying for the client for whom the reply is destined). private class ClientsReplyRoutingCache { // for every client: the Gateway to use to route repies back to it plus the last time that client connected via this Gateway. private readonly ConcurrentDictionary<GrainId, Tuple<SiloAddress, DateTime>> clientRoutes = new(); private readonly TimeSpan TIME_BEFORE_ROUTE_CACHED_ENTRY_EXPIRES; internal ClientsReplyRoutingCache(TimeSpan responseTimeout) { TIME_BEFORE_ROUTE_CACHED_ENTRY_EXPIRES = responseTimeout.Multiply(5); } internal void RecordClientRoute(GrainId client, SiloAddress gateway) { clientRoutes[client] = new(gateway, DateTime.UtcNow); } internal bool TryFindClientRoute(GrainId client, out SiloAddress gateway) { if (clientRoutes.TryGetValue(client, out var tuple)) { gateway = tuple.Item1; return true; } gateway = null; return false; } internal void DropExpiredEntries() { var expiredTime = DateTime.UtcNow - TIME_BEFORE_ROUTE_CACHED_ENTRY_EXPIRES; foreach (var client in clientRoutes) { if (client.Value.Item2 < expiredTime) { clientRoutes.TryRemove(client.Key, out _); } } } } private sealed class GatewaySender { private readonly Gateway gateway; private readonly MessageCenter messageCenter; private readonly MessageFactory messageFactory; private readonly ILogger<GatewaySender> log; private readonly CounterStatistic gatewaySends; internal GatewaySender(Gateway gateway, MessageCenter messageCenter, MessageFactory messageFactory, ILogger<GatewaySender> log) { this.gateway = gateway; this.messageCenter = messageCenter; this.messageFactory = messageFactory; this.log = log; this.gatewaySends = CounterStatistic.FindOrCreate(StatisticNames.GATEWAY_SENT); } public void Send(ClientState clientState, Message msg) { // This should never happen -- but make sure to handle it reasonably, just in case if (clientState == null) { if (msg == null) return; this.log.Info(ErrorCode.GatewayTryingToSendToUnrecognizedClient, "Trying to send a message {0} to an unrecognized client {1}", msg.ToString(), msg.TargetGrain); MessagingStatisticsGroup.OnFailedSentMessage(msg); // Message for unrecognized client -- reject it if (msg.Direction == Message.Directions.Request) { MessagingStatisticsGroup.OnRejectedMessage(msg); Message error = this.messageFactory.CreateRejectionResponse( msg, Message.RejectionTypes.Unrecoverable, "Unknown client " + msg.TargetGrain); messageCenter.SendMessage(error); } else { MessagingStatisticsGroup.OnDroppedSentMessage(msg); } return; } lock (clientState.PendingToSend) { // if disconnected - queue for later. if (!clientState.IsConnected) { if (msg == null) return; if (this.log.IsEnabled(LogLevel.Trace)) this.log.Trace("Queued message {0} for client {1}", msg, msg.TargetGrain); clientState.PendingToSend.Enqueue(msg); return; } // if the queue is non empty - drain it first. if (clientState.PendingToSend.Count > 0) { if (msg != null) clientState.PendingToSend.Enqueue(msg); // For now, drain in-line, although in the future this should happen in yet another asynch agent Drain(clientState); return; } // the queue was empty AND we are connected. // If the request includes a message to send, send it (or enqueue it for later) if (msg == null) return; if (!Send(msg, clientState)) { if (this.log.IsEnabled(LogLevel.Trace)) this.log.Trace("Queued message {0} for client {1}", msg, msg.TargetGrain); clientState.PendingToSend.Enqueue(msg); } else { if (this.log.IsEnabled(LogLevel.Trace)) this.log.Trace("Sent message {0} to client {1}", msg, msg.TargetGrain); } } } private void Drain(ClientState clientState) { lock (clientState.PendingToSend) { while (clientState.PendingToSend.Count > 0) { var m = clientState.PendingToSend.Peek(); if (Send(m, clientState)) { if (this.log.IsEnabled(LogLevel.Trace)) this.log.Trace("Sent queued message {0} to client {1}", m, clientState.Id); clientState.PendingToSend.Dequeue(); } else { return; } } } } private bool Send(Message msg, ClientState client) { var connection = client.Connection; if (connection is null) return false; try { connection.Send(msg); gatewaySends.Increment(); return true; } catch (Exception exception) { gateway.RecordClosedConnection(connection); connection.CloseAsync(new ConnectionAbortedException("Exception posting a message to sender. See InnerException for details.", exception)).Ignore(); return false; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Text; public class BringUpTest { const int Pass = 100; const int Fail = -1; public static int Main() { if (TestInterfaceCache() == Fail) return Fail; if (TestMultipleInterfaces() == Fail) return Fail; if (TestArrayInterfaces() == Fail) return Fail; return Pass; } #region Interface Dispatch Cache Test private static int TestInterfaceCache() { MyInterface[] itfs = new MyInterface[50]; itfs[0] = new Foo0(); itfs[1] = new Foo1(); itfs[2] = new Foo2(); itfs[3] = new Foo3(); itfs[4] = new Foo4(); itfs[5] = new Foo5(); itfs[6] = new Foo6(); itfs[7] = new Foo7(); itfs[8] = new Foo8(); itfs[9] = new Foo9(); itfs[10] = new Foo10(); itfs[11] = new Foo11(); itfs[12] = new Foo12(); itfs[13] = new Foo13(); itfs[14] = new Foo14(); itfs[15] = new Foo15(); itfs[16] = new Foo16(); itfs[17] = new Foo17(); itfs[18] = new Foo18(); itfs[19] = new Foo19(); itfs[20] = new Foo20(); itfs[21] = new Foo21(); itfs[22] = new Foo22(); itfs[23] = new Foo23(); itfs[24] = new Foo24(); itfs[25] = new Foo25(); itfs[26] = new Foo26(); itfs[27] = new Foo27(); itfs[28] = new Foo28(); itfs[29] = new Foo29(); itfs[30] = new Foo30(); itfs[31] = new Foo31(); itfs[32] = new Foo32(); itfs[33] = new Foo33(); itfs[34] = new Foo34(); itfs[35] = new Foo35(); itfs[36] = new Foo36(); itfs[37] = new Foo37(); itfs[38] = new Foo38(); itfs[39] = new Foo39(); itfs[40] = new Foo40(); itfs[41] = new Foo41(); itfs[42] = new Foo42(); itfs[43] = new Foo43(); itfs[44] = new Foo44(); itfs[45] = new Foo45(); itfs[46] = new Foo46(); itfs[47] = new Foo47(); itfs[48] = new Foo48(); itfs[49] = new Foo49(); StringBuilder sb = new StringBuilder(); int counter = 0; for (int i = 0; i < 50; i++) { sb.Append(itfs[i].GetAString()); counter += itfs[i].GetAnInt(); } string expected = "Foo0Foo1Foo2Foo3Foo4Foo5Foo6Foo7Foo8Foo9Foo10Foo11Foo12Foo13Foo14Foo15Foo16Foo17Foo18Foo19Foo20Foo21Foo22Foo23Foo24Foo25Foo26Foo27Foo28Foo29Foo30Foo31Foo32Foo33Foo34Foo35Foo36Foo37Foo38Foo39Foo40Foo41Foo42Foo43Foo44Foo45Foo46Foo47Foo48Foo49"; if (!expected.Equals(sb.ToString())) { Console.WriteLine("Concatenating strings from interface calls failed."); Console.Write("Expected: "); Console.WriteLine(expected); Console.Write(" Actual: "); Console.WriteLine(sb.ToString()); return Fail; } if (counter != 1225) { Console.WriteLine("Summing ints from interface calls failed."); Console.WriteLine("Expected: 1225"); Console.Write("Actual: "); Console.WriteLine(counter); return Fail; } return 100; } interface MyInterface { int GetAnInt(); string GetAString(); } class Foo0 : MyInterface { public int GetAnInt() { return 0; } public string GetAString() { return "Foo0"; } } class Foo1 : MyInterface { public int GetAnInt() { return 1; } public string GetAString() { return "Foo1"; } } class Foo2 : MyInterface { public int GetAnInt() { return 2; } public string GetAString() { return "Foo2"; } } class Foo3 : MyInterface { public int GetAnInt() { return 3; } public string GetAString() { return "Foo3"; } } class Foo4 : MyInterface { public int GetAnInt() { return 4; } public string GetAString() { return "Foo4"; } } class Foo5 : MyInterface { public int GetAnInt() { return 5; } public string GetAString() { return "Foo5"; } } class Foo6 : MyInterface { public int GetAnInt() { return 6; } public string GetAString() { return "Foo6"; } } class Foo7 : MyInterface { public int GetAnInt() { return 7; } public string GetAString() { return "Foo7"; } } class Foo8 : MyInterface { public int GetAnInt() { return 8; } public string GetAString() { return "Foo8"; } } class Foo9 : MyInterface { public int GetAnInt() { return 9; } public string GetAString() { return "Foo9"; } } class Foo10 : MyInterface { public int GetAnInt() { return 10; } public string GetAString() { return "Foo10"; } } class Foo11 : MyInterface { public int GetAnInt() { return 11; } public string GetAString() { return "Foo11"; } } class Foo12 : MyInterface { public int GetAnInt() { return 12; } public string GetAString() { return "Foo12"; } } class Foo13 : MyInterface { public int GetAnInt() { return 13; } public string GetAString() { return "Foo13"; } } class Foo14 : MyInterface { public int GetAnInt() { return 14; } public string GetAString() { return "Foo14"; } } class Foo15 : MyInterface { public int GetAnInt() { return 15; } public string GetAString() { return "Foo15"; } } class Foo16 : MyInterface { public int GetAnInt() { return 16; } public string GetAString() { return "Foo16"; } } class Foo17 : MyInterface { public int GetAnInt() { return 17; } public string GetAString() { return "Foo17"; } } class Foo18 : MyInterface { public int GetAnInt() { return 18; } public string GetAString() { return "Foo18"; } } class Foo19 : MyInterface { public int GetAnInt() { return 19; } public string GetAString() { return "Foo19"; } } class Foo20 : MyInterface { public int GetAnInt() { return 20; } public string GetAString() { return "Foo20"; } } class Foo21 : MyInterface { public int GetAnInt() { return 21; } public string GetAString() { return "Foo21"; } } class Foo22 : MyInterface { public int GetAnInt() { return 22; } public string GetAString() { return "Foo22"; } } class Foo23 : MyInterface { public int GetAnInt() { return 23; } public string GetAString() { return "Foo23"; } } class Foo24 : MyInterface { public int GetAnInt() { return 24; } public string GetAString() { return "Foo24"; } } class Foo25 : MyInterface { public int GetAnInt() { return 25; } public string GetAString() { return "Foo25"; } } class Foo26 : MyInterface { public int GetAnInt() { return 26; } public string GetAString() { return "Foo26"; } } class Foo27 : MyInterface { public int GetAnInt() { return 27; } public string GetAString() { return "Foo27"; } } class Foo28 : MyInterface { public int GetAnInt() { return 28; } public string GetAString() { return "Foo28"; } } class Foo29 : MyInterface { public int GetAnInt() { return 29; } public string GetAString() { return "Foo29"; } } class Foo30 : MyInterface { public int GetAnInt() { return 30; } public string GetAString() { return "Foo30"; } } class Foo31 : MyInterface { public int GetAnInt() { return 31; } public string GetAString() { return "Foo31"; } } class Foo32 : MyInterface { public int GetAnInt() { return 32; } public string GetAString() { return "Foo32"; } } class Foo33 : MyInterface { public int GetAnInt() { return 33; } public string GetAString() { return "Foo33"; } } class Foo34 : MyInterface { public int GetAnInt() { return 34; } public string GetAString() { return "Foo34"; } } class Foo35 : MyInterface { public int GetAnInt() { return 35; } public string GetAString() { return "Foo35"; } } class Foo36 : MyInterface { public int GetAnInt() { return 36; } public string GetAString() { return "Foo36"; } } class Foo37 : MyInterface { public int GetAnInt() { return 37; } public string GetAString() { return "Foo37"; } } class Foo38 : MyInterface { public int GetAnInt() { return 38; } public string GetAString() { return "Foo38"; } } class Foo39 : MyInterface { public int GetAnInt() { return 39; } public string GetAString() { return "Foo39"; } } class Foo40 : MyInterface { public int GetAnInt() { return 40; } public string GetAString() { return "Foo40"; } } class Foo41 : MyInterface { public int GetAnInt() { return 41; } public string GetAString() { return "Foo41"; } } class Foo42 : MyInterface { public int GetAnInt() { return 42; } public string GetAString() { return "Foo42"; } } class Foo43 : MyInterface { public int GetAnInt() { return 43; } public string GetAString() { return "Foo43"; } } class Foo44 : MyInterface { public int GetAnInt() { return 44; } public string GetAString() { return "Foo44"; } } class Foo45 : MyInterface { public int GetAnInt() { return 45; } public string GetAString() { return "Foo45"; } } class Foo46 : MyInterface { public int GetAnInt() { return 46; } public string GetAString() { return "Foo46"; } } class Foo47 : MyInterface { public int GetAnInt() { return 47; } public string GetAString() { return "Foo47"; } } class Foo48 : MyInterface { public int GetAnInt() { return 48; } public string GetAString() { return "Foo48"; } } class Foo49 : MyInterface { public int GetAnInt() { return 49; } public string GetAString() { return "Foo49"; } } #endregion #region Implicit Interface Test private static int TestMultipleInterfaces() { TestClass<int> testInt = new TestClass<int>(5); MyInterface myInterface = testInt as MyInterface; if (!myInterface.GetAString().Equals("TestClass")) { Console.Write("On type TestClass, MyInterface.GetAString() returned "); Console.Write(myInterface.GetAString()); Console.WriteLine(" Expected: TestClass"); return Fail; } if (myInterface.GetAnInt() != 1) { Console.Write("On type TestClass, MyInterface.GetAnInt() returned "); Console.Write(myInterface.GetAnInt()); Console.WriteLine(" Expected: 1"); return Fail; } Interface<int> itf = testInt as Interface<int>; if (itf.GetT() != 5) { Console.Write("On type TestClass, Interface<int>::GetT() returned "); Console.Write(itf.GetT()); Console.WriteLine(" Expected: 5"); return Fail; } return Pass; } interface Interface<T> { T GetT(); } class TestClass<T> : MyInterface, Interface<T> { T _t; public TestClass(T t) { _t = t; } public T GetT() { return _t; } public int GetAnInt() { return 1; } public string GetAString() { return "TestClass"; } } #endregion #region Array Interfaces Test private static int TestArrayInterfaces() { { object stringArray = new string[] { "A", "B", "C", "D" }; Console.WriteLine("Testing IEnumerable<T> on array..."); string result = String.Empty; foreach (var s in (System.Collections.Generic.IEnumerable<string>)stringArray) result += s; if (result != "ABCD") { Console.WriteLine("Failed."); return Fail; } } { object stringArray = new string[] { "A", "B", "C", "D" }; Console.WriteLine("Testing IEnumerable on array..."); string result = String.Empty; foreach (var s in (System.Collections.IEnumerable)stringArray) result += s; if (result != "ABCD") { Console.WriteLine("Failed."); return Fail; } } { object intArray = new int[5, 5]; Console.WriteLine("Testing IList on MDArray..."); if (((System.Collections.IList)intArray).Count != 25) { Console.WriteLine("Failed."); return Fail; } } return Pass; } #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 Microsoft.Xml.Schema { using System; using Microsoft.Xml; using System.Collections; using System.ComponentModel; using Microsoft.Xml.Serialization; /// <include file='doc\XmlSchemaComplexType.uex' path='docs/doc[@for="XmlSchemaComplexType"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public class XmlSchemaComplexType : XmlSchemaType { private XmlSchemaDerivationMethod _block = XmlSchemaDerivationMethod.None; private XmlSchemaContentModel _contentModel; private XmlSchemaParticle _particle; private XmlSchemaObjectCollection _attributes; private XmlSchemaAnyAttribute _anyAttribute; private XmlSchemaParticle _contentTypeParticle = XmlSchemaParticle.Empty; private XmlSchemaDerivationMethod _blockResolved; private XmlSchemaObjectTable _localElements; private XmlSchemaObjectTable _attributeUses; private XmlSchemaAnyAttribute _attributeWildcard; private static XmlSchemaComplexType s_anyTypeLax; private static XmlSchemaComplexType s_anyTypeSkip; private static XmlSchemaComplexType s_untypedAnyType; //additional info for Partial validation private byte _pvFlags; private const byte wildCardMask = 0x01; private const byte isMixedMask = 0x02; private const byte isAbstractMask = 0x04; //const byte dupDeclMask = 0x08; static XmlSchemaComplexType() { s_anyTypeLax = CreateAnyType(XmlSchemaContentProcessing.Lax); s_anyTypeSkip = CreateAnyType(XmlSchemaContentProcessing.Skip); // Create xdt:untypedAny s_untypedAnyType = new XmlSchemaComplexType(); s_untypedAnyType.SetQualifiedName(new XmlQualifiedName("untypedAny", XmlReservedNs.NsXQueryDataType)); s_untypedAnyType.IsMixed = true; s_untypedAnyType.SetContentTypeParticle(s_anyTypeLax.ContentTypeParticle); s_untypedAnyType.SetContentType(XmlSchemaContentType.Mixed); s_untypedAnyType.ElementDecl = SchemaElementDecl.CreateAnyTypeElementDecl(); s_untypedAnyType.ElementDecl.SchemaType = s_untypedAnyType; s_untypedAnyType.ElementDecl.ContentValidator = AnyTypeContentValidator; } private static XmlSchemaComplexType CreateAnyType(XmlSchemaContentProcessing processContents) { XmlSchemaComplexType localAnyType = new XmlSchemaComplexType(); localAnyType.SetQualifiedName(DatatypeImplementation.QnAnyType); XmlSchemaAny anyElement = new XmlSchemaAny(); anyElement.MinOccurs = decimal.Zero; anyElement.MaxOccurs = decimal.MaxValue; anyElement.ProcessContents = processContents; anyElement.BuildNamespaceList(null); XmlSchemaSequence seq = new XmlSchemaSequence(); seq.Items.Add(anyElement); localAnyType.SetContentTypeParticle(seq); localAnyType.SetContentType(XmlSchemaContentType.Mixed); localAnyType.ElementDecl = SchemaElementDecl.CreateAnyTypeElementDecl(); localAnyType.ElementDecl.SchemaType = localAnyType; //Create contentValidator for Any ParticleContentValidator contentValidator = new ParticleContentValidator(XmlSchemaContentType.Mixed); contentValidator.Start(); contentValidator.OpenGroup(); contentValidator.AddNamespaceList(anyElement.NamespaceList, anyElement); contentValidator.AddStar(); contentValidator.CloseGroup(); ContentValidator anyContentValidator = contentValidator.Finish(true); localAnyType.ElementDecl.ContentValidator = anyContentValidator; XmlSchemaAnyAttribute anyAttribute = new XmlSchemaAnyAttribute(); anyAttribute.ProcessContents = processContents; anyAttribute.BuildNamespaceList(null); localAnyType.SetAttributeWildcard(anyAttribute); localAnyType.ElementDecl.AnyAttribute = anyAttribute; return localAnyType; } /// <include file='doc\XmlSchemaComplexType.uex' path='docs/doc[@for="XmlSchemaComplexType.XmlSchemaComplexType"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSchemaComplexType() { } [XmlIgnore] internal static XmlSchemaComplexType AnyType { get { return s_anyTypeLax; } } [XmlIgnore] internal static XmlSchemaComplexType UntypedAnyType { get { return s_untypedAnyType; } } [XmlIgnore] internal static XmlSchemaComplexType AnyTypeSkip { get { return s_anyTypeSkip; } } internal static ContentValidator AnyTypeContentValidator { get { return s_anyTypeLax.ElementDecl.ContentValidator; } } /// <include file='doc\XmlSchemaComplexType.uex' path='docs/doc[@for="XmlSchemaComplexType.IsAbstract"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlAttribute("abstract"), DefaultValue(false)] public bool IsAbstract { get { return (_pvFlags & isAbstractMask) != 0; } set { if (value) { _pvFlags = (byte)(_pvFlags | isAbstractMask); } else { _pvFlags = (byte)(_pvFlags & ~isAbstractMask); } } } /// <include file='doc\XmlSchemaComplexType.uex' path='docs/doc[@for="XmlSchemaComplexType.Block"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlAttribute("block"), DefaultValue(XmlSchemaDerivationMethod.None)] public XmlSchemaDerivationMethod Block { get { return _block; } set { _block = value; } } /// <include file='doc\XmlSchemaComplexType.uex' path='docs/doc[@for="XmlSchemaComplexType.IsMixed"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlAttribute("mixed"), DefaultValue(false)] public override bool IsMixed { get { return (_pvFlags & isMixedMask) != 0; } set { if (value) { _pvFlags = (byte)(_pvFlags | isMixedMask); } else { _pvFlags = (byte)(_pvFlags & ~isMixedMask); } } } /// <include file='doc\XmlSchemaComplexType.uex' path='docs/doc[@for="XmlSchemaComplexType.ContentModel"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlElement("simpleContent", typeof(XmlSchemaSimpleContent)), XmlElement("complexContent", typeof(XmlSchemaComplexContent))] public XmlSchemaContentModel ContentModel { get { return _contentModel; } set { _contentModel = value; } } /// <include file='doc\XmlSchemaComplexType.uex' path='docs/doc[@for="XmlSchemaComplexType.Particle"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlElement("group", typeof(XmlSchemaGroupRef)), XmlElement("choice", typeof(XmlSchemaChoice)), XmlElement("all", typeof(XmlSchemaAll)), XmlElement("sequence", typeof(XmlSchemaSequence))] public XmlSchemaParticle Particle { get { return _particle; } set { _particle = value; } } /// <include file='doc\XmlSchemaComplexType.uex' path='docs/doc[@for="XmlSchemaComplexType.Attributes"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlElement("attribute", typeof(XmlSchemaAttribute)), XmlElement("attributeGroup", typeof(XmlSchemaAttributeGroupRef))] public XmlSchemaObjectCollection Attributes { get { if (_attributes == null) { _attributes = new XmlSchemaObjectCollection(); } return _attributes; } } /// <include file='doc\XmlSchemaComplexType.uex' path='docs/doc[@for="XmlSchemaComplexType.AnyAttribute"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlElement("anyAttribute")] public XmlSchemaAnyAttribute AnyAttribute { get { return _anyAttribute; } set { _anyAttribute = value; } } /// <include file='doc\XmlSchemaComplexType.uex' path='docs/doc[@for="XmlSchemaComplexType.ContentType"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlIgnore] public XmlSchemaContentType ContentType { get { return SchemaContentType; } } /// <include file='doc\XmlSchemaComplexType.uex' path='docs/doc[@for="XmlSchemaComplexType.ContentTypeParticle"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlIgnore] public XmlSchemaParticle ContentTypeParticle { get { return _contentTypeParticle; } } /// <include file='doc\XmlSchemaComplexType.uex' path='docs/doc[@for="XmlSchemaComplexType.BlockResolved"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlIgnore] public XmlSchemaDerivationMethod BlockResolved { get { return _blockResolved; } } /// <include file='doc\XmlSchemaComplexType.uex' path='docs/doc[@for="XmlSchemaComplexType.AttributeUses"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlIgnore] public XmlSchemaObjectTable AttributeUses { get { if (_attributeUses == null) { _attributeUses = new XmlSchemaObjectTable(); } return _attributeUses; } } /// <include file='doc\XmlSchemaComplexType.uex' path='docs/doc[@for="XmlSchemaComplexType.AttributeWildcard"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlIgnore] public XmlSchemaAnyAttribute AttributeWildcard { get { return _attributeWildcard; } } /// <include file='doc\XmlSchemaComplexType.uex' path='docs/doc[@for="XmlSchemaComplexType.LocalElements"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlIgnore] internal XmlSchemaObjectTable LocalElements { get { if (_localElements == null) { _localElements = new XmlSchemaObjectTable(); } return _localElements; } } internal void SetContentTypeParticle(XmlSchemaParticle value) { _contentTypeParticle = value; } internal void SetBlockResolved(XmlSchemaDerivationMethod value) { _blockResolved = value; } internal void SetAttributeWildcard(XmlSchemaAnyAttribute value) { _attributeWildcard = value; } internal bool HasWildCard { get { return (_pvFlags & wildCardMask) != 0; } set { if (value) { _pvFlags = (byte)(_pvFlags | wildCardMask); } else { _pvFlags = (byte)(_pvFlags & ~wildCardMask); } } } internal override XmlQualifiedName DerivedFrom { get { if (_contentModel == null) { // type derived from anyType return XmlQualifiedName.Empty; } if (_contentModel.Content is XmlSchemaComplexContentRestriction) return ((XmlSchemaComplexContentRestriction)_contentModel.Content).BaseTypeName; else if (_contentModel.Content is XmlSchemaComplexContentExtension) return ((XmlSchemaComplexContentExtension)_contentModel.Content).BaseTypeName; else if (_contentModel.Content is XmlSchemaSimpleContentRestriction) return ((XmlSchemaSimpleContentRestriction)_contentModel.Content).BaseTypeName; else if (_contentModel.Content is XmlSchemaSimpleContentExtension) return ((XmlSchemaSimpleContentExtension)_contentModel.Content).BaseTypeName; else return XmlQualifiedName.Empty; } } internal void SetAttributes(XmlSchemaObjectCollection newAttributes) { _attributes = newAttributes; } internal bool ContainsIdAttribute(bool findAll) { int idCount = 0; foreach (XmlSchemaAttribute attribute in this.AttributeUses.Values) { if (attribute.Use != XmlSchemaUse.Prohibited) { XmlSchemaDatatype datatype = attribute.Datatype; if (datatype != null && datatype.TypeCode == XmlTypeCode.Id) { idCount++; if (idCount > 1) { //two or more attributes is error break; } } } } return findAll ? (idCount > 1) : (idCount > 0); } internal override XmlSchemaObject Clone() { System.Diagnostics.Debug.Assert(false, "Should never call Clone() on XmlSchemaComplexType. Call Clone(XmlSchema) instead."); return Clone(null); } internal XmlSchemaObject Clone(XmlSchema parentSchema) { XmlSchemaComplexType complexType = (XmlSchemaComplexType)MemberwiseClone(); //Deep clone the QNames as these will be updated on chameleon includes if (complexType.ContentModel != null) { //simpleContent or complexContent XmlSchemaSimpleContent simpleContent = complexType.ContentModel as XmlSchemaSimpleContent; if (simpleContent != null) { XmlSchemaSimpleContent newSimpleContent = (XmlSchemaSimpleContent)simpleContent.Clone(); XmlSchemaSimpleContentExtension simpleExt = simpleContent.Content as XmlSchemaSimpleContentExtension; if (simpleExt != null) { XmlSchemaSimpleContentExtension newSimpleExt = (XmlSchemaSimpleContentExtension)simpleExt.Clone(); newSimpleExt.BaseTypeName = simpleExt.BaseTypeName.Clone(); newSimpleExt.SetAttributes(CloneAttributes(simpleExt.Attributes)); newSimpleContent.Content = newSimpleExt; } else { //simpleContent.Content is XmlSchemaSimpleContentRestriction XmlSchemaSimpleContentRestriction simpleRest = (XmlSchemaSimpleContentRestriction)simpleContent.Content; XmlSchemaSimpleContentRestriction newSimpleRest = (XmlSchemaSimpleContentRestriction)simpleRest.Clone(); newSimpleRest.BaseTypeName = simpleRest.BaseTypeName.Clone(); newSimpleRest.SetAttributes(CloneAttributes(simpleRest.Attributes)); newSimpleContent.Content = newSimpleRest; } complexType.ContentModel = newSimpleContent; } else { // complexType.ContentModel is XmlSchemaComplexContent XmlSchemaComplexContent complexContent = (XmlSchemaComplexContent)complexType.ContentModel; XmlSchemaComplexContent newComplexContent = (XmlSchemaComplexContent)complexContent.Clone(); XmlSchemaComplexContentExtension complexExt = complexContent.Content as XmlSchemaComplexContentExtension; if (complexExt != null) { XmlSchemaComplexContentExtension newComplexExt = (XmlSchemaComplexContentExtension)complexExt.Clone(); newComplexExt.BaseTypeName = complexExt.BaseTypeName.Clone(); newComplexExt.SetAttributes(CloneAttributes(complexExt.Attributes)); if (HasParticleRef(complexExt.Particle, parentSchema)) { newComplexExt.Particle = CloneParticle(complexExt.Particle, parentSchema); } newComplexContent.Content = newComplexExt; } else { // complexContent.Content is XmlSchemaComplexContentRestriction XmlSchemaComplexContentRestriction complexRest = complexContent.Content as XmlSchemaComplexContentRestriction; XmlSchemaComplexContentRestriction newComplexRest = (XmlSchemaComplexContentRestriction)complexRest.Clone(); newComplexRest.BaseTypeName = complexRest.BaseTypeName.Clone(); newComplexRest.SetAttributes(CloneAttributes(complexRest.Attributes)); if (HasParticleRef(newComplexRest.Particle, parentSchema)) { newComplexRest.Particle = CloneParticle(newComplexRest.Particle, parentSchema); } newComplexContent.Content = newComplexRest; } complexType.ContentModel = newComplexContent; } } else { //equals XmlSchemaComplexContent with baseType is anyType if (HasParticleRef(complexType.Particle, parentSchema)) { complexType.Particle = CloneParticle(complexType.Particle, parentSchema); } complexType.SetAttributes(CloneAttributes(complexType.Attributes)); } complexType.ClearCompiledState(); return complexType; } private void ClearCompiledState() { //Re-set post-compiled state for cloned object _attributeUses = null; _localElements = null; _attributeWildcard = null; _contentTypeParticle = XmlSchemaParticle.Empty; _blockResolved = XmlSchemaDerivationMethod.None; } internal static XmlSchemaObjectCollection CloneAttributes(XmlSchemaObjectCollection attributes) { if (HasAttributeQNameRef(attributes)) { XmlSchemaObjectCollection newAttributes = attributes.Clone(); XmlSchemaAttributeGroupRef attributeGroupRef; XmlSchemaAttributeGroupRef newAttGroupRef; XmlSchemaObject xso; XmlSchemaAttribute att; for (int i = 0; i < attributes.Count; i++) { xso = attributes[i]; attributeGroupRef = xso as XmlSchemaAttributeGroupRef; if (attributeGroupRef != null) { newAttGroupRef = (XmlSchemaAttributeGroupRef)attributeGroupRef.Clone(); newAttGroupRef.RefName = attributeGroupRef.RefName.Clone(); newAttributes[i] = newAttGroupRef; } else { //Its XmlSchemaAttribute att = xso as XmlSchemaAttribute; if (!att.RefName.IsEmpty || !att.SchemaTypeName.IsEmpty) { newAttributes[i] = att.Clone(); } } } return newAttributes; } return attributes; } private static XmlSchemaObjectCollection CloneGroupBaseParticles(XmlSchemaObjectCollection groupBaseParticles, XmlSchema parentSchema) { XmlSchemaObjectCollection newParticles = groupBaseParticles.Clone(); for (int i = 0; i < groupBaseParticles.Count; i++) { XmlSchemaParticle p = (XmlSchemaParticle)groupBaseParticles[i]; newParticles[i] = CloneParticle(p, parentSchema); } return newParticles; } internal static XmlSchemaParticle CloneParticle(XmlSchemaParticle particle, XmlSchema parentSchema) { XmlSchemaGroupBase groupBase = particle as XmlSchemaGroupBase; if (groupBase != null) { //Choice or sequence XmlSchemaGroupBase newGroupBase = groupBase; XmlSchemaObjectCollection newGroupbaseParticles = CloneGroupBaseParticles(groupBase.Items, parentSchema); newGroupBase = (XmlSchemaGroupBase)groupBase.Clone(); newGroupBase.SetItems(newGroupbaseParticles); return newGroupBase; } else if (particle is XmlSchemaGroupRef) { // group ref XmlSchemaGroupRef newGroupRef = (XmlSchemaGroupRef)particle.Clone(); newGroupRef.RefName = newGroupRef.RefName.Clone(); return newGroupRef; } else { XmlSchemaElement oldElem = particle as XmlSchemaElement; // If the particle is an element and one of the following is true: // - it references another element by name // - it references its type by name // - it's form (effective) is qualified (meaning it will inherint namespace from chameleon includes if that happens) // then the element itself needs to be cloned. if (oldElem != null && (!oldElem.RefName.IsEmpty || !oldElem.SchemaTypeName.IsEmpty || GetResolvedElementForm(parentSchema, oldElem) == XmlSchemaForm.Qualified)) { XmlSchemaElement newElem = (XmlSchemaElement)oldElem.Clone(parentSchema); return newElem; } } return particle; } // This method returns the effective value of the "element form" for the specified element in the specified // parentSchema. Element form is either qualified, unqualified or none. If it's qualified it means that // if the element doesn't declare its own namespace the targetNamespace of the schema is used instead. // The element form can be either specified on the element itself via the "form" attribute or // if that one is not present its inheritted from the value of the elementFormDefault attribute on the owning // schema. private static XmlSchemaForm GetResolvedElementForm(XmlSchema parentSchema, XmlSchemaElement element) { if (element.Form == XmlSchemaForm.None && parentSchema != null) { return parentSchema.ElementFormDefault; } else { return element.Form; } } internal static bool HasParticleRef(XmlSchemaParticle particle, XmlSchema parentSchema) { XmlSchemaGroupBase groupBase = particle as XmlSchemaGroupBase; if (groupBase != null) { bool foundRef = false; int i = 0; while (i < groupBase.Items.Count && !foundRef) { XmlSchemaParticle p = (XmlSchemaParticle)groupBase.Items[i++]; if (p is XmlSchemaGroupRef) { foundRef = true; } else { XmlSchemaElement elem = p as XmlSchemaElement; // This is the same condition as in the CloneParticle method // that's on purpose. This method is used to determine if we need to clone the whole particle. // If we do, then the CloneParticle is called and it will try to clone only // those elements which need cloning - and those are the ones matching this condition. if (elem != null && (!elem.RefName.IsEmpty || !elem.SchemaTypeName.IsEmpty || GetResolvedElementForm(parentSchema, elem) == XmlSchemaForm.Qualified)) { foundRef = true; } else { foundRef = HasParticleRef(p, parentSchema); } } } return foundRef; } else if (particle is XmlSchemaGroupRef) { return true; } return false; } internal static bool HasAttributeQNameRef(XmlSchemaObjectCollection attributes) { for (int i = 0; i < attributes.Count; ++i) { if (attributes[i] is XmlSchemaAttributeGroupRef) { return true; } else { XmlSchemaAttribute attribute = attributes[i] as XmlSchemaAttribute; if (!attribute.RefName.IsEmpty || !attribute.SchemaTypeName.IsEmpty) { return true; } } } return false; } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Collections.Generic; using System.Globalization; using System.Reactive.Linq; using System.Threading; using Avalonia.Data; using Avalonia.Markup.Data; using Avalonia.UnitTests; using Moq; using Xunit; namespace Avalonia.Markup.UnitTests.Data { public class BindingExpressionTests { [Fact] public async void Should_Get_Simple_Property_Value() { var data = new Class1 { StringValue = "foo" }; var target = new BindingExpression(new ExpressionObserver(data, "StringValue"), typeof(string)); var result = await target.Take(1); Assert.Equal("foo", result); } [Fact] public void Should_Set_Simple_Property_Value() { var data = new Class1 { StringValue = "foo" }; var target = new BindingExpression(new ExpressionObserver(data, "StringValue"), typeof(string)); target.OnNext("bar"); Assert.Equal("bar", data.StringValue); } [Fact] public async void Should_Convert_Get_String_To_Double() { Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; var data = new Class1 { StringValue = "5.6" }; var target = new BindingExpression(new ExpressionObserver(data, "StringValue"), typeof(double)); var result = await target.Take(1); Assert.Equal(5.6, result); } [Fact] public async void Getting_Invalid_Double_String_Should_Return_BindingError() { var data = new Class1 { StringValue = "foo" }; var target = new BindingExpression(new ExpressionObserver(data, "StringValue"), typeof(double)); var result = await target.Take(1); Assert.IsType<BindingNotification>(result); } [Fact] public async void Should_Coerce_Get_Null_Double_String_To_UnsetValue() { var data = new Class1 { StringValue = null }; var target = new BindingExpression(new ExpressionObserver(data, "StringValue"), typeof(double)); var result = await target.Take(1); Assert.Equal(AvaloniaProperty.UnsetValue, result); } [Fact] public void Should_Convert_Set_String_To_Double() { Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; var data = new Class1 { StringValue = (5.6).ToString() }; var target = new BindingExpression(new ExpressionObserver(data, "StringValue"), typeof(double)); target.OnNext(6.7); Assert.Equal((6.7).ToString(), data.StringValue); } [Fact] public async void Should_Convert_Get_Double_To_String() { Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; var data = new Class1 { DoubleValue = 5.6 }; var target = new BindingExpression(new ExpressionObserver(data, "DoubleValue"), typeof(string)); var result = await target.Take(1); Assert.Equal((5.6).ToString(), result); } [Fact] public void Should_Convert_Set_Double_To_String() { Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; var data = new Class1 { DoubleValue = 5.6 }; var target = new BindingExpression(new ExpressionObserver(data, "DoubleValue"), typeof(string)); target.OnNext("6.7"); Assert.Equal(6.7, data.DoubleValue); } [Fact] public async void Should_Return_BindingNotification_With_FallbackValue_For_NonConvertibe_Target_Value() { Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; var data = new Class1 { StringValue = "foo" }; var target = new BindingExpression( new ExpressionObserver(data, "StringValue"), typeof(int), 42, DefaultValueConverter.Instance); var result = await target.Take(1); Assert.Equal( new BindingNotification( new InvalidCastException("'foo' is not a valid number."), BindingErrorType.Error, 42), result); } [Fact] public async void Should_Return_BindingNotification_With_FallbackValue_For_NonConvertibe_Target_Value_With_Data_Validation() { Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; var data = new Class1 { StringValue = "foo" }; var target = new BindingExpression( new ExpressionObserver(data, "StringValue", true), typeof(int), 42, DefaultValueConverter.Instance); var result = await target.Take(1); Assert.Equal( new BindingNotification( new InvalidCastException("'foo' is not a valid number."), BindingErrorType.Error, 42), result); } [Fact] public async void Should_Return_BindingNotification_For_Invalid_FallbackValue() { Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; var data = new Class1 { StringValue = "foo" }; var target = new BindingExpression( new ExpressionObserver(data, "StringValue"), typeof(int), "bar", DefaultValueConverter.Instance); var result = await target.Take(1); Assert.Equal( new BindingNotification( new AggregateException( new InvalidCastException("Could not convert 'foo' to 'System.Int32'"), new InvalidCastException("Could not convert FallbackValue 'bar' to 'System.Int32'")), BindingErrorType.Error), result); } [Fact] public async void Should_Return_BindingNotification_For_Invalid_FallbackValue_With_Data_Validation() { Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; var data = new Class1 { StringValue = "foo" }; var target = new BindingExpression( new ExpressionObserver(data, "StringValue", true), typeof(int), "bar", DefaultValueConverter.Instance); var result = await target.Take(1); Assert.Equal( new BindingNotification( new AggregateException( new InvalidCastException("Could not convert 'foo' to 'System.Int32'"), new InvalidCastException("Could not convert FallbackValue 'bar' to 'System.Int32'")), BindingErrorType.Error), result); } [Fact] public void Setting_Invalid_Double_String_Should_Not_Change_Target() { var data = new Class1 { DoubleValue = 5.6 }; var target = new BindingExpression(new ExpressionObserver(data, "DoubleValue"), typeof(string)); target.OnNext("foo"); Assert.Equal(5.6, data.DoubleValue); } [Fact] public void Setting_Invalid_Double_String_Should_Use_FallbackValue() { var data = new Class1 { DoubleValue = 5.6 }; var target = new BindingExpression( new ExpressionObserver(data, "DoubleValue"), typeof(string), "9.8", DefaultValueConverter.Instance); target.OnNext("foo"); Assert.Equal(9.8, data.DoubleValue); } [Fact] public void Should_Coerce_Setting_Null_Double_To_Default_Value() { var data = new Class1 { DoubleValue = 5.6 }; var target = new BindingExpression(new ExpressionObserver(data, "DoubleValue"), typeof(string)); target.OnNext(null); Assert.Equal(0, data.DoubleValue); } [Fact] public void Should_Coerce_Setting_UnsetValue_Double_To_Default_Value() { var data = new Class1 { DoubleValue = 5.6 }; var target = new BindingExpression(new ExpressionObserver(data, "DoubleValue"), typeof(string)); target.OnNext(AvaloniaProperty.UnsetValue); Assert.Equal(0, data.DoubleValue); } [Fact] public void Should_Pass_ConverterParameter_To_Convert() { var data = new Class1 { DoubleValue = 5.6 }; var converter = new Mock<IValueConverter>(); var target = new BindingExpression( new ExpressionObserver(data, "DoubleValue"), typeof(string), converter.Object, converterParameter: "foo"); target.Subscribe(_ => { }); converter.Verify(x => x.Convert(5.6, typeof(string), "foo", CultureInfo.CurrentUICulture)); } [Fact] public void Should_Pass_ConverterParameter_To_ConvertBack() { var data = new Class1 { DoubleValue = 5.6 }; var converter = new Mock<IValueConverter>(); var target = new BindingExpression( new ExpressionObserver(data, "DoubleValue"), typeof(string), converter.Object, converterParameter: "foo"); target.OnNext("bar"); converter.Verify(x => x.ConvertBack("bar", typeof(double), "foo", CultureInfo.CurrentUICulture)); } [Fact] public void Should_Handle_DataValidation() { var data = new Class1 { DoubleValue = 5.6 }; var converter = new Mock<IValueConverter>(); var target = new BindingExpression(new ExpressionObserver(data, "DoubleValue", true), typeof(string)); var result = new List<object>(); target.Subscribe(x => result.Add(x)); target.OnNext(1.2); target.OnNext("3.4"); target.OnNext("bar"); Assert.Equal( new[] { new BindingNotification("5.6"), new BindingNotification("1.2"), new BindingNotification("3.4"), new BindingNotification( new InvalidCastException("'bar' is not a valid number."), BindingErrorType.Error) }, result); } private class Class1 : NotifyingBase { private string _stringValue; private double _doubleValue; public string StringValue { get { return _stringValue; } set { _stringValue = value; RaisePropertyChanged(); } } public double DoubleValue { get { return _doubleValue; } set { _doubleValue = value; RaisePropertyChanged(); } } } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Data.IO.dll Alpha // Description: The data access libraries for the DotSpatial project. // // ******************************************************************************************************** // The contents of this file are subject to the MIT License (MIT) // you may not use this file except in compliance with the License. You may obtain a copy of the License at // http://dotspatial.codeplex.com/license // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF // ANY KIND, either expressed or implied. See the License for the specific language governing rights and // limitations under the License. // // The Original Code is from DotSpatial.Data.IO.dll // // The Initial Developer of this Original Code is Ted Dunsford. Created in February 2008 // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.IO; namespace DotSpatial.Data { /// <summary> /// The buffered binary reader was originally designed by Ted Dunsford to make shapefile reading more /// efficient, but ostensibly could be used for other binary reading exercises. To use this class, /// simply specify the BufferSize in bytes that you would like to use and begin reading values. /// </summary> public class BufferedBinaryReader { #region Private Variables private readonly long _fileLength; private readonly ProgressMeter _progressMeter; private BinaryReader _binaryReader; private byte[] _buffer; private long _bufferOffset; // Position of the start of the buffer relative to the start of the file private int _bufferSize; private string _fileName; private long _fileOffset; // position in the entire file private FileStream _fileStream; private bool _isBufferLoaded; private bool _isFinishedBuffering; private bool _isFinishedReading; private int _maxBufferSize = 9600000; // Approximately around ten megs, divisible by 8 private int _readOffset; // #endregion #region Constructors /// <summary> /// Creates a new instance of BufferedBinaryReader. /// </summary> ///<param name="fileName">The string path of a file to open using this BufferedBinaryReader.</param> public BufferedBinaryReader(string fileName) : this(fileName, null) { // This is just an overload that sends the default null value in for the progressHandler } /// <summary> /// Creates a new instance of BufferedBinaryReader, and specifies where to send progress messages. /// </summary> /// <param name="fileName">The string path of a file to open using this BufferedBinaryReader.</param> /// <param name="progressHandler">Any implementation of IProgressHandler for receiving progress messages.</param> public BufferedBinaryReader(string fileName, IProgressHandler progressHandler) { //Modified 9/22/09 by L. C. Wilson to open as read-only so it is possible to open read-only files //Not sure if elsewhere write access is required _fileName = fileName; _fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read); _binaryReader = new BinaryReader(_fileStream); FileInfo fi = new FileInfo(fileName); _fileLength = fi.Length; _fileOffset = 0; _readOffset = -1; // There is no buffer loaded. _bufferSize = 0; _bufferOffset = -1; // -1 means no buffer is loaded. _isFinishedBuffering = false; _isFinishedReading = false; _progressMeter = new ProgressMeter(progressHandler, "Reading from " + Path.GetFileName(fileName), _fileLength); if (_fileLength < 10000000) _progressMeter.StepPercent = 5; if (_fileLength < 5000000) _progressMeter.StepPercent = 10; if (_fileLength < 100000) _progressMeter.StepPercent = 50; if (_fileLength < 10000) _progressMeter.StepPercent = 100; //long testMax = _fileLength / _progressMeter.StepPercent; //if (testMax < (long)9600000) _maxBufferSize = Convert.ToInt32(testMax); // otherwise keep it at 96000000 } #endregion #region Methods // This internal method attempts to advance the buffer. private void AdvanceBuffer() { if (_isFinishedReading) { throw new EndOfStreamException(DataStrings.EndOfFile); } if (_isFinishedBuffering == false) { if (_maxBufferSize > FileRemainder) { // If the buffer size is greater than the remainder, load the entire remainder and close the file. _bufferSize = Convert.ToInt32(FileRemainder); _buffer = new byte[_bufferSize]; _binaryReader.Read(_buffer, 0, _bufferSize); Close(); } else { _bufferSize = _maxBufferSize; _buffer = new byte[_bufferSize]; _binaryReader.Read(_buffer, 0, _bufferSize); } _isBufferLoaded = true; _bufferOffset = _fileOffset; _readOffset = 0; } else { // We are done, so throw the event to indicate we are done. OnFinishedReading(); } } /// <summary> /// Closes the internal binary reader and underlying file, but does not free /// the buffer that is in memory. For that, call the dispose method. /// </summary> public void Close() { if (_binaryReader != null) { _binaryReader.Close(); } _binaryReader = null; OnFinishedBuffering(); } /// <summary> /// This will not close the file, so be sure to close before calling Dispose. /// This will dispose the file stream and set the buffer to null. /// </summary> public void Dispose() { _buffer = null; _binaryReader = null; _fileStream.Dispose(); } /// <summary> /// Instructs the reader to fill its buffer with data. This only does something /// if the buffer is not loaded yet. This method is optional since the first /// effort at reading the file will automatically load the buffer. /// </summary> public void FillBuffer() { if (_isBufferLoaded == false) { AdvanceBuffer(); } } /// <summary> /// This method will both assign a new maximum buffer size to the reader and /// force the reader to load the values into memory. This is unnecessary /// unless you plan on closing the file before reading values from this class. /// Even if values are loaded, this will assign the MaxBufferSize property /// so that future buffers have the specified size. /// </summary> /// <param name="maxBufferSize">An integer buffer size to assign to the maximum buffer size before reading values.</param> public void FillBuffer(int maxBufferSize) { _maxBufferSize = maxBufferSize; FillBuffer(); } /// <summary> /// Uses the seek method to quickly reach a desired location to begin reading. /// This will not buffer or read values. If the new position is beyond the end /// of the current buffer, the next read will load a new buffer. /// </summary> /// <param name="offset">A 64 bit integer specifying where to skip to in the file.</param> /// <param name="origin">A System.IO.SeekOrigin enumeration specifying how to estimate the location.</param> public void Seek(long offset, SeekOrigin origin) { if (offset == 0 && origin == SeekOrigin.Current) return; long startPosition = 0; switch (origin) { case SeekOrigin.Begin: startPosition = offset; break; case SeekOrigin.Current: startPosition = _readOffset + offset; break; case SeekOrigin.End: startPosition = _fileLength - offset; break; } if (startPosition >= _fileLength || startPosition < 0) { // regardless of what direction, we need a start position inside the file throw new EndOfStreamException(DataStrings.EndOfFile); } // Only worry about resetting the buffer or repositioning the position // inside the buffer if a buffer is actually loaded. if (_isBufferLoaded) { long delta = startPosition - _fileOffset; if (delta > _bufferSize - _readOffset || delta < 0) { // The new position is beyond our current buffer _buffer = null; _readOffset = -1; _bufferOffset = -1; _isBufferLoaded = false; if (_isFinishedBuffering || _binaryReader == null) { _fileStream = new FileStream(_fileName, FileMode.Open, FileAccess.Read); _binaryReader = new BinaryReader(_fileStream); } _isFinishedBuffering = false; } else { // The new position is still inside the buffer _readOffset += Convert.ToInt32(delta); _fileOffset += delta; // we don't want to actually seek in the internal reader return; } } // If no buffer is loaded, the file may not be open and may cause an exception when trying to seek. // probably better for tracking than not throwing one. _fileOffset = startPosition; if (_fileStream.CanSeek) _fileStream.Seek(offset, origin); return; } #region Read Methods /// <summary> /// Gets the progress meter. /// </summary> public ProgressMeter ProgressMeter { get { return _progressMeter; } } /// <summary> /// Reads a boolean form the buffer, automatcially loading the next buffer if necessary. /// </summary> /// <returns>A boolean value converted from bytes in the file.</returns> public bool ReadBool() { byte[] data = ReadBytes(1); return BitConverter.ToBoolean(data, 0); } /// <summary> /// Reads a character from two bytes in the buffer, automatically loading the next buffer if necessary. /// </summary> /// <returns></returns> public char ReadChar() { byte[] data = ReadBytes(2); return BitConverter.ToChar(data, 0); } /// <summary> /// Reads an array of character from two bytes in the buffer, automatically loading /// </summary> /// <returns></returns> public char[] ReadChars(int count) { byte[] data = ReadBytes(count * 2); char[] result = new char[count]; for (int i = 0; i < count; i++) { result[i] = BitConverter.ToChar(data, i * 2); } return result; } /// <summary> /// Reads a double-precision floating point from 8 bytes in the buffer, automatically loading the next buffer if necessary. /// </summary> /// <param name="isLittleEndian">Boolean, true if the value should be returned with little endian byte ordering.</param> /// <returns>A double value converted from bytes in the file.</returns> public double ReadDouble(bool isLittleEndian = true) { // Integers are 8 Bytes long. byte[] data = ReadBytes(8); if (isLittleEndian != BitConverter.IsLittleEndian) { // The IsLittleEndian property on the BitConverter tells us what the system is using by default. // The isLittleEndian argument tells us what bit order the output should be in. Array.Reverse(data); } double result = BitConverter.ToDouble(data, 0); return result; } /// <summary> /// Reads double precision X and Y values that are interwoven /// </summary> /// <param name="count"></param> /// <returns></returns> public Vertex[] ReadVertices(int count) { int len = count * 16; byte[] rawBytes = new byte[len]; Read(rawBytes, 0, len); Vertex[] result = new Vertex[count]; Buffer.BlockCopy(rawBytes, 0, result, 0, len); return result; } /// <summary> /// Reads the specified number of doubles into an array /// This uses Buffer.CopyBlock, and seems to work ok /// for little-endian in windows. /// </summary> /// <param name="count">The count of doubles</param> /// <returns>An array of doubles</returns> public double[] ReadDoubles(int count) { byte[] rawBytes = new byte[count * 8]; Read(rawBytes, 0, count * 8); double[] result = new double[count]; Buffer.BlockCopy(rawBytes, 0, result, 0, count * 8); return result; } /// <summary> /// Reads the specified number of integers into an array /// </summary> /// <param name="count">The integer count of integers to read</param> /// <returns>An array of the specified integers and length equal to count</returns> public int[] ReadIntegers(int count) { byte[] rawBytes = new byte[count * 4]; Read(rawBytes, 0, count * 4); int[] result = new int[count]; Buffer.BlockCopy(rawBytes, 0, result, 0, count * 4); return result; } /// <summary> /// By default, this will use little Endian ordering. /// </summary> /// <returns>An Int32 converted from the file.</returns> public int ReadInt32() { return ReadInt32(true); } /// <summary> /// Reads an integer from the file, using the isLittleEndian argument /// to decide whether to flip the bits or not. /// </summary> /// <param name="isLittleEndian">Boolean, true if the value should be returned with little endian byte ordering.</param> /// <returns>an Int32 value converted from bytes in the file.</returns> public int ReadInt32(bool isLittleEndian) { // Integers are 4 Bytes long. byte[] data = ReadBytes(4); if (isLittleEndian != BitConverter.IsLittleEndian) { // The IsLittleEndian property on the BitConverter tells us what the system is using by default. // The isLittleEndian argument tells us what bit order the output should be in. Array.Reverse(data); } return BitConverter.ToInt32(data, 0); } /// <summary> /// Reads a short, sixteen bit integer as bytes in little-endian order /// </summary> /// <returns>A short value</returns> public short ReadInt16() { byte[] data = ReadBytes(2); return BitConverter.ToInt16(data, 0); } /// <summary> /// Reads a single-precision floading point from 4 bytes in the buffer, automatically loading the next buffer if necessary. /// This assumes the value should be little endian. /// </summary> /// <returns>A single-precision floating point converted from four bytes</returns> public float ReadSingle() { return ReadSingle(true); } /// <summary> /// Reads a single-precision floading point from 4 bytes in the buffer, automatically loading the next buffer if necessary. /// </summary> /// <param name="isLittleEndian">Boolean, true if the value should be returned with little endian byte ordering.</param> /// <returns>A single-precision floating point converted from four bytes</returns> public float ReadSingle(bool isLittleEndian) { // Integers are 4 Bytes long. byte[] data = ReadBytes(4); if (isLittleEndian != BitConverter.IsLittleEndian) { // The IsLittleEndian property on the BitConverter tells us what the system is using by default. // The isLittleEndian argument tells us what bit order the output should be in. Array.Reverse(data); } return BitConverter.ToInt32(data, 0); } /// <summary> /// Reads the specified number of bytes. This will throw an exception /// if a number of bytes is specified that exeeds the file length. /// </summary> /// <param name="byteCount">The integer count of the bytes.</param> /// <returns>An array of bytes</returns> public byte[] ReadBytes(int byteCount) { byte[] result = new byte[byteCount]; Read(result, 0, byteCount); return result; } /// <summary> /// copies count bytes from the internal buffer to the specified buffer index as the starting point in the specified buffer. /// </summary> /// <param name="buffer">A previously dimensioned array of byte values to fill with data</param> /// <param name="index">The index in the argument array to start pasting values to</param> /// <param name="count">The number of values to copy into the parameter buffer</param> public void Read(byte[] buffer, int index, int count) { bool finished = false; int bytesPasted = 0; if (_isBufferLoaded == false) AdvanceBuffer(); do { int bytesInBuffer = _bufferSize - _readOffset; if (count - bytesPasted <= bytesInBuffer) { // Read the specified bytes and advance Buffer.BlockCopy(_buffer, _readOffset, buffer, index, count - bytesPasted); _readOffset += count - bytesPasted; _fileOffset += count - bytesPasted; if (_fileOffset >= _fileLength) { OnFinishedReading(); // We got to the end of the file. } finished = true; } else { // Read what we can from the array and then advance the buffer Buffer.BlockCopy(_buffer, _readOffset, buffer, index, bytesInBuffer); index += bytesInBuffer; bytesPasted += bytesInBuffer; _fileOffset += bytesInBuffer; if (bytesPasted >= count) { // Sometimes there might be less than count bytes left in the file. // In those cases, we actually finish reading down here instead. if (_fileOffset >= _fileLength) { OnFinishedReading(); // We reached the end of the file } finished = true; // Even if we aren't at the end of the file, we are done with this read session } else { // We haven't pasted enough bytes, so advance the buffer and continue reading AdvanceBuffer(); } } } while (finished == false); if (_isFinishedReading == false) _progressMeter.CurrentValue = _fileOffset; } #endregion #endregion #region Properties /// <summary> /// Gets a long integer specifying the starting position of the currently loaded buffer /// relative to the start of the file. A value of -1 indicates that no buffer is /// currently loaded. /// </summary> public long BufferOffset { get { return _bufferOffset; } } /// <summary> /// Gets an integer value specifying the size of the buffer currently loaded into memory. /// This will either be the MaxBufferSize, or a smaller buffer representing a smaller /// remainder existing in the file. /// </summary> public int BufferSize { get { return _bufferSize; } } /// <summary> /// Gets a boolean indicating whether there is currently any information loaded into the buffer. /// </summary> public bool IsBufferLoaded { get { return _isBufferLoaded; } } /// <summary> /// Gets a boolean value once the offset has reached the end of the file, /// and every byte value has been read from the file. /// </summary> public bool IsFinishedReading { get { return _isFinishedReading; } } /// <summary> /// Gets a boolean value once the entire file has been loaded into memory. /// This usually will occur before any reading even takes place. /// </summary> public bool IsFinishedBuffering { get { return _isFinishedBuffering; } } /// <summary> /// Gets the length in bytes of the file being read. /// </summary> public long FileLength { get { return _fileLength; } } /// <summary> /// Gets the current read position in the file in bytes. /// </summary> public long FileOffset { get { return _fileOffset; } } /// <summary> /// Gets a long value specifying how many bytes have not yet been read in the file. /// </summary> public long FileRemainder { get { return _fileLength - _fileOffset; } } /// <summary> /// Gets or sets the buffer size to read in chunks. This does not /// describe the size of the actual /// </summary> public int MaxBufferSize { get { return _maxBufferSize; } set { if (value < 0) { throw new ArgumentException(DataStrings.ArgumentCannotBeNegative_S.Replace("%S", "BufferSize")); } _maxBufferSize = value; } } /// <summary> /// Gets or sets the progress message that has no percentage as part of it. /// </summary> public string ProgressBaseMessage { get { return _progressMeter.Key; } set { _progressMeter.Key = value; } } /// <summary> /// This acts like a placeholder on the buffer and indicates where reading will begin (relative to the start of the buffer) /// </summary> public int ReadOffset { get { return _readOffset; } } #endregion #region Events /// <summary> /// Occurs when this reader has read every byte from the file. /// </summary> public event EventHandler FinishedReading; /// <summary> /// Fires the FinishedReading event. /// </summary> protected virtual void OnFinishedReading() { _isFinishedReading = true; _progressMeter.Reset(); _buffer = null; if (FinishedReading == null) return; FinishedReading(this, EventArgs.Empty); } /// <summary> /// Occurs when the end of the last portion of the file has been /// loaded into the file and the file has been closed. /// </summary> public event EventHandler FinishedBuffering; /// <summary> /// Fires the FinishedBuffering event. /// </summary> protected virtual void OnFinishedBuffering() { _isFinishedBuffering = true; if (FinishedBuffering == null) return; FinishedBuffering(this, EventArgs.Empty); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Buffers; using System.Text; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Security.Cryptography.Asn1; using System.Security.Cryptography.Pkcs; using System.Security.Cryptography.Pkcs.Asn1; using System.Security.Cryptography.X509Certificates; using X509IssuerSerial = System.Security.Cryptography.Xml.X509IssuerSerial; namespace Internal.Cryptography { internal static class Helpers { public static byte[] CloneByteArray(this byte[] a) { return (byte[])(a.Clone()); } #if !netcoreapp // Compatibility API. internal static void AppendData(this IncrementalHash hasher, ReadOnlySpan<byte> data) { hasher.AppendData(data.ToArray()); } #endif internal static HashAlgorithmName GetDigestAlgorithm(Oid oid) { Debug.Assert(oid != null); return GetDigestAlgorithm(oid.Value); } internal static HashAlgorithmName GetDigestAlgorithm(string oidValue) { switch (oidValue) { case Oids.Md5: return HashAlgorithmName.MD5; case Oids.Sha1: return HashAlgorithmName.SHA1; case Oids.Sha256: return HashAlgorithmName.SHA256; case Oids.Sha384: return HashAlgorithmName.SHA384; case Oids.Sha512: return HashAlgorithmName.SHA512; default: throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, oidValue); } } internal static string GetOidFromHashAlgorithm(HashAlgorithmName algName) { if (algName == HashAlgorithmName.MD5) return Oids.Md5; if (algName == HashAlgorithmName.SHA1) return Oids.Sha1; if (algName == HashAlgorithmName.SHA256) return Oids.Sha256; if (algName == HashAlgorithmName.SHA384) return Oids.Sha384; if (algName == HashAlgorithmName.SHA512) return Oids.Sha512; throw new CryptographicException(SR.Cryptography_Cms_UnknownAlgorithm, algName.Name); } /// <summary> /// This is not just a convenience wrapper for Array.Resize(). In DEBUG builds, it forces the array to move in memory even if no resize is needed. This should be used by /// helper methods that do anything of the form "call a native api once to get the estimated size, call it again to get the data and return the data in a byte[] array." /// Sometimes, that data consist of a native data structure containing pointers to other parts of the block. Using such a helper to retrieve such a block results in an intermittent /// AV. By using this helper, you make that AV repro every time. /// </summary> public static byte[] Resize(this byte[] a, int size) { Array.Resize(ref a, size); #if DEBUG a = a.CloneByteArray(); #endif return a; } public static void RemoveAt<T>(ref T[] arr, int idx) { Debug.Assert(arr != null); Debug.Assert(idx >= 0); Debug.Assert(idx < arr.Length); if (arr.Length == 1) { arr = Array.Empty<T>(); return; } T[] tmp = new T[arr.Length - 1]; if (idx != 0) { Array.Copy(arr, 0, tmp, 0, idx); } if (idx < tmp.Length) { Array.Copy(arr, idx + 1, tmp, idx, tmp.Length - idx); } arr = tmp; } public static T[] NormalizeSet<T>( T[] setItems, Action<byte[]> encodedValueProcessor=null) { AsnSet<T> set = new AsnSet<T> { SetData = setItems, }; AsnWriter writer = AsnSerializer.Serialize(set, AsnEncodingRules.DER); byte[] normalizedValue = writer.Encode(); set = AsnSerializer.Deserialize<AsnSet<T>>(normalizedValue, AsnEncodingRules.DER); if (encodedValueProcessor != null) { encodedValueProcessor(normalizedValue); } return set.SetData; } public static CmsRecipientCollection DeepCopy(this CmsRecipientCollection recipients) { CmsRecipientCollection recipientsCopy = new CmsRecipientCollection(); foreach (CmsRecipient recipient in recipients) { X509Certificate2 originalCert = recipient.Certificate; X509Certificate2 certCopy = new X509Certificate2(originalCert.Handle); CmsRecipient recipientCopy = new CmsRecipient(recipient.RecipientIdentifierType, certCopy); recipientsCopy.Add(recipientCopy); GC.KeepAlive(originalCert); } return recipientsCopy; } public static byte[] UnicodeToOctetString(this string s) { byte[] octets = new byte[2 * (s.Length + 1)]; Encoding.Unicode.GetBytes(s, 0, s.Length, octets, 0); return octets; } public static string OctetStringToUnicode(this byte[] octets) { if (octets.Length < 2) return string.Empty; // Desktop compat: 0-length byte array maps to string.empty. 1-length byte array gets passed to Marshal.PtrToStringUni() with who knows what outcome. string s = Encoding.Unicode.GetString(octets, 0, octets.Length - 2); return s; } public static X509Certificate2Collection GetStoreCertificates(StoreName storeName, StoreLocation storeLocation, bool openExistingOnly) { using (X509Store store = new X509Store()) { OpenFlags flags = OpenFlags.ReadOnly | OpenFlags.IncludeArchived; if (openExistingOnly) flags |= OpenFlags.OpenExistingOnly; store.Open(flags); X509Certificate2Collection certificates = store.Certificates; return certificates; } } /// <summary> /// Desktop compat: We do not complain about multiple matches. Just take the first one and ignore the rest. /// </summary> public static X509Certificate2 TryFindMatchingCertificate(this X509Certificate2Collection certs, SubjectIdentifier recipientIdentifier) { // // Note: SubjectIdentifier has no public constructor so the only one that can construct this type is this assembly. // Therefore, we trust that the string-ized byte array (serial or ski) in it is correct and canonicalized. // SubjectIdentifierType recipientIdentifierType = recipientIdentifier.Type; switch (recipientIdentifierType) { case SubjectIdentifierType.IssuerAndSerialNumber: { X509IssuerSerial issuerSerial = (X509IssuerSerial)(recipientIdentifier.Value); byte[] serialNumber = issuerSerial.SerialNumber.ToSerialBytes(); string issuer = issuerSerial.IssuerName; foreach (X509Certificate2 candidate in certs) { byte[] candidateSerialNumber = candidate.GetSerialNumber(); if (AreByteArraysEqual(candidateSerialNumber, serialNumber) && candidate.Issuer == issuer) return candidate; } } break; case SubjectIdentifierType.SubjectKeyIdentifier: { string skiString = (string)(recipientIdentifier.Value); byte[] ski = skiString.ToSkiBytes(); foreach (X509Certificate2 cert in certs) { byte[] candidateSki = PkcsPal.Instance.GetSubjectKeyIdentifier(cert); if (AreByteArraysEqual(ski, candidateSki)) return cert; } } break; default: // RecipientInfo's can only be created by this package so if this an invalid type, it's the package's fault. Debug.Fail($"Invalid recipientIdentifier type: {recipientIdentifierType}"); throw new CryptographicException(); } return null; } private static bool AreByteArraysEqual(byte[] ba1, byte[] ba2) { if (ba1.Length != ba2.Length) return false; for (int i = 0; i < ba1.Length; i++) { if (ba1[i] != ba2[i]) return false; } return true; } /// <summary> /// Asserts on bad or non-canonicalized input. Input must come from trusted sources. /// /// Subject Key Identifier is string-ized as an upper case hex string. This format is part of the public api behavior and cannot be changed. /// </summary> private static byte[] ToSkiBytes(this string skiString) { return skiString.UpperHexStringToByteArray(); } public static string ToSkiString(this ReadOnlySpan<byte> skiBytes) { return ToUpperHexString(skiBytes); } public static string ToSkiString(this byte[] skiBytes) { return ToUpperHexString(skiBytes); } /// <summary> /// Asserts on bad or non-canonicalized input. Input must come from trusted sources. /// /// Serial number is string-ized as a reversed upper case hex string. This format is part of the public api behavior and cannot be changed. /// </summary> private static byte[] ToSerialBytes(this string serialString) { byte[] ba = serialString.UpperHexStringToByteArray(); Array.Reverse(ba); return ba; } public static string ToSerialString(this byte[] serialBytes) { serialBytes = serialBytes.CloneByteArray(); Array.Reverse(serialBytes); return ToUpperHexString(serialBytes); } private static string ToUpperHexString(ReadOnlySpan<byte> ba) { StringBuilder sb = new StringBuilder(ba.Length * 2); for (int i = 0; i < ba.Length; i++) { sb.Append(ba[i].ToString("X2")); } return sb.ToString(); } /// <summary> /// Asserts on bad input. Input must come from trusted sources. /// </summary> private static byte[] UpperHexStringToByteArray(this string normalizedString) { Debug.Assert((normalizedString.Length & 0x1) == 0); byte[] ba = new byte[normalizedString.Length / 2]; for (int i = 0; i < ba.Length; i++) { char c = normalizedString[i * 2]; byte b = (byte)(UpperHexCharToNybble(c) << 4); c = normalizedString[i * 2 + 1]; b |= UpperHexCharToNybble(c); ba[i] = b; } return ba; } /// <summary> /// Asserts on bad input. Input must come from trusted sources. /// </summary> private static byte UpperHexCharToNybble(char c) { if (c >= '0' && c <= '9') return (byte)(c - '0'); if (c >= 'A' && c <= 'F') return (byte)(c - 'A' + 10); Debug.Fail($"Invalid hex character: {c}"); throw new CryptographicException(); // This just keeps the compiler happy. We don't expect to reach this. } /// <summary> /// Useful helper for "upgrading" well-known CMS attributes to type-specific objects such as Pkcs9DocumentName, Pkcs9DocumentDescription, etc. /// </summary> public static Pkcs9AttributeObject CreateBestPkcs9AttributeObjectAvailable(Oid oid, byte[] encodedAttribute) { Pkcs9AttributeObject attributeObject = new Pkcs9AttributeObject(oid, encodedAttribute); switch (oid.Value) { case Oids.DocumentName: attributeObject = Upgrade<Pkcs9DocumentName>(attributeObject); break; case Oids.DocumentDescription: attributeObject = Upgrade<Pkcs9DocumentDescription>(attributeObject); break; case Oids.SigningTime: attributeObject = Upgrade<Pkcs9SigningTime>(attributeObject); break; case Oids.ContentType: attributeObject = Upgrade<Pkcs9ContentType>(attributeObject); break; case Oids.MessageDigest: attributeObject = Upgrade<Pkcs9MessageDigest>(attributeObject); break; default: break; } return attributeObject; } private static T Upgrade<T>(Pkcs9AttributeObject basicAttribute) where T : Pkcs9AttributeObject, new() { T enhancedAttribute = new T(); enhancedAttribute.CopyFrom(basicAttribute); return enhancedAttribute; } public static byte[] GetSubjectKeyIdentifier(this X509Certificate2 certificate) { Debug.Assert(certificate != null); X509Extension extension = certificate.Extensions[Oids.SubjectKeyIdentifier]; if (extension != null) { // Certificates are DER encoded. AsnReader reader = new AsnReader(extension.RawData, AsnEncodingRules.DER); if (reader.TryGetPrimitiveOctetStringBytes(out ReadOnlyMemory<byte> contents)) { return contents.ToArray(); } // TryGetPrimitiveOctetStringBytes will have thrown if the next tag wasn't // Universal (primitive) OCTET STRING, since we're in DER mode. // So there's really no way we can get here. Debug.Fail($"TryGetPrimitiveOctetStringBytes returned false in DER mode"); throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); } // The Desktop/Windows version of this method use CertGetCertificateContextProperty // with a property ID of CERT_KEY_IDENTIFIER_PROP_ID. // // MSDN says that when there's no extension, this method takes the SHA-1 of the // SubjectPublicKeyInfo block, and returns that. // // https://msdn.microsoft.com/en-us/library/windows/desktop/aa376079%28v=vs.85%29.aspx #pragma warning disable CA5350 // SHA-1 is required for compat. using (HashAlgorithm hash = SHA1.Create()) #pragma warning restore CA5350 // Do not use insecure cryptographic algorithm SHA1. { ReadOnlyMemory<byte> publicKeyInfoBytes = GetSubjectPublicKeyInfo(certificate); return hash.ComputeHash(publicKeyInfoBytes.ToArray()); } } internal static void DigestWriter(IncrementalHash hasher, AsnWriter writer) { #if netcoreapp hasher.AppendData(writer.EncodeAsSpan()); #else hasher.AppendData(writer.Encode()); #endif } private static ReadOnlyMemory<byte> GetSubjectPublicKeyInfo(X509Certificate2 certificate) { var parsedCertificate = AsnSerializer.Deserialize<Certificate>(certificate.RawData, AsnEncodingRules.DER); return parsedCertificate.TbsCertificate.SubjectPublicKeyInfo; } [StructLayout(LayoutKind.Sequential)] private struct Certificate { internal TbsCertificateLite TbsCertificate; internal AlgorithmIdentifierAsn AlgorithmIdentifier; [BitString] internal ReadOnlyMemory<byte> SignatureValue; } [StructLayout(LayoutKind.Sequential)] private struct TbsCertificateLite { [ExpectedTag(0, ExplicitTag = true)] #pragma warning disable CS3016 // Arrays as attribute arguments is not CLS-compliant [DefaultValue(0xA0, 0x03, 0x02, 0x01, 0x00)] #pragma warning restore CS3016 // Arrays as attribute arguments is not CLS-compliant internal int Version; [Integer] internal ReadOnlyMemory<byte> SerialNumber; internal AlgorithmIdentifierAsn AlgorithmIdentifier; [AnyValue] [ExpectedTag(TagClass.Universal, (int)UniversalTagNumber.SequenceOf)] internal ReadOnlyMemory<byte> Issuer; [AnyValue] [ExpectedTag(TagClass.Universal, (int)UniversalTagNumber.Sequence)] internal ReadOnlyMemory<byte> Validity; [AnyValue] [ExpectedTag(TagClass.Universal, (int)UniversalTagNumber.SequenceOf)] internal ReadOnlyMemory<byte> Subject; [AnyValue] [ExpectedTag(TagClass.Universal, (int)UniversalTagNumber.Sequence)] internal ReadOnlyMemory<byte> SubjectPublicKeyInfo; [ExpectedTag(1)] [OptionalValue] [BitString] internal ReadOnlyMemory<byte>? IssuerUniqueId; [ExpectedTag(2)] [OptionalValue] [BitString] internal ReadOnlyMemory<byte>? SubjectUniqueId; [OptionalValue] [AnyValue] [ExpectedTag(3)] internal ReadOnlyMemory<byte>? Extensions; } [StructLayout(LayoutKind.Sequential)] internal struct AsnSet<T> { [SetOf] public T[] SetData; } } }
// 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. // // The older-style CustomAttribute-related members on the various Reflection types. The implementation dependency // stack on .Net Native differs from that of CoreClr due to the difference in development history. // // - IEnumerable<CustomAttributeData> xInfo.get_CustomAttributes is at the very bottom of the dependency stack. // // - CustomAttributeExtensions layers on top of that (primarily because it's the one with the nice generic methods.) // // - Everything else is a thin layer over one of these two. // // using System; using System.IO; using System.Reflection; using System.Collections.Generic; using System.Reflection.Runtime.General; using Internal.LowLevelLinq; using Internal.Reflection.Extensions.NonPortable; namespace System.Reflection.Runtime.Assemblies { internal partial class RuntimeAssembly { public sealed override IList<CustomAttributeData> GetCustomAttributesData() => CustomAttributes.ToReadOnlyCollection(); public sealed override object[] GetCustomAttributes(bool inherit) => CustomAttributeExtensions.GetCustomAttributes(this).ToArray(); // inherit is meaningless for Assemblies public sealed override object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); IEnumerable<CustomAttributeData> cads = this.GetMatchingCustomAttributes(attributeType, skipTypeValidation: true); // inherit is meaningless for Assemblies return cads.InstantiateAsArray(attributeType); } public sealed override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); IEnumerable<CustomAttributeData> cads = this.GetMatchingCustomAttributes(attributeType, skipTypeValidation: true); // inherit is meaningless for Assemblies return cads.Any(); } } } namespace System.Reflection.Runtime.MethodInfos { internal abstract partial class RuntimeConstructorInfo { public sealed override IList<CustomAttributeData> GetCustomAttributesData() => CustomAttributes.ToReadOnlyCollection(); public sealed override object[] GetCustomAttributes(bool inherit) => CustomAttributeExtensions.GetCustomAttributes(this, inherit).ToArray(); public sealed override object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); IEnumerable<CustomAttributeData> cads = this.GetMatchingCustomAttributes(attributeType, inherit: inherit, skipTypeValidation: true); return cads.InstantiateAsArray(attributeType); } public sealed override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); IEnumerable<CustomAttributeData> cads = this.GetMatchingCustomAttributes(attributeType, inherit: inherit, skipTypeValidation: true); return cads.Any(); } } } namespace System.Reflection.Runtime.EventInfos { internal abstract partial class RuntimeEventInfo { public sealed override IList<CustomAttributeData> GetCustomAttributesData() => CustomAttributes.ToReadOnlyCollection(); public sealed override object[] GetCustomAttributes(bool inherit) => CustomAttributeExtensions.GetCustomAttributes(this, inherit: false).ToArray(); // Desktop compat: for events, this form of the api ignores "inherit" public sealed override object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); IEnumerable<CustomAttributeData> cads = this.GetMatchingCustomAttributes(attributeType, inherit: false, skipTypeValidation: true); // Desktop compat: for events, this form of the api ignores "inherit" return cads.InstantiateAsArray(attributeType); } public sealed override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); IEnumerable<CustomAttributeData> cads = this.GetMatchingCustomAttributes(attributeType, inherit: false, skipTypeValidation: true); // Desktop compat: for events, this form of the api ignores "inherit" return cads.Any(); } } } namespace System.Reflection.Runtime.FieldInfos { internal abstract partial class RuntimeFieldInfo { public sealed override IList<CustomAttributeData> GetCustomAttributesData() => CustomAttributes.ToReadOnlyCollection(); public sealed override object[] GetCustomAttributes(bool inherit) => CustomAttributeExtensions.GetCustomAttributes(this, inherit).ToArray(); public sealed override object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); IEnumerable<CustomAttributeData> cads = this.GetMatchingCustomAttributes(attributeType, inherit: inherit, skipTypeValidation: true); return cads.InstantiateAsArray(attributeType); } public sealed override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); IEnumerable<CustomAttributeData> cads = this.GetMatchingCustomAttributes(attributeType, inherit: inherit, skipTypeValidation: true); return cads.Any(); } } } namespace System.Reflection.Runtime.MethodInfos { internal abstract partial class RuntimeMethodInfo { public sealed override IList<CustomAttributeData> GetCustomAttributesData() => CustomAttributes.ToReadOnlyCollection(); public sealed override object[] GetCustomAttributes(bool inherit) => CustomAttributeExtensions.GetCustomAttributes(this, inherit).ToArray(); public sealed override object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); IEnumerable<CustomAttributeData> cads = this.GetMatchingCustomAttributes(attributeType, inherit: inherit, skipTypeValidation: true); return cads.InstantiateAsArray(attributeType); } public sealed override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); IEnumerable<CustomAttributeData> cads = this.GetMatchingCustomAttributes(attributeType, inherit: inherit, skipTypeValidation: true); return cads.Any(); } } } namespace System.Reflection.Runtime.Modules { internal abstract partial class RuntimeModule { public sealed override IList<CustomAttributeData> GetCustomAttributesData() => CustomAttributes.ToReadOnlyCollection(); public sealed override object[] GetCustomAttributes(bool inherit) => CustomAttributeExtensions.GetCustomAttributes(this).ToArray(); // inherit is meaningless for Modules public sealed override object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); IEnumerable<CustomAttributeData> cads = this.GetMatchingCustomAttributes(attributeType, skipTypeValidation: true); // inherit is meaningless for Modules return cads.InstantiateAsArray(attributeType); } public sealed override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); IEnumerable<CustomAttributeData> cads = this.GetMatchingCustomAttributes(attributeType, skipTypeValidation: true); // inherit is meaningless for Modules return cads.Any(); } } } namespace System.Reflection.Runtime.ParameterInfos { internal abstract partial class RuntimeParameterInfo { public sealed override IList<CustomAttributeData> GetCustomAttributesData() => CustomAttributes.ToReadOnlyCollection(); public sealed override object[] GetCustomAttributes(bool inherit) => CustomAttributeExtensions.GetCustomAttributes(this, inherit: false).ToArray(); // Desktop compat: for parameters, this form of the api ignores "inherit" public sealed override object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); IEnumerable<CustomAttributeData> cads = this.GetMatchingCustomAttributes(attributeType, inherit: false, skipTypeValidation: true); // Desktop compat: for parameters, this form of the api ignores "inherit" return cads.InstantiateAsArray(attributeType); } public sealed override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); IEnumerable<CustomAttributeData> cads = this.GetMatchingCustomAttributes(attributeType, inherit: false, skipTypeValidation: true); // Desktop compat: for parameters, this form of the api ignores "inherit" return cads.Any(); } } } namespace System.Reflection.Runtime.PropertyInfos { internal abstract partial class RuntimePropertyInfo { public sealed override IList<CustomAttributeData> GetCustomAttributesData() => CustomAttributes.ToReadOnlyCollection(); public sealed override object[] GetCustomAttributes(bool inherit) => CustomAttributeExtensions.GetCustomAttributes(this, inherit: false).ToArray(); // Desktop compat: for properties, this form of the api ignores "inherit" public sealed override object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); IEnumerable<CustomAttributeData> cads = this.GetMatchingCustomAttributes(attributeType, inherit: false, skipTypeValidation: true); // Desktop compat: for properties, this form of the api ignores "inherit" return cads.InstantiateAsArray(attributeType); } public sealed override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); IEnumerable<CustomAttributeData> cads = this.GetMatchingCustomAttributes(attributeType, inherit: false, skipTypeValidation: true); // Desktop compat: for properties, this form of the api ignores "inherit" return cads.Any(); } } } namespace System.Reflection.Runtime.TypeInfos { internal abstract partial class RuntimeTypeInfo { public sealed override IList<CustomAttributeData> GetCustomAttributesData() => CustomAttributes.ToReadOnlyCollection(); public sealed override object[] GetCustomAttributes(bool inherit) => CustomAttributeExtensions.GetCustomAttributes(this, inherit).ToArray(); public sealed override object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); IEnumerable<CustomAttributeData> cads = this.GetMatchingCustomAttributes(attributeType, inherit: inherit, skipTypeValidation: true); return cads.InstantiateAsArray(attributeType); } public sealed override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); IEnumerable<CustomAttributeData> cads = this.GetMatchingCustomAttributes(attributeType, inherit: inherit, skipTypeValidation: true); return cads.Any(); } } }
using System; using System.Collections.Generic; using System.Text; using NUnit.Framework; using InTheHand.Net.Bluetooth; using InTheHand.Net.Bluetooth.Widcomm; using InTheHand.Net.Sockets; using System.Net.Sockets; using System.IO; using System.Diagnostics; using InTheHand.Net.Bluetooth.Factory; using System.Threading; namespace InTheHand.Net.Tests.Widcomm { [TestFixture] public class WidcommBluetoothListenerTest { private static TestLsnrRfcommPort Init_OneListener() { TestWcLsnrBluetoothFactory f = new TestWcLsnrBluetoothFactory(); TestLsnrRfCommIf commIf = new TestLsnrRfCommIf(); f.queueIRfCommIf.Enqueue(commIf); TestLsnrRfcommPort port0 = new TestLsnrRfcommPort(); f.queueIRfCommPort.Enqueue(port0); BluetoothFactory.SetFactory(f); // port0.SetOpenServerResult(PORT_RETURN_CODE.SUCCESS); // return port0; } private static TestLsnrRfcommPort Init_OneListenerStartedTwice() { TestWcLsnrBluetoothFactory f = new TestWcLsnrBluetoothFactory(); TestLsnrRfCommIf commIf = new TestLsnrRfCommIf(); f.queueIRfCommIf.Enqueue(commIf); commIf = new TestLsnrRfCommIf(); f.queueIRfCommIf.Enqueue(commIf); f.MaxSdpServices = 2; // For Start() TestLsnrRfcommPort port0 = new TestLsnrRfcommPort(); f.queueIRfCommPort.Enqueue(port0); // For Start TestLsnrRfcommPort port1 = new TestLsnrRfcommPort(); f.queueIRfCommPort.Enqueue(port1); // For Client Finalize TestLsnrRfcommPort port2 = new TestLsnrRfcommPort(); f.queueIRfCommPort.Enqueue(port2); // BluetoothFactory.SetFactory(f); // port0.SetOpenServerResult(PORT_RETURN_CODE.SUCCESS); port1.SetOpenServerResult(PORT_RETURN_CODE.SUCCESS); port2.SetOpenServerResult(PORT_RETURN_CODE.SUCCESS); // return port0; } [Test] public void StopNoStart() { TestLsnrRfcommPort port0 = Init_OneListener(); BluetoothListener lsnr = new BluetoothListener(BluetoothService.VideoSource); lsnr.Stop(); } [Test] public void StopStartStop() { TestLsnrRfcommPort port0 = Init_OneListenerStartedTwice(); BluetoothListener lsnr = new BluetoothListener(BluetoothService.VideoSource); lsnr.Start(); lsnr.Stop(); lsnr.Start(); // lsnr = null; GC.Collect(); GC.Collect(); GC.WaitForPendingFinalizers(); } //---- [Test] public void OneConnection() { TestWcLsnrBluetoothFactory f = new TestWcLsnrBluetoothFactory(); TestLsnrRfCommIf commIf = new TestLsnrRfCommIf(); f.queueIRfCommIf.Enqueue(commIf); TestLsnrRfcommPort port0 = new TestLsnrRfcommPort(); f.queueIRfCommPort.Enqueue(port0); BluetoothFactory.SetFactory(f); TestLsnrRfcommPort port1 = AddSomeCreatablePorts(f); // port0.SetOpenServerResult(PORT_RETURN_CODE.SUCCESS); BluetoothListener lsnr = new BluetoothListener(BluetoothService.VideoSource); lsnr.Start(); IAsyncResult ar = lsnr.BeginAcceptBluetoothClient(null, null); port0.AssertOpenServerCalledAndClear(29);//adter Start? port0.NewEvent(PORT_EV.CONNECTED); TestsApmUtils.SafeNoHangWaitShort(ar, "Accept"); Assert.IsTrue(ar.IsCompleted, "IsCompleted"); BluetoothClient cli = lsnr.EndAcceptBluetoothClient(ar); TestSdpService2 sdpSvc = f.GetTestSdpService(); Assert.AreEqual(0, sdpSvc.NumDisposeCalls, "NumDisposeCalls"); lsnr.Stop(); Assert.AreEqual(1, sdpSvc.NumDisposeCalls, "NumDisposeCalls"); // Assert.IsTrue(cli.Connected, "cli.Connected"); Assert.AreEqual(0, f.queueIRfCommPort.Count, "Used both ports"); port1.AssertCloseCalledOnce("second acceptor closed"); cli.Close(); port0.AssertCloseCalledOnce("first accepted connection now closed"); // BluetoothEndPoint lep = lsnr.LocalEndPoint; sdpSvc.AssertCalls( "AddServiceClassIdList: 00001303-0000-1000-8000-00805f9b34fb" + NewLine + "AddRFCommProtocolDescriptor: " + lep.Port + NewLine ); } private static TestLsnrRfcommPort AddACreatablePort(TestWcLsnrBluetoothFactory f, PORT_RETURN_CODE result) { TestLsnrRfcommPort port1 = new TestLsnrRfcommPort(); port1.SetOpenServerResult(result); // now begun immediately f.queueIRfCommPort.Enqueue(port1); return port1; } private static TestLsnrRfcommPort AddSomeCreatablePorts(TestWcLsnrBluetoothFactory f) { TestLsnrRfcommPort port1 = AddACreatablePort(f, PORT_RETURN_CODE.SUCCESS); //AddACreatablePort(f, PORT_RETURN_CODE.SUCCESS); //AddACreatablePort(f, PORT_RETURN_CODE.SUCCESS); //AddACreatablePort(f, PORT_RETURN_CODE.SUCCESS); return port1; } [Test] public void OneConnection_PendingBeforeSyncAccept() { TestWcLsnrBluetoothFactory f = new TestWcLsnrBluetoothFactory(); TestLsnrRfCommIf commIf = new TestLsnrRfCommIf(); f.queueIRfCommIf.Enqueue(commIf); TestLsnrRfcommPort port0 = new TestLsnrRfcommPort(); f.queueIRfCommPort.Enqueue(port0); BluetoothFactory.SetFactory(f); // port0.SetOpenServerResult(PORT_RETURN_CODE.SUCCESS); BluetoothListener lsnr = new BluetoothListener(BluetoothService.VideoSource); try { Assert.IsFalse(lsnr.Pending(), "!Pending before Start"); lsnr.Start(); port0.AssertOpenServerCalledAndClear(29);//adter Start? TestLsnrRfcommPort port1 = new TestLsnrRfcommPort(); port1.SetOpenServerResult(PORT_RETURN_CODE.SUCCESS); // now begun immediately f.queueIRfCommPort.Enqueue(port1); Assert.IsFalse(lsnr.Pending(), "!Pending before"); port0.NewEvent(PORT_EV.CONNECTED); Thread.Sleep(100); Assert.IsTrue(lsnr.Pending(), "Pending"); BluetoothClient cli = lsnr.AcceptBluetoothClient(); TestSdpService2 sdpSvc = f.GetTestSdpService(); Assert.AreEqual(0, sdpSvc.NumDisposeCalls, "NumDisposeCalls"); lsnr.Stop(); Assert.AreEqual(1, sdpSvc.NumDisposeCalls, "NumDisposeCalls"); // Assert.IsTrue(cli.Connected, "cli.Connected"); //TODOAssert.AreEqual(0, f.queueIRfCommPort.Count, "Used both ports"); //TODO port1.AssertCloseCalledOnce("second acceptor closed"); cli.Close(); port0.AssertCloseCalledOnce("first accepted connection now closed"); // BluetoothEndPoint lep = lsnr.LocalEndPoint; sdpSvc.AssertCalls( "AddServiceClassIdList: 00001303-0000-1000-8000-00805f9b34fb" + NewLine + "AddRFCommProtocolDescriptor: " + lep.Port + NewLine ); // // } finally { lsnr.Stop(); // See errors that might otherwise occur on the Finalizer. } } [Test] public void OneConnection_PeerImmediatelyCloses() { TestWcLsnrBluetoothFactory f = new TestWcLsnrBluetoothFactory(); TestLsnrRfCommIf commIf = new TestLsnrRfCommIf(); f.queueIRfCommIf.Enqueue(commIf); TestLsnrRfcommPort port0 = new TestLsnrRfcommPort(); f.queueIRfCommPort.Enqueue(port0); BluetoothFactory.SetFactory(f); // port0.SetOpenServerResult(PORT_RETURN_CODE.SUCCESS); BluetoothListener lsnr = new BluetoothListener(BluetoothService.VideoSource); lsnr.Start(); IAsyncResult ar = lsnr.BeginAcceptBluetoothClient(null, null); port0.AssertOpenServerCalledAndClear(29);//adter Start? TestLsnrRfcommPort port1 = new TestLsnrRfcommPort(); f.queueIRfCommPort.Enqueue(port1); port1.SetOpenServerResult(PORT_RETURN_CODE.SUCCESS); // now begun immediately FireOpenReceiveCloseEvents firer = new FireOpenReceiveCloseEvents(port0); firer.Run(); //port0.NewEvent(PORT_EV.CONNECTED); //Assert.IsFalse(ar.IsCompleted, "Connect 1 completed"); // 100ms later... firer.Complete(); port0.AssertCloseCalledOnce("first accepted connection now closed"); TestsApmUtils.SafeNoHangWaitShort(ar, "Accept"); Assert.IsTrue(ar.IsCompleted, "IsCompleted"); BluetoothClient cli = lsnr.EndAcceptBluetoothClient(ar); lsnr.Stop(); // //TODO ! Assert.IsTrue(cli.Connected, "cli.Connected"); Assert.AreEqual(0, f.queueIRfCommPort.Count, "Used both ports"); port1.AssertCloseCalledOnce("second acceptor closed"); // Stream peer = cli.GetStream(); byte[] buf = new byte[10]; int readLen = TestsApmUtils.SafeNoHangRead(peer, buf, 0, buf.Length); Assert.AreEqual(1, readLen, "readLen"); cli.Close(); port0.AssertCloseCalledAtLeastOnce("first accepted connection now closed"); } [Test] public void ZeroConnections() { TestWcLsnrBluetoothFactory f = new TestWcLsnrBluetoothFactory(); TestLsnrRfCommIf commIf = new TestLsnrRfCommIf(); f.queueIRfCommIf.Enqueue(commIf); TestLsnrRfcommPort port0 = new TestLsnrRfcommPort(); f.queueIRfCommPort.Enqueue(port0); BluetoothFactory.SetFactory(f); // port0.SetOpenServerResult(PORT_RETURN_CODE.SUCCESS); BluetoothListener lsnr = new BluetoothListener(BluetoothService.VideoSource); lsnr.Start(); IAsyncResult ar = lsnr.BeginAcceptBluetoothClient(null, null); lsnr.Stop(); Assert.IsTrue(ar.IsCompleted, ".IsCompleted"); try { BluetoothClient cli = lsnr.EndAcceptBluetoothClient(ar); } catch (ObjectDisposedException) { } // Assert.AreEqual(0, f.queueIRfCommPort.Count, "Used all ports"); port0.AssertCloseCalledOnce("acceptor closed"); } [Test] public void OneFailedIncomingConnection() { TestWcLsnrBluetoothFactory f = new TestWcLsnrBluetoothFactory(); TestLsnrRfCommIf commIf = new TestLsnrRfCommIf(); f.queueIRfCommIf.Enqueue(commIf); TestLsnrRfcommPort port0 = new TestLsnrRfcommPort(); f.queueIRfCommPort.Enqueue(port0); BluetoothFactory.SetFactory(f); // port0.SetOpenServerResult(PORT_RETURN_CODE.SUCCESS); BluetoothListener lsnr = new BluetoothListener(BluetoothService.VideoSink); lsnr.ServiceName = "weeee"; lsnr.Start(); IAsyncResult ar = lsnr.BeginAcceptBluetoothClient(null, null); TestLsnrRfcommPort port1 = new TestLsnrRfcommPort(); f.queueIRfCommPort.Enqueue(port1); port1.SetOpenServerResult(PORT_RETURN_CODE.SUCCESS); // now begun immediately port0.NewEvent(PORT_EV.CONNECT_ERR); TestsApmUtils.SafeNoHangWaitShort(ar, "Accept"); Assert.IsTrue(ar.IsCompleted, "IsCompleted"); port0.AssertOpenServerCalledAndClear(29); try { try { BluetoothClient cli = lsnr.EndAcceptBluetoothClient(ar); } catch (System.IO.IOException ioexShouldNotWrapSEx) { //HACK ioexShouldNotWrapSEx throw ioexShouldNotWrapSEx.InnerException; } Assert.Fail("should have thrown!"); } catch (SocketException) { } TestSdpService2 sdpSvc = f.GetTestSdpService(); Assert.AreEqual(0, sdpSvc.NumDisposeCalls, "NumDisposeCalls"); lsnr.Stop(); Assert.AreEqual(1, sdpSvc.NumDisposeCalls, "NumDisposeCalls"); // Assert.AreEqual(0, f.queueIRfCommPort.Count, "Used both ports"); port1.AssertCloseCalledOnce("second acceptor closed"); //port0.AssertCloseCalledOnce("first failed connection now closed"); // BluetoothEndPoint lep = lsnr.LocalEndPoint; sdpSvc.AssertCalls( "AddServiceClassIdList: 00001304-0000-1000-8000-00805f9b34fb" + NewLine + "AddRFCommProtocolDescriptor: " + lep.Port + NewLine + "AddServiceName: weeee" + NewLine ); } [Test] public void MultipleConnection() { MultipleConnection_(false, false, BTM_SEC.NONE); } [Test] public void MultipleConnection_AuthNotEncrypt() { MultipleConnection_(true, false, BTM_SEC.IN_AUTHENTICATE); } [Test] public void MultipleConnection_NotAuthEncrypt() { MultipleConnection_(false, true, BTM_SEC.IN_ENCRYPT | BTM_SEC.IN_AUTHENTICATE); } [Test] public void MultipleConnection_AuthEncrypt() { MultipleConnection_(true, true, BTM_SEC.IN_ENCRYPT | BTM_SEC.IN_AUTHENTICATE); } void MultipleConnection_(bool auth, bool encrypt, BTM_SEC expectedSecurityLevel) { TestWcLsnrBluetoothFactory f = new TestWcLsnrBluetoothFactory(); TestLsnrRfCommIf commIf = new TestLsnrRfCommIf(); f.queueIRfCommIf.Enqueue(commIf); TestLsnrRfcommPort port0 = new TestLsnrRfcommPort(); f.queueIRfCommPort.Enqueue(port0); port0.SetOpenServerResult(PORT_RETURN_CODE.SUCCESS); BluetoothFactory.SetFactory(f); // BluetoothListener lsnr = new BluetoothListener(BluetoothService.VideoSource); if (auth) lsnr.Authenticate = true; if (encrypt) lsnr.Encrypt = true; Assert.AreEqual(auth, lsnr.Authenticate, ".Authenticate 1"); Assert.AreEqual(encrypt, lsnr.Encrypt, ".Encrypt 1"); lsnr.Start(); IAsyncResult ar; commIf.AssertSetSecurityLevel(expectedSecurityLevel, true); // ar = lsnr.BeginAcceptBluetoothClient(null, null); port0.AssertOpenServerCalledAndClear(29);//adter Start? TestLsnrRfcommPort port1 = new TestLsnrRfcommPort(); f.queueIRfCommPort.Enqueue(port1); port1.SetOpenServerResult(PORT_RETURN_CODE.SUCCESS); port0.NewEvent(PORT_EV.CONNECTED); TestsApmUtils.SafeNoHangWaitShort(ar, "Accept"); Assert.IsTrue(ar.IsCompleted, "IsCompleted"); BluetoothClient cli0 = lsnr.EndAcceptBluetoothClient(ar); // ar = lsnr.BeginAcceptBluetoothClient(null, null); port1.AssertOpenServerCalledAndClear(29);//adter Start? TestLsnrRfcommPort port2 = new TestLsnrRfcommPort(); port2.SetOpenServerResult(PORT_RETURN_CODE.SUCCESS); f.queueIRfCommPort.Enqueue(port2); port1.NewEvent(PORT_EV.CONNECTED); TestsApmUtils.SafeNoHangWaitShort(ar, "Accept"); Assert.IsTrue(ar.IsCompleted, "IsCompleted"); BluetoothClient cli1 = lsnr.EndAcceptBluetoothClient(ar); // ar = lsnr.BeginAcceptBluetoothClient(null, null); port2.AssertOpenServerCalledAndClear(29);//adter Start? TestLsnrRfcommPort port3 = new TestLsnrRfcommPort(); port3.SetOpenServerResult(PORT_RETURN_CODE.SUCCESS); f.queueIRfCommPort.Enqueue(port3); port2.NewEvent(PORT_EV.CONNECTED); TestsApmUtils.SafeNoHangWaitShort(ar, "Accept"); Assert.IsTrue(ar.IsCompleted, "IsCompleted"); BluetoothClient cli2 = lsnr.EndAcceptBluetoothClient(ar); // ar = lsnr.BeginAcceptBluetoothClient(null, null); port3.AssertOpenServerCalledAndClear(29);//adter Start? TestLsnrRfcommPort port4 = new TestLsnrRfcommPort(); f.queueIRfCommPort.Enqueue(port4); port4.SetOpenServerResult(PORT_RETURN_CODE.SUCCESS); port3.NewEvent(PORT_EV.CONNECTED); TestsApmUtils.SafeNoHangWaitShort(ar, "Accept"); Assert.IsTrue(ar.IsCompleted, "IsCompleted"); BluetoothClient cli3 = lsnr.EndAcceptBluetoothClient(ar); // TestSdpService2 sdpSvc = f.GetTestSdpService(); Assert.AreEqual(0, sdpSvc.NumDisposeCalls, "NumDisposeCalls"); lsnr.Stop(); Assert.AreEqual(1, sdpSvc.NumDisposeCalls, "NumDisposeCalls"); Assert.AreEqual(auth, lsnr.Authenticate, ".Authenticate 2"); Assert.AreEqual(encrypt, lsnr.Encrypt, ".Encrypt 2"); // Assert.IsTrue(cli0.Connected, "0 cli.Connected"); Assert.AreEqual(0, f.queueIRfCommPort.Count, "Used both ports"); port4.AssertCloseCalledOnce("4 acceptor closed"); cli0.Close(); port0.AssertCloseCalledOnce("0 accepted connection now closed"); // Assert.IsTrue(cli1.Connected, "1 cli.Connected"); cli1.Close(); port1.AssertCloseCalledOnce("1 accepted connection now closed"); // Assert.IsTrue(cli2.Connected, "2 cli.Connected"); cli2.Close(); port2.AssertCloseCalledOnce("2 accepted connection now closed"); // Assert.IsTrue(cli3.Connected, "3 cli.Connected"); cli3.Close(); port3.AssertCloseCalledOnce("3 accepted connection now closed"); } delegate TResult MyFunc<T0, TResult>(T0 p0); delegate TResult MyFunc<T0, T1, TResult>(T0 p0, T1 p1); private static ServiceRecord CreateAVariousRecord() { MyFunc<ElementType, ServiceAttributeId> createId = delegate(ElementType etX) { return (ServiceAttributeId)0x4000 + checked((byte)etX); }; ServiceRecordBuilder bldr = new ServiceRecordBuilder(); bldr.AddServiceClass(BluetoothService.HealthDevice); bldr.ServiceName = "alan"; IList<ServiceAttribute> attrList = new List<ServiceAttribute>(); ElementType et_; #if SUPPORT_NIL et_ = ElementType.Nil; attrList.Add(new ServiceAttribute(createId(et_), new ServiceElement(et_, null))); #endif et_ = ElementType.Boolean; attrList.Add(new ServiceAttribute(createId(et_), new ServiceElement(et_, true))); ElementType[] weee = { ElementType.UInt8, ElementType.UInt16, ElementType.UInt32, //UInt64, UInt128, ElementType.Int8, ElementType.Int16, ElementType.Int32, //Int64, Int128, }; foreach (ElementType et in weee) { attrList.Add(new ServiceAttribute( createId(et), ServiceElement.CreateNumericalServiceElement(et, (uint)et))); } et_ = ElementType.Uuid16; attrList.Add(new ServiceAttribute(createId(et_), new ServiceElement(et_, (UInt16)et_))); et_ = ElementType.Uuid32; attrList.Add(new ServiceAttribute(createId(et_), new ServiceElement(et_, (UInt32)et_))); et_ = ElementType.Uuid128; attrList.Add(new ServiceAttribute(createId(et_), new ServiceElement(et_, BluetoothService.CreateBluetoothUuid((int)et_)))); bldr.AddCustomAttributes(attrList); bldr.AddCustomAttributes(ElementsAndVariableAndFixedInDeepTree1()); ServiceRecord record = bldr.ServiceRecord; return record; } public static IList<ServiceAttribute> ElementsAndVariableAndFixedInDeepTree1() { IList<ServiceAttribute> attrs = new List<ServiceAttribute>(); // String str = InTheHand.Net.Tests.Sdp2.Data_SdpCreator_SingleElementTests.RecordBytes_OneString_StringValue; ServiceElement itemStr1 = new ServiceElement(ElementType.TextString, str); ServiceElement itemStr2 = new ServiceElement(ElementType.TextString, str); // Uri uri = new Uri("http://example.com/foo.txt"); ServiceElement itemUrl = new ServiceElement(ElementType.Url, uri); // ServiceElement itemF1 = new ServiceElement(ElementType.UInt16, (UInt16)0xfe12); ServiceElement itemF2 = new ServiceElement(ElementType.UInt16, (UInt16)0x1234); // IList<ServiceElement> leaves2 = new List<ServiceElement>(); leaves2.Add(itemStr1); leaves2.Add(itemUrl); leaves2.Add(itemF1); ServiceElement e2 = new ServiceElement(ElementType.ElementSequence, leaves2); // ServiceElement e1 = new ServiceElement(ElementType.ElementSequence, e2); // IList<ServiceElement> leaves0 = new List<ServiceElement>(); leaves0.Add(e1); leaves0.Add(itemStr2); leaves0.Add(itemF2); attrs.Add( new ServiceAttribute(0x0401, new ServiceElement(ElementType.ElementAlternative, leaves0))); return attrs; } [Test] public void TestCreateAVariousRecord() { ServiceRecord record = CreateAVariousRecord(); #if false TestWcLsnrBluetoothFactory f = new TestWcLsnrBluetoothFactory(); BluetoothFactory.SetFactory(f); //---- int port = 19; ServiceRecordHelper.SetRfcommChannelNumber(record, port); // ISdpService x0 = SdpService.CreateCustom(record); TestSdpService2 x = (TestSdpService2)x0; #endif TestWcLsnrBluetoothFactory f = new TestWcLsnrBluetoothFactory(); TestLsnrRfCommIf commIf = new TestLsnrRfCommIf(); f.queueIRfCommIf.Enqueue(commIf); TestLsnrRfcommPort port0 = new TestLsnrRfcommPort(); f.queueIRfCommPort.Enqueue(port0); BluetoothFactory.SetFactory(f); // port0.SetOpenServerResult(PORT_RETURN_CODE.SUCCESS); BluetoothListener lsnr = new BluetoothListener(BluetoothService.VideoSource, record); lsnr.Start(); int port = lsnr.LocalEndPoint.Port; lsnr.Stop(); // TestSdpService2 x = f.GetTestSdpService(); x.AssertCalls( // Well-known "AddServiceClassIdList: <00001400-0000-1000-8000-00805f9b34fb>" + NewLine + "AddRFCommProtocolDescriptor: " + port + NewLine // Eeeeeeech, how to detect all possible LangOffset_WellKnown strings!!!! + "AddAttribute: id: 0x0006, dt: DATA_ELE_SEQ, len: 9, val: " + "09-65-6E-" + "09-00-6A-" + "09-01-00" + NewLine + "AddAttribute: id: 0x0100, dt: TEXT_STR, len: 4, val: 61-6C-61-6E" + NewLine + "AddAttribute: id: 0x0401, dt: DATA_ELE_ALT, len: 66, val: " + "35-2F-35-2D-25-0C-61-62-63-64-C3-A9-66-67-68-C4-" + "AD-6A-45-1A-68-74-74-70-3A-2F-2F-65-78-61-6D-70-" + "6C-65-2E-63-6F-6D-2F-66-6F-6F-2E-74-78-74-09-FE-" + "12-25-0C-61-62-63-64-C3-A9-66-67-68-C4-AD-6A-09-" + "12-34" + NewLine + "AddAttribute: id: 0x4015, dt: UINT, len: 1, val: 15" + NewLine + "AddAttribute: id: 0x4016, dt: UINT, len: 2, val: 00-16" + NewLine + "AddAttribute: id: 0x4017, dt: UINT, len: 4, val: 00-00-00-17" + NewLine + "AddAttribute: id: 0x401E, dt: TWO_COMP_INT, len: 1, val: 1E" + NewLine + "AddAttribute: id: 0x401F, dt: TWO_COMP_INT, len: 2, val: 00-1F" + NewLine + "AddAttribute: id: 0x4020, dt: TWO_COMP_INT, len: 4, val: 00-00-00-20" + NewLine + "AddAttribute: id: 0x4028, dt: UUID, len: 2, val: 00-28" + NewLine + "AddAttribute: id: 0x4029, dt: UUID, len: 4, val: 00-00-00-29" + NewLine + "AddAttribute: id: 0x402A, dt: UUID, len: 16, val: 00-00-00-2A-00-00-10-00-80-00-00-80-5F-9B-34-FB" + NewLine + "AddAttribute: id: 0x402C, dt: BOOLEAN, len: 1, val: 01" + NewLine ); } const string NewLine = "\r\n"; } }
// 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.Concurrent; using System.Collections.Generic; using System.Composition; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.FindSymbols.SymbolTree; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.NavigateTo; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.SolutionCrawler; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.IncrementalCaches { /// <summary> /// Features like add-using want to be able to quickly search symbol indices for projects and /// metadata. However, creating those indices can be expensive. As such, we don't want to /// construct them during the add-using process itself. Instead, we expose this type as an /// Incremental-Analyzer to walk our projects/metadata in the background to keep the indices /// up to date. /// /// We also then export this type as a service that can give back the index for a project or /// metadata dll on request. If the index has been produced then it will be returned and /// can be used by add-using. Otherwise, nothing is returned and no results will be found. /// /// This means that as the project is being indexed, partial results may be returned. However /// once it is fully indexed, then total results will be returned. /// </summary> [Shared] [ExportIncrementalAnalyzerProvider(nameof(SymbolTreeInfoIncrementalAnalyzerProvider), new[] { WorkspaceKind.Host, WorkspaceKind.RemoteWorkspace })] [ExportWorkspaceServiceFactory(typeof(ISymbolTreeInfoCacheService))] internal class SymbolTreeInfoIncrementalAnalyzerProvider : IIncrementalAnalyzerProvider, IWorkspaceServiceFactory { private struct MetadataInfo { /// <summary> /// Can't be null. Even if we weren't able to read in metadata, we'll still create an empty /// index. /// </summary> public readonly SymbolTreeInfo SymbolTreeInfo; /// <summary> /// Note: the Incremental-Analyzer infrastructure guarantees that it will call all the methods /// on <see cref="IncrementalAnalyzer"/> in a serial fashion. As that is the only type that /// reads/writes these <see cref="MetadataInfo"/> objects, we don't need to lock this. /// </summary> public readonly HashSet<ProjectId> ReferencingProjects; public MetadataInfo(SymbolTreeInfo info, HashSet<ProjectId> referencingProjects) { Contract.ThrowIfNull(info); SymbolTreeInfo = info; ReferencingProjects = referencingProjects; } } // Concurrent dictionaries so they can be read from the SymbolTreeInfoCacheService while // they are being populated/updated by the IncrementalAnalyzer. private readonly ConcurrentDictionary<ProjectId, SymbolTreeInfo> _projectToInfo = new ConcurrentDictionary<ProjectId, SymbolTreeInfo>(); private readonly ConcurrentDictionary<string, MetadataInfo> _metadataPathToInfo = new ConcurrentDictionary<string, MetadataInfo>(); public IIncrementalAnalyzer CreateIncrementalAnalyzer(Workspace workspace) { var cacheService = workspace.Services.GetService<IWorkspaceCacheService>(); if (cacheService != null) { cacheService.CacheFlushRequested += OnCacheFlushRequested; } return new IncrementalAnalyzer(_projectToInfo, _metadataPathToInfo); } private void OnCacheFlushRequested(object sender, EventArgs e) { // If we hear about low memory conditions, flush our caches. This will degrade the // experience a bit (as we will no longer offer to Add-Using for p2p refs/metadata), // but will be better than OOM'ing. These caches will be regenerated in the future // when the incremental analyzer reanalyzers the projects in teh workspace. _projectToInfo.Clear(); _metadataPathToInfo.Clear(); } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => new SymbolTreeInfoCacheService(_projectToInfo, _metadataPathToInfo); private static string GetReferenceKey(PortableExecutableReference reference) => reference.FilePath ?? reference.Display; private class SymbolTreeInfoCacheService : ISymbolTreeInfoCacheService { private readonly ConcurrentDictionary<ProjectId, SymbolTreeInfo> _projectToInfo; private readonly ConcurrentDictionary<string, MetadataInfo> _metadataPathToInfo; public SymbolTreeInfoCacheService( ConcurrentDictionary<ProjectId, SymbolTreeInfo> projectToInfo, ConcurrentDictionary<string, MetadataInfo> metadataPathToInfo) { _projectToInfo = projectToInfo; _metadataPathToInfo = metadataPathToInfo; } public async Task<SymbolTreeInfo> TryGetMetadataSymbolTreeInfoAsync( Solution solution, PortableExecutableReference reference, CancellationToken cancellationToken) { var checksum = SymbolTreeInfo.GetMetadataChecksum(solution, reference, cancellationToken); var key = GetReferenceKey(reference); if (key != null) { if (_metadataPathToInfo.TryGetValue(key, out var metadataInfo) && metadataInfo.SymbolTreeInfo.Checksum == checksum) { return metadataInfo.SymbolTreeInfo; } } // If we didn't have it in our cache, see if we can load it from disk. // Note: pass 'loadOnly' so we only attempt to load from disk, not to actually // try to create the metadata. var info = await SymbolTreeInfo.GetInfoForMetadataReferenceAsync( solution, reference, checksum, loadOnly: true, cancellationToken: cancellationToken).ConfigureAwait(false); return info; } public async Task<SymbolTreeInfo> TryGetSourceSymbolTreeInfoAsync( Project project, CancellationToken cancellationToken) { if (_projectToInfo.TryGetValue(project.Id, out var projectInfo) && projectInfo.Checksum == await SymbolTreeInfo.GetSourceSymbolsChecksumAsync(project, cancellationToken).ConfigureAwait(false)) { return projectInfo; } return null; } } private class IncrementalAnalyzer : IncrementalAnalyzerBase { private readonly ConcurrentDictionary<ProjectId, SymbolTreeInfo> _projectToInfo; private readonly ConcurrentDictionary<string, MetadataInfo> _metadataPathToInfo; public IncrementalAnalyzer( ConcurrentDictionary<ProjectId, SymbolTreeInfo> projectToInfo, ConcurrentDictionary<string, MetadataInfo> metadataPathToInfo) { _projectToInfo = projectToInfo; _metadataPathToInfo = metadataPathToInfo; } public override Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, InvocationReasons reasons, CancellationToken cancellationToken) { if (!document.SupportsSyntaxTree) { // Not a language we can produce indices for (i.e. TypeScript). Bail immediately. return SpecializedTasks.EmptyTask; } if (bodyOpt != null) { // This was a method level edit. This can't change the symbol tree info // for this project. Bail immediately. return SpecializedTasks.EmptyTask; } return UpdateSymbolTreeInfoAsync(document.Project, cancellationToken); } public override Task AnalyzeProjectAsync(Project project, bool semanticsChanged, InvocationReasons reasons, CancellationToken cancellationToken) { return UpdateSymbolTreeInfoAsync(project, cancellationToken); } private async Task UpdateSymbolTreeInfoAsync(Project project, CancellationToken cancellationToken) { if (!project.SupportsCompilation) { // Not a language we can produce indices for (i.e. TypeScript). Bail immediately. return; } if (!RemoteFeatureOptions.ShouldComputeIndex(project.Solution.Workspace)) { return; } // Produce the indices for the source and metadata symbols in parallel. var projectTask = UpdateSourceSymbolTreeInfoAsync(project, cancellationToken); var referencesTask = UpdateReferencesAync(project, cancellationToken); await Task.WhenAll(projectTask, referencesTask).ConfigureAwait(false); } private async Task UpdateSourceSymbolTreeInfoAsync(Project project, CancellationToken cancellationToken) { var checksum = await SymbolTreeInfo.GetSourceSymbolsChecksumAsync(project, cancellationToken).ConfigureAwait(false); if (!_projectToInfo.TryGetValue(project.Id, out var projectInfo) || projectInfo.Checksum != checksum) { projectInfo = await SymbolTreeInfo.GetInfoForSourceAssemblyAsync( project, checksum, cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(projectInfo); Contract.ThrowIfTrue(projectInfo.Checksum != checksum, "If we computed a SymbolTreeInfo, then its checksum much match our checksum."); // Mark that we're up to date with this project. Future calls with the same // semantic version can bail out immediately. _projectToInfo.AddOrUpdate(project.Id, projectInfo, (_1, _2) => projectInfo); } } private Task UpdateReferencesAync(Project project, CancellationToken cancellationToken) { // Process all metadata references in parallel. var tasks = project.MetadataReferences.OfType<PortableExecutableReference>() .Select(r => UpdateReferenceAsync(project, r, cancellationToken)) .ToArray(); return Task.WhenAll(tasks); } private async Task UpdateReferenceAsync( Project project, PortableExecutableReference reference, CancellationToken cancellationToken) { var key = GetReferenceKey(reference); if (key == null) { return; } var checksum = SymbolTreeInfo.GetMetadataChecksum(project.Solution, reference, cancellationToken); if (!_metadataPathToInfo.TryGetValue(key, out var metadataInfo) || metadataInfo.SymbolTreeInfo.Checksum != checksum) { var info = await SymbolTreeInfo.GetInfoForMetadataReferenceAsync( project.Solution, reference, checksum, loadOnly: false, cancellationToken: cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(info); Contract.ThrowIfTrue(info.Checksum != checksum, "If we computed a SymbolTreeInfo, then its checksum much match our checksum."); // Note, getting the info may fail (for example, bogus metadata). That's ok. // We still want to cache that result so that don't try to continuously produce // this info over and over again. metadataInfo = new MetadataInfo(info, metadataInfo.ReferencingProjects ?? new HashSet<ProjectId>()); _metadataPathToInfo.AddOrUpdate(key, metadataInfo, (_1, _2) => metadataInfo); } // Keep track that this dll is referenced by this project. metadataInfo.ReferencingProjects.Add(project.Id); } public override void RemoveProject(ProjectId projectId) { _projectToInfo.TryRemove(projectId, out var info); RemoveMetadataReferences(projectId); } private void RemoveMetadataReferences(ProjectId projectId) { foreach (var kvp in _metadataPathToInfo.ToArray()) { if (kvp.Value.ReferencingProjects.Remove(projectId)) { if (kvp.Value.ReferencingProjects.Count == 0) { // This metadata dll isn't referenced by any project. We can just dump it. _metadataPathToInfo.TryRemove(kvp.Key, out var unneeded); } } } } } } }
/****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2017. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using Leap.Unity.Attributes; using System; using System.Collections; using System.Collections.Generic; #if UNITY_EDITOR using UnityEditor; #endif using UnityEngine; namespace Leap.Unity.Attachments { /// <summary> /// Add an GameObject with this script to your scene if you would like to have a /// Transform hierarchy that will follow various important points on a hand, whether /// for visuals or for logic. The AttachmentHands object will maintain two child /// objects, one for each of the player's hands. Use the Inspector to customize /// which points you'd like to see in the hierarchy beneath the individual /// AttachmentHand objects. /// </summary> [ExecuteInEditMode] public class AttachmentHands : MonoBehaviour { [SerializeField] private AttachmentPointFlags _attachmentPoints = AttachmentPointFlags.Palm | AttachmentPointFlags.Wrist; public AttachmentPointFlags attachmentPoints { get { return _attachmentPoints; } set { if (_attachmentPoints != value) { #if UNITY_EDITOR Undo.IncrementCurrentGroup(); Undo.SetCurrentGroupName("Modify Attachment Points"); Undo.RecordObject(this, "Modify AttachmentHands Points"); #endif _attachmentPoints = value; refreshAttachmentHandTransforms(); } } } private Func<Hand>[] _handAccessors; /// <summary> /// Gets or sets the functions used to get the latest Leap.Hand data for the corresponding /// AttachmentHand objects in the attachmentHands array. Modify this if you'd like to customize /// how hand data is sent to AttachmentHands; e.g. a networked multiplayer game receiving /// serialized hand data for a networked player representation. /// /// This array is automatically populated if it is null or empty during OnValidate() in the editor, /// but it can be modified freely afterwards. /// </summary> public Func<Hand>[] handAccessors { get { return _handAccessors; } set { _handAccessors = value; } } private AttachmentHand[] _attachmentHands; /// <summary> /// Gets or sets the array of AttachmentHand objects that this component manages. The length of this /// array should match the handAccessors array; corresponding-index slots in handAccessors will be /// used to assign transform data to the AttachmentHand objects in this component's Update(). /// /// This array is automatically populated if it is null or empty during OnValidate() in the editor, /// but can be modified freely afterwards. /// </summary> public AttachmentHand[] attachmentHands { get { return _attachmentHands; } set { _attachmentHands = value; } } #if UNITY_EDITOR void OnValidate() { if (getIsPrefab()) return; reinitialize(); } #endif void Awake() { #if UNITY_EDITOR if (getIsPrefab()) return; #endif reinitialize(); } private void reinitialize() { refreshHandAccessors(); refreshAttachmentHands(); #if UNITY_EDITOR EditorApplication.delayCall += refreshAttachmentHandTransforms; #else refreshAttachmentHandTransforms(); #endif } void Update() { #if UNITY_EDITOR PrefabType prefabType = PrefabUtility.GetPrefabType(this.gameObject); if (prefabType == PrefabType.Prefab || prefabType == PrefabType.ModelPrefab) { return; } #endif bool requiresReinitialization = false; using (new ProfilerSample("Attachment Hands Update", this.gameObject)) { for (int i = 0; i < _attachmentHands.Length; i++) { var attachmentHand = attachmentHands[i]; if (attachmentHand == null) { requiresReinitialization = true; break; } var leapHand = handAccessors[i](); attachmentHand.isTracked = leapHand != null; #if UNITY_EDITOR if (Hands.Provider != null) { if (leapHand == null && !Application.isPlaying) { leapHand = Hands.Provider.MakeTestHand(attachmentHand.chirality == Chirality.Left); } } #endif using (new ProfilerSample(attachmentHand.gameObject.name + " Update Points")) { foreach (var point in attachmentHand.points) { point.SetTransformUsingHand(leapHand); } } } if (requiresReinitialization) { reinitialize(); } } } private void refreshHandAccessors() { // If necessary, generate a left-hand and right-hand set of accessors. if (_handAccessors == null || _handAccessors.Length == 0) { _handAccessors = new Func<Hand>[2]; _handAccessors[0] = new Func<Hand>(() => { return Hands.Left; }); _handAccessors[1] = new Func<Hand>(() => { return Hands.Right; }); } } private void refreshAttachmentHands() { // If we're a prefab, we'll be unable to set parent transforms, so we shouldn't create new objects in general. bool isPrefab = false; #if UNITY_EDITOR isPrefab = getIsPrefab(); #endif // If necessary, generate a left and right AttachmentHand. if (_attachmentHands == null || _attachmentHands.Length == 0 || (_attachmentHands[0] == null || _attachmentHands[1] == null)) { _attachmentHands = new AttachmentHand[2]; // Try to use existing AttachmentHand objects first. foreach (Transform child in this.transform.GetChildren()) { var attachmentHand = child.GetComponent<AttachmentHand>(); if (attachmentHand != null) { _attachmentHands[attachmentHand.chirality == Chirality.Left ? 0 : 1] = attachmentHand; } } // If we are a prefab and there are missing AttachmentHands, we have to return early. // We can't set parent transforms while a prefab. We're only OK if we already have attachmentHand // objects and their parents are properly set. if (isPrefab && (_attachmentHands[0] == null || _attachmentHands[0].transform.parent != this.transform || _attachmentHands[1] == null || _attachmentHands[1].transform.parent != this.transform)) { return; } // Construct any missing AttachmentHand objects. if (_attachmentHands[0] == null) { GameObject obj = new GameObject(); #if UNITY_EDITOR Undo.RegisterCreatedObjectUndo(obj, "Created GameObject"); #endif _attachmentHands[0] = obj.AddComponent<AttachmentHand>(); _attachmentHands[0].chirality = Chirality.Left; } _attachmentHands[0].gameObject.name = "Attachment Hand (Left)"; if (_attachmentHands[0].transform.parent != this.transform) _attachmentHands[0].transform.parent = this.transform; if (_attachmentHands[1] == null) { GameObject obj = new GameObject(); #if UNITY_EDITOR Undo.RegisterCreatedObjectUndo(obj, "Created GameObject"); #endif _attachmentHands[1] = obj.AddComponent<AttachmentHand>(); _attachmentHands[1].chirality = Chirality.Right; } _attachmentHands[1].gameObject.name = "Attachment Hand (Right)"; if (_attachmentHands[1].transform.parent != this.transform) _attachmentHands[1].transform.parent = this.transform; // Organize left hand first in sibling order. _attachmentHands[0].transform.SetSiblingIndex(0); _attachmentHands[1].transform.SetSiblingIndex(1); } } private void refreshAttachmentHandTransforms() { if (this == null) return; #if UNITY_EDITOR if (getIsPrefab()) return; #endif bool requiresReinitialization = false; if (_attachmentHands == null) { requiresReinitialization = true; } else { foreach (var hand in _attachmentHands) { if (hand == null) { // AttachmentHand must have been destroyed requiresReinitialization = true; break; } hand.refreshAttachmentTransforms(_attachmentPoints); } #if UNITY_EDITOR EditorUtility.SetDirty(this); #endif } if (requiresReinitialization) { reinitialize(); } } #if UNITY_EDITOR private bool getIsPrefab() { PrefabType prefabType = PrefabUtility.GetPrefabType(this.gameObject); return (prefabType == PrefabType.Prefab || prefabType == PrefabType.ModelPrefab); } #endif } }
using System; namespace Aardvark.Base { public enum Metric { Manhattan = 1, Euclidean = 2, Maximum = int.MaxValue, L1 = Manhattan, L2 = Euclidean, LInfinity = Maximum, } public static class Constant<T> { /// <summary> /// A value that is or is close to the minimum value of the type, but /// can be parsed back without exception. /// </summary> public static readonly T ParseableMinValue; /// <summary> /// A value that is or is close to the maximum value of the type, but /// can be parsed back without exception. /// </summary> public static readonly T ParseableMaxValue; /// <summary> /// The smallest value that can be added to 1.0 for obtaining a result /// that is different from 1.0. /// </summary> public static readonly T MachineEpsilon; /// <summary> /// Four times the MachineEpsilon of the type. /// </summary> public static readonly T PositiveTinyValue; /// <summary> /// Minus four times the MachineEpsilon of the type. /// </summary> public static readonly T NegativeTinyValue; private static volatile float floatStore; static Constant() { // Console.WriteLine("initializing {0}", typeof(T).Name); if (typeof(T) == typeof(byte)) { ParseableMinValue = (T)(object)byte.MinValue; ParseableMinValue = (T)(object)byte.MinValue; ParseableMaxValue = (T)(object)byte.MaxValue; MachineEpsilon = (T)(object)(byte)1; PositiveTinyValue = (T)(object)(byte)4; } else if (typeof(T) == typeof(ushort)) { ParseableMinValue = (T)(object)ushort.MinValue; ParseableMaxValue = (T)(object)ushort.MaxValue; MachineEpsilon = (T)(object)(ushort)1; PositiveTinyValue = (T)(object)(ushort)4; } else if (typeof(T) == typeof(uint)) { ParseableMinValue = (T)(object)uint.MinValue; ParseableMaxValue = (T)(object)uint.MaxValue; MachineEpsilon = (T)(object)(uint)1; PositiveTinyValue = (T)(object)(uint)4; } else if (typeof(T) == typeof(ulong)) { ParseableMinValue = (T)(object)ulong.MinValue; ParseableMaxValue = (T)(object)ulong.MaxValue; MachineEpsilon = (T)(object)(ulong)1; PositiveTinyValue = (T)(object)(ulong)4; } else if (typeof(T) == typeof(sbyte)) { ParseableMinValue = (T)(object)sbyte.MinValue; ParseableMaxValue = (T)(object)sbyte.MaxValue; MachineEpsilon = (T)(object)(sbyte)1; PositiveTinyValue = (T)(object)(sbyte)4; NegativeTinyValue = (T)(object)(sbyte)-4; } else if (typeof(T) == typeof(short)) { ParseableMinValue = (T)(object)short.MinValue; ParseableMaxValue = (T)(object)short.MaxValue; MachineEpsilon = (T)(object)(short)1; PositiveTinyValue = (T)(object)(short)4; NegativeTinyValue = (T)(object)(short)-4; } else if (typeof(T) == typeof(int)) { ParseableMinValue = (T)(object)int.MinValue; ParseableMaxValue = (T)(object)int.MaxValue; MachineEpsilon = (T)(object)1; PositiveTinyValue = (T)(object)4; NegativeTinyValue = (T)(object)-4; } else if (typeof(T) == typeof(long)) { ParseableMinValue = (T)(object)long.MinValue; ParseableMaxValue = (T)(object)long.MaxValue; MachineEpsilon = (T)(object)1L; PositiveTinyValue = (T)(object)4L; NegativeTinyValue = (T)(object)-4L; } else if (typeof(T) == typeof(float)) { ParseableMinValue = (T)(object)(float.MinValue * 0.999999f); ParseableMaxValue = (T)(object)(float.MaxValue * 0.999999f); floatStore = 2.0f; float floatEps = 1.0f; while (floatStore > 1.0f) { floatEps /= 2; floatStore = floatEps + 1.0f; } MachineEpsilon = (T)(object)(2 * floatEps); PositiveTinyValue = (T)(object)(8 * floatEps); NegativeTinyValue = (T)(object)(-8 * floatEps); } else if (typeof(T) == typeof(double)) { ParseableMinValue = (T)(object)(double.MinValue * 0.999999995); ParseableMaxValue = (T)(object)(double.MaxValue * 0.999999995); double doubleStore = 2.0; double doubleEps = 1.0; while (doubleStore > 1.0) { doubleEps /= 2; doubleStore = doubleEps + 1.0; } MachineEpsilon = (T)(object)(2 * doubleEps); PositiveTinyValue = (T)(object)(8 * doubleEps); NegativeTinyValue = (T)(object)(-8 * doubleEps); } } } static class Constants { [OnAardvarkInit] public static void Init() { var ignore1 = Constant<double>.MachineEpsilon; var ignore2 = Constant<float>.MachineEpsilon; var ignore3 = Constant<byte>.MachineEpsilon; var ignore4 = Constant<sbyte>.MachineEpsilon; var ignore5 = Constant<short>.MachineEpsilon; var ignore6 = Constant<ushort>.MachineEpsilon; var ignore7 = Constant<uint>.MachineEpsilon; var ignore8 = Constant<int>.MachineEpsilon; var ignore9 = Constant<long>.MachineEpsilon; var ignore0 = Constant<ulong>.MachineEpsilon; } } /// <summary> /// Mathematical constants. /// </summary> public static class Constant { /// <summary> /// Ratio of a circle's circumference to its diameter /// in Euclidean geometry. Also known as Archimedes' constant. /// </summary> public const double Pi = 3.1415926535897932384626433832795; /// <summary> /// One divided by Pi (1 / Pi). /// </summary> public const double PiInv = 0.318309886183790671537767526745028724068919291480912897495; /// <summary> /// Ratio of a circle's circumference to its diameter as float /// in Euclidean geometry. Also known as Archimedes' constant. /// </summary> [Obsolete("Use ConstantF.Pi instead")] public const float PiF = (float)Pi; /// <summary> /// Two times PI: the circumference of the unit circle. /// </summary> public const double PiTimesTwo = 6.283185307179586476925286766559; /// <summary> /// Three times PI. /// </summary> public const double PiTimesThree = 9.424777960769379715387930149839; /// <summary> /// Four times PI: the surface area of the unit sphere. /// </summary> public const double PiTimesFour = 12.56637061435917295385057353312; /// <summary> /// Half of PI. /// </summary> public const double PiHalf = 1.570796326794896619231321691640; /// <summary> /// Quarter of PI. /// </summary> public const double PiQuarter = 0.78539816339744830961566084581988; /// <summary> /// Square of PI. /// </summary> public const double PiSquared = 9.869604401089358618834490999876; /// <summary> /// Sqrt(2 * PI). /// </summary> public const double SqrtPiTimesTwo = 2.5066282746310005024157652848110; /// <summary> /// Base of the natural logarithm. /// Also known as Euler's number. /// </summary> public const double E = Math.E; /// <summary> /// Golden Ratio. /// The golden ratio expresses the relationship that /// the sum of two quantities is to the larger quantity /// as the larger is to the smaller. /// It is defined as (1 + sqrt(5)) / 2). /// </summary> public const double Phi = 1.61803398874989484820458683; /// <summary> /// Square root of 2. /// </summary> public const double Sqrt2 = 1.414213562373095048801688724209; /// <summary> /// Square root of 0.5. /// </summary> public const double Sqrt2Half = 0.70710678118654752440084436210485; /// <summary> /// Square root of 0.5. /// </summary> [Obsolete("Use ConstantF.Sqrt2Half instead")] public const float Sqrt2HalfF = (float)Sqrt2Half; /// <summary> /// Square root of 3. /// </summary> public const double Sqrt3 = 1.732050807568877293527446341505; /// <summary> /// Square root of 5. /// </summary> public const double Sqrt5 = 2.236067977499789696409173668731; /// <summary> /// Natural logarithm (base e) of 2. /// </summary> public const double Ln2 = 0.69314718055994530941723212145818; /// <summary> /// Natural logarithm (base e) of 2 as float. /// </summary> [Obsolete("Use ConstantF.Ln2 instead")] public const float Ln2F = (float)Ln2; /// <summary> /// 1 divided by logarithm of 2 (base e). /// </summary> public const double Ln2Inv = 1.4426950408889634073599246810023; /// <summary> /// 1 divided by logarithm of 2 (base e) as float. /// </summary> [Obsolete("Use ConstantF.Ln2Inv instead")] public const float Ln2InvF = (float)Ln2Inv; /// <summary> /// 1 divided by 3. /// </summary> public const double OneThird = 0.33333333333333333333333333333333; /// <summary> /// 1 divided by 3. /// </summary> [Obsolete("Use ConstantF.OneThird instead")] public const double OneThirdF = (float)OneThird; /// <summary> /// Used to convert degrees to radians. /// See also <see cref="Conversion"/> class. /// </summary> public const double RadiansPerDegree = Pi / 180.0; /// <summary> /// Used to convert radians to degrees. /// See also <see cref="Conversion"/> class. /// </summary> public const double DegreesPerRadian = 180.0 / Pi; /// <summary> /// Used to convert gons to radians. /// See also <see cref="Conversion"/> class. /// </summary> public const double RadiansPerGon = Pi / 200.0; /// <summary> /// Used to convert radians to gons. /// See also <see cref="Conversion"/> class. /// </summary> public const double GonsPerRadian = 200.0 / Pi; /// <summary> /// Used to convert gons to degrees. /// See also <see cref="Conversion"/> class. /// </summary> public const double DegreesPerGon = 180.0 / 200.0; /// <summary> /// Used to convert degrees to gons. /// See also <see cref="Conversion"/> class. /// </summary> public const double GonsPerDegree = 200.0 / 180.0; /// <summary> /// One sixtieth (1/60) of one degree (in radians). /// </summary> public const double ArcMinute = Pi / (180 * 60); /// <summary> /// One sixtieth (1/60) of one arc minute (in radians). /// </summary> public const double ArcSecond = Pi / (180 * 60 * 60); /// <summary> /// The speed of light in meters per second. /// </summary> public const double SpeedOfLight = 299792458.0; } /// <summary> /// Mathematical constants. /// </summary> public static class ConstantF { /// <summary> /// Ratio of a circle's circumference to its diameter /// in Euclidean geometry. Also known as Archimedes' constant. /// </summary> public const float Pi = (float)Constant.Pi; /// <summary> /// One divided by Pi (1 / Pi). /// </summary> public const float PiInv = (float)Constant.PiInv; /// <summary> /// Two times PI: the circumference of the unit circle. /// </summary> public const float PiTimesTwo = (float)Constant.PiTimesTwo; /// <summary> /// Twree times PI. /// </summary> public const float PiTimesThree = (float)Constant.PiTimesThree; /// <summary> /// Four times PI: the surface area of the unit sphere. /// </summary> public const float PiTimesFour = (float)Constant.PiTimesFour; /// <summary> /// Half of PI. /// </summary> public const float PiHalf = (float)Constant.PiHalf; /// <summary> /// Quarter of PI. /// </summary> public const float PiQuarter = (float)Constant.PiQuarter; /// <summary> /// Square of PI. /// </summary> public const float PiSquared = (float)Constant.PiSquared; /// <summary> /// Sqrt(2 * PI). /// </summary> public const float SqrtPiTimesTwo = (float)Constant.SqrtPiTimesTwo; /// <summary> /// Base of the natural logarithm. /// Also known as Euler's number. /// </summary> public const float E = (float)Constant.E; /// <summary> /// Golden Ratio. /// The golden ratio expresses the relationship that /// the sum of two quantities is to the larger quantity /// as the larger is to the smaller. /// It is defined as (1 + sqrt(5)) / 2). /// </summary> public const float Phi = (float)Constant.Phi; /// <summary> /// Square root of 2. /// </summary> public const float Sqrt2 = (float)Constant.Sqrt2; /// <summary> /// Square root of 0.5. /// </summary> public const float Sqrt2Half = (float)Constant.Sqrt2Half; /// <summary> /// Square root of 3. /// </summary> public const float Sqrt3 = (float)Constant.Sqrt3; /// <summary> /// Square root of 5. /// </summary> public const float Sqrt5 = (float)Constant.Sqrt5; /// <summary> /// Natural logarithm (base e) of 2. /// </summary> public const float Ln2 = (float)Constant.Ln2; /// <summary> /// 1 divided by logarithm of 2 (base e). /// </summary> public const float Ln2Inv = (float)Constant.Ln2Inv; /// <summary> /// 1 divided by 3. /// </summary> public const float OneThird = (float)Constant.OneThird; /// <summary> /// Used to convert degrees to radians. /// See also <see cref="Conversion"/> class. /// </summary> public const float RadiansPerDegree = (float)Constant.RadiansPerDegree; /// <summary> /// Used to convert radians to degrees. /// See also <see cref="Conversion"/> class. /// </summary> public const float DegreesPerRadian = (float)Constant.DegreesPerRadian; /// <summary> /// Used to convert gons to radians. /// See also <see cref="Conversion"/> class. /// </summary> public const float RadiansPerGon = (float)Constant.RadiansPerGon; /// <summary> /// Used to convert radians to gons. /// See also <see cref="Conversion"/> class. /// </summary> public const float GonsPerRadian = (float)Constant.GonsPerRadian; /// <summary> /// Used to convert gons to degrees. /// See also <see cref="Conversion"/> class. /// </summary> public const float DegreesPerGon = (float)Constant.DegreesPerGon; /// <summary> /// Used to convert degrees to gons. /// See also <see cref="Conversion"/> class. /// </summary> public const float GonsPerDegree = (float)Constant.GonsPerDegree; /// <summary> /// One sixtieth (1/60) of one degree (in radians). /// </summary> public const float ArcMinute = (float)Constant.ArcMinute; /// <summary> /// One sixtieth (1/60) of one arc minute (in radians). /// </summary> public const float ArcSecond = (float)Constant.ArcSecond; /// <summary> /// The speed of light in meters per second. /// </summary> public const float SpeedOfLight = (float)Constant.SpeedOfLight; } }
namespace PrimerProForms { partial class FormBuildableWordsTD { /// <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() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormBuildableWordsTD)); this.labTitle = new System.Windows.Forms.Label(); this.tbHighlights = new System.Windows.Forms.TextBox(); this.tbGraphemes = new System.Windows.Forms.TextBox(); this.labGrapheme = new System.Windows.Forms.Label(); this.btnCancel = new System.Windows.Forms.Button(); this.btnOK = new System.Windows.Forms.Button(); this.chkParaFmt = new System.Windows.Forms.CheckBox(); this.btnGraphemes = new System.Windows.Forms.Button(); this.btnHighlight = new System.Windows.Forms.Button(); this.labHighlight = new System.Windows.Forms.Label(); this.chkNoDup = new System.Windows.Forms.CheckBox(); this.SuspendLayout(); // // labTitle // this.labTitle.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labTitle.Location = new System.Drawing.Point(90, 13); this.labTitle.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.labTitle.Name = "labTitle"; this.labTitle.Size = new System.Drawing.Size(510, 46); this.labTitle.TabIndex = 0; this.labTitle.Text = "List only graphemes (consonants and vowels) which have been taught. The grapheme" + "s should be separated by a space. (e.g. p b m mp mb mpw mbw a e i o u aa)"; // // tbHighlights // this.tbHighlights.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.tbHighlights.Location = new System.Drawing.Point(322, 106); this.tbHighlights.Margin = new System.Windows.Forms.Padding(2); this.tbHighlights.Name = "tbHighlights"; this.tbHighlights.Size = new System.Drawing.Size(188, 21); this.tbHighlights.TabIndex = 5; // // tbGraphemes // this.tbGraphemes.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.tbGraphemes.Location = new System.Drawing.Point(93, 68); this.tbGraphemes.Margin = new System.Windows.Forms.Padding(2); this.tbGraphemes.Name = "tbGraphemes"; this.tbGraphemes.Size = new System.Drawing.Size(418, 21); this.tbGraphemes.TabIndex = 2; // // labGrapheme // this.labGrapheme.AutoEllipsis = true; this.labGrapheme.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labGrapheme.Location = new System.Drawing.Point(18, 68); this.labGrapheme.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.labGrapheme.Name = "labGrapheme"; this.labGrapheme.Size = new System.Drawing.Size(78, 20); this.labGrapheme.TabIndex = 1; this.labGrapheme.Text = "Graphemes"; // // btnCancel // this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnCancel.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnCancel.Location = new System.Drawing.Point(589, 195); this.btnCancel.Margin = new System.Windows.Forms.Padding(2); this.btnCancel.Name = "btnCancel"; this.btnCancel.Size = new System.Drawing.Size(75, 26); this.btnCancel.TabIndex = 9; this.btnCancel.Text = "Cancel"; this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); // // btnOK // this.btnOK.DialogResult = System.Windows.Forms.DialogResult.OK; this.btnOK.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnOK.Location = new System.Drawing.Point(499, 195); this.btnOK.Margin = new System.Windows.Forms.Padding(2); this.btnOK.Name = "btnOK"; this.btnOK.Size = new System.Drawing.Size(75, 26); this.btnOK.TabIndex = 8; this.btnOK.Text = "OK"; this.btnOK.Click += new System.EventHandler(this.btnOK_Click); // // chkParaFmt // this.chkParaFmt.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.chkParaFmt.Location = new System.Drawing.Point(93, 150); this.chkParaFmt.Margin = new System.Windows.Forms.Padding(2); this.chkParaFmt.Name = "chkParaFmt"; this.chkParaFmt.Size = new System.Drawing.Size(204, 20); this.chkParaFmt.TabIndex = 7; this.chkParaFmt.Text = "Display in &paragraph format"; this.chkParaFmt.CheckedChanged += new System.EventHandler(this.chkParaFmt_CheckedChanged); // // btnGraphemes // this.btnGraphemes.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnGraphemes.Location = new System.Drawing.Point(525, 68); this.btnGraphemes.Margin = new System.Windows.Forms.Padding(2); this.btnGraphemes.Name = "btnGraphemes"; this.btnGraphemes.Size = new System.Drawing.Size(135, 26); this.btnGraphemes.TabIndex = 3; this.btnGraphemes.Text = "Item Selection"; this.btnGraphemes.UseVisualStyleBackColor = true; this.btnGraphemes.Click += new System.EventHandler(this.btnGraphemes_Click); // // btnHighlight // this.btnHighlight.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnHighlight.Location = new System.Drawing.Point(525, 106); this.btnHighlight.Margin = new System.Windows.Forms.Padding(2); this.btnHighlight.Name = "btnHighlight"; this.btnHighlight.Size = new System.Drawing.Size(135, 26); this.btnHighlight.TabIndex = 6; this.btnHighlight.Text = "Item Selection"; this.btnHighlight.UseVisualStyleBackColor = true; this.btnHighlight.Click += new System.EventHandler(this.btnHighlight_Click); // // labHighlight // this.labHighlight.AutoEllipsis = true; this.labHighlight.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labHighlight.Location = new System.Drawing.Point(18, 105); this.labHighlight.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.labHighlight.Name = "labHighlight"; this.labHighlight.Size = new System.Drawing.Size(278, 20); this.labHighlight.TabIndex = 4; this.labHighlight.Text = "Highlight words with these graphemes"; this.labHighlight.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // chkNoDup // this.chkNoDup.AutoSize = true; this.chkNoDup.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.chkNoDup.Location = new System.Drawing.Point(93, 195); this.chkNoDup.Margin = new System.Windows.Forms.Padding(2); this.chkNoDup.Name = "chkNoDup"; this.chkNoDup.Size = new System.Drawing.Size(103, 19); this.chkNoDup.TabIndex = 10; this.chkNoDup.Text = "No Duplicates"; this.chkNoDup.UseVisualStyleBackColor = true; this.chkNoDup.CheckedChanged += new System.EventHandler(this.chkNoDup_CheckedChanged); // // FormBuildableWordsTD // this.AcceptButton = this.btnOK; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.btnCancel; this.ClientSize = new System.Drawing.Size(676, 230); this.Controls.Add(this.chkNoDup); this.Controls.Add(this.labHighlight); this.Controls.Add(this.btnHighlight); this.Controls.Add(this.btnGraphemes); this.Controls.Add(this.chkParaFmt); this.Controls.Add(this.tbHighlights); this.Controls.Add(this.tbGraphemes); this.Controls.Add(this.labGrapheme); this.Controls.Add(this.btnCancel); this.Controls.Add(this.btnOK); this.Controls.Add(this.labTitle); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Margin = new System.Windows.Forms.Padding(2); this.Name = "FormBuildableWordsTD"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Buildable Words Search"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label labTitle; private System.Windows.Forms.TextBox tbHighlights; private System.Windows.Forms.TextBox tbGraphemes; private System.Windows.Forms.Label labGrapheme; private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.Button btnOK; private System.Windows.Forms.CheckBox chkParaFmt; private System.Windows.Forms.Button btnGraphemes; private System.Windows.Forms.Button btnHighlight; private System.Windows.Forms.Label labHighlight; private System.Windows.Forms.CheckBox chkNoDup; } }
using System; using System.Collections.Generic; using System.Diagnostics; using ALinq.Mapping; using System.Data.SqlClient; using System.Globalization; using System.Reflection; using System.Text; namespace ALinq.SqlClient { internal abstract class SqlFormatter : DbFormatter { protected SqlFormatter(SqlProvider sqlProvider) : base(sqlProvider) { } internal override Visitor CreateVisitor() { return new Visitor(); } // Nested Types private class AliasMapper : SqlVisitor { // Fields private Dictionary<SqlColumn, SqlAlias> aliasMap; private SqlAlias currentAlias; // Methods internal AliasMapper(Dictionary<SqlColumn, SqlAlias> aliasMap) { this.aliasMap = aliasMap; } internal override SqlAlias VisitAlias(SqlAlias a) { SqlAlias currentAlias = this.currentAlias; this.currentAlias = a; base.VisitAlias(a); this.currentAlias = currentAlias; return a; } internal override SqlExpression VisitColumn(SqlColumn col) { this.aliasMap[col] = this.currentAlias; this.Visit(col.Expression); return col; } internal override SqlRow VisitRow(SqlRow row) { foreach (SqlColumn column in row.Columns) { this.VisitColumn(column); } return row; } internal override SqlTable VisitTable(SqlTable tab) { foreach (SqlColumn column in tab.Columns) { this.VisitColumn(column); } return tab; } internal override SqlExpression VisitTableValuedFunctionCall(SqlTableValuedFunctionCall fc) { foreach (SqlColumn column in fc.Columns) { this.VisitColumn(column); } return fc; } } internal class Visitor : SqlVisitor { // Fields protected internal Dictionary<SqlColumn, SqlAlias> aliasMap = new Dictionary<SqlColumn, SqlAlias>(); protected internal int depth; protected internal bool isDebugMode; protected internal Dictionary<SqlNode, string> names = new Dictionary<SqlNode, string>(); protected internal bool parenthesizeTop; protected internal StringBuilder sb; protected internal List<SqlSource> suppressedAliases = new List<SqlSource>(); private SqlIdentifier sqlIdentifier; // Methods public Visitor() { //this.sqlIdentity = sqlIdentity; } internal SqlIdentifier SqlIdentifier { get { if (sqlIdentifier == null) sqlIdentifier = new ALinq.SqlClient.MsSqlIdentifier(); return sqlIdentifier; } set { sqlIdentifier = value; } } internal virtual string EscapeSingleQuotes(string str) { if (str.IndexOf('\'') < 0) { return str; } var builder = new StringBuilder(); foreach (char ch in str) { if (ch == '\'') { builder.Append("''"); } else { builder.Append("'"); } } return builder.ToString(); } public string Format(SqlNode node) { return this.Format(node, false); } public string Format(SqlNode node, bool isDebug) { this.sb = new StringBuilder(); this.isDebugMode = isDebug; this.aliasMap.Clear(); if (isDebug) { new SqlFormatter.AliasMapper(this.aliasMap).Visit(node); } this.Visit(node); return this.sb.ToString(); } private void FormatType(IProviderType type) { this.sb.Append(type.ToQueryString()); } public virtual void FormatValue(object value) { if (value == null) { this.sb.Append("NULL"); } else { Type type = value.GetType(); if (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(Nullable<>))) { type = type.GetGenericArguments()[0]; } switch (Type.GetTypeCode(type)) { case TypeCode.Object: if (!(value is Guid)) { Type type2 = value as Type; if (type2 != null) { if (this.isDebugMode) { this.sb.Append("typeof("); this.sb.Append(type2.Name); this.sb.Append(")"); return; } this.FormatValue(""); return; } break; } this.sb.Append("'"); this.sb.Append(value); this.sb.Append("'"); return; case TypeCode.Boolean: this.sb.Append(this.GetBoolValue((bool)value)); return; case TypeCode.Char: case TypeCode.DateTime: case TypeCode.String: this.sb.Append("'"); this.sb.Append(this.EscapeSingleQuotes(value.ToString())); this.sb.Append("'"); return; case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: this.sb.Append(value); return; } if (!this.isDebugMode) { throw Error.ValueHasNoLiteralInSql(value); } this.sb.Append("value("); this.sb.Append(value.ToString()); this.sb.Append(")"); } } internal virtual string GetBoolValue(bool value) { if (!value) { return "0"; } return "1"; } public virtual string GetOperator(SqlNodeType nt) { switch (nt) { case SqlNodeType.Add: return "+"; case SqlNodeType.And: return "AND"; case SqlNodeType.Avg: return "AVG"; case SqlNodeType.BitAnd: return "&"; case SqlNodeType.BitNot: return "~"; case SqlNodeType.BitOr: return "|"; case SqlNodeType.BitXor: return "^"; case SqlNodeType.ClrLength: return "CLRLENGTH"; case SqlNodeType.Concat: return "+"; case SqlNodeType.Count: return "COUNT"; case SqlNodeType.Covar: return "COVAR"; case SqlNodeType.EQ: return "="; case SqlNodeType.EQ2V: return "="; case SqlNodeType.IsNotNull: return "IS NOT NULL"; case SqlNodeType.IsNull: return "IS NULL"; case SqlNodeType.LE: return "<="; case SqlNodeType.LongCount: switch (this.Mode) { case SqlProvider.ProviderMode.Sql2000: case SqlProvider.ProviderMode.Sql2005: case SqlProvider.ProviderMode.SqlCE: return "COUNT_BIG"; default: return "COUNT"; } case SqlNodeType.LT: return "<"; case SqlNodeType.GE: return ">="; case SqlNodeType.GT: return ">"; case SqlNodeType.Max: return "MAX"; case SqlNodeType.Min: return "MIN"; case SqlNodeType.Mod: return "%"; case SqlNodeType.Mul: return "*"; case SqlNodeType.NE: return "<>"; case SqlNodeType.NE2V: return "<>"; case SqlNodeType.Negate: return "-"; case SqlNodeType.Not: return "NOT"; case SqlNodeType.Not2V: return "NOT"; case SqlNodeType.Or: return "OR"; case SqlNodeType.Div: return "/"; case SqlNodeType.Stddev: return "STDEV"; case SqlNodeType.Sub: return "-"; case SqlNodeType.Sum: return "SUM"; } throw Error.InvalidFormatNode(nt); } protected virtual string InferName(SqlExpression exp, string def) { if (exp == null) { return null; } SqlNodeType nodeType = exp.NodeType; switch (nodeType) { case SqlNodeType.Column: return ((SqlColumn)exp).Name; case SqlNodeType.ColumnRef: return ((SqlColumnRef)exp).Column.Name; case SqlNodeType.ExprSet: return this.InferName(((SqlExprSet)exp).Expressions[0], def); } if (nodeType != SqlNodeType.Member) { return def; } return ((SqlMember)exp).Member.Name; } protected internal virtual bool IsSimpleCrossJoinList(SqlNode node) { var join = node as SqlJoin; if (join != null) { return (((join.JoinType == SqlJoinType.Cross) && IsSimpleCrossJoinList(join.Left)) && IsSimpleCrossJoinList(join.Right)); } var alias = node as SqlAlias; return ((alias != null) && (alias.Node is SqlTable)); } protected internal virtual void NewLine() { if (this.sb.Length > 0) { this.sb.AppendLine(); } for (int i = 0; i < this.depth; i++) { this.sb.Append(" "); } } internal static bool RequiresOnCondition(SqlJoinType joinType) { switch (joinType) { case SqlJoinType.Cross: case SqlJoinType.CrossApply: case SqlJoinType.OuterApply: return false; case SqlJoinType.Inner: case SqlJoinType.LeftOuter: return true; } throw Error.InvalidFormatNode(joinType); } internal override SqlAlias VisitAlias(SqlAlias alias) { bool flag = alias.Node is SqlSelect; int depth = this.depth; string str = null; string name = ""; var node = alias.Node as SqlTable; if (node != null) { name = node.Name; } if (alias.Name == null) { if (!names.TryGetValue(alias, out str)) { str = "A" + this.names.Count; names[alias] = str; } } else { str = alias.Name; } if (flag) { this.depth++; this.sb.Append("("); this.NewLine(); } this.Visit(alias.Node); if (flag) { this.NewLine(); this.sb.Append(")"); this.depth = depth; } if ((!this.suppressedAliases.Contains(alias) && (str != null)) && (name != str)) { if (Mode == SqlProvider.ProviderMode.Oracle || Mode == SqlProvider.ProviderMode.OdpOracle) sb.Append(" "); else this.sb.Append(" AS "); this.WriteName(str); } return alias; } internal override SqlExpression VisitAliasRef(SqlAliasRef aref) { this.sb.Append("AREF("); this.WriteAliasName(aref.Alias); this.sb.Append(")"); return aref; } internal override SqlStatement VisitAssign(SqlAssign sa) { this.sb.Append("SET "); this.Visit(sa.LValue); this.sb.Append(" = "); this.Visit(sa.RValue); return sa; } internal override SqlExpression VisitBetween(SqlBetween between) { this.VisitWithParens(between.Expression, between); this.sb.Append(" BETWEEN "); this.Visit(between.Start); this.sb.Append(" AND "); this.Visit(between.End); return between; } internal override SqlExpression VisitBinaryOperator(SqlBinary bo) { if (bo.NodeType == SqlNodeType.Coalesce) { this.sb.Append("COALESCE("); this.Visit(bo.Left); this.sb.Append(","); this.Visit(bo.Right); this.sb.Append(")"); return bo; } this.VisitWithParens(bo.Left, bo); this.sb.Append(" "); this.sb.Append(this.GetOperator(bo.NodeType)); this.sb.Append(" "); this.VisitWithParens(bo.Right, bo); return bo; } internal override SqlBlock VisitBlock(SqlBlock block) { int num = 0; int count = block.Statements.Count; while (num < count) { this.Visit(block.Statements[num]); if (num < (count - 1)) { var select = block.Statements[num + 1] as SqlSelect; if ((select == null) || !select.DoNotOutput) { this.NewLine(); this.NewLine(); } } num++; } return block; } internal override SqlExpression VisitCast(SqlUnary c) { this.sb.Append("CAST("); this.Visit(c.Operand); this.sb.Append(" AS "); QueryFormatOptions none = QueryFormatOptions.None; if (c.Operand.SqlType.CanSuppressSizeForConversionToString) { none = QueryFormatOptions.SuppressSize; } this.sb.Append(c.SqlType.ToQueryString(none)); this.sb.Append(")"); return c; } internal override SqlExpression VisitClientArray(SqlClientArray scar) { if (!this.isDebugMode) { throw Error.InvalidFormatNode("ClientArray"); } this.sb.Append("new []{"); int num = 0; int count = scar.Expressions.Count; while (num < count) { if (num > 0) { this.sb.Append(", "); } this.Visit(scar.Expressions[num]); num++; } this.sb.Append("}"); return scar; } internal override SqlExpression VisitClientCase(SqlClientCase c) { if (!this.isDebugMode) { throw Error.InvalidFormatNode("ClientCase"); } this.depth++; this.NewLine(); this.sb.Append("(CASE"); this.depth++; if (c.Expression != null) { this.sb.Append(" "); this.Visit(c.Expression); } int num = 0; int count = c.Whens.Count; while (num < count) { SqlClientWhen when = c.Whens[num]; if ((num == (count - 1)) && (when.Match == null)) { this.NewLine(); this.sb.Append("ELSE "); this.Visit(when.Value); } else { this.NewLine(); this.sb.Append("WHEN "); this.Visit(when.Match); this.sb.Append(" THEN "); this.Visit(when.Value); } num++; } this.depth--; this.NewLine(); this.sb.Append(" END)"); this.depth--; return c; } internal override SqlExpression VisitClientParameter(SqlClientParameter cp) { object obj2; if (!this.isDebugMode) { throw Error.InvalidFormatNode("ClientParameter"); } this.sb.Append("client-parameter("); try { obj2 = cp.Accessor.Compile().DynamicInvoke(new object[1]); } catch (TargetInvocationException exception) { throw exception.InnerException; } this.sb.Append(obj2); this.sb.Append(")"); return cp; } internal override SqlExpression VisitClientQuery(SqlClientQuery cq) { if (!this.isDebugMode) { throw Error.InvalidFormatNode("ClientQuery"); } this.sb.Append("client("); int num = 0; int count = cq.Arguments.Count; while (num < count) { if (num > 0) { this.sb.Append(", "); } this.Visit(cq.Arguments[num]); num++; } this.sb.Append("; "); this.Visit(cq.Query); this.sb.Append(")"); return cq; } internal override SqlExpression VisitColumn(SqlColumn c) { if (!this.isDebugMode) { throw Error.InvalidFormatNode("Column"); } this.sb.Append("COLUMN("); if (c.Expression != null) { this.Visit(c.Expression); } else { string name = null; if (c.Alias != null) { if (c.Alias.Name == null) { if (!this.names.TryGetValue(c.Alias, out name)) { name = "A" + this.names.Count; this.names[c.Alias] = name; } } else { name = c.Alias.Name; } } this.sb.Append(name); this.sb.Append("."); this.sb.Append(c.Name); } this.sb.Append(")"); return c; } internal override SqlExpression VisitColumnRef(SqlColumnRef cref) { string str = null; SqlColumn key = cref.Column; SqlAlias alias = key.Alias; if (alias == null) { this.aliasMap.TryGetValue(key, out alias); } if (alias != null) { if (alias.Name == null) { if (!this.names.TryGetValue(alias, out str)) { str = "A" + this.names.Count; this.names[key.Alias] = str; } } else { str = key.Alias.Name; } } if ((!this.suppressedAliases.Contains(key.Alias) && (str != null)) && (str.Length != 0)) { this.WriteName(str); this.sb.Append("."); } string name = key.Name; string str3 = this.InferName(key.Expression, null); if (name == null) { name = str3; } if ((name == null) && !this.names.TryGetValue(key, out name)) { name = "C" + this.names.Count; this.names[key] = name; } this.WriteName(name); return cref; } protected internal virtual void VisitCrossJoinList(SqlNode node) { var join = node as SqlJoin; if (join != null) { this.VisitCrossJoinList(join.Left); this.sb.Append(", "); this.VisitCrossJoinList(join.Right); } else { this.Visit(node); } } internal override SqlStatement VisitDelete(SqlDelete sd) { sb.Append("DELETE FROM "); suppressedAliases.Add(sd.Select.From); Visit(sd.Select.From); if (sd.Select.Where != null) { sb.Append(" WHERE "); Visit(sd.Select.Where); } suppressedAliases.Remove(sd.Select.From); return sd; } internal override SqlExpression VisitDiscriminatedType(SqlDiscriminatedType dt) { if (this.isDebugMode) { this.sb.Append("DTYPE("); } base.VisitDiscriminatedType(dt); if (this.isDebugMode) { this.sb.Append(")"); } return dt; } internal override SqlExpression VisitDiscriminatorOf(SqlDiscriminatorOf dof) { if (this.isDebugMode) { this.sb.Append("DISCO("); } base.VisitDiscriminatorOf(dof); if (this.isDebugMode) { this.sb.Append(")"); } return dof; } internal override SqlExpression VisitElement(SqlSubSelect elem) { if (!this.isDebugMode) { throw Error.InvalidFormatNode("Element"); } int depth = this.depth; this.depth++; this.sb.Append("ELEMENT("); this.NewLine(); this.Visit(elem.Select); this.NewLine(); this.sb.Append(")"); this.depth = depth; return elem; } internal override SqlExpression VisitExists(SqlSubSelect sqlExpr) { int oldDepth = depth; this.depth++; this.sb.Append("EXISTS("); this.NewLine(); this.Visit(sqlExpr.Select); this.NewLine(); this.sb.Append(")"); this.depth = oldDepth; return sqlExpr; } internal override SqlExpression VisitExprSet(SqlExprSet xs) { if (this.isDebugMode) { this.sb.Append("ES("); int num = 0; int count = xs.Expressions.Count; while (num < count) { if (num > 0) { this.sb.Append(", "); } this.Visit(xs.Expressions[num]); num++; } this.sb.Append(")"); return xs; } this.Visit(xs.GetFirstExpression()); return xs; } internal override SqlExpression VisitFunctionCall(SqlFunctionCall fc) { if (Mode == SqlProvider.ProviderMode.OdpOracle || Mode == SqlProvider.ProviderMode.Oracle) if (fc.Arguments.Count == 0) fc.Brackets = false; if (fc.Name.Contains(".")) WriteName(fc.Name); else sb.Append(fc.Name); if (fc.Brackets) sb.Append("("); else sb.Append(" "); int num = 0; int count = fc.Arguments.Count; while (num < count) { if (num > 0) { if (fc.Comma) this.sb.Append(", "); else sb.Append(" "); } this.Visit(fc.Arguments[num]); num++; } if (fc.Brackets) this.sb.Append(")"); return fc; } internal override SqlExpression VisitGrouping(SqlGrouping g) { if (!this.isDebugMode) { throw Error.InvalidFormatNode("Grouping"); } this.sb.Append("Group("); this.Visit(g.Key); this.sb.Append(", "); this.Visit(g.Group); this.sb.Append(")"); return g; } internal override SqlExpression VisitIn(SqlIn sin) { this.VisitWithParens(sin.Expression, sin); this.sb.Append(" IN ("); int num = 0; int count = sin.Values.Count; while (num < count) { if (num > 0) { this.sb.Append(", "); } this.Visit(sin.Values[num]); num++; } this.sb.Append(")"); return sin; } internal override SqlStatement VisitInsert(SqlInsert si) { if (si.OutputKey != null) { this.sb.Append("DECLARE @output TABLE("); this.WriteName(si.OutputKey.Name); this.sb.Append(" "); this.sb.Append(si.OutputKey.SqlType.ToQueryString()); this.sb.Append(")"); this.NewLine(); if (si.OutputToLocal) { this.sb.Append("DECLARE @id "); this.sb.Append(si.OutputKey.SqlType.ToQueryString()); this.NewLine(); } } this.sb.Append("INSERT INTO "); this.Visit(si.Table); if (si.Row.Columns.Count != 0) { this.sb.Append("("); int num = 0; int count = si.Row.Columns.Count; while (num < count) { if (num > 0) { this.sb.Append(", "); } this.WriteName(si.Row.Columns[num].Name); num++; } this.sb.Append(")"); } if (si.OutputKey != null) { this.NewLine(); this.sb.Append("OUTPUT INSERTED."); this.WriteName(si.OutputKey.Name); if (si.OutputToLocal) { this.sb.Append(" INTO @output"); } } if (si.Row.Columns.Count == 0) { this.sb.Append(" DEFAULT VALUES"); } else { this.NewLine(); this.sb.Append("VALUES ("); if (this.isDebugMode && (si.Row.Columns.Count == 0)) { this.Visit(si.Expression); } else { int num3 = 0; int num4 = si.Row.Columns.Count; while (num3 < num4) { if (num3 > 0) { this.sb.Append(", "); } this.Visit(si.Row.Columns[num3].Expression); num3++; } } this.sb.Append(")"); } if (si.OutputKey != null) { this.NewLine(); if (si.OutputToLocal) { this.sb.Append("SELECT @id = "); this.sb.Append(si.OutputKey.Name); this.sb.Append(" FROM @output"); return si; } this.sb.Append("SELECT "); this.WriteName(si.OutputKey.Name); this.sb.Append(" FROM @output"); } return si; } internal override SqlSource VisitJoin(SqlJoin join) { //if (this.Mode == SqlProvider.ProviderMode.Access) // this.sb.Append("("); this.Visit(join.Left); this.NewLine(); switch (join.JoinType) { case SqlJoinType.Cross: this.sb.Append("CROSS JOIN "); break; case SqlJoinType.Inner: this.sb.Append("INNER JOIN "); break; case SqlJoinType.LeftOuter: this.sb.Append("LEFT OUTER JOIN "); break; case SqlJoinType.CrossApply: this.sb.Append("CROSS APPLY "); break; case SqlJoinType.OuterApply: this.sb.Append("OUTER APPLY "); break; } SqlJoin right = join.Right as SqlJoin; if ((right == null) || (((right.JoinType == SqlJoinType.Cross) && (join.JoinType != SqlJoinType.CrossApply)) && (join.JoinType != SqlJoinType.OuterApply))) { this.Visit(join.Right); } else { this.VisitJoinSource(join.Right); } if (join.Condition != null) { this.sb.Append(" ON "); this.Visit(join.Condition); //return join; } else if (RequiresOnCondition(join.JoinType)) { this.sb.Append(" ON 1=1 "); } //if (Mode == SqlProvider.ProviderMode.Access) // this.sb.Append(")"); return join; } internal override SqlExpression VisitJoinedCollection(SqlJoinedCollection jc) { if (!this.isDebugMode) { throw Error.InvalidFormatNode("JoinedCollection"); } this.sb.Append("big-join("); this.Visit(jc.Expression); this.sb.Append(", "); this.Visit(jc.Count); this.sb.Append(")"); return jc; } internal void VisitJoinSource(SqlSource src) { if (src.NodeType == SqlNodeType.Join) { this.depth++; this.sb.Append("("); this.Visit(src); this.sb.Append(")"); this.depth--; } else { this.Visit(src); } } internal override SqlExpression VisitLift(SqlLift lift) { this.Visit(lift.Expression); return lift; } internal override SqlExpression VisitLike(SqlLike like) { this.VisitWithParens(like.Expression, like); this.sb.Append(" LIKE "); this.Visit(like.Pattern); if (like.Escape != null) { this.sb.Append(" ESCAPE "); this.Visit(like.Escape); } return like; } internal override SqlNode VisitLink(SqlLink link) { if (!this.isDebugMode) { throw Error.InvalidFormatNode("Link"); } if (link.Expansion != null) { this.sb.Append("LINK("); this.Visit(link.Expansion); this.sb.Append(")"); return link; } this.sb.Append("LINK("); int num = 0; int count = link.KeyExpressions.Count; while (num < count) { if (num > 0) { this.sb.Append(", "); } this.Visit(link.KeyExpressions[num]); num++; } this.sb.Append(")"); return link; } protected override SqlNode VisitMember(SqlMember m) { this.Visit(m.Expression); this.sb.Append("."); this.sb.Append(m.Member.Name); return m; } internal override SqlMemberAssign VisitMemberAssign(SqlMemberAssign ma) { throw Error.InvalidFormatNode("MemberAssign"); } internal override SqlExpression VisitMethodCall(SqlMethodCall mc) { if (!this.isDebugMode) { throw Error.InvalidFormatNode("MethodCall"); } if (mc.Method.IsStatic) { this.sb.Append(mc.Method.DeclaringType); } else { this.Visit(mc.Object); } this.sb.Append("."); this.sb.Append(mc.Method.Name); this.sb.Append("("); int num = 0; int count = mc.Arguments.Count; while (num < count) { if (num > 0) { this.sb.Append(", "); } this.Visit(mc.Arguments[num]); num++; } this.sb.Append(")"); return mc; } internal override SqlExpression VisitMultiset(SqlSubSelect sms) { if (!this.isDebugMode) { throw Error.InvalidFormatNode("Multiset"); } int depth = this.depth; this.depth++; this.sb.Append("MULTISET("); this.NewLine(); this.Visit(sms.Select); this.NewLine(); this.sb.Append(")"); this.depth = depth; return sms; } internal override SqlExpression VisitNew(SqlNew sox) { if (!this.isDebugMode) { throw Error.InvalidFormatNode("New"); } this.sb.Append("new "); this.sb.Append(sox.ClrType.Name); this.sb.Append("{ "); int num = 0; int count = sox.Args.Count; while (num < count) { SqlExpression node = sox.Args[num]; if (num > 0) { this.sb.Append(", "); } this.sb.Append(sox.ArgMembers[num].Name); this.sb.Append(" = "); this.Visit(node); num++; } int num3 = 0; int num4 = sox.Members.Count; while (num3 < num4) { SqlMemberAssign assign = sox.Members[num3]; if (num3 > 0) { this.sb.Append(", "); } if (this.InferName(assign.Expression, null) != assign.Member.Name) { this.sb.Append(assign.Member.Name); this.sb.Append(" = "); } this.Visit(assign.Expression); num3++; } this.sb.Append(" }"); return sox; } internal override SqlExpression VisitNop(SqlNop nop) { if (!this.isDebugMode) { throw Error.InvalidFormatNode("NOP"); } this.sb.Append("NOP()"); return nop; } internal override SqlExpression VisitObjectType(SqlObjectType ot) { if (!this.isDebugMode) { throw Error.InvalidFormatNode("ObjectType"); } this.sb.Append("("); base.VisitObjectType(ot); this.sb.Append(").GetType()"); return ot; } internal override SqlExpression VisitOptionalValue(SqlOptionalValue sov) { if (!this.isDebugMode) { throw Error.InvalidFormatNode("OptionalValue"); } this.sb.Append("opt("); this.Visit(sov.HasValue); this.sb.Append(", "); this.Visit(sov.Value); this.sb.Append(")"); return sov; } internal override SqlExpression VisitParameter(SqlParameter p) { sb.Append(p.Name); return p; } internal override SqlRow VisitRow(SqlRow row) { int num = 0; int count = row.Columns.Count; while (num < count) { SqlColumn key = row.Columns[num]; if (num > 0) { sb.Append(", "); } Visit(key.Expression); string name = key.Name; string str2 = InferName(key.Expression, null); if (name == null) { name = str2; } if ((name == null) && !this.names.TryGetValue(key, out name)) { name = "C" + this.names.Count; this.names[key] = name; } if (Mode == SqlProvider.ProviderMode.Oracle || Mode == SqlProvider.ProviderMode.OdpOracle) { if (str2 != null) str2 = sqlIdentifier.UnquoteIdentifier(str2); } if (!string.IsNullOrEmpty(name) && name != str2) { if (Mode == SqlProvider.ProviderMode.Oracle || Mode == SqlProvider.ProviderMode.OdpOracle) sb.Append(" "); else sb.Append(" AS "); this.WriteName(name); } num++; } return row; } internal override SqlRowNumber VisitRowNumber(SqlRowNumber rowNumber) { this.sb.Append("ROW_NUMBER() OVER (ORDER BY "); int num = 0; int count = rowNumber.OrderBy.Count; while (num < count) { SqlOrderExpression expression = rowNumber.OrderBy[num]; if (num > 0) { this.sb.Append(", "); } this.Visit(expression.Expression); if (expression.OrderType == SqlOrderType.Descending) { this.sb.Append(" DESC"); } num++; } this.sb.Append(")"); return rowNumber; } internal override SqlExpression VisitScalarSubSelect(SqlSubSelect ss) { int depth = this.depth; this.depth++; if (this.isDebugMode) { this.sb.Append("SCALAR"); } this.sb.Append("("); this.NewLine(); this.Visit(ss.Select); this.NewLine(); this.sb.Append(")"); this.depth = depth; return ss; } internal override SqlExpression VisitSearchedCase(SqlSearchedCase c) { this.depth++; this.NewLine(); this.sb.Append("(CASE "); this.depth++; int num = 0; int count = c.Whens.Count; while (num < count) { SqlWhen when = c.Whens[num]; this.NewLine(); this.sb.Append("WHEN "); this.Visit(when.Match); this.sb.Append(" THEN "); this.Visit(when.Value); num++; } if (c.Else != null) { this.NewLine(); this.sb.Append("ELSE "); this.Visit(c.Else); } this.depth--; this.NewLine(); this.sb.Append(" END)"); this.depth--; return c; } internal override SqlSelect VisitSelect(SqlSelect ss) { if (!ss.DoNotOutput) { string str = null; if (ss.From != null) { StringBuilder sb = this.sb; this.sb = new StringBuilder(); if (this.IsSimpleCrossJoinList(ss.From)) { this.VisitCrossJoinList(ss.From); } else { this.Visit(ss.From); } str = this.sb.ToString(); this.sb = sb; } this.sb.Append("SELECT "); if (ss.IsDistinct) { this.sb.Append("DISTINCT "); } if (ss.Top != null) { this.sb.Append("TOP "); if (this.parenthesizeTop) { this.sb.Append("("); } this.Visit(ss.Top); if (this.parenthesizeTop) { this.sb.Append(")"); } this.sb.Append(" "); if (ss.IsPercent) { this.sb.Append(" PERCENT "); } } if (ss.Row.Columns.Count > 0) { this.VisitRow(ss.Row); } else if (this.isDebugMode) { this.Visit(ss.Selection); } else { sb.Append("NULL AS "); sb.Append(SqlIdentifier.QuoteCompoundIdentifier("EMPTY")); } if (str != null) { this.NewLine(); this.sb.Append("FROM "); this.sb.Append(str); } if (ss.Where != null) { this.NewLine(); this.sb.Append("WHERE "); this.Visit(ss.Where); } if (ss.GroupBy.Count > 0) { this.NewLine(); this.sb.Append("GROUP BY "); int num = 0; int count = ss.GroupBy.Count; while (num < count) { SqlExpression node = ss.GroupBy[num]; if (num > 0) { this.sb.Append(", "); } this.Visit(node); num++; } if (ss.Having != null) { this.NewLine(); this.sb.Append("HAVING "); this.Visit(ss.Having); } } if ((ss.OrderBy.Count > 0) && (ss.OrderingType != SqlOrderingType.Never)) { this.NewLine(); this.sb.Append("ORDER BY "); int num3 = 0; int num4 = ss.OrderBy.Count; while (num3 < num4) { SqlOrderExpression expression2 = ss.OrderBy[num3]; if (num3 > 0) { this.sb.Append(", "); } this.Visit(expression2.Expression); if (expression2.OrderType == SqlOrderType.Descending) { this.sb.Append(" DESC"); } num3++; } } } return ss; } internal override SqlExpression VisitSharedExpression(SqlSharedExpression shared) { if (!this.isDebugMode) { throw Error.InvalidFormatNode("Shared"); } this.sb.Append("SHARED("); this.Visit(shared.Expression); this.sb.Append(")"); return shared; } internal override SqlExpression VisitSharedExpressionRef(SqlSharedExpressionRef sref) { if (!this.isDebugMode) { throw Error.InvalidFormatNode("SharedRef"); } this.sb.Append("SHAREDREF("); this.Visit(sref.SharedExpression.Expression); this.sb.Append(")"); return sref; } internal override SqlExpression VisitSimpleCase(SqlSimpleCase c) { this.depth++; this.NewLine(); this.sb.Append("(CASE"); this.depth++; if (c.Expression != null) { this.sb.Append(" "); this.Visit(c.Expression); } int num = 0; int count = c.Whens.Count; while (num < count) { SqlWhen when = c.Whens[num]; if ((num == (count - 1)) && (when.Match == null)) { this.NewLine(); this.sb.Append("ELSE "); this.Visit(when.Value); } else { this.NewLine(); this.sb.Append("WHEN "); this.Visit(when.Match); this.sb.Append(" THEN "); this.Visit(when.Value); } num++; } this.depth--; this.NewLine(); this.sb.Append(" END)"); this.depth--; return c; } internal override SqlExpression VisitSimpleExpression(SqlSimpleExpression simple) { if (!this.isDebugMode) { throw Error.InvalidFormatNode("SIMPLE"); } this.sb.Append("SIMPLE("); base.VisitSimpleExpression(simple); this.sb.Append(")"); return simple; } internal override SqlStoredProcedureCall VisitStoredProcedureCall(SqlStoredProcedureCall spc) { sb.Append("EXEC "); if (spc.Function.Method.ReturnType != typeof(void)) sb.Append("@RETURN_VALUE = "); WriteName(spc.Function.MappedName); sb.Append(" "); int count = spc.Function.Parameters.Count; for (int i = 0; i < count; i++) { MetaParameter parameter = spc.Function.Parameters[i]; if (i > 0) { sb.Append(", "); } WriteRecordVariableName(parameter.MappedName); sb.Append(" = "); Visit(spc.Arguments[i]); if (parameter.Parameter.IsOut || parameter.Parameter.ParameterType.IsByRef) { sb.Append(" OUTPUT"); } } if (spc.Arguments.Count > count) { if (count > 0) { this.sb.Append(", "); } this.WriteRecordVariableName(spc.Function.ReturnParameter.MappedName); this.sb.Append(" = "); this.Visit(spc.Arguments[count]); this.sb.Append(" OUTPUT"); } return spc; } internal override SqlTable VisitTable(SqlTable tab) { string name = tab.Name; this.WriteName(name); return tab; } internal override SqlExpression VisitTableValuedFunctionCall(SqlTableValuedFunctionCall fc) { return this.VisitFunctionCall(fc); } internal override SqlExpression VisitTreat(SqlUnary t) { this.sb.Append("TREAT("); this.Visit(t.Operand); this.sb.Append(" AS "); this.FormatType(t.SqlType); this.sb.Append(")"); return t; } internal override SqlExpression VisitTypeCase(SqlTypeCase c) { if (!this.isDebugMode) { throw Error.InvalidFormatNode("TypeCase"); } this.depth++; this.NewLine(); this.sb.Append("(CASE"); this.depth++; if (c.Discriminator != null) { this.sb.Append(" "); this.Visit(c.Discriminator); } int num = 0; int count = c.Whens.Count; while (num < count) { SqlTypeCaseWhen when = c.Whens[num]; if ((num == (count - 1)) && (when.Match == null)) { this.NewLine(); this.sb.Append("ELSE "); this.Visit(when.TypeBinding); } else { this.NewLine(); this.sb.Append("WHEN "); this.Visit(when.Match); this.sb.Append(" THEN "); this.Visit(when.TypeBinding); } num++; } this.depth--; this.NewLine(); this.sb.Append(" END)"); this.depth--; return c; } internal override SqlExpression VisitUnaryOperator(SqlUnary uo) { switch (uo.NodeType) { case SqlNodeType.Avg: case SqlNodeType.ClrLength: case SqlNodeType.Count: case SqlNodeType.Covar: case SqlNodeType.LongCount: case SqlNodeType.Min: case SqlNodeType.Max: case SqlNodeType.Sum: case SqlNodeType.Stddev: this.sb.Append(this.GetOperator(uo.NodeType)); this.sb.Append("("); if (uo.Operand == null) { this.sb.Append("*"); } else { this.Visit(uo.Operand); } this.sb.Append(")"); return uo; case SqlNodeType.BitNot: case SqlNodeType.Negate: this.sb.Append(this.GetOperator(uo.NodeType)); this.VisitWithParens(uo.Operand, uo); return uo; case SqlNodeType.Convert: { return TranslateConverter(uo); } case SqlNodeType.IsNotNull: case SqlNodeType.IsNull: this.VisitWithParens(uo.Operand, uo); this.sb.Append(" "); this.sb.Append(this.GetOperator(uo.NodeType)); return uo; case SqlNodeType.Not: case SqlNodeType.Not2V: this.sb.Append(this.GetOperator(uo.NodeType)); this.sb.Append(" "); this.VisitWithParens(uo.Operand, uo); return uo; case SqlNodeType.ValueOf: case SqlNodeType.OuterJoinedValue: this.Visit(uo.Operand); return uo; } throw Error.InvalidFormatNode(uo.NodeType); } protected virtual SqlExpression TranslateConverter(SqlUnary uo) { sb.Append("CONVERT("); QueryFormatOptions none = QueryFormatOptions.None; if (uo.Operand.SqlType.CanSuppressSizeForConversionToString) { none = QueryFormatOptions.SuppressSize; } sb.Append(uo.SqlType.ToQueryString(none)); sb.Append(","); Visit(uo.Operand); sb.Append(")"); return uo; } internal override SqlNode VisitUnion(SqlUnion su) { this.sb.Append("("); int depth = this.depth; this.depth++; this.NewLine(); this.Visit(su.Left); this.NewLine(); this.sb.Append("UNION"); if (su.All) { this.sb.Append(" ALL"); } this.NewLine(); this.Visit(su.Right); this.NewLine(); this.sb.Append(")"); this.depth = depth; return su; } internal override SqlStatement VisitUpdate(SqlUpdate su) { if (su.IsInsert) return VisitInsert(su); this.sb.Append("UPDATE "); this.suppressedAliases.Add(su.Select.From); this.Visit(su.Select.From); this.NewLine(); this.sb.Append("SET "); int num = 0; int count = su.Assignments.Count; while (num < count) { if (num > 0) { this.sb.Append(", "); } SqlAssign assign = su.Assignments[num]; this.Visit(assign.LValue); this.sb.Append(" = "); this.Visit(assign.RValue); num++; } if (su.Select.Where != null) { this.NewLine(); this.sb.Append("WHERE "); this.Visit(su.Select.Where); } this.suppressedAliases.Remove(su.Select.From); return su; } SqlStatement VisitInsert(SqlUpdate su) { this.sb.Append("INSERT INTO "); this.suppressedAliases.Add(su.Select.From); this.Visit(su.Select.From); //this.NewLine(); this.sb.Append("("); int num = 0; int count = su.Assignments.Count; while (num < count) { if (num > 0) this.sb.Append(", "); SqlAssign assign = su.Assignments[num]; this.Visit(assign.LValue); num++; } this.sb.Append(")"); this.NewLine(); this.sb.Append("VALUES "); sb.Append("("); num = 0; while (num < count) { if (num > 0) this.sb.Append(", "); SqlAssign assign = su.Assignments[num]; this.Visit(assign.RValue); num++; } sb.Append(")"); return su; } internal override SqlExpression VisitUserColumn(SqlUserColumn suc) { this.sb.Append(suc.Name); return suc; } internal override SqlUserQuery VisitUserQuery(SqlUserQuery suq) { if (suq.Arguments.Count > 0) { StringBuilder sb = this.sb; this.sb = new StringBuilder(); object[] args = new object[suq.Arguments.Count]; int index = 0; int length = args.Length; while (index < length) { this.Visit(suq.Arguments[index]); args[index] = this.sb.ToString(); this.sb.Length = 0; index++; } this.sb = sb; this.sb.Append(string.Format(CultureInfo.InvariantCulture, suq.QueryText, args)); return suq; } this.sb.Append(suq.QueryText); return suq; } internal override SqlExpression VisitUserRow(SqlUserRow row) { if (!this.isDebugMode) { throw Error.InvalidFormatNode("UserRow"); } return row; } internal override SqlExpression VisitValue(SqlValue sqlValue) { if (sqlValue.IsClientSpecified && !this.isDebugMode) { throw Error.InvalidFormatNode("Value"); } FormatValue(sqlValue.Value); return sqlValue; } internal override SqlExpression VisitVariable(SqlVariable v) { //if (v.Name.StartsWith(SqlIdentifier.ParameterPrefix)) sb.Append(v.Name); //else //sb.Append(SqlIdentifier.QuoteCompoundIdentifier(v.Name)); return v; } protected internal virtual void VisitWithParens(SqlNode node, SqlNode outer) { if (node == null) { return; } SqlNodeType nodeType = node.NodeType; if (nodeType <= SqlNodeType.Member) { switch (nodeType) { case SqlNodeType.FunctionCall: case SqlNodeType.Member: case SqlNodeType.ColumnRef: goto Label_0099; case SqlNodeType.Add: case SqlNodeType.And: case SqlNodeType.BitAnd: case SqlNodeType.BitNot: case SqlNodeType.BitOr: case SqlNodeType.BitXor: goto Label_00A2; case SqlNodeType.Alias: case SqlNodeType.AliasRef: case SqlNodeType.Assign: case SqlNodeType.Avg: case SqlNodeType.Between: goto Label_00B9; } goto Label_00B9; } if (nodeType <= SqlNodeType.Parameter) { switch (nodeType) { case SqlNodeType.Not: case SqlNodeType.Not2V: case SqlNodeType.Or: case SqlNodeType.Mul: goto Label_00A2; case SqlNodeType.Nop: case SqlNodeType.ObjectType: case SqlNodeType.OptionalValue: goto Label_00B9; case SqlNodeType.OuterJoinedValue: case SqlNodeType.Parameter: goto Label_0099; } goto Label_00B9; } if ((nodeType != SqlNodeType.TableValuedFunctionCall) && (nodeType != SqlNodeType.Value)) { goto Label_00B9; } Label_0099: this.Visit(node); return; Label_00A2: if (outer.NodeType == node.NodeType) { this.Visit(node); return; } Label_00B9: if (this.Mode == SqlProvider.ProviderMode.Access && nodeType == SqlNodeType.Variable) { this.Visit(node); } else { this.sb.Append("("); this.Visit(node); this.sb.Append(")"); } } private void WriteAliasName(SqlAlias alias) { string name = null; if (alias.Name == null) { if (!this.names.TryGetValue(alias, out name)) { name = "A" + this.names.Count; this.names[alias] = name; } } else { name = alias.Name; } this.WriteName(name); } protected virtual void WriteName(string name) { this.sb.Append(SqlIdentifier.QuoteCompoundIdentifier(name)); } public SqlProvider.ProviderMode Mode { get; set; } private void WriteRecordVariableName(string name) { WriteVariableName(name); } protected virtual void WriteVariableName(string name) { if (name.StartsWith(SqlIdentifier.ParameterPrefix, StringComparison.Ordinal)) { this.sb.Append(SqlIdentifier.QuoteCompoundIdentifier(name)); } else { this.sb.Append(SqlIdentifier.QuoteCompoundIdentifier("@" + name)); } } } } }
//------------------------------------------------------------------------------ // <copyright file="TreeNodeBinding.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.UI.WebControls { using System; using System.ComponentModel; using System.Drawing.Design; using System.Web; /// <devdoc> /// Provides a data mapping definition for a TreeView /// </devdoc> [DefaultProperty("TextField")] public sealed class TreeNodeBinding : IStateManager, ICloneable, IDataSourceViewSchemaAccessor { private bool _isTrackingViewState; private StateBag _viewState; /// <devdoc> /// The data member to use in the mapping /// </devdoc> [ DefaultValue(""), WebCategory("Data"), WebSysDescription(SR.Binding_DataMember), ] public string DataMember { get { string s = (string)ViewState["DataMember"]; if (s == null) { return String.Empty; } else { return s; } } set { ViewState["DataMember"] = value; } } /// <devdoc> /// The depth of the level for which this TreeNodeBinding is defining a data mapping /// </devdoc> [ DefaultValue(-1), TypeConverter("System.Web.UI.Design.WebControls.TreeNodeBindingDepthConverter, " + AssemblyRef.SystemDesign), WebCategory("Data"), WebSysDescription(SR.TreeNodeBinding_Depth), ] public int Depth { get { object o = ViewState["Depth"]; if (o == null) { return -1; } return (int)o; } set { ViewState["Depth"] = value; } } [DefaultValue("")] [Localizable(true)] [WebCategory("Databindings")] [WebSysDescription(SR.TreeNodeBinding_FormatString)] public string FormatString { get { string s = (string)ViewState["FormatString"]; if (s == null) { return String.Empty; } return s; } set { ViewState["FormatString"] = value; } } /// <devdoc> /// Gets and sets the TreeNodeBinding ImageToolTip /// </devdoc> [DefaultValue("")] [Localizable(true)] [WebCategory("DefaultProperties")] [WebSysDescription(SR.TreeNodeBinding_ImageToolTip)] public string ImageToolTip { get { string s = (string)ViewState["ImageToolTip"]; if (s == null) { return String.Empty; } return s; } set { ViewState["ImageToolTip"] = value; } } /// <devdoc> /// Get and sets the fieldname to use for the ImageToolTip property in a TreeNode /// </devdoc> [DefaultValue("")] [TypeConverter("System.Web.UI.Design.DataSourceViewSchemaConverter, " + AssemblyRef.SystemDesign), WebSysDescription(SR.TreeNodeBinding_ImageToolTipField)] [WebCategory("Databindings")] public string ImageToolTipField { get { string s = (string)ViewState["ImageToolTipField"]; if (s == null) { return String.Empty; } else { return s; } } set { ViewState["ImageToolTipField"] = value; } } /// <devdoc> /// Gets and sets the image URl to be rendered for this node /// </devdoc> [DefaultValue("")] [Editor("System.Web.UI.Design.ImageUrlEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor))] [UrlProperty()] [WebCategory("DefaultProperties")] [WebSysDescription(SR.TreeNodeBinding_ImageUrl)] public string ImageUrl { get { string s = (string)ViewState["ImageUrl"]; if (s == null) { return String.Empty; } return s; } set { ViewState["ImageUrl"] = value; } } /// <devdoc> /// Get and sets the fieldname to use for the ImageUrl property in a TreeNode /// </devdoc> [ DefaultValue(""), TypeConverter("System.Web.UI.Design.DataSourceViewSchemaConverter, " + AssemblyRef.SystemDesign), WebCategory("Databindings"), WebSysDescription(SR.TreeNodeBinding_ImageUrlField), ] public string ImageUrlField { get { string s = (string)ViewState["ImageUrlField"]; if (s == null) { return String.Empty; } else { return s; } } set { ViewState["ImageUrlField"] = value; } } /// <devdoc> /// Gets and sets the URL to navigate to when the node is clicked /// </devdoc> [DefaultValue("")] [Editor("System.Web.UI.Design.UrlEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor))] [UrlProperty()] [WebCategory("DefaultProperties")] [WebSysDescription(SR.TreeNodeBinding_NavigateUrl)] public string NavigateUrl { get { string s = (string)ViewState["NavigateUrl"]; if (s == null) { return String.Empty; } return s; } set { ViewState["NavigateUrl"] = value; } } /// <devdoc> /// Get and sets the fieldname to use for the NavigateUrl property in a TreeNode /// </devdoc> [ DefaultValue(""), TypeConverter("System.Web.UI.Design.DataSourceViewSchemaConverter, " + AssemblyRef.SystemDesign), WebCategory("Databindings"), WebSysDescription(SR.TreeNodeBinding_NavigateUrlField), ] public string NavigateUrlField { get { string s = (string)ViewState["NavigateUrlField"]; if (s == null) { return String.Empty; } else { return s; } } set { ViewState["NavigateUrlField"] = value; } } /// <devdoc> /// Gets and sets whether to populate this binding immediately or on the next request for population /// </devdoc> [ DefaultValue(false), WebCategory("DefaultProperties"), WebSysDescription(SR.TreeNodeBinding_PopulateOnDemand), ] public bool PopulateOnDemand { get { object o = ViewState["PopulateOnDemand"]; if (o == null) { return false; } return (bool)o; } set { ViewState["PopulateOnDemand"] = value; } } /// <devdoc> /// Gets and sets the action which the TreeNodeBinding will perform when selected /// </devdoc> [DefaultValue(TreeNodeSelectAction.Select)] [WebCategory("DefaultProperties")] [WebSysDescription(SR.TreeNodeBinding_SelectAction)] public TreeNodeSelectAction SelectAction { get { object o = ViewState["SelectAction"]; if (o == null) { return TreeNodeSelectAction.Select; } return (TreeNodeSelectAction)o; } set { ViewState["SelectAction"] = value; } } /// <devdoc> /// Gets and sets whether the TreeNodeBinding has a CheckBox /// </devdoc> [DefaultValue(typeof(Nullable<bool>), "")] [WebCategory("DefaultProperties")] [WebSysDescription(SR.TreeNodeBinding_ShowCheckBox)] public bool? ShowCheckBox { get { object o = ViewState["ShowCheckBox"]; if (o == null) { return null; } return (bool?)o; } set { ViewState["ShowCheckBox"] = value; } } /// <devdoc> /// Gets and sets the target window that the TreeNodeBinding will browse to if selected /// </devdoc> [DefaultValue("")] [WebCategory("DefaultProperties")] [WebSysDescription(SR.TreeNodeBinding_Target)] public string Target { get { string s = (string)ViewState["Target"]; if (s == null) { return String.Empty; } return s; } set { ViewState["Target"] = value; } } [ DefaultValue(""), TypeConverter("System.Web.UI.Design.DataSourceViewSchemaConverter, " + AssemblyRef.SystemDesign), WebCategory("Databindings"), WebSysDescription(SR.TreeNodeBinding_TargetField), ] public string TargetField { get { string s = (string)ViewState["TargetField"]; if (s == null) { return String.Empty; } else { return s; } } set { ViewState["TargetField"] = value; } } /// <devdoc> /// Gets and sets the display text /// </devdoc> [DefaultValue("")] [Localizable(true)] [WebCategory("DefaultProperties")] [WebSysDescription(SR.TreeNodeBinding_Text)] public string Text { get { string s = (string)ViewState["Text"]; if (s == null) { s = (string)ViewState["Value"]; if (s == null) { return String.Empty; } } return s; } set { ViewState["Text"] = value; } } /// <devdoc> /// Get and sets the fieldname to use for the Text property in a TreeNode /// </devdoc> [ DefaultValue(""), TypeConverter("System.Web.UI.Design.DataSourceViewSchemaConverter, " + AssemblyRef.SystemDesign), WebCategory("Databindings"), WebSysDescription(SR.TreeNodeBinding_TextField), ] public string TextField { get { string s = (string)ViewState["TextField"]; if (s == null) { return String.Empty; } else { return s; } } set { ViewState["TextField"] = value; } } /// <devdoc> /// Gets and sets the TreeNodeBinding tooltip /// </devdoc> [DefaultValue("")] [Localizable(true)] [WebCategory("DefaultProperties")] [WebSysDescription(SR.TreeNodeBinding_ToolTip)] public string ToolTip { get { string s = (string)ViewState["ToolTip"]; if (s == null) { return String.Empty; } return s; } set { ViewState["ToolTip"] = value; } } /// <devdoc> /// Get and sets the fieldname to use for the ToolTip property in a TreeNode /// </devdoc> [ DefaultValue(""), TypeConverter("System.Web.UI.Design.DataSourceViewSchemaConverter, " + AssemblyRef.SystemDesign), WebCategory("Databindings"), WebSysDescription(SR.TreeNodeBinding_ToolTipField), ] public string ToolTipField { get { string s = (string)ViewState["ToolTipField"]; if (s == null) { return String.Empty; } else { return s; } } set { ViewState["ToolTipField"] = value; } } /// <devdoc> /// Gets and sets the value /// </devdoc> [DefaultValue("")] [Localizable(true)] [WebCategory("DefaultProperties")] [WebSysDescription(SR.TreeNodeBinding_Value)] public string Value { get { string s = (string)ViewState["Value"]; if (s == null) { s = (string)ViewState["Text"]; if (s == null) { return String.Empty; } } return s; } set { ViewState["Value"] = value; } } /// <devdoc> /// Get and sets the fieldname to use for the Value property in a TreeNode /// </devdoc> [ DefaultValue(""), TypeConverter("System.Web.UI.Design.DataSourceViewSchemaConverter, " + AssemblyRef.SystemDesign), WebCategory("Databindings"), WebSysDescription(SR.TreeNodeBinding_ValueField), ] public string ValueField { get { string s = (string)ViewState["ValueField"]; if (s == null) { return String.Empty; } else { return s; } } set { ViewState["ValueField"] = value; } } /// <devdoc> /// The state for this TreeNodeBinding /// </devdoc> private StateBag ViewState { get { if (_viewState == null) { _viewState = new StateBag(); if (_isTrackingViewState) { ((IStateManager)_viewState).TrackViewState(); } } return _viewState; } } internal void SetDirty() { ViewState.SetDirty(true); } public override string ToString() { return (String.IsNullOrEmpty(DataMember) ? SR.GetString(SR.TreeNodeBinding_EmptyBindingText) : DataMember); } #region ICloneable implemention /// <internalonly/> /// <devdoc> /// Creates a clone of the TreeNodeBinding. /// </devdoc> object ICloneable.Clone() { TreeNodeBinding clone = new TreeNodeBinding(); clone.DataMember = DataMember; clone.Depth = Depth; clone.FormatString = FormatString; clone.ImageToolTip = ImageToolTip; clone.ImageToolTipField = ImageToolTipField; clone.ImageUrl = ImageUrl; clone.ImageUrlField = ImageUrlField; clone.NavigateUrl = NavigateUrl; clone.NavigateUrlField = NavigateUrlField; clone.PopulateOnDemand = PopulateOnDemand; clone.SelectAction = SelectAction; clone.ShowCheckBox = ShowCheckBox; clone.Target = Target; clone.TargetField = TargetField; clone.Text = Text; clone.TextField = TextField; clone.ToolTip = ToolTip; clone.ToolTipField = ToolTipField; clone.Value = Value; clone.ValueField = ValueField; return clone; } #endregion #region IStateManager implementation /// <internalonly/> bool IStateManager.IsTrackingViewState { get { return _isTrackingViewState; } } /// <internalonly/> void IStateManager.LoadViewState(object state) { if (state != null) { ((IStateManager)ViewState).LoadViewState(state); } } /// <internalonly/> object IStateManager.SaveViewState() { if (_viewState != null) { return ((IStateManager)_viewState).SaveViewState(); } return null; } /// <internalonly/> void IStateManager.TrackViewState() { _isTrackingViewState = true; if (_viewState != null) { ((IStateManager)_viewState).TrackViewState(); } } #endregion #region IDataSourceViewSchemaAccessor implementation /// <internalonly/> object IDataSourceViewSchemaAccessor.DataSourceViewSchema { get { return ViewState["IDataSourceViewSchemaAccessor.DataSourceViewSchema"]; } set { ViewState["IDataSourceViewSchemaAccessor.DataSourceViewSchema"] = value; } } #endregion } }
//--------------------------------------------------------------------- // <copyright file="SyndicationDeserializer.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <summary> // Provides a deserializer for atom content structured as // syndication items or feeds. // </summary> // // @owner [....] //--------------------------------------------------------------------- namespace System.Data.Services.Serializers { #region Namespaces. using System; using System.Collections.Generic; using System.Data.Services.Common; using System.Data.Services.Providers; using System.Diagnostics; using System.IO; using System.Linq; using System.ServiceModel.Syndication; using System.Text; using System.Xml; #endregion Namespaces. /// <summary>Provides a deserializer for structured content.</summary> internal class SyndicationDeserializer : Deserializer { /// <summary>Factory for syndication formatting objects.</summary> private readonly SyndicationFormatterFactory factory; /// <summary>reader to read xml from the request stream</summary> private readonly XmlReader xmlReader; /// <summary>Initializes a new <see cref="SyndicationDeserializer"/> for the specified stream.</summary> /// <param name="stream">Input stream reader from which ATOM content must be read.</param> /// <param name="encoding">Encoding to use for the stream (null to auto-discover).</param> /// <param name="dataService">Data service for which the deserializer will act.</param> /// <param name="update">indicates whether this is a update operation or not</param> /// <param name="factory">Factory for formatter objects.</param> /// <param name="tracker">Tracker to use for modifications.</param> internal SyndicationDeserializer(Stream stream, Encoding encoding, IDataService dataService, bool update, SyndicationFormatterFactory factory, UpdateTracker tracker) : base(update, dataService, tracker) { Debug.Assert(stream != null, "stream != null"); Debug.Assert(factory != null, "factory != null"); this.factory = factory; this.xmlReader = factory.CreateReader(stream, encoding); } /// <summary> /// Indicates the various form of data in the inline xml element /// </summary> private enum LinkContent { /// <summary>If the link element didn't not contain an inline element at all.</summary> NoInlineElementSpecified, /// <summary>If the link element contained an empty inline element.</summary> EmptyInlineElementSpecified, /// <summary>If the inline element under the link element contained some data.</summary> InlineElementContainsData } /// <summary>returns the content format for the deserializer</summary> protected override ContentFormat ContentFormat { get { return ContentFormat.Atom; } } /// <summary> /// Assumes the payload to represent a single object and processes accordingly /// </summary> /// <param name="segmentInfo">info about the object being created</param> /// <returns>the newly formed object that the payload represents</returns> protected override object CreateSingleObject(SegmentInfo segmentInfo) { SyndicationItem item = ReadSyndicationItem(this.factory.CreateSyndicationItemFormatter(), this.xmlReader); return this.CreateObject(segmentInfo, true /*topLevel*/, item); } /// <summary>Provides an opportunity to clean-up resources.</summary> /// <param name="disposing"> /// Whether the call is being made from an explicit call to /// IDisposable.Dispose() rather than through the finalizer. /// </param> protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { this.xmlReader.Close(); } } /// <summary> /// Get the resource referred by the uri in the payload /// </summary> /// <returns>resource referred by the uri in the payload.</returns> protected override string GetLinkUriFromPayload() { throw Error.NotImplemented(); } /// <summary>Checks whether the specified item has a payload.</summary> /// <param name='item'>Item to check.</param> /// <returns>true if the item has content or links specified; false otherwise.</returns> private static bool HasContent(SyndicationItem item) { return item.Content != null || item.Links.Count > 0; } /// <summary>Gets the text for the type annotated on the specified <paramref name='item' />.</summary> /// <param name='item'>Item to read type from.</param> /// <returns>The text for the type annotated on the specified item; null if none is set.</returns> private static string SyndicationItemGetType(SyndicationItem item) { Debug.Assert(item != null, "item != null"); SyndicationCategory category = item.Categories.Where(c => c.Scheme == XmlConstants.DataWebSchemeNamespace).FirstOrDefault(); return (category == null) ? null : category.Name; } /// <summary>Reads a SyndicationFeed object from the specified XmlReader.</summary> /// <param name='formatter'>Formatter to use when reading content.</param> /// <param name='reader'>Read to read feed from.</param> /// <returns>A new SyndicationFeed instance.</returns> private static SyndicationFeed ReadSyndicationFeed(SyndicationFeedFormatter formatter, XmlReader reader) { Debug.Assert(formatter != null, "formatter != null"); Debug.Assert(reader != null, "reader != null"); try { formatter.ReadFrom(reader); } catch (XmlException exception) { throw DataServiceException.CreateBadRequestError(Strings.Syndication_ErrorReadingFeed(exception.Message), exception); } Debug.Assert(formatter.Feed != null, "formatter.Feed != null"); return formatter.Feed; } /// <summary>Reads a SyndicationItem object from the specified XmlReader.</summary> /// <param name='formatter'>Formatter to use when reading content.</param> /// <param name='reader'>Read to read feed from.</param> /// <returns>A new SyndicationItem instance.</returns> private static SyndicationItem ReadSyndicationItem(SyndicationItemFormatter formatter, XmlReader reader) { Debug.Assert(formatter != null, "formatter != null"); Debug.Assert(reader != null, "reader != null"); try { formatter.ReadFrom(reader); } catch (XmlException exception) { throw DataServiceException.CreateBadRequestError(Strings.Syndication_ErrorReadingEntry(exception.Message), exception); } Debug.Assert(formatter.Item != null, "formatter.Item != null"); return formatter.Item; } /// <summary> /// Read the link media type and validate for non open property types /// </summary> /// <param name="mediaType">media type as specified on the link element.</param> /// <param name="property">property which the link represents.</param> /// <returns>returns the type parameters specified in the media link.</returns> private static string ValidateTypeParameterForNonOpenTypeProperties(string mediaType, ResourceProperty property) { string typeParameterValue = null; if (!String.IsNullOrEmpty(mediaType)) { string mime; Encoding encoding; KeyValuePair<string, string>[] contentTypeParameters = HttpProcessUtility.ReadContentType(mediaType, out mime, out encoding); if (mime != XmlConstants.MimeApplicationAtom) { throw DataServiceException.CreateBadRequestError(Strings.BadRequest_MimeTypeMustBeApplicationAtom(mime, XmlConstants.MimeApplicationAtom)); } // If the type parameter is specified, make sure its correct. We do the validation for known properties here // and for open-properties, the validation is done if the link is expanded. Otherwise, there is no good way of // doing the validation. typeParameterValue = HttpProcessUtility.GetParameterValue(contentTypeParameters, XmlConstants.AtomTypeAttributeName); if (!String.IsNullOrEmpty(typeParameterValue) && property != null) { if (property.Kind == ResourcePropertyKind.ResourceReference) { if (typeParameterValue != XmlConstants.AtomEntryElementName) { throw DataServiceException.CreateBadRequestError(Strings.BadRequest_InvalidTypeParameterSpecifiedInMimeType(typeParameterValue, XmlConstants.AtomEntryElementName)); } } else if (typeParameterValue != XmlConstants.AtomFeedElementName) { throw DataServiceException.CreateBadRequestError(Strings.BadRequest_InvalidTypeParameterSpecifiedInMimeType(typeParameterValue, XmlConstants.AtomFeedElementName)); } } } return typeParameterValue; } /// <summary> /// Gets the XmlReader for the m:properties element under the atom:entry element /// </summary> /// <param name="item">item to read from</param> /// <returns>XmlReader for the m:properties element if found, null otherwise.</returns> private static XmlReader GetPropertiesReaderFromEntry(SyndicationItem item) { SyndicationElementExtension properties = item.ElementExtensions.Where(p => p.OuterName == XmlConstants.AtomPropertiesElementName && p.OuterNamespace == XmlConstants.DataWebMetadataNamespace).FirstOrDefault(); if (properties != null) { return properties.GetReader(); } return null; } /// <summary> /// Gets the XmlReader for the m:properties element under the atom:content element /// </summary> /// <param name="item">item to read from</param> /// <returns>XmlReader for the m:properties element if found, null otherwise.</returns> private static XmlReader GetPropertiesReaderFromContent(SyndicationItem item) { XmlSyndicationContent itemContent = item.Content as XmlSyndicationContent; XmlReader reader = null; if (itemContent != null) { string contentType = itemContent.Type; if (!WebUtil.CompareMimeType(contentType, XmlConstants.MimeApplicationXml)) { throw DataServiceException.CreateBadRequestError( Strings.Syndication_EntryContentTypeUnsupported(contentType)); } bool shouldDispose = false; try { reader = itemContent.GetReaderAtContent(); WebUtil.XmlReaderEnsureElement(reader); Debug.Assert( reader.NodeType == XmlNodeType.Element, reader.NodeType.ToString() + " == XmlNodeType.Element -- otherwise XmlSyndicationContent didn't see a 'content' tag"); reader.ReadStartElement(XmlConstants.AtomContentElementName, XmlConstants.AtomNamespace); if (!reader.IsStartElement(XmlConstants.AtomPropertiesElementName, XmlConstants.DataWebMetadataNamespace)) { shouldDispose = true; } } catch { shouldDispose = true; throw; } finally { if (shouldDispose) { WebUtil.Dispose(reader); reader = null; } } } return reader; } /// <summary>Applies the properties in the plain XML content to the specified resource.</summary> /// <param name="item">item to read from.</param> /// <param name='resourceType'>Type of resource whose values are being set.</param> /// <param name="propertiesApplied">Properties that have been applied to the <paramref name="resource"/></param> /// <param name='resource'>Target resource.</param> private void ApplyProperties(SyndicationItem item, ResourceType resourceType, EpmContentDeSerializer.EpmAppliedPropertyInfo propertiesApplied, object resource) { Debug.Assert(item != null, "item != null"); Debug.Assert(resourceType != null, "resourceType != null"); Debug.Assert(propertiesApplied != null, "propertiesApplied != null"); Debug.Assert(resource != null, "resource != null"); using (XmlReader propertiesFromEntry = GetPropertiesReaderFromEntry(item)) using (XmlReader propertiesFromContent = GetPropertiesReaderFromContent(item)) { XmlReader reader = null; if (resourceType.IsMediaLinkEntry) { if (propertiesFromContent != null) { // The server is expecting a MLE payload, however we found a <m:properties> element under the <atom:content> element. // The client must assumed the resource type is a non-MLE type and serialized as such. // // We must throw here otherwise the client would falsely assume all the properties are correctly deserialized on // the server where as in fact the properties element is under the wrong node. throw DataServiceException.CreateBadRequestError(Strings.DataServiceException_GeneralError); } reader = propertiesFromEntry; } else { if (propertiesFromEntry != null) { // The server is expecting a non-MLE payload, however we found a <m:properties> element under the <entry> element. // The client must assumed the resource type is a MLE type and serialized as such. // // We must throw here otherwise the client would falsely assume all the properties are correctly deserialized on // the server where as in fact the properties element is under the wrong node. throw DataServiceException.CreateBadRequestError(Strings.DataServiceException_GeneralError); } reader = propertiesFromContent; } if (reader != null) { reader.ReadStartElement(XmlConstants.AtomPropertiesElementName, XmlConstants.DataWebMetadataNamespace); PlainXmlDeserializer.ApplyContent(this, reader, resourceType, resource, propertiesApplied, this.MaxObjectCount); } } } /// <summary>Reads the current object from the <paramref name="item"/>.</summary> /// <param name="segmentInfo">segmentinfo containing information about the current element that is getting processes</param> /// <param name="topLevel">true if the element currently pointed by the xml reader refers to a top level element</param> /// <param name="item">Item to read from.</param> /// <returns>returns the clr object with the data populated</returns> private object CreateObject(SegmentInfo segmentInfo, bool topLevel, SyndicationItem item) { Debug.Assert(item != null, "item != null"); Debug.Assert(topLevel || !this.Update, "deep updates not supported"); this.RecurseEnter(); object result; // update the object count everytime you encounter a new resource this.CheckAndIncrementObjectCount(); // Process the type annotation. ResourceType currentResourceType = this.GetResourceType(item, segmentInfo.TargetResourceType); if (currentResourceType.ResourceTypeKind != ResourceTypeKind.EntityType) { throw DataServiceException.CreateBadRequestError(Strings.BadRequest_OnlyEntityTypesMustBeSpecifiedInEntryElement(currentResourceType.FullName)); } // We have the actual type info from the payload. Update the request/response DSV if any property is FF mapped with KeepInContent=false. this.UpdateAndCheckEpmRequestResponseDSV(currentResourceType, topLevel); // Get a resource cookie from the provider. ResourceSetWrapper container; if (segmentInfo.TargetKind == RequestTargetKind.OpenProperty) { // Open navigation properties are not supported on OpenTypes. throw DataServiceException.CreateBadRequestError(Strings.OpenNavigationPropertiesNotSupportedOnOpenTypes(segmentInfo.Identifier)); } else { Debug.Assert(segmentInfo.TargetKind == RequestTargetKind.Resource, "segmentInfo.TargetKind == RequestTargetKind.Resource"); container = segmentInfo.TargetContainer; } DataServiceHostWrapper host = this.Service.OperationContext.Host; if (this.Update) { Debug.Assert(currentResourceType.ResourceTypeKind == ResourceTypeKind.EntityType, "only expecting entity types"); // Only verify ETag if there is going to be some update applied (that's the idea) // In reality: // - for normal entities (V1 compatible) - don't check ETags if there is no content element. (Same as in V1) // - for V2 stuff - check ETags always as we can't tell if there's going to be something modified or not // with EPM properties can be anywhere in the payload and thus even without content there still can be updates // with MLE the properties are not in the content element but in their own element // It's hard to recognize if there's going to be update up front and so this below is an approximation // which seems to be good enough. Note that if we add new ways of handling properties in the content // the condition below might need to change. bool verifyETag = topLevel && (HasContent(item) || currentResourceType.HasEntityPropertyMappings || currentResourceType.IsMediaLinkEntry); bool replaceResource = topLevel && host.AstoriaHttpVerb == AstoriaVerbs.PUT; // if its a top level resource, then it cannot be null result = this.GetObjectFromSegmentInfo(currentResourceType, segmentInfo, verifyETag, topLevel /*checkForNull*/, replaceResource); if (this.Tracker != null) { this.Tracker.TrackAction(result, container, UpdateOperations.Change); } } else { if (segmentInfo.TargetKind == RequestTargetKind.Resource) { DataServiceConfiguration.CheckResourceRights(segmentInfo.TargetContainer, EntitySetRights.WriteAppend); } result = this.Updatable.CreateResource(container.Name, currentResourceType.FullName); if (this.Tracker != null) { this.Tracker.TrackAction(result, container, UpdateOperations.Add); } } // Process the content in the entry. EpmContentDeSerializer.EpmAppliedPropertyInfo propertiesApplied = new EpmContentDeSerializer.EpmAppliedPropertyInfo(); this.ApplyProperties(item, currentResourceType, propertiesApplied, result); // Perform application of epm properties here if (currentResourceType.HasEntityPropertyMappings) { new EpmContentDeSerializer(currentResourceType, result).DeSerialize( item, new EpmContentDeSerializer.EpmContentDeserializerState { IsUpdateOperation = this.Update, Updatable = this.Updatable, Service = this.Service, PropertiesApplied = propertiesApplied }); } // Process the links in the entry. foreach (SyndicationLink link in item.Links) { string navigationPropertyName = UriUtil.GetNameFromAtomLinkRelationAttribute(link.RelationshipType); if (null == navigationPropertyName) { continue; } Deserializer.CheckForBindingInPutOperations(host.AstoriaHttpVerb); Debug.Assert(segmentInfo.TargetContainer != null, "segmentInfo.TargetContainer != null"); this.ApplyLink(link, segmentInfo.TargetContainer, currentResourceType, result, navigationPropertyName); } this.RecurseLeave(); return result; } /// <summary>Applies the information from a link to the specified resource.</summary> /// <param name='link'>LinkDescriptor with information to apply.</param> /// <param name="resourceSet">Set for the target resource.</param> /// <param name='resourceType'>Type for the target resource.</param> /// <param name='resource'>Target resource to which information will be applied.</param> /// <param name="propertyName">Name of the property that this link represents.</param> private void ApplyLink(SyndicationLink link, ResourceSetWrapper resourceSet, ResourceType resourceType, object resource, string propertyName) { Debug.Assert(link != null, "link != null"); Debug.Assert(resourceType != null, "resourceType != null"); Debug.Assert(resource != null, "resource != null"); ResourceProperty property = resourceType.TryResolvePropertyName(propertyName); if (property == null) { // Open navigation properties are not supported on OpenTypes throw DataServiceException.CreateBadRequestError(Strings.OpenNavigationPropertiesNotSupportedOnOpenTypes(propertyName)); } if (property.TypeKind != ResourceTypeKind.EntityType) { throw DataServiceException.CreateBadRequestError(Strings.BadRequest_InvalidNavigationPropertyName(propertyName, resourceType.FullName)); } string typeParameterValue = ValidateTypeParameterForNonOpenTypeProperties(link.MediaType, property); LinkContent linkContent = this.HandleLinkContent(link, resource, resourceSet, resourceType, property, typeParameterValue, propertyName); #region Handle bind/unbind operation // If the href was specified empty or an empty inline element was specified, then we will set the // reference to null - this helps in overrriding if there was a default non-value for this property // else if only link element was specified, and then href points to a single result, then we will // perform a bind operation if ((linkContent == LinkContent.NoInlineElementSpecified && link.Uri != null && String.IsNullOrEmpty(link.Uri.OriginalString)) || linkContent == LinkContent.EmptyInlineElementSpecified) { // update the object count when you are performing a bind operation this.CheckAndIncrementObjectCount(); if (property != null && property.Kind == ResourcePropertyKind.ResourceSetReference) { throw DataServiceException.CreateBadRequestError(Strings.BadRequest_CannotSetCollectionsToNull(propertyName)); } // For open properties, we will assume that this is a reference property and set it to null this.Updatable.SetReference(resource, propertyName, null); } else if (linkContent == LinkContent.NoInlineElementSpecified && link.Uri != null && !String.IsNullOrEmpty(link.Uri.OriginalString)) { // update the object count when you are performing a bind operation this.CheckAndIncrementObjectCount(); // If the link points to a reference navigation property, then update the link Uri referencedUri = RequestUriProcessor.GetAbsoluteUriFromReference(link.Uri.OriginalString, this.Service.OperationContext); RequestDescription description = RequestUriProcessor.ProcessRequestUri(referencedUri, this.Service); if (!description.IsSingleResult) { if (property != null && property.Kind == ResourcePropertyKind.ResourceReference) { throw DataServiceException.CreateBadRequestError(Strings.BadRequest_LinkHrefMustReferToSingleResource(propertyName)); } return; } // no need to check for null. For collection properties, they can never be null and that // check has been added below. For reference properties, if they are null, it means unbind // and hence no need to check for null. // Get the resource object targetResource = this.Service.GetResource(description, description.SegmentInfos.Length - 1, null); if (property.Kind == ResourcePropertyKind.ResourceReference) { this.Updatable.SetReference(resource, propertyName, targetResource); } else { WebUtil.CheckResourceExists(targetResource != null, description.LastSegmentInfo.Identifier); this.Updatable.AddReferenceToCollection(resource, propertyName, targetResource); } } #endregion Handle bind/unbind operation } /// <summary>Gets the type attribute and resolves the type.</summary> /// <param name="item">Item from which type attribute needs to be read</param> /// <param name="expectedType">Expected base type for the item.</param> /// <returns>Resolved type.</returns> private ResourceType GetResourceType(SyndicationItem item, ResourceType expectedType) { Debug.Assert(item != null, "item != null"); string typeName = SyndicationItemGetType(item); ResourceType resourceType; // If the type is not specified in the payload, we assume the type to be the expected type if (String.IsNullOrEmpty(typeName)) { // check if the expected type takes part in inheritance resourceType = expectedType; if (this.Service.Provider.HasDerivedTypes(resourceType)) { throw DataServiceException.CreateBadRequestError(Strings.BadRequest_TypeInformationMustBeSpecifiedForInhertiance); } } else { // Otherwise, try and resolve the name specified in the payload resourceType = this.Service.Provider.TryResolveResourceType(typeName); if (resourceType == null) { throw DataServiceException.CreateBadRequestError(Strings.BadRequest_InvalidTypeName(typeName)); } } return resourceType; } /// <summary> /// Handle the contents under the link element /// </summary> /// <param name="link">syndication link element</param> /// <param name="parentResource">parent resource which contains the link.</param> /// <param name="parentResourceSet">resource set of the parent resource</param> /// <param name="parentResourceType">resource type of the parent resource</param> /// <param name="property">property representing the link.</param> /// <param name="typeParameterValue">type parameter value as specified in the type attribute.</param> /// <param name="propertyName">name of the property that this link represents.</param> /// <returns>returns whether there are child elements under link element.</returns> private LinkContent HandleLinkContent( SyndicationLink link, object parentResource, ResourceSetWrapper parentResourceSet, ResourceType parentResourceType, ResourceProperty property, string typeParameterValue, string propertyName) { Debug.Assert(parentResource != null, "parent resource cannot be null"); Debug.Assert(property != null, "property != null"); Debug.Assert(link != null, "link != null"); LinkContent linkContent = LinkContent.NoInlineElementSpecified; foreach (var e in link.ElementExtensions) { // link can contain other elements apart from the inline elements. if (e.OuterNamespace != XmlConstants.DataWebMetadataNamespace || e.OuterName != XmlConstants.AtomInlineElementName) { continue; } // Deep payload cannot be specified for update if (this.Update) { throw DataServiceException.CreateBadRequestError(Strings.BadRequest_DeepUpdateNotSupported); } linkContent = LinkContent.EmptyInlineElementSpecified; using (XmlReader linkReader = e.GetReader()) { while (linkReader.Read()) { if (linkReader.NodeType == XmlNodeType.Element) { string elementName = linkReader.LocalName; string namespaceUri = linkReader.NamespaceURI; if (namespaceUri != XmlConstants.AtomNamespace) { throw DataServiceException.CreateBadRequestError( Strings.BadRequest_InlineElementMustContainValidElement( elementName, XmlConstants.AtomInlineElementName, XmlConstants.AtomFeedElementName, XmlConstants.AtomEntryElementName)); } ResourceSetWrapper targetSet = this.Service.Provider.GetContainer(parentResourceSet, parentResourceType, property); if (targetSet == null) { throw DataServiceException.CreateBadRequestError(Strings.BadRequest_InvalidPropertyNameSpecified(propertyName, parentResourceType.FullName)); } // FeatureVersion needs to be 2.0 if any of the property in the types contained in the resource set has KeepInContent false this.RequestDescription.UpdateAndCheckEpmFeatureVersion(targetSet, this.Service); linkContent = LinkContent.InlineElementContainsData; if (elementName == XmlConstants.AtomEntryElementName) { if (property.Kind != ResourcePropertyKind.ResourceReference) { throw DataServiceException.CreateBadRequestError(Strings.Syndication_EntryElementForReferenceProperties(e.OuterName, propertyName)); } // Make sure if the media type is specified. If its specified, it should better be link SyndicationItem propertyItem; propertyItem = ReadSyndicationItem(this.factory.CreateSyndicationItemFormatter(), linkReader); SegmentInfo propertySegment = CreateSegment(property, propertyName, targetSet, true /* singleResult */); Debug.Assert(propertySegment.TargetKind != RequestTargetKind.OpenProperty, "Open navigation properties are not supported on OpenTypes."); object propertyValue = this.CreateObject(propertySegment, false /* topLevel */, propertyItem); this.Updatable.SetReference(parentResource, propertyName, propertyValue); } else if (elementName == XmlConstants.AtomFeedElementName) { if (property.Kind != ResourcePropertyKind.ResourceSetReference) { throw DataServiceException.CreateBadRequestError(Strings.Syndication_FeedElementForCollections(e.OuterName, propertyName)); } SyndicationFeed propertyFeed; propertyFeed = ReadSyndicationFeed(this.factory.CreateSyndicationFeedFormatter(), linkReader); SegmentInfo propertySegment = CreateSegment(property, propertyName, targetSet, false /* singleResult */); Debug.Assert(propertySegment.TargetKind != RequestTargetKind.OpenProperty, "Open navigation properties are not supported on OpenTypes."); foreach (SyndicationItem item in propertyFeed.Items) { object propertyValue = this.CreateObject(propertySegment, false /* topLevel */, item); if (propertyValue == null) { if (propertySegment.ProjectedProperty != null && propertySegment.ProjectedProperty.Kind == ResourcePropertyKind.ResourceSetReference) { throw DataServiceException.CreateBadRequestError( Strings.BadRequest_CannotSetCollectionsToNull(propertyName)); } } Debug.Assert( propertySegment.TargetSource == RequestTargetSource.Property && propertySegment.TargetKind == RequestTargetKind.Resource && propertySegment.SingleResult == false, "Must be navigation set property."); this.Updatable.AddReferenceToCollection(parentResource, propertyName, propertyValue); } } else { throw DataServiceException.CreateBadRequestError( Strings.BadRequest_InlineElementMustContainValidElement( elementName, XmlConstants.AtomInlineElementName, XmlConstants.AtomFeedElementName, XmlConstants.AtomEntryElementName)); } } } } } return linkContent; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using Orleans.GrainDirectory; namespace Orleans.Runtime { internal interface IGrainTypeResolver { bool TryGetGrainClassData(Type grainInterfaceType, out GrainClassData implementation, string grainClassNamePrefix); bool TryGetGrainClassData(int grainInterfaceId, out GrainClassData implementation, string grainClassNamePrefix); bool TryGetGrainClassData(string grainImplementationClassName, out GrainClassData implementation); bool IsUnordered(int grainTypeCode); string GetLoadedGrainAssemblies(); } /// <summary> /// Internal data structure that holds a grain interfaces to grain classes map. /// </summary> [Serializable] internal class GrainInterfaceMap : IGrainTypeResolver { /// <summary> /// Metadata for a grain interface /// </summary> [Serializable] internal class GrainInterfaceData { [NonSerialized] private readonly Type iface; private readonly HashSet<GrainClassData> implementations; internal Type Interface { get { return iface; } } internal int InterfaceId { get; private set; } internal string GrainInterface { get; private set; } internal GrainClassData[] Implementations { get { return implementations.ToArray(); } } internal GrainClassData PrimaryImplementation { get; private set; } internal GrainInterfaceData(int interfaceId, Type iface, string grainInterface) { InterfaceId = interfaceId; this.iface = iface; GrainInterface = grainInterface; implementations = new HashSet<GrainClassData>(); } internal void AddImplementation(GrainClassData implementation, bool primaryImplemenation = false) { lock (this) { if (!implementations.Contains(implementation)) implementations.Add(implementation); if (primaryImplemenation) PrimaryImplementation = implementation; } } public override string ToString() { return String.Format("{0}:{1}", GrainInterface, InterfaceId); } } private readonly Dictionary<string, GrainInterfaceData> typeToInterfaceData; private readonly Dictionary<int, GrainInterfaceData> table; private readonly HashSet<int> unordered; [NonSerialized] private readonly Dictionary<int, GrainClassData> implementationIndex; [NonSerialized] // Client shouldn't need this private readonly Dictionary<string, string> primaryImplementations; private readonly bool localTestMode; private readonly HashSet<string> loadedGrainAsemblies; public GrainInterfaceMap(bool localTestMode) { table = new Dictionary<int, GrainInterfaceData>(); typeToInterfaceData = new Dictionary<string, GrainInterfaceData>(); primaryImplementations = new Dictionary<string, string>(); implementationIndex = new Dictionary<int, GrainClassData>(); unordered = new HashSet<int>(); this.localTestMode = localTestMode; if(localTestMode) // if we are running in test mode, we'll build a list of loaded grain assemblies to help with troubleshooting deployment issue loadedGrainAsemblies = new HashSet<string>(); } internal void AddEntry(int interfaceId, Type iface, int grainTypeCode, string grainInterface, string grainClass, string assembly, bool isGenericGrainClass, PlacementStrategy placement, MultiClusterRegistrationStrategy registrationStrategy, bool primaryImplementation = false) { lock (this) { GrainInterfaceData grainInterfaceData; if (table.ContainsKey(interfaceId)) { grainInterfaceData = table[interfaceId]; } else { grainInterfaceData = new GrainInterfaceData(interfaceId, iface, grainInterface); table[interfaceId] = grainInterfaceData; var interfaceTypeKey = GetTypeKey(iface, isGenericGrainClass); typeToInterfaceData[interfaceTypeKey] = grainInterfaceData; } var implementation = new GrainClassData(grainTypeCode, grainClass, isGenericGrainClass, grainInterfaceData, placement, registrationStrategy); if (!implementationIndex.ContainsKey(grainTypeCode)) implementationIndex.Add(grainTypeCode, implementation); grainInterfaceData.AddImplementation(implementation, primaryImplementation); if (primaryImplementation) { primaryImplementations[grainInterface] = grainClass; } else { if (!primaryImplementations.ContainsKey(grainInterface)) primaryImplementations.Add(grainInterface, grainClass); } if (localTestMode) { if (!loadedGrainAsemblies.Contains(assembly)) loadedGrainAsemblies.Add(assembly); } } } internal Dictionary<string, string> GetPrimaryImplementations() { lock (this) { return new Dictionary<string, string>(primaryImplementations); } } internal bool TryGetPrimaryImplementation(string grainInterface, out string grainClass) { lock (this) { return primaryImplementations.TryGetValue(grainInterface, out grainClass); } } internal bool TryGetServiceInterface(int interfaceId, out Type iface) { lock (this) { iface = null; if (!table.ContainsKey(interfaceId)) return false; var interfaceData = table[interfaceId]; iface = interfaceData.Interface; return true; } } internal bool ContainsGrainInterface(int interfaceId) { lock (this) { return table.ContainsKey(interfaceId); } } internal bool TryGetTypeInfo(int typeCode, out string grainClass, out PlacementStrategy placement, out MultiClusterRegistrationStrategy registrationStrategy, string genericArguments = null) { lock (this) { grainClass = null; placement = null; registrationStrategy = null; if (!implementationIndex.ContainsKey(typeCode)) return false; var implementation = implementationIndex[typeCode]; grainClass = implementation.GetClassName(genericArguments); placement = implementation.PlacementStrategy; registrationStrategy = implementation.RegistrationStrategy; return true; } } internal bool TryGetGrainClass(int grainTypeCode, out string grainClass, string genericArguments) { grainClass = null; GrainClassData implementation; if (!implementationIndex.TryGetValue(grainTypeCode, out implementation)) { return false; } grainClass = implementation.GetClassName(genericArguments); return true; } public bool TryGetGrainClassData(Type interfaceType, out GrainClassData implementation, string grainClassNamePrefix) { implementation = null; GrainInterfaceData interfaceData; var typeInfo = interfaceType.GetTypeInfo(); // First, try to find a non-generic grain implementation: if (this.typeToInterfaceData.TryGetValue(GetTypeKey(interfaceType, false), out interfaceData) && TryGetGrainClassData(interfaceData, out implementation, grainClassNamePrefix)) { return true; } // If a concrete implementation was not found and the interface is generic, // try to find a generic grain implementation: if (typeInfo.IsGenericType && this.typeToInterfaceData.TryGetValue(GetTypeKey(interfaceType, true), out interfaceData) && TryGetGrainClassData(interfaceData, out implementation, grainClassNamePrefix)) { return true; } return false; } public bool TryGetGrainClassData(int grainInterfaceId, out GrainClassData implementation, string grainClassNamePrefix = null) { implementation = null; GrainInterfaceData interfaceData; if (!table.TryGetValue(grainInterfaceId, out interfaceData)) { return false; } return TryGetGrainClassData(interfaceData, out implementation, grainClassNamePrefix); } private string GetTypeKey(Type interfaceType, bool isGenericGrainClass) { var typeInfo = interfaceType.GetTypeInfo(); if (isGenericGrainClass && typeInfo.IsGenericType) { return typeInfo.GetGenericTypeDefinition().AssemblyQualifiedName; } else { return TypeUtils.GetTemplatedName( TypeUtils.GetFullName(interfaceType), interfaceType, interfaceType.GetGenericArguments(), t => false); } } private static bool TryGetGrainClassData(GrainInterfaceData interfaceData, out GrainClassData implementation, string grainClassNamePrefix) { implementation = null; var implementations = interfaceData.Implementations; if (implementations.Length == 0) return false; if (String.IsNullOrEmpty(grainClassNamePrefix)) { if (implementations.Length == 1) { implementation = implementations[0]; return true; } if (interfaceData.PrimaryImplementation != null) { implementation = interfaceData.PrimaryImplementation; return true; } throw new OrleansException(String.Format("Cannot resolve grain interface ID={0} to a grain class because of multiple implementations of it: {1}", interfaceData.InterfaceId, Utils.EnumerableToString(implementations, d => d.GrainClass, ",", false))); } if (implementations.Length == 1) { if (implementations[0].GrainClass.StartsWith(grainClassNamePrefix, StringComparison.Ordinal)) { implementation = implementations[0]; return true; } return false; } var matches = implementations.Where(impl => impl.GrainClass.Equals(grainClassNamePrefix)).ToArray(); //exact match? if (matches.Length == 0) matches = implementations.Where( impl => impl.GrainClass.StartsWith(grainClassNamePrefix, StringComparison.Ordinal)).ToArray(); //prefix matches if (matches.Length == 0) return false; if (matches.Length == 1) { implementation = matches[0]; return true; } throw new OrleansException(String.Format("Cannot resolve grain interface ID={0}, grainClassNamePrefix={1} to a grain class because of multiple implementations of it: {2}", interfaceData.InterfaceId, grainClassNamePrefix, Utils.EnumerableToString(matches, d => d.GrainClass, ",", false))); } public bool TryGetGrainClassData(string grainImplementationClassName, out GrainClassData implementation) { implementation = null; // have to iterate since _primaryImplementations is not serialized. foreach (var interfaceData in table.Values) { foreach(var implClass in interfaceData.Implementations) if (implClass.GrainClass.Equals(grainImplementationClassName)) { implementation = implClass; return true; } } return false; } public string GetLoadedGrainAssemblies() { return loadedGrainAsemblies != null ? loadedGrainAsemblies.ToStrings() : String.Empty; } public void AddToUnorderedList(int grainClassTypeCode) { if (!unordered.Contains(grainClassTypeCode)) unordered.Add(grainClassTypeCode); } public bool IsUnordered(int grainTypeCode) { return unordered.Contains(grainTypeCode); } } /// <summary> /// Metadata for a grain class /// </summary> [Serializable] internal sealed class GrainClassData { [NonSerialized] private readonly GrainInterfaceMap.GrainInterfaceData interfaceData; [NonSerialized] private readonly Dictionary<string, string> genericClassNames; private readonly PlacementStrategy placementStrategy; private readonly MultiClusterRegistrationStrategy registrationStrategy; private readonly bool isGeneric; internal int GrainTypeCode { get; private set; } internal string GrainClass { get; private set; } internal PlacementStrategy PlacementStrategy { get { return placementStrategy; } } internal GrainInterfaceMap.GrainInterfaceData InterfaceData { get { return interfaceData; } } internal bool IsGeneric { get { return isGeneric; } } public MultiClusterRegistrationStrategy RegistrationStrategy { get { return registrationStrategy; } } internal GrainClassData(int grainTypeCode, string grainClass, bool isGeneric, GrainInterfaceMap.GrainInterfaceData interfaceData, PlacementStrategy placement, MultiClusterRegistrationStrategy registrationStrategy) { GrainTypeCode = grainTypeCode; GrainClass = grainClass; this.isGeneric = isGeneric; this.interfaceData = interfaceData; genericClassNames = new Dictionary<string, string>(); // TODO: initialize only for generic classes placementStrategy = placement ?? PlacementStrategy.GetDefault(); this.registrationStrategy = registrationStrategy ?? MultiClusterRegistrationStrategy.GetDefault(); } internal string GetClassName(string typeArguments) { // Knowing whether the grain implementation is generic allows for non-generic grain classes // to implement one or more generic grain interfaces. // For generic grain classes, the assumption that they take the same generic arguments // as the implemented generic interface(s) still holds. if (!isGeneric || String.IsNullOrWhiteSpace(typeArguments)) { return GrainClass; } else { lock (this) { if (genericClassNames.ContainsKey(typeArguments)) return genericClassNames[typeArguments]; var className = String.Format("{0}[{1}]", GrainClass, typeArguments); genericClassNames.Add(typeArguments, className); return className; } } } internal long GetTypeCode(Type interfaceType) { var typeInfo = interfaceType.GetTypeInfo(); if (typeInfo.IsGenericType && this.IsGeneric) { string args = TypeUtils.GetGenericTypeArgs(typeInfo.GetGenericArguments(), t => true); int hash = Utils.CalculateIdHash(args); return (((long)(hash & 0x00FFFFFF)) << 32) + GrainTypeCode; } else { return GrainTypeCode; } } public override string ToString() { return String.Format("{0}:{1}", GrainClass, GrainTypeCode); } public override int GetHashCode() { return GrainTypeCode; } public override bool Equals(object obj) { if(!(obj is GrainClassData)) return false; return GrainTypeCode == ((GrainClassData) obj).GrainTypeCode; } } }
// 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 Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Test.Utilities; using System; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { internal class AccessibilityTests : CSharpResultProviderTestBase { [WorkItem(889710, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/889710")] [Fact] public void HideNonPublicMembersBaseClass() { var sourceA = @"public class A { public object FA0; internal object FA1; protected internal object FA2; protected object FA3; private object FA4; public object PA0 { get { return null; } } internal object PA1 { get { return null; } } protected internal object PA2 { get { return null; } } protected object PA3 { get { return null; } } private object PA4 { get { return null; } } public object PA5 { set { } } public object PA6 { internal get; set; } public object PA7 { protected internal get; set; } public object PA8 { protected get; set; } public object PA9 { private get; set; } internal object PAA { private get; set; } protected internal object PAB { internal get; set; } protected internal object PAC { protected get; set; } protected object PAD { private get; set; } public static object SFA0; internal static object SFA1; protected static internal object SPA2 { get { return null; } } protected static object SPA3 { get { return null; } } public static object SPA4 { private get { return null; } set { } } }"; var sourceB = @"public class B : A { public object FB0; internal object FB1; protected internal object FB2; protected object FB3; private object FB4; public object PB0 { get { return null; } } internal object PB1 { get { return null; } } protected internal object PB2 { get { return null; } } protected object PB3 { get { return null; } } private object PB4 { get { return null; } } public object PB5 { set { } } public object PB6 { internal get; set; } public object PB7 { protected internal get; set; } public object PB8 { protected get; set; } public object PB9 { private get; set; } internal object PBA { private get; set; } protected internal object PBB { internal get; set; } protected internal object PBC { protected get; set; } protected object PBD { private get; set; } public static object SPB0 { get { return null; } } public static object SPB1 { internal get { return null; } set { } } protected static internal object SFB2; protected static object SFB3; private static object SFB4; } class C { A a = new B(); }"; // Derived class in assembly with PDB, // base class in assembly without PDB. var compilationA = CSharpTestBase.CreateCompilationWithMscorlib(sourceA, options: TestOptions.ReleaseDll); var bytesA = compilationA.EmitToArray(); var referenceA = MetadataReference.CreateFromImage(bytesA); var compilationB = CSharpTestBase.CreateCompilationWithMscorlib(sourceB, options: TestOptions.DebugDll, references: new MetadataReference[] { referenceA }); var bytesB = compilationB.EmitToArray(); var assemblyA = ReflectionUtilities.Load(bytesA); var assemblyB = ReflectionUtilities.Load(bytesB); DkmClrValue value; using (ReflectionUtilities.LoadAssemblies(assemblyA, assemblyB)) { var runtime = new DkmClrRuntimeInstance(new[] { assemblyB }); var type = assemblyB.GetType("C", throwOnError: true); value = CreateDkmClrValue( Activator.CreateInstance(type), runtime.GetType((TypeImpl)type)); } var rootExpr = "new C()"; var evalResult = FormatResult(rootExpr, value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.HideNonPublicMembers)); Verify(evalResult, EvalResult(rootExpr, "{C}", "C", rootExpr, DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("a", "{B}", "A {B}", "(new C()).a", DkmEvaluationResultFlags.Expandable)); // The native EE includes properties where the setter is accessible but the getter is not. // We treat those properties as non-public. children = GetChildren(children[0]); Verify(children, EvalResult("FA0", "null", "object", "(new C()).a.FA0"), EvalResult("FA2", "null", "object", "(new C()).a.FA2"), EvalResult("FA3", "null", "object", "(new C()).a.FA3"), EvalResult("FB0", "null", "object", "((B)(new C()).a).FB0"), EvalResult("FB1", "null", "object", "((B)(new C()).a).FB1"), EvalResult("FB2", "null", "object", "((B)(new C()).a).FB2"), EvalResult("FB3", "null", "object", "((B)(new C()).a).FB3"), EvalResult("FB4", "null", "object", "((B)(new C()).a).FB4"), EvalResult("PA0", "null", "object", "(new C()).a.PA0", DkmEvaluationResultFlags.ReadOnly), EvalResult("PA2", "null", "object", "(new C()).a.PA2", DkmEvaluationResultFlags.ReadOnly), EvalResult("PA3", "null", "object", "(new C()).a.PA3", DkmEvaluationResultFlags.ReadOnly), EvalResult("PA7", "null", "object", "(new C()).a.PA7"), EvalResult("PA8", "null", "object", "(new C()).a.PA8"), EvalResult("PAC", "null", "object", "(new C()).a.PAC"), EvalResult("PB0", "null", "object", "((B)(new C()).a).PB0", DkmEvaluationResultFlags.ReadOnly), EvalResult("PB1", "null", "object", "((B)(new C()).a).PB1", DkmEvaluationResultFlags.ReadOnly), EvalResult("PB2", "null", "object", "((B)(new C()).a).PB2", DkmEvaluationResultFlags.ReadOnly), EvalResult("PB3", "null", "object", "((B)(new C()).a).PB3", DkmEvaluationResultFlags.ReadOnly), EvalResult("PB4", "null", "object", "((B)(new C()).a).PB4", DkmEvaluationResultFlags.ReadOnly), EvalResult("PB6", "null", "object", "((B)(new C()).a).PB6"), EvalResult("PB7", "null", "object", "((B)(new C()).a).PB7"), EvalResult("PB8", "null", "object", "((B)(new C()).a).PB8"), EvalResult("PB9", "null", "object", "((B)(new C()).a).PB9"), EvalResult("PBA", "null", "object", "((B)(new C()).a).PBA"), EvalResult("PBB", "null", "object", "((B)(new C()).a).PBB"), EvalResult("PBC", "null", "object", "((B)(new C()).a).PBC"), EvalResult("PBD", "null", "object", "((B)(new C()).a).PBD"), EvalResult("Static members", null, "", "B", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class), EvalResult("Non-Public members", null, "", "(new C()).a, hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); // Static members var more = GetChildren(children[children.Length - 2]); Verify(more, EvalResult("SFA0", "null", "object", "A.SFA0"), EvalResult("SFB2", "null", "object", "B.SFB2"), EvalResult("SFB3", "null", "object", "B.SFB3"), EvalResult("SFB4", "null", "object", "B.SFB4"), EvalResult("SPA2", "null", "object", "A.SPA2", DkmEvaluationResultFlags.ReadOnly), EvalResult("SPA3", "null", "object", "A.SPA3", DkmEvaluationResultFlags.ReadOnly), EvalResult("SPB0", "null", "object", "B.SPB0", DkmEvaluationResultFlags.ReadOnly), EvalResult("SPB1", "null", "object", "B.SPB1"), EvalResult("Non-Public members", null, "", "B, hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); // Non-Public static members more = GetChildren(more[more.Length - 1]); Verify(more, EvalResult("SFA1", "null", "object", "A.SFA1"), EvalResult("SPA4", "null", "object", "A.SPA4")); // Non-Public members more = GetChildren(children[children.Length - 1]); Verify(more, EvalResult("FA1", "null", "object", "(new C()).a.FA1"), EvalResult("FA4", "null", "object", "(new C()).a.FA4"), EvalResult("PA1", "null", "object", "(new C()).a.PA1", DkmEvaluationResultFlags.ReadOnly), EvalResult("PA4", "null", "object", "(new C()).a.PA4", DkmEvaluationResultFlags.ReadOnly), EvalResult("PA6", "null", "object", "(new C()).a.PA6"), EvalResult("PA9", "null", "object", "(new C()).a.PA9"), EvalResult("PAA", "null", "object", "(new C()).a.PAA"), EvalResult("PAB", "null", "object", "(new C()).a.PAB"), EvalResult("PAD", "null", "object", "(new C()).a.PAD")); } [WorkItem(889710, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/889710")] [Fact] public void HideNonPublicMembersDerivedClass() { var sourceA = @"public class A { public object FA0; internal object FA1; protected internal object FA2; protected object FA3; private object FA4; public object PA0 { get { return null; } } internal object PA1 { get { return null; } } protected internal object PA2 { get { return null; } } protected object PA3 { get { return null; } } private object PA4 { get { return null; } } public object PA5 { set { } } public object PA6 { internal get; set; } public object PA7 { protected internal get; set; } public object PA8 { protected get; set; } public object PA9 { private get; set; } internal object PAA { private get; set; } protected internal object PAB { internal get; set; } protected internal object PAC { protected get; set; } protected object PAD { private get; set; } public static object SFA0; internal static object SFA1; protected static internal object SPA2 { get { return null; } } protected static object SPA3 { get { return null; } } public static object SPA4 { private get { return null; } set { } } }"; var sourceB = @"public class B : A { public object FB0; internal object FB1; protected internal object FB2; protected object FB3; private object FB4; public object PB0 { get { return null; } } internal object PB1 { get { return null; } } protected internal object PB2 { get { return null; } } protected object PB3 { get { return null; } } private object PB4 { get { return null; } } public object PB5 { set { } } public object PB6 { internal get; set; } public object PB7 { protected internal get; set; } public object PB8 { protected get; set; } public object PB9 { private get; set; } internal object PBA { private get; set; } protected internal object PBB { internal get; set; } protected internal object PBC { protected get; set; } protected object PBD { private get; set; } public static object SPB0 { get { return null; } } public static object SPB1 { internal get { return null; } set { } } protected static internal object SFB2; protected static object SFB3; private static object SFB4; } class C { A a = new B(); }"; // Base class in assembly with PDB, // derived class in assembly without PDB. var compilationA = CSharpTestBase.CreateCompilationWithMscorlib(sourceA, options: TestOptions.DebugDll); var bytesA = compilationA.EmitToArray(); var referenceA = MetadataReference.CreateFromImage(bytesA); var compilationB = CSharpTestBase.CreateCompilationWithMscorlib(sourceB, options: TestOptions.ReleaseDll, references: new MetadataReference[] { referenceA }); var bytesB = compilationB.EmitToArray(); var assemblyA = ReflectionUtilities.Load(bytesA); var assemblyB = ReflectionUtilities.Load(bytesB); DkmClrValue value; using (ReflectionUtilities.LoadAssemblies(assemblyA, assemblyB)) { var runtime = new DkmClrRuntimeInstance(new[] { assemblyA }); var type = assemblyB.GetType("C", throwOnError: true); value = CreateDkmClrValue( Activator.CreateInstance(type), runtime.GetType((TypeImpl)type)); } var rootExpr = "new C()"; var evalResult = FormatResult(rootExpr, value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.HideNonPublicMembers)); Verify(evalResult, EvalResult(rootExpr, "{C}", "C", rootExpr, DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("Non-Public members", null, "", "new C(), hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); children = GetChildren(children[0]); Verify(children, EvalResult("a", "{B}", "A {B}", "(new C()).a", DkmEvaluationResultFlags.Expandable)); // The native EE includes properties where the // setter is accessible but the getter is not. // We treat those properties as non-public. children = GetChildren(children[0]); Verify(children, EvalResult("FA0", "null", "object", "(new C()).a.FA0"), EvalResult("FA1", "null", "object", "(new C()).a.FA1"), EvalResult("FA2", "null", "object", "(new C()).a.FA2"), EvalResult("FA3", "null", "object", "(new C()).a.FA3"), EvalResult("FA4", "null", "object", "(new C()).a.FA4"), EvalResult("FB0", "null", "object", "((B)(new C()).a).FB0"), EvalResult("FB2", "null", "object", "((B)(new C()).a).FB2"), EvalResult("FB3", "null", "object", "((B)(new C()).a).FB3"), EvalResult("PA0", "null", "object", "(new C()).a.PA0", DkmEvaluationResultFlags.ReadOnly), EvalResult("PA1", "null", "object", "(new C()).a.PA1", DkmEvaluationResultFlags.ReadOnly), EvalResult("PA2", "null", "object", "(new C()).a.PA2", DkmEvaluationResultFlags.ReadOnly), EvalResult("PA3", "null", "object", "(new C()).a.PA3", DkmEvaluationResultFlags.ReadOnly), EvalResult("PA4", "null", "object", "(new C()).a.PA4", DkmEvaluationResultFlags.ReadOnly), EvalResult("PA6", "null", "object", "(new C()).a.PA6"), EvalResult("PA7", "null", "object", "(new C()).a.PA7"), EvalResult("PA8", "null", "object", "(new C()).a.PA8"), EvalResult("PA9", "null", "object", "(new C()).a.PA9"), EvalResult("PAA", "null", "object", "(new C()).a.PAA"), EvalResult("PAB", "null", "object", "(new C()).a.PAB"), EvalResult("PAC", "null", "object", "(new C()).a.PAC"), EvalResult("PAD", "null", "object", "(new C()).a.PAD"), EvalResult("PB0", "null", "object", "((B)(new C()).a).PB0", DkmEvaluationResultFlags.ReadOnly), EvalResult("PB2", "null", "object", "((B)(new C()).a).PB2", DkmEvaluationResultFlags.ReadOnly), EvalResult("PB3", "null", "object", "((B)(new C()).a).PB3", DkmEvaluationResultFlags.ReadOnly), EvalResult("PB7", "null", "object", "((B)(new C()).a).PB7"), EvalResult("PB8", "null", "object", "((B)(new C()).a).PB8"), EvalResult("PBC", "null", "object", "((B)(new C()).a).PBC"), EvalResult("Static members", null, "", "B", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class), EvalResult("Non-Public members", null, "", "(new C()).a, hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); // Static members var more = GetChildren(children[children.Length - 2]); Verify(more, EvalResult("SFA0", "null", "object", "A.SFA0"), EvalResult("SFA1", "null", "object", "A.SFA1"), EvalResult("SFB2", "null", "object", "B.SFB2"), EvalResult("SFB3", "null", "object", "B.SFB3"), EvalResult("SPA2", "null", "object", "A.SPA2", DkmEvaluationResultFlags.ReadOnly), EvalResult("SPA3", "null", "object", "A.SPA3", DkmEvaluationResultFlags.ReadOnly), EvalResult("SPA4", "null", "object", "A.SPA4"), EvalResult("SPB0", "null", "object", "B.SPB0", DkmEvaluationResultFlags.ReadOnly), EvalResult("Non-Public members", null, "", "B, hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); // Non-Public static members more = GetChildren(more[more.Length - 1]); Verify(more, EvalResult("SFB4", "null", "object", "B.SFB4"), EvalResult("SPB1", "null", "object", "B.SPB1")); // Non-Public members more = GetChildren(children[children.Length - 1]); Verify(more, EvalResult("FB1", "null", "object", "((B)(new C()).a).FB1"), EvalResult("FB4", "null", "object", "((B)(new C()).a).FB4"), EvalResult("PB1", "null", "object", "((B)(new C()).a).PB1", DkmEvaluationResultFlags.ReadOnly), EvalResult("PB4", "null", "object", "((B)(new C()).a).PB4", DkmEvaluationResultFlags.ReadOnly), EvalResult("PB6", "null", "object", "((B)(new C()).a).PB6"), EvalResult("PB9", "null", "object", "((B)(new C()).a).PB9"), EvalResult("PBA", "null", "object", "((B)(new C()).a).PBA"), EvalResult("PBB", "null", "object", "((B)(new C()).a).PBB"), EvalResult("PBD", "null", "object", "((B)(new C()).a).PBD")); } /// <summary> /// Class in assembly with no module. (For instance, /// an anonymous type created during debugging.) /// </summary> [Fact] public void NoModule() { var source = @"class C { object F; }"; var assembly = GetAssembly(source); var runtime = new DkmClrRuntimeInstance(new[] { assembly }, (r, a) => null); var type = assembly.GetType("C"); var value = CreateDkmClrValue( Activator.CreateInstance(type), runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.HideNonPublicMembers)); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); } } }
/* ChatObject_subscriber.cs A subscription example This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C# -example <arch> Chat.idl Example subscription of type ChatObject automatically generated by 'rtiddsgen'. To test them, follow these steps: (1) Compile this file and the example publication. (2) Start the subscription with the command objs\<arch>${constructMap.nativeFQNameInModule}_subscriber <domain_id> <sample_count> (3) Start the publication with the command objs\<arch>${constructMap.nativeFQNameInModule}_publisher <domain_id> <sample_count> (4) [Optional] Specify the list of discovery initial peers and multicast receive addresses via an environment variable or a file (in the current working directory) called NDDS_DISCOVERY_PEERS. You can run any number of publishers and subscribers programs, and can add and remove them dynamically from the domain. Example: To run the example application on domain <domain_id>: bin\<Debug|Release>\ChatObject_publisher <domain_id> <sample_count> bin\<Debug|Release>\ChatObject_subscriber <domain_id> <sample_count> */ using System; using System.Collections.Generic; using System.Text; namespace My{ public class ChatObjectSubscriber { public class ChatObjectListener : DDS.DataReaderListener { public override void on_requested_deadline_missed( DDS.DataReader reader, ref DDS.RequestedDeadlineMissedStatus status) {} public override void on_requested_incompatible_qos( DDS.DataReader reader, DDS.RequestedIncompatibleQosStatus status) {} public override void on_sample_rejected( DDS.DataReader reader, ref DDS.SampleRejectedStatus status) {} public override void on_liveliness_changed( DDS.DataReader reader, ref DDS.LivelinessChangedStatus status) {} public override void on_sample_lost( DDS.DataReader reader, ref DDS.SampleLostStatus status) {} public override void on_subscription_matched( DDS.DataReader reader, ref DDS.SubscriptionMatchedStatus status) {} public override void on_data_available(DDS.DataReader reader) { ChatObjectDataReader ChatObject_reader = (ChatObjectDataReader)reader; try { ChatObject_reader.read( /*>>><<<*/ data_seq, info_seq, DDS.ResourceLimitsQosPolicy.LENGTH_UNLIMITED, DDS.SampleStateKind.ANY_SAMPLE_STATE, DDS.ViewStateKind.ANY_VIEW_STATE, DDS.InstanceStateKind.ANY_INSTANCE_STATE); } catch(DDS.Retcode_NoData) { return; } catch(DDS.Exception e) { Console.WriteLine("take/read error {0}", e); return; } System.Int32 data_length = data_seq.length; for (int i = 0; i < data_length; ++i) { if (info_seq.get_at(i).valid_data) { ChatObjectTypeSupport.print_data(data_seq.get_at(i)); } } try { ChatObject_reader.return_loan(data_seq, info_seq); } catch(DDS.Exception e) { Console.WriteLine("return loan error {0}", e); } } public ChatObjectListener() { data_seq = new ChatObjectSeq(); info_seq = new DDS.SampleInfoSeq(); } private ChatObjectSeq data_seq; private DDS.SampleInfoSeq info_seq; }; public static void Main(string[] args) { // --- Get domain ID --- // int domain_id = 0; if (args.Length >= 1) { domain_id = Int32.Parse(args[0]); } // --- Get max loop count; 0 means infinite loop --- // int sample_count = 0; if (args.Length >= 2) { sample_count = Int32.Parse(args[1]); } /* Uncomment this to turn on additional logging NDDS.ConfigLogger.get_instance().set_verbosity_by_category( NDDS.LogCategory.NDDS_CONFIG_LOG_CATEGORY_API, NDDS.LogVerbosity.NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ // --- Run --- // try { ChatObjectSubscriber.subscribe( domain_id, sample_count); } catch(DDS.Exception) { Console.WriteLine("error in subscriber"); } } static void subscribe(int domain_id, int sample_count) { // --- Create participant --- // /* To customize the participant QoS, use the configuration file USER_QOS_PROFILES.xml */ DDS.DomainParticipant participant = DDS.DomainParticipantFactory.get_instance().create_participant( domain_id, DDS.DomainParticipantFactory.PARTICIPANT_QOS_DEFAULT, null /* listener */, DDS.StatusMask.STATUS_MASK_NONE); if (participant == null) { shutdown(participant); throw new ApplicationException("create_participant error"); } // --- Create subscriber --- // /* To customize the subscriber QoS, use the configuration file USER_QOS_PROFILES.xml */ DDS.Subscriber subscriber = participant.create_subscriber( DDS.DomainParticipant.SUBSCRIBER_QOS_DEFAULT, null /* listener */, DDS.StatusMask.STATUS_MASK_NONE); if (subscriber == null) { shutdown(participant); throw new ApplicationException("create_subscriber error"); } // --- Create topic --- // /* Register the type before creating the topic */ System.String type_name = ChatObjectTypeSupport.get_type_name(); try { ChatObjectTypeSupport.register_type( participant, type_name); } catch(DDS.Exception e) { Console.WriteLine("register_type error {0}", e); shutdown(participant); throw e; } /* To customize the topic QoS, use the configuration file USER_QOS_PROFILES.xml */ DDS.Topic topic = participant.create_topic( My.CHAT_TOPIC_NAME.VALUE, /*>>><<<*/ type_name, DDS.DomainParticipant.TOPIC_QOS_DEFAULT, null /* listener */, DDS.StatusMask.STATUS_MASK_NONE); if (topic == null) { shutdown(participant); throw new ApplicationException("create_topic error"); } /* >>> Create ContentFiltered Topic */ DDS.StringWrapper[] cft_param_list = new DDS.StringWrapper[] { "'Rajive'", "'Shannon'", "'Jaromy'" }; DDS.StringSeq cft_parameters = new DDS.StringSeq(3); cft_parameters.from_array(cft_param_list); DDS.ContentFilteredTopic cft = participant.create_contentfilteredtopic("Chat/filtered", topic, "(id = %0 OR id = %1 OR id = %2)", cft_parameters); if (cft == null) { Console.WriteLine("create_contentfilteredtopic error\n"); shutdown(participant); throw new ApplicationException("create_contentfilteredtopic error"); } /* <<< */ // --- Create reader --- // /* Create a data reader listener */ ChatObjectListener reader_listener = new ChatObjectListener(); /* To customize the data reader QoS, use the configuration file USER_QOS_PROFILES.xml */ DDS.DataReader reader = subscriber.create_datareader( cft, /*>>><<<*/ DDS.Subscriber.DATAREADER_QOS_DEFAULT, null, /*>>><<<*/ DDS.StatusMask.STATUS_MASK_NONE); /*>>><<<*/ if (reader == null) { shutdown(participant); reader_listener = null; throw new ApplicationException("create_datareader error"); } /* >>> Setup StatusCondition */ DDS.StatusCondition status_condition = reader.get_statuscondition(); if (status_condition.Equals(null)) { Console.WriteLine("get_statuscondition error\n"); shutdown(participant); throw new ApplicationException("get_statuscondition error"); } try { status_condition.set_enabled_statuses((DDS.StatusMask)DDS.StatusKind.DATA_AVAILABLE_STATUS); } catch { Console.WriteLine("set_enabled_statuses error\n"); shutdown(participant); throw new ApplicationException("set_enabled_statuses error"); } /* <<< */ /* >>> Setup WaitSet */ DDS.WaitSet waitset = new DDS.WaitSet(); try { waitset.attach_condition(status_condition); } catch { // ... error waitset.Dispose(); waitset = null; shutdown(participant); reader_listener.Dispose(); reader_listener = null; return; } // holder for active conditions DDS.ConditionSeq active_conditions = new DDS.ConditionSeq(); /* <<< */ // --- Wait for data --- // /* Main loop */ const System.Int32 receive_period = 4000; // milliseconds for (int count=0; (sample_count == 0) || (count < sample_count); ++count) { Console.WriteLine( "ChatObject subscriber sleeping ...", receive_period / 1000); /* >>> Wait */ /* Wait for condition to trigger */ try { waitset.wait(active_conditions, DDS.Duration_t.DURATION_INFINITE); reader_listener.on_data_available(reader); } catch { } /* <<< */ // System.Threading.Thread.Sleep(receive_period); /*>>><<<*/ } // --- Shutdown --- // /* Delete all entities */ waitset.Dispose(); waitset = null; /*>>><<<*/ shutdown(participant); reader_listener = null; } static void shutdown( DDS.DomainParticipant participant) { /* Delete all entities */ if (participant != null) { participant.delete_contained_entities(); DDS.DomainParticipantFactory.get_instance().delete_participant( ref participant); } /* RTI Connext provides finalize_instance() method on domain participant factory for users who want to release memory used by the participant factory. Uncomment the following block of code for clean destruction of the singleton. */ /* try { DDS.DomainParticipantFactory.finalize_instance(); } catch(DDS.Exception e) { Console.WriteLine("finalize_instance error {0}", e); throw e; } */ } } }
// 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. // // // A HostSecurityManager gives a hosting application the chance to // participate in the security decisions in the AppDomain. // namespace System.Security { using System.Collections; #if FEATURE_CLICKONCE using System.Deployment.Internal.Isolation; using System.Deployment.Internal.Isolation.Manifest; using System.Runtime.Hosting; #endif using System.Reflection; using System.Security; using System.Security.Permissions; using System.Security.Policy; using System.Runtime.Versioning; using System.Diagnostics.Contracts; [Serializable] [Flags] [System.Runtime.InteropServices.ComVisible(true)] public enum HostSecurityManagerOptions { None = 0x0000, HostAppDomainEvidence = 0x0001, [Obsolete("AppDomain policy levels are obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")] HostPolicyLevel = 0x0002, HostAssemblyEvidence = 0x0004, HostDetermineApplicationTrust = 0x0008, HostResolvePolicy = 0x0010, AllFlags = 0x001F } [System.Security.SecurityCritical] // auto-generated_required [Serializable] #if !FEATURE_CORECLR [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.Infrastructure)] #endif [System.Runtime.InteropServices.ComVisible(true)] public class HostSecurityManager { public HostSecurityManager () {} // The host can choose which events he wants to participate in. This property can be set when // the host only cares about a subset of the capabilities exposed through the HostSecurityManager. public virtual HostSecurityManagerOptions Flags { get { // We use AllFlags as the default. return HostSecurityManagerOptions.AllFlags; } } #if FEATURE_CAS_POLICY // provide policy for the AppDomain. [Obsolete("AppDomain policy levels are obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")] public virtual PolicyLevel DomainPolicy { get { if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyExplicit")); } return null; } } #endif public virtual Evidence ProvideAppDomainEvidence (Evidence inputEvidence) { // The default implementation does not modify the input evidence. return inputEvidence; } public virtual Evidence ProvideAssemblyEvidence (Assembly loadedAssembly, Evidence inputEvidence) { // The default implementation does not modify the input evidence. return inputEvidence; } #if FEATURE_CLICKONCE [System.Security.SecurityCritical] // auto-generated [SecurityPermissionAttribute(SecurityAction.Assert, Unrestricted=true)] public virtual ApplicationTrust DetermineApplicationTrust(Evidence applicationEvidence, Evidence activatorEvidence, TrustManagerContext context) { if (applicationEvidence == null) throw new ArgumentNullException("applicationEvidence"); Contract.EndContractBlock(); // This method looks for a trust decision for the ActivationContext in three locations, in order // of preference: // // 1. Supplied by the host in the AppDomainSetup. If the host supplied a decision this way, it // will be in the applicationEvidence. // 2. Reuse the ApplicationTrust from the current AppDomain // 3. Ask the TrustManager for a trust decision // get the activation context from the application evidence. // The default HostSecurityManager does not examine the activatorEvidence // but other security managers could use it to figure out the // evidence of the domain attempting to activate the application. ActivationArguments activationArgs = applicationEvidence.GetHostEvidence<ActivationArguments>(); if (activationArgs == null) throw new ArgumentException(Environment.GetResourceString("Policy_MissingActivationContextInAppEvidence")); ActivationContext actCtx = activationArgs.ActivationContext; if (actCtx == null) throw new ArgumentException(Environment.GetResourceString("Policy_MissingActivationContextInAppEvidence")); // Make sure that any ApplicationTrust we find applies to the ActivationContext we're // creating the new AppDomain for. ApplicationTrust appTrust = applicationEvidence.GetHostEvidence<ApplicationTrust>(); if (appTrust != null && !CmsUtils.CompareIdentities(appTrust.ApplicationIdentity, activationArgs.ApplicationIdentity, ApplicationVersionMatch.MatchExactVersion)) { appTrust = null; } // If there was not a trust decision supplied in the Evidence, we can reuse the existing trust // decision from this domain if its identity matches the ActivationContext of the new domain. // Otherwise consult the TrustManager for a trust decision if (appTrust == null) { if (AppDomain.CurrentDomain.ApplicationTrust != null && CmsUtils.CompareIdentities(AppDomain.CurrentDomain.ApplicationTrust.ApplicationIdentity, activationArgs.ApplicationIdentity, ApplicationVersionMatch.MatchExactVersion)) { appTrust = AppDomain.CurrentDomain.ApplicationTrust; } else { appTrust = ApplicationSecurityManager.DetermineApplicationTrustInternal(actCtx, context); } } // If the trust decision allows the application to run, then it should also have a permission set // which is at least the permission set the application requested. ApplicationSecurityInfo appRequest = new ApplicationSecurityInfo(actCtx); if (appTrust != null && appTrust.IsApplicationTrustedToRun && !appRequest.DefaultRequestSet.IsSubsetOf(appTrust.DefaultGrantSet.PermissionSet)) { throw new InvalidOperationException(Environment.GetResourceString("Policy_AppTrustMustGrantAppRequest")); } return appTrust; } #endif // FEATURE_CLICKONCE #if FEATURE_CAS_POLICY // Query the CLR to see what it would have granted a specific set of evidence public virtual PermissionSet ResolvePolicy(Evidence evidence) { if (evidence == null) throw new ArgumentNullException("evidence"); Contract.EndContractBlock(); // // If the evidence is from the GAC then the result is full trust. // In a homogenous domain, then the application trust object provides the grant set. // When CAS policy is disabled, the result is full trust. // Otherwise, the result comes from evaluating CAS policy. // if (evidence.GetHostEvidence<GacInstalled>() != null) { return new PermissionSet(PermissionState.Unrestricted); } else if (AppDomain.CurrentDomain.IsHomogenous) { return AppDomain.CurrentDomain.GetHomogenousGrantSet(evidence); } else if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled) { return new PermissionSet(PermissionState.Unrestricted); } else { return SecurityManager.PolicyManager.CodeGroupResolve(evidence, false); } } #endif /// <summary> /// Determine what types of evidence the host might be able to supply for the AppDomain if requested /// </summary> /// <returns></returns> public virtual Type[] GetHostSuppliedAppDomainEvidenceTypes() { return null; } /// <summary> /// Determine what types of evidence the host might be able to supply for an assembly if requested /// </summary> public virtual Type[] GetHostSuppliedAssemblyEvidenceTypes(Assembly assembly) { return null; } /// <summary> /// Ask the host to supply a specific type of evidence for the AppDomain /// </summary> public virtual EvidenceBase GenerateAppDomainEvidence(Type evidenceType) { return null; } /// <summary> /// Ask the host to supply a specific type of evidence for an assembly /// </summary> public virtual EvidenceBase GenerateAssemblyEvidence(Type evidenceType, Assembly assembly) { return null; } } }
using NUnit.Framework; using System; using System.Collections.Generic; using System.IO; namespace DiskQueue.Tests { [TestFixture] public class PersistentQueueTests : PersistentQueueTestsBase { [Test] [ExpectedException(typeof(InvalidOperationException), ExpectedMessage = "Another instance of the queue is already in action, or directory does not exists")] public void Only_single_instance_of_queue_can_exists_at_any_one_time() { using (new PersistentQueue(path)) { new PersistentQueue(path); } } [Test] public void If_a_non_running_process_has_a_lock_then_can_start_an_instance () { Directory.CreateDirectory(path); var lockFilePath = Path.Combine(path, "lock"); File.WriteAllText(lockFilePath, "78924759045"); using (new PersistentQueue(path)) { Assert.Pass(); } } [Test] public void Can_create_new_queue() { new PersistentQueue(path).Dispose(); } [Test] [ExpectedException(typeof(InvalidOperationException), ExpectedMessage ="Unexpected data in transaction log. Expected to get transaction separator but got unknown data. Tx #1")] public void Corrupt_index_file_should_throw() { var buffer = new List<byte>(); buffer.AddRange(Guid.NewGuid().ToByteArray()); buffer.AddRange(Guid.NewGuid().ToByteArray()); buffer.AddRange(Guid.NewGuid().ToByteArray()); Directory.CreateDirectory(path); File.WriteAllBytes(Path.Combine(path, "transaction.log"), buffer.ToArray()); new PersistentQueue(path); } [Test] public void Dequeing_from_empty_queue_will_return_null() { using (var queue = new PersistentQueue(path)) using (var session = queue.OpenSession()) { Assert.IsNull(session.Dequeue()); } } [Test] public void Can_enqueue_data_in_queue() { using (var queue = new PersistentQueue(path)) using (var session = queue.OpenSession()) { session.Enqueue(new byte[] { 1, 2, 3, 4 }); session.Flush(); } } [Test] public void Can_dequeue_data_from_queue() { using (var queue = new PersistentQueue(path)) using (var session = queue.OpenSession()) { session.Enqueue(new byte[] { 1, 2, 3, 4 }); session.Flush(); CollectionAssert.AreEqual(new byte[] { 1, 2, 3, 4 }, session.Dequeue()); } } [Test] public void Can_enqueue_and_dequeue_data_after_restarting_queue() { using (var queue = new PersistentQueue(path)) using (var session = queue.OpenSession()) { session.Enqueue(new byte[] { 1, 2, 3, 4 }); session.Flush(); } using (var queue = new PersistentQueue(path)) using (var session = queue.OpenSession()) { CollectionAssert.AreEqual(new byte[] { 1, 2, 3, 4 }, session.Dequeue()); session.Flush(); } } [Test] public void After_dequeue_from_queue_item_no_longer_on_queue() { using (var queue = new PersistentQueue(path)) using (var session = queue.OpenSession()) { session.Enqueue(new byte[] { 1, 2, 3, 4 }); session.Flush(); } using (var queue = new PersistentQueue(path)) using (var session = queue.OpenSession()) { CollectionAssert.AreEqual(new byte[] { 1, 2, 3, 4 }, session.Dequeue()); Assert.IsNull(session.Dequeue()); session.Flush(); } } [Test] public void After_dequeue_from_queue_item_no_longer_on_queue_with_queues_restarts() { using (var queue = new PersistentQueue(path)) using (var session = queue.OpenSession()) { session.Enqueue(new byte[] { 1, 2, 3, 4 }); session.Flush(); } using (var queue = new PersistentQueue(path)) using (var session = queue.OpenSession()) { CollectionAssert.AreEqual(new byte[] { 1, 2, 3, 4 }, session.Dequeue()); session.Flush(); } using (var queue = new PersistentQueue(path)) using (var session = queue.OpenSession()) { Assert.IsNull(session.Dequeue()); session.Flush(); } } [Test] public void Not_flushing_the_session_will_revert_dequequed_items() { using (var queue = new PersistentQueue(path)) using (var session = queue.OpenSession()) { session.Enqueue(new byte[] { 1, 2, 3, 4 }); session.Flush(); } using (var queue = new PersistentQueue(path)) using (var session = queue.OpenSession()) { CollectionAssert.AreEqual(new byte[] { 1, 2, 3, 4 }, session.Dequeue()); //Explicitly ommitted: session.Flush(); } using (var queue = new PersistentQueue(path)) using (var session = queue.OpenSession()) { CollectionAssert.AreEqual(new byte[] { 1, 2, 3, 4 }, session.Dequeue()); session.Flush(); } } [Test] public void Not_flushing_the_session_will_revert_dequequed_items_two_sessions_same_queue() { using (var queue = new PersistentQueue(path)) using (var session = queue.OpenSession()) { session.Enqueue(new byte[] { 1, 2, 3, 4 }); session.Flush(); } using (var queue = new PersistentQueue(path)) using (var session2 = queue.OpenSession()) { using (var session1 = queue.OpenSession()) { CollectionAssert.AreEqual(new byte[] { 1, 2, 3, 4 }, session1.Dequeue()); //Explicitly ommitted: session.Flush(); } CollectionAssert.AreEqual(new byte[] { 1, 2, 3, 4 }, session2.Dequeue()); session2.Flush(); } } [Test] public void Two_sessions_off_the_same_queue_cannot_get_same_item() { using (var queue = new PersistentQueue(path)) using (var session = queue.OpenSession()) { session.Enqueue(new byte[] { 1, 2, 3, 4 }); session.Flush(); } using (var queue = new PersistentQueue(path)) using (var session2 = queue.OpenSession()) using (var session1 = queue.OpenSession()) { CollectionAssert.AreEqual(new byte[] { 1, 2, 3, 4 }, session1.Dequeue()); Assert.IsNull(session2.Dequeue()); } } } }
using System; using Anotar.MetroLog; public class ClassWithException { public async void AsyncMethod() { try { System.Diagnostics.Trace.WriteLine("Foo"); } catch { } } public void Trace() { try { LogTo.Trace(); } catch { } } public void TraceString() { try { LogTo.Trace("TheMessage"); } catch { } } public void TraceStringParams() { try { LogTo.Trace("TheMessage {0}", 1); } catch { } } public void TraceStringException() { try { LogTo.TraceException("TheMessage", new Exception()); } catch { } } public void Debug() { try { LogTo.Debug(); } catch { } } public void DebugString() { try { LogTo.Debug("TheMessage"); } catch { } } public void DebugStringParams() { try { LogTo.Debug("TheMessage {0}", 1); } catch { } } public void DebugStringException() { try { LogTo.DebugException("TheMessage", new Exception()); } catch { } } public void Info() { try { LogTo.Info(); } catch { } } public void InfoString() { try { LogTo.Info("TheMessage"); } catch { } } public void InfoStringParams() { try { LogTo.Info("TheMessage {0}", 1); } catch { } } public void InfoStringException() { try { LogTo.InfoException("TheMessage", new Exception()); } catch { } } public void Warn() { try { LogTo.Warn(); } catch { } } public void WarnString() { try { LogTo.Warn("TheMessage"); } catch { } } public void WarnStringParams() { try { LogTo.Warn("TheMessage {0}", 1); } catch { } } public void WarnStringException() { try { LogTo.WarnException("TheMessage", new Exception()); } catch { } } public void Error() { try { LogTo.Error(); } catch { } } public void ErrorString() { try { LogTo.Error("TheMessage"); } catch { } } public void ErrorStringParams() { try { LogTo.Error("TheMessage {0}", 1); } catch { } } public void ErrorStringException() { try { LogTo.ErrorException("TheMessage", new Exception()); } catch { } } public void Fatal() { try { LogTo.Fatal(); } catch { } } public void FatalString() { try { LogTo.Fatal("TheMessage"); } catch { } } public void FatalStringParams() { try { LogTo.Fatal("TheMessage {0}", 1); } catch { } } public void FatalStringException() { try { LogTo.FatalException("TheMessage", new Exception()); } catch { } } }
using System; using System.Collections; using System.Threading; using Microsoft.SPOT.Hardware; #if NP using SecretLabs.NETMF.Hardware.NetduinoPlus; #endif #if (N2 || N1) using SecretLabs.NETMF.Hardware.Netduino; #endif #if MINI using SecretLabs.NETMF.Hardware.NetduinoMini; #endif namespace TrackerRTC { public class LinearActuator : IDisposable, ILinearActuator { private const int MOVE_CHECK_INTERVAL_TIME = 5000; private double _lastPosition; private double _westPosition; private double _eastPosition; private double _maxCurrent; private readonly OutputPort _megaMotoEnable; private readonly OutputPort _megaMotoPWMA; private readonly OutputPort _megaMotoPWMB; private readonly AnalogInput _linearActuatorSensor; private readonly AnalogInput _megaMotoSensor; #if NP // Netduino 2 / NetduinoPlus 2 pinout // use default pinout private const int NOISE = 2; public LinearActuator() : this(AnalogChannels.ANALOG_PIN_A5, Pins.GPIO_PIN_D7, Pins.GPIO_PIN_D6, Pins.GPIO_PIN_D5, AnalogChannels.ANALOG_PIN_A2) { } public LinearActuator(bool dual) : this(AnalogChannels.ANALOG_PIN_A4, Pins.GPIO_PIN_D10, Pins.GPIO_PIN_D9, Pins.GPIO_PIN_D8, AnalogChannels.ANALOG_PIN_A1) { } #endif #if N2 // Netduino 2 / NetduinoPlus 2 pinout // use default pinout private const int NOISE = 2; public LinearActuator() : this(AnalogChannels.ANALOG_PIN_A5, Pins.GPIO_PIN_D7, Pins.GPIO_PIN_D6, Pins.GPIO_PIN_D5, AnalogChannels.ANALOG_PIN_A2) { } public LinearActuator(bool dual) : this(AnalogChannels.ANALOG_PIN_A4, Pins.GPIO_PIN_D10, Pins.GPIO_PIN_D9, Pins.GPIO_PIN_D8, AnalogChannels.ANALOG_PIN_A1) { } #endif #if N1 // Netduino has I2C at A5, move actuator sensor to A0 private const int NOISE = 1; public LinearActuator() : this(AnalogChannels.ANALOG_PIN_A0, Pins.GPIO_PIN_D7, Pins.GPIO_PIN_D6, Pins.GPIO_PIN_D4, AnalogChannels.ANALOG_PIN_A1) { } public LinearActuator(bool dual) : this(AnalogChannels.ANALOG_PIN_A2, Pins.GPIO_PIN_D10, Pins.GPIO_PIN_D9, Pins.GPIO_PIN_D8, AnalogChannels.ANALOG_PIN_A3) { } #endif #if MINI // Netduino Mini pinout // use default pinout private const int NOISE = 2; public LinearActuator() : this(AnalogChannels.ANALOG_PIN_5, Pins.GPIO_PIN_16, Pins.GPIO_PIN_17, Pins.GPIO_PIN_18, AnalogChannels.ANALOG_PIN_7) { } public LinearActuator(bool dual) : this(AnalogChannels.ANALOG_PIN_6, Pins.GPIO_PIN_15, Pins.GPIO_PIN_20, Pins.GPIO_PIN_19, AnalogChannels.ANALOG_PIN_8) { } #endif public LinearActuator(Cpu.AnalogChannel actuatorSensorPin, Cpu.Pin megaMotoEnablePin, Cpu.Pin megaMotoPWMAPin, Cpu.Pin megaMotoPWMBPin, Cpu.AnalogChannel megaMotoSensorPin) { _megaMotoEnable = new OutputPort(megaMotoEnablePin, false); _megaMotoPWMA = new OutputPort(megaMotoPWMAPin, false); _megaMotoPWMB = new OutputPort(megaMotoPWMBPin, false); _linearActuatorSensor = new AnalogInput(actuatorSensorPin); _linearActuatorSensor.Scale = 255; _megaMotoSensor = new AnalogInput(megaMotoSensorPin); _megaMotoSensor.Scale = 255; RetractedPosition = 90; // default range ExtendedPosition = 270; } /// <summary> /// Fully extend and retract actuator to initialize the range /// </summary> public void Initialize() { Extend(); Retract(); Thread.Sleep(10000); } /// <summary> /// Value from the actuator position sensor /// take the average of 10 samples, throw out the highest and lowest /// </summary> public double CurrentPosition { get { // take the average of 10 samples, throw out the highest and lowest double sum = 0; double highest = 0; double lowest = 255; for (var i = 0; i < 10; i++) { var val = _linearActuatorSensor.Read(); if (val > highest) highest = val; if (val < lowest) lowest = val; sum += val; Thread.Sleep(10); } sum -= (highest + lowest); var avg = sum / 8; return avg; //return _linearActuatorSensor.Read(); } } private double Range { get { return _westPosition - _eastPosition; } } /// <summary> /// Maximum current detected during actuator moves /// </summary> public double MaxCurrent { get { return _maxCurrent; } } /// <summary> /// The position in degrees of the azimuth or elevation when the actuator is fully retracted /// </summary> public double RetractedPosition { get; set; } /// <summary> /// The position in degrees of the azimuth or elevation when the actuator is fully extended /// </summary> public double ExtendedPosition { get; set; } /// <summary> /// The most recent position in degrees /// </summary> public double CurrentAngle { get; set; } /// <summary> /// Calculates angle using sensor position and range /// </summary> public double CalculatedAngle { get { return CalculateAngle(); } } /// <summary> /// Fraction extended from east (0 to 1) /// </summary> public double RelativePosition { get { var position = CurrentPosition - _eastPosition; return position/Range; } } private double CalculateAngle() { var delta = ExtendedPosition - RetractedPosition; var degreesPerStep = delta / Range; var position = CurrentPosition - _eastPosition; var rVal = RetractedPosition; if (position >= 1) rVal = (position * degreesPerStep) + RetractedPosition; CurrentAngle = rVal; return rVal; } /// <summary> /// Move tracker to the requested angle /// </summary> /// <param name="position"></param> public void MoveTo(double position) { if (position > ExtendedPosition) { if (CurrentAngle < ExtendedPosition) { Extend(); CurrentAngle = ExtendedPosition; } return; } if (position < RetractedPosition) { if (CurrentAngle > RetractedPosition) { Retract(); CurrentAngle = RetractedPosition; } return; } if (CalculatedAngle < position) { MoveOut(); while (CalculatedAngle < position) { Thread.Sleep(100); } Stop(); } else if (CalculatedAngle > position) { MoveIn(); while (CalculatedAngle > position) { Thread.Sleep(100); } Stop(); } } private bool IsMoving() { var rVal = false; if (_megaMotoEnable.Read()) { var mark = CurrentPosition; var delta = Math.Abs(mark - _lastPosition); if (delta > NOISE) { _lastPosition = mark; rVal = true; } var current = _megaMotoSensor.Read(); if (current > _maxCurrent) { _maxCurrent = current; } } return rVal; } private void MoveIn() { _lastPosition = CurrentPosition; _megaMotoPWMA.Write(false); _megaMotoPWMB.Write(true); _megaMotoEnable.Write(true); } private void MoveOut() { _lastPosition = CurrentPosition; _megaMotoPWMA.Write(true); _megaMotoPWMB.Write(false); _megaMotoEnable.Write(true); } public void Stop() { _lastPosition = CurrentPosition; _megaMotoPWMA.Write(false); _megaMotoPWMB.Write(false); _megaMotoEnable.Write(false); CalculateAngle(); } /// <summary> /// Move array to fully retracted position /// </summary> public void Retract() { MoveIn(); do { Thread.Sleep(MOVE_CHECK_INTERVAL_TIME); } while (IsMoving()); _lastPosition = CurrentPosition; _eastPosition = _lastPosition; Stop(); } /// <summary> /// Move array to fully extended position /// </summary> public void Extend() { MoveOut(); do { Thread.Sleep(MOVE_CHECK_INTERVAL_TIME); } while (IsMoving()); _lastPosition = CurrentPosition; _westPosition = _lastPosition; Stop(); } public void Dispose() { if (_linearActuatorSensor != null) { _linearActuatorSensor.Dispose(); } if (_megaMotoSensor != null) { _megaMotoSensor.Dispose(); } if (_megaMotoPWMA != null) { _megaMotoPWMA.Dispose(); } if (_megaMotoPWMB != null) { _megaMotoPWMB.Dispose(); } if (_megaMotoEnable != null) { _megaMotoEnable.Dispose(); } GC.SuppressFinalize(this); } } }
// Author: abi // Project: DungeonQuest // Path: C:\code\Xna\DungeonQuest\Graphics // Creation date: 28.03.2007 01:01 // Last modified: 31.07.2007 04:41 #region Using directives using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using DungeonQuest.Game; using DungeonQuest.Helpers; using System; using System.Collections.Generic; using System.Text; using System.Xml; #endregion namespace DungeonQuest.Graphics { /// <summary> /// Texture font for our game, uses GameFont.png. /// If you want to know more details about creating bitmap fonts in XNA, /// how to generate the bitmaps and more details about using it, please /// check out the following links: /// http://blogs.msdn.com/garykac/archive/2006/08/30/728521.aspx /// http://blogs.msdn.com/garykac/articles/732007.aspx /// http://www.angelcode.com/products/bmfont/ /// </summary> public class TextureFont { #region Constants #region Font xml info const string FontXmlInfo = @"<Font Height=""51""> <Char c=""a"" u=""2"" v=""10"" width=""22""/> <Char c=""b"" u=""2"" v=""41"" width=""21""/> <Char c=""c"" u=""2"" v=""71"" width=""21""/> <Char c=""d"" u=""2"" v=""101"" width=""21""/> <Char c=""e"" u=""2"" v=""131"" width=""21""/> <Char c=""f"" u=""2"" v=""161"" width=""16""/> <Char c=""g"" u=""2"" v=""186"" width=""22""/> <Char c=""h"" u=""2"" v=""217"" width=""22""/> <Char c=""i"" u=""2"" v=""248"" width=""10""/> <Char c=""j"" u=""2"" v=""267"" width=""10""/> <Char c=""k"" u=""2"" v=""286"" width=""20""/> <Char c=""l"" u=""2"" v=""315"" width=""10""/> <Char c=""m"" u=""2"" v=""334"" width=""34""/> <Char c=""n"" u=""2"" v=""377"" width=""22""/> <Char c=""o"" u=""2"" v=""408"" width=""20""/> <Char c=""p"" u=""2"" v=""437"" width=""21""/> <Char c=""q"" u=""2"" v=""467"" width=""21""/> <Char c=""r"" u=""54"" v=""10"" width=""21""/> <Char c=""s"" u=""54"" v=""40"" width=""22""/> <Char c=""t"" u=""54"" v=""71"" width=""18""/> <Char c=""u"" u=""54"" v=""98"" width=""22""/> <Char c=""v"" u=""54"" v=""129"" width=""17""/> <Char c=""w"" u=""54"" v=""155"" width=""29""/> <Char c=""x"" u=""54"" v=""193"" width=""20""/> <Char c=""y"" u=""54"" v=""222"" width=""22""/> <Char c=""z"" u=""54"" v=""253"" width=""22""/> <Char c=""A"" u=""54"" v=""284"" width=""17""/> <Char c=""B"" u=""54"" v=""310"" width=""21""/> <Char c=""C"" u=""54"" v=""340"" width=""21""/> <Char c=""D"" u=""54"" v=""370"" width=""21""/> <Char c=""E"" u=""54"" v=""400"" width=""21""/> <Char c=""F"" u=""54"" v=""430"" width=""19""/> <Char c=""G"" u=""54"" v=""458"" width=""20""/> <Char c=""H"" u=""54"" v=""487"" width=""22""/> <Char c=""I"" u=""106"" v=""10"" width=""10""/> <Char c=""J"" u=""106"" v=""29"" width=""22""/> <Char c=""K"" u=""106"" v=""60"" width=""20""/> <Char c=""L"" u=""106"" v=""89"" width=""18""/> <Char c=""M"" u=""106"" v=""116"" width=""29""/> <Char c=""N"" u=""106"" v=""154"" width=""22""/> <Char c=""O"" u=""106"" v=""185"" width=""20""/> <Char c=""P"" u=""106"" v=""214"" width=""18""/> <Char c=""Q"" u=""106"" v=""241"" width=""20""/> <Char c=""R"" u=""106"" v=""270"" width=""22""/> <Char c=""S"" u=""106"" v=""301"" width=""22""/> <Char c=""T"" u=""106"" v=""332"" width=""18""/> <Char c=""U"" u=""106"" v=""359"" width=""22""/> <Char c=""V"" u=""106"" v=""390"" width=""17""/> <Char c=""W"" u=""106"" v=""416"" width=""29""/> <Char c=""X"" u=""106"" v=""454"" width=""20""/> <Char c=""Y"" u=""106"" v=""483"" width=""17""/> <Char c=""Z"" u=""158"" v=""10"" width=""22""/> <Char c=""1"" u=""158"" v=""41"" width=""10""/> <Char c=""2"" u=""158"" v=""60"" width=""21""/> <Char c=""3"" u=""158"" v=""90"" width=""21""/> <Char c=""4"" u=""158"" v=""120"" width=""22""/> <Char c=""5"" u=""158"" v=""151"" width=""21""/> <Char c=""6"" u=""158"" v=""181"" width=""21""/> <Char c=""7"" u=""158"" v=""211"" width=""22""/> <Char c=""8"" u=""158"" v=""242"" width=""20""/> <Char c=""9"" u=""158"" v=""271"" width=""21""/> <Char c=""0"" u=""158"" v=""301"" width=""20""/> <Char c=""-"" u=""158"" v=""330"" width=""19""/> <Char c=""="" u=""158"" v=""358"" width=""32""/> <Char c=""!"" u=""158"" v=""399"" width=""10""/> <Char c=""@"" u=""158"" v=""418"" width=""54""/> <Char c=""#"" u=""158"" v=""481"" width=""30""/> <Char c=""$"" u=""210"" v=""10"" width=""22""/> <Char c=""%"" u=""210"" v=""41"" width=""35""/> <Char c=""^"" u=""210"" v=""85"" width=""26""/> <Char c=""&amp;"" u=""210"" v=""120"" width=""21""/> <Char c=""*"" u=""210"" v=""150"" width=""15""/> <Char c=""("" u=""210"" v=""174"" width=""10""/> <Char c="")"" u=""210"" v=""193"" width=""10""/> <Char c=""_"" u=""210"" v=""212"" width=""30""/> <Char c=""+"" u=""210"" v=""251"" width=""32""/> <Char c=""["" u=""210"" v=""292"" width=""9""/> <Char c=""]"" u=""210"" v=""310"" width=""9""/> <Char c=""{"" u=""210"" v=""328"" width=""9""/> <Char c=""}"" u=""210"" v=""346"" width=""9""/> <Char c="";"" u=""210"" v=""364"" width=""10""/> <Char c=""'"" u=""210"" v=""383"" width=""10""/> <Char c="":"" u=""210"" v=""402"" width=""10""/> <Char c=""&amp;qwo;"" u=""210"" v=""421"" width=""18""/> <Char c="","" u=""210"" v=""448"" width=""10""/> <Char c=""."" u=""210"" v=""467"" width=""10""/> <Char c=""&lt;"" u=""262"" v=""10"" width=""32""/> <Char c=""&gt;"" u=""262"" v=""51"" width=""32""/> <Char c=""/"" u=""262"" v=""92"" width=""16""/> <Char c=""?"" u=""262"" v=""117"" width=""21""/> <Char c=""\"" u=""262"" v=""147"" width=""16""/> <Char c=""|"" u=""262"" v=""172"" width=""10""/> <Char c="" "" u=""262"" v=""191"" width=""15""/> </Font>"; #endregion /// <summary> /// Game font filename for our bitmap. /// </summary> const string GameFontFilename = "Gothican"; /// <summary> /// TextureFont height /// </summary> const int FontHeight = 51;//first try texture: 36; /// <summary> /// Substract this value from the y postion when rendering. /// Most letters start below the CharRects, this fixes that issue. /// </summary> const int SubRenderHeight = 0;//7;//5;//7;//6;' /// <summary> /// Substract this value from the pixel location we assign for each /// letter for rendering. /// </summary> const int SubRenderWidth = -3;//-6;//5; /// <summary> /// Char rectangles, goes from space (32) to ~ (126). /// Height is not used (always the same), instead we save the actual /// used width for rendering in the height value! /// This are the characters: /// !"#$%&'()*+,-./0123456789:;<=>?@ /// ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_` /// abcdefghijklmnopqrstuvwxyz{|}~ /// /// Note: Was done before in RocketCommanderXna and this way it /// is easier to reuse the code below! /// </summary> static Rectangle[] CharRects = new Rectangle[126 - 32 + 1]; #region obs /*obs /// <summary> /// Char rectangles, goes from space (32) to ~ (126). /// Height is not used (always the same), instead we save the actual /// used width for rendering in the height value! /// This are the characters: /// !"#$%&'()*+,-./0123456789:;<=>?@ /// ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_` /// abcdefghijklmnopqrstuvwxyz{|}~ /// Then we also got 4 extra rects for the XBox Buttons: A, B, X, Y /// </summary> static Rectangle[] CharRects = new Rectangle[126 - 32 + 1] { new Rectangle(0, 0, 1, 8), // space new Rectangle(1, 0, 11, 10), new Rectangle(12, 0, 14, 13), new Rectangle(26, 0, 20, 18), new Rectangle(46, 0, 20, 18), new Rectangle(66, 0, 24, 22), new Rectangle(90, 0, 25, 23), new Rectangle(115, 0, 8, 7), new Rectangle(124, 0, 10, 9), new Rectangle(136, 0, 10, 9), new Rectangle(146, 0, 20, 18), new Rectangle(166, 0, 20, 18), new Rectangle(186, 0, 10, 8), new Rectangle(196, 0, 10, 9), new Rectangle(207, 0, 10, 8), new Rectangle(217, 0, 18, 16), new Rectangle(235, 0, 20, 19), new Rectangle(0, 36, 20, 18), // 1 new Rectangle(20, 36, 20, 18), new Rectangle(40, 36, 20, 18), new Rectangle(60, 36, 21, 19), new Rectangle(81, 36, 20, 18), new Rectangle(101, 36, 20, 18), new Rectangle(121, 36, 20, 18), new Rectangle(141, 36, 20, 18), new Rectangle(161, 36, 20, 18), // 9 new Rectangle(181, 36, 10, 8), new Rectangle(191, 36, 10, 8), new Rectangle(201, 36, 20, 18), new Rectangle(221, 36, 20, 18), new Rectangle(0, 72, 20, 18), // > new Rectangle(20, 72, 19, 17), new Rectangle(39, 72, 26, 24), new Rectangle(65, 72, 22, 20), new Rectangle(87, 72, 22, 20), new Rectangle(109, 72, 22, 20), new Rectangle(131, 72, 23, 21), new Rectangle(154, 72, 20, 18), new Rectangle(174, 72, 19, 17), new Rectangle(193, 72, 23, 21), new Rectangle(216, 72, 23, 21), new Rectangle(239, 72, 11, 10), new Rectangle(0, 108, 15, 13), // J new Rectangle(15, 108, 22, 20), new Rectangle(37, 108, 19, 17), new Rectangle(56, 108, 29, 26), new Rectangle(85, 108, 23, 21), new Rectangle(108, 108, 24, 22), // O new Rectangle(132, 108, 22, 20), new Rectangle(154, 108, 24, 22), new Rectangle(178, 108, 24, 22), new Rectangle(202, 108, 21, 19), new Rectangle(223, 108, 17, 15), // T new Rectangle(0, 144, 22, 20), // U new Rectangle(22, 144, 22, 20), new Rectangle(44, 144, 30, 28), new Rectangle(74, 144, 22, 20), new Rectangle(96, 144, 20, 18), new Rectangle(116, 144, 20, 18), new Rectangle(136, 144, 10, 9), new Rectangle(146, 144, 18, 16), new Rectangle(167, 144, 10, 9), new Rectangle(177, 144, 17, 16), new Rectangle(194, 144, 17, 16), new Rectangle(211, 144, 17, 16), new Rectangle(228, 144, 20, 18), new Rectangle(0, 180, 20, 18), // b new Rectangle(20, 180, 18, 16), new Rectangle(38, 180, 20, 18), new Rectangle(58, 180, 20, 18), // e new Rectangle(79, 180, 14, 12), // f new Rectangle(93, 180, 20, 18), // g new Rectangle(114, 180, 19, 18), // h new Rectangle(133, 180, 11, 10), new Rectangle(145, 180, 11, 10), // j new Rectangle(156, 180, 20, 18), new Rectangle(176, 180, 11, 9), new Rectangle(187, 180, 29, 27), new Rectangle(216, 180, 20, 18), new Rectangle(236, 180, 20, 19), new Rectangle(0, 216, 20, 18), // p new Rectangle(20, 216, 20, 18), new Rectangle(40, 216, 13, 12), // r new Rectangle(53, 216, 17, 16), new Rectangle(70, 216, 14, 11), // t new Rectangle(84, 216, 19, 18), new Rectangle(104, 216, 17, 16), new Rectangle(122, 216, 25, 23), new Rectangle(148, 216, 19, 17), new Rectangle(168, 216, 18, 16), new Rectangle(186, 216, 16, 15), new Rectangle(203, 216, 10, 9), new Rectangle(214, 216, 12, 11), // | new Rectangle(227, 216, 10, 9), new Rectangle(237, 216, 18, 17), }; /*obs, first try /// <summary> /// XBox 360 Button rects, can just be added to your text :) /// Check out the unit test below. /// </summary> public const char XBoxAButton = (char)(126 + 1), XBoxBButton = (char)(126 + 2), XBoxXButton = (char)(126 + 3), XBoxYButton = (char)(126 + 4); /// <summary> /// Char rectangles, goes from space (32) to ~ (126). /// Height is not used (always the same), instead we save the actual /// used width for rendering in the height value! /// This are the characters: /// !"#$%&'()*+,-./0123456789:;<=>?@ /// ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_` /// abcdefghijklmnopqrstuvwxyz{|}~ /// Then we also got 4 extra rects for the XBox Buttons: A, B, X, Y /// </summary> static Rectangle[] CharRects = new Rectangle[126 - 32 + 4 + 1] { new Rectangle(0, 0, 1, 6), // space new Rectangle(1, 0, 6, 5), new Rectangle(7, 0, 8, 6), new Rectangle(15, 0, 10, 9), new Rectangle(25, 0, 11, 10), new Rectangle(36, 0, 16, 14), new Rectangle(52, 0, 14, 12), new Rectangle(66, 0, 5, 3), new Rectangle(71, 0, 9, 7), new Rectangle(80, 0, 9, 7), new Rectangle(89, 0, 11, 9), new Rectangle(100, 0, 10, 9), new Rectangle(110, 0, 6, 5), new Rectangle(116, 0, 7, 5), new Rectangle(123, 0, 6, 5), new Rectangle(129, 0, 5, 3), new Rectangle(134, 0, 13, 11), new Rectangle(147, 0, 13, 11), new Rectangle(160, 0, 13, 11), new Rectangle(173, 0, 13, 11), new Rectangle(186, 0, 13, 11), new Rectangle(199, 0, 13, 11), new Rectangle(212, 0, 13, 11), new Rectangle(225, 0, 13, 11), new Rectangle(238, 0, 13, 11), new Rectangle(0, 25, 13, 11), // 9 new Rectangle(13, 25, 6, 5), new Rectangle(19, 25, 6, 5), new Rectangle(25, 25, 10, 9), new Rectangle(35, 25, 10, 9), new Rectangle(45, 25, 10, 9), new Rectangle(55, 25, 9, 7), new Rectangle(64, 25, 16, 14), new Rectangle(80, 25, 15, 13), new Rectangle(95, 25, 13, 11), new Rectangle(108, 25, 12, 10), new Rectangle(120, 25, 13, 12), new Rectangle(133, 25, 11, 9), new Rectangle(144, 25, 11, 9), new Rectangle(155, 25, 13, 11), new Rectangle(168, 25, 14, 13), new Rectangle(182, 25, 8, 6), new Rectangle(190, 25, 9, 7), new Rectangle(199, 25, 14, 12), new Rectangle(213, 25, 11, 9), new Rectangle(224, 25, 16, 14), new Rectangle(240, 25, 13, 12), new Rectangle(0, 50, 13, 11), // O new Rectangle(13, 50, 12, 11), new Rectangle(25, 50, 13, 11), new Rectangle(38, 50, 13, 12), new Rectangle(51, 50, 11, 9), new Rectangle(62, 50, 11, 9), new Rectangle(73, 50, 13, 11), new Rectangle(86, 50, 13, 11), new Rectangle(99, 50, 18, 16), new Rectangle(117, 50, 14, 13), new Rectangle(131, 50, 14, 12), new Rectangle(145, 50, 12, 11), new Rectangle(157, 50, 8, 7), new Rectangle(165, 50, 5, 3), new Rectangle(170, 50, 8, 7), new Rectangle(178, 50, 10, 8), new Rectangle(188, 50, 8, 6), new Rectangle(196, 50, 5, 4), new Rectangle(201, 50, 11, 10), new Rectangle(212, 50, 12, 10), new Rectangle(224, 50, 10, 9), new Rectangle(234, 50, 12, 10), new Rectangle(0, 75, 11, 9), // e new Rectangle(11, 75, 9, 7), new Rectangle(20, 75, 11, 10), new Rectangle(31, 75, 12, 10), new Rectangle(43, 75, 7, 5), new Rectangle(50, 75, 8, 6), new Rectangle(58, 75, 12, 10), new Rectangle(70, 75, 7, 5), new Rectangle(77, 75, 18, 16), new Rectangle(95, 75, 12, 10), new Rectangle(107, 75, 11, 9), new Rectangle(118, 75, 12, 10), new Rectangle(130, 75, 12, 10), new Rectangle(142, 75, 10, 9), new Rectangle(152, 75, 9, 8), new Rectangle(161, 75, 9, 7), new Rectangle(170, 75, 12, 10), new Rectangle(182, 75, 11, 9), new Rectangle(193, 75, 15, 13), new Rectangle(208, 75, 13, 11), new Rectangle(221, 75, 11, 10), new Rectangle(232, 75, 10, 8), new Rectangle(242, 75, 6, 5), new Rectangle(0, 100, 10, 9), // | new Rectangle(10, 100, 6, 5), new Rectangle(16, 100, 10, 8), // 4 extra chars for the xbox controller buttons new Rectangle(29, 100, 20, 21), new Rectangle(49, 100, 20, 21), new Rectangle(69, 100, 20, 21), new Rectangle(89, 100, 20, 21), }; */ #endregion #endregion #region Variables /// <summary> /// TextureFont texture /// </summary> Texture fontTexture; /// <summary> /// TextureFont sprite /// </summary> SpriteBatch fontSprite; #endregion #region Properties /// <summary> /// Height /// </summary> /// <returns>Int</returns> public static int Height { get { return (FontHeight - SubRenderHeight) * BaseGame.Height / 1200; } // get } // Height #endregion #region Constructor /// <summary> /// Create texture font /// </summary> public TextureFont() { fontTexture = new Texture(GameFontFilename); fontSprite = new SpriteBatch(BaseGame.Device); // Load all char rects from the xml data above XmlNode xmlFont = XmlHelper.LoadXmlFromText(FontXmlInfo); for (int i = 0; i < CharRects.Length; i++) { // Use default values for letters that are not supported // They will not be displayed at all Rectangle rect = new Rectangle(0, 0, 0, 0); // Convert to char, start with '!' char ch = (char)((int)' ' + i); // Find out if it is available in the list above foreach (XmlNode node in xmlFont) if (XmlHelper.GetXmlAttribute(node, "c").Length > 0 && XmlHelper.GetXmlAttribute(node, "c")[0] == ch) { // Found it! Assign values rect.X = Convert.ToInt32(XmlHelper.GetXmlAttribute(node, "v"))-4; rect.Y = Convert.ToInt32(XmlHelper.GetXmlAttribute(node, "u"))-2; rect.Width = Convert.ToInt32(XmlHelper.GetXmlAttribute(node, "width"))+6; // Use the default sub value for the actual render width rect.Height = rect.Width - SubRenderWidth; //tst: //Log.Write("Found ch=" + ch + " at " + i + " with rect: " + rect); break; } // foreach if (XmlHelper.GetXmlAttribute) // Assign the result CharRects[i] = rect; } // for (int) } // TextureFont() #endregion #region Dispose /*obs, XNA handles this fine /// <summary> /// Dispose /// </summary> public void Dispose() { DisposeHelper.Dispose(ref fontTexture); DisposeHelper.Dispose(ref fontSprite); } // Dispose() */ #endregion #region Get text width /// <summary> /// Get the text width of a given text. /// </summary> /// <param name="text">Text</param> /// <returns>Width (in pixels) of the text</returns> public int GetTextWidth(string text) { int width = 0; //foreach (char c in text) char[] chars = text.ToCharArray(); for (int num = 0; num < chars.Length; num++) { int charNum = (int)chars[num]; if (charNum >= 32 && charNum - 32 < CharRects.Length) width += CharRects[charNum - 32].Height + SubRenderWidth; } // foreach return width * //BaseGame.Height / 1050; BaseGame.Height / (1700 * 3 / 4); } // GetTextWidth(text) #endregion #region Write all /// <summary> /// TextureFont to render /// </summary> internal class FontToRender { #region Variables /// <summary> /// X and y position /// </summary> public int x, y; /// <summary> /// Text /// </summary> public string text; /// <summary> /// Color /// </summary> public Color color; #endregion #region Constructor /// <summary> /// Create font to render /// </summary> /// <param name="setX">Set x</param> /// <param name="setY">Set y</param> /// <param name="setText">Set text</param> /// <param name="setColor">Set color</param> public FontToRender(int setX, int setY, string setText, Color setColor) { x = setX; y = setY; text = setText; color = setColor; } // FontToRender(setX, setY, setText) #endregion } // class FontToRender /// <summary> /// Remember font texts to render to render them all at once /// in our Render method (beween rest of the ui and the mouse cursor). /// </summary> static List<FontToRender> remTexts = new List<FontToRender>(); /// <summary> /// Write the given text at the specified position. /// </summary> /// <param name="x">X</param> /// <param name="y">Y</param> /// <param name="text">Text</param> /// <param name="color">Color</param> public static void WriteText(int x, int y, string text, Color color) { remTexts.Add(new FontToRender(x, y, text, color)); } // WriteText(x, y, text) /// <summary> /// Write /// </summary> /// <param name="x">X</param> /// <param name="y">Y</param> /// <param name="text">Text</param> public static void WriteText(int x, int y, string text) { remTexts.Add(new FontToRender(x, y, text, Color.White)); } // WriteText(x, y, text) /// <summary> /// Write /// </summary> /// <param name="x">X</param> /// <param name="y">Y</param> /// <param name="text">Text</param> public static void WriteText(Point pos, string text) { remTexts.Add(new FontToRender(pos.X, pos.Y, text, Color.White)); } // WriteText(pos, text) /// <summary> /// Write small text centered /// </summary> /// <param name="x">X</param> /// <param name="y">Y</param> /// <param name="text">Text</param> /// <param name="col">Color</param> /// <param name="alpha">Alpha</param> public static void WriteSmallTextCentered(int x, int y, string text, Color col, float alpha) { WriteText(x - BaseGame.GameFont.GetTextWidth(text) / 2, y, text, ColorHelper.ApplyAlphaToColor(col, alpha)); } // WriteSmallTextCentered(x, y, text) /// <summary> /// Write small text centered /// </summary> /// <param name="x">X</param> /// <param name="y">Y</param> /// <param name="text">Text</param> /// <param name="col">Color</param> /// <param name="alpha">Alpha</param> public static void WriteSmallTextCentered(int x, int y, string text, float alpha) { WriteText(x - BaseGame.GameFont.GetTextWidth(text) / 2, y, text, ColorHelper.ApplyAlphaToColor(Color.White, alpha)); } // WriteSmallTextCentered(x, y, text) /// <summary> /// Write text centered /// </summary> /// <param name="x">X</param> /// <param name="y">Y</param> /// <param name="text">Text</param> public static void WriteTextCentered(int x, int y, string text) { WriteText(x - BaseGame.GameFont.GetTextWidth(text) / 2, y, text); } // WriteTextCentered(x, y, text) /// <summary> /// Write text centered /// </summary> /// <param name="x">X</param> /// <param name="y">Y</param> /// <param name="text">Text</param> /// <param name="col">Color</param> /// <param name="alpha">Alpha</param> public static void WriteTextCentered(int x, int y, string text, Color col, float alpha) { WriteText(x - BaseGame.GameFont.GetTextWidth(text) / 2, y, text, ColorHelper.ApplyAlphaToColor(col, alpha)); } // WriteTextCentered(x, y, text) /// <summary> /// Write all /// </summary> /// <param name="texts">Texts</param> public void WriteAll() { if (remTexts.Count == 0) return; BaseGame.AlphaBlending = true; // Start rendering fontSprite.Begin(SpriteBlendMode.AlphaBlend); // Draw each character in the text //foreach (UIRenderer.FontToRender fontText in texts) for (int textNum = 0; textNum < remTexts.Count; textNum++) { FontToRender fontText = remTexts[textNum]; int x = fontText.x; int y = fontText.y; Color color = fontText.color; //foreach (char c in fontText.text) char[] chars = fontText.text.ToCharArray(); for (int num = 0; num < chars.Length; num++) { int charNum = (int)chars[num]; if (charNum >= 32 && charNum - 32 < CharRects.Length) { // Draw this char Rectangle rect = CharRects[charNum - 32]; // Reduce height to prevent overlapping pixels rect.Y += 1; rect.Height = FontHeight;// Height;// - 1; // Add 2 pixel for g, j, y //if (c == 'g' || c == 'j' || c == 'y') // rect.Height+=2; Rectangle destRect = new Rectangle(x, y - SubRenderHeight, rect.Width, rect.Height); // Scale destRect (1600x1200 is the base size) //destRect.Width = destRect.Width; //destRect.Height = destRect.Height; // If we want upscaling, just use destRect fontSprite.Draw(fontTexture.XnaTexture, //obs:destRect, // Rescale to fit resolution, but only size //destRect, new Rectangle( destRect.X,// * BaseGame.Width / 1024, destRect.Y,// * BaseGame.Height / 768, //first try: //destRect.Width * BaseGame.Width / 1400, //destRect.Height * BaseGame.Height / 1050), //better for Dungeon Quest: destRect.Width * BaseGame.Width / 1700,//1920, destRect.Height * BaseGame.Height / (1700 * 3 / 4)),//(1920 * 3 / 4)), rect, color); //, // Make sure fonts are always displayed at the front of everything //0, Vector2.Zero, SpriteEffects.None, 1.1f); // Increase x pos by width we use for this character int charWidth = CharRects[charNum - 32].Height * BaseGame.Height / //old:1050; //(1920 * 3 / 4); (1700 * 3 / 4); x += charWidth; } // if (charNum) } // foreach } // foreach (fontText) // End rendering fontSprite.End(); remTexts.Clear(); } // WriteAll(texts) #endregion #region Unit Testing #if DEBUG /// <summary> /// Test render font /// </summary> public static void TestRenderFont() { TestGame.Start("TestRenderFont", delegate { TestGame.BackgroundColor = Color.Black; TestGame.GameFont.fontTexture.RenderOnScreen( new Rectangle(200, 200, 512, 512)); TextureFont.WriteText(30, 30, "Evil Monster in da house"); TextureFont.WriteText(30, 90, "aaaaaaaaaaaaaaa"); TextureFont.WriteText(30, 120, "ttttttttttttttttt"); }); } // TestRenderFont() #endif #endregion } // class TextureFont } // namespace DungeonQuest.Graphics
using System; using System.Collections.Generic; using System.Linq; using Slp.Evi.Storage.Query; using Slp.Evi.Storage.Relational.Query.Sources; namespace Slp.Evi.Storage.Relational.PostProcess.Optimizers.SelfJoinOptimizerHelpers { /// <summary> /// The type representing satisfaction map /// </summary> public class SatisfactionMap { /// <summary> /// The satisfaction storage /// </summary> private readonly Dictionary<SqlTable, Dictionary<SqlTable, SelfJoinConstraintsSatisfaction>> _storeDictionary; /// <summary> /// The present tables /// </summary> private readonly List<SqlTable> _presentTables; /// <summary> /// The context /// </summary> private readonly IQueryContext _context; /// <summary> /// The satisfied satisfactions /// </summary> private readonly List<SelfJoinConstraintsSatisfaction> _satisfiedSatisfactions; /// <summary> /// Prevents a default instance of the <see cref="SatisfactionMap"/> class from being created. /// </summary> private SatisfactionMap(List<SqlTable> presentTables, IQueryContext context) { _presentTables = presentTables; _context = context; _satisfiedSatisfactions = new List<SelfJoinConstraintsSatisfaction>(); _storeDictionary = new Dictionary<SqlTable, Dictionary<SqlTable, SelfJoinConstraintsSatisfaction>>(); } /// <summary> /// Creates the initial satisfaction map. /// </summary> public SatisfactionMap CreateInitialSatisfactionMap() { return CreateInitialSatisfactionMap(_presentTables, _context); } /// <summary> /// Creates the initial satisfaction map /// </summary> /// <param name="presentTables">Tables present in the model</param> /// <param name="context">The query context</param> /// <returns></returns> public static SatisfactionMap CreateInitialSatisfactionMap(List<SqlTable> presentTables, IQueryContext context) { var firstTableOccurrence = new Dictionary<string, SqlTable>(); var result = new SatisfactionMap(presentTables, context); foreach (var sqlTable in presentTables) { var tableName = sqlTable.TableName; if (!firstTableOccurrence.ContainsKey(tableName)) { firstTableOccurrence.Add(tableName, sqlTable); } else { var replaceByTable = firstTableOccurrence[tableName]; result._storeDictionary.Add(sqlTable, new Dictionary<SqlTable, SelfJoinConstraintsSatisfaction>()); result._storeDictionary[sqlTable].Add(replaceByTable, GetSelfJoinConstraints(sqlTable, replaceByTable, context)); } } return result; } /// <summary> /// Gets the self join constraints of a table /// </summary> /// <param name="sqlTable">The SQL table</param> /// <param name="replaceByTable">The table that will be used to replace the <paramref name="sqlTable"/></param> /// <param name="context">The query context</param> private static SelfJoinConstraintsSatisfaction GetSelfJoinConstraints(SqlTable sqlTable, SqlTable replaceByTable, IQueryContext context) { var tableName = sqlTable.TableName; var tableInfo = context.SchemaProvider.GetTableInfo(tableName); var constraints = tableInfo.UniqueKeys.ToList(); if (tableInfo.PrimaryKey != null) { constraints.Add(tableInfo.PrimaryKey); } return new SelfJoinConstraintsSatisfaction(sqlTable, replaceByTable, constraints.Select(databaseConstraint => new UniqueConstraint(databaseConstraint))); } /// <summary> /// Gets the satisfactions for table <paramref name="table"/> /// </summary> public IEnumerable<SelfJoinConstraintsSatisfaction> GetSatisfactionsFromMap(SqlTable table) { foreach (var sqlTable in _storeDictionary.Keys) { if (sqlTable == table) { foreach (var selfJoinConstraintsSatisfaction in _storeDictionary[sqlTable].Values) { yield return selfJoinConstraintsSatisfaction; } } else { foreach (var replaceByTable in _storeDictionary[sqlTable].Keys) { if (replaceByTable == table) { yield return _storeDictionary[sqlTable][replaceByTable]; } } } } } /// <summary> /// Gets the satisfaction for tables <paramref name="table"/> and <paramref name="otherTable"/> /// </summary> public SelfJoinConstraintsSatisfaction GetSatisfactionFromMap(SqlTable table, SqlTable otherTable) { if (_storeDictionary.ContainsKey(table) && _storeDictionary[table].ContainsKey(otherTable)) { return _storeDictionary[table][otherTable]; } else if (_storeDictionary.ContainsKey(otherTable) && _storeDictionary[otherTable].ContainsKey(table)) { return _storeDictionary[otherTable][table]; } else { return null; } } /// <summary> /// Marks <paramref name="satisfaction"/>as satisfied. /// </summary> public void MarkAsSatisfied(SelfJoinConstraintsSatisfaction satisfaction) { _satisfiedSatisfactions.Add(satisfaction); } /// <summary> /// Gets the satisfied satisfactions. /// </summary> public IEnumerable<SelfJoinConstraintsSatisfaction> GetSatisfiedSatisfactions() { return _satisfiedSatisfactions; } /// <summary> /// Intersects with the <paramref name="other"/> map. /// </summary> public void IntersectWith(SatisfactionMap other) { if (other._context != _context || other._presentTables != _presentTables) { throw new ArgumentException("Cannot intersect with differently originated satisfaction map", nameof(other)); } foreach (var sqlTable in _storeDictionary.Keys) { foreach (var replaceByTable in _storeDictionary[sqlTable].Keys) { var satisfaction = _storeDictionary[sqlTable][replaceByTable]; var wasSatisfied = satisfaction.IsSatisfied; satisfaction.IntersectWith(other._storeDictionary[sqlTable][replaceByTable]); if (wasSatisfied && !satisfaction.IsSatisfied) { _satisfiedSatisfactions.Remove(satisfaction); } } } } /// <summary> /// Merges with the <paramref name="other"/> map. /// </summary> public void MergeWith(SatisfactionMap other) { if (other._context != _context || other._presentTables != _presentTables) { throw new ArgumentException("Cannot merge with differently originated satisfaction map", nameof(other)); } foreach (var sqlTable in _storeDictionary.Keys) { foreach (var replaceByTable in _storeDictionary[sqlTable].Keys) { var satisfaction = _storeDictionary[sqlTable][replaceByTable]; var wasSatisfied = satisfaction.IsSatisfied; satisfaction.MergeWith(other._storeDictionary[sqlTable][replaceByTable]); if (!wasSatisfied && satisfaction.IsSatisfied) { _satisfiedSatisfactions.Add(satisfaction); } } } } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// Archived Census Student Validation Data Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class SCEN_ASVDataSet : EduHubDataSet<SCEN_ASV> { /// <inheritdoc /> public override string Name { get { return "SCEN_ASV"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return false; } } internal SCEN_ASVDataSet(EduHubContext Context) : base(Context) { Index_ID = new Lazy<Dictionary<int, SCEN_ASV>>(() => this.ToDictionary(i => i.ID)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="SCEN_ASV" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="SCEN_ASV" /> fields for each CSV column header</returns> internal override Action<SCEN_ASV, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<SCEN_ASV, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "ID": mapper[i] = (e, v) => e.ID = int.Parse(v); break; case "ID_RETURN": mapper[i] = (e, v) => e.ID_RETURN = v == null ? (int?)null : int.Parse(v); break; case "STKEY": mapper[i] = (e, v) => e.STKEY = v; break; case "REGISTRATION": mapper[i] = (e, v) => e.REGISTRATION = v == null ? (short?)null : short.Parse(v); break; case "ID_STUDENTVALIDATIONTYPE": mapper[i] = (e, v) => e.ID_STUDENTVALIDATIONTYPE = v == null ? (short?)null : short.Parse(v); break; case "FIELDVALUES": mapper[i] = (e, v) => e.FIELDVALUES = v; break; case "STATUS": mapper[i] = (e, v) => e.STATUS = v; break; case "CREATEUSER": mapper[i] = (e, v) => e.CREATEUSER = v; break; case "CREATED": mapper[i] = (e, v) => e.CREATED = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LUPDATEUSER": mapper[i] = (e, v) => e.LUPDATEUSER = v; break; case "LUPDATED": mapper[i] = (e, v) => e.LUPDATED = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="SCEN_ASV" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="SCEN_ASV" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="SCEN_ASV" /> entities</param> /// <returns>A merged <see cref="IEnumerable{SCEN_ASV}"/> of entities</returns> internal override IEnumerable<SCEN_ASV> ApplyDeltaEntities(IEnumerable<SCEN_ASV> Entities, List<SCEN_ASV> DeltaEntities) { HashSet<int> Index_ID = new HashSet<int>(DeltaEntities.Select(i => i.ID)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.ID; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_ID.Remove(entity.ID); if (entity.ID.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<Dictionary<int, SCEN_ASV>> Index_ID; #endregion #region Index Methods /// <summary> /// Find SCEN_ASV by ID field /// </summary> /// <param name="ID">ID value used to find SCEN_ASV</param> /// <returns>Related SCEN_ASV entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public SCEN_ASV FindByID(int ID) { return Index_ID.Value[ID]; } /// <summary> /// Attempt to find SCEN_ASV by ID field /// </summary> /// <param name="ID">ID value used to find SCEN_ASV</param> /// <param name="Value">Related SCEN_ASV entity</param> /// <returns>True if the related SCEN_ASV entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByID(int ID, out SCEN_ASV Value) { return Index_ID.Value.TryGetValue(ID, out Value); } /// <summary> /// Attempt to find SCEN_ASV by ID field /// </summary> /// <param name="ID">ID value used to find SCEN_ASV</param> /// <returns>Related SCEN_ASV entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public SCEN_ASV TryFindByID(int ID) { SCEN_ASV value; if (Index_ID.Value.TryGetValue(ID, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a SCEN_ASV table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[SCEN_ASV]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[SCEN_ASV]( [ID] int IDENTITY NOT NULL, [ID_RETURN] int NULL, [STKEY] varchar(10) NULL, [REGISTRATION] smallint NULL, [ID_STUDENTVALIDATIONTYPE] smallint NULL, [FIELDVALUES] varchar(255) NULL, [STATUS] varchar(1) NULL, [CREATEUSER] varchar(128) NULL, [CREATED] datetime NULL, [LUPDATEUSER] varchar(128) NULL, [LUPDATED] datetime NULL, CONSTRAINT [SCEN_ASV_Index_ID] PRIMARY KEY CLUSTERED ( [ID] ASC ) ); END"); } /// <summary> /// Returns null as <see cref="SCEN_ASVDataSet"/> has no non-clustered indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>null</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return null; } /// <summary> /// Returns null as <see cref="SCEN_ASVDataSet"/> has no non-clustered indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>null</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return null; } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="SCEN_ASV"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="SCEN_ASV"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<SCEN_ASV> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<int> Index_ID = new List<int>(); foreach (var entity in Entities) { Index_ID.Add(entity.ID); } builder.AppendLine("DELETE [dbo].[SCEN_ASV] WHERE"); // Index_ID builder.Append("[ID] IN ("); for (int index = 0; index < Index_ID.Count; index++) { if (index != 0) builder.Append(", "); // ID var parameterID = $"@p{parameterIndex++}"; builder.Append(parameterID); command.Parameters.Add(parameterID, SqlDbType.Int).Value = Index_ID[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the SCEN_ASV data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the SCEN_ASV data set</returns> public override EduHubDataSetDataReader<SCEN_ASV> GetDataSetDataReader() { return new SCEN_ASVDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the SCEN_ASV data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the SCEN_ASV data set</returns> public override EduHubDataSetDataReader<SCEN_ASV> GetDataSetDataReader(List<SCEN_ASV> Entities) { return new SCEN_ASVDataReader(new EduHubDataSetLoadedReader<SCEN_ASV>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class SCEN_ASVDataReader : EduHubDataSetDataReader<SCEN_ASV> { public SCEN_ASVDataReader(IEduHubDataSetReader<SCEN_ASV> Reader) : base (Reader) { } public override int FieldCount { get { return 11; } } public override object GetValue(int i) { switch (i) { case 0: // ID return Current.ID; case 1: // ID_RETURN return Current.ID_RETURN; case 2: // STKEY return Current.STKEY; case 3: // REGISTRATION return Current.REGISTRATION; case 4: // ID_STUDENTVALIDATIONTYPE return Current.ID_STUDENTVALIDATIONTYPE; case 5: // FIELDVALUES return Current.FIELDVALUES; case 6: // STATUS return Current.STATUS; case 7: // CREATEUSER return Current.CREATEUSER; case 8: // CREATED return Current.CREATED; case 9: // LUPDATEUSER return Current.LUPDATEUSER; case 10: // LUPDATED return Current.LUPDATED; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 1: // ID_RETURN return Current.ID_RETURN == null; case 2: // STKEY return Current.STKEY == null; case 3: // REGISTRATION return Current.REGISTRATION == null; case 4: // ID_STUDENTVALIDATIONTYPE return Current.ID_STUDENTVALIDATIONTYPE == null; case 5: // FIELDVALUES return Current.FIELDVALUES == null; case 6: // STATUS return Current.STATUS == null; case 7: // CREATEUSER return Current.CREATEUSER == null; case 8: // CREATED return Current.CREATED == null; case 9: // LUPDATEUSER return Current.LUPDATEUSER == null; case 10: // LUPDATED return Current.LUPDATED == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // ID return "ID"; case 1: // ID_RETURN return "ID_RETURN"; case 2: // STKEY return "STKEY"; case 3: // REGISTRATION return "REGISTRATION"; case 4: // ID_STUDENTVALIDATIONTYPE return "ID_STUDENTVALIDATIONTYPE"; case 5: // FIELDVALUES return "FIELDVALUES"; case 6: // STATUS return "STATUS"; case 7: // CREATEUSER return "CREATEUSER"; case 8: // CREATED return "CREATED"; case 9: // LUPDATEUSER return "LUPDATEUSER"; case 10: // LUPDATED return "LUPDATED"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "ID": return 0; case "ID_RETURN": return 1; case "STKEY": return 2; case "REGISTRATION": return 3; case "ID_STUDENTVALIDATIONTYPE": return 4; case "FIELDVALUES": return 5; case "STATUS": return 6; case "CREATEUSER": return 7; case "CREATED": return 8; case "LUPDATEUSER": return 9; case "LUPDATED": return 10; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
//----------------------------------------------------------------------------- // Copyright (C) LogicKing.com //----------------------------------------------------------------------------- // field name sign size LogickingEditorFieldEditor.fieldSize = "80 18"; LogickingEditorFieldEditor.actionFieldSize = "235 18"; // field value sign size LogickingEditorFieldEditor.valueSize = "230 18"; LogickingEditorFieldEditor.smallValueSize = "40 18"; LogickingEditorFieldEditor.valueListSize = "195 18"; // parameter value button size LogickingEditorFieldEditor.buttonSize = "30 18"; LogickingEditorFieldEditor.actionButtonSize = "90 20"; // checkBox size LogickingEditorFieldEditor.boolSize = "50 18"; LogickingEditorFieldEditor.smallButtonSize = "18 18"; LogickingEditorFieldEditor.stackSize = "260 18"; LogickingEditorFieldEditor.fullSizeControlSize = "260 18"; // Column 1 size LogickingEditorFieldEditor.column1size = "185 18"; // Column 2 size LogickingEditorFieldEditor.column2size = "80 18"; function LogickingEditorFieldEditor::onWake(%this) { echo("On Wake"); %this.currentObjects = %this.currentObjects $= "" ? getWord(LogickingEditor.currentObjects, 0) : %this.currentObjects; %this.createFields(); if(!isObject(%this.soundDescription)) { %this.soundDescription = new SFXDescription(fieldsEditorDescription) { volume = 1.0; isLooping = false; is3D = false; channel = $SimAudioType; }; MissionCleanup.add(%this.soundDescription); } //TestCam object is for "Fly Path" button functionality of fly paths if(!isObject(%this.testCam)) { %this.testCam = new PathCamera() { dataBlock = CutSceneCam; }; MissionCleanup.add( %this.testCam ); } } function LogickingEditorFieldEditor::clearStackList(%this) { %this.stacksListItems[counter] = %this.stacksListItems[counter] $= "" ? 0 : %this.stacksListItems[counter]; echo("clearStackList ", %this.stacksListItems[counter]); for(%i = 0; %i < %this.stacksListItems[counter]; %i++) { %stack = %this.stacksListItems[%i]; if(isObject(%stack)) %stack.clear(); %this.stacksList[%this.stacksListItemCaptions[%i]] = ""; } %this.stacksListItems[counter] = 0; } function LogickingEditorFieldEditor::getStack(%this, %caption) { %stack = %this.stacksList[%caption]; if(!isObject(%stack)) { %stack = %this.createStack(%caption); echo("Create Stack Caption", %caption); %this.stacksListItems[counter] = %this.stacksListItems[counter] $= "" ? 0 : %this.stacksListItems[counter]; %counter = %this.stacksListItems[counter]; %this.stacksListItems[%counter] = %stack; %this.stacksListItemCaptions[%counter] = %caption; %this.stacksListItems[counter]++; } return %stack; } function LogickingEditorFieldEditor::createStack(%this, %caption) { %rollOut = createDataControl("rollOut", "0 0", "260 50"); %rollOut.caption = %caption; %this.addControl(%rollOut); fieldEditorStack.addGuiControl(%rollOut); %stack = createDataControl("stack", "2 22", %this.stackSize); %this.stacksList[%caption] = %stack; %this.addControl(%stack); %rollOut.addGuiControl(%stack); %stack.rollOut = %rollOut; return %stack; } // Groups of parameters editing function LogickingEditorFieldEditor::createGroupEditor(%this, %object, %fieldIndex) { %groupName = getFieldName(%object.templateName, %fieldIndex); %value = getFieldValue(%object.templateName, %fieldIndex); %hint = getFieldHint(%object.templateName, %fieldIndex); %additional = getFieldAdditional(%object.templateName, %fieldIndex); breakToWordsA(%value, "|"); for(%i = 0; %i < $breakToWordsAReturnBuf[counter]; %i++) { %value[%i] = $breakToWordsAReturnBuf[%i]; } clearBreakToWordsBuf(); %type = %value[0]; %parentStack = %this.getStack(%groupName); %parentStack.setName(%groupName @ "Group"); %stack = createDataControl("stack", "0 0", %this.stackSize); %stack.StackingType = "Horizontal"; %this.addControl(%stack); // creation of table's header and separators %text = createDataControl("text", "0 0", %this.column1size, "LogicMechanicsTextBoldCenterProfile"); %text.setText(%value[1]); %stack.addGuiControl(%text); %this.addControl(%text); %text = createDataControl("text", "0 0", %this.column2size, "LogicMechanicsTextBoldLeftProfile"); %text.setText(%value[2]); %stack.addGuiControl(%text); %this.addControl(%text); %parentStack.addGuiControl(%stack); %text = createDataControl("text", "0 0", %this.fullSizeControlSize, "LogicMechanicsTextBoldCenterProfile"); %text.setText("----------------------------------------------------------------------------------"); %parentStack.addGuiControl(%text); %this.addControl(%text); // panel for adding new field for editing %stack = createDataControl("stack", "0 0", %this.stackSize); %stack.StackingType = "Horizontal"; %stack.setName("add" @ %groupName @ "GroupPanel"); %this.addControl(%stack); %text = createDataControl("text", "0 0", %this.fullSizeControlSize); %text.setText(""); %stack.addGuiControl(%text); %this.addControl(%text); %button = createDataControl("icon", "0 0", %this.smallButtonSize); %this.reduceGuiControlSize(%text, %button); %button.setBitmap("tools/gui/images/iconAdd.png"); %button.Command = " LogickingEditorFieldEditor.addClearEditGroupPanel(" @ %object @ ", " @ %groupName @ "); "; %stack.addGuiControl(%button); %this.addControl(%button); %parentStack.addGuiControl(%stack); %this.inspectGroup(%object, %groupName, %type); %parentStack.rollOut.sizeToContents(); } function LogickingEditorFieldEditor::inspectGroup(%this, %object, %groupName) { %stack = %groupName @ "Group"; %this.clearStack(%stack); %count = %object.getFieldValue( %groupName @ "Count"); if(%count $= "" || %count == 0) return; for(%i = 0; %i < %count; %i++) { %param1 = %object.getFieldValue(%groupName @ %i @ "_0"); %param2 = %object.getFieldValue(%groupName @ %i @ "_1"); if(%param1 $= "") continue; %this.addEditGroupPanel(%object, %groupName, %i, %param1, %param2); } %stack.rollOut.sizeToContents(); } function LogickingEditorFieldEditor::addClearEditGroupPanel(%this, %object, %groupName, %type) { %count = %object.getFieldValue( %groupName @ "Count"); %this.addEditGroupPanel(%object, %groupName, %count, "", 0); %object.setFieldValue( %groupName @ "Count", %count + 1); } function LogickingEditorFieldEditor::addEditGroupPanel(%this, %object, %groupName, %fieldIdx, %textValue, %text2Value) { // this function can be enhanced. Currently it works only with two parameters %index = getFieldIndex(%object.templatename, %groupName); %value = getFieldValue(%object.templateName, %index); // in the %value field there are type of the main field and headers of the columns, separator is '|' symbol. breakToWordsA(%value, "|"); %counter = $breakToWordsAReturnBuf[counter]; for(%i = 0; %i < %counter; %i++) { %value[%i] = $breakToWordsAReturnBuf[%i]; } clearBreakToWordsBuf(); %type = %value[0]; %additional = getFieldAdditional(%object.templateName, %index); %stack = createDataControl("stack", "0 0", %this.stackSize); %stack.StackingType = "Horizontal"; %this.addControlByType(%object, %stack, %groupName @ %fieldIdx @ "_0", %type, %textValue, "", "", %additional); %text = %stack.getObject(0); // adding additional editing field if needed if(%counter > 2) { %text2Value = %text2Value $= "" ? 0 : %text2Value; %text2 = createDataControl("editorTextEdit", "0 0", %this.smallValueSize); %text2.text = %text2Value; %text2.fieldName = %groupName @ %fieldIdx @ "_1"; %text2.AltCommand = " LogickingEditorFieldEditor.applyFieldValueFromEdit($ThisControl, " @ %groupName @ %fieldIdx @ "_1); "; %stack.addGuiControl(%text2); %this.addControl(%text2); %this.reduceGuiControlSize(%text, %text2); } // buttons of movement items inside the list %button = createDataControl("icon", "0 0", %this.smallButtonSize); %button.setBitmap("tools/LogickingEditor/images/GUI/moveObjectUp.png"); %button.command = " LogickingEditorFieldEditor.moveFieldInGroup(" @ %object @ ", " @ %groupName @ ", " @ %fieldIdx @ ", \"" @ %textValue @ "\", \"" @ %text2Value @ "\", -1); "; %button.ToolTip = "Move object up in list"; %stack.addGuiControl(%button); %this.reduceGuiControlSize(%text, %button); %button = createDataControl("icon", "0 0", %this.smallButtonSize); %button.setBitmap("tools/LogickingEditor/images/GUI/moveObjectDown.png"); %button.command = " LogickingEditorFieldEditor.moveFieldInGroup(" @ %object @ ", " @ %groupName @ ", " @ %fieldIdx @ ", \"" @ %textValue @ "\", \"" @ %text2Value @ "\", 1); "; %button.ToolTip = "Move object down in list"; %stack.addGuiControl(%button); %this.reduceGuiControlSize(%text, %button); // Remove row button %button = createDataControl("icon", "0 0", %this.smallButtonSize); %button.setBitmap("tools/gui/images/iconDelete.png"); %button.command = " LogickingEditorFieldEditor.removeEditGroup(" @ %object @ ", " @ %groupName @ ", " @ %fieldIdx @ "); "; %stack.addGuiControl(%button); %this.reduceGuiControlSize(%text, %button); %mainStack = %groupName @ "Group"; %mainStack.addGuiControl(%stack); %addPanel = "add" @ %groupName @ "GroupPanel"; %mainStack.pushToBack(%addPanel); %mainStack.rollOut.sizeToContents(); } // Change position inside of a group function LogickingEditorFieldEditor::moveFieldInGroup(%this, %object, %groupName, %fieldIdx, %value1, %value2, %sign) { if(%fieldIdx == 0 && %sign == -1) return; %nextIndex = %fieldIdx + %sign; %param1 = %object.getFieldValue(%groupName @ %nextIndex @ "_0"); %param2 = %object.getFieldValue(%groupName @ %nextIndex @ "_1"); if(%param1 $= "" && %param2 $= "") return; %object.setFieldValue(%groupName @ %nextIndex @ "_0", %value1); %object.setFieldValue(%groupName @ %nextIndex @ "_1", %value2); %object.setFieldValue(%groupName @ %fieldIdx @ "_0", %param1); %object.setFieldValue(%groupName @ %fieldIdx @ "_1", %param2); EWorldEditor.isDirty = true; %this.inspectGroup(%object, %groupName); } // Remove field from the list function LogickingEditorFieldEditor::removeEditGroup(%this, %object, %groupName, %fieldIdx) { %count = %object.getFieldValue( %groupName @ "Count"); for(%i = %fieldIdx; %i < %count - 1; %i++) { %param1 = %object.getFieldValue( %groupName @ %i + 1 @ "_0"); %object.setFieldValue( %groupName @ %i @ "_0", %param1 ); %param2 = %object.getFieldValue( %groupName @ %i + 1 @ "_1"); %object.setFieldValue( %groupName @ %i @ "_1", %param2 ); } %object.setFieldValue( %groupName @ "Count", %count - 1); %this.inspectGroup(%object, %groupName); } // Clearance of fields' stack function LogickingEditorFieldEditor::clearStack(%this, %stackGroup, %startIdx) { %count = %stackGroup.getCount(); %startIdx = %startIdx $= "" ? 2 : %startIdx; for(%i = %count - 2; %i >= %startIdx; %i--) { %stack = %stackGroup.getObject(%i); if(isObject(%stack)) { %stackGroup.remove(%stack); // defered delete, because clearStack will try to delete button that evokes itself //%stack.schedule(0, "delete"); } } } // Creation of child object with predefined code(chunks) function LogickingEditorFieldEditor::createInternalObjectsEditor(%this, %object, %fieldIndex) { %field = getFieldName(%object.templateName, %fieldIndex); %parentStack = %this.getStack(%field); %parentStack.setName(%object.getName() @ "internalObjectsStack"); // panel of new item add %stack = createDataControl("stack", "0 0", %this.stackSize); %stack.StackingType = "Horizontal"; %stack.setName("addInternalObjectPanel"); %this.addControl(%stack); %text = createDataControl("text", "0 0", %this.fullSizeControlSize); %text.setText(""); %stack.addGuiControl(%text); %this.addControl(%text); %button = createDataControl("icon", "0 0", %this.smallButtonSize); %this.reduceGuiControlSize(%text, %button); %button.setBitmap("tools/gui/images/iconAdd.png"); %button.Command = " LogickingEditorFieldEditor.createInternalObject(" @ %object @ ", " @ %fieldIndex @ "); "; %button.toolTip = %hint; %stack.addGuiControl(%button); %this.addControl(%button); %parentStack.addGuiControl(%stack); %this.inspectInternalObjects(%object); %parentStack.rollOut.sizeToContents(); } function LogickingEditorFieldEditor::createInternalObject(%this, %parentObject, %fieldIndex) { %field = getFieldName(%parentObject.templateName, %fieldIndex); %creationChunk = getFieldValue(%parentObject.templateName, %fieldIndex); %hint = getFieldHint(%parentObject.templateName, %fieldIndex); %nameMask = getFieldAdditional(%parentObject.templateName, %fieldIndex); %nameMask = %nameMask $= "" ? %field : %nameMask; %objectName = %parentObject.getName() @ %nameMask; // child object creation %childObject = eval(%creationChunk); %childObject.nameMask = %nameMask; if(!isObject(%childObject)) { error("Error!! Can't create object by given chunk: \"", %creationChunk, "\""); return; } // moving new object to parent's namespace %parentObject.add(%childObject); %childObject.setName(%objectName @ "_" @ %parentObject.getCount()); LogickingEditor.moveObjectToCamera(%childObject); LogickingEditor.selectObject(%parentObject); %this.inspectInternalObjects(%parentObject); } function LogickingEditorFieldEditor::inspectInternalObjects(%this, %parentObject) { %count = %parentObject.getCount(); %this.clearStack(%parentObject.getName() @ "internalObjectsStack", 0); for(%i = 0; %i < %count; %i++) { %object = %parentObject.getObject(%i); if(!isObject(%object)) continue; %this.addInternalObjectPanel(%parentObject, %object); } } function LogickingEditorFieldEditor::addInternalObjectPanel(%this, %parentObject, %childObject) { %stack = createDataControl("stack", "0 0", %this.stackSize); %stack.StackingType = "Horizontal"; %childObjectName = %childObject.getName(); // selection button of an object %text = createDataControl("button", "0 0", %this.valueSize); %text.text = %childObjectName; %text.Command = " LogickingEditor.selectObject(" @ %childObject @ ");"; %stack.addGuiControl(%text); %this.addControl(%text); // buttons of camera movement to object's position and otherwise %manipulationButton = createDataControl("button", "0 0", %this.buttonSize); %stack.addGuiControl(%manipulationButton); %this.addControl(%manipulationButton); %manipulationButton.setText("..."); %this.reduceGuiControlSize(%text, %manipulationButton); %manipulationButton.Command = " LogickingEditorFieldEditor.showInternaiObjectManipulationButtons(" @ %manipulationButton @ "); "; %manipulationButton.ToolTip = "Show object manipulation buttons"; // moving button to the top of the list %button = createDataControl("button", "0 0", %this.buttonSize); %stack.addGuiControl(%button); %this.addControl(%button); %button.setText("Up"); %button.Command = " LogickingEditorFieldEditor.pushInternalObjectUp(" @ %parentObject @ ", " @ %childObject @ "); "; %button.ToolTip = "Bring object to front"; // moving camera to the object's position %button = createDataControl("icon", "0 0", %this.smallButtonSize); //%button.setBitmap("tools/LogickingEditor/images/GUI/toObjectPos.png"); %button.commandTemp = " LogickingEditor.moveCameraToObject(" @ %childObject @ "); "; %button.ToolTipTemp = "Move camera to objects position"; %stack.addGuiControl(%button); %this.reduceGuiControlSize(%text, %button); %manipulationButton.toObj = %button; // moving object to camera position %button = createDataControl("icon", "0 0", %this.smallButtonSize); //%button.setBitmap("tools/LogickingEditor/images/GUI/toCameraPos.png"); %button.commandTemp = " LogickingEditor.askMoveObjectToCamera(" @ %childObject @ "); "; %button.ToolTipTemp = "Place object to camera position"; %stack.addGuiControl(%button); %this.reduceGuiControlSize(%text, %button); %manipulationButton.toCam = %button; // delete of an object %button = createDataControl("icon", "0 0", %this.smallButtonSize); %button.setBitmap("tools/gui/images/iconDelete.png"); %button.command = " LogickingEditorFieldEditor.removeInternalObject(" @ %parentObject @ ", " @ %childObject @ "); "; %button.ToolTip = "Delete current object"; %stack.addGuiControl(%button); %this.reduceGuiControlSize(%text, %button); %mainStack = %parentObject.getName() @ "internalObjectsStack"; %mainStack.addGuiControl(%stack); %mainStack.pushToBack(addInternalObjectPanel); %mainStack.rollOut.sizeToContents(); } function LogickingEditorFieldEditor::showInternaiObjectManipulationButtons(%this, %button) { if(%this.selectedManipulationButton !$= "") { %toCam = %this.selectedManipulationButton.toCam; %toObj = %this.selectedManipulationButton.toObj; %toCam.setBitmap(""); %toObj.setBitmap(""); %toCam.command = ""; %toObj.command = ""; %toCam.ToolTip = ""; %toObj.ToolTip = ""; } %this.selectedManipulationButton = %button; %button.toObj.setBitmap("tools/LogickingEditor/images/GUI/toObjectPos.png"); %button.toCam.setBitmap("tools/LogickingEditor/images/GUI/toCameraPos.png"); %button.toCam.command = %button.toCam.commandTemp; %button.toObj.command = %button.toObj.commandTemp; %button.toCam.ToolTip = %button.toCam.ToolTipTemp; %button.toObj.ToolTip = %button.toObj.ToolTipTemp; } function LogickingEditorFieldEditor::removeInternalObject(%this, %parentObject, %childObject) { if(!isObject(%parentObject)) return; if(!isObject(%childObject) || !%parentObject.isMember(%childObject)) return; %parentObject.remove(%childObject); %childObject.schedule(0, "delete"); %this.inspectInternalObjects(%parentObject); } function LogickingEditorFieldEditor::pushInternalObjectUp(%this, %parentObject, %childObject) { if(!isObject(%parentObject)) return; if(!isObject(%childObject) || !%parentObject.isMember(%childObject)) return; %parentObject.bringToFront(%childObject); %this.inspectInternalObjects(%parentObject); } /////////////////////////////////////// // reduce of first element's width to second's element width function LogickingEditorFieldEditor::reduceGuiControlSize(%this, %text, %control) { %textExtent = %text.getExtent(); %textWidth = getWord(%textExtent, 0); %textHeight = getWord(%textExtent, 1); %controlExtent = %control.getExtent(); %text.setExtent(%textWidth - getWord(%controlExtent, 0), %textHeight); } function LogickingEditorFieldEditor::addControl(%this, %control) { %this.guiControls[counter] = %this.guiControls[counter] $= "" ? 0 : %this.guiControls[counter]; %counter = %this.guiControls[counter]; %this.guiControls[%counter] = %control; %this.guiControls[counter]++; } function LogickingEditorFieldEditor::addTextEdit(%this, %stack, %field, %value, %buttonCommand, %hint, %additionalControls) { %obj = getWord(%this.currentObjects, 0); %text = createDataControl("editorTextEdit", "0 0", %this.valueSize); %prevControl = %stack.getObject(0); if(isObject(%prevControl)) %this.reduceGuiControlSize(%text, %prevControl); %stack.addGuiControl(%text); %this.addControl(%text); %list = %this.checkFieldEquals(%field); if(%list !$= "") { %value = "!!!!! There is different values in: " @ %list @ " !!!!!!"; %text.skipValueSaving = true; } %text.text = %value; %text.ToolTip = %hint; %text.AltCommand = " LogickingEditorFieldEditor.applyFieldValueFromEdit($ThisControl, " @ %field @ "); "; %text.validate = " LogickingEditorFieldEditor.applyFieldValueFromEdit($ThisControl, " @ %field @ "); "; %text.fieldName = %field; %count = getWordCount(%additionalControls); for(%i = 0; %i < %count; %i++) { %controlType = getWord(%additionalControls, %i); switch$(%controlType) { case "playButton": %button = createDataControl("button", "0 0", %this.smallButtonSize); %stack.addGuiControl(%button); %this.addControl(%button); %button.setText(">"); %button.Command = " LogickingEditorFieldEditor.playSound(" @ %text @ "); "; %button.ToolTip = "Play sound"; %this.reduceGuiControlSize(%text, %button); } } %buttonCommand = " LogickingEditorFieldEditor.currentControl = " @ %text @ "; " @ %buttonCommand; %button = createDataControl("button", "0 0", %this.buttonSize); %stack.addGuiControl(%button); %this.addControl(%button); %button.setText("..."); %button.Command = %buttonCommand; %button.ToolTip = " Edit field value"; } function LogickingEditorFieldEditor::checkFieldExisting(%this, %fieldIndex) { %selectedAmount = getWordCount(%this.currentObjects); if(%selectedAmount < 2 ) return true; %object = getWord(%this.currentObjects, 0); %object = %object.getId(); %field = getFieldName(%object.templateName, %fieldIndex); for(%i = 0; %i < %selectedAmount; %i++) { %_object = getWord(%this.currentObjects, %i); if(%object == %_object || %_object.templateName $= "") continue; if(%field !$= getFieldName(%_object.templateName, %fieldIndex)) return false; } return true; } function LogickingEditorFieldEditor::checkFieldEquals(%this, %fieldName) { %selectedAmount = getWordCount(%this.currentObjects); %objectsList = ""; if(%selectedAmount < 2 ) return %objectsList; %object = getWord(%this.currentObjects, 0); %value = %object.getFieldValue(%fieldName); for(%i = 0; %i < %selectedAmount; %i++) { %_object = getWord(%this.currentObjects, %i); if(%object == %_object || %_object.templateName $= "") continue; if(%value !$= %_object.getFieldValue(%fieldName)) { if(%objectsList $= "") %objectsList = %object.getId() @ ":" @ %object.getName() @ ";"; %objectsList = %objectsList @ %_object.getId() @ ":" @ %_object.getName() @ "; "; } } return %objectsList; } function LogickingEditorFieldEditor::createFields(%this) { %this.clearFields(); %obj = getWord(%this.currentObjects, 0); if(!isObject(%obj)) return; %objectsAmount = getWordCount(%this.currentObjects); if(%objectsAmount > 1) { LogickingEditorFieldEditorWindow.text = " "; for(%i = 0; %i < %objectsAmount; %i++) { %_obj = getWord(%this.currentObjects, %i); LogickingEditorFieldEditorWindow.text = LogickingEditorFieldEditorWindow.text @ %_obj.getId() @ "; "; } objectNameLabel.setActive(false); objectNameEdit.setActive(false); objectNameEdit.setValue("# Group of objects #"); %_obj = getWord(%this.currentObjects, 0); %enabled = %_obj.isEnabled(); for(%i = 1; %i < %objectsAmount; %i++) { %_obj = getWord(%this.currentObjects, %i); if(%enabled != %_obj.isEnabled()) { objectEnableCheckBox.useInactiveState = 1; %enabled = -1; break; } } objectEnableCheckBox.setStateOn(%enabled); %_obj = getWord(%this.currentObjects, 0); %hidden = %_obj.isHidden(); for(%i = 1; %i < %objectsAmount; %i++) { %_obj = getWord(%this.currentObjects, %i); if(%_obj.isMethod("isHidden") && %hidden != %_obj.isHidden()) { objectHideCheckBox.useInactiveState = 1; %hidden = -1; break; } } objectHideCheckBox.setStateOn(%hidden); objectPositionLabel.setActive(false); objectPositionEdit.setActive(false); objectPositionEdit.setValue("# Group of objects #"); toObjectPosButton.setVisible(false); toCameraPosButton.setVisible(false); } else { %objName = %obj.getName(); LogickingEditorFieldEditorWindow.text = %obj.getId() @ " : " @ %objName; objectNameLabel.setActive(false); objectNameEdit.setActive(true); objectNameEdit.text = %objName; objectEnableCheckBox.setValue(%obj.isEnabled()); objectEnableCheckBox.useInactiveState = 0; if(%obj.isMethod(isHidden)) objectHideCheckBox.setValue(%obj.isHidden()); objectHideCheckBox.useInactiveState = 0; objectPositionLabel.setActive(true); objectPositionEdit.setActive(true); if(%obj.isMethod(getPosition)) objectPositionEdit.text = %obj.getPosition(); else objectPositionEdit.text = ""; if(%obj.isMethod("getPosition")) { toObjectPosButton.setVisible(true); toCameraPosButton.setVisible(true); } } if(%obj.isMethod(getScale)) objectScaleEdit.text = %obj.getScale(); else objectScaleEdit.text = ""; objectScaleEdit.setActive(true); %fieldsCount = getFieldsCounter(%obj.templateName); if(%obj.parentGroup !$= "" && %obj.parentGroup.templateName !$= "") { %parentStack = %this.getStack("General"); %stack = createDataControl("stack", "0 0", %this.stackSize); %stack.StackingType = "Horizontal"; %this.addControl(%stack); %parentStack.addGuiControl(%stack); %text = createDataControl("text", "0 0", %this.valueSize); %text.setText("Switch to parent:"); %text.ToolTip = "Switch parent group of deleted object"; %stack.addGuiControl(%text); %this.addControl(%text); %button = createDataControl("button", "0 0", %this.actionButtonSize); %stack.addGuiControl(%button); %this.addControl(%button); %button.setText(%obj.parentGroup); %button.ToolTip = %obj.parentGroup; %button.Command = " LogickingEditor.selectObject(" @ %obj.parentGroup @ ");"; %this.reduceGuiControlSize(%text, %button); } for(%i = 0; %i < %fieldsCount; %i++) { if(!%this.checkFieldExisting(%i)) continue; %type = getFieldType(%obj.templateName, %i); switch$(%type) { case "action": continue; case "group": %this.createGroupEditor(%obj, %i); continue; case "internalObjectsList" : %this.createInternalObjectsEditor(%obj, %i); continue; } %field = getFieldName(%obj.templateName, %i); %group = getFieldGroup(%obj.templateName, %i); %hint = getFieldHint(%obj.templateName, %i); %additional = getFieldAdditional(%obj.templateName, %i); %value = %obj.getFieldValue(%field); %parentStack = %this.getStack(%group); %stack = createDataControl("stack", "0 0", %this.stackSize); %stack.StackingType = "Horizontal"; %this.addControl(%stack); %text = createDataControl("text", "0 0", %this.fieldSize); %text.setText(%field @ " "); %text.ToolTip = %field; %stack.addGuiControl(%text); %this.addControl(%text); %this.addControlByType(%obj, %stack, %field, %type, %value, %group, %hint, %additional); %parentStack.addGuiControl(%stack); %parentStack.rollOut.sizeToContents(); } } function LogickingEditorFieldEditor::addControlByType(%this, %obj, %stack, %field, %type, %value, %group, %hint, %additional) { if(%type $= "") return; switch$(%type) { case "string": %this.addTextEdit(%stack, %field, %value, " LogickingEditorFieldEditor.editFieldValue(" @ %obj @ ", " @ %field @ ", false);", %hint); case "code": %this.addTextEdit(%stack, %field, %value, " LogickingEditorFieldEditor.editFieldValue(" @ %obj @ ", " @ %field @ ", true);", %hint); case "objectLink": %this.addObjectLink(%stack, %field, %value, %additional, %hint); case "file": %this.addTextEdit(%stack, %field, %value, " LogickingEditorFieldEditor.setFilePath(" @ %obj @ ", " @ %field @ ", \"" @ %additional @ "\");", %hint); case "sound": %this.addTextEdit(%stack, %field, %value, " LogickingEditorFieldEditor.setFilePath(" @ %obj @ ", " @ %field @ ", \"" @ %additional @ "\");", %hint, "playButton"); case "vector": %edit = createDataControl("editorTextEdit", "0 0", %this.valueListSize); %stack.addGuiControl(%edit); %this.addControl(%edit); %list = %this.checkFieldEquals(%field); if(%list !$= "") { %value = "!!!!! There is different values in: " @ %list @ " !!!!!!"; %edit.skipValueSaving = true; } %edit.text = %value; %edit.ToolTip = %hint; %edit.AltCommand = " LogickingEditorFieldEditor.setVectorValue($ThisControl, " @ %field @ "); "; %edit.validate = " LogickingEditorFieldEditor.setVectorValue($ThisControl, " @ %field @ "); "; %edit.fieldName = %field; /*case "action": %text.setExtent(getWord(%this.actionFieldSize, 0), getWord(%this.actionFieldSize, 1)); %button = createDataControl("button", "0 0", %this.actionButtonSize); %stack.addGuiControl(%button); %this.addControl(%button); %button.setText("Execute"); %button.Command = %obj.getId() @ "." @ %field @ "();"; %button.ToolTip = %hint; */ case "list": %idx = getFieldIndex(%obj.templateName, %field); %valuesCount = getFieldValuesCount(%obj.templateName, %idx); %list = createDataControl("list", "0 0", %this.valueListSize); %list.clear(); %stack.addGuiControl(%list); %this.addControl(%list); %list.command = " LogickingEditorFieldEditor.applyListFieldValue(" @ %list @ ", " @ %field @ "); "; %list.ToolTip = %hint; for(%i = 0; %i < %valuesCount; %i++) { %templateValue = getFieldValue(%obj.templateName, %idx, %i); %list.add(%templateValue, %i); } %objList = %this.checkFieldEquals(%field); if(%objList !$= "") { %value = "!!!!! There is different values in: " @ %objList @ " !!!!!!"; %list.add(%value, %valuesCount); %list.setSelected(%valuesCount); %list.skipValueSaving = true; } else { %selected = %list.findText(%value); %list.setSelected(%selected); } case "bool": %checkBox = createDataControl("checkBox", "0 0", %this.boolSize); %stack.addGuiControl(%checkBox); %this.addControl(%checkBox); if(%this.checkFieldEquals(%field) !$= "") { %value = -1; %checkBox.useInactiveState = 1; %checkBox.skipValueSaving = true; } %checkBox.setStateOn(%value); %checkBox.command = " LogickingEditorFieldEditor.applyBoolValue($ThisControl, " @ %field @ "); "; case "command": %button = createDataControl("button", "0 0", %this.actionButtonSize); %stack.addGuiControl(%button); %this.addControl(%button); %button.setText(%field); %button.Command = " Helpers::evalWithThisObj(\"" @ %additional @ "\", " @ %obj @ "); "; %button.ToolTip = %hint; } } function LogickingEditorFieldEditor::clearFields(%this) { %this.clearStackList(); %this.guiControls[counter] = %this.guiControls[counter] $= "" ? 0 : %this.guiControls[counter]; for(%i = 0; %i < %this.guiControls[counter]; %i++) { %control = %this.guiControls[%i]; if(isObject(%control)) %control.schedule(0, "delete"); %this.guiControls[%i] = ""; } %this.guiControls[counter] = 0; objectNameEdit.setText(""); objectNameEdit.setActive(false); objectEnableCheckBox.setValue(false); objectHideCheckBox.setValue(false); objectPositionEdit.setText(""); objectPositionEdit.setActive(false); objectScaleEdit.setText(""); objectScaleEdit.setActive(false); toObjectPosButton.setVisible(false); toCameraPosButton.setVisible(false); LogickingEditorFieldEditorWindow.text = "Select object to edit..."; } function LogickingEditorFieldEditor::editFieldValue(%this, %object, %field, %codeMode) { if(LogickingEditorFieldInspector.selected) return; LogickingEditor.showWindow(LogickingEditorFieldInspector); %this.currentField = %field; %this.codeMode = %codeMode; if(%codeMode) { //evaluateButton.Visible = true; LogickingEditor.pickingMode = true; LogickingEditor.selectNames = true; pickObjectModeCheckBox.Visible = true; pickObjectModeCheckBox.setValue(LogickingEditor.pickingMode); selectNamesCheckBox.Visible = true; selectNamesCheckBox.setValue(LogickingEditor.selectNames); LogickingEditorFieldInspectorWindow.Extent = "600 235"; } else { //evaluateButton.Visible = false; LogickingEditor.pickingMode = false; LogickingEditor.selectNames = false; pickObjectModeCheckBox.Visible = false; selectNamesCheckBox.Visible = false; LogickingEditorFieldInspectorWindow.Extent = "600 125"; } LogickingEditorFieldInspector.currentField = %field; LogickingEditorFieldInspectorWindow.text = %object.getName() @ " . " @ %field; %index = getFieldIndex(%object.templateName, %field); defaultValueText.text = getFieldValue(%object.templateName, %index); tolltipTextLabel.text = getFieldHint(%object.templateName, %index); tolltipTextLabel.ToolTip = getFieldHint(%object.templateName, %index); %argsCount = getFieldAdditional(%object.templateName, %index); argumentsPopUpMenu.clear(); argumentsPopUpMenu.add("%this", 0); for(%i = 0; %i < %argsCount; %i++) argumentsPopUpMenu.add("%arg" @ %i, %i + 1); argumentsPopUpMenu.setFirstSelected(); %value = LogickingEditorFieldEditor.currentControl.getValue();//%object.getFieldValue(%field); fieldInspectorEditBox.setText(%value); } /*function LogickingEditorFieldEditor::askGroupApply(%this, %fieldName, %value) { %msg = "Would you like to apply change for objects: "; %objectsAmount = EWorldEditor.getSelectionSize(); for(%i = 0; %i < %objectsAmount; %i++) { %object = EWorldEditor.getSelectedObject(%i); %msg = %msg @ "\n" @ %object.getId() @ ":" @ %object.getName() @ ";"; } MessageBoxYesNo( "Apply changes?", %msg, " LogickingEditorFieldEditor.setFieldValue(" @ %fieldName @ ", " @ %value @ ")"); }*/ function LogickingEditorFieldEditor::setFieldValue(%this, %fieldName, %value) { %objectsAmount = getWordCount(%this.currentObjects); for(%i = 0; %i < %objectsAmount; %i++) { %object = getWord(%this.currentObjects, %i); if(isObject(%object)) { %object.setFieldValue(%fieldName, %value); LogickingEditor.processLinks(%object); } } EWorldEditor.isDirty = true; } function LogickingEditorFieldEditor::setVectorValue(%this, %control, %fieldName) { %value = %control.getText(); %value = VectorAdd(%value, "0 0 0"); %control.setValue(%value); %this.setFieldValue(%fieldName, %value); %control.skipValueSaving = ""; } // Calls whenewer value is changed function LogickingEditorFieldEditor::applyFieldValueFromEdit(%this, %currentTextEdit, %fieldName) { if(LogickingEditorFieldInspector.selected && %fieldName $= %this.currentField) fieldInspectorEditBox.setText(%currentTextEdit.getText()); %this.setFieldValue(%fieldName, %currentTextEdit.getText()); } function LogickingEditorFieldEditor::applyBoolValue(%this, %control, %fieldName) { %this.setFieldValue(%fieldName, %control.getValue()); %control.skipValueSaving = ""; %control.useInactiveState = 0; } // Calls whenewer value is changed from inspector function LogickingEditorFieldEditor::applyFieldValue(%this) { %objectsAmount = getWordCount(%this.currentObjects); %value = fieldInspectorEditBox.getValue(); for(%i = 0; %i < %objectsAmount; %i++) { %object = getWord(%this.currentObjects, %i); if(isObject(%object)) { %object.setFieldValue(%this.currentField, %value); LogickingEditor.processLinks(%object); } } //if(%value $= "") %value = " "; %this.currentControl.setValue(%value); %this.currentControl.skipValueSaving = true; %this.currentControl = ""; LogickingEditorFieldInspector.close(); EWorldEditor.isDirty = true; } function LogickingEditorFieldEditor::applyListFieldValue(%this, %listBox, %fieldName) { if(%listBox.skipValueSaving) { %selected = %listBox.getSelected(); if(%selected == %listBox.size() - 1) { return; } %listBox.skipValueSaving = ""; %listBox.clear(); %obj = getWord(%this.currentObjects, 0); %index = getFieldIndex(%obj.templateName, %fieldName); %valuesCount = getFieldValuesCount(%obj.templateName, %index); for(%i = 0; %i < %valuesCount; %i++) { %templateValue = getFieldValue(%obj.templateName, %index, %i); %listBox.add(%templateValue, %i); } %listBox.setSelected(%selected); } %this.setFieldValue(%fieldName, %listBox.getText()); } function LogickingEditorFieldEditor::setFilePath(%this, %object, %field, %filter) { %index = getFieldIndex(%object.templateName, %field); %filter = %filter $= "" ? "*.*" : %filter; %dlg = new OpenFileDialog() { Filters = %filter; DefaultPath = $Pref::MissionEditor::LastPath; DefaultFile = ""; ChangePath = false; MustExist = true; }; %ret = %dlg.Execute(); if(%ret) { %path = filePath(%dlg.FileName) @ "/" @ fileBase(%dlg.FileName); %path = makeRelativePath(%path, getMainDotCSDir()); %this.setFieldValue(%field, %path); $Pref::MissionEditor::LastPath = filePath( %dlg.FileName ); %this.currentControl.text = %path; %this.currentControl = ""; } %dlg.schedule(0, "delete"); } function LogickingEditorFieldEditor::selectLinkedObject(%this, %button) { %text = %button.text; if(isObject(%text)) { LogickingEditor.selectObject(%text); } } function LogickingEditorFieldEditor::addObjectLink(%this, %stack, %field, %value, %additional, %hint) { %obj = getWord(%this.currentObjects, 0); %button = createDataControl("button", "0 0", %this.valueSize); %prevControl = %stack.getObject(0); if(isObject(%prevControl)) %this.reduceGuiControlSize(%button, %prevControl); %stack.addGuiControl(%button); %this.addControl(%button); %list = %this.checkFieldEquals(%field); if(%list !$= "") { %value = "!!!!! There is different values in: " @ %list @ " !!!!!!"; %button.skipValueSaving = true; } %button.setText(%value); %button.ToolTip = %hint; %button.Command = " LogickingEditorFieldEditor.selectLinkedObject(" @ %button @ ");"; %button.fieldName = %field; %button2 = createDataControl("button", "0 0", %this.buttonSize); %stack.addGuiControl(%button2); %this.addControl(%button2); %button2.setText("..."); %button2.Command = " LogickingEditorFieldEditor.currentControl = " @ %button @ "; LogickingEditorObjectsList.caller = LogickingEditorFieldEditor; LogickingEditorObjectsList.classNameFilter = \"" @ %additional @ "\"; LogickingEditor.toggleWindow(LogickingEditorObjectsList); "; %button2.ToolTip = "Select object"; if(%this.checkFieldEquals(%field) $= "") { %checkBox = createDataControl("checkBox", "0 0", %this.smallButtonSize); %this.reduceGuiControlSize(%button, %checkBox); %button.checkBox = %checkBox; %stack.addGuiControl(%checkBox); %this.addControl(%checkBox); %checkBox.ToolTip = "Enable/disable objectLink"; if(isObject(%value)) { %checkBox.ToolTip = "Enable/disable: \" " @ %value.getId() @ " : " @ %value.getName() @ " \""; %checkBox.setStateOn(%value.isEnabled()); %checkBox.command = " " @ %value @ ".setEnabled($ThisControl.getValue()); "; } } } function LogickingEditorFieldEditor::setFieldByDeafault(%this) { MessageBoxYesNo( "Set field value by default?", "Do you want to set field \"" @ %this.currentField @"\" to default value \"" @ defaultValueText.text @ "\" ?", " fieldInspectorEditBox.setValue(defaultValueText.text); ", ""); //fieldInspectorEditBox.schedule(200, \"onChangeCursorPos\", strlen(defaultValueText.text)); } function LogickingEditorFieldEditor::evaluateField(%this) { %retValue = Helpers::evalWithThisObj(fieldInspectorEditBox.getText(), getWord(LogickingEditor.currentObjects, 0), "", true); if(%retValue $= "") MessageBoxOK("Error!", "Parse error!!!"); else MessageBoxOK("Success!", "Syntax is correct!"); } function LogickingEditorFieldEditor::acceptPosition(%this) { %object = getWord(%this.currentObjects, 0); if(!%object.isMethod(setTransform)) return; %position = objectPositionEdit.getText(); %position = VectorAdd(%position, "0 0 0"); objectPositionEdit.setText(%position); %transform = %object.getTransform(); for(%i = 3; %i < 7; %i++) %position = %position @ " " @ getWord(%transform, %i); %object.setTransform(%position); EWorldEditor.isDirty = true; } function LogickingEditorFieldEditor::acceptScale(%this) { %scale = objectScaleEdit.getText(); %scale = VectorAdd(%scale, "0 0 0"); objectScaleEdit.setValue(%scale); %objectsAmount = getWordCount(%this.currentObjects); for(%i = 0; %i < %objectsAmount; %i++) { %object = getWord(%this.currentObjects, %i); if(%object.isMethod(setScale)) %object.setScale(%scale); } EWorldEditor.isDirty = true; } function LogickingEditorFieldEditor::acceptName(%this) { %object = getWord(LogickingEditor.currentObjects, 0); %newName = objectNameEdit.getText(); %object.setName(%newName); LogickingEditorFieldEditorWindow.text = "Current object: " @ %object.getId() @ " : " @ %object.getName(); currentObjectButton.text = %object.getId() @ " : " @ %object.getName(); %count = %object.getCount(); if(%count > 0) { for(%i = 0; %i < %count; %i++) { %childObject = %object.getObject(%i); %childObject.setName(%newName @ %childObject.nameMask @ "_" @ %i); } %this.inspectInternalObjects(%object); } EWorldEditor.isDirty = true; } function LogickingEditorFieldEditor::acceptEnabled(%this, %value) { %objectsAmount = getWordCount(%this.currentObjects); for(%i = 0; %i < %objectsAmount; %i++) { %object = getWord(%this.currentObjects, %i); if(%object.isMethod("setEnabled")) %object.setEnabled(%value); } objectEnableCheckBox.useInactiveState = 0; EWorldEditor.isDirty = true; } function LogickingEditorFieldEditor::acceptHidden(%this, %value) { %objectsAmount = getWordCount(%this.currentObjects); for(%i = 0; %i < %objectsAmount; %i++) { %object = getWord(%this.currentObjects, %i); if(%object.isMethod("setHidden")) %object.setHidden(%value); } objectHideCheckBox.useInactiveState = 0; EWorldEditor.isDirty = true; } function LogickingEditorFieldEditor::acceptAllChanges(%this) { if(%this.currentObjects $= "") return; // we must save change before focus lost for(%i = 0; %i < %this.guiControls[counter]; %i++) { %control = %this.guiControls[%i]; if(isObject(%control) && (%control.fieldName !$= "" && %control.skipValueSaving $= "")) { if(%control.getClassName() $= "GuiButtonCtrl") %value = %control.text; else %value = %control.getValue(); %this.setFieldValue(%control.fieldName, %value); } } } function LogickingEditorFieldEditor::onPickObject(%this, %object) { } function LogickingEditorFieldEditor::onStartSelection(%this) { if(!LogickingEditor.pickingMode) %this.currentObjects = ""; %this.isListSelected = true; } function LogickingEditorFieldEditor::onEndSelection(%this) { %this.isListSelected = false; if(!LogickingEditor.pickingMode) %this.createFields(); } function LogickingEditorFieldEditor::selectObject(%this, %object) { if(isObject(%this.currentControl)) { %value = %object.getName() $= "" ? %object.getId() : %object.getName(); %this.currentControl.setValue(%value); if(%this.currentControl.isMethod("setText")) %this.currentControl.setText(%value); if(isObject(%this.currentControl.checkBox)) %this.currentControl.checkBox.setStateOn(%object.isEnabled()); %this.setFieldValue(%this.currentControl.fieldName, %value); %this.currentControl = ""; LogickingEditorObjectsList.templateNameFilter = ""; LogickingEditorObjectsList.classNameFilter = ""; } } function LogickingEditorFieldEditor::onSelectObject(%this, %object) { %this.acceptAllChanges(); %n = EWorldEditor.getSelectionSize(); if(%this.isListSelected) %this.currentObjects = %this.currentObjects @ %object @ " "; else if((%this.isListSelected == false || %this.isListSelected $= "") && EWorldEditor.getSelectionSize() >1) { %this.currentObjects = ""; %count = EWorldEditor.getSelectionSize(); for(%i = 0; %i < %count; %i++) %this.currentObjects = %this.currentObjects @ EWorldEditor.getSelectedObject(%i) @ " "; } else { %this.currentObjects = %object; %this.createFields(); } } function LogickingEditorFieldEditor::onUnselectObject(%this) { %this.acceptAllChanges(); %this.clearFields(); %this.currentObjects = ""; } function LogickingEditorFieldEditor::onSleep(%this) { %this.acceptAllChanges(); %this.currentObjects = ""; } function LogickingEditorFieldEditor::insertArgument(%this) { %argument = argumentsPopUpMenu.getText(); %text = fieldInspectorEditBox.getValue(); %startPos = fieldInspectorEditBox.getCursorPos(); %endPos = fieldInspectorEditBox.getCursorPos(); if(LogickingEditorFieldEditor.posInText !$= "") { %startPos = getWord(LogickingEditorFieldEditor.posInText, 0); %endPos = getWord(LogickingEditorFieldEditor.posInText, 1); } %begin = getSubStr(%text, 0, %startPos); %end = getSubStr(%text, %endPos, strlen(%text)); %text = %begin @ %argument @ %end; fieldInspectorEditBox.text = %text; fieldInspectorEditBox.setCursorPos(strlen(%text)); } function LogickingEditorFieldEditor::insertAction(%this) { %action = availableActionsPopUp.getText(); if(%action $= "") return; %text = fieldInspectorEditBox.getValue(); %start = getWord(LogickingEditorFieldEditor.posInText, 0); %end = getWord(LogickingEditorFieldEditor.posInText, 1); %str = "()"; if(isObject(LogickingEditorFieldEditor.highlightedObject)) %index = getFieldIndex(LogickingEditorFieldEditor.highlightedObject.templateName, %action); if(%index !$= "" && %index != -1) %str = "(" @ getFieldAdditional(LogickingEditorFieldEditor.highlightedObject.templateName, %index) @ ")"; if(getSubStr(%text, %end, 1) $= ".") %end++; else %action = "." @ %action; %beginPart = getSubStr(%text, 0, %end); %end = getEndPos(%text, %end, " \t;"); %endPart = getSubStr(%text, %end, strlen(%text) - %end); if(strchr(");,", getSubStr(%endPart, 0, 1)) $= "") %str = %str @ ";"; %text = %beginPart @ %action @ %str @ %endPart; fieldInspectorEditBox.setValue(%text); fieldInspectorEditBox.setCursorPos(strlen(%text)); } function LogickingEditorFieldEditor::highlightObject(%this, %object) { EWorldEditor.highlightObject(%object); availableActionsLabel.Visible = true; availableActionsPopUp.Visible = true; insertActionButton.Visible = true; actionParametersLabel.setValue(""); availableActionsPopUp.clear(); LogickingEditorFieldEditor.highlightedObject = %object; %fieldsCount = getFieldsCounter(%object.templateName); %counter = 0; %selectedAction = ""; for(%i = 0; %i < %fieldsCount; %i++) { %group = getFieldGroup(%object.templateName, %i); if(%group $= "Actions") { %value = getFieldValue(%object.templateName, %i); availableActionsPopUp.add(%value, %counter); %counter++; if(%selectedAction $= "") %selectedAction = %i; } } availableActionsPopUp.setFirstSelected(); %params = getFieldHint(%object.templateName, %selectedAction); actionParametersLabel.text = %params; actionParametersLabel.Visible = true; } function LogickingEditorFieldEditor::clearHighlighting(%this) { EWorldEditor.clearHighlighting(); LogickingEditorFieldEditor.highlightedObject = ""; availableActionsLabel.Visible = false; availableActionsPopUp.Visible = false; insertActionButton.Visible = false; actionParametersLabel.Visible = false; actionParametersLabel.setValue(""); availableActionsPopUp.clear(); } function LogickingEditorFieldEditor::playSound(%this, %text) { if(%text.text $= "") return; %filePath = %text.text; %sfxSource = %this.cachedFiles[%filePath]; if(!isObject(%sfxSource)) { if(isObject(some)) some.schedule(0, "delete"); %sfxProfile = new SFXProfile("some") { filename = %filePath; description = %this.soundDescription; preload = true; }; MissionCleanup.add(%sfxProfile); if(!isObject(%sfxProfile)) { echo("Warning! ", %filePath, ". Unable to create profile for sound"); return; } %sfxSource = sfxCreateSource(%sfxProfile, 0, 0, 0); %this.cachedFiles[%filePath] = %sfxSource; } %sfxSource.play(); %sfxSource.schedule(5000, "stop"); } function LogickingEditorFieldEditor::flyPath(%this) { if(!isObject(%this.testCam)) return; %this.currentScene = %this.testCam; %path = getWord(%this.currentObjects, 0); if(!isObject(%path) || %path.getCount() == 0) return; %this.acceptAllChanges(); %node = %path.getObject(%i); %this.currentScene.setTransform(%node.getTransform()); %this.currentScene.reset(0); %this.currentScene.followPath(%path); LogickingEditor.closeAllWindows(); } function LogickingEditorFieldEditor::stopFly(%this) { if(%this.currentScene !$= "") { %this.currentScene.stop(); %this.currentScene = ""; } } function LogickingEditorFieldEditor::selectedToCameraPos(%this) { %objectsAmount = getWordCount(%this.currentObjects); for(%i = 0; %i < %objectsAmount; %i++) { %object = getWord(%this.currentObjects, %i); LogickingEditor.askMoveObjectToCamera(%object); } } function LogickingEditorFieldEditor::cameraToSelectedPos(%this) { %objectsAmount = getWordCount(%this.currentObjects); for(%i = 0; %i < %objectsAmount; %i++) { %object = getWord(%this.currentObjects, %i); LogickingEditor.moveCameraToObject(%object); } } function LogickingEditorFieldInspector::showActionParams(%this) { %fieldName = availableActionsPopUp.getText(); %index = getFieldIndex(LogickingEditorFieldEditor.highlightedObject.templateName, %fieldName); %params = getFieldAdditional(LogickingEditorFieldEditor.highlightedObject.templateName, %index); actionParametersLabel.text = %params; } function LogickingEditorFieldInspector::close(%this) { EWorldEditor.blockDelete = ""; LogickingEditor.toggleWindow(LogickingEditorFieldInspector); if(LogickingEditor.pickingMode) { LogickingEditor.pickingMode = false; if(getWordCount(LogickingEditorFieldEditor.currentObjects) == 1) LogickingEditor.selectObject(getWord(LogickingEditorFieldEditor.currentObjects, 0)); } EWorldEditor.clearHighlighting(); } function LogickingEditorFieldInspector::onWake(%this) { EWorldEditor.blockDelete = true; } function LogickingEditorFieldInspector::onPickObject(%this, %object) { %text = fieldInspectorEditBox.getText(); %startPos = fieldInspectorEditBox.getCursorPos(); %endPos = fieldInspectorEditBox.getCursorPos(); %char = getSubStr(%text, %startPos - 1, 1); %objectName = %object.getName() $= "" ? %object.getId() : %object.getName(); if(%char !$= " " && %char !$= "(" && %char !$= "") %objectName = " " @ %objectName; %begin = getSubStr(%text, 0, %startPos); %end = getSubStr(%text, %endPos, strlen(%text)); %text = %begin @ %objectName @ %end; fieldInspectorEditBox.text = %text; fieldInspectorEditBox.onChangeCursorPos(strlen(%text)); } function LogickingEditorFieldInspector::onSelectObject(%this, %object) { } function LogickingEditorFieldInspector::onUnselectObject(%this) { } function LogickingEditorFieldInspector::onStartSelection(%thist) { } function LogickingEditorFieldInspector::onEndSelection(%thist) { } function fieldInspectorEditBox::onChangeCursorPos(%this, %cursorPos) { if(!LogickingEditorFieldEditor.codeMode || LogickingEditorFieldEditor.codeMode $= "") return; %text = %this.getValue(); %start = 0; %end = strlen(%text); %start = getBeginPos(%text, %cursorPos, " \t.(;"); %end = getEndPos(%text, %cursorPos, " \t.();"); %text = getSubStr(%text, %start, %end - %start); if(isObject(%text)) { LogickingEditorFieldEditor.posInText = %start @ " " @ %end; LogickingEditorFieldEditor.highlightObject(%text); if(LogickingEditor.selectNames) fieldInspectorEditBox.selectText(%start, %end); return; } else { LogickingEditorFieldEditor.posInText = ""; LogickingEditorFieldEditor.clearHighlighting(); } if(getSubStr(%text, 0, 1) $= "%") { LogickingEditorFieldEditor.posInText = %start @ " " @ %end; if(LogickingEditor.selectNames) fieldInspectorEditBox.selectText(%start, %end); return; } else { LogickingEditorFieldEditor.posInText = ""; return; } } function getBeginPos(%text, %pos, %separators) { for(%i = %pos-1; %i >= 0; %i--) { %char = getSubStr(%text, %i, 1); if(strchr(%separators, %char) !$= "") { return %i + 1; } } return 0; } function getEndPos(%text, %pos, %separators) { if(strlen(%text) == 0) return 0; for(%i = %pos-1; %i < strlen(%text); %i++) { %char = getSubStr(%text, %i, 1); if(strchr(%separators, %char) !$= "") { return %i; } } return strlen(%text); } function breakToWords(%text, %separators) { if(strlen(%text) == 0) return ""; %tempBuf = ""; %returnBuf = ""; for(%i = 0; %i < strlen(%text); %i++) { %char = getSubStr(%text, %i, 1); if(strchr(%separators, %char) !$= "") { %returnBuf = %returnBuf @ %tempBuf @ " "; %tempBuf = ""; } else %tempBuf = %tempBuf @ %char; } %returnBuf = %returnBuf @ %tempBuf; return %returnBuf; } function breakToWordsA(%text, %separators) { if(strlen(%text) == 0) return ""; %counter = 0; %tempBuf = ""; for(%i = 0; %i < strlen(%text); %i++) { %char = getSubStr(%text, %i, 1); if(strchr(%separators, %char) !$= "") { $breakToWordsAReturnBuf[%counter] = %tempBuf; %tempBuf = ""; %counter++; } else %tempBuf = %tempBuf @ %char; } $breakToWordsAReturnBuf[%counter] = %tempBuf; %counter++; $breakToWordsAReturnBuf[counter] = %counter; } function clearBreakToWordsBuf() { for(%i = 0; %i < $breakToWordsAReturnBuf[counter]; %i++) { $breakToWordsAReturnBuf[%i] = ""; } $breakToWordsAReturnBuf[counter] = ""; }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Globalization; using Xunit; namespace System.Drawing.PrimitivesTest { public class RectangleTests { [Fact] public void DefaultConstructorTest() { Assert.Equal(Rectangle.Empty, new Rectangle()); } [Theory] [InlineData(int.MaxValue, int.MinValue, int.MaxValue, int.MinValue)] [InlineData(int.MaxValue, 0, int.MinValue, 0)] [InlineData(0, 0, 0, 0)] [InlineData(0, int.MinValue, 0, int.MaxValue)] public void NonDefaultConstructorTest(int x, int y, int width, int height) { Rectangle rect1 = new Rectangle(x, y, width, height); Rectangle rect2 = new Rectangle(new Point(x, y), new Size(width, height)); Assert.Equal(rect1, rect2); } [Theory] [InlineData(int.MaxValue, int.MinValue, int.MaxValue, int.MinValue)] [InlineData(int.MaxValue, 0, int.MinValue, 0)] [InlineData(0, 0, 0, 0)] [InlineData(0, int.MinValue, 0, int.MaxValue)] public void FromLTRBTest(int left, int top, int right, int bottom) { Rectangle rect1 = new Rectangle(left, top, right - left, bottom - top); Rectangle rect2 = Rectangle.FromLTRB(left, top, right, bottom); Assert.Equal(rect1, rect2); } [Fact] public void EmptyTest() { Assert.True(Rectangle.Empty.IsEmpty); Assert.True(new Rectangle(0, 0, 0, 0).IsEmpty); Assert.True(new Rectangle().IsEmpty); } [Theory] [InlineData(int.MaxValue, int.MinValue, int.MaxValue, int.MinValue)] [InlineData(int.MaxValue, 0, int.MinValue, 0)] [InlineData(int.MinValue, int.MaxValue, int.MinValue, int.MaxValue)] [InlineData(0, int.MinValue, 0, int.MaxValue)] public void NonEmptyTest(int x, int y, int width, int height) { Assert.False(new Rectangle(x, y, width, height).IsEmpty); } [Theory] [InlineData(int.MaxValue, int.MinValue, int.MaxValue, int.MinValue)] [InlineData(int.MaxValue, 0, int.MinValue, 0)] [InlineData(0, 0, 0, 0)] [InlineData(0, int.MinValue, 0, int.MaxValue)] [InlineData(int.MinValue, int.MaxValue, int.MinValue, int.MaxValue)] public void DimensionsTest(int x, int y, int width, int height) { Rectangle rect = new Rectangle(x, y, width, height); Assert.Equal(new Point(x, y), rect.Location); Assert.Equal(new Size(width, height), rect.Size); Assert.Equal(x, rect.X); Assert.Equal(y, rect.Y); Assert.Equal(width, rect.Width); Assert.Equal(height, rect.Height); Assert.Equal(x, rect.Left); Assert.Equal(y, rect.Top); Assert.Equal(x + width, rect.Right); Assert.Equal(y + height, rect.Bottom); Point p = new Point(width, height); Size s = new Size(x, y); rect.Location = p; rect.Size = s; Assert.Equal(p, rect.Location); Assert.Equal(s, rect.Size); Assert.Equal(width, rect.X); Assert.Equal(height, rect.Y); Assert.Equal(x, rect.Width); Assert.Equal(y, rect.Height); Assert.Equal(width, rect.Left); Assert.Equal(height, rect.Top); Assert.Equal(x + width, rect.Right); Assert.Equal(y + height, rect.Bottom); } [Theory] [InlineData(0, 0)] [InlineData(int.MaxValue, int.MinValue)] public static void LocationSetTest(int x, int y) { var point = new Point(x, y); var rect = new Rectangle(10, 10, 10, 10); rect.Location = point; Assert.Equal(point, rect.Location); Assert.Equal(point.X, rect.X); Assert.Equal(point.Y, rect.Y); } [Theory] [InlineData(0, 0)] [InlineData(int.MaxValue, int.MinValue)] public static void SizeSetTest(int x, int y) { var size = new Size(x, y); var rect = new Rectangle(10, 10, 10, 10); rect.Size = size; Assert.Equal(size, rect.Size); Assert.Equal(size.Width, rect.Width); Assert.Equal(size.Height, rect.Height); } [Theory] [InlineData(int.MaxValue, int.MinValue, int.MaxValue, int.MinValue)] [InlineData(int.MaxValue, 0, int.MinValue, 0)] [InlineData(0, int.MinValue, 0, int.MaxValue)] [InlineData(int.MinValue, int.MaxValue, int.MinValue, int.MaxValue)] public void EqualityTest(int x, int y, int width, int height) { Rectangle rect1 = new Rectangle(x, y, width, height); Rectangle rect2 = new Rectangle(width / 2, height / 2, x, y); Assert.True(rect1 != rect2); Assert.False(rect1 == rect2); Assert.False(rect1.Equals(rect2)); } [Fact] public static void EqualityTest_NotRectangle() { var rectangle = new Rectangle(0, 0, 0, 0); Assert.False(rectangle.Equals(null)); Assert.False(rectangle.Equals(0)); Assert.False(rectangle.Equals(new RectangleF(0, 0, 0, 0))); } [Fact] public static void GetHashCodeTest() { var rect1 = new Rectangle(10, 10, 10, 10); var rect2 = new Rectangle(10, 10, 10, 10); Assert.Equal(rect1.GetHashCode(), rect2.GetHashCode()); Assert.NotEqual(rect1.GetHashCode(), new Rectangle(20, 10, 10, 10).GetHashCode()); Assert.NotEqual(rect1.GetHashCode(), new Rectangle(10, 20, 10, 10).GetHashCode()); Assert.NotEqual(rect1.GetHashCode(), new Rectangle(10, 10, 20, 10).GetHashCode()); Assert.NotEqual(rect1.GetHashCode(), new Rectangle(10, 10, 10, 20).GetHashCode()); } [Theory] [InlineData(float.MaxValue, float.MinValue, float.MaxValue, float.MinValue)] [InlineData(float.MinValue, float.MaxValue, float.MinValue, float.MaxValue)] [InlineData(0, 0, 0, 0)] public void RectangleFConversionTest(float x, float y, float width, float height) { RectangleF rect = new RectangleF(x, y, width, height); Rectangle rCeiling = new Rectangle((int)Math.Ceiling(x), (int)Math.Ceiling(y), (int)Math.Ceiling(width), (int)Math.Ceiling(height)); Rectangle rTruncate = new Rectangle((int)x, (int)y, (int)width, (int)height); Rectangle rRound = new Rectangle((int)Math.Round(x), (int)Math.Round(y), (int)Math.Round(width), (int)Math.Round(height)); Assert.Equal(rCeiling, Rectangle.Ceiling(rect)); Assert.Equal(rTruncate, Rectangle.Truncate(rect)); Assert.Equal(rRound, Rectangle.Round(rect)); } [Theory] [InlineData(int.MaxValue, int.MinValue, int.MinValue, int.MaxValue)] [InlineData(0, int.MinValue, int.MaxValue, 0)] public void ContainsTest(int x, int y, int width, int height) { Rectangle rect = new Rectangle(2 * x - width, 2 * y - height, width, height); Point p = new Point(x, y); Rectangle r = new Rectangle(x, y, width / 2, height / 2); Assert.False(rect.Contains(x, y)); Assert.False(rect.Contains(p)); Assert.False(rect.Contains(r)); } [Theory] [InlineData(0, 0, 0, 0)] [InlineData(int.MaxValue, int.MinValue, int.MinValue, int.MaxValue)] [InlineData(0, int.MinValue, int.MaxValue, 0)] public void InflateTest(int x, int y, int width, int height) { Rectangle rect = new Rectangle(x, y, width, height); Rectangle inflatedRect = new Rectangle(x - width, y - height, width + 2 * width, height + 2 * height); Assert.Equal(inflatedRect, Rectangle.Inflate(rect, width, height)); rect.Inflate(width, height); Assert.Equal(inflatedRect, rect); Size s = new Size(x, y); inflatedRect = new Rectangle(rect.X - x, rect.Y - y, rect.Width + 2 * x, rect.Height + 2 * y); rect.Inflate(s); Assert.Equal(inflatedRect, rect); } [Theory] [InlineData(0, 0, 0, 0)] [InlineData(int.MaxValue, int.MinValue, int.MinValue, int.MaxValue)] [InlineData(0, int.MinValue, int.MaxValue, 0)] public void IntersectTest(int x, int y, int width, int height) { Rectangle rect = new Rectangle(x, y, width, height); Rectangle expectedRect = Rectangle.Intersect(rect, rect); rect.Intersect(rect); Assert.Equal(expectedRect, rect); Assert.False(rect.IntersectsWith(expectedRect)); } [Fact] public static void Intersect_IntersectingRects_Test() { var rect1 = new Rectangle(0, 0, 5, 5); var rect2 = new Rectangle(1, 1, 3, 3); var expected = new Rectangle(1, 1, 3, 3); Assert.Equal(expected, Rectangle.Intersect(rect1, rect2)); } [Theory] [InlineData(0, 0, 0, 0)] [InlineData(int.MaxValue, int.MinValue, int.MinValue, int.MaxValue)] [InlineData(int.MaxValue, 0, 0, int.MaxValue)] [InlineData(0, int.MinValue, int.MaxValue, 0)] public void UnionTest(int x, int y, int width, int height) { Rectangle a = new Rectangle(x, y, width, height); Rectangle b = new Rectangle(width, height, x, y); int x1 = Math.Min(a.X, b.X); int x2 = Math.Max(a.X + a.Width, b.X + b.Width); int y1 = Math.Min(a.Y, b.Y); int y2 = Math.Max(a.Y + a.Height, b.Y + b.Height); Rectangle expectedRectangle = new Rectangle(x1, y1, x2 - x1, y2 - y1); Assert.Equal(expectedRectangle, Rectangle.Union(a, b)); } [Theory] [InlineData(0, 0, 0, 0)] [InlineData(int.MaxValue, int.MinValue, int.MinValue, int.MaxValue)] [InlineData(int.MaxValue, 0, 0, int.MaxValue)] [InlineData(0, int.MinValue, int.MaxValue, 0)] public void OffsetTest(int x, int y, int width, int height) { Rectangle r1 = new Rectangle(x, y, width, height); Rectangle expectedRect = new Rectangle(x + width, y + height, width, height); Point p = new Point(width, height); r1.Offset(p); Assert.Equal(expectedRect, r1); expectedRect.Offset(p); r1.Offset(width, height); Assert.Equal(expectedRect, r1); } [Theory] [InlineData(0, 0, 0, 0)] [InlineData(5, -5, 0, 1)] public void ToStringTest(int x, int y, int width, int height) { var r = new Rectangle(x, y, width, height); Assert.Equal(string.Format(CultureInfo.CurrentCulture, "{{X={0},Y={1},Width={2},Height={3}}}", r.X, r.Y, r.Width, r.Height), r.ToString()); } } }
using System; using System.Collections.Generic; using System.Data.Services.Common; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using NuGet.Resources; namespace NuGet { [DataServiceKey("Id", "Version")] [EntityPropertyMapping("LastUpdated", SyndicationItemProperty.Updated, SyndicationTextContentKind.Plaintext, keepInContent: false)] [EntityPropertyMapping("Id", SyndicationItemProperty.Title, SyndicationTextContentKind.Plaintext, keepInContent: false)] [EntityPropertyMapping("Authors", SyndicationItemProperty.AuthorName, SyndicationTextContentKind.Plaintext, keepInContent: false)] [EntityPropertyMapping("Summary", SyndicationItemProperty.Summary, SyndicationTextContentKind.Plaintext, keepInContent: false)] [CLSCompliant(false)] public class DataServicePackage : IPackage { private readonly LazyWithRecreate<IPackage> _package; public DataServicePackage() { _package = new LazyWithRecreate<IPackage>(DownloadAndVerifyPackage, ShouldUpdatePackage); } public string Id { get; set; } public string Version { get; set; } public string Title { get; set; } public string Authors { get; set; } public string Owners { get; set; } public Uri IconUrl { get; set; } public Uri LicenseUrl { get; set; } public Uri ProjectUrl { get; set; } public Uri ReportAbuseUrl { get; set; } public Uri GalleryDetailsUrl { get; set; } public Uri DownloadUrl { get { return Context.GetReadStreamUri(this); } } public bool Listed { get; set; } public DateTimeOffset? Published { get; set; } public DateTimeOffset LastUpdated { get; set; } public int DownloadCount { get; set; } public bool RequireLicenseAcceptance { get; set; } public string Description { get; set; } public string Summary { get; set; } public string ReleaseNotes { get; set; } public string Language { get; set; } public string Tags { get; set; } public string Dependencies { get; set; } public string PackageHash { get; set; } public string PackageHashAlgorithm { get; set; } public bool IsLatestVersion { get; set; } public bool IsAbsoluteLatestVersion { get; set; } internal string OldHash { get; set; } internal IDataServiceContext Context { get; set; } internal PackageDownloader Downloader { get; set; } public string Copyright { get; set; } bool IPackage.Listed { get { return Listed; } } IEnumerable<string> IPackageMetadata.Authors { get { if (String.IsNullOrEmpty(Authors)) { return Enumerable.Empty<string>(); } return Authors.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); } } IEnumerable<string> IPackageMetadata.Owners { get { if (String.IsNullOrEmpty(Owners)) { return Enumerable.Empty<string>(); } return Owners.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); } } IEnumerable<PackageDependency> IPackageMetadata.Dependencies { get { if (String.IsNullOrEmpty(Dependencies)) { return Enumerable.Empty<PackageDependency>(); } return from d in Dependencies.Split('|') let dependency = ParseDependency(d) where dependency != null select dependency; } } SemanticVersion IPackageMetadata.Version { get { if (Version != null) { return new SemanticVersion(Version); } return null; } } public IEnumerable<IPackageAssemblyReference> AssemblyReferences { get { return _package.Value.AssemblyReferences; } } public IEnumerable<FrameworkAssemblyReference> FrameworkAssemblies { get { return _package.Value.FrameworkAssemblies; } } public IEnumerable<IPackageFile> GetFiles() { return _package.Value.GetFiles(); } public Stream GetStream() { return _package.Value.GetStream(); } public override string ToString() { return this.GetFullName(); } private bool ShouldUpdatePackage() { return ShouldUpdatePackage(MachineCache.Default); } internal bool ShouldUpdatePackage(IPackageRepository cacheRepository) { // If we never receieved a hash from the server or the hash changed re-download the package. if (String.IsNullOrEmpty(PackageHash) || !PackageHash.Equals(OldHash, StringComparison.OrdinalIgnoreCase)) { return true; } // If the package hasn't been cached, then re-download the package. IPackage package = GetPackage(cacheRepository); if (package == null) { return true; } // If the cached package hash isn't the same as incoming package hash // then re-download the package. string cachedHash = package.GetHash(PackageHashAlgorithm); if (!cachedHash.Equals(PackageHash, StringComparison.OrdinalIgnoreCase)) { return true; } return false; } private IPackage DownloadAndVerifyPackage() { return DownloadPackage(MachineCache.Default); } internal IPackage DownloadPackage(IPackageRepository cacheRepository) { IPackage package = null; // If OldHash is null, we're looking at a new instance of the data service package. // The package might be stored in the cache so we're going to try the looking there before attempting a download. if (OldHash == null) { package = GetPackage(cacheRepository); } if (package == null) { package = Downloader.DownloadPackage(DownloadUrl, this); // Add the package to the cache cacheRepository.AddPackage(package); // Clear the cache for this package ZipPackage.ClearCache(package); } // Update the hash OldHash = PackageHash; return package; } /// <summary> /// Parses a dependency from the feed in the format: /// id:versionSpec or id /// </summary> private static PackageDependency ParseDependency(string value) { if (String.IsNullOrWhiteSpace(value)) { return null; } string[] tokens = value.Trim().Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries); if (tokens.Length == 0) { return null; } // Trim the id string id = tokens[0].Trim(); IVersionSpec versionSpec = null; if (tokens.Length > 1) { // Attempt to parse the version VersionUtility.TryParseVersionSpec(tokens[1], out versionSpec); } return new PackageDependency(id, versionSpec); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We want to return null if any error occurred while trying to find the package.")] private IPackage GetPackage(IPackageRepository repository) { try { return repository.FindPackage(Id, ((IPackageMetadata)this).Version); } catch { // If the package in the repository is corrupted then return null return null; } } /// <summary> /// We can't use the built in Lazy for 2 reasons: /// 1. It caches the exception if any is thrown from the creator func (this means it won't retry calling the function). /// 2. There's no way to force a retry or expiration of the cache. /// </summary> private class LazyWithRecreate<T> { private readonly Func<T> _creator; private readonly Func<bool> _shouldRecreate; private T _value; private bool _isValueCreated; public LazyWithRecreate(Func<T> creator, Func<bool> shouldRecreate) { _creator = creator; _shouldRecreate = shouldRecreate; } public T Value { get { if (_shouldRecreate() || !_isValueCreated) { _value = _creator(); _isValueCreated = true; } return _value; } } } } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ #if CLR2 using Microsoft.Scripting.Utils; #endif using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Reflection; using System.Windows.Resources; using System.Windows; using System.Windows.Browser; using System.Net; using System.Windows.Threading; namespace Microsoft.Scripting.Silverlight { /// <summary> /// Interface for a browser virtual filesystem, as is expected /// by DLR-languages that run in Silverlight. /// </summary> public abstract class BrowserVirtualFilesystem { /// <summary> /// Defines the name of this filesystem. /// </summary> public abstract string Name(); /// <summary> /// The current "storage-unit", which is left up to the concrete /// classes to decide it's meaning. For a XAP file, the storage-unit /// is which XAP file to get files out of. For a web-server, it's /// an absolute URI. Basically, it maps to a current-drive for a /// traditional filesystem. /// </summary> public object CurrentStorageUnit { get; set; } /// <summary> /// Switches the storage unit and executes the given delegate in that /// context. /// </summary> /// <param name="storageUnit">the storage unit to switch to</param> /// <param name="action">delegate to run in the context of the storage unit</param> public void UsingStorageUnit(object storageUnit, Action action) { var origStorageUnit = CurrentStorageUnit; CurrentStorageUnit = storageUnit; action.Invoke(); CurrentStorageUnit = origStorageUnit; } /// <summary> /// Get a file based on a relative path, in the current storage unit /// </summary> /// <param name="relativePath"></param> /// <returns>the stream representing the file</returns> public Stream GetFile(string relativePath) { return GetFile(CurrentStorageUnit, relativePath); } /// <summary> /// Get a file based on a relative Uri, in the current storage unit /// </summary> /// <param name="relativePath"></param> /// <returns>the stream representing the file</returns> public Stream GetFile(Uri relativePath) { return GetFile(CurrentStorageUnit, relativePath); } /// <summary> /// Get a file based on a relative path, in the given storage unit /// </summary> /// <param name="storageUnit">Looks for the file in this</param> /// <param name="relativePath"></param> /// <returns>the stream representing the file</returns> public Stream GetFile(object storageUnit, string relativePath) { return GetFileInternal(storageUnit, relativePath); } /// <summary> /// Get a file based on a relative Uri, in the given storage unit /// </summary> /// <param name="storageUnit">Looks for the file in this</param> /// <param name="relativeUri"></param> /// <returns>the stream representing the file</returns> public Stream GetFile(object storageUnit, Uri relativeUri) { return GetFileInternal(storageUnit, relativeUri); } /// <summary> /// Get a file's contents based on a relative path, in the current /// storage-unit. /// </summary> /// <param name="relativeUri"></param> /// <returns>The file's contents as a string</returns> public string GetFileContents(string relativeUri) { return GetFileContents(CurrentStorageUnit, relativeUri); } /// <summary> /// Get a file's contents based on a relative Uri, in the current /// storage-unit. /// </summary> /// <param name="relativeUri"></param> /// <returns>The file's contents as a string</returns> public string GetFileContents(Uri relativeUri) { return GetFileContents(CurrentStorageUnit, relativeUri); } /// <summary> /// Get a file's contents based on a relative path, in the given /// storage-unit. /// </summary> /// <param name="storageUnit">Looks for the file in this</param> /// <param name="relativePath"></param> /// <returns>The file's contents as a string</returns> public string GetFileContents(object storageUnit, string relativePath) { return GetFileContents(storageUnit, new Uri(NormalizePath(relativePath), UriKind.Relative)); } /// <summary> /// Get a file's contents based on a relative Uri, in the given /// storage-unit. /// </summary> /// <param name="storageUnit">Looks for the file in this</param> /// <param name="relativeUri"></param> /// <returns>The file's contents as a string</returns> public string GetFileContents(object storageUnit, Uri relativeUri) { Stream stream = GetFile(storageUnit, relativeUri); if (stream == null) { return null; } string result; using (StreamReader sr = new StreamReader(stream)) { result = sr.ReadToEnd(); } return result; } /// <summary> /// Normalizes a path, which in general means making sure the directory /// separators are forward-slashes. /// </summary> /// <param name="path">a string representing a path</param> /// <returns>a normalized version of "path"</returns> public static string Normalize(string path) { return path.Replace('\\', '/'); } /// <summary> /// See (static) BrowserVirtualFilesystem.Normalize /// </summary> public virtual string NormalizePath(string path) { return BrowserVirtualFilesystem.Normalize(path); } /// <summary> /// Gets a file's stream /// </summary> /// <param name="storageUnit">Looks for the file in this</param> /// <param name="relativePath">path of the file</param> /// <returns>a Stream for the file's contents</returns> protected Stream GetFileInternal(object storageUnit, string relativePath) { return GetFileInternal(storageUnit, new Uri(NormalizePath(relativePath), UriKind.RelativeOrAbsolute)); } /// <summary> /// Defines how the specific virtual file-system gets a file. /// </summary> /// <param name="storageUnit"></param> /// <param name="relativeUri"></param> /// <returns></returns> protected abstract Stream GetFileInternal(object storageUnit, Uri relativeUri); } /// <summary> /// Access the XAP file contents /// </summary> public class XapVirtualFilesystem : BrowserVirtualFilesystem { public override string Name() { return "XAP file"; } /// <summary> /// Normalizes the path by making sure all directory separators are /// forward slashes, and makes sure no path starts with "./", as the /// root of the XAP file is an empty string. /// </summary> /// <param name="path"></param> /// <returns></returns> public override string NormalizePath(string path) { var normPath = base.NormalizePath(path); // Application.GetResource doesn't like paths that start with ./ // BUG: try to get this fixed in SL if (normPath.StartsWith("./")) { normPath = normPath.Substring(2); } return normPath; } /// <summary> /// Gets a Stream for a file from the given "xap" file. /// </summary> /// <param name="xap">a StreamResourceInfo representing a XAP file</param> /// <param name="relativeUri">a string respresenting a relative URI</param> /// <returns>a Stream for the file, or null if it did not find the file</returns> protected override Stream GetFileInternal(object xap, Uri relativeUri) { relativeUri = new Uri(NormalizePath(relativeUri.ToString()), UriKind.Relative); StreamResourceInfo sri = null; // TODO: Application.GetResourceStream always returns null when called from // a non-UI thread. Should dispatch to the UI thread but block this thread until // the call completes. if (xap == null) { sri = Application.GetResourceStream(relativeUri); } else { sri = Application.GetResourceStream((StreamResourceInfo) xap, relativeUri); } return sri == null ? DynamicApplication.GetManifestResourceStream(relativeUri.ToString()) : sri.Stream; } #region Depricated Methods /// <summary> /// Get the contents of the entry-point script as a string /// </summary> [Obsolete("This method will be unavaliable in the next version")] public string GetEntryPointContents() { return BrowserPAL.PAL.VirtualFilesystem.GetFileContents(Settings.EntryPoint); } /// <summary> /// Get a list of the assemblies defined in the AppManifest /// </summary> [Obsolete("Use DynamicApplication.Current.AppManifest.AssemblyParts() instead")] public List<Assembly> GetManifestAssemblies() { return DynamicApplication.Current.AppManifest.AssemblyParts(); } #endregion } /// <summary> /// Download and cache files over HTTP /// </summary> public class HttpVirtualFilesystem : BrowserVirtualFilesystem { public override string Name() { return "Web server"; } /// <summary> /// The cache of files already downloaded /// </summary> private DownloadCache _cache = new DownloadCache(); /// <summary> /// Gets a file out of the download cache. This does not download the /// file if it is not in the cache; use "DownloadAndCache" before /// using this method download the file and cache it. /// </summary> /// <param name="baseUri"> /// URI to base relative URI's off of. If null, it defaults to the HTML /// page's URI. /// </param> /// <param name="relativeUri">URI relative to the base URI</param> /// <returns>A stream for the URI</returns> protected override Stream GetFileInternal(object baseUri, Uri relativeUri) { if (!relativeUri.IsAbsoluteUri) { // TODO: HttpVirtualFilesystem shouldn't manage all these checks, // needs to be re-organized. // check in the XAP first var stream = XapPAL.PAL.VirtualFilesystem.GetFile(relativeUri); if (stream != null) return stream; // also check any ZIP files if (HtmlPage.IsEnabled && (DynamicApplication.Current != null && DynamicApplication.Current.ScriptTags != null)) { foreach (var zip in DynamicApplication.Current.ScriptTags.ZipPackages) { var relUriStr = relativeUri.ToString(); var dirname = Path.GetDirectoryName(relUriStr); if (dirname.Length == 0) continue; var dirs = dirname.Split('/'); if (dirs.Length == 0) continue; var toplevelDir = dirs[0]; if (toplevelDir != Path.GetFileNameWithoutExtension(zip.ToString())) continue; var rest = relUriStr.Split(new string[] { toplevelDir + "/" }, StringSplitOptions.None); if (rest.Length <= 1) continue; var pathToFileInZip = rest[1]; var file = XapPAL.PAL.VirtualFilesystem.GetFile( new StreamResourceInfo(GetFileInternal(baseUri, zip), null), pathToFileInZip ); if (file != null) return file; } } } var fullUri = DynamicApplication.MakeUri((Uri)baseUri, relativeUri); if (_cache.Has(fullUri)) { byte[] bytes = _cache.GetBinary(fullUri); string strContent = _cache.Get(fullUri); return new MemoryStream( strContent != null ? System.Text.Encoding.UTF8.GetBytes(strContent) : bytes ); } else { return null; } } /// <summary> /// Download and cache a list of URIs, and execute a delegate when it's /// complete. /// </summary> /// <param name="uris">List of URIs to download and cache</param> /// <param name="onComplete"> /// Called when the URI's are successfully downloaded and cached /// </param> internal void DownloadAndCache(List<Uri> uris, Action onComplete) { _cache.Download(uris, onComplete); } } /// <summary> /// A cache of Uris mapping to strings. /// </summary> public class DownloadCache { // TODO: shouldn't differentiate between TextContent and BinaryContent, // should just have BinaryContent and then convert to UTF8 for TextContent. internal struct DownloadContent { internal string TextContent; internal byte[] BinaryContent; internal DownloadContent(string tC, byte[] bC) { TextContent = tC; BinaryContent = bC; } } private DownloadCacheDownloader _downloader; public DownloadCache() { _downloader = new DownloadCacheDownloader(this); } private Dictionary<Uri, DownloadContent> _cache = new Dictionary<Uri, DownloadContent>(); /// <summary> /// Adds a URI/code pair to the cache if the URI doesn't not already /// exist. /// </summary> /// <param name="uri"></param> /// <param name="code"></param> public void Add(Uri uri, string code) { if (!Has(uri)) { _cache.Add(uri, new DownloadContent(code, null)); } } public void Add(Uri uri, byte[] data) { if (!Has(uri)) { _cache.Add(uri, new DownloadContent(null, data)); } } /// <summary> /// Gets a string from the cache from a URI. Returns null if the URI is /// not in the cache. /// </summary> /// <param name="uri">A URI to look-up</param> /// <returns>Binary content associated with that URI.</returns> public string Get(Uri uri) { if (!Has(uri)) return null; return _cache[uri].TextContent; } /// <summary> /// Get binary content from the cache from a URI. Returns null if the /// URI is not in the cache. /// </summary> /// <param name="uri">A URI to look-up</param> /// <returns>Binary content associated with that URI.</returns> public byte[] GetBinary(Uri uri) { if (!Has(uri)) return null; return _cache[uri].BinaryContent; } /// <summary> /// Indexer to Get and Add string to the cache. Indexes on URIs. /// </summary> public string this[Uri uri] { get { return Get(uri); } set { Add(uri, value); } } /// <summary> /// Does the cache contain the URI? /// </summary> public bool Has(Uri uri) { return _cache.ContainsKey(uri); } /// <summary> /// Clears the cache completely. /// </summary> public void Clear() { _cache = null; _cache = new Dictionary<Uri, DownloadContent>(); } /// <summary> /// Downloads the list of URIs, caches the result of the download, and /// calls onComplete when finished. /// </summary> public void Download(List<Uri> uris, Action onComplete) { _downloader.Download(uris, onComplete); } internal class DownloadCacheDownloader { private List<Uri> _downloadQueue; private DownloadCache _cache; internal DownloadCacheDownloader(DownloadCache cache) { _cache = cache; } internal void Download(List<Uri> uris, Action onComplete) { if (uris.Count == 0) { onComplete.Invoke(); return; } _downloadQueue = new List<Uri>(uris); var iteratingQueue = new List<Uri>(_downloadQueue); foreach (var uri in iteratingQueue) { InternalDownload(uri, onComplete); } } private void InternalDownload(Uri uri, Action onComplete) { if (HasDomainFailed(uri.Host)) { DownloadWithXmlHttpRequest(uri, onComplete); } else { DownloadWithWebClient(uri, onComplete, () => { DomainFailed(uri.Host); DownloadWithXmlHttpRequest(uri, onComplete); }); } } private void DownloadComplete(Uri uri, Stream content, Action onComplete) { DownloadComplete(uri, StreamToByteArray(content), onComplete); } private void DownloadComplete(Uri uri, byte[] content, Action onComplete) { _cache.Add(uri, content); InternalDownloadComplete(uri, onComplete); } private byte[] StreamToByteArray(Stream stream) { byte[] buffer = new byte[stream.Length]; int read = stream.Read(buffer, 0, buffer.Length); return buffer; } private void DownloadComplete(Uri uri, string content, Action onComplete) { _cache.Add(uri, content); InternalDownloadComplete(uri, onComplete); } private void InternalDownloadComplete(Uri uri, Action onComplete) { if (_downloadQueue != null) { lock (_downloadQueue) { if (_downloadQueue != null && _downloadQueue.Count > 0 && _downloadQueue.Contains(uri)) { _downloadQueue.Remove(uri); if (_downloadQueue.Count == 0) { _downloadQueue = null; onComplete.Invoke(); } } } } } #region WebRequest / XMLHttpRequest fail-over private Dictionary<string, bool> _webClientDownloadFailureForDomain = new Dictionary<string, bool>(); private bool HasDomainFailed(string host) { return _webClientDownloadFailureForDomain.ContainsKey(host) && _webClientDownloadFailureForDomain[host]; } private void DomainFailed(string host) { _webClientDownloadFailureForDomain[host] = true; } #endregion #region WebRequest private void DownloadWithWebClient(Uri uri, Action onComplete, Action onSecurityException) { var webClient = new WebClient(); webClient.OpenReadCompleted += (s, e) => { if (e.Error == null && e.Cancelled == false) { var requestUri = (Uri)((object[])e.UserState)[0]; var completeAction = (Action)((object[])e.UserState)[1]; DownloadComplete(requestUri, e.Result, completeAction); } else { if (e.Error.InnerException.GetType() == typeof(System.Security.SecurityException)) { onSecurityException(); } else { throw e.Error.InnerException; } } }; webClient.OpenReadAsync(uri, new object[] { uri, onComplete }); } #endregion #region XMLHttpRequest // XMLHttpRequest is used instead of WebClient when this // scenario happens: // localhost/index.html --> bar.com/dlr.xap --> localhost/foo.py // ^^^ // WebClient refuses to do the marked request, because you cannot // make a request from an internet-zone to a local-zone. XMLHttpRequest // works though, since it executes in the local domain. // // Also, when the XAP is hosted cross-domain, all inbound HTML // events and interactions are disabled. This can be re-enabled // by both setting the ExternalCallersFromCrossDomain property in the // AppManifest.xaml to "ScriptableOnly" and setting the "enableHtmlAccess" // param on the Silverlight object tag to "true". This not only allows the // "XMLHttpRequest.onreadstatechange" event to call back into managed // code, but re-enabled all HTML events, like the REPL. See // http://msdn.microsoft.com/en-us/library/cc645023(VS.95).aspx for // more information. // // If for some reason you can't change the AppManifest's settings, // you'll have to use polling to detect when the download is done // (see "XMLHttpRequest with polling" region below). However this is // not enabled anywhere, as the scenario is a bit limited. // // Also note that OnXmlHttpDownloadComplete catches ALL exceptions // to make sure they don't leak out into JavaScript. private bool _emittedXMLHttpRequestHander = false; private void DownloadWithXmlHttpRequest(Uri uri, Action onComplete) { if (!_emittedXMLHttpRequestHander) { if (HtmlPage.BrowserInformation.Name == "Microsoft Internet Explorer") { // IE's JavaScript API has no way of getting to binary data from XMLHttpRequest, // so resort to VBScript. However, the performance of this is horrible. AddScriptTag("vbscript", null, @" Function BinaryArrayToAscCSV( aBytes ) Dim j, sOutput sOutput = """" For j = 1 to LenB(aBytes) sOutput= sOutput & AscB( MidB(aBytes,j,1) ) sOutput= sOutput & "","" Next BinaryArrayToAscCSV = sOutput End Function "); AddScriptTag(null, "text/javascript", @" function request2csv(request) { return BinaryArrayToAscCSV(request.responseBody); } "); } HtmlPage.Window.Eval(@" function OnXmlHttpRequest_ReadyStateChange(file) { return function() { this.currentSLObject.OnXmlHttpDownloadComplete(this, file); } } var isIE = false; function DLR_DownloadResource(uri, binary) { request = new XMLHttpRequest(); request.open('GET', uri, false); if (binary && request.overrideMimeType) request.overrideMimeType('text/plain; charset=x-user-defined'); request.send(); if (request.status != 200) return ''; var raw; if (binary && typeof(request.responseBody) !== 'undefined') { isIE = true; raw = BinaryArrayToAscCSV(request.responseBody); return raw.substring(0, raw.length - 2).split(','); } else { return request.responseText; } } function DLR_DownloadTextResource(uri) { return DLR_DownloadResource(uri, false); } function DLR_DownloadBinaryResource(uri) { var raw = DLR_DownloadResource(uri, true); var data = new Array(raw.length); if (isIE) { for(i = 0; i < raw.length; i++) { data[i] = parseInt(raw[i]); } } else { for(i = 0; i < raw.length; i++) { data[i] = raw.charCodeAt(i) & 0xff; } } return data; } "); _emittedXMLHttpRequestHander = true; } var file = uri.ToString(); // HACK treat zip files as binary content if (Path.GetExtension(file).Contains("zip")) { ScriptObject bin = (ScriptObject)HtmlPage.Window.Eval(string.Format(@"DLR_DownloadBinaryResource(""{0}"");", file)); byte[] binaryContent = new byte[(int)(double)bin.GetProperty("length")]; for (int i = 0; i < binaryContent.Length; i++) { binaryContent[i] = (byte)(double)bin.GetProperty(i.ToString()); } DownloadComplete(new Uri(file, UriKind.RelativeOrAbsolute), binaryContent, onComplete); } else { string content = (string)(HtmlPage.Window.GetProperty("DLR_DownloadTextResource") as ScriptObject).InvokeSelf(file); DownloadComplete(new Uri(file, UriKind.RelativeOrAbsolute), content, onComplete); } } private void AddScriptTag(string lang, string type, string text) { var scriptTag = HtmlPage.Document.CreateElement("script"); if (lang != null) scriptTag.SetAttribute("language", lang); if (type != null) scriptTag.SetAttribute("type", type); scriptTag.SetProperty("text", text); (HtmlPage.Document.GetElementsByTagName("head")[0] as HtmlElement).AppendChild(scriptTag); } #if false private Action _onComplete; // Managed handler of XmlHttpRequest.onreadstatechange; a JavaScript one is currently // used, but switching back to this might be best for performance. [ScriptableMember] public void OnXmlHttpDownloadComplete(ScriptObject handlerThis, string file) { try { object objReadyState = handlerThis.GetProperty("readyState"); object objStatus = handlerThis.GetProperty("status"); int readyState = 0; int status = 0; if (objStatus != null) status = (int)((double)objStatus / 1); if (objReadyState != null) readyState = (int)((double)objReadyState / 1); if (readyState == 4 && status == 200) { // HACK treat zip files as binary content if (Path.GetExtension(file).Contains("zip")) { string content; byte[] binaryContent; if (HtmlPage.BrowserInformation.UserAgent.IndexOf("MSIE") != -1) { content = (string)HtmlPage.Window.Invoke("request2csv", handlerThis); var strArray = content.Substring("BinaryArrayToAscCSV".Length).Split(','); binaryContent = new byte[strArray.Length]; for (int i = 0; i < strArray.Length; i++) { string strByte = strArray[i]; if (strByte.Length == 0) break; binaryContent[i] = byte.Parse(strByte); } } else { content = (string)handlerThis.GetProperty("responseText"); binaryContent = new byte[content.Length]; for (int i = 0; i < content.Length; i++) { binaryContent[i] = (byte)(((int)content[i]) & 0xff); } } DownloadComplete(new Uri(file, UriKind.RelativeOrAbsolute), binaryContent, _onComplete); } else { string content = (string)handlerThis.GetProperty("responseText"); DownloadComplete(new Uri(file, UriKind.RelativeOrAbsolute), content, _onComplete); } } else if (readyState == 4 && status != 200) { throw new Exception(file + " download failed (status: " + status + ")"); } } catch (Exception e) { // This catch-all is necessary since any unhandled exceptions // will not be processed by Application.UnhandledException, so // call it directly if reporting errors is enabled. if (Settings.ReportUnhandledErrors) DynamicApplication.Current.HandleException(this, e); } } #endif #endregion #region XMLHttpRequest with polling #if false private void DownloadWithXmlHttpRequestAndPolling(Uri uri, Action onComplete) { var request = HtmlPage.Window.CreateInstance("XMLHttpRequest"); request.Invoke("open", "GET", uri.ToString()); request.SetProperty("onreadystatechange", HtmlPage.Window.Eval("DLR.__onDownloadCompleteToPoll(\"" + uri.ToString() + "\")")); request.Invoke("send"); PollForDownloadComplete(uri, onComplete); } private void PollForDownloadComplete(Uri uri, Action onComplete) { var pollCount = 0; var timer = new DispatcherTimer(); timer.Interval = new TimeSpan(0, 0, 0, 0, 50); timer.Tick += (sender, args) => { object objStatus = null; int status = 0; var obj = HtmlPage.Document.GetElementById(uri.ToString()); if (obj != null) { objStatus = obj.GetProperty("status"); if (objStatus != null) status = (int)((double)objStatus / 1); } Action<Uri, int> onFailure = (duri, dstatus) => { timer.Stop(); throw new Exception(duri.ToString() + " download failed (status: " + dstatus + ")"); }; if (status == 200) { var content = (string)obj.GetProperty("scriptContent"); HtmlPage.Document.Body.RemoveChild(obj); timer.Stop(); DownloadComplete(uri, content, onComplete); } else if (status == 400) { onFailure(uri, status); } else { if (pollCount < 50) pollCount++; else onFailure(uri, status); } }; timer.Start(); } #endif #endregion } } #if false /// <summary> /// Read and write files from Isolated Storage /// </summary> public class IsolatedStorageVirtualFilesystem : BrowserVirtualFilesystem { public override string Name() { return "Isolated Storage"; } protected override Stream GetFileInternal(object baseUri, Uri relativeUri) { throw new NotImplementedException("TODO"); } } #endif }
// // Encog(tm) Core v3.3 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, 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. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using Encog.ML.Data; using Encog.ML.Train; using Encog.Neural.Networks.Training.Propagation; namespace Encog.ML.SVM.Training { /// <summary> /// Provides training for Support Vector Machine networks. /// </summary> /// public class SVMSearchTrain : BasicTraining { /// <summary> /// The default starting number for C. /// </summary> /// public const double DefaultConstBegin = 1; /// <summary> /// The default ending number for C. /// </summary> /// public const double DefaultConstEnd = 15; /// <summary> /// The default step for C. /// </summary> /// public const double DefaultConstStep = 2; /// <summary> /// The default gamma begin. /// </summary> /// public const double DefaultGammaBegin = 1; /// <summary> /// The default gamma end. /// </summary> /// public const double DefaultGammaEnd = 10; /// <summary> /// The default gamma step. /// </summary> /// public const double DefaultGammaStep = 1; /// <summary> /// The internal training object, used for the search. /// </summary> /// private readonly SVMTrain _internalTrain; /// <summary> /// The network that is to be trained. /// </summary> /// private readonly SupportVectorMachine _network; /// <summary> /// The best error. /// </summary> /// private double _bestError; /// <summary> /// The beginning value for C. /// </summary> /// private double _constBegin; /// <summary> /// The ending value for C. /// </summary> /// private double _constEnd; /// <summary> /// The step value for C. /// </summary> /// private double _constStep; /// <summary> /// The current C. /// </summary> /// private double _currentConst; /// <summary> /// The current gamma. /// </summary> /// private double _currentGamma; /// <summary> /// The number of folds. /// </summary> /// private int _fold; /// <summary> /// The beginning value for gamma. /// </summary> /// private double _gammaBegin; /// <summary> /// The ending value for gamma. /// </summary> /// private double _gammaEnd; /// <summary> /// The step value for gamma. /// </summary> /// private double _gammaStep; /// <summary> /// Is the network setup. /// </summary> /// private bool _isSetup; /// <summary> /// Is the training done. /// </summary> /// private bool _trainingDone; /// <summary> /// The best values found for C. /// </summary> /// public double BestConst { get; set; } /// <summary> /// The best values found for gamma. /// </summary> /// private double BestGamma { get; set; } /// <summary> /// Construct a trainer for an SVM network. /// </summary> /// /// <param name="method">The method to train.</param> /// <param name="training">The training data for this network.</param> public SVMSearchTrain(SupportVectorMachine method, IMLDataSet training) : base(TrainingImplementationType.Iterative) { _fold = 0; _constBegin = DefaultConstBegin; _constStep = DefaultConstStep; _constEnd = DefaultConstEnd; _gammaBegin = DefaultGammaBegin; _gammaEnd = DefaultGammaEnd; _gammaStep = DefaultGammaStep; _network = method; Training = training; _isSetup = false; _trainingDone = false; _internalTrain = new SVMTrain(_network, training); } /// <inheritdoc/> public override sealed bool CanContinue { get { return false; } } /// <value>the constBegin to set</value> public double ConstBegin { get { return _constBegin; } set { _constBegin = value; } } /// <value>the constEnd to set</value> public double ConstEnd { get { return _constEnd; } set { _constEnd = value; } } /// <value>the constStep to set</value> public double ConstStep { get { return _constStep; } set { _constStep = value; } } /// <value>the fold to set</value> public int Fold { get { return _fold; } set { _fold = value; } } /// <value>the gammaBegin to set</value> public double GammaBegin { get { return _gammaBegin; } set { _gammaBegin = value; } } /// <value>the gammaEnd to set.</value> public double GammaEnd { get { return _gammaEnd; } set { _gammaEnd = value; } } /// <value>the gammaStep to set</value> public double GammaStep { get { return _gammaStep; } set { _gammaStep = value; } } /// <inheritdoc/> public override IMLMethod Method { get { return _network; } } /// <value>True if the training is done.</value> public override bool TrainingDone { get { return _trainingDone; } } /// <inheritdoc/> public override sealed void FinishTraining() { _internalTrain.Gamma = BestGamma; _internalTrain.C = BestConst; _internalTrain.Iteration(); } /// <summary> /// Perform one training iteration. /// </summary> public override sealed void Iteration() { if (!_trainingDone) { if (!_isSetup) { Setup(); } PreIteration(); _internalTrain.Fold = _fold; if (_network.KernelType == KernelType.RadialBasisFunction) { _internalTrain.Gamma = _currentGamma; _internalTrain.C = _currentConst; _internalTrain.Iteration(); double e = _internalTrain.Error; //System.out.println(this.currentGamma + "," + this.currentConst // + "," + e); // new best error? if (!Double.IsNaN(e)) { if (e < _bestError) { BestConst = _currentConst; BestGamma = _currentGamma; _bestError = e; } } // advance _currentConst += _constStep; if (_currentConst > _constEnd) { _currentConst = _constBegin; _currentGamma += _gammaStep; if (_currentGamma > _gammaEnd) { _trainingDone = true; } } Error = _bestError; } else { _internalTrain.Gamma = _currentGamma; _internalTrain.C = _currentConst; _internalTrain.Iteration(); } PostIteration(); } } /// <inheritdoc/> public override sealed TrainingContinuation Pause() { return null; } /// <inheritdoc/> public override void Resume(TrainingContinuation state) { } /// <summary> /// Setup to train the SVM. /// </summary> /// private void Setup() { _currentConst = _constBegin; _currentGamma = _gammaBegin; _bestError = Double.PositiveInfinity; _isSetup = true; if (_currentGamma <= 0 || _currentGamma < EncogFramework.DefaultDoubleEqual) { throw new EncogError("SVM search training cannot use a gamma value less than zero."); } if (_currentConst <= 0 || _currentConst < EncogFramework.DefaultDoubleEqual) { throw new EncogError("SVM search training cannot use a const value less than zero."); } if (_gammaStep < 0) { throw new EncogError("SVM search gamma step cannot use a const value less than zero."); } if (_constStep < 0) { throw new EncogError("SVM search const step cannot use a const value less than zero."); } } } }
using System; using System.Collections.Generic; using System.Runtime.Serialization; using Platform.Text; using ServiceStack.DataAnnotations; using ServiceStack.DesignPatterns.Model; namespace ServiceStack.Text.Tests.Support { [DataContract(Namespace = "http://schemas.ddnglobal.com/types/")] public class UserPublicView { /// <summary> /// I'm naming this 'Id' instead of 'UserId' as this is dto is /// meant to be cached and we may want to handle all caches generically at some point. /// </summary> /// <value>The id.</value> [DataMember] public Guid Id { get; set; } [DataMember] public UserPublicProfile Profile { get; set; } [DataMember] public ArrayOfPost Posts { get; set; } } [Serializable] [DataContract(Namespace = "http://schemas.ddnglobal.com/types/")] public class UserPublicProfile { public UserPublicProfile() { this.FollowerUsers = new List<UserSearchResult>(); this.FollowingUsers = new List<UserSearchResult>(); this.UserFileTypes = new ArrayOfString(); } [DataMember] public Guid Id { get; set; } [DataMember] public string UserType { get; set; } [DataMember] public string UserName { get; set; } [DataMember] public string FullName { get; set; } [DataMember] public string Country { get; set; } [DataMember] public string LanguageCode { get; set; } [DataMember] public DateTime? DateOfBirth { get; set; } [DataMember] public DateTime? LastLoginDate { get; set; } [DataMember] public long FlowPostCount { get; set; } [DataMember] public int BuyCount { get; set; } [DataMember] public int ClientTracksCount { get; set; } [DataMember] public int ViewCount { get; set; } [DataMember] public List<UserSearchResult> FollowerUsers { get; set; } [DataMember] public List<UserSearchResult> FollowingUsers { get; set; } ///ArrayOfString causes translation error [DataMember] public ArrayOfString UserFileTypes { get; set; } [DataMember] public string OriginalProfileBase64Hash { get; set; } [DataMember] public string AboutMe { get; set; } } [Serializable] [CollectionDataContract(Namespace = "http://schemas.ddnglobal.com/types/", ItemName = "String")] public class ArrayOfString : List<string> { public ArrayOfString() { } public ArrayOfString(IEnumerable<string> collection) : base(collection) { } //TODO: allow params[] constructor, fails on: //Profile = user.TranslateTo<UserPrivateProfile>() public static ArrayOfString New(params string[] ids) { return new ArrayOfString(ids); } //public ArrayOfString(params string[] ids) : base(ids) { } } [Serializable] [DataContract(Namespace = "http://schemas.ddnglobal.com/types/")] public class UserSearchResult : IHasId<Guid> { [DataMember] public Guid Id { get; set; } [DataMember(EmitDefaultValue = false)] public string UserType { get; set; } [DataMember] public string UserName { get; set; } [DataMember(EmitDefaultValue = false)] public string FullName { get; set; } [DataMember(EmitDefaultValue = false)] public string FirstName { get; set; } [DataMember(EmitDefaultValue = false)] public string LastName { get; set; } [DataMember(EmitDefaultValue = false)] public string LanguageCode { get; set; } [DataMember(EmitDefaultValue = false)] public int FlowPostCount { get; set; } [DataMember(EmitDefaultValue = false)] public int ClientTracksCount { get; set; } [DataMember(EmitDefaultValue = false)] public int FollowingCount { get; set; } [DataMember(EmitDefaultValue = false)] public int FollowersCount { get; set; } [DataMember(EmitDefaultValue = false)] public int ViewCount { get; set; } [DataMember(EmitDefaultValue = false)] public DateTime ActivationDate { get; set; } } [Serializable] [CollectionDataContract(Namespace = "http://schemas.ddnglobal.com/types/", ItemName = "Post")] public class ArrayOfPost : List<Post> { public ArrayOfPost() { } public ArrayOfPost(IEnumerable<Post> collection) : base(collection) { } public static ArrayOfPost New(params Post[] ids) { return new ArrayOfPost(ids); } } [Serializable] [DataContract(Namespace = "http://schemas.ddnglobal.com/types/")] public class Post : IHasStringId { public Post() { this.TrackUrns = new ArrayOfStringId(); } public string Id { get { return this.Urn; } } [DataMember] public string Urn { get; set; } [DataMember] public DateTime DateAdded { get; set; } [DataMember] public bool CanPreviewFullLength { get; set; } [DataMember] public Guid OriginUserId { get; set; } [DataMember] public string OriginUserName { get; set; } [DataMember] public Guid SourceUserId { get; set; } [DataMember] public string SourceUserName { get; set; } [DataMember] public string SubjectUrn { get; set; } [DataMember] public string ContentUrn { get; set; } [DataMember] public ArrayOfStringId TrackUrns { get; set; } [DataMember] public string Caption { get; set; } [DataMember] public Guid CaptionUserId { get; set; } [DataMember] public string CaptionUserName { get; set; } [DataMember] public string PostType { get; set; } [DataMember] public Guid? OnBehalfOfUserId { get; set; } } [CollectionDataContract(Namespace = "http://schemas.ddnglobal.com/types/", ItemName = "Id")] public class ArrayOfStringId : List<string> { public ArrayOfStringId() { } public ArrayOfStringId(IEnumerable<string> collection) : base(collection) { } //TODO: allow params[] constructor, fails on: o.TranslateTo<ArrayOfStringId>() public static ArrayOfStringId New(params string[] ids) { return new ArrayOfStringId(ids); } //public ArrayOfStringId(params string[] ids) : base(ids) { } } public enum FlowPostType { Content, Text, Promo, } [TextRecord] public class FlowPostTransient { public FlowPostTransient() { this.TrackUrns = new List<string>(); } [TextField] public long Id { get; set; } [TextField] public string Urn { get; set; } [TextField] public Guid UserId { get; set; } [TextField] public DateTime DateAdded { get; set; } [TextField] public DateTime DateModified { get; set; } [TextField] public Guid? TargetUserId { get; set; } [TextField] public long? ForwardedPostId { get; set; } [TextField] public Guid OriginUserId { get; set; } [TextField] public string OriginUserName { get; set; } [TextField] public Guid SourceUserId { get; set; } [TextField] public string SourceUserName { get; set; } [TextField] public string SubjectUrn { get; set; } [TextField] public string ContentUrn { get; set; } [TextField] public IList<string> TrackUrns { get; set; } [TextField] public string Caption { get; set; } [TextField] public Guid CaptionUserId { get; set; } [TextField] public string CaptionSourceName { get; set; } [TextField] public string ForwardedPostUrn { get; set; } [TextField] public FlowPostType PostType { get; set; } [TextField] public Guid? OnBehalfOfUserId { get; set; } } [DataContract(Namespace = "http://schemas.ddnglobal.com/types/")] public class Property { public Property() { } public Property(string name, string value) { this.Name = name; this.Value = value; } [DataMember] public string Name { get; set; } [DataMember] public string Value { get; set; } public override string ToString() { return this.Name + "," + this.Value; } } [CollectionDataContract(Namespace = "http://schemas.ddnglobal.com/types/", ItemName = "Property")] public class Properties : List<Property> { public Properties() { } public Properties(IEnumerable<Property> collection) : base(collection) { } public string GetPropertyValue(string name) { foreach (var property in this) { if (string.CompareOrdinal(property.Name, name) == 0) { return property.Value; } } return null; } public Dictionary<string, string> ToDictionary() { var propertyDict = new Dictionary<string, string>(); foreach (var property in this) { propertyDict[property.Name] = property.Value; } return propertyDict; } } [DataContract(Namespace = "http://schemas.ddnglobal.com/types/")] public class ResponseStatus { /// <summary> /// Initializes a new instance of the <see cref="ResponseStatus"/> class. /// /// A response status without an errorcode == success /// </summary> public ResponseStatus() { this.Errors = new List<ResponseError>(); } [DataMember] public string ErrorCode { get; set; } [DataMember] public string Message { get; set; } [DataMember] public string StackTrace { get; set; } [DataMember] public List<ResponseError> Errors { get; set; } public bool IsSuccess { get { return this.ErrorCode == null; } } } [DataContract(Namespace = "http://schemas.ddnglobal.com/types/")] public class ResponseError { [DataMember] public string ErrorCode { get; set; } [DataMember] public string FieldName { get; set; } [DataMember] public string Message { get; set; } } [DataContract(Namespace = "http://schemas.ddnglobal.com/types/")] public class GetContentStatsResponse : IExtensibleDataObject { public GetContentStatsResponse() { this.Version = 100; this.ResponseStatus = new ResponseStatus(); this.TopRecommenders = new List<UserSearchResult>(); this.LatestPosts = new List<Post>(); } [DataMember] public DateTime CreatedDate { get; set; } [DataMember] public List<UserSearchResult> TopRecommenders { get; set; } [DataMember] public List<Post> LatestPosts { get; set; } #region Standard Response Properties [DataMember] public int Version { get; set; } [DataMember] public Properties Properties { get; set; } public ExtensionDataObject ExtensionData { get; set; } [DataMember] public ResponseStatus ResponseStatus { get; set; } #endregion } [DataContract(Namespace = "http://schemas.ddnglobal.com/types/")] public class ProUserPublicProfile { public ProUserPublicProfile() { this.SocialLinks = new List<SocialLinkUrl>(); this.ArtistImages = new List<ImageAsset>(); this.Genres = new List<string>(); this.Posts = new ArrayOfPost(); this.FollowerUsers = new List<UserSearchResult>(); this.FollowingUsers = new List<UserSearchResult>(); } [DataMember] public Guid Id { get; set; } [DataMember] public string Alias { get; set; } [DataMember] public string RefUrn { get; set; } [DataMember] public string ProUserType { get; set; } [DataMember] public string ProUserSalesType { get; set; } #region Header [DataMember] public TextLink ProUserLink { get; set; } /// <summary> /// Same as above but in an [A] HTML link /// </summary> [DataMember] public string ProUserLinkHtml { get; set; } /// <summary> /// For the twitter and facebook icons /// </summary> [DataMember] public List<SocialLinkUrl> SocialLinks { get; set; } #endregion #region Theme [DataMember] public ImageAsset BannerImage { get; set; } [DataMember] public string BannerImageBackgroundColor { get; set; } [DataMember] public List<string> UserFileTypes { get; set; } [DataMember] public string OriginalProfileBase64Hash { get; set; } #endregion #region Music [DataMember] public List<ImageAsset> ArtistImages { get; set; } [DataMember] public List<string> Genres { get; set; } #endregion #region Biography [DataMember] public string BiographyPageHtml { get; set; } #endregion #region Outbox [DataMember] public ArrayOfPost Posts { get; set; } [DataMember] public List<UserSearchResult> FollowerUsers { get; set; } [DataMember] public int FollowerUsersCount { get; set; } [DataMember] public List<UserSearchResult> FollowingUsers { get; set; } [DataMember] public int FollowingUsersCount { get; set; } #endregion } public enum SocialLink { iTunes = 0, Bebo = 1, Blogger = 2, Delicious = 3, Digg = 4, Email = 5, EverNote = 6, Facebook = 7, Flickr = 8, FriendFeed = 9, GoogleWave = 10, GroveShark = 11, iLike = 12, LastFm = 13, Mix = 14, MySpace = 15, Posterous = 16, Reddit = 17, Rss = 18, StumbleUpon = 19, Twitter = 20, Vimeo = 21, Wikipedia = 22, WordPress = 23, Yahoo = 24, YahooBuzz = 25, YouTube = 26, } [DataContract(Namespace = "http://schemas.ddnglobal.com/types/")] public class SocialLinkUrl { [References(typeof(SocialLink))] [DataMember(EmitDefaultValue = false)] public string Name { get; set; } [DataMember] public string LinkUrl { get; set; } } [DataContract(Namespace = "http://schemas.ddnglobal.com/types/")] [Serializable] public class ImageAsset { [DataMember(EmitDefaultValue = false)] public string RelativePath { get; set; } [DataMember(EmitDefaultValue = false)] public string AbsoluteUrl { get; set; } [DataMember(EmitDefaultValue = false)] public string Hash { get; set; } [DataMember(EmitDefaultValue = false)] public long? SizeBytes { get; set; } [DataMember(EmitDefaultValue = false)] public int? Width { get; set; } [DataMember(EmitDefaultValue = false)] public int? Height { get; set; } [DataMember(EmitDefaultValue = false)] public string BackgroundColorHex { get; set; } } [DataContract(Namespace = "http://schemas.ddnglobal.com/types/")] public class TextLink { [DataMember(EmitDefaultValue = false)] public string Label { get; set; } [DataMember] public string LinkUrl { get; set; } } }
#region License /* * WebSocketServer.cs * * A C# implementation of the WebSocket protocol server. * * 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 #region Contributors /* * Contributors: * - Juan Manuel Lallana <juan.manuel.lallana@gmail.com> * - Jonas Hovgaard <j@jhovgaard.dk> * - Liryna <liryna.stark@gmail.com> * - Rohan Singh <rohan-singh@hotmail.com> */ #endregion using System; using System.Collections.Generic; using System.Net.Sockets; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.Text; using System.Threading; using WebSocketSharp.Net; using WebSocketSharp.Net.WebSockets; namespace WebSocketSharp.Server { /// <summary> /// Provides a WebSocket protocol server. /// </summary> /// <remarks> /// The WebSocketServer class can provide multiple WebSocket services. /// </remarks> public class WebSocketServer { #region Private Fields private System.Net.IPAddress _address; private AuthenticationSchemes _authSchemes; private static readonly string _defaultRealm; private bool _dnsStyle; private string _hostname; private TcpListener _listener; private Logger _logger; private int _port; private string _realm; private Thread _receiveThread; private bool _reuseAddress; private bool _secure; private WebSocketServiceManager _services; private ServerSslConfiguration _sslConfig; private volatile ServerState _state; private object _sync; private Func<IIdentity, NetworkCredential> _userCredFinder; #endregion #region Static Constructor static WebSocketServer () { _defaultRealm = "SECRET AREA"; } #endregion #region Public Constructors /// <summary> /// Initializes a new instance of the <see cref="WebSocketServer"/> class. /// </summary> /// <remarks> /// An instance initialized by this constructor listens for the incoming connection requests on /// port 80. /// </remarks> public WebSocketServer () { init (null, System.Net.IPAddress.Any, 80, false); } /// <summary> /// Initializes a new instance of the <see cref="WebSocketServer"/> class with /// the specified <paramref name="port"/>. /// </summary> /// <remarks> /// <para> /// An instance initialized by this constructor listens for the incoming connection requests /// on <paramref name="port"/>. /// </para> /// <para> /// If <paramref name="port"/> is 443, that instance provides a secure connection. /// </para> /// </remarks> /// <param name="port"> /// An <see cref="int"/> that represents the port number on which to listen. /// </param> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="port"/> isn't between 1 and 65535 inclusive. /// </exception> public WebSocketServer (int port) : this (port, port == 443) { } /// <summary> /// Initializes a new instance of the <see cref="WebSocketServer"/> class with /// the specified WebSocket URL. /// </summary> /// <remarks> /// <para> /// An instance initialized by this constructor listens for the incoming connection requests /// on the host name and port in <paramref name="url"/>. /// </para> /// <para> /// If <paramref name="url"/> doesn't include a port, either port 80 or 443 is used on /// which to listen. It's determined by the scheme (ws or wss) in <paramref name="url"/>. /// (Port 80 if the scheme is ws.) /// </para> /// </remarks> /// <param name="url"> /// A <see cref="string"/> that represents the WebSocket URL of the server. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="url"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="url"/> is empty. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="url"/> is invalid. /// </para> /// </exception> public WebSocketServer (string url) { if (url == null) throw new ArgumentNullException ("url"); if (url.Length == 0) throw new ArgumentException ("An empty string.", "url"); Uri uri; string msg; if (!tryCreateUri (url, out uri, out msg)) throw new ArgumentException (msg, "url"); var host = uri.DnsSafeHost; var addr = host.ToIPAddress (); if (!addr.IsLocal ()) throw new ArgumentException ("The host part isn't a local host name: " + url, "url"); init (host, addr, uri.Port, uri.Scheme == "wss"); } /// <summary> /// Initializes a new instance of the <see cref="WebSocketServer"/> class with /// the specified <paramref name="port"/> and <paramref name="secure"/>. /// </summary> /// <remarks> /// An instance initialized by this constructor listens for the incoming connection requests on /// <paramref name="port"/>. /// </remarks> /// <param name="port"> /// An <see cref="int"/> that represents the port number on which to listen. /// </param> /// <param name="secure"> /// A <see cref="bool"/> that indicates providing a secure connection or not. /// (<c>true</c> indicates providing a secure connection.) /// </param> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="port"/> isn't between 1 and 65535 inclusive. /// </exception> public WebSocketServer (int port, bool secure) { if (!port.IsPortNumber ()) throw new ArgumentOutOfRangeException ( "port", "Not between 1 and 65535 inclusive: " + port); init (null, System.Net.IPAddress.Any, port, secure); } /// <summary> /// Initializes a new instance of the <see cref="WebSocketServer"/> class with /// the specified <paramref name="address"/> and <paramref name="port"/>. /// </summary> /// <remarks> /// <para> /// An instance initialized by this constructor listens for the incoming connection requests /// on <paramref name="address"/> and <paramref name="port"/>. /// </para> /// <para> /// If <paramref name="port"/> is 443, that instance provides a secure connection. /// </para> /// </remarks> /// <param name="address"> /// A <see cref="System.Net.IPAddress"/> that represents the local IP address of the server. /// </param> /// <param name="port"> /// An <see cref="int"/> that represents the port number on which to listen. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="address"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="address"/> isn't a local IP address. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="port"/> isn't between 1 and 65535 inclusive. /// </exception> public WebSocketServer (System.Net.IPAddress address, int port) : this (address, port, port == 443) { } /// <summary> /// Initializes a new instance of the <see cref="WebSocketServer"/> class with /// the specified <paramref name="address"/>, <paramref name="port"/>, /// and <paramref name="secure"/>. /// </summary> /// <remarks> /// An instance initialized by this constructor listens for the incoming connection requests on /// <paramref name="address"/> and <paramref name="port"/>. /// </remarks> /// <param name="address"> /// A <see cref="System.Net.IPAddress"/> that represents the local IP address of the server. /// </param> /// <param name="port"> /// An <see cref="int"/> that represents the port number on which to listen. /// </param> /// <param name="secure"> /// A <see cref="bool"/> that indicates providing a secure connection or not. /// (<c>true</c> indicates providing a secure connection.) /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="address"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="address"/> isn't a local IP address. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="port"/> isn't between 1 and 65535 inclusive. /// </exception> public WebSocketServer (System.Net.IPAddress address, int port, bool secure) { if (address == null) throw new ArgumentNullException ("address"); if (!address.IsLocal ()) throw new ArgumentException ("Not a local IP address: " + address, "address"); if (!port.IsPortNumber ()) throw new ArgumentOutOfRangeException ( "port", "Not between 1 and 65535 inclusive: " + port); init (null, address, port, secure); } #endregion #region Public Properties /// <summary> /// Gets the local IP address of the server. /// </summary> /// <value> /// A <see cref="System.Net.IPAddress"/> that represents the local IP address of the server. /// </value> public System.Net.IPAddress Address { get { return _address; } } /// <summary> /// Gets or sets the scheme used to authenticate the clients. /// </summary> /// <value> /// One of the <see cref="WebSocketSharp.Net.AuthenticationSchemes"/> enum values, /// indicates the scheme used to authenticate the clients. The default value is /// <see cref="WebSocketSharp.Net.AuthenticationSchemes.Anonymous"/>. /// </value> public AuthenticationSchemes AuthenticationSchemes { get { return _authSchemes; } set { var msg = _state.CheckIfAvailable (true, false, false); if (msg != null) { _logger.Error (msg); return; } _authSchemes = value; } } /// <summary> /// Gets a value indicating whether the server has started. /// </summary> /// <value> /// <c>true</c> if the server has started; otherwise, <c>false</c>. /// </value> public bool IsListening { get { return _state == ServerState.Start; } } /// <summary> /// Gets a value indicating whether the server provides a secure connection. /// </summary> /// <value> /// <c>true</c> if the server provides a secure connection; otherwise, <c>false</c>. /// </value> public bool IsSecure { get { return _secure; } } /// <summary> /// Gets or sets a value indicating whether the server cleans up /// the inactive sessions periodically. /// </summary> /// <value> /// <c>true</c> if the server cleans up the inactive sessions every 60 seconds; /// otherwise, <c>false</c>. The default value is <c>true</c>. /// </value> public bool KeepClean { get { return _services.KeepClean; } set { var msg = _state.CheckIfAvailable (true, false, false); if (msg != null) { _logger.Error (msg); return; } _services.KeepClean = value; } } /// <summary> /// Gets the logging functions. /// </summary> /// <remarks> /// The default logging level is <see cref="LogLevel.Error"/>. If you would like to change it, /// you should set the <c>Log.Level</c> property to any of the <see cref="LogLevel"/> enum /// values. /// </remarks> /// <value> /// A <see cref="Logger"/> that provides the logging functions. /// </value> public Logger Log { get { return _logger; } } /// <summary> /// Gets the port on which to listen for incoming connection requests. /// </summary> /// <value> /// An <see cref="int"/> that represents the port number on which to listen. /// </value> public int Port { get { return _port; } } /// <summary> /// Gets or sets the name of the realm associated with the server. /// </summary> /// <remarks> /// If this property is <see langword="null"/> or empty, <c>"SECRET AREA"</c> will be used as /// the name of the realm. /// </remarks> /// <value> /// A <see cref="string"/> that represents the name of the realm. The default value is /// <see langword="null"/>. /// </value> public string Realm { get { return _realm; } set { var msg = _state.CheckIfAvailable (true, false, false); if (msg != null) { _logger.Error (msg); return; } _realm = value; } } /// <summary> /// Gets or sets a value indicating whether the server is allowed to be bound to /// an address that is already in use. /// </summary> /// <remarks> /// If you would like to resolve to wait for socket in <c>TIME_WAIT</c> state, /// you should set this property to <c>true</c>. /// </remarks> /// <value> /// <c>true</c> if the server is allowed to be bound to an address that is already in use; /// otherwise, <c>false</c>. The default value is <c>false</c>. /// </value> public bool ReuseAddress { get { return _reuseAddress; } set { var msg = _state.CheckIfAvailable (true, false, false); if (msg != null) { _logger.Error (msg); return; } _reuseAddress = value; } } /// <summary> /// Gets or sets the SSL configuration used to authenticate the server and /// optionally the client for secure connection. /// </summary> /// <value> /// A <see cref="ServerSslConfiguration"/> that represents the configuration used to /// authenticate the server and optionally the client for secure connection. /// </value> public ServerSslConfiguration SslConfiguration { get { return _sslConfig ?? (_sslConfig = new ServerSslConfiguration (null)); } set { var msg = _state.CheckIfAvailable (true, false, false); if (msg != null) { _logger.Error (msg); return; } _sslConfig = value; } } /// <summary> /// Gets or sets the delegate called to find the credentials for an identity used to /// authenticate a client. /// </summary> /// <value> /// A <c>Func&lt;<see cref="IIdentity"/>, <see cref="NetworkCredential"/>&gt;</c> delegate /// that references the method(s) used to find the credentials. The default value is /// <see langword="null"/>. /// </value> public Func<IIdentity, NetworkCredential> UserCredentialsFinder { get { return _userCredFinder; } set { var msg = _state.CheckIfAvailable (true, false, false); if (msg != null) { _logger.Error (msg); return; } _userCredFinder = value; } } /// <summary> /// Gets or sets the wait time for the response to the WebSocket Ping or Close. /// </summary> /// <value> /// A <see cref="TimeSpan"/> that represents the wait time. The default value is /// the same as 1 second. /// </value> public TimeSpan WaitTime { get { return _services.WaitTime; } set { var msg = _state.CheckIfAvailable (true, false, false) ?? value.CheckIfValidWaitTime (); if (msg != null) { _logger.Error (msg); return; } _services.WaitTime = value; } } /// <summary> /// Gets the access to the WebSocket services provided by the server. /// </summary> /// <value> /// A <see cref="WebSocketServiceManager"/> that manages the WebSocket services. /// </value> public WebSocketServiceManager WebSocketServices { get { return _services; } } #endregion #region Private Methods private void abort () { lock (_sync) { if (!IsListening) return; _state = ServerState.ShuttingDown; } _listener.Stop (); _services.Stop (new CloseEventArgs (CloseStatusCode.ServerError), true, false); _state = ServerState.Stop; } private string checkIfCertificateExists () { return _secure && (_sslConfig == null || _sslConfig.ServerCertificate == null) ? "The secure connection requires a server certificate." : null; } private string getRealm () { var realm = _realm; return realm != null && realm.Length > 0 ? realm : _defaultRealm; } private void init (string hostname, System.Net.IPAddress address, int port, bool secure) { _hostname = hostname ?? address.ToString (); _address = address; _port = port; _secure = secure; _authSchemes = AuthenticationSchemes.Anonymous; _dnsStyle = Uri.CheckHostName (hostname) == UriHostNameType.Dns; _listener = new TcpListener (address, port); _logger = new Logger (); _services = new WebSocketServiceManager (_logger); _sync = new object (); } private void processRequest (TcpListenerWebSocketContext context) { var uri = context.RequestUri; if (uri == null || uri.Port != _port) { context.Close (HttpStatusCode.BadRequest); return; } if (_dnsStyle) { var hostname = uri.DnsSafeHost; if (Uri.CheckHostName (hostname) == UriHostNameType.Dns && hostname != _hostname) { context.Close (HttpStatusCode.NotFound); return; } } WebSocketServiceHost host; if (!_services.InternalTryGetServiceHost (uri.AbsolutePath, out host)) { context.Close (HttpStatusCode.NotImplemented); return; } host.StartSession (context); } private void receiveRequest () { while (true) { try { var cl = _listener.AcceptTcpClient (); ThreadPool.QueueUserWorkItem ( state => { try { var ctx = cl.GetWebSocketContext (null, _secure, _sslConfig, _logger); if (!ctx.Authenticate (_authSchemes, getRealm (), _userCredFinder)) return; processRequest (ctx); } catch (Exception ex) { _logger.Fatal (ex.ToString ()); cl.Close (); } } ); } catch (SocketException ex) { _logger.Warn ("Receiving has been stopped.\n reason: " + ex.Message); break; } catch (Exception ex) { _logger.Fatal (ex.ToString ()); break; } } if (IsListening) abort (); } private void startReceiving () { if (_reuseAddress) _listener.Server.SetSocketOption ( SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); _listener.Start (); _receiveThread = new Thread (new ThreadStart (receiveRequest)); _receiveThread.IsBackground = true; _receiveThread.Start (); } private void stopReceiving (int millisecondsTimeout) { _listener.Stop (); _receiveThread.Join (millisecondsTimeout); } private static bool tryCreateUri (string uriString, out Uri result, out string message) { if (!uriString.TryCreateWebSocketUri (out result, out message)) return false; if (result.PathAndQuery != "/") { result = null; message = "Includes the path or query component: " + uriString; return false; } return true; } #endregion #region Public Methods /// <summary> /// Adds a WebSocket service with the specified behavior, <paramref name="path"/>, /// and <paramref name="initializer"/>. /// </summary> /// <remarks> /// <para> /// This method converts <paramref name="path"/> to URL-decoded string, /// and removes <c>'/'</c> from tail end of <paramref name="path"/>. /// </para> /// <para> /// <paramref name="initializer"/> returns an initialized specified typed /// <see cref="WebSocketBehavior"/> instance. /// </para> /// </remarks> /// <param name="path"> /// A <see cref="string"/> that represents the absolute path to the service to add. /// </param> /// <param name="initializer"> /// A <c>Func&lt;T&gt;</c> delegate that references the method used to initialize /// a new specified typed <see cref="WebSocketBehavior"/> instance (a new /// <see cref="IWebSocketSession"/> instance). /// </param> /// <typeparam name="TBehavior"> /// The type of the behavior of the service to add. The TBehavior must inherit /// the <see cref="WebSocketBehavior"/> class. /// </typeparam> public void AddWebSocketService<TBehavior> (string path, Func<TBehavior> initializer) where TBehavior : WebSocketBehavior { var msg = path.CheckIfValidServicePath () ?? (initializer == null ? "'initializer' is null." : null); if (msg != null) { _logger.Error (msg); return; } _services.Add<TBehavior> (path, initializer); } /// <summary> /// Adds a WebSocket service with the specified behavior and <paramref name="path"/>. /// </summary> /// <remarks> /// This method converts <paramref name="path"/> to URL-decoded string, /// and removes <c>'/'</c> from tail end of <paramref name="path"/>. /// </remarks> /// <param name="path"> /// A <see cref="string"/> that represents the absolute path to the service to add. /// </param> /// <typeparam name="TBehaviorWithNew"> /// The type of the behavior of the service to add. The TBehaviorWithNew must inherit /// the <see cref="WebSocketBehavior"/> class, and must have a public parameterless /// constructor. /// </typeparam> public void AddWebSocketService<TBehaviorWithNew> (string path) where TBehaviorWithNew : WebSocketBehavior, new () { AddWebSocketService<TBehaviorWithNew> (path, () => new TBehaviorWithNew ()); } /// <summary> /// Removes the WebSocket service with the specified <paramref name="path"/>. /// </summary> /// <remarks> /// This method converts <paramref name="path"/> to URL-decoded string, /// and removes <c>'/'</c> from tail end of <paramref name="path"/>. /// </remarks> /// <returns> /// <c>true</c> if the service is successfully found and removed; otherwise, <c>false</c>. /// </returns> /// <param name="path"> /// A <see cref="string"/> that represents the absolute path to the service to find. /// </param> public bool RemoveWebSocketService (string path) { var msg = path.CheckIfValidServicePath (); if (msg != null) { _logger.Error (msg); return false; } return _services.Remove (path); } /// <summary> /// Starts receiving the WebSocket connection requests. /// </summary> public void Start () { lock (_sync) { var msg = _state.CheckIfAvailable (true, false, false) ?? checkIfCertificateExists (); if (msg != null) { _logger.Error (msg); return; } _services.Start (); startReceiving (); _state = ServerState.Start; } } /// <summary> /// Stops receiving the WebSocket connection requests. /// </summary> public void Stop () { lock (_sync) { var msg = _state.CheckIfAvailable (false, true, false); if (msg != null) { _logger.Error (msg); return; } _state = ServerState.ShuttingDown; } stopReceiving (5000); _services.Stop (new CloseEventArgs (), true, true); _state = ServerState.Stop; } /// <summary> /// Stops receiving the WebSocket connection requests with /// the specified <see cref="ushort"/> and <see cref="string"/>. /// </summary> /// <param name="code"> /// A <see cref="ushort"/> that represents the status code indicating the reason for the stop. /// </param> /// <param name="reason"> /// A <see cref="string"/> that represents the reason for the stop. /// </param> public void Stop (ushort code, string reason) { lock (_sync) { var msg = _state.CheckIfAvailable (false, true, false) ?? WebSocket.CheckCloseParameters (code, reason, false); if (msg != null) { _logger.Error (msg); return; } _state = ServerState.ShuttingDown; } stopReceiving (5000); if (code == (ushort) CloseStatusCode.NoStatus) { _services.Stop (new CloseEventArgs (), true, true); } else { var send = !code.IsReserved (); _services.Stop (new CloseEventArgs (code, reason), send, send); } _state = ServerState.Stop; } /// <summary> /// Stops receiving the WebSocket connection requests with /// the specified <see cref="CloseStatusCode"/> and <see cref="string"/>. /// </summary> /// <param name="code"> /// One of the <see cref="CloseStatusCode"/> enum values, represents the status code indicating /// the reason for the stop. /// </param> /// <param name="reason"> /// A <see cref="string"/> that represents the reason for the stop. /// </param> public void Stop (CloseStatusCode code, string reason) { lock (_sync) { var msg = _state.CheckIfAvailable (false, true, false) ?? WebSocket.CheckCloseParameters (code, reason, false); if (msg != null) { _logger.Error (msg); return; } _state = ServerState.ShuttingDown; } stopReceiving (5000); if (code == CloseStatusCode.NoStatus) { _services.Stop (new CloseEventArgs (), true, true); } else { var send = !code.IsReserved (); _services.Stop (new CloseEventArgs (code, reason), send, send); } _state = ServerState.Stop; } #endregion } }
#region License /* * All content copyright Terracotta, Inc., unless otherwise indicated. 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. * */ #endregion using System.Globalization; namespace Quartz.Impl.AdoJobStore { /// <summary> /// This class extends <see cref="AdoConstants" /> /// to include the query string constants in use by the <see cref="StdAdoDelegate" /> /// class. /// </summary> /// <author><a href="mailto:jeff@binaryfeed.org">Jeffrey Wescott</a></author> /// <author>Marko Lahma (.NET)</author> public class StdAdoConstants : AdoConstants { public const string TablePrefixSubst = "{0}"; // table prefix substitution string public const string SchedulerNameSubst = "{1}"; // DELETE public static readonly string SqlDeleteBlobTrigger = string.Format(CultureInfo.InvariantCulture, "DELETE FROM {0}{1} WHERE {2} = {3} AND {4} = @triggerName AND {5} = @triggerGroup", TablePrefixSubst, TableBlobTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerName, ColumnTriggerGroup); public static readonly string SqlDeleteCalendar = string.Format(CultureInfo.InvariantCulture, "DELETE FROM {0}{1} WHERE {2} = {3} AND {4} = @calendarName", TablePrefixSubst, TableCalendars, ColumnSchedulerName, SchedulerNameSubst, ColumnCalendarName); public static readonly string SqlDeleteCronTrigger = string.Format(CultureInfo.InvariantCulture, "DELETE FROM {0}{1} WHERE {2} = {3} AND {4} = @triggerName AND {5} = @triggerGroup", TablePrefixSubst, TableCronTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerName, ColumnTriggerGroup); public static readonly string SqlDeleteFiredTrigger = string.Format(CultureInfo.InvariantCulture, "DELETE FROM {0}{1} WHERE {2} = {3} AND {4} = @triggerEntryId", TablePrefixSubst, TableFiredTriggers,ColumnSchedulerName, SchedulerNameSubst, ColumnEntryId); public static readonly string SqlDeleteFiredTriggers = string.Format(CultureInfo.InvariantCulture, "DELETE FROM {0}{1} WHERE {2} = {3}", TablePrefixSubst, TableFiredTriggers, ColumnSchedulerName, SchedulerNameSubst); public static readonly string SqlDeleteInstancesFiredTriggers = string.Format(CultureInfo.InvariantCulture, "DELETE FROM {0}{1} WHERE {2} = {3} AND {4} = @instanceName", TablePrefixSubst, TableFiredTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnInstanceName); public static readonly string SqlDeleteJobDetail = string.Format(CultureInfo.InvariantCulture, "DELETE FROM {0}{1} WHERE {2} = {3} AND {4} = @jobName AND {5} = @jobGroup", TablePrefixSubst, TableJobDetails, ColumnSchedulerName, SchedulerNameSubst, ColumnJobName, ColumnJobGroup); public static readonly string SqlDeleteNoRecoveryFiredTriggers = string.Format(CultureInfo.InvariantCulture, "DELETE FROM {0}{1} WHERE {2} = {3} AND {4} = @instanceName AND {5} = @requestsRecovery", TablePrefixSubst, TableFiredTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnInstanceName, ColumnRequestsRecovery); public static readonly string SqlDeletePausedTriggerGroup = string.Format(CultureInfo.InvariantCulture, "DELETE FROM {0}{1} WHERE {2} = {3} AND {4} LIKE @triggerGroup", TablePrefixSubst, TablePausedTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerGroup); public static readonly string SqlDeletePausedTriggerGroups = string.Format(CultureInfo.InvariantCulture, "DELETE FROM {0}{1} WHERE {2} = {3}", TablePrefixSubst, TablePausedTriggers, ColumnSchedulerName, SchedulerNameSubst); public static readonly string SqlDeleteSchedulerState = string.Format(CultureInfo.InvariantCulture, "DELETE FROM {0}{1} WHERE {2} = {3} AND {4} = @instanceName", TablePrefixSubst, TableSchedulerState, ColumnSchedulerName, SchedulerNameSubst, ColumnInstanceName); public static readonly string SqlDeleteSimpleTrigger = string.Format(CultureInfo.InvariantCulture, "DELETE FROM {0}{1} WHERE {2} = {3} AND {4} = @triggerName AND {5} = @triggerGroup", TablePrefixSubst, TableSimpleTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerName, ColumnTriggerGroup); public static readonly string SqlDeleteTrigger = string.Format(CultureInfo.InvariantCulture, "DELETE FROM {0}{1} WHERE {2} = {3} AND {4} = @triggerName AND {5} = @triggerGroup", TablePrefixSubst, TableTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerName, ColumnTriggerGroup); public static readonly string SqlDeleteAllSimpleTriggers = string.Format("DELETE FROM {0}SIMPLE_TRIGGERS WHERE {1} = {2}", TablePrefixSubst, ColumnSchedulerName, SchedulerNameSubst); public static readonly string SqlDeleteAllSimpropTriggers = string.Format("DELETE FROM {0}SIMPROP_TRIGGERS WHERE {1} = {2}", TablePrefixSubst, ColumnSchedulerName, SchedulerNameSubst); public static readonly string SqlDeleteAllCronTriggers = string.Format("DELETE FROM {0}CRON_TRIGGERS WHERE {1} = {2}", TablePrefixSubst, ColumnSchedulerName, SchedulerNameSubst); public static readonly string SqlDeleteAllBlobTriggers = string.Format("DELETE FROM {0}BLOB_TRIGGERS WHERE {1} = {2}", TablePrefixSubst, ColumnSchedulerName, SchedulerNameSubst); public static readonly string SqlDeleteAllTriggers = string.Format("DELETE FROM {0}TRIGGERS WHERE {1} = {2}", TablePrefixSubst, ColumnSchedulerName, SchedulerNameSubst); public static readonly string SqlDeleteAllJobDetails = string.Format("DELETE FROM {0}JOB_DETAILS WHERE {1} = {2}", TablePrefixSubst, ColumnSchedulerName, SchedulerNameSubst); public static readonly string SqlDeleteAllCalendars = string.Format("DELETE FROM {0}CALENDARS WHERE {1} = {2}", TablePrefixSubst, ColumnSchedulerName, SchedulerNameSubst); public static readonly string SqlDeleteAllPausedTriggerGrps = string.Format("DELETE FROM {0}PAUSED_TRIGGER_GRPS WHERE {1} = {2}", TablePrefixSubst, ColumnSchedulerName, SchedulerNameSubst); // INSERT public static readonly string SqlInsertBlobTrigger = string.Format(CultureInfo.InvariantCulture, "INSERT INTO {0}{1} ({2}, {3}, {4}, {5}) VALUES({6}, @triggerName, @triggerGroup, @blob)", TablePrefixSubst, TableBlobTriggers, ColumnSchedulerName, ColumnTriggerName, ColumnTriggerGroup, ColumnBlob, SchedulerNameSubst); public static readonly string SqlInsertCalendar = string.Format(CultureInfo.InvariantCulture, "INSERT INTO {0}{1} ({2}, {3}, {4}) VALUES({5}, @calendarName, @calendar)", TablePrefixSubst, TableCalendars, ColumnSchedulerName, ColumnCalendarName, ColumnCalendar, SchedulerNameSubst); public static readonly string SqlInsertCronTrigger = string.Format(CultureInfo.InvariantCulture, "INSERT INTO {0}{1} ({2}, {3}, {4}, {5}, {6}) VALUES({7}, @triggerName, @triggerGroup, @triggerCronExpression, @triggerTimeZone)", TablePrefixSubst, TableCronTriggers, ColumnSchedulerName, ColumnTriggerName, ColumnTriggerGroup, ColumnCronExpression, ColumnTimeZoneId, SchedulerNameSubst); public static readonly string SqlInsertFiredTrigger = string.Format(CultureInfo.InvariantCulture, "INSERT INTO {0}{1} ({2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {11}, {12}, {13}) VALUES({14}, @triggerEntryId, @triggerName, @triggerGroup, @triggerInstanceName, @triggerFireTime, @triggerState, @triggerJobName, @triggerJobGroup, @triggerJobStateful, @triggerJobRequestsRecovery, @triggerPriority)", TablePrefixSubst, TableFiredTriggers, ColumnSchedulerName, ColumnEntryId, ColumnTriggerName, ColumnTriggerGroup, ColumnInstanceName, ColumnFiredTime, ColumnEntryState, ColumnJobName, ColumnJobGroup, ColumnIsNonConcurrent, ColumnRequestsRecovery, ColumnPriority, SchedulerNameSubst); public static readonly string SqlInsertJobDetail = string.Format(CultureInfo.InvariantCulture, "INSERT INTO {0}{1} ({2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {11}) VALUES({12}, @jobName, @jobGroup, @jobDescription, @jobType, @jobDurable, @jobVolatile, @jobStateful, @jobRequestsRecovery, @jobDataMap)", TablePrefixSubst, TableJobDetails, ColumnSchedulerName, ColumnJobName, ColumnJobGroup, ColumnDescription, ColumnJobClass, ColumnIsDurable, ColumnIsNonConcurrent, ColumnIsUpdateData, ColumnRequestsRecovery, ColumnJobDataMap, SchedulerNameSubst); public static readonly string SqlInsertPausedTriggerGroup = string.Format(CultureInfo.InvariantCulture, "INSERT INTO {0}{1} ({2}, {3}) VALUES ({4}, @triggerGroup)", TablePrefixSubst, TablePausedTriggers, ColumnSchedulerName, ColumnTriggerGroup, SchedulerNameSubst); public static readonly string SqlInsertSchedulerState = string.Format(CultureInfo.InvariantCulture, "INSERT INTO {0}{1} ({2}, {3}, {4}, {5}) VALUES({6}, @instanceName, @lastCheckinTime, @checkinInterval)", TablePrefixSubst, TableSchedulerState, ColumnSchedulerName, ColumnInstanceName, ColumnLastCheckinTime, ColumnCheckinInterval, SchedulerNameSubst); public static readonly string SqlInsertSimpleTrigger = string.Format(CultureInfo.InvariantCulture, "INSERT INTO {0}{1} ({2}, {3}, {4}, {5}, {6}, {7}) VALUES({8}, @triggerName, @triggerGroup, @triggerRepeatCount, @triggerRepeatInterval, @triggerTimesTriggered)", TablePrefixSubst, TableSimpleTriggers, ColumnSchedulerName, ColumnTriggerName, ColumnTriggerGroup, ColumnRepeatCount, ColumnRepeatInterval, ColumnTimesTriggered, SchedulerNameSubst); public static readonly string SqlInsertTrigger = string.Format(CultureInfo.InvariantCulture, @"INSERT INTO {0}{1} ({2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {11}, {12}, {13}, {14}, {15}, {16}, {17}) VALUES({18}, @triggerName, @triggerGroup, @triggerJobName, @triggerJobGroup, @triggerDescription, @triggerNextFireTime, @triggerPreviousFireTime, @triggerState, @triggerType, @triggerStartTime, @triggerEndTime, @triggerCalendarName, @triggerMisfireInstruction, @triggerJobJobDataMap, @triggerPriority)", TablePrefixSubst, TableTriggers, ColumnSchedulerName, ColumnTriggerName, ColumnTriggerGroup, ColumnJobName, ColumnJobGroup, ColumnDescription, ColumnNextFireTime, ColumnPreviousFireTime, ColumnTriggerState, ColumnTriggerType, ColumnStartTime, ColumnEndTime, ColumnCalendarName, ColumnMifireInstruction, ColumnJobDataMap, ColumnPriority, SchedulerNameSubst); // SELECT public static readonly string SqlSelectBlobTrigger = string.Format(CultureInfo.InvariantCulture, "SELECT {6} FROM {0}{1} WHERE {2} = {3} AND {4} = @triggerName AND {5} = @triggerGroup", TablePrefixSubst, TableBlobTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerName, ColumnTriggerGroup, ColumnBlob); public static readonly string SqlSelectCalendar = string.Format(CultureInfo.InvariantCulture, "SELECT {5} FROM {0}{1} WHERE {2} = {3} AND {4} = @calendarName", TablePrefixSubst, TableCalendars, ColumnSchedulerName, SchedulerNameSubst, ColumnCalendarName, ColumnCalendar); public static readonly string SqlSelectCalendarExistence = string.Format(CultureInfo.InvariantCulture, "SELECT {0} FROM {1}{2} WHERE {3} = {4} AND {5} = @calendarName", ColumnCalendarName, TablePrefixSubst, TableCalendars, ColumnSchedulerName, SchedulerNameSubst, ColumnCalendarName); public static readonly string SqlSelectCalendars = string.Format(CultureInfo.InvariantCulture, "SELECT {0} FROM {1}{2} WHERE {3} = {4}", ColumnCalendarName, TablePrefixSubst, TableCalendars, ColumnSchedulerName, SchedulerNameSubst); public static readonly string SqlSelectCronTriggers = string.Format(CultureInfo.InvariantCulture, "SELECT * FROM {0}{1} WHERE {2} = {3} AND {4} = @triggerName AND {5} = @triggerGroup", TablePrefixSubst, TableCronTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerName, ColumnTriggerGroup); public static readonly string SqlSelectFiredTrigger = string.Format(CultureInfo.InvariantCulture, "SELECT * FROM {0}{1} WHERE {2} = {3} AND {4} = @triggerName AND {5} = @triggerGroup", TablePrefixSubst, TableFiredTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerName, ColumnTriggerGroup); public static readonly string SqlSelectFiredTriggerGroup = string.Format(CultureInfo.InvariantCulture, "SELECT * FROM {0}{1} WHERE {2} = {3} AND {4} = @triggerGroup", TablePrefixSubst, TableFiredTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerGroup); public static readonly string SqlSelectFiredTriggers = string.Format(CultureInfo.InvariantCulture, "SELECT * FROM {0}{1} WHERE {2} = {3}", TablePrefixSubst, TableFiredTriggers, ColumnSchedulerName, SchedulerNameSubst); public static readonly string SqlSelectFiredTriggerInstanceNames = string.Format(CultureInfo.InvariantCulture, "SELECT DISTINCT {0} FROM {1}{2} WHERE {3} = {4}", ColumnInstanceName, TablePrefixSubst, TableFiredTriggers, ColumnSchedulerName, SchedulerNameSubst); public static readonly string SqlSelectFiredTriggersOfJob = string.Format(CultureInfo.InvariantCulture, "SELECT * FROM {0}{1} WHERE {2} = {3} AND {4} = @jobName AND {5} = @jobGroup", TablePrefixSubst, TableFiredTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnJobName, ColumnJobGroup); public static readonly string SqlSelectFiredTriggersOfJobGroup = string.Format(CultureInfo.InvariantCulture, "SELECT * FROM {0}{1} WHERE {2} = {3} AND {4} = @jobGroup", TablePrefixSubst, TableFiredTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnJobGroup); public static readonly string SqlSelectInstancesFiredTriggers = string.Format(CultureInfo.InvariantCulture, "SELECT * FROM {0}{1} WHERE {2} = {3} AND {4} = @instanceName", TablePrefixSubst, TableFiredTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnInstanceName); public static readonly string SqlSelectInstancesRecoverableFiredTriggers = string.Format(CultureInfo.InvariantCulture, "SELECT * FROM {0}{1} WHERE {2} = {3} AND {4} = @instanceName AND {5} = @requestsRecovery", TablePrefixSubst, TableFiredTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnInstanceName, ColumnRequestsRecovery); public static readonly string SqlSelectJobDetail = string.Format(CultureInfo.InvariantCulture, "SELECT {6},{7},{8},{9},{10},{11},{12} FROM {0}{1} WHERE {2} = {3} AND {4} = @jobName AND {5} = @jobGroup", TablePrefixSubst, TableJobDetails, ColumnSchedulerName, SchedulerNameSubst, ColumnJobName, ColumnJobGroup, ColumnJobName, ColumnJobGroup, ColumnDescription, ColumnJobClass, ColumnIsDurable, ColumnRequestsRecovery, ColumnJobDataMap); public static readonly string SqlSelectJobExecutionCount = string.Format(CultureInfo.InvariantCulture, "SELECT COUNT({0}) FROM {1}{2} WHERE {3} = {4} AND {5} = @jobName AND {6} = @jobGroup", ColumnTriggerName, TablePrefixSubst, TableFiredTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnJobName, ColumnJobGroup); public static readonly string SqlSelectJobExistence = string.Format(CultureInfo.InvariantCulture, "SELECT {0} FROM {1}{2} WHERE {3} = {4} AND {5} = @jobName AND {6} = @jobGroup", ColumnJobName, TablePrefixSubst, TableJobDetails, ColumnSchedulerName, SchedulerNameSubst, ColumnJobName, ColumnJobGroup); public static readonly string SqlSelectJobForTrigger = string.Format(CultureInfo.InvariantCulture, "SELECT J.{0}, J.{1}, J.{2}, J.{3}, J.{4} FROM {5}{6} T, {7}{8} J WHERE T.{9} = {10} AND T.{11} = {12} AND T.{13} = @triggerName AND T.{14} = @triggerGroup AND T.{15} = J.{16} AND T.{17} = J.{18}", ColumnJobName, ColumnJobGroup, ColumnIsDurable, ColumnJobClass, ColumnRequestsRecovery, TablePrefixSubst, TableTriggers, TablePrefixSubst, TableJobDetails, ColumnSchedulerName, SchedulerNameSubst, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerName, ColumnTriggerGroup, ColumnJobName, ColumnJobName, ColumnJobGroup, ColumnJobGroup); public static readonly string SqlSelectJobGroups = string.Format(CultureInfo.InvariantCulture, "SELECT DISTINCT({0}) FROM {1}{2} WHERE {3} = {4}", ColumnJobGroup, TablePrefixSubst, TableJobDetails, ColumnSchedulerName, SchedulerNameSubst); public static readonly string SqlSelectJobNonConcurrent = string.Format(CultureInfo.InvariantCulture, "SELECT {0} FROM {1}{2} WHERE {3} = {4} AND {5} = @jobName AND {6} = @jobGroup", ColumnIsNonConcurrent, TablePrefixSubst, TableJobDetails, ColumnSchedulerName, SchedulerNameSubst, ColumnJobName, ColumnJobGroup); public static readonly string SqlSelectJobsInGroup = string.Format(CultureInfo.InvariantCulture, "SELECT {0}, {1} FROM {2}{3} WHERE {4} = {5} AND {6} LIKE @jobGroup", ColumnJobName, ColumnJobGroup, TablePrefixSubst, TableJobDetails, ColumnSchedulerName, SchedulerNameSubst, ColumnJobGroup); public static readonly string SqlSelectMisfiredTriggers = string.Format(CultureInfo.InvariantCulture, "SELECT * FROM {0}{1} WHERE {2} = {3} AND {4} <> {5} AND {6} < @nextFireTime ORDER BY {7} ASC, {8} DESC", TablePrefixSubst, TableTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnMifireInstruction, (int)MisfireInstruction.IgnoreMisfirePolicy, ColumnNextFireTime, ColumnNextFireTime, ColumnPriority); public static readonly string SqlSelectMisfiredTriggersInGroupInState = string.Format(CultureInfo.InvariantCulture, "SELECT {0} FROM {1}{2} WHERE {3} = {4} AND {5} <> {6} AND {7} < @nextFireTime AND {8} = @triggerGroup AND {9} = @state ORDER BY {10} ASC, {11} DESC", ColumnTriggerName, TablePrefixSubst, TableTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnMifireInstruction, (int)MisfireInstruction.IgnoreMisfirePolicy, ColumnNextFireTime, ColumnTriggerGroup, ColumnTriggerState, ColumnNextFireTime, ColumnPriority); public static readonly string SqlSelectMisfiredTriggersInState = string.Format(CultureInfo.InvariantCulture, "SELECT {0}, {1} FROM {2}{3} WHERE {4} = {5} AND {6} <> {7} AND {8} < @nextFireTime AND {9} = @state ORDER BY {10} ASC, {11} DESC", ColumnTriggerName, ColumnTriggerGroup, TablePrefixSubst, TableTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnMifireInstruction, (int)MisfireInstruction.IgnoreMisfirePolicy, ColumnNextFireTime, ColumnTriggerState, ColumnNextFireTime, ColumnPriority); public static readonly string SqlCountMisfiredTriggersInStates = string.Format("SELECT COUNT({0}) FROM {1}{2} WHERE {3} = {4} AND {5} <> {6} AND {7} < @nextFireTime AND {8} = @state1", ColumnTriggerName, TablePrefixSubst, TableTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnMifireInstruction, (int)MisfireInstruction.IgnoreMisfirePolicy, ColumnNextFireTime, ColumnTriggerState); public static readonly string SqlSelectHasMisfiredTriggersInState = string.Format("SELECT {0}, {1} FROM {2}{3} WHERE {4} = {5} AND {6} <> {7} AND {8} < @nextFireTime AND {9} = @state1 ORDER BY {10} ASC, {11} DESC", ColumnTriggerName, ColumnTriggerGroup, TablePrefixSubst, TableTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnMifireInstruction, (int)MisfireInstruction.IgnoreMisfirePolicy, ColumnNextFireTime, ColumnTriggerState, ColumnNextFireTime, ColumnPriority); public static readonly string SqlSelectNextTriggerToAcquire = string.Format(CultureInfo.InvariantCulture, "SELECT {0}, {1}, {2}, {3} FROM {4}{5} WHERE {6} = {7} AND {8} = @state AND {9} <= @noLaterThan AND ({10} = -1 OR ({10} <> -1 AND {9} >= @noEarlierThan)) ORDER BY {9} ASC, {11} DESC", ColumnTriggerName, ColumnTriggerGroup, ColumnNextFireTime, ColumnPriority, TablePrefixSubst, TableTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerState, ColumnNextFireTime, ColumnMifireInstruction, ColumnPriority); public static readonly string SqlSelectNumCalendars = string.Format(CultureInfo.InvariantCulture, "SELECT COUNT({0}) FROM {1}{2} WHERE {3} = {4}", ColumnCalendarName, TablePrefixSubst, TableCalendars, ColumnSchedulerName, SchedulerNameSubst); public static readonly string SqlSelectNumJobs = string.Format(CultureInfo.InvariantCulture, "SELECT COUNT({0}) FROM {1}{2} WHERE {3} = {4}", ColumnJobName, TablePrefixSubst, TableJobDetails, ColumnSchedulerName, SchedulerNameSubst); public static readonly string SqlSelectNumTriggers = string.Format(CultureInfo.InvariantCulture, "SELECT COUNT({0}) FROM {1}{2} WHERE {3} = {4}", ColumnTriggerName, TablePrefixSubst, TableTriggers, ColumnSchedulerName, SchedulerNameSubst); public static readonly string SqlSelectNumTriggersForJob = string.Format(CultureInfo.InvariantCulture, "SELECT COUNT({0}) FROM {1}{2} WHERE {3} = {4} AND {5} = @jobName AND {6} = @jobGroup", ColumnTriggerName, TablePrefixSubst, TableTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnJobName, ColumnJobGroup); public static readonly string SqlSelectNumTriggersInGroup = string.Format(CultureInfo.InvariantCulture, "SELECT COUNT({0}) FROM {1}{2} WHERE {3} = {4} AND {5} = @triggerGroup", ColumnTriggerName, TablePrefixSubst, TableTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerGroup); public static readonly string SqlSelectPausedTriggerGroup = string.Format(CultureInfo.InvariantCulture, "SELECT {0} FROM {1}{2} WHERE {3} = {4} AND {5} = @triggerGroup", ColumnTriggerGroup, TablePrefixSubst, TablePausedTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerGroup); public static readonly string SqlSelectPausedTriggerGroups = string.Format(CultureInfo.InvariantCulture, "SELECT {0} FROM {1}{2} WHERE {3} = {4}", ColumnTriggerGroup, TablePrefixSubst, TablePausedTriggers, ColumnSchedulerName, SchedulerNameSubst); public static readonly string SqlSelectReferencedCalendar = string.Format(CultureInfo.InvariantCulture, "SELECT {0} FROM {1}{2} WHERE {3} = {4} AND {5} = @calendarName", ColumnCalendarName, TablePrefixSubst, TableTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnCalendarName); public static readonly string SqlSelectSchedulerState = string.Format(CultureInfo.InvariantCulture, "SELECT * FROM {0}{1} WHERE {2} = {3} AND {4} = @instanceName", TablePrefixSubst, TableSchedulerState, ColumnSchedulerName, SchedulerNameSubst, ColumnInstanceName); public static readonly string SqlSelectSchedulerStates = string.Format(CultureInfo.InvariantCulture, "SELECT * FROM {0}{1}", TablePrefixSubst, TableSchedulerState); public static readonly string SqlSelectSimpleTrigger = string.Format(CultureInfo.InvariantCulture, "SELECT * FROM {0}{1} WHERE {2} = {3} AND {4} = @triggerName AND {5} = @triggerGroup", TablePrefixSubst, TableSimpleTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerName, ColumnTriggerGroup); public static readonly string SqlSelectTrigger = string.Format(CultureInfo.InvariantCulture, "SELECT {6},{7},{8},{9},{10},{11},{12},{13},{14},{15},{16},{17} FROM {0}{1} WHERE {2} = {3} AND {4} = @triggerName AND {5} = @triggerGroup", TablePrefixSubst, TableTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerName, ColumnTriggerGroup, ColumnJobName, ColumnJobGroup, ColumnDescription, ColumnNextFireTime, ColumnPreviousFireTime, ColumnTriggerType, ColumnStartTime, ColumnEndTime, ColumnCalendarName, ColumnMifireInstruction, ColumnPriority, ColumnJobDataMap); public static readonly string SqlSelectTriggerData = string.Format(CultureInfo.InvariantCulture, "SELECT {0} FROM {1}{2} WHERE {3} = {4} AND {5} = @triggerName AND {6} = @triggerGroup", ColumnJobDataMap, TablePrefixSubst, TableTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerName, ColumnTriggerGroup); public static readonly string SqlSelectTriggerExistence = string.Format(CultureInfo.InvariantCulture, "SELECT {0} FROM {1}{2} WHERE {3} = {4} AND {5} = @triggerName AND {6} = @triggerGroup", ColumnTriggerName, TablePrefixSubst, TableTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerName, ColumnTriggerGroup); public static readonly string SqlSelectTriggerForFireTime = string.Format(CultureInfo.InvariantCulture, "SELECT {0}, {1} FROM {2}{3} WHERE {4} = {5} AND {6} = @state AND {7} = @nextFireTime", ColumnTriggerName, ColumnTriggerGroup, TablePrefixSubst, TableTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerState, ColumnNextFireTime); public static readonly string SqlSelectTriggerGroups = string.Format(CultureInfo.InvariantCulture, "SELECT DISTINCT({0}) FROM {1}{2} WHERE {3} = {4}", ColumnTriggerGroup, TablePrefixSubst, TableTriggers, ColumnSchedulerName, SchedulerNameSubst); public static readonly string SqlSelectTriggerGroupsFiltered = string.Format(CultureInfo.InvariantCulture, "SELECT DISTINCT({0}) FROM {1}{2} WHERE {3} = {4} AND {0} LIKE @triggerGroup", ColumnTriggerGroup, TablePrefixSubst, TableTriggers, ColumnSchedulerName, SchedulerNameSubst); public static readonly string SqlSelectTriggerState = string.Format(CultureInfo.InvariantCulture, "SELECT {0} FROM {1}{2} WHERE {3} = {4} AND {5} = @triggerName AND {6} = @triggerGroup", ColumnTriggerState, TablePrefixSubst, TableTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerName, ColumnTriggerGroup); public static readonly string SqlSelectTriggerStatus = string.Format(CultureInfo.InvariantCulture, "SELECT {0}, {1}, {2}, {3} FROM {4}{5} WHERE {6} = {7} AND {8} = @triggerName AND {9} = @triggerGroup", ColumnTriggerState, ColumnNextFireTime, ColumnJobName, ColumnJobGroup, TablePrefixSubst, TableTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerName, ColumnTriggerGroup); public static readonly string SqlSelectTriggersForCalendar = string.Format(CultureInfo.InvariantCulture, "SELECT {0}, {1} FROM {2}{3} WHERE {4} = {5} AND {6} = @calendarName", ColumnTriggerName, ColumnTriggerGroup, TablePrefixSubst, TableTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnCalendarName); public static readonly string SqlSelectTriggersForJob = string.Format(CultureInfo.InvariantCulture, "SELECT {0}, {1} FROM {2}{3} WHERE {4} = {5} AND {6} = @jobName AND {7} = @jobGroup", ColumnTriggerName, ColumnTriggerGroup, TablePrefixSubst, TableTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnJobName, ColumnJobGroup); public static readonly string SqlSelectTriggersInGroup = string.Format(CultureInfo.InvariantCulture, "SELECT {0}, {1} FROM {2}{3} WHERE {4} = {5} AND {6} LIKE @triggerGroup", ColumnTriggerName, ColumnTriggerGroup, TablePrefixSubst, TableTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerGroup); public static readonly string SqlSelectTriggersInState = string.Format(CultureInfo.InvariantCulture, "SELECT {0}, {1} FROM {2}{3} WHERE {4} = {5} AND {6} = @state", ColumnTriggerName, ColumnTriggerGroup, TablePrefixSubst, TableTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerState); // UPDATE public static readonly string SqlUpdateBlobTrigger = string.Format(CultureInfo.InvariantCulture, "UPDATE {0}{1} SET {2} = @blob WHERE {3} = {4} AND {5} = @triggerName AND {6} = @triggerGroup", TablePrefixSubst, TableBlobTriggers, ColumnBlob, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerName, ColumnTriggerGroup); public static readonly string SqlUpdateCalendar = string.Format(CultureInfo.InvariantCulture, "UPDATE {0}{1} SET {2} = @calendar WHERE {3} = {4} AND {5} = @calendarName", TablePrefixSubst, TableCalendars, ColumnCalendar, ColumnSchedulerName, SchedulerNameSubst, ColumnCalendarName); public static readonly string SqlUpdateCronTrigger = string.Format(CultureInfo.InvariantCulture, "UPDATE {0}{1} SET {2} = @triggerCronExpression, {3} = @timeZoneId WHERE {4} = {5} AND {6} = @triggerName AND {7} = @triggerGroup", TablePrefixSubst, TableCronTriggers, ColumnCronExpression, ColumnTimeZoneId, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerName, ColumnTriggerGroup); public static readonly string SqlUpdateInstancesFiredTriggerState = string.Format(CultureInfo.InvariantCulture, "UPDATE {0}{1} SET {2} = @triggerEntryState AND {3} = @firedTime AND {4} = @priority WHERE {5} = {6} AND {7} = @instanceName", TablePrefixSubst, TableFiredTriggers, ColumnEntryState, ColumnFiredTime, ColumnPriority, ColumnSchedulerName, SchedulerNameSubst, ColumnInstanceName); public static readonly string SqlUpdateJobData = string.Format(CultureInfo.InvariantCulture, "UPDATE {0}{1} SET {2} = @jobDataMap WHERE {3} = {4} AND {5} = @jobName AND {6} = @jobGroup", TablePrefixSubst, TableJobDetails, ColumnJobDataMap, ColumnSchedulerName, SchedulerNameSubst, ColumnJobName, ColumnJobGroup); public static readonly string SqlUpdateJobDetail = string.Format(CultureInfo.InvariantCulture, "UPDATE {0}{1} SET {2} = @jobDescription, {3} = @jobType, {4} = @jobDurable, {5} = @jobVolatile, {6} = @jobStateful, {7} = @jobRequestsRecovery, {8} = @jobDataMap WHERE {9} = {10} AND {11} = @jobName AND {12} = @jobGroup", TablePrefixSubst, TableJobDetails, ColumnDescription, ColumnJobClass, ColumnIsDurable, ColumnIsNonConcurrent, ColumnIsUpdateData, ColumnRequestsRecovery, ColumnJobDataMap, ColumnSchedulerName, SchedulerNameSubst, ColumnJobName, ColumnJobGroup); public static readonly string SqlUpdateJobTriggerStates = string.Format(CultureInfo.InvariantCulture, "UPDATE {0}{1} SET {2} = @state WHERE {3} = {4} AND {5} = @jobName AND {6} = @jobGroup", TablePrefixSubst, TableTriggers, ColumnTriggerState, ColumnSchedulerName, SchedulerNameSubst, ColumnJobName, ColumnJobGroup); public static readonly string SqlUpdateJobTriggerStatesFromOtherState = string.Format(CultureInfo.InvariantCulture, "UPDATE {0}{1} SET {2} = @state WHERE {3} = {4} AND {5} = @jobName AND {6} = @jobGroup AND {7} = @oldState", TablePrefixSubst, TableTriggers, ColumnTriggerState, ColumnSchedulerName, SchedulerNameSubst, ColumnJobName, ColumnJobGroup, ColumnTriggerState); public static readonly string SqlUpdateSchedulerState = string.Format(CultureInfo.InvariantCulture, "UPDATE {0}{1} SET {2} = @lastCheckinTime WHERE {3} = {4} AND {5} = @instanceName", TablePrefixSubst, TableSchedulerState, ColumnLastCheckinTime, ColumnSchedulerName, SchedulerNameSubst, ColumnInstanceName); public static readonly string SqlUpdateSimpleTrigger = string.Format(CultureInfo.InvariantCulture, "UPDATE {0}{1} SET {2} = @triggerRepeatCount, {3} = @triggerRepeatInterval, {4} = @triggerTimesTriggered WHERE {5} = {6} AND {7} = @triggerName AND {8} = @triggerGroup", TablePrefixSubst, TableSimpleTriggers, ColumnRepeatCount, ColumnRepeatInterval, ColumnTimesTriggered, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerName, ColumnTriggerGroup); public static readonly string SqlUpdateTrigger = string.Format(CultureInfo.InvariantCulture, @"UPDATE {0}{1} SET {2} = @triggerJobName, {3} = @triggerJobGroup, {4} = @triggerDescription, {5} = @triggerNextFireTime, {6} = @triggerPreviousFireTime, {7} = @triggerState, {8} = @triggerType, {9} = @triggerStartTime, {10} = @triggerEndTime, {11} = @triggerCalendarName, {12} = @triggerMisfireInstruction, {13} = @triggerPriority, {14} = @triggerJobJobDataMap WHERE {15} = {16} AND {17} = @triggerName AND {18} = @triggerGroup", TablePrefixSubst, TableTriggers, ColumnJobName, ColumnJobGroup, ColumnDescription, ColumnNextFireTime, ColumnPreviousFireTime, ColumnTriggerState, ColumnTriggerType, ColumnStartTime, ColumnEndTime, ColumnCalendarName, ColumnMifireInstruction, ColumnPriority, ColumnJobDataMap, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerName, ColumnTriggerGroup); public static readonly string SqlUpdateFiredTrigger = string.Format( CultureInfo.InvariantCulture, "UPDATE {0}{1} SET {2} = @instanceName, {3} = @firedTime, {4} = @entryState, {5} = @jobName, {6} = @jobGroup, {7} = @isNonConcurrent, {8} = @requestsRecover WHERE {9} = {10} AND {11} = @entryId", TablePrefixSubst, TableFiredTriggers, ColumnInstanceName, ColumnFiredTime, ColumnEntryState, ColumnJobName, ColumnJobGroup, ColumnIsNonConcurrent, ColumnRequestsRecovery, ColumnSchedulerName, SchedulerNameSubst, ColumnEntryId); public static readonly string SqlUpdateTriggerGroupStateFromState = string.Format(CultureInfo.InvariantCulture, "UPDATE {0}{1} SET {2} = @newState WHERE {3} = {4} AND {5} LIKE @triggerGroup AND {6} = @oldState", TablePrefixSubst, TableTriggers, ColumnTriggerState, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerGroup, ColumnTriggerState); public static readonly string SqlUpdateTriggerGroupStateFromStates = string.Format(CultureInfo.InvariantCulture, "UPDATE {0}{1} SET {2} = @newState WHERE {3} = {4} AND {5} LIKE @groupName AND ({6} = @oldState1 OR {7} = @oldState2 OR {8} = @oldState3)", TablePrefixSubst, TableTriggers, ColumnTriggerState, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerGroup, ColumnTriggerState, ColumnTriggerState, ColumnTriggerState); public static readonly string SqlUpdateTriggerSkipData = string.Format(CultureInfo.InvariantCulture, @"UPDATE {0}{1} SET {2} = @triggerJobName, {3} = @triggerJobGroup, {4} = @triggerDescription, {5} = @triggerNextFireTime, {6} = @triggerPreviousFireTime, {7} = @triggerState, {8} = @triggerType, {9} = @triggerStartTime, {10} = @triggerEndTime, {11} = @triggerCalendarName, {12} = @triggerMisfireInstruction, {13} = @triggerPriority WHERE {14} = {15} AND {16} = @triggerName AND {17} = @triggerGroup", TablePrefixSubst, TableTriggers, ColumnJobName, ColumnJobGroup, ColumnDescription, ColumnNextFireTime, ColumnPreviousFireTime, ColumnTriggerState, ColumnTriggerType, ColumnStartTime, ColumnEndTime, ColumnCalendarName, ColumnMifireInstruction, ColumnPriority, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerName, ColumnTriggerGroup); public static readonly string SqlUpdateTriggerState = string.Format(CultureInfo.InvariantCulture, "UPDATE {0}{1} SET {2} = @state WHERE {3} = {4} AND {5} = @triggerName AND {6} = @triggerGroup", TablePrefixSubst, TableTriggers, ColumnTriggerState, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerName, ColumnTriggerGroup); public static readonly string SqlUpdateTriggerStateFromState = string.Format(CultureInfo.InvariantCulture, "UPDATE {0}{1} SET {2} = @newState WHERE {3} = {4} AND {5} = @triggerName AND {6} = @triggerGroup AND {7} = @oldState", TablePrefixSubst, TableTriggers, ColumnTriggerState, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerName, ColumnTriggerGroup, ColumnTriggerState); public static readonly string SqlUpdateTriggerStateFromStates = string.Format(CultureInfo.InvariantCulture, "UPDATE {0}{1} SET {2} = @newState WHERE {3} = {4} AND {5} = @triggerName AND {6} = @triggerGroup AND ({7} = @oldState1 OR {8} = @oldState2 OR {9} = @oldState3)", TablePrefixSubst, TableTriggers, ColumnTriggerState, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerName, ColumnTriggerGroup, ColumnTriggerState, ColumnTriggerState, ColumnTriggerState); public static readonly string SqlUpdateTriggerStatesFromOtherStates = string.Format(CultureInfo.InvariantCulture, "UPDATE {0}{1} SET {2} = @newState WHERE {3} = {4} AND ({5} = @oldState1 OR {6} = @oldState2)", TablePrefixSubst, TableTriggers, ColumnTriggerState, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerState, ColumnTriggerState); } }
using System; using System.Diagnostics; using System.Text; namespace Core { public class Callback { private static void CallCollNeeded(Context ctx, TEXTENCODE encode, string name) { Debug.Assert(ctx.CollNeeded == null || ctx.CollNeeded16 == null); if (ctx.CollNeeded != null) { string external = name; if (external == null) return; ctx.CollNeeded(ctx.CollNeededArg, ctx, encode, external); C._tagfree(ctx, ref external); } #if !OMIT_UTF16 if (ctx.CollNeeded16 != null) { Mem tmp = Mem_New(ctx); Mem_SetStr(tmp, -1, name, TEXTENCODE.UTF8, DESTRUCTOR.STATIC); string external = Mem_Text(tmp, TEXTENCODE.UTF16NATIVE); if (external != null) ctx.CollNeeded16(ctx.CollNeededArg, ctx, Context.CTXENCODE(ctx), external); Mem_Free(ref tmp); } #endif } static TEXTENCODE[] _SynthCollSeq_TextEncodes = { TEXTENCODE.UTF16BE, TEXTENCODE.UTF16LE, TEXTENCODE.UTF8 }; private static RC SynthCollSeq(Context ctx, CollSeq coll) { string z = coll.Name; for (int i = 0; i < 3; i++) { CollSeq coll2 = Callback.FindCollSeq(ctx, _SynthCollSeq_TextEncodes[i], z, false); if (coll2.Cmp != null) { coll = coll2.memcpy(); coll.Del = null; // Do not copy the destructor return RC.OK; } } return RC.ERROR; } public static CollSeq GetCollSeq(Parse parse, TEXTENCODE encode, CollSeq coll, string name) { Context ctx = parse.Ctx; CollSeq p = coll; if (p == null) p = FindCollSeq(ctx, encode, name, false); if (p == null || p.Cmp == null) { // No collation sequence of this type for this encoding is registered. Call the collation factory to see if it can supply us with one. CallCollNeeded(ctx, encode, name); p = FindCollSeq(ctx, encode, name, false); } Debug.Assert(p == null || p.Cmp != null); if (p != null) parse.ErrorMsg("no such collation sequence: %s", name); return p; } public static RC CheckCollSeq(Parse parse, CollSeq coll) { if (coll != null) { Context ctx = parse.Ctx; CollSeq p = GetCollSeq(parse, Context.CTXENCODE(ctx), coll, coll.Name); if (p == null) return RC.ERROR; Debug.Assert(p == coll); } return RC.OK; } private static CollSeq[] FindCollSeqEntry(Context ctx, string name, bool create) { int nameLength = name.Length; CollSeq[] coll = ctx.CollSeqs.Find(name, nameLength, (CollSeq[])null); if (coll == null && create) { coll = new CollSeq[3]; //sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 ); if (coll != null) { coll[0] = new CollSeq(); coll[0].Name = name; coll[0].Encode = TEXTENCODE.UTF8; coll[1] = new CollSeq(); coll[1].Name = name; coll[1].Encode = TEXTENCODE.UTF16LE; coll[2] = new CollSeq(); coll[2].Name = name; coll[2].Encode = TEXTENCODE.UTF16BE; CollSeq[] del = ctx.CollSeqs.Insert(coll[0].Name, nameLength, coll); CollSeq del2 = (del != null ? del[0] : null); // If a malloc() failure occurred in sqlite3HashInsert(), it will return the pColl pointer to be deleted (because it wasn't added to the hash table). Debug.Assert(del == null || del2 == coll[0]); if (del2 != null) { ctx.MallocFailed = true; C._tagfree(ctx, ref del2); del2 = null; coll = null; } } } return coll; } public static CollSeq FindCollSeq(Context ctx, TEXTENCODE encode, string name, bool create) { CollSeq[] colls; if (name != null) colls = FindCollSeqEntry(ctx, name, create); else { colls = new CollSeq[(int)encode]; colls[(int)encode - 1] = ctx.DefaultColl; } Debug.Assert((int)TEXTENCODE.UTF8 == 1 && (int)TEXTENCODE.UTF16LE == 2 && (int)TEXTENCODE.UTF16BE == 3); Debug.Assert(encode >= TEXTENCODE.UTF8 && encode <= TEXTENCODE.UTF16BE); return (colls != null ? colls[(int)encode - 1] : null); } const int FUNC_PERFECT_MATCH = 6; // The score for a perfect match static int MatchQuality(FuncDef p, int args, TEXTENCODE encode) { // nArg of -2 is a special case if (args == -2) return (p.Func == null && p.Step == null ? 0 : FUNC_PERFECT_MATCH); // Wrong number of arguments means "no match" if (p.Args != args && p.Args >= 0) return 0; // Give a better score to a function with a specific number of arguments than to function that accepts any number of arguments. int match = (p.Args == args ? 4 : 1); // Bonus points if the text encoding matches if (encode == p.PrefEncode) match += 2; // Exact encoding match else if ((encode & p.PrefEncode & (TEXTENCODE)2) != 0) match += 1; // Both are UTF16, but with different byte orders return match; } static FuncDef FunctionSearch(FuncDefHash hash, int h, string func, int funcLength) { for (FuncDef p = hash[h]; p != null; p = p.Hash) if (p.Name.Length == funcLength && p.Name.StartsWith(func, StringComparison.OrdinalIgnoreCase)) return p; return null; } public static void FuncDefInsert(FuncDefHash hash, FuncDef def) { int nameLength = def.Name.Length; int h = (char.ToLowerInvariant(def.Name[0]) + nameLength) % hash.data.Length; FuncDef other = FunctionSearch(hash, h, def.Name, nameLength); if (other != null) { Debug.Assert(other != def && other.Next != def); def.Next = other.Next; other.Next = def; } else { def.Next = null; def.Hash = hash[h]; hash[h] = def; } } public static FuncDef FindFunction(Context ctx, string name, int nameLength, int args, TEXTENCODE encode, bool createFlag) { Debug.Assert(args >= -2); Debug.Assert(args >= -1 || !createFlag); Debug.Assert(encode == TEXTENCODE.UTF8 || encode == TEXTENCODE.UTF16LE || encode == TEXTENCODE.UTF16BE); int h = (char.ToLowerInvariant(name[0]) + nameLength) % ctx.Funcs.data.Length; // Hash value // First search for a match amongst the application-defined functions. FuncDef best = null; // Best match found so far int bestScore = 0; // Score of best match FuncDef p = FunctionSearch(ctx.Funcs, h, name, nameLength); while (p != null) { int score = MatchQuality(p, args, encode); if (score > bestScore) { best = p; bestScore = score; } p = p.Next; } // If no match is found, search the built-in functions. // // If the SQLITE_PreferBuiltin flag is set, then search the built-in functions even if a prior app-defined function was found. And give // priority to built-in functions. // // Except, if createFlag is true, that means that we are trying to install a new function. Whatever FuncDef structure is returned it will // have fields overwritten with new information appropriate for the new function. But the FuncDefs for built-in functions are read-only. // So we must not search for built-ins when creating a new function. if (createFlag && (best == null || (ctx.Flags & Context.FLAG.PreferBuiltin) != 0)) { FuncDefHash hash = sqlite3GlobalFunctions; bestScore = 0; p = FunctionSearch(hash, h, name, nameLength); while (p != null) { int score = MatchQuality(p, args, encode); if (score > bestScore) { best = p; bestScore = score; } p = p.Next; } } // If the createFlag parameter is true and the search did not reveal an exact match for the name, number of arguments and encoding, then add a // new entry to the hash table and return it. if (createFlag && bestScore < FUNC_PERFECT_MATCH && (best = new FuncDef()) != null) { best.Name = name; best.Args = (short)args; best.PrefEncode = encode; FuncDefInsert(ctx.Funcs, best); } return (best != null && (best.Step != null || best.Func != null || createFlag) ? best : null); } public static void SchemaClear(Schema p) { Schema schema = p; Hash temp1 = schema.TableHash; Hash temp2 = schema.TriggerHash; schema.TriggerHash.Init(); schema.IndexHash.Clear(); HashElem elem; for (elem = temp2.First; elem != null; elem = elem.Next) sqlite3DeleteTrigger(null, ref elem.Data); temp2.Clear(); schema.TriggerHash.Init(); for (elem = temp1.First; elem != null; elem = elem.Next) sqlite3DeleteTable(null, ref elem.Data); temp1.Clear(); schema.FKeyHash.Clear(); schema.SeqTable = null; if ((schema.Flags & SCHEMA.SchemaLoaded) != 0) { schema.Generation++; schema.Flags &= ~SCHEMA.SchemaLoaded; } } public static Schema SchemaGet(Context ctx, Btree bt) { Schema p = (bt != null ? bt.Schema(-1, SchemaClear) : new Schema()); if (p == null) ctx.MallocFailed = true; else if (p.FileFormat == 0) { p.TableHash.Init(); p.IndexHash.Init(); p.TriggerHash.Init(); p.FKeyHash.Init(); p.Encode = TEXTENCODE.UTF8; } return p; } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using Newtonsoft.Json.Linq.JsonPath; #if DNXCORE50 using Xunit; using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; #endif using Newtonsoft.Json.Linq; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif namespace Newtonsoft.Json.Tests.Linq.JsonPath { [TestFixture] public class JPathParseTests : TestFixtureBase { [Test] public void BooleanQuery_TwoValues() { JPath path = new JPath("[?(1 > 2)]"); Assert.AreEqual(1, path.Filters.Count); BooleanQueryExpression booleanExpression = (BooleanQueryExpression)((QueryFilter)path.Filters[0]).Expression; Assert.AreEqual(1, (int)(JValue)booleanExpression.Left); Assert.AreEqual(2, (int)(JValue)booleanExpression.Right); Assert.AreEqual(QueryOperator.GreaterThan, booleanExpression.Operator); } [Test] public void BooleanQuery_TwoPaths() { JPath path = new JPath("[?(@.price > @.max_price)]"); Assert.AreEqual(1, path.Filters.Count); BooleanQueryExpression booleanExpression = (BooleanQueryExpression)((QueryFilter)path.Filters[0]).Expression; List<PathFilter> leftPaths = (List<PathFilter>)booleanExpression.Left; List<PathFilter> rightPaths = (List<PathFilter>)booleanExpression.Right; Assert.AreEqual("price", ((FieldFilter)leftPaths[0]).Name); Assert.AreEqual("max_price", ((FieldFilter)rightPaths[0]).Name); Assert.AreEqual(QueryOperator.GreaterThan, booleanExpression.Operator); } [Test] public void SingleProperty() { JPath path = new JPath("Blah"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual("Blah", ((FieldFilter)path.Filters[0]).Name); } [Test] public void SingleQuotedProperty() { JPath path = new JPath("['Blah']"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual("Blah", ((FieldFilter)path.Filters[0]).Name); } [Test] public void SingleQuotedPropertyWithWhitespace() { JPath path = new JPath("[ 'Blah' ]"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual("Blah", ((FieldFilter)path.Filters[0]).Name); } [Test] public void SingleQuotedPropertyWithDots() { JPath path = new JPath("['Blah.Ha']"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual("Blah.Ha", ((FieldFilter)path.Filters[0]).Name); } [Test] public void SingleQuotedPropertyWithBrackets() { JPath path = new JPath("['[*]']"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual("[*]", ((FieldFilter)path.Filters[0]).Name); } [Test] public void SinglePropertyWithRoot() { JPath path = new JPath("$.Blah"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual("Blah", ((FieldFilter)path.Filters[0]).Name); } [Test] public void SinglePropertyWithRootWithStartAndEndWhitespace() { JPath path = new JPath(" $.Blah "); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual("Blah", ((FieldFilter)path.Filters[0]).Name); } [Test] public void RootWithBadWhitespace() { ExceptionAssert.Throws<JsonException>(() => { new JPath("$ .Blah"); }, @"Unexpected character while parsing path: "); } [Test] public void NoFieldNameAfterDot() { ExceptionAssert.Throws<JsonException>(() => { new JPath("$.Blah."); }, @"Unexpected end while parsing path."); } [Test] public void RootWithBadWhitespace2() { ExceptionAssert.Throws<JsonException>(() => { new JPath("$. Blah"); }, @"Unexpected character while parsing path: "); } [Test] public void WildcardPropertyWithRoot() { JPath path = new JPath("$.*"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual(null, ((FieldFilter)path.Filters[0]).Name); } [Test] public void WildcardArrayWithRoot() { JPath path = new JPath("$.[*]"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual(null, ((ArrayIndexFilter)path.Filters[0]).Index); } [Test] public void RootArrayNoDot() { JPath path = new JPath("$[1]"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual(1, ((ArrayIndexFilter)path.Filters[0]).Index); } [Test] public void WildcardArray() { JPath path = new JPath("[*]"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual(null, ((ArrayIndexFilter)path.Filters[0]).Index); } [Test] public void WildcardArrayWithProperty() { JPath path = new JPath("[ * ].derp"); Assert.AreEqual(2, path.Filters.Count); Assert.AreEqual(null, ((ArrayIndexFilter)path.Filters[0]).Index); Assert.AreEqual("derp", ((FieldFilter)path.Filters[1]).Name); } [Test] public void QuotedWildcardPropertyWithRoot() { JPath path = new JPath("$.['*']"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual("*", ((FieldFilter)path.Filters[0]).Name); } [Test] public void SingleScanWithRoot() { JPath path = new JPath("$..Blah"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual("Blah", ((ScanFilter)path.Filters[0]).Name); } [Test] public void QueryTrue() { JPath path = new JPath("$.elements[?(true)]"); Assert.AreEqual(2, path.Filters.Count); Assert.AreEqual("elements", ((FieldFilter)path.Filters[0]).Name); Assert.AreEqual(QueryOperator.Exists, ((QueryFilter)path.Filters[1]).Expression.Operator); } [Test] public void ScanQuery() { JPath path = new JPath("$.elements..[?(@.id=='AAA')]"); Assert.AreEqual(2, path.Filters.Count); Assert.AreEqual("elements", ((FieldFilter)path.Filters[0]).Name); BooleanQueryExpression expression = (BooleanQueryExpression)((QueryScanFilter) path.Filters[1]).Expression; List<PathFilter> paths = (List<PathFilter>)expression.Left; Assert.IsInstanceOf(typeof(FieldFilter), paths[0]); } [Test] public void WildcardScanWithRoot() { JPath path = new JPath("$..*"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual(null, ((ScanFilter)path.Filters[0]).Name); } [Test] public void WildcardScanWithRootWithWhitespace() { JPath path = new JPath("$..* "); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual(null, ((ScanFilter)path.Filters[0]).Name); } [Test] public void TwoProperties() { JPath path = new JPath("Blah.Two"); Assert.AreEqual(2, path.Filters.Count); Assert.AreEqual("Blah", ((FieldFilter)path.Filters[0]).Name); Assert.AreEqual("Two", ((FieldFilter)path.Filters[1]).Name); } [Test] public void OnePropertyOneScan() { JPath path = new JPath("Blah..Two"); Assert.AreEqual(2, path.Filters.Count); Assert.AreEqual("Blah", ((FieldFilter)path.Filters[0]).Name); Assert.AreEqual("Two", ((ScanFilter)path.Filters[1]).Name); } [Test] public void SinglePropertyAndIndexer() { JPath path = new JPath("Blah[0]"); Assert.AreEqual(2, path.Filters.Count); Assert.AreEqual("Blah", ((FieldFilter)path.Filters[0]).Name); Assert.AreEqual(0, ((ArrayIndexFilter)path.Filters[1]).Index); } [Test] public void SinglePropertyAndExistsQuery() { JPath path = new JPath("Blah[ ?( @..name ) ]"); Assert.AreEqual(2, path.Filters.Count); Assert.AreEqual("Blah", ((FieldFilter)path.Filters[0]).Name); BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[1]).Expression; Assert.AreEqual(QueryOperator.Exists, expressions.Operator); List<PathFilter> paths = (List<PathFilter>)expressions.Left; Assert.AreEqual(1, paths.Count); Assert.AreEqual("name", ((ScanFilter)paths[0]).Name); } [Test] public void SinglePropertyAndFilterWithWhitespace() { JPath path = new JPath("Blah[ ?( @.name=='hi' ) ]"); Assert.AreEqual(2, path.Filters.Count); Assert.AreEqual("Blah", ((FieldFilter)path.Filters[0]).Name); BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[1]).Expression; Assert.AreEqual(QueryOperator.Equals, expressions.Operator); Assert.AreEqual("hi", (string)(JToken)expressions.Right); } [Test] public void SinglePropertyAndFilterWithEscapeQuote() { JPath path = new JPath(@"Blah[ ?( @.name=='h\'i' ) ]"); Assert.AreEqual(2, path.Filters.Count); Assert.AreEqual("Blah", ((FieldFilter)path.Filters[0]).Name); BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[1]).Expression; Assert.AreEqual(QueryOperator.Equals, expressions.Operator); Assert.AreEqual("h'i", (string)(JToken)expressions.Right); } [Test] public void SinglePropertyAndFilterWithDoubleEscape() { JPath path = new JPath(@"Blah[ ?( @.name=='h\\i' ) ]"); Assert.AreEqual(2, path.Filters.Count); Assert.AreEqual("Blah", ((FieldFilter)path.Filters[0]).Name); BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[1]).Expression; Assert.AreEqual(QueryOperator.Equals, expressions.Operator); Assert.AreEqual("h\\i", (string)(JToken)expressions.Right); } [Test] public void SinglePropertyAndFilterWithRegexAndOptions() { JPath path = new JPath("Blah[ ?( @.name=~/hi/i ) ]"); Assert.AreEqual(2, path.Filters.Count); Assert.AreEqual("Blah", ((FieldFilter)path.Filters[0]).Name); BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[1]).Expression; Assert.AreEqual(QueryOperator.RegexEquals, expressions.Operator); Assert.AreEqual("/hi/i", (string)(JToken)expressions.Right); } [Test] public void SinglePropertyAndFilterWithRegex() { JPath path = new JPath("Blah[?(@.title =~ /^.*Sword.*$/)]"); Assert.AreEqual(2, path.Filters.Count); Assert.AreEqual("Blah", ((FieldFilter)path.Filters[0]).Name); BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[1]).Expression; Assert.AreEqual(QueryOperator.RegexEquals, expressions.Operator); Assert.AreEqual("/^.*Sword.*$/", (string)(JToken)expressions.Right); } [Test] public void SinglePropertyAndFilterWithEscapedRegex() { JPath path = new JPath(@"Blah[?(@.title =~ /[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g)]"); Assert.AreEqual(2, path.Filters.Count); Assert.AreEqual("Blah", ((FieldFilter)path.Filters[0]).Name); BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[1]).Expression; Assert.AreEqual(QueryOperator.RegexEquals, expressions.Operator); Assert.AreEqual(@"/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g", (string)(JToken)expressions.Right); } [Test] public void SinglePropertyAndFilterWithOpenRegex() { ExceptionAssert.Throws<JsonException>(() => { new JPath(@"Blah[?(@.title =~ /[\"); }, "Path ended with an open regex."); } [Test] public void SinglePropertyAndFilterWithUnknownEscape() { ExceptionAssert.Throws<JsonException>(() => { new JPath(@"Blah[ ?( @.name=='h\i' ) ]"); }, @"Unknown escape character: \i"); } [Test] public void SinglePropertyAndFilterWithFalse() { JPath path = new JPath("Blah[ ?( @.name==false ) ]"); Assert.AreEqual(2, path.Filters.Count); Assert.AreEqual("Blah", ((FieldFilter)path.Filters[0]).Name); BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[1]).Expression; Assert.AreEqual(QueryOperator.Equals, expressions.Operator); Assert.AreEqual(false, (bool)(JToken)expressions.Right); } [Test] public void SinglePropertyAndFilterWithTrue() { JPath path = new JPath("Blah[ ?( @.name==true ) ]"); Assert.AreEqual(2, path.Filters.Count); Assert.AreEqual("Blah", ((FieldFilter)path.Filters[0]).Name); BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[1]).Expression; Assert.AreEqual(QueryOperator.Equals, expressions.Operator); Assert.AreEqual(true, (bool)(JToken)expressions.Right); } [Test] public void SinglePropertyAndFilterWithNull() { JPath path = new JPath("Blah[ ?( @.name==null ) ]"); Assert.AreEqual(2, path.Filters.Count); Assert.AreEqual("Blah", ((FieldFilter)path.Filters[0]).Name); BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[1]).Expression; Assert.AreEqual(QueryOperator.Equals, expressions.Operator); Assert.AreEqual(null, ((JValue)expressions.Right).Value); } [Test] public void FilterWithScan() { JPath path = new JPath("[?(@..name<>null)]"); BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[0]).Expression; List<PathFilter> paths = (List<PathFilter>)expressions.Left; Assert.AreEqual("name", ((ScanFilter)paths[0]).Name); } [Test] public void FilterWithNotEquals() { JPath path = new JPath("[?(@.name<>null)]"); BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[0]).Expression; Assert.AreEqual(QueryOperator.NotEquals, expressions.Operator); } [Test] public void FilterWithNotEquals2() { JPath path = new JPath("[?(@.name!=null)]"); BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[0]).Expression; Assert.AreEqual(QueryOperator.NotEquals, expressions.Operator); } [Test] public void FilterWithLessThan() { JPath path = new JPath("[?(@.name<null)]"); BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[0]).Expression; Assert.AreEqual(QueryOperator.LessThan, expressions.Operator); } [Test] public void FilterWithLessThanOrEquals() { JPath path = new JPath("[?(@.name<=null)]"); BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[0]).Expression; Assert.AreEqual(QueryOperator.LessThanOrEquals, expressions.Operator); } [Test] public void FilterWithGreaterThan() { JPath path = new JPath("[?(@.name>null)]"); BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[0]).Expression; Assert.AreEqual(QueryOperator.GreaterThan, expressions.Operator); } [Test] public void FilterWithGreaterThanOrEquals() { JPath path = new JPath("[?(@.name>=null)]"); BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[0]).Expression; Assert.AreEqual(QueryOperator.GreaterThanOrEquals, expressions.Operator); } [Test] public void FilterWithInteger() { JPath path = new JPath("[?(@.name>=12)]"); BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[0]).Expression; Assert.AreEqual(12, (int)(JToken)expressions.Right); } [Test] public void FilterWithNegativeInteger() { JPath path = new JPath("[?(@.name>=-12)]"); BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[0]).Expression; Assert.AreEqual(-12, (int)(JToken)expressions.Right); } [Test] public void FilterWithFloat() { JPath path = new JPath("[?(@.name>=12.1)]"); BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[0]).Expression; Assert.AreEqual(12.1d, (double)(JToken)expressions.Right); } [Test] public void FilterExistWithAnd() { JPath path = new JPath("[?(@.name&&@.title)]"); CompositeExpression expressions = (CompositeExpression)((QueryFilter)path.Filters[0]).Expression; Assert.AreEqual(QueryOperator.And, expressions.Operator); Assert.AreEqual(2, expressions.Expressions.Count); var first = (BooleanQueryExpression)expressions.Expressions[0]; var firstPaths = (List<PathFilter>)first.Left; Assert.AreEqual("name", ((FieldFilter)firstPaths[0]).Name); Assert.AreEqual(QueryOperator.Exists, first.Operator); var second = (BooleanQueryExpression)expressions.Expressions[1]; var secondPaths = (List<PathFilter>)second.Left; Assert.AreEqual("title", ((FieldFilter)secondPaths[0]).Name); Assert.AreEqual(QueryOperator.Exists, second.Operator); } [Test] public void FilterExistWithAndOr() { JPath path = new JPath("[?(@.name&&@.title||@.pie)]"); CompositeExpression andExpression = (CompositeExpression)((QueryFilter)path.Filters[0]).Expression; Assert.AreEqual(QueryOperator.And, andExpression.Operator); Assert.AreEqual(2, andExpression.Expressions.Count); var first = (BooleanQueryExpression)andExpression.Expressions[0]; var firstPaths = (List<PathFilter>)first.Left; Assert.AreEqual("name", ((FieldFilter)firstPaths[0]).Name); Assert.AreEqual(QueryOperator.Exists, first.Operator); CompositeExpression orExpression = (CompositeExpression)andExpression.Expressions[1]; Assert.AreEqual(2, orExpression.Expressions.Count); var orFirst = (BooleanQueryExpression)orExpression.Expressions[0]; var orFirstPaths = (List<PathFilter>)orFirst.Left; Assert.AreEqual("title", ((FieldFilter)orFirstPaths[0]).Name); Assert.AreEqual(QueryOperator.Exists, orFirst.Operator); var orSecond = (BooleanQueryExpression)orExpression.Expressions[1]; var orSecondPaths = (List<PathFilter>)orSecond.Left; Assert.AreEqual("pie", ((FieldFilter)orSecondPaths[0]).Name); Assert.AreEqual(QueryOperator.Exists, orSecond.Operator); } [Test] public void FilterWithRoot() { JPath path = new JPath("[?($.name>=12.1)]"); BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[0]).Expression; List<PathFilter> paths = (List<PathFilter>)expressions.Left; Assert.AreEqual(2, paths.Count); Assert.IsInstanceOf(typeof(RootFilter), paths[0]); Assert.IsInstanceOf(typeof(FieldFilter), paths[1]); } [Test] public void BadOr1() { ExceptionAssert.Throws<JsonException>(() => new JPath("[?(@.name||)]"), "Unexpected character while parsing path query: )"); } [Test] public void BaddOr2() { ExceptionAssert.Throws<JsonException>(() => new JPath("[?(@.name|)]"), "Unexpected character while parsing path query: |"); } [Test] public void BaddOr3() { ExceptionAssert.Throws<JsonException>(() => new JPath("[?(@.name|"), "Unexpected character while parsing path query: |"); } [Test] public void BaddOr4() { ExceptionAssert.Throws<JsonException>(() => new JPath("[?(@.name||"), "Path ended with open query."); } [Test] public void NoAtAfterOr() { ExceptionAssert.Throws<JsonException>(() => new JPath("[?(@.name||s"), "Unexpected character while parsing path query: s"); } [Test] public void NoPathAfterAt() { ExceptionAssert.Throws<JsonException>(() => new JPath("[?(@.name||@"), @"Path ended with open query."); } [Test] public void NoPathAfterDot() { ExceptionAssert.Throws<JsonException>(() => new JPath("[?(@.name||@."), @"Unexpected end while parsing path."); } [Test] public void NoPathAfterDot2() { ExceptionAssert.Throws<JsonException>(() => new JPath("[?(@.name||@.)]"), @"Unexpected end while parsing path."); } [Test] public void FilterWithFloatExp() { JPath path = new JPath("[?(@.name>=5.56789e+0)]"); BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[0]).Expression; Assert.AreEqual(5.56789e+0, (double)(JToken)expressions.Right); } [Test] public void MultiplePropertiesAndIndexers() { JPath path = new JPath("Blah[0]..Two.Three[1].Four"); Assert.AreEqual(6, path.Filters.Count); Assert.AreEqual("Blah", ((FieldFilter)path.Filters[0]).Name); Assert.AreEqual(0, ((ArrayIndexFilter)path.Filters[1]).Index); Assert.AreEqual("Two", ((ScanFilter)path.Filters[2]).Name); Assert.AreEqual("Three", ((FieldFilter)path.Filters[3]).Name); Assert.AreEqual(1, ((ArrayIndexFilter)path.Filters[4]).Index); Assert.AreEqual("Four", ((FieldFilter)path.Filters[5]).Name); } [Test] public void BadCharactersInIndexer() { ExceptionAssert.Throws<JsonException>(() => { new JPath("Blah[[0]].Two.Three[1].Four"); }, @"Unexpected character while parsing path indexer: ["); } [Test] public void UnclosedIndexer() { ExceptionAssert.Throws<JsonException>(() => { new JPath("Blah[0"); }, @"Path ended with open indexer."); } [Test] public void IndexerOnly() { JPath path = new JPath("[111119990]"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual(111119990, ((ArrayIndexFilter)path.Filters[0]).Index); } [Test] public void IndexerOnlyWithWhitespace() { JPath path = new JPath("[ 10 ]"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual(10, ((ArrayIndexFilter)path.Filters[0]).Index); } [Test] public void MultipleIndexes() { JPath path = new JPath("[111119990,3]"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual(2, ((ArrayMultipleIndexFilter)path.Filters[0]).Indexes.Count); Assert.AreEqual(111119990, ((ArrayMultipleIndexFilter)path.Filters[0]).Indexes[0]); Assert.AreEqual(3, ((ArrayMultipleIndexFilter)path.Filters[0]).Indexes[1]); } [Test] public void MultipleIndexesWithWhitespace() { JPath path = new JPath("[ 111119990 , 3 ]"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual(2, ((ArrayMultipleIndexFilter)path.Filters[0]).Indexes.Count); Assert.AreEqual(111119990, ((ArrayMultipleIndexFilter)path.Filters[0]).Indexes[0]); Assert.AreEqual(3, ((ArrayMultipleIndexFilter)path.Filters[0]).Indexes[1]); } [Test] public void MultipleQuotedIndexes() { JPath path = new JPath("['111119990','3']"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual(2, ((FieldMultipleFilter)path.Filters[0]).Names.Count); Assert.AreEqual("111119990", ((FieldMultipleFilter)path.Filters[0]).Names[0]); Assert.AreEqual("3", ((FieldMultipleFilter)path.Filters[0]).Names[1]); } [Test] public void MultipleQuotedIndexesWithWhitespace() { JPath path = new JPath("[ '111119990' , '3' ]"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual(2, ((FieldMultipleFilter)path.Filters[0]).Names.Count); Assert.AreEqual("111119990", ((FieldMultipleFilter)path.Filters[0]).Names[0]); Assert.AreEqual("3", ((FieldMultipleFilter)path.Filters[0]).Names[1]); } [Test] public void SlicingIndexAll() { JPath path = new JPath("[111119990:3:2]"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual(111119990, ((ArraySliceFilter)path.Filters[0]).Start); Assert.AreEqual(3, ((ArraySliceFilter)path.Filters[0]).End); Assert.AreEqual(2, ((ArraySliceFilter)path.Filters[0]).Step); } [Test] public void SlicingIndex() { JPath path = new JPath("[111119990:3]"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual(111119990, ((ArraySliceFilter)path.Filters[0]).Start); Assert.AreEqual(3, ((ArraySliceFilter)path.Filters[0]).End); Assert.AreEqual(null, ((ArraySliceFilter)path.Filters[0]).Step); } [Test] public void SlicingIndexNegative() { JPath path = new JPath("[-111119990:-3:-2]"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual(-111119990, ((ArraySliceFilter)path.Filters[0]).Start); Assert.AreEqual(-3, ((ArraySliceFilter)path.Filters[0]).End); Assert.AreEqual(-2, ((ArraySliceFilter)path.Filters[0]).Step); } [Test] public void SlicingIndexEmptyStop() { JPath path = new JPath("[ -3 : ]"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual(-3, ((ArraySliceFilter)path.Filters[0]).Start); Assert.AreEqual(null, ((ArraySliceFilter)path.Filters[0]).End); Assert.AreEqual(null, ((ArraySliceFilter)path.Filters[0]).Step); } [Test] public void SlicingIndexEmptyStart() { JPath path = new JPath("[ : 1 : ]"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual(null, ((ArraySliceFilter)path.Filters[0]).Start); Assert.AreEqual(1, ((ArraySliceFilter)path.Filters[0]).End); Assert.AreEqual(null, ((ArraySliceFilter)path.Filters[0]).Step); } [Test] public void SlicingIndexWhitespace() { JPath path = new JPath("[ -111119990 : -3 : -2 ]"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual(-111119990, ((ArraySliceFilter)path.Filters[0]).Start); Assert.AreEqual(-3, ((ArraySliceFilter)path.Filters[0]).End); Assert.AreEqual(-2, ((ArraySliceFilter)path.Filters[0]).Step); } [Test] public void EmptyIndexer() { ExceptionAssert.Throws<JsonException>(() => { new JPath("[]"); }, "Array index expected."); } [Test] public void IndexerCloseInProperty() { ExceptionAssert.Throws<JsonException>(() => { new JPath("]"); }, "Unexpected character while parsing path: ]"); } [Test] public void AdjacentIndexers() { JPath path = new JPath("[1][0][0][" + int.MaxValue + "]"); Assert.AreEqual(4, path.Filters.Count); Assert.AreEqual(1, ((ArrayIndexFilter)path.Filters[0]).Index); Assert.AreEqual(0, ((ArrayIndexFilter)path.Filters[1]).Index); Assert.AreEqual(0, ((ArrayIndexFilter)path.Filters[2]).Index); Assert.AreEqual(int.MaxValue, ((ArrayIndexFilter)path.Filters[3]).Index); } [Test] public void MissingDotAfterIndexer() { ExceptionAssert.Throws<JsonException>(() => { new JPath("[1]Blah"); }, "Unexpected character following indexer: B"); } [Test] public void PropertyFollowingEscapedPropertyName() { JPath path = new JPath("frameworks.dnxcore50.dependencies.['System.Xml.ReaderWriter'].source"); Assert.AreEqual(5, path.Filters.Count); Assert.AreEqual("frameworks", ((FieldFilter)path.Filters[0]).Name); Assert.AreEqual("dnxcore50", ((FieldFilter)path.Filters[1]).Name); Assert.AreEqual("dependencies", ((FieldFilter)path.Filters[2]).Name); Assert.AreEqual("System.Xml.ReaderWriter", ((FieldFilter)path.Filters[3]).Name); Assert.AreEqual("source", ((FieldFilter)path.Filters[4]).Name); } } }
/* * 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 NUnit.Framework; using OpenSim.Region.ScriptEngine.Shared.CodeTools; using OpenSim.Tests.Common; using System; namespace OpenSim.Region.ScriptEngine.Shared.Tests { public class LSL_EventTests : OpenSimTestCase { private CSCodeGenerator m_cg = new CSCodeGenerator(); [Test] public void TestBadEvent() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); TestCompile("default { bad() {} }", true); } [Test] public void TestAttachEvent() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); TestKeyArgEvent("attach"); } [Test] public void TestObjectRezEvent() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); TestKeyArgEvent("object_rez"); } [Test] public void TestMovingEndEvent() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); TestVoidArgEvent("moving_end"); } [Test] public void TestMovingStartEvent() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); TestVoidArgEvent("moving_start"); } [Test] public void TestNoSensorEvent() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); TestVoidArgEvent("no_sensor"); } [Test] public void TestNotAtRotTargetEvent() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); TestVoidArgEvent("not_at_rot_target"); } [Test] public void TestNotAtTargetEvent() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); TestVoidArgEvent("not_at_target"); } [Test] public void TestStateEntryEvent() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); TestVoidArgEvent("state_entry"); } [Test] public void TestStateExitEvent() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); TestVoidArgEvent("state_exit"); } [Test] public void TestTimerEvent() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); TestVoidArgEvent("timer"); } private void TestVoidArgEvent(string eventName) { TestCompile("default { " + eventName + "() {} }", false); TestCompile("default { " + eventName + "(integer n) {} }", true); } [Test] public void TestChangedEvent() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); TestIntArgEvent("changed"); } [Test] public void TestCollisionEvent() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); TestIntArgEvent("collision"); } [Test] public void TestCollisionStartEvent() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); TestIntArgEvent("collision_start"); } [Test] public void TestCollisionEndEvent() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); TestIntArgEvent("collision_end"); } [Test] public void TestOnRezEvent() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); TestIntArgEvent("on_rez"); } [Test] public void TestRunTimePermissionsEvent() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); TestIntArgEvent("run_time_permissions"); } [Test] public void TestSensorEvent() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); TestIntArgEvent("sensor"); } [Test] public void TestTouchEvent() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); TestIntArgEvent("touch"); } [Test] public void TestTouchStartEvent() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); TestIntArgEvent("touch_start"); } [Test] public void TestTouchEndEvent() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); TestIntArgEvent("touch_end"); } [Test] public void TestLandCollisionEvent() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); TestVectorArgEvent("land_collision"); } [Test] public void TestLandCollisionStartEvent() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); TestVectorArgEvent("land_collision_start"); } [Test] public void TestLandCollisionEndEvent() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); TestVectorArgEvent("land_collision_end"); } [Test] public void TestAtRotTargetEvent() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); TestIntRotRotArgEvent("at_rot_target"); } [Test] public void TestAtTargetEvent() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); TestIntVecVecArgEvent("at_target"); } [Test] public void TestControlEvent() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); TestKeyIntIntArgEvent("control"); } private void TestIntArgEvent(string eventName) { TestCompile("default { " + eventName + "(integer n) {} }", false); TestCompile("default { " + eventName + "{{}} }", true); TestCompile("default { " + eventName + "(string s) {{}} }", true); TestCompile("default { " + eventName + "(integer n, integer o) {{}} }", true); } private void TestKeyArgEvent(string eventName) { TestCompile("default { " + eventName + "(key k) {} }", false); TestCompile("default { " + eventName + "{{}} }", true); TestCompile("default { " + eventName + "(string s) {{}} }", true); TestCompile("default { " + eventName + "(key k, key l) {{}} }", true); } private void TestVectorArgEvent(string eventName) { TestCompile("default { " + eventName + "(vector v) {} }", false); TestCompile("default { " + eventName + "{{}} }", true); TestCompile("default { " + eventName + "(string s) {{}} }", true); TestCompile("default { " + eventName + "(vector v, vector w) {{}} }", true); } private void TestIntRotRotArgEvent(string eventName) { TestCompile("default { " + eventName + "(integer n, rotation r, rotation s) {} }", false); TestCompile("default { " + eventName + "{{}} }", true); TestCompile("default { " + eventName + "(string s) {{}} }", true); TestCompile("default { " + eventName + "(integer n, rotation r, rotation s, rotation t) {{}} }", true); } private void TestIntVecVecArgEvent(string eventName) { TestCompile("default { " + eventName + "(integer n, vector v, vector w) {} }", false); TestCompile("default { " + eventName + "{{}} }", true); TestCompile("default { " + eventName + "(string s) {{}} }", true); TestCompile("default { " + eventName + "(integer n, vector v, vector w, vector x) {{}} }", true); } private void TestKeyIntIntArgEvent(string eventName) { TestCompile("default { " + eventName + "(key k, integer n, integer o) {} }", false); TestCompile("default { " + eventName + "{{}} }", true); TestCompile("default { " + eventName + "(string s) {{}} }", true); TestCompile("default { " + eventName + "(key k, integer n, integer o, integer p) {{}} }", true); } private void TestCompile(string script, bool expectException) { bool gotException = false; Exception ge = null; try { m_cg.Convert(script); } catch (Exception e) { gotException = true; ge = e; } Assert.That( gotException, Is.EqualTo(expectException), "Failed on {0}, exception {1}", script, ge != null ? ge.ToString() : "n/a"); } } }